[ { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void cirrus_do_copy(CirrusVGAState *s, int dst, int src, int w, int h)\n{\n int sx, sy;\n int dx, dy;\n int width, height;\n int depth;\n int notify = 0;\n\n depth = s->get_bpp((VGAState *)s) / 8;\n s->get_resolution((VGAState *)s, &width, &height);\n\n /* extra x, y */\n sx = (src % (width * depth)) / depth;\n sy = (src / (width * depth));\n dx = (dst % (width *depth)) / depth;\n dy = (dst / (width * depth));\n\n /* normalize width */\n w /= depth;\n\n /* if we're doing a backward copy, we have to adjust\n our x/y to be the upper left corner (instead of the lower\n right corner) */\n if (s->cirrus_blt_dstpitch < 0) {\n\tsx -= (s->cirrus_blt_width / depth) - 1;\n\tdx -= (s->cirrus_blt_width / depth) - 1;\n\tsy -= s->cirrus_blt_height - 1;\n\tdy -= s->cirrus_blt_height - 1;\n }\n\n /* are we in the visible portion of memory? */\n if (sx >= 0 && sy >= 0 && dx >= 0 && dy >= 0 &&\n\t(sx + w) <= width && (sy + h) <= height &&\n\t(dx + w) <= width && (dy + h) <= height) {\n\tnotify = 1;\n }\n\n /* make to sure only copy if it's a plain copy ROP */\n if (*s->cirrus_rop != cirrus_bitblt_rop_fwd_src &&\n\t*s->cirrus_rop != cirrus_bitblt_rop_bkwd_src)\n\tnotify = 0;\n\n /* we have to flush all pending changes so that the copy\n is generated at the appropriate moment in time */\n if (notify)\n\tvga_hw_update();\n\n (*s->cirrus_rop) (s, s->vram_ptr + s->cirrus_blt_dstaddr,\n\t\t s->vram_ptr + s->cirrus_blt_srcaddr,\n\t\t s->cirrus_blt_dstpitch, s->cirrus_blt_srcpitch,\n\t\t s->cirrus_blt_width, s->cirrus_blt_height);\n\n if (notify)\n\ts->ds->dpy_copy(s->ds,\n\t\t\tsx, sy, dx, dy,\n\t\t\ts->cirrus_blt_width / depth,\n\t\t\ts->cirrus_blt_height);\n\n /* we don't have to notify the display that this portion has\n changed since dpy_copy implies this */\n\n if (!notify)\n\tcirrus_invalidate_region(s, s->cirrus_blt_dstaddr,\n\t\t\t\t s->cirrus_blt_dstpitch, s->cirrus_blt_width,\n\t\t\t\t s->cirrus_blt_height);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2007-1320 - Cirrus LGD-54XX \"bitblt\" heap overflow\n\nI have just noticed that patch for CVE-2007-1320 has never been applied\nto the QEMU CVS. Please find it below.\n\n| Multiple heap-based buffer overflows in the cirrus_invalidate_region\n| function in the Cirrus VGA extension in QEMU 0.8.2, as used in Xen and\n| possibly other products, might allow local users to execute arbitrary\n| code via unspecified vectors related to \"attempting to mark\n| non-existent regions as dirty,\" aka the \"bitblt\" heap overflow.\n\n\ngit-svn-id: svn://svn.savannah.nongnu.org/qemu/trunk@4340 c046a42c-6fe2-441c-8c8c-71466251a162'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int cirrus_bitblt_videotovideo_copy(CirrusVGAState * s)\n{\n if (s->ds->dpy_copy) {\n\tcirrus_do_copy(s, s->cirrus_blt_dstaddr - s->start_addr,\n\t\t s->cirrus_blt_srcaddr - s->start_addr,\n\t\t s->cirrus_blt_width, s->cirrus_blt_height);\n } else {\n\n if (BLTUNSAFE(s))\n return 0;\n\n\t(*s->cirrus_rop) (s, s->vram_ptr +\n (s->cirrus_blt_dstaddr & s->cirrus_addr_mask),\n\t\t\t s->vram_ptr +\n (s->cirrus_blt_srcaddr & s->cirrus_addr_mask),\n\t\t\t s->cirrus_blt_dstpitch, s->cirrus_blt_srcpitch,\n\t\t\t s->cirrus_blt_width, s->cirrus_blt_height);\n\n\tcirrus_invalidate_region(s, s->cirrus_blt_dstaddr,\n\t\t\t\t s->cirrus_blt_dstpitch, s->cirrus_blt_width,\n\t\t\t\t s->cirrus_blt_height);\n }\n\n return 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2008-4539: fix a heap overflow in Cirrus emulation\n\nThe code in hw/cirrus_vga.c has changed a lot between CVE-2007-1320 has\nbeen announced and the patch has been applied. As a consequence it has\nwrongly applied and QEMU is still vulnerable to this bug if using VNC.\n\n(noticed by Jan Niehusmann)\n\nSigned-off-by: Aurelien Jarno \n\ngit-svn-id: svn://svn.savannah.nongnu.org/qemu/trunk@5587 c046a42c-6fe2-441c-8c8c-71466251a162'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int putreg(struct task_struct *child,\n\tunsigned long regno, unsigned long value)\n{\n\tunsigned long tmp; \n\t\n\t/* Some code in the 64bit emulation may not be 64bit clean.\n\t Don't take any chances. */\n\tif (test_tsk_thread_flag(child, TIF_IA32))\n\t\tvalue &= 0xffffffff;\n\tswitch (regno) {\n\t\tcase offsetof(struct user_regs_struct,fs):\n\t\t\tif (value && (value & 3) != 3)\n\t\t\t\treturn -EIO;\n\t\t\tchild->thread.fsindex = value & 0xffff; \n\t\t\treturn 0;\n\t\tcase offsetof(struct user_regs_struct,gs):\n\t\t\tif (value && (value & 3) != 3)\n\t\t\t\treturn -EIO;\n\t\t\tchild->thread.gsindex = value & 0xffff;\n\t\t\treturn 0;\n\t\tcase offsetof(struct user_regs_struct,ds):\n\t\t\tif (value && (value & 3) != 3)\n\t\t\t\treturn -EIO;\n\t\t\tchild->thread.ds = value & 0xffff;\n\t\t\treturn 0;\n\t\tcase offsetof(struct user_regs_struct,es): \n\t\t\tif (value && (value & 3) != 3)\n\t\t\t\treturn -EIO;\n\t\t\tchild->thread.es = value & 0xffff;\n\t\t\treturn 0;\n\t\tcase offsetof(struct user_regs_struct,ss):\n\t\t\tif ((value & 3) != 3)\n\t\t\t\treturn -EIO;\n\t\t\tvalue &= 0xffff;\n\t\t\treturn 0;\n\t\tcase offsetof(struct user_regs_struct,fs_base):\n\t\t\tif (value >= TASK_SIZE_OF(child))\n\t\t\t\treturn -EIO;\n\t\t\tchild->thread.fs = value;\n\t\t\treturn 0;\n\t\tcase offsetof(struct user_regs_struct,gs_base):\n\t\t\tif (value >= TASK_SIZE_OF(child))\n\t\t\t\treturn -EIO;\n\t\t\tchild->thread.gs = value;\n\t\t\treturn 0;\n\t\tcase offsetof(struct user_regs_struct, eflags):\n\t\t\tvalue &= FLAG_MASK;\n\t\t\ttmp = get_stack_long(child, EFL_OFFSET); \n\t\t\ttmp &= ~FLAG_MASK; \n\t\t\tvalue |= tmp;\n\t\t\tbreak;\n\t\tcase offsetof(struct user_regs_struct,cs): \n\t\t\tif ((value & 3) != 3)\n\t\t\t\treturn -EIO;\n\t\t\tvalue &= 0xffff;\n\t\t\tbreak;\n\t}\n\tput_stack_long(child, regno - sizeof(struct pt_regs), value);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'x86_64: Zero extend all registers after ptrace in 32bit entry path.\n\nStrictly it's only needed for eax.\n\nIt actually does a little more than strictly needed -- the other registers\nare already zero extended.\n\nAlso remove the now unnecessary and non functional compat task check\nin ptrace.\n\nThis is CVE-2007-4573\n\nFound by Wojciech Purczynski\n\nSigned-off-by: Andi Kleen \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ProcShmCreatePixmap(client)\n register ClientPtr client;\n{\n PixmapPtr pMap;\n DrawablePtr pDraw;\n DepthPtr pDepth;\n register int i, rc;\n ShmDescPtr shmdesc;\n REQUEST(xShmCreatePixmapReq);\n unsigned int width, height, depth;\n unsigned long size;\n\n REQUEST_SIZE_MATCH(xShmCreatePixmapReq);\n client->errorValue = stuff->pid;\n if (!sharedPixmaps)\n\treturn BadImplementation;\n LEGAL_NEW_RESOURCE(stuff->pid, client);\n rc = dixLookupDrawable(&pDraw, stuff->drawable, client, M_ANY,\n\t\t\t DixGetAttrAccess);\n if (rc != Success)\n\treturn rc;\n\n VERIFY_SHMPTR(stuff->shmseg, stuff->offset, TRUE, shmdesc, client);\n \n width = stuff->width;\n height = stuff->height;\n depth = stuff->depth;\n if (!width || !height || !depth)\n {\n\tclient->errorValue = 0;\n return BadValue;\n }\n if (width > 32767 || height > 32767)\n\treturn BadAlloc;\n\n if (stuff->depth != 1)\n {\n pDepth = pDraw->pScreen->allowedDepths;\n for (i=0; ipScreen->numDepths; i++, pDepth++)\n\t if (pDepth->depth == stuff->depth)\n goto CreatePmap;\n\tclient->errorValue = stuff->depth;\n return BadValue;\n }\n\nCreatePmap:\n size = PixmapBytePad(width, depth) * height;\n if (sizeof(size) == 4 && BitsPerPixel(depth) > 8) {\n\tif (size < width * height)\n\t return BadAlloc;\n\t/* thankfully, offset is unsigned */\n\tif (stuff->offset + size < size)\n\t return BadAlloc;\n }\n\n VERIFY_SHMSIZE(shmdesc, stuff->offset, size, client);\n pMap = (*shmFuncs[pDraw->pScreen->myNum]->CreatePixmap)(\n\t\t\t pDraw->pScreen, stuff->width,\n\t\t\t stuff->height, stuff->depth,\n\t\t\t shmdesc->addr + stuff->offset);\n if (pMap)\n {\n\trc = XaceHook(XACE_RESOURCE_ACCESS, client, stuff->pid, RT_PIXMAP,\n\t\t pMap, RT_NONE, NULL, DixCreateAccess);\n\tif (rc != Success) {\n\t pDraw->pScreen->DestroyPixmap(pMap);\n\t return rc;\n\t}\n\tdixSetPrivate(&pMap->devPrivates, shmPixmapPrivate, shmdesc);\n\tshmdesc->refcnt++;\n\tpMap->drawable.serialNumber = NEXT_SERIAL_NUMBER;\n\tpMap->drawable.id = stuff->pid;\n\tif (AddResource(stuff->pid, RT_PIXMAP, (pointer)pMap))\n\t{\n\t return(client->noClientException);\n\t}\n\tpDraw->pScreen->DestroyPixmap(pMap);\n }\n return (BadAlloc);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'CVE-2007-6429: Always test for size+offset wrapping.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ia32_setup_frame(int sig, struct k_sigaction *ka,\n\t\t compat_sigset_t *set, struct pt_regs *regs)\n{\n\tstruct sigframe __user *frame;\n\tvoid __user *restorer;\n\tint err = 0;\n\n\t/* copy_to_user optimizes that into a single 8 byte store */\n\tstatic const struct {\n\t\tu16 poplmovl;\n\t\tu32 val;\n\t\tu16 int80;\n\t\tu16 pad;\n\t} __attribute__((packed)) code = {\n\t\t0xb858,\t\t /* popl %eax ; movl $...,%eax */\n\t\t__NR_ia32_sigreturn,\n\t\t0x80cd,\t\t/* int $0x80 */\n\t\t0,\n\t};\n\n\tframe = get_sigframe(ka, regs, sizeof(*frame));\n\n\tif (!access_ok(VERIFY_WRITE, frame, sizeof(*frame)))\n\t\tgoto give_sigsegv;\n\n\terr |= __put_user(sig, &frame->sig);\n\tif (err)\n\t\tgoto give_sigsegv;\n\n\terr |= ia32_setup_sigcontext(&frame->sc, &frame->fpstate, regs,\n\t\t\t\t\tset->sig[0]);\n\tif (err)\n\t\tgoto give_sigsegv;\n\n\tif (_COMPAT_NSIG_WORDS > 1) {\n\t\terr |= __copy_to_user(frame->extramask, &set->sig[1],\n\t\t\t\t sizeof(frame->extramask));\n\t\tif (err)\n\t\t\tgoto give_sigsegv;\n\t}\n\n\tif (ka->sa.sa_flags & SA_RESTORER) {\n\t\trestorer = ka->sa.sa_restorer;\n\t} else {\n\t\t/* Return stub is in 32bit vsyscall page */\n\t\tif (current->binfmt->hasvdso)\n\t\t\trestorer = VDSO32_SYMBOL(current->mm->context.vdso,\n\t\t\t\t\t\t sigreturn);\n\t\telse\n\t\t\trestorer = &frame->retcode;\n\t}\n\terr |= __put_user(ptr_to_compat(restorer), &frame->pretcode);\n\n\t/*\n\t * These are actually not used anymore, but left because some\n\t * gdb versions depend on them as a marker.\n\t */\n\terr |= __copy_to_user(frame->retcode, &code, 8);\n\tif (err)\n\t\tgoto give_sigsegv;\n\n\t/* Set up registers for signal handler */\n\tregs->sp = (unsigned long) frame;\n\tregs->ip = (unsigned long) ka->sa.sa_handler;\n\n\t/* Make -mregparm=3 work */\n\tregs->ax = sig;\n\tregs->dx = 0;\n\tregs->cx = 0;\n\n\tasm volatile(\"movl %0,%%ds\" :: \"r\" (__USER32_DS));\n\tasm volatile(\"movl %0,%%es\" :: \"r\" (__USER32_DS));\n\n\tregs->cs = __USER32_CS;\n\tregs->ss = __USER32_DS;\n\n\tset_fs(USER_DS);\n\tregs->flags &= ~X86_EFLAGS_TF;\n\tif (test_thread_flag(TIF_SINGLESTEP))\n\t\tptrace_notify(SIGTRAP);\n\n#if DEBUG_SIG\n\tprintk(KERN_DEBUG \"SIG deliver (%s:%d): sp=%p pc=%lx ra=%u\\n\",\n\t current->comm, current->pid, frame, regs->ip, frame->pretcode);\n#endif\n\n\treturn 0;\n\ngive_sigsegv:\n\tforce_sigsegv(sig, current);\n\treturn -EFAULT;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'x86: clear DF before calling signal handler\n\nThe Linux kernel currently does not clear the direction flag before\ncalling a signal handler, whereas the x86/x86-64 ABI requires that.\n\nLinux had this behavior/bug forever, but this becomes a real problem\nwith gcc version 4.3, which assumes that the direction flag is\ncorrectly cleared at the entry of a function.\n\nThis patches changes the setup_frame() functions to clear the\ndirection before entering the signal handler.\n\nSigned-off-by: Aurelien Jarno \nSigned-off-by: Ingo Molnar \nAcked-by: H. Peter Anvin '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: _gnutls_ciphertext2compressed (gnutls_session_t session,\n\t\t\t opaque * compress_data,\n\t\t\t int compress_size,\n\t\t\t gnutls_datum_t ciphertext, uint8_t type)\n{\n uint8_t MAC[MAX_HASH_SIZE];\n uint16_t c_length;\n uint8_t pad;\n int length;\n digest_hd_st td;\n uint16_t blocksize;\n int ret, i, pad_failed = 0;\n uint8_t major, minor;\n gnutls_protocol_t ver;\n int hash_size =\n _gnutls_hash_get_algo_len (session->security_parameters.\n\t\t\t read_mac_algorithm);\n\n ver = gnutls_protocol_get_version (session);\n minor = _gnutls_version_get_minor (ver);\n major = _gnutls_version_get_major (ver);\n\n blocksize = _gnutls_cipher_get_block_size (session->security_parameters.\n\t\t\t\t\t read_bulk_cipher_algorithm);\n\n /* initialize MAC \n */\n ret = mac_init (&td, session->security_parameters.read_mac_algorithm,\n\t\t session->connection_state.read_mac_secret.data,\n\t\t session->connection_state.read_mac_secret.size, ver);\n\n if (ret < 0\n && session->security_parameters.read_mac_algorithm != GNUTLS_MAC_NULL)\n {\n gnutls_assert ();\n return GNUTLS_E_INTERNAL_ERROR;\n }\n\n\n /* actual decryption (inplace)\n */\n switch (_gnutls_cipher_is_block\n\t (session->security_parameters.read_bulk_cipher_algorithm))\n {\n case CIPHER_STREAM:\n if ((ret = _gnutls_cipher_decrypt (&session->connection_state.\n\t\t\t\t\t read_cipher_state,\n\t\t\t\t\t ciphertext.data,\n\t\t\t\t\t ciphertext.size)) < 0)\n\t{\n\t gnutls_assert ();\n\t return ret;\n\t}\n\n length = ciphertext.size - hash_size;\n\n break;\n case CIPHER_BLOCK:\n if ((ciphertext.size < blocksize) || (ciphertext.size % blocksize != 0))\n\t{\n\t gnutls_assert ();\n\t return GNUTLS_E_DECRYPTION_FAILED;\n\t}\n\n if ((ret = _gnutls_cipher_decrypt (&session->connection_state.\n\t\t\t\t\t read_cipher_state,\n\t\t\t\t\t ciphertext.data,\n\t\t\t\t\t ciphertext.size)) < 0)\n\t{\n\t gnutls_assert ();\n\t return ret;\n\t}\n\n /* ignore the IV in TLS 1.1.\n */\n if (session->security_parameters.version >= GNUTLS_TLS1_1)\n\t{\n\t ciphertext.size -= blocksize;\n\t ciphertext.data += blocksize;\n\n\t if (ciphertext.size == 0)\n\t {\n\t gnutls_assert ();\n\t return GNUTLS_E_DECRYPTION_FAILED;\n\t }\n\t}\n\n pad = ciphertext.data[ciphertext.size - 1] + 1;\t/* pad */\n\n length = ciphertext.size - hash_size - pad;\n\n if (pad > ciphertext.size - hash_size)\n\t{\n\t gnutls_assert ();\n\t /* We do not fail here. We check below for the\n\t * the pad_failed. If zero means success.\n\t */\n\t pad_failed = GNUTLS_E_DECRYPTION_FAILED;\n\t}\n\n /* Check the pading bytes (TLS 1.x)\n */\n if (ver >= GNUTLS_TLS1 && pad_failed == 0)\n\tfor (i = 2; i < pad; i++)\n\t {\n\t if (ciphertext.data[ciphertext.size - i] !=\n\t\tciphertext.data[ciphertext.size - 1])\n\t pad_failed = GNUTLS_E_DECRYPTION_FAILED;\n\t }\n break;\n default:\n gnutls_assert ();\n return GNUTLS_E_INTERNAL_ERROR;\n }\n\n if (length < 0)\n length = 0;\n c_length = _gnutls_conv_uint16 ((uint16_t) length);\n\n /* Pass the type, version, length and compressed through\n * MAC.\n */\n if (session->security_parameters.read_mac_algorithm != GNUTLS_MAC_NULL)\n {\n _gnutls_hmac (&td,\n\t\t UINT64DATA (session->connection_state.\n\t\t\t\tread_sequence_number), 8);\n\n _gnutls_hmac (&td, &type, 1);\n if (ver >= GNUTLS_TLS1)\n\t{\t\t\t/* TLS 1.x */\n\t _gnutls_hmac (&td, &major, 1);\n\t _gnutls_hmac (&td, &minor, 1);\n\t}\n _gnutls_hmac (&td, &c_length, 2);\n\n if (length > 0)\n\t_gnutls_hmac (&td, ciphertext.data, length);\n\n mac_deinit (&td, MAC, ver);\n }\n\n /* This one was introduced to avoid a timing attack against the TLS\n * 1.0 protocol.\n */\n if (pad_failed != 0)\n return pad_failed;\n\n /* HMAC was not the same. \n */\n if (memcmp (MAC, &ciphertext.data[length], hash_size) != 0)\n {\n gnutls_assert ();\n return GNUTLS_E_DECRYPTION_FAILED;\n }\n\n /* copy the decrypted stuff to compress_data.\n */\n if (compress_size < length)\n {\n gnutls_assert ();\n return GNUTLS_E_DECOMPRESSION_FAILED;\n }\n memcpy (compress_data, ciphertext.data, length);\n\n return length;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'Fix GNUTLS-SA-2008-1 security vulnerabilities.\nSee http://www.gnu.org/software/gnutls/security.html for updates.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static struct dentry *__lookup_hash(struct qstr *name,\n\t\tstruct dentry *base, struct nameidata *nd)\n{\n\tstruct dentry *dentry;\n\tstruct inode *inode;\n\tint err;\n\n\tinode = base->d_inode;\n\n\t/*\n\t * See if the low-level filesystem might want\n\t * to use its own hash..\n\t */\n\tif (base->d_op && base->d_op->d_hash) {\n\t\terr = base->d_op->d_hash(base, name);\n\t\tdentry = ERR_PTR(err);\n\t\tif (err < 0)\n\t\t\tgoto out;\n\t}\n\n\tdentry = cached_lookup(base, name, nd);\n\tif (!dentry) {\n\t\tstruct dentry *new = d_alloc(base, name);\n\t\tdentry = ERR_PTR(-ENOMEM);\n\t\tif (!new)\n\t\t\tgoto out;\n\t\tdentry = inode->i_op->lookup(inode, new, nd);\n\t\tif (!dentry)\n\t\t\tdentry = new;\n\t\telse\n\t\t\tdput(new);\n\t}\nout:\n\treturn dentry;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': '[patch] vfs: fix lookup on deleted directory\n\nLookup can install a child dentry for a deleted directory. This keeps\nthe directory dentry alive, and the inode pinned in the cache and on\ndisk, even after all external references have gone away.\n\nThis isn't a big problem normally, since memory pressure or umount\nwill clear out the directory dentry and its children, releasing the\ninode. But for UBIFS this causes problems because its orphan area can\noverflow.\n\nFix this by returning ENOENT for all lookups on a S_DEAD directory\nbefore creating a child dentry.\n\nThanks to Zoltan Sogor for noticing this while testing UBIFS, and\nArtem for the excellent analysis of the problem and testing.\n\nReported-by: Artem Bityutskiy \nTested-by: Artem Bityutskiy \nSigned-off-by: Miklos Szeredi \nSigned-off-by: Al Viro '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int run_diff_files(struct rev_info *revs, unsigned int option)\n{\n\tint entries, i;\n\tint diff_unmerged_stage = revs->max_count;\n\tint silent_on_removed = option & DIFF_SILENT_ON_REMOVED;\n\tunsigned ce_option = ((option & DIFF_RACY_IS_MODIFIED)\n\t\t\t ? CE_MATCH_RACY_IS_DIRTY : 0);\n\tchar symcache[PATH_MAX];\n\n\tif (diff_unmerged_stage < 0)\n\t\tdiff_unmerged_stage = 2;\n\tentries = active_nr;\n\tsymcache[0] = '\\0';\n\tfor (i = 0; i < entries; i++) {\n\t\tstruct stat st;\n\t\tunsigned int oldmode, newmode;\n\t\tstruct cache_entry *ce = active_cache[i];\n\t\tint changed;\n\n\t\tif (DIFF_OPT_TST(&revs->diffopt, QUIET) &&\n\t\t\tDIFF_OPT_TST(&revs->diffopt, HAS_CHANGES))\n\t\t\tbreak;\n\n\t\tif (!ce_path_match(ce, revs->prune_data))\n\t\t\tcontinue;\n\n\t\tif (ce_stage(ce)) {\n\t\t\tstruct combine_diff_path *dpath;\n\t\t\tint num_compare_stages = 0;\n\t\t\tsize_t path_len;\n\n\t\t\tpath_len = ce_namelen(ce);\n\n\t\t\tdpath = xmalloc(combine_diff_path_size(5, path_len));\n\t\t\tdpath->path = (char *) &(dpath->parent[5]);\n\n\t\t\tdpath->next = NULL;\n\t\t\tdpath->len = path_len;\n\t\t\tmemcpy(dpath->path, ce->name, path_len);\n\t\t\tdpath->path[path_len] = '\\0';\n\t\t\thashclr(dpath->sha1);\n\t\t\tmemset(&(dpath->parent[0]), 0,\n\t\t\t sizeof(struct combine_diff_parent)*5);\n\n\t\t\tchanged = check_removed(ce, &st);\n\t\t\tif (!changed)\n\t\t\t\tdpath->mode = ce_mode_from_stat(ce, st.st_mode);\n\t\t\telse {\n\t\t\t\tif (changed < 0) {\n\t\t\t\t\tperror(ce->name);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (silent_on_removed)\n\t\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\twhile (i < entries) {\n\t\t\t\tstruct cache_entry *nce = active_cache[i];\n\t\t\t\tint stage;\n\n\t\t\t\tif (strcmp(ce->name, nce->name))\n\t\t\t\t\tbreak;\n\n\t\t\t\t/* Stage #2 (ours) is the first parent,\n\t\t\t\t * stage #3 (theirs) is the second.\n\t\t\t\t */\n\t\t\t\tstage = ce_stage(nce);\n\t\t\t\tif (2 <= stage) {\n\t\t\t\t\tint mode = nce->ce_mode;\n\t\t\t\t\tnum_compare_stages++;\n\t\t\t\t\thashcpy(dpath->parent[stage-2].sha1, nce->sha1);\n\t\t\t\t\tdpath->parent[stage-2].mode = ce_mode_from_stat(nce, mode);\n\t\t\t\t\tdpath->parent[stage-2].status =\n\t\t\t\t\t\tDIFF_STATUS_MODIFIED;\n\t\t\t\t}\n\n\t\t\t\t/* diff against the proper unmerged stage */\n\t\t\t\tif (stage == diff_unmerged_stage)\n\t\t\t\t\tce = nce;\n\t\t\t\ti++;\n\t\t\t}\n\t\t\t/*\n\t\t\t * Compensate for loop update\n\t\t\t */\n\t\t\ti--;\n\n\t\t\tif (revs->combine_merges && num_compare_stages == 2) {\n\t\t\t\tshow_combined_diff(dpath, 2,\n\t\t\t\t\t\t revs->dense_combined_merges,\n\t\t\t\t\t\t revs);\n\t\t\t\tfree(dpath);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfree(dpath);\n\t\t\tdpath = NULL;\n\n\t\t\t/*\n\t\t\t * Show the diff for the 'ce' if we found the one\n\t\t\t * from the desired stage.\n\t\t\t */\n\t\t\tdiff_unmerge(&revs->diffopt, ce->name, 0, null_sha1);\n\t\t\tif (ce_stage(ce) != diff_unmerged_stage)\n\t\t\t\tcontinue;\n\t\t}\n\n\t\tif (ce_uptodate(ce))\n\t\t\tcontinue;\n\n\t\tchanged = check_removed(ce, &st);\n\t\tif (changed) {\n\t\t\tif (changed < 0) {\n\t\t\t\tperror(ce->name);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (silent_on_removed)\n\t\t\t\tcontinue;\n\t\t\tdiff_addremove(&revs->diffopt, '-', ce->ce_mode,\n\t\t\t\t ce->sha1, ce->name, NULL);\n\t\t\tcontinue;\n\t\t}\n\t\tchanged = ce_match_stat(ce, &st, ce_option);\n\t\tif (!changed) {\n\t\t\tce_mark_uptodate(ce);\n\t\t\tif (!DIFF_OPT_TST(&revs->diffopt, FIND_COPIES_HARDER))\n\t\t\t\tcontinue;\n\t\t}\n\t\toldmode = ce->ce_mode;\n\t\tnewmode = ce_mode_from_stat(ce, st.st_mode);\n\t\tdiff_change(&revs->diffopt, oldmode, newmode,\n\t\t\t ce->sha1, (changed ? null_sha1 : ce->sha1),\n\t\t\t ce->name, NULL);\n\n\t}\n\tdiffcore_std(&revs->diffopt);\n\tdiff_flush(&revs->diffopt);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix buffer overflow in git diff\n\nIf PATH_MAX on your system is smaller than a path stored, it may cause\nbuffer overflow and stack corruption in diff_addremove() and diff_change()\nfunctions when running git-diff\n\nSigned-off-by: Dmitry Potapov \nSigned-off-by: Junio C Hamano '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int arch_setup_additional_pages(struct linux_binprm *bprm, int exstack)\n{\n\tstruct vm_area_struct *vma;\n\tstruct mm_struct *mm = current->mm;\n\tunsigned long addr;\n\tint ret;\n\n\tdown_write(&mm->mmap_sem);\n\taddr = get_unmapped_area(NULL, 0, PAGE_SIZE, 0, 0);\n\tif (IS_ERR_VALUE(addr)) {\n\t\tret = addr;\n\t\tgoto up_fail;\n\t}\n\n\tvma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);\n\tif (!vma) {\n\t\tret = -ENOMEM;\n\t\tgoto up_fail;\n\t}\n\n\tvma->vm_start = addr;\n\tvma->vm_end = addr + PAGE_SIZE;\n\t/* MAYWRITE to allow gdb to COW and set breakpoints */\n\tvma->vm_flags = VM_READ|VM_EXEC|VM_MAYREAD|VM_MAYEXEC|VM_MAYWRITE;\n\t/*\n\t * Make sure the vDSO gets into every core dump.\n\t * Dumping its contents makes post-mortem fully interpretable later\n\t * without matching up the same kernel and hardware config to see\n\t * what PC values meant.\n\t */\n\tvma->vm_flags |= VM_ALWAYSDUMP;\n\tvma->vm_flags |= mm->def_flags;\n\tvma->vm_page_prot = protection_map[vma->vm_flags & 7];\n\tvma->vm_ops = &syscall_vm_ops;\n\tvma->vm_mm = mm;\n\n\tret = insert_vm_struct(mm, vma);\n\tif (unlikely(ret)) {\n\t\tkmem_cache_free(vm_area_cachep, vma);\n\t\tgoto up_fail;\n\t}\n\n\tcurrent->mm->context.vdso = (void *)addr;\n\tcurrent_thread_info()->sysenter_return =\n\t\t\t\t (void *)VDSO_SYM(&SYSENTER_RETURN);\n\tmm->total_vm++;\nup_fail:\n\tup_write(&mm->mmap_sem);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': '[PATCH] i386 vDSO: use install_special_mapping\n\nThis patch uses install_special_mapping for the i386 vDSO setup, consolidating\nduplicated code.\n\nSigned-off-by: Roland McGrath \nCc: Ingo Molnar \nCc: Paul Mackerras \nCc: Benjamin Herrenschmidt \nCc: Andi Kleen \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: jpc_mqdec_t *jpc_mqdec_create(int maxctxs, jas_stream_t *in)\n{\n\tjpc_mqdec_t *mqdec;\n\n\t/* There must be at least one context. */\n\tassert(maxctxs > 0);\n\n\t/* Allocate memory for the MQ decoder. */\n\tif (!(mqdec = jas_malloc(sizeof(jpc_mqdec_t)))) {\n\t\tgoto error;\n\t}\n\tmqdec->in = in;\n\tmqdec->maxctxs = maxctxs;\n\t/* Allocate memory for the per-context state information. */\n\tif (!(mqdec->ctxs = jas_malloc(mqdec->maxctxs * sizeof(jpc_mqstate_t *)))) {\n\t\tgoto error;\n\t}\n\t/* Set the current context to the first context. */\n\tmqdec->curctx = mqdec->ctxs;\n\n\t/* If an input stream has been associated with the MQ decoder,\n\t initialize the decoder state from the stream. */\n\tif (mqdec->in) {\n\t\tjpc_mqdec_init(mqdec);\n\t}\n\t/* Initialize the per-context state information. */\n\tjpc_mqdec_setctxs(mqdec, 0, 0);\n\n\treturn mqdec;\n\nerror:\n\t/* Oops... Something has gone wrong. */\n\tif (mqdec) {\n\t\tjpc_mqdec_destroy(mqdec);\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being\ninvoked with the size argument being computed in a manner that would not\nallow integer overflow to be detected. Now, these places in the code\nhave been modified to use special-purpose memory allocation functions\n(e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow.\nThis should fix many security problems.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: jpc_mqenc_t *jpc_mqenc_create(int maxctxs, jas_stream_t *out)\n{\n\tjpc_mqenc_t *mqenc;\n\n\t/* Allocate memory for the MQ encoder. */\n\tif (!(mqenc = jas_malloc(sizeof(jpc_mqenc_t)))) {\n\t\tgoto error;\n\t}\n\tmqenc->out = out;\n\tmqenc->maxctxs = maxctxs;\n\n\t/* Allocate memory for the per-context state information. */\n\tif (!(mqenc->ctxs = jas_malloc(mqenc->maxctxs * sizeof(jpc_mqstate_t *)))) {\n\t\tgoto error;\n\t}\n\n\t/* Set the current context to the first one. */\n\tmqenc->curctx = mqenc->ctxs;\n\n\tjpc_mqenc_init(mqenc);\n\n\t/* Initialize the per-context state information to something sane. */\n\tjpc_mqenc_setctxs(mqenc, 0, 0);\n\n\treturn mqenc;\n\nerror:\n\tif (mqenc) {\n\t\tjpc_mqenc_destroy(mqenc);\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being\ninvoked with the size argument being computed in a manner that would not\nallow integer overflow to be detected. Now, these places in the code\nhave been modified to use special-purpose memory allocation functions\n(e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow.\nThis should fix many security problems.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void jpc_qmfb_split_col(jpc_fix_t *a, int numrows, int stride,\n int parity)\n{\n\n\tint bufsize = JPC_CEILDIVPOW2(numrows, 1);\n\tjpc_fix_t splitbuf[QMFB_SPLITBUFSIZE];\n\tjpc_fix_t *buf = splitbuf;\n\tregister jpc_fix_t *srcptr;\n\tregister jpc_fix_t *dstptr;\n\tregister int n;\n\tregister int m;\n\tint hstartcol;\n\n\t/* Get a buffer. */\n\tif (bufsize > QMFB_SPLITBUFSIZE) {\n\t\tif (!(buf = jas_malloc(bufsize * sizeof(jpc_fix_t)))) {\n\t\t\t/* We have no choice but to commit suicide in this case. */\n\t\t\tabort();\n\t\t}\n\t}\n\n\tif (numrows >= 2) {\n\t\thstartcol = (numrows + 1 - parity) >> 1;\n\t\tm = (parity) ? hstartcol : (numrows - hstartcol);\n\t\t/* Save the samples destined for the highpass channel. */\n\t\tn = m;\n\t\tdstptr = buf;\n\t\tsrcptr = &a[(1 - parity) * stride];\n\t\twhile (n-- > 0) {\n\t\t\t*dstptr = *srcptr;\n\t\t\t++dstptr;\n\t\t\tsrcptr += stride << 1;\n\t\t}\n\t\t/* Copy the appropriate samples into the lowpass channel. */\n\t\tdstptr = &a[(1 - parity) * stride];\n\t\tsrcptr = &a[(2 - parity) * stride];\n\t\tn = numrows - m - (!parity);\n\t\twhile (n-- > 0) {\n\t\t\t*dstptr = *srcptr;\n\t\t\tdstptr += stride;\n\t\t\tsrcptr += stride << 1;\n\t\t}\n\t\t/* Copy the saved samples into the highpass channel. */\n\t\tdstptr = &a[hstartcol * stride];\n\t\tsrcptr = buf;\n\t\tn = m;\n\t\twhile (n-- > 0) {\n\t\t\t*dstptr = *srcptr;\n\t\t\tdstptr += stride;\n\t\t\t++srcptr;\n\t\t}\n\t}\n\n\t/* If the split buffer was allocated on the heap, free this memory. */\n\tif (buf != splitbuf) {\n\t\tjas_free(buf);\n\t}\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being\ninvoked with the size argument being computed in a manner that would not\nallow integer overflow to be detected. Now, these places in the code\nhave been modified to use special-purpose memory allocation functions\n(e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow.\nThis should fix many security problems.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int jas_cmshapmatlut_invert(jas_cmshapmatlut_t *invlut,\n jas_cmshapmatlut_t *lut, int n)\n{\n\tint i;\n\tint j;\n\tint k;\n\tjas_cmreal_t ax;\n\tjas_cmreal_t ay;\n\tjas_cmreal_t bx;\n\tjas_cmreal_t by;\n\tjas_cmreal_t sx;\n\tjas_cmreal_t sy;\n\tassert(n >= 2);\n\tif (invlut->data) {\n\t\tjas_free(invlut->data);\n\t\tinvlut->data = 0;\n\t}\n\t/* The sample values should be nondecreasing. */\n\tfor (i = 1; i < lut->size; ++i) {\n\t\tif (lut->data[i - 1] > lut->data[i]) {\n\t\t\tassert(0);\n\t\t\treturn -1;\n\t\t}\n\t}\n\tif (!(invlut->data = jas_malloc(n * sizeof(jas_cmreal_t))))\n\t\treturn -1;\n\tinvlut->size = n;\n\tfor (i = 0; i < invlut->size; ++i) {\n\t\tsy = ((double) i) / (invlut->size - 1);\n\t\tsx = 1.0;\n\t\tfor (j = 0; j < lut->size; ++j) {\n\t\t\tay = lut->data[j];\n\t\t\tif (sy == ay) {\n\t\t\t\tfor (k = j + 1; k < lut->size; ++k) {\n\t\t\t\t\tby = lut->data[k];\n\t\t\t\t\tif (by != sy)\n\t\t\t\t\t\tbreak;\n#if 0\nassert(0);\n#endif\n\t\t\t\t}\n\t\t\t\tif (k < lut->size) {\n\t\t\t\t\t--k;\n\t\t\t\t\tax = ((double) j) / (lut->size - 1);\n\t\t\t\t\tbx = ((double) k) / (lut->size - 1);\n\t\t\t\t\tsx = (ax + bx) / 2.0;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (j < lut->size - 1) {\n\t\t\t\tby = lut->data[j + 1];\n\t\t\t\tif (sy > ay && sy < by) {\n\t\t\t\t\tax = ((double) j) / (lut->size - 1);\n\t\t\t\t\tbx = ((double) j + 1) / (lut->size - 1);\n\t\t\t\t\tsx = ax +\n\t\t\t\t\t (sy - ay) / (by - ay) * (bx - ax);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tinvlut->data[i] = sx;\n\t}\n#if 0\nfor (i=0;isize;++i)\n\tjas_eprintf(\"lut[%d]=%f \", i, lut->data[i]);\nfor (i=0;isize;++i)\n\tjas_eprintf(\"invlut[%d]=%f \", i, invlut->data[i]);\n#endif\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being\ninvoked with the size argument being computed in a manner that would not\nallow integer overflow to be detected. Now, these places in the code\nhave been modified to use special-purpose memory allocation functions\n(e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow.\nThis should fix many security problems.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int jpc_enc_enccblk(jpc_enc_t *enc, jas_stream_t *out, jpc_enc_tcmpt_t *tcmpt, jpc_enc_band_t *band, jpc_enc_cblk_t *cblk)\n{\n\tjpc_enc_pass_t *pass;\n\tjpc_enc_pass_t *endpasses;\n\tint bitpos;\n\tint n;\n\tint adjust;\n\tint ret;\n\tint passtype;\n\tint t;\n\tjpc_bitstream_t *bout;\n\tjpc_enc_pass_t *termpass;\n\tjpc_enc_rlvl_t *rlvl;\n\tint vcausal;\n\tint segsym;\n\tint termmode;\n\tint c;\n\n\tbout = 0;\n\trlvl = band->rlvl;\n\n\tcblk->stream = jas_stream_memopen(0, 0);\n\tassert(cblk->stream);\n\tcblk->mqenc = jpc_mqenc_create(JPC_NUMCTXS, cblk->stream);\n\tassert(cblk->mqenc);\n\tjpc_mqenc_setctxs(cblk->mqenc, JPC_NUMCTXS, jpc_mqctxs);\n\n\tcblk->numpasses = (cblk->numbps > 0) ? (3 * cblk->numbps - 2) : 0;\n\tif (cblk->numpasses > 0) {\n\t\tcblk->passes = jas_malloc(cblk->numpasses * sizeof(jpc_enc_pass_t));\n\t\tassert(cblk->passes);\n\t} else {\n\t\tcblk->passes = 0;\n\t}\n\tendpasses = (cblk->passes) ? &cblk->passes[cblk->numpasses] : 0;\n\tfor (pass = cblk->passes; pass != endpasses; ++pass) {\n\t\tpass->start = 0;\n\t\tpass->end = 0;\n\t\tpass->term = JPC_ISTERMINATED(pass - cblk->passes, 0, cblk->numpasses, (tcmpt->cblksty & JPC_COX_TERMALL) != 0, (tcmpt->cblksty & JPC_COX_LAZY) != 0);\n\t\tpass->type = JPC_SEGTYPE(pass - cblk->passes, 0, (tcmpt->cblksty & JPC_COX_LAZY) != 0);\n\t\tpass->lyrno = -1;\nif (pass == endpasses - 1) {\nassert(pass->term == 1);\n\tpass->term = 1;\n}\n\t}\n\n\tcblk->flags = jas_matrix_create(jas_matrix_numrows(cblk->data) + 2,\n\t jas_matrix_numcols(cblk->data) + 2);\n\tassert(cblk->flags);\n\n\n\tbitpos = cblk->numbps - 1;\n\tpass = cblk->passes;\n\tn = cblk->numpasses;\n\twhile (--n >= 0) {\n\n\t\tif (pass->type == JPC_SEG_MQ) {\n\t\t\t/* NOP */\n\t\t} else {\n\t\t\tassert(pass->type == JPC_SEG_RAW);\n\t\t\tif (!bout) {\n\t\t\t\tbout = jpc_bitstream_sopen(cblk->stream, \"w\");\n\t\t\t\tassert(bout);\n\t\t\t}\n\t\t}\n\n#if 1\n\t\tpasstype = (pass - cblk->passes + 2) % 3;\n#else\n\t\tpasstype = JPC_PASSTYPE(pass - cblk->passes + 2);\n#endif\n\t\tpass->start = jas_stream_tell(cblk->stream);\n#if 0\nassert(jas_stream_tell(cblk->stream) == jas_stream_getrwcount(cblk->stream));\n#endif\n\t\tassert(bitpos >= 0);\n\t\tvcausal = (tcmpt->cblksty & JPC_COX_VSC) != 0;\n\t\tsegsym = (tcmpt->cblksty & JPC_COX_SEGSYM) != 0;\n\t\tif (pass->term) {\n\t\t\ttermmode = ((tcmpt->cblksty & JPC_COX_PTERM) ?\n\t\t\t JPC_MQENC_PTERM : JPC_MQENC_DEFTERM) + 1;\n\t\t} else {\n\t\t\ttermmode = 0;\n\t\t}\n\t\tswitch (passtype) {\n\t\tcase JPC_SIGPASS:\n\t\t\tret = (pass->type == JPC_SEG_MQ) ? jpc_encsigpass(cblk->mqenc,\n\t\t\t bitpos, band->orient, vcausal, cblk->flags,\n\t\t\t cblk->data, termmode, &pass->nmsedec) :\n\t\t\t jpc_encrawsigpass(bout, bitpos, vcausal, cblk->flags,\n\t\t\t cblk->data, termmode, &pass->nmsedec);\n\t\t\tbreak;\n\t\tcase JPC_REFPASS:\n\t\t\tret = (pass->type == JPC_SEG_MQ) ? jpc_encrefpass(cblk->mqenc,\n\t\t\t bitpos, vcausal, cblk->flags, cblk->data, termmode,\n\t\t\t &pass->nmsedec) : jpc_encrawrefpass(bout, bitpos,\n\t\t\t vcausal, cblk->flags, cblk->data, termmode,\n\t\t\t &pass->nmsedec);\n\t\t\tbreak;\n\t\tcase JPC_CLNPASS:\n\t\t\tassert(pass->type == JPC_SEG_MQ);\n\t\t\tret = jpc_encclnpass(cblk->mqenc, bitpos, band->orient,\n\t\t\t vcausal, segsym, cblk->flags, cblk->data, termmode,\n\t\t\t &pass->nmsedec);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tassert(0);\n\t\t\tbreak;\n\t\t}\n\n\t\tif (pass->type == JPC_SEG_MQ) {\n\t\t\tif (pass->term) {\n\t\t\t\tjpc_mqenc_init(cblk->mqenc);\n\t\t\t}\n\t\t\tjpc_mqenc_getstate(cblk->mqenc, &pass->mqencstate);\n\t\t\tpass->end = jas_stream_tell(cblk->stream);\n\t\t\tif (tcmpt->cblksty & JPC_COX_RESET) {\n\t\t\t\tjpc_mqenc_setctxs(cblk->mqenc, JPC_NUMCTXS, jpc_mqctxs);\n\t\t\t}\n\t\t} else {\n\t\t\tif (pass->term) {\n\t\t\t\tif (jpc_bitstream_pending(bout)) {\n\t\t\t\t\tjpc_bitstream_outalign(bout, 0x2a);\n\t\t\t\t}\n\t\t\t\tjpc_bitstream_close(bout);\n\t\t\t\tbout = 0;\n\t\t\t\tpass->end = jas_stream_tell(cblk->stream);\n\t\t\t} else {\n\t\t\t\tpass->end = jas_stream_tell(cblk->stream) +\n\t\t\t\t jpc_bitstream_pending(bout);\n/* NOTE - This will not work. need to adjust by # of pending output bytes */\n\t\t\t}\n\t\t}\n#if 0\n/* XXX - This assertion fails sometimes when various coding modes are used.\nThis seems to be harmless, but why does it happen at all? */\nassert(jas_stream_tell(cblk->stream) == jas_stream_getrwcount(cblk->stream));\n#endif\n\n\t\tpass->wmsedec = jpc_fixtodbl(band->rlvl->tcmpt->synweight) *\n\t\t jpc_fixtodbl(band->rlvl->tcmpt->synweight) *\n\t\t jpc_fixtodbl(band->synweight) *\n\t\t jpc_fixtodbl(band->synweight) *\n\t\t jpc_fixtodbl(band->absstepsize) * jpc_fixtodbl(band->absstepsize) *\n\t\t ((double) (1 << bitpos)) * ((double)(1 << bitpos)) *\n\t\t jpc_fixtodbl(pass->nmsedec);\n\t\tpass->cumwmsedec = pass->wmsedec;\n\t\tif (pass != cblk->passes) {\n\t\t\tpass->cumwmsedec += pass[-1].cumwmsedec;\n\t\t}\n\t\tif (passtype == JPC_CLNPASS) {\n\t\t\t--bitpos;\n\t\t}\n\t\t++pass;\n\t}\n\n#if 0\ndump_passes(cblk->passes, cblk->numpasses, cblk);\n#endif\n\n\tn = 0;\n\tendpasses = (cblk->passes) ? &cblk->passes[cblk->numpasses] : 0;\n\tfor (pass = cblk->passes; pass != endpasses; ++pass) {\n\t\tif (pass->start < n) {\n\t\t\tpass->start = n;\n\t\t}\n\t\tif (pass->end < n) {\n\t\t\tpass->end = n;\n\t\t}\n\t\tif (!pass->term) {\n\t\t\ttermpass = pass;\n\t\t\twhile (termpass - pass < cblk->numpasses &&\n\t\t\t !termpass->term) {\n\t\t\t\t++termpass;\n\t\t\t}\n\t\t\tif (pass->type == JPC_SEG_MQ) {\n\t\t\t\tt = (pass->mqencstate.lastbyte == 0xff) ? 1 : 0;\n\t\t\t\tif (pass->mqencstate.ctreg >= 5) {\n\t\t\t\t\tadjust = 4 + t;\n\t\t\t\t} else {\n\t\t\t\t\tadjust = 5 + t;\n\t\t\t\t}\n\t\t\t\tpass->end += adjust;\n\t\t\t}\n\t\t\tif (pass->end > termpass->end) {\n\t\t\t\tpass->end = termpass->end;\n\t\t\t}\n\t\t\tif ((c = getthebyte(cblk->stream, pass->end - 1)) == EOF) {\n\t\t\t\tabort();\n\t\t\t}\n\t\t\tif (c == 0xff) {\n\t\t\t\t++pass->end;\n\t\t\t}\n\t\t\tn = JAS_MAX(n, pass->end);\n\t\t} else {\n\t\t\tn = JAS_MAX(n, pass->end);\n\t\t}\n\t}\n\n#if 0\ndump_passes(cblk->passes, cblk->numpasses, cblk);\n#endif\n\n\tif (bout) {\n\t\tjpc_bitstream_close(bout);\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being\ninvoked with the size argument being computed in a manner that would not\nallow integer overflow to be detected. Now, these places in the code\nhave been modified to use special-purpose memory allocation functions\n(e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow.\nThis should fix many security problems.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int jpc_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate,\n jas_stream_t *in)\n{\n\tjpc_siz_t *siz = &ms->parms.siz;\n\tunsigned int i;\n\tuint_fast8_t tmp;\n\n\t/* Eliminate compiler warning about unused variables. */\n\tcstate = 0;\n\n\tif (jpc_getuint16(in, &siz->caps) ||\n\t jpc_getuint32(in, &siz->width) ||\n\t jpc_getuint32(in, &siz->height) ||\n\t jpc_getuint32(in, &siz->xoff) ||\n\t jpc_getuint32(in, &siz->yoff) ||\n\t jpc_getuint32(in, &siz->tilewidth) ||\n\t jpc_getuint32(in, &siz->tileheight) ||\n\t jpc_getuint32(in, &siz->tilexoff) ||\n\t jpc_getuint32(in, &siz->tileyoff) ||\n\t jpc_getuint16(in, &siz->numcomps)) {\n\t\treturn -1;\n\t}\n\tif (!siz->width || !siz->height || !siz->tilewidth ||\n\t !siz->tileheight || !siz->numcomps) {\n\t\treturn -1;\n\t}\n\tif (!(siz->comps = jas_malloc(siz->numcomps * sizeof(jpc_sizcomp_t)))) {\n\t\treturn -1;\n\t}\n\tfor (i = 0; i < siz->numcomps; ++i) {\n\t\tif (jpc_getuint8(in, &tmp) ||\n\t\t jpc_getuint8(in, &siz->comps[i].hsamp) ||\n\t\t jpc_getuint8(in, &siz->comps[i].vsamp)) {\n\t\t\tjas_free(siz->comps);\n\t\t\treturn -1;\n\t\t}\n\t\tsiz->comps[i].sgnd = (tmp >> 7) & 1;\n\t\tsiz->comps[i].prec = (tmp & 0x7f) + 1;\n\t}\n\tif (jas_stream_eof(in)) {\n\t\tjas_free(siz->comps);\n\t\treturn -1;\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being\ninvoked with the size argument being computed in a manner that would not\nallow integer overflow to be detected. Now, these places in the code\nhave been modified to use special-purpose memory allocation functions\n(e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow.\nThis should fix many security problems.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int jp2_pclr_getdata(jp2_box_t *box, jas_stream_t *in)\n{\n\tjp2_pclr_t *pclr = &box->data.pclr;\n\tint lutsize;\n\tunsigned int i;\n\tunsigned int j;\n\tint_fast32_t x;\n\n\tpclr->lutdata = 0;\n\n\tif (jp2_getuint16(in, &pclr->numlutents) ||\n\t jp2_getuint8(in, &pclr->numchans)) {\n\t\treturn -1;\n\t}\n\tlutsize = pclr->numlutents * pclr->numchans;\n\tif (!(pclr->lutdata = jas_malloc(lutsize * sizeof(int_fast32_t)))) {\n\t\treturn -1;\n\t}\n\tif (!(pclr->bpc = jas_malloc(pclr->numchans * sizeof(uint_fast8_t)))) {\n\t\treturn -1;\n\t}\n\tfor (i = 0; i < pclr->numchans; ++i) {\n\t\tif (jp2_getuint8(in, &pclr->bpc[i])) {\n\t\t\treturn -1;\n\t\t}\n\t}\n\tfor (i = 0; i < pclr->numlutents; ++i) {\n\t\tfor (j = 0; j < pclr->numchans; ++j) {\n\t\t\tif (jp2_getint(in, (pclr->bpc[j] & 0x80) != 0,\n\t\t\t (pclr->bpc[j] & 0x7f) + 1, &x)) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tpclr->lutdata[i * pclr->numchans + j] = x;\n\t\t}\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being\ninvoked with the size argument being computed in a manner that would not\nallow integer overflow to be detected. Now, these places in the code\nhave been modified to use special-purpose memory allocation functions\n(e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow.\nThis should fix many security problems.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: _dbus_marshal_validate_test (void)\n{\n DBusString str;\n int i;\n\n const char *valid_paths[] = {\n \"/\",\n \"/foo/bar\",\n \"/foo\",\n \"/foo/bar/baz\"\n };\n const char *invalid_paths[] = {\n \"bar\",\n \"bar/baz\",\n \"/foo/bar/\",\n \"/foo/\"\n \"foo/\",\n \"boo//blah\",\n \"//\",\n \"///\",\n \"foo///blah/\",\n \"Hello World\",\n \"\",\n \" \",\n \"foo bar\"\n };\n\n const char *valid_interfaces[] = {\n \"org.freedesktop.Foo\",\n \"Bar.Baz\",\n \"Blah.Blah.Blah.Blah.Blah\",\n \"a.b\",\n \"a.b.c.d.e.f.g\",\n \"a0.b1.c2.d3.e4.f5.g6\",\n \"abc123.foo27\"\n };\n const char *invalid_interfaces[] = {\n \".\",\n \"\",\n \"..\",\n \".Foo.Bar\",\n \"..Foo.Bar\",\n \"Foo.Bar.\",\n \"Foo.Bar..\",\n \"Foo\",\n \"9foo.bar.baz\",\n \"foo.bar..baz\",\n \"foo.bar...baz\",\n \"foo.bar.b..blah\",\n \":\",\n \":0-1\",\n \"10\",\n \":11.34324\",\n \"0.0.0\",\n \"0..0\",\n \"foo.Bar.%\",\n \"foo.Bar!!\",\n \"!Foo.bar.bz\",\n \"foo.$.blah\",\n \"\",\n \" \",\n \"foo bar\"\n };\n\n const char *valid_unique_names[] = {\n \":0\",\n \":a\",\n \":\",\n \":.a\",\n \":.1\",\n \":0.1\",\n \":000.2222\",\n \":.blah\",\n \":abce.freedesktop.blah\"\n };\n const char *invalid_unique_names[] = {\n //\":-\",\n \":!\",\n //\":0-10\",\n \":blah.\",\n \":blah.\",\n \":blah..org\",\n \":blah.org..\",\n \":..blah.org\",\n \"\",\n \" \",\n \"foo bar\"\n };\n\n const char *valid_members[] = {\n \"Hello\",\n \"Bar\",\n \"foobar\",\n \"_foobar\",\n \"foo89\"\n };\n\n const char *invalid_members[] = {\n \"9Hello\",\n \"10\",\n \"1\",\n \"foo-bar\",\n \"blah.org\",\n \".blah\",\n \"blah.\",\n \"Hello.\",\n \"!foo\",\n \"\",\n \" \",\n \"foo bar\"\n };\n\n const char *valid_signatures[] = {\n \"\",\n \"sss\",\n \"i\",\n \"b\"\n };\n\n const char *invalid_signatures[] = {\n \" \",\n \"not a valid signature\",\n \"123\",\n \".\",\n \"(\"\n };\n\n /* Signature with reason */\n\n run_validity_tests (signature_tests, _DBUS_N_ELEMENTS (signature_tests),\n _dbus_validate_signature_with_reason);\n\n /* Path validation */\n i = 0;\n while (i < (int) _DBUS_N_ELEMENTS (valid_paths))\n {\n _dbus_string_init_const (&str, valid_paths[i]);\n\n if (!_dbus_validate_path (&str, 0,\n _dbus_string_get_length (&str)))\n {\n _dbus_warn (\"Path \\\"%s\\\" should have been valid\\n\", valid_paths[i]);\n _dbus_assert_not_reached (\"invalid path\");\n }\n\n ++i;\n }\n\n i = 0;\n while (i < (int) _DBUS_N_ELEMENTS (invalid_paths))\n {\n _dbus_string_init_const (&str, invalid_paths[i]);\n\n if (_dbus_validate_path (&str, 0,\n _dbus_string_get_length (&str)))\n {\n _dbus_warn (\"Path \\\"%s\\\" should have been invalid\\n\", invalid_paths[i]);\n _dbus_assert_not_reached (\"valid path\");\n }\n\n ++i;\n }\n\n /* Interface validation */\n i = 0;\n while (i < (int) _DBUS_N_ELEMENTS (valid_interfaces))\n {\n _dbus_string_init_const (&str, valid_interfaces[i]);\n\n if (!_dbus_validate_interface (&str, 0,\n _dbus_string_get_length (&str)))\n {\n _dbus_warn (\"Interface \\\"%s\\\" should have been valid\\n\", valid_interfaces[i]);\n _dbus_assert_not_reached (\"invalid interface\");\n }\n\n ++i;\n }\n\n i = 0;\n while (i < (int) _DBUS_N_ELEMENTS (invalid_interfaces))\n {\n _dbus_string_init_const (&str, invalid_interfaces[i]);\n\n if (_dbus_validate_interface (&str, 0,\n _dbus_string_get_length (&str)))\n {\n _dbus_warn (\"Interface \\\"%s\\\" should have been invalid\\n\", invalid_interfaces[i]);\n _dbus_assert_not_reached (\"valid interface\");\n }\n\n ++i;\n }\n\n /* Bus name validation (check that valid interfaces are valid bus names,\n * and invalid interfaces are invalid services except if they start with ':')\n */\n i = 0;\n while (i < (int) _DBUS_N_ELEMENTS (valid_interfaces))\n {\n _dbus_string_init_const (&str, valid_interfaces[i]);\n\n if (!_dbus_validate_bus_name (&str, 0,\n _dbus_string_get_length (&str)))\n {\n _dbus_warn (\"Bus name \\\"%s\\\" should have been valid\\n\", valid_interfaces[i]);\n _dbus_assert_not_reached (\"invalid bus name\");\n }\n\n ++i;\n }\n\n i = 0;\n while (i < (int) _DBUS_N_ELEMENTS (invalid_interfaces))\n {\n if (invalid_interfaces[i][0] != ':')\n {\n _dbus_string_init_const (&str, invalid_interfaces[i]);\n\n if (_dbus_validate_bus_name (&str, 0,\n _dbus_string_get_length (&str)))\n {\n _dbus_warn (\"Bus name \\\"%s\\\" should have been invalid\\n\", invalid_interfaces[i]);\n _dbus_assert_not_reached (\"valid bus name\");\n }\n }\n\n ++i;\n }\n\n /* unique name validation */\n i = 0;\n while (i < (int) _DBUS_N_ELEMENTS (valid_unique_names))\n {\n _dbus_string_init_const (&str, valid_unique_names[i]);\n\n if (!_dbus_validate_bus_name (&str, 0,\n _dbus_string_get_length (&str)))\n {\n _dbus_warn (\"Bus name \\\"%s\\\" should have been valid\\n\", valid_unique_names[i]);\n _dbus_assert_not_reached (\"invalid unique name\");\n }\n\n ++i;\n }\n\n i = 0;\n while (i < (int) _DBUS_N_ELEMENTS (invalid_unique_names))\n {\n _dbus_string_init_const (&str, invalid_unique_names[i]);\n\n if (_dbus_validate_bus_name (&str, 0,\n _dbus_string_get_length (&str)))\n {\n _dbus_warn (\"Bus name \\\"%s\\\" should have been invalid\\n\", invalid_unique_names[i]);\n _dbus_assert_not_reached (\"valid unique name\");\n }\n\n ++i;\n }\n\n\n /* Error name validation (currently identical to interfaces)\n */\n i = 0;\n while (i < (int) _DBUS_N_ELEMENTS (valid_interfaces))\n {\n _dbus_string_init_const (&str, valid_interfaces[i]);\n\n if (!_dbus_validate_error_name (&str, 0,\n _dbus_string_get_length (&str)))\n {\n _dbus_warn (\"Error name \\\"%s\\\" should have been valid\\n\", valid_interfaces[i]);\n _dbus_assert_not_reached (\"invalid error name\");\n }\n\n ++i;\n }\n\n i = 0;\n while (i < (int) _DBUS_N_ELEMENTS (invalid_interfaces))\n {\n if (invalid_interfaces[i][0] != ':')\n {\n _dbus_string_init_const (&str, invalid_interfaces[i]);\n\n if (_dbus_validate_error_name (&str, 0,\n _dbus_string_get_length (&str)))\n {\n _dbus_warn (\"Error name \\\"%s\\\" should have been invalid\\n\", invalid_interfaces[i]);\n _dbus_assert_not_reached (\"valid error name\");\n }\n }\n\n ++i;\n }\n\n /* Member validation */\n i = 0;\n while (i < (int) _DBUS_N_ELEMENTS (valid_members))\n {\n _dbus_string_init_const (&str, valid_members[i]);\n\n if (!_dbus_validate_member (&str, 0,\n _dbus_string_get_length (&str)))\n {\n _dbus_warn (\"Member \\\"%s\\\" should have been valid\\n\", valid_members[i]);\n _dbus_assert_not_reached (\"invalid member\");\n }\n\n ++i;\n }\n\n i = 0;\n while (i < (int) _DBUS_N_ELEMENTS (invalid_members))\n {\n _dbus_string_init_const (&str, invalid_members[i]);\n\n if (_dbus_validate_member (&str, 0,\n _dbus_string_get_length (&str)))\n {\n _dbus_warn (\"Member \\\"%s\\\" should have been invalid\\n\", invalid_members[i]);\n _dbus_assert_not_reached (\"valid member\");\n }\n\n ++i;\n }\n\n /* Signature validation */\n i = 0;\n while (i < (int) _DBUS_N_ELEMENTS (valid_signatures))\n {\n _dbus_string_init_const (&str, valid_signatures[i]);\n\n if (!_dbus_validate_signature (&str, 0,\n _dbus_string_get_length (&str)))\n {\n _dbus_warn (\"Signature \\\"%s\\\" should have been valid\\n\", valid_signatures[i]);\n _dbus_assert_not_reached (\"invalid signature\");\n }\n\n ++i;\n }\n\n i = 0;\n while (i < (int) _DBUS_N_ELEMENTS (invalid_signatures))\n {\n _dbus_string_init_const (&str, invalid_signatures[i]);\n\n if (_dbus_validate_signature (&str, 0,\n _dbus_string_get_length (&str)))\n {\n _dbus_warn (\"Signature \\\"%s\\\" should have been invalid\\n\", invalid_signatures[i]);\n _dbus_assert_not_reached (\"valid signature\");\n }\n\n ++i;\n }\n\n /* Validate claimed length longer than real length */\n _dbus_string_init_const (&str, \"abc.efg\");\n if (_dbus_validate_bus_name (&str, 0, 8))\n _dbus_assert_not_reached (\"validated too-long string\");\n if (_dbus_validate_interface (&str, 0, 8))\n _dbus_assert_not_reached (\"validated too-long string\");\n if (_dbus_validate_error_name (&str, 0, 8))\n _dbus_assert_not_reached (\"validated too-long string\");\n\n _dbus_string_init_const (&str, \"abc\");\n if (_dbus_validate_member (&str, 0, 4))\n _dbus_assert_not_reached (\"validated too-long string\");\n\n _dbus_string_init_const (&str, \"sss\");\n if (_dbus_validate_signature (&str, 0, 4))\n _dbus_assert_not_reached (\"validated too-long signature\");\n\n /* Validate string exceeding max name length */\n if (!_dbus_string_init (&str))\n _dbus_assert_not_reached (\"no memory\");\n\n while (_dbus_string_get_length (&str) <= DBUS_MAXIMUM_NAME_LENGTH)\n if (!_dbus_string_append (&str, \"abc.def\"))\n _dbus_assert_not_reached (\"no memory\");\n\n if (_dbus_validate_bus_name (&str, 0, _dbus_string_get_length (&str)))\n _dbus_assert_not_reached (\"validated overmax string\");\n if (_dbus_validate_interface (&str, 0, _dbus_string_get_length (&str)))\n _dbus_assert_not_reached (\"validated overmax string\");\n if (_dbus_validate_error_name (&str, 0, _dbus_string_get_length (&str)))\n _dbus_assert_not_reached (\"validated overmax string\");\n\n /* overlong member */\n _dbus_string_set_length (&str, 0);\n while (_dbus_string_get_length (&str) <= DBUS_MAXIMUM_NAME_LENGTH)\n if (!_dbus_string_append (&str, \"abc\"))\n _dbus_assert_not_reached (\"no memory\");\n\n if (_dbus_validate_member (&str, 0, _dbus_string_get_length (&str)))\n _dbus_assert_not_reached (\"validated overmax string\");\n\n /* overlong unique name */\n _dbus_string_set_length (&str, 0);\n _dbus_string_append (&str, \":\");\n while (_dbus_string_get_length (&str) <= DBUS_MAXIMUM_NAME_LENGTH)\n if (!_dbus_string_append (&str, \"abc\"))\n _dbus_assert_not_reached (\"no memory\");\n\n if (_dbus_validate_bus_name (&str, 0, _dbus_string_get_length (&str)))\n _dbus_assert_not_reached (\"validated overmax string\");\n\n _dbus_string_free (&str);\n\n /* Body validation; test basic validation of valid bodies for both endian */\n \n {\n int sequence;\n DBusString signature;\n DBusString body;\n\n if (!_dbus_string_init (&signature) || !_dbus_string_init (&body))\n _dbus_assert_not_reached (\"oom\");\n\n sequence = 0;\n while (dbus_internal_do_not_use_generate_bodies (sequence,\n DBUS_LITTLE_ENDIAN,\n &signature, &body))\n {\n DBusValidity validity;\n\n validity = _dbus_validate_body_with_reason (&signature, 0,\n DBUS_LITTLE_ENDIAN,\n NULL, &body, 0,\n _dbus_string_get_length (&body));\n if (validity != DBUS_VALID)\n {\n _dbus_warn (\"invalid code %d expected valid on sequence %d little endian\\n\",\n validity, sequence);\n _dbus_verbose_bytes_of_string (&signature, 0, _dbus_string_get_length (&signature));\n _dbus_verbose_bytes_of_string (&body, 0, _dbus_string_get_length (&body));\n _dbus_assert_not_reached (\"test failed\");\n }\n\n _dbus_string_set_length (&signature, 0);\n _dbus_string_set_length (&body, 0);\n ++sequence;\n }\n \n sequence = 0;\n while (dbus_internal_do_not_use_generate_bodies (sequence,\n DBUS_BIG_ENDIAN,\n &signature, &body))\n {\n DBusValidity validity;\n\n validity = _dbus_validate_body_with_reason (&signature, 0,\n DBUS_BIG_ENDIAN,\n NULL, &body, 0,\n _dbus_string_get_length (&body));\n if (validity != DBUS_VALID)\n {\n _dbus_warn (\"invalid code %d expected valid on sequence %d big endian\\n\",\n validity, sequence);\n _dbus_verbose_bytes_of_string (&signature, 0, _dbus_string_get_length (&signature));\n _dbus_verbose_bytes_of_string (&body, 0, _dbus_string_get_length (&body));\n _dbus_assert_not_reached (\"test failed\");\n }\n\n _dbus_string_set_length (&signature, 0);\n _dbus_string_set_length (&body, 0);\n ++sequence;\n }\n\n _dbus_string_free (&signature);\n _dbus_string_free (&body);\n }\n \n return TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Bug 17803: Panic from dbus_signature_validate\n\n\t* dbus/dbus-marshal-validate.c: Ensure we validate\n\ta basic type before calling is_basic on it.\n\t* dbus-marshal-validate-util.c: Test.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int hfsplus_find_cat(struct super_block *sb, u32 cnid,\n\t\t struct hfs_find_data *fd)\n{\n\thfsplus_cat_entry tmp;\n\tint err;\n\tu16 type;\n\n\thfsplus_cat_build_key(sb, fd->search_key, cnid, NULL);\n\terr = hfs_brec_read(fd, &tmp, sizeof(hfsplus_cat_entry));\n\tif (err)\n\t\treturn err;\n\n\ttype = be16_to_cpu(tmp.type);\n\tif (type != HFSPLUS_FOLDER_THREAD && type != HFSPLUS_FILE_THREAD) {\n\t\tprintk(KERN_ERR \"hfs: found bad thread record in catalog\\n\");\n\t\treturn -EIO;\n\t}\n\n\thfsplus_cat_build_key_uni(fd->search_key, be32_to_cpu(tmp.thread.parentID),\n\t\t\t\t &tmp.thread.nodeName);\n\treturn hfs_brec_find(fd);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'hfsplus: fix Buffer overflow with a corrupted image\n\nWhen an hfsplus image gets corrupted it might happen that the catalog\nnamelength field gets b0rked. If we mount such an image the memcpy() in\nhfsplus_cat_build_key_uni() writes more than the 255 that fit in the name\nfield. Depending on the size of the overwritten data, we either only get\nmemory corruption or also trigger an oops like this:\n\n[ 221.628020] BUG: unable to handle kernel paging request at c82b0000\n[ 221.629066] IP: [] hfsplus_find_cat+0x10d/0x151\n[ 221.629066] *pde = 0ea29163 *pte = 082b0160\n[ 221.629066] Oops: 0002 [#1] PREEMPT DEBUG_PAGEALLOC\n[ 221.629066] Modules linked in:\n[ 221.629066]\n[ 221.629066] Pid: 4845, comm: mount Not tainted (2.6.27-rc4-00123-gd3ee1b4-dirty #28)\n[ 221.629066] EIP: 0060:[] EFLAGS: 00010206 CPU: 0\n[ 221.629066] EIP is at hfsplus_find_cat+0x10d/0x151\n[ 221.629066] EAX: 00000029 EBX: 00016210 ECX: 000042c2 EDX: 00000002\n[ 221.629066] ESI: c82d70ca EDI: c82b0000 EBP: c82d1bcc ESP: c82d199c\n[ 221.629066] DS: 007b ES: 007b FS: 0000 GS: 0033 SS: 0068\n[ 221.629066] Process mount (pid: 4845, ti=c82d1000 task=c8224060 task.ti=c82d1000)\n[ 221.629066] Stack: c080b3c4 c82aa8f8 c82d19c2 00016210 c080b3be c82d1bd4 c82aa8f0 00000300\n[ 221.629066] 01000000 750008b1 74006e00 74006900 65006c00 c82d6400 c013bd35 c8224060\n[ 221.629066] 00000036 00000046 c82d19f0 00000082 c8224548 c8224060 00000036 c0d653cc\n[ 221.629066] Call Trace:\n[ 221.629066] [] ? trace_hardirqs_off+0xb/0xd\n[ 221.629066] [] ? trace_hardirqs_off_caller+0x14/0x9b\n[ 221.629066] [] ? trace_hardirqs_off+0xb/0xd\n[ 221.629066] [] ? trace_hardirqs_off_caller+0x14/0x9b\n[ 221.629066] [] ? trace_hardirqs_off+0xb/0xd\n[ 221.629066] [] ? native_sched_clock+0x82/0x96\n[ 221.629066] [] ? __kernel_text_address+0x1b/0x27\n[ 221.629066] [] ? dump_trace+0xca/0xd6\n[ 221.629066] [] ? save_stack_address+0x0/0x2c\n[ 221.629066] [] ? save_stack_trace+0x1c/0x3a\n[ 221.629066] [] ? save_trace+0x37/0x8d\n[ 221.629066] [] ? add_lock_to_list+0x67/0x8d\n[ 221.629066] [] ? validate_chain+0x8a4/0x9f4\n[ 221.629066] [] ? down+0xc/0x2f\n[ 221.629066] [] ? __lock_acquire+0x68a/0x6e0\n[ 221.629066] [] ? trace_hardirqs_off+0xb/0xd\n[ 221.629066] [] ? trace_hardirqs_off_caller+0x14/0x9b\n[ 221.629066] [] ? trace_hardirqs_off+0xb/0xd\n[ 221.629066] [] ? native_sched_clock+0x82/0x96\n[ 221.629066] [] ? mark_held_locks+0x43/0x5a\n[ 221.629066] [] ? trace_hardirqs_on+0xb/0xd\n[ 221.629066] [] ? trace_hardirqs_on_caller+0xf4/0x12f\n[ 221.629066] [] ? _spin_unlock_irqrestore+0x42/0x58\n[ 221.629066] [] ? down+0x2b/0x2f\n[ 221.629066] [] ? hfsplus_iget+0xa0/0x154\n[ 221.629066] [] ? hfsplus_fill_super+0x280/0x447\n[ 221.629066] [] ? native_sched_clock+0x82/0x96\n[ 221.629066] [] ? trace_hardirqs_off_caller+0x14/0x9b\n[ 221.629066] [] ? trace_hardirqs_off_caller+0x14/0x9b\n[ 221.629066] [] ? __lock_acquire+0x68a/0x6e0\n[ 221.629066] [] ? string+0x2b/0x74\n[ 221.629066] [] ? vsnprintf+0x2e9/0x512\n[ 221.629066] [] ? dump_trace+0xca/0xd6\n[ 221.629066] [] ? save_stack_trace+0x1c/0x3a\n[ 221.629066] [] ? save_stack_trace+0x1c/0x3a\n[ 221.629066] [] ? save_trace+0x37/0x8d\n[ 221.629066] [] ? add_lock_to_list+0x67/0x8d\n[ 221.629066] [] ? validate_chain+0x8a4/0x9f4\n[ 221.629066] [] ? up+0xc/0x2f\n[ 221.629066] [] ? __lock_acquire+0x68a/0x6e0\n[ 221.629066] [] ? trace_hardirqs_off+0xb/0xd\n[ 221.629066] [] ? trace_hardirqs_off_caller+0x14/0x9b\n[ 221.629066] [] ? trace_hardirqs_off+0xb/0xd\n[ 221.629066] [] ? native_sched_clock+0x82/0x96\n[ 221.629066] [] ? snprintf+0x1b/0x1d\n[ 221.629066] [] ? disk_name+0x25/0x67\n[ 221.629066] [] ? get_sb_bdev+0xcd/0x10b\n[ 221.629066] [] ? kstrdup+0x2a/0x4c\n[ 221.629066] [] ? hfsplus_get_sb+0x13/0x15\n[ 221.629066] [] ? hfsplus_fill_super+0x0/0x447\n[ 221.629066] [] ? vfs_kern_mount+0x3b/0x76\n[ 221.629066] [] ? do_kern_mount+0x32/0xba\n[ 221.629066] [] ? do_new_mount+0x46/0x74\n[ 221.629066] [] ? do_mount+0x175/0x193\n[ 221.629066] [] ? trace_hardirqs_on_caller+0xf4/0x12f\n[ 221.629066] [] ? __get_free_pages+0x1e/0x24\n[ 221.629066] [] ? lock_kernel+0x19/0x8c\n[ 221.629066] [] ? sys_mount+0x51/0x9b\n[ 221.629066] [] ? sys_mount+0x64/0x9b\n[ 221.629066] [] ? sysenter_do_call+0x12/0x31\n[ 221.629066] =======================\n[ 221.629066] Code: 89 c2 c1 e2 08 c1 e8 08 09 c2 8b 85 e8 fd ff ff 66 89 50 06 89 c7 53 83 c7 08 56 57 68 c4 b3 80 c0 e8 8c 5c ef ff 89 d9 c1 e9 02 a5 89 d9 83 e1 03 74 02 f3 a4 83 c3 06 8b 95 e8 fd ff ff 0f\n[ 221.629066] EIP: [] hfsplus_find_cat+0x10d/0x151 SS:ESP 0068:c82d199c\n[ 221.629066] ---[ end trace e417a1d67f0d0066 ]---\n\nSince hfsplus_cat_build_key_uni() returns void and only has one callsite,\nthe check is performed at the callsite.\n\nSigned-off-by: Eric Sesterhenn \nReviewed-by: Pekka Enberg \nCc: Roman Zippel \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int uvc_parse_format(struct uvc_device *dev,\n\tstruct uvc_streaming *streaming, struct uvc_format *format,\n\t__u32 **intervals, unsigned char *buffer, int buflen)\n{\n\tstruct usb_interface *intf = streaming->intf;\n\tstruct usb_host_interface *alts = intf->cur_altsetting;\n\tstruct uvc_format_desc *fmtdesc;\n\tstruct uvc_frame *frame;\n\tconst unsigned char *start = buffer;\n\tunsigned int interval;\n\tunsigned int i, n;\n\t__u8 ftype;\n\n\tformat->type = buffer[2];\n\tformat->index = buffer[3];\n\n\tswitch (buffer[2]) {\n\tcase VS_FORMAT_UNCOMPRESSED:\n\tcase VS_FORMAT_FRAME_BASED:\n\t\tif (buflen < 27) {\n\t\t\tuvc_trace(UVC_TRACE_DESCR, \"device %d videostreaming\"\n\t\t\t \"interface %d FORMAT error\\n\",\n\t\t\t dev->udev->devnum,\n\t\t\t alts->desc.bInterfaceNumber);\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t\t/* Find the format descriptor from its GUID. */\n\t\tfmtdesc = uvc_format_by_guid(&buffer[5]);\n\n\t\tif (fmtdesc != NULL) {\n\t\t\tstrncpy(format->name, fmtdesc->name,\n\t\t\t\tsizeof format->name);\n\t\t\tformat->fcc = fmtdesc->fcc;\n\t\t} else {\n\t\t\tuvc_printk(KERN_INFO, \"Unknown video format \"\n\t\t\t\tUVC_GUID_FORMAT \"\\n\",\n\t\t\t\tUVC_GUID_ARGS(&buffer[5]));\n\t\t\tsnprintf(format->name, sizeof format->name,\n\t\t\t\tUVC_GUID_FORMAT, UVC_GUID_ARGS(&buffer[5]));\n\t\t\tformat->fcc = 0;\n\t\t}\n\n\t\tformat->bpp = buffer[21];\n\t\tif (buffer[2] == VS_FORMAT_UNCOMPRESSED) {\n\t\t\tftype = VS_FRAME_UNCOMPRESSED;\n\t\t} else {\n\t\t\tftype = VS_FRAME_FRAME_BASED;\n\t\t\tif (buffer[27])\n\t\t\t\tformat->flags = UVC_FMT_FLAG_COMPRESSED;\n\t\t}\n\t\tbreak;\n\n\tcase VS_FORMAT_MJPEG:\n\t\tif (buflen < 11) {\n\t\t\tuvc_trace(UVC_TRACE_DESCR, \"device %d videostreaming\"\n\t\t\t \"interface %d FORMAT error\\n\",\n\t\t\t dev->udev->devnum,\n\t\t\t alts->desc.bInterfaceNumber);\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t\tstrncpy(format->name, \"MJPEG\", sizeof format->name);\n\t\tformat->fcc = V4L2_PIX_FMT_MJPEG;\n\t\tformat->flags = UVC_FMT_FLAG_COMPRESSED;\n\t\tformat->bpp = 0;\n\t\tftype = VS_FRAME_MJPEG;\n\t\tbreak;\n\n\tcase VS_FORMAT_DV:\n\t\tif (buflen < 9) {\n\t\t\tuvc_trace(UVC_TRACE_DESCR, \"device %d videostreaming\"\n\t\t\t \"interface %d FORMAT error\\n\",\n\t\t\t dev->udev->devnum,\n\t\t\t alts->desc.bInterfaceNumber);\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t\tswitch (buffer[8] & 0x7f) {\n\t\tcase 0:\n\t\t\tstrncpy(format->name, \"SD-DV\", sizeof format->name);\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tstrncpy(format->name, \"SDL-DV\", sizeof format->name);\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tstrncpy(format->name, \"HD-DV\", sizeof format->name);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tuvc_trace(UVC_TRACE_DESCR, \"device %d videostreaming\"\n\t\t\t \"interface %d: unknown DV format %u\\n\",\n\t\t\t dev->udev->devnum,\n\t\t\t alts->desc.bInterfaceNumber, buffer[8]);\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t\tstrncat(format->name, buffer[8] & (1 << 7) ? \" 60Hz\" : \" 50Hz\",\n\t\t\tsizeof format->name);\n\n\t\tformat->fcc = V4L2_PIX_FMT_DV;\n\t\tformat->flags = UVC_FMT_FLAG_COMPRESSED | UVC_FMT_FLAG_STREAM;\n\t\tformat->bpp = 0;\n\t\tftype = 0;\n\n\t\t/* Create a dummy frame descriptor. */\n\t\tframe = &format->frame[0];\n\t\tmemset(&format->frame[0], 0, sizeof format->frame[0]);\n\t\tframe->bFrameIntervalType = 1;\n\t\tframe->dwDefaultFrameInterval = 1;\n\t\tframe->dwFrameInterval = *intervals;\n\t\t*(*intervals)++ = 1;\n\t\tformat->nframes = 1;\n\t\tbreak;\n\n\tcase VS_FORMAT_MPEG2TS:\n\tcase VS_FORMAT_STREAM_BASED:\n\t\t/* Not supported yet. */\n\tdefault:\n\t\tuvc_trace(UVC_TRACE_DESCR, \"device %d videostreaming\"\n\t\t \"interface %d unsupported format %u\\n\",\n\t\t dev->udev->devnum, alts->desc.bInterfaceNumber,\n\t\t buffer[2]);\n\t\treturn -EINVAL;\n\t}\n\n\tuvc_trace(UVC_TRACE_DESCR, \"Found format %s.\\n\", format->name);\n\n\tbuflen -= buffer[0];\n\tbuffer += buffer[0];\n\n\t/* Parse the frame descriptors. Only uncompressed, MJPEG and frame\n\t * based formats have frame descriptors.\n\t */\n\twhile (buflen > 2 && buffer[2] == ftype) {\n\t\tframe = &format->frame[format->nframes];\n\n\t\tif (ftype != VS_FRAME_FRAME_BASED)\n\t\t\tn = buflen > 25 ? buffer[25] : 0;\n\t\telse\n\t\t\tn = buflen > 21 ? buffer[21] : 0;\n\n\t\tn = n ? n : 3;\n\n\t\tif (buflen < 26 + 4*n) {\n\t\t\tuvc_trace(UVC_TRACE_DESCR, \"device %d videostreaming\"\n\t\t\t \"interface %d FRAME error\\n\", dev->udev->devnum,\n\t\t\t alts->desc.bInterfaceNumber);\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t\tframe->bFrameIndex = buffer[3];\n\t\tframe->bmCapabilities = buffer[4];\n\t\tframe->wWidth = le16_to_cpup((__le16 *)&buffer[5]);\n\t\tframe->wHeight = le16_to_cpup((__le16 *)&buffer[7]);\n\t\tframe->dwMinBitRate = le32_to_cpup((__le32 *)&buffer[9]);\n\t\tframe->dwMaxBitRate = le32_to_cpup((__le32 *)&buffer[13]);\n\t\tif (ftype != VS_FRAME_FRAME_BASED) {\n\t\t\tframe->dwMaxVideoFrameBufferSize =\n\t\t\t\tle32_to_cpup((__le32 *)&buffer[17]);\n\t\t\tframe->dwDefaultFrameInterval =\n\t\t\t\tle32_to_cpup((__le32 *)&buffer[21]);\n\t\t\tframe->bFrameIntervalType = buffer[25];\n\t\t} else {\n\t\t\tframe->dwMaxVideoFrameBufferSize = 0;\n\t\t\tframe->dwDefaultFrameInterval =\n\t\t\t\tle32_to_cpup((__le32 *)&buffer[17]);\n\t\t\tframe->bFrameIntervalType = buffer[21];\n\t\t}\n\t\tframe->dwFrameInterval = *intervals;\n\n\t\t/* Several UVC chipsets screw up dwMaxVideoFrameBufferSize\n\t\t * completely. Observed behaviours range from setting the\n\t\t * value to 1.1x the actual frame size of hardwiring the\n\t\t * 16 low bits to 0. This results in a higher than necessary\n\t\t * memory usage as well as a wrong image size information. For\n\t\t * uncompressed formats this can be fixed by computing the\n\t\t * value from the frame size.\n\t\t */\n\t\tif (!(format->flags & UVC_FMT_FLAG_COMPRESSED))\n\t\t\tframe->dwMaxVideoFrameBufferSize = format->bpp\n\t\t\t\t* frame->wWidth * frame->wHeight / 8;\n\n\t\t/* Some bogus devices report dwMinFrameInterval equal to\n\t\t * dwMaxFrameInterval and have dwFrameIntervalStep set to\n\t\t * zero. Setting all null intervals to 1 fixes the problem and\n\t\t * some other divisions by zero which could happen.\n\t\t */\n\t\tfor (i = 0; i < n; ++i) {\n\t\t\tinterval = le32_to_cpup((__le32 *)&buffer[26+4*i]);\n\t\t\t*(*intervals)++ = interval ? interval : 1;\n\t\t}\n\n\t\t/* Make sure that the default frame interval stays between\n\t\t * the boundaries.\n\t\t */\n\t\tn -= frame->bFrameIntervalType ? 1 : 2;\n\t\tframe->dwDefaultFrameInterval =\n\t\t\tmin(frame->dwFrameInterval[n],\n\t\t\t max(frame->dwFrameInterval[0],\n\t\t\t\tframe->dwDefaultFrameInterval));\n\n\t\tuvc_trace(UVC_TRACE_DESCR, \"- %ux%u (%u.%u fps)\\n\",\n\t\t\tframe->wWidth, frame->wHeight,\n\t\t\t10000000/frame->dwDefaultFrameInterval,\n\t\t\t(100000000/frame->dwDefaultFrameInterval)%10);\n\n\t\tformat->nframes++;\n\t\tbuflen -= buffer[0];\n\t\tbuffer += buffer[0];\n\t}\n\n\tif (buflen > 2 && buffer[2] == VS_STILL_IMAGE_FRAME) {\n\t\tbuflen -= buffer[0];\n\t\tbuffer += buffer[0];\n\t}\n\n\tif (buflen > 2 && buffer[2] == VS_COLORFORMAT) {\n\t\tif (buflen < 6) {\n\t\t\tuvc_trace(UVC_TRACE_DESCR, \"device %d videostreaming\"\n\t\t\t \"interface %d COLORFORMAT error\\n\",\n\t\t\t dev->udev->devnum,\n\t\t\t alts->desc.bInterfaceNumber);\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t\tformat->colorspace = uvc_colorspace(buffer[3]);\n\n\t\tbuflen -= buffer[0];\n\t\tbuffer += buffer[0];\n\t}\n\n\treturn buffer - start;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'V4L/DVB (8207): uvcvideo: Fix a buffer overflow in format descriptor parsing\n\nThanks to Oliver Neukum for catching and reporting this bug.\n\nSigned-off-by: Laurent Pinchart \nSigned-off-by: Mauro Carvalho Chehab '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void audit_inotify_unregister(struct list_head *in_list)\n{\n\tstruct audit_parent *p, *n;\n\n\tlist_for_each_entry_safe(p, n, in_list, ilist) {\n\t\tlist_del(&p->ilist);\n\t\tinotify_rm_watch(audit_ih, &p->wdata);\n\t\t/* the put matching the get in audit_do_del_rule() */\n\t\tput_inotify_watch(&p->wdata);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'Fix inotify watch removal/umount races\n\nInotify watch removals suck violently.\n\nTo kick the watch out we need (in this order) inode->inotify_mutex and\nih->mutex. That's fine if we have a hold on inode; however, for all\nother cases we need to make damn sure we don't race with umount. We can\n*NOT* just grab a reference to a watch - inotify_unmount_inodes() will\nhappily sail past it and we'll end with reference to inode potentially\noutliving its superblock.\n\nIdeally we just want to grab an active reference to superblock if we\ncan; that will make sure we won't go into inotify_umount_inodes() until\nwe are done. Cleanup is just deactivate_super().\n\nHowever, that leaves a messy case - what if we *are* racing with\numount() and active references to superblock can't be acquired anymore?\nWe can bump ->s_count, grab ->s_umount, which will almost certainly wait\nuntil the superblock is shut down and the watch in question is pining\nfor fjords. That's fine, but there is a problem - we might have hit the\nwindow between ->s_active getting to 0 / ->s_count - below S_BIAS (i.e.\nthe moment when superblock is past the point of no return and is heading\nfor shutdown) and the moment when deactivate_super() acquires\n->s_umount.\n\nWe could just do drop_super() yield() and retry, but that's rather\nantisocial and this stuff is luser-triggerable. OTOH, having grabbed\n->s_umount and having found that we'd got there first (i.e. that\n->s_root is non-NULL) we know that we won't race with\ninotify_umount_inodes().\n\nSo we could grab a reference to watch and do the rest as above, just\nwith drop_super() instead of deactivate_super(), right? Wrong. We had\nto drop ih->mutex before we could grab ->s_umount. So the watch\ncould've been gone already.\n\nThat still can be dealt with - we need to save watch->wd, do idr_find()\nand compare its result with our pointer. If they match, we either have\nthe damn thing still alive or we'd lost not one but two races at once,\nthe watch had been killed and a new one got created with the same ->wd\nat the same address. That couldn't have happened in inotify_destroy(),\nbut inotify_rm_wd() could run into that. Still, \"new one got created\"\nis not a problem - we have every right to kill it or leave it alone,\nwhatever's more convenient.\n\nSo we can use idr_find(...) == watch && watch->inode->i_sb == sb as\n\"grab it and kill it\" check. If it's been our original watch, we are\nfine, if it's a newcomer - nevermind, just pretend that we'd won the\nrace and kill the fscker anyway; we are safe since we know that its\nsuperblock won't be going away.\n\nAnd yes, this is far beyond mere \"not very pretty\"; so's the entire\nconcept of inotify to start with.\n\nSigned-off-by: Al Viro \nAcked-by: Greg KH \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void audit_put_chunk(struct audit_chunk *chunk)\n{\n\tput_inotify_watch(&chunk->watch);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'Fix inotify watch removal/umount races\n\nInotify watch removals suck violently.\n\nTo kick the watch out we need (in this order) inode->inotify_mutex and\nih->mutex. That's fine if we have a hold on inode; however, for all\nother cases we need to make damn sure we don't race with umount. We can\n*NOT* just grab a reference to a watch - inotify_unmount_inodes() will\nhappily sail past it and we'll end with reference to inode potentially\noutliving its superblock.\n\nIdeally we just want to grab an active reference to superblock if we\ncan; that will make sure we won't go into inotify_umount_inodes() until\nwe are done. Cleanup is just deactivate_super().\n\nHowever, that leaves a messy case - what if we *are* racing with\numount() and active references to superblock can't be acquired anymore?\nWe can bump ->s_count, grab ->s_umount, which will almost certainly wait\nuntil the superblock is shut down and the watch in question is pining\nfor fjords. That's fine, but there is a problem - we might have hit the\nwindow between ->s_active getting to 0 / ->s_count - below S_BIAS (i.e.\nthe moment when superblock is past the point of no return and is heading\nfor shutdown) and the moment when deactivate_super() acquires\n->s_umount.\n\nWe could just do drop_super() yield() and retry, but that's rather\nantisocial and this stuff is luser-triggerable. OTOH, having grabbed\n->s_umount and having found that we'd got there first (i.e. that\n->s_root is non-NULL) we know that we won't race with\ninotify_umount_inodes().\n\nSo we could grab a reference to watch and do the rest as above, just\nwith drop_super() instead of deactivate_super(), right? Wrong. We had\nto drop ih->mutex before we could grab ->s_umount. So the watch\ncould've been gone already.\n\nThat still can be dealt with - we need to save watch->wd, do idr_find()\nand compare its result with our pointer. If they match, we either have\nthe damn thing still alive or we'd lost not one but two races at once,\nthe watch had been killed and a new one got created with the same ->wd\nat the same address. That couldn't have happened in inotify_destroy(),\nbut inotify_rm_wd() could run into that. Still, \"new one got created\"\nis not a problem - we have every right to kill it or leave it alone,\nwhatever's more convenient.\n\nSo we can use idr_find(...) == watch && watch->inode->i_sb == sb as\n\"grab it and kill it\" check. If it's been our original watch, we are\nfine, if it's a newcomer - nevermind, just pretend that we'd won the\nrace and kill the fscker anyway; we are safe since we know that its\nsuperblock won't be going away.\n\nAnd yes, this is far beyond mere \"not very pretty\"; so's the entire\nconcept of inotify to start with.\n\nSigned-off-by: Al Viro \nAcked-by: Greg KH \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void ima_adpcm_reset2 (_AFmoduleinst *i)\n{\n\tima_adpcm_data\t*d = (ima_adpcm_data *) i->modspec;\n\tint\t\tframesPerBlock;\n\n\tframesPerBlock = d->samplesPerBlock / d->track->f.channelCount;\n\n\td->track->fpos_next_frame = d->track->fpos_first_frame +\n\t\td->blockAlign * (d->track->nextfframe / framesPerBlock);\n\td->track->frames2ignore += d->framesToIgnore;\n\n\tassert(d->track->nextfframe % framesPerBlock == 0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix decoding of multi-channel ADPCM audio files.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: long keyctl_join_session_keyring(const char __user *_name)\n{\n\tchar *name;\n\tlong ret;\n\n\t/* fetch the name from userspace */\n\tname = NULL;\n\tif (_name) {\n\t\tname = strndup_user(_name, PAGE_SIZE);\n\t\tif (IS_ERR(name)) {\n\t\t\tret = PTR_ERR(name);\n\t\t\tgoto error;\n\t\t}\n\t}\n\n\t/* join the session */\n\tret = join_session_keyring(name);\n\n error:\n\treturn ret;\n\n} /* end keyctl_join_session_keyring() */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'security: introduce missing kfree\n\nPlug this leak.\n\nAcked-by: David Howells \nCc: James Morris \nCc: \nSigned-off-by: Vegard Nossum \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int originates_from_local_legacy_unicast_socket(AvahiServer *s, const AvahiAddress *address, uint16_t port) {\n assert(s);\n assert(address);\n assert(port > 0);\n\n if (!s->config.enable_reflector)\n return 0;\n\n if (!avahi_address_is_local(s->monitor, address))\n return 0;\n\n if (address->proto == AVAHI_PROTO_INET && s->fd_legacy_unicast_ipv4 >= 0) {\n struct sockaddr_in lsa;\n socklen_t l = sizeof(lsa);\n\n if (getsockname(s->fd_legacy_unicast_ipv4, (struct sockaddr*) &lsa, &l) != 0)\n avahi_log_warn(\"getsockname(): %s\", strerror(errno));\n else\n return lsa.sin_port == port;\n\n }\n\n if (address->proto == AVAHI_PROTO_INET6 && s->fd_legacy_unicast_ipv6 >= 0) {\n struct sockaddr_in6 lsa;\n socklen_t l = sizeof(lsa);\n\n if (getsockname(s->fd_legacy_unicast_ipv6, (struct sockaddr*) &lsa, &l) != 0)\n avahi_log_warn(\"getsockname(): %s\", strerror(errno));\n else\n return lsa.sin6_port == port;\n }\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2009-0758: Reflector creates packet storm on legacy unicast traffic\n\nFixes rhbz #488314.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: struct nfs_server *nfs_clone_server(struct nfs_server *source,\n\t\t\t\t struct nfs_fh *fh,\n\t\t\t\t struct nfs_fattr *fattr)\n{\n\tstruct nfs_server *server;\n\tstruct nfs_fattr fattr_fsinfo;\n\tint error;\n\n\tdprintk(\"--> nfs_clone_server(,%llx:%llx,)\\n\",\n\t\t(unsigned long long) fattr->fsid.major,\n\t\t(unsigned long long) fattr->fsid.minor);\n\n\tserver = nfs_alloc_server();\n\tif (!server)\n\t\treturn ERR_PTR(-ENOMEM);\n\n\t/* Copy data from the source */\n\tserver->nfs_client = source->nfs_client;\n\tatomic_inc(&server->nfs_client->cl_count);\n\tnfs_server_copy_userdata(server, source);\n\n\tserver->fsid = fattr->fsid;\n\n\terror = nfs_init_server_rpcclient(server, source->client->cl_auth->au_flavor);\n\tif (error < 0)\n\t\tgoto out_free_server;\n\tif (!IS_ERR(source->client_acl))\n\t\tnfs_init_server_aclclient(server);\n\n\t/* probe the filesystem info for this server filesystem */\n\terror = nfs_probe_fsinfo(server, fh, &fattr_fsinfo);\n\tif (error < 0)\n\t\tgoto out_free_server;\n\n\tdprintk(\"Cloned FSID: %llx:%llx\\n\",\n\t\t(unsigned long long) server->fsid.major,\n\t\t(unsigned long long) server->fsid.minor);\n\n\terror = nfs_start_lockd(server);\n\tif (error < 0)\n\t\tgoto out_free_server;\n\n\tspin_lock(&nfs_client_lock);\n\tlist_add_tail(&server->client_link, &server->nfs_client->cl_superblocks);\n\tlist_add_tail(&server->master_link, &nfs_volume_list);\n\tspin_unlock(&nfs_client_lock);\n\n\tserver->mount_time = jiffies;\n\n\tdprintk(\"<-- nfs_clone_server() = %p\\n\", server);\n\treturn server;\n\nout_free_server:\n\tnfs_free_server(server);\n\tdprintk(\"<-- nfs_clone_server() = error %d\\n\", error);\n\treturn ERR_PTR(error);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'NFS: Fix an Oops in encode_lookup()\n\nIt doesn't look as if the NFS file name limit is being initialised correctly\nin the struct nfs_server. Make sure that we limit whatever is being set in\nnfs_probe_fsinfo() and nfs_init_server().\n\nAlso ensure that readdirplus and nfs4_path_walk respect our file name\nlimits.\n\nSigned-off-by: Trond Myklebust \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int tc_fill_tclass(struct sk_buff *skb, struct Qdisc *q,\n\t\t\t unsigned long cl,\n\t\t\t u32 pid, u32 seq, u16 flags, int event)\n{\n\tstruct tcmsg *tcm;\n\tstruct nlmsghdr *nlh;\n\tunsigned char *b = skb_tail_pointer(skb);\n\tstruct gnet_dump d;\n\tconst struct Qdisc_class_ops *cl_ops = q->ops->cl_ops;\n\n\tnlh = NLMSG_NEW(skb, pid, seq, event, sizeof(*tcm), flags);\n\ttcm = NLMSG_DATA(nlh);\n\ttcm->tcm_family = AF_UNSPEC;\n\ttcm->tcm_ifindex = qdisc_dev(q)->ifindex;\n\ttcm->tcm_parent = q->handle;\n\ttcm->tcm_handle = q->handle;\n\ttcm->tcm_info = 0;\n\tNLA_PUT_STRING(skb, TCA_KIND, q->ops->id);\n\tif (cl_ops->dump && cl_ops->dump(q, cl, skb, tcm) < 0)\n\t\tgoto nla_put_failure;\n\n\tif (gnet_stats_start_copy_compat(skb, TCA_STATS2, TCA_STATS, TCA_XSTATS,\n\t\t\t\t\t qdisc_root_sleeping_lock(q), &d) < 0)\n\t\tgoto nla_put_failure;\n\n\tif (cl_ops->dump_stats && cl_ops->dump_stats(q, cl, &d) < 0)\n\t\tgoto nla_put_failure;\n\n\tif (gnet_stats_finish_copy(&d) < 0)\n\t\tgoto nla_put_failure;\n\n\tnlh->nlmsg_len = skb_tail_pointer(skb) - b;\n\treturn skb->len;\n\nnlmsg_failure:\nnla_put_failure:\n\tnlmsg_trim(skb, b);\n\treturn -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-909'], 'message': 'tc: Fix unitialized kernel memory leak\n\nThree bytes of uninitialized kernel memory are currently leaked to user\n\nSigned-off-by: Eric Dumazet \nReviewed-by: Jiri Pirko \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: tca_get_fill(struct sk_buff *skb, struct tc_action *a, u32 pid, u32 seq,\n u16 flags, int event, int bind, int ref)\n{\n\tstruct tcamsg *t;\n\tstruct nlmsghdr *nlh;\n\tunsigned char *b = skb->tail;\n\tstruct rtattr *x;\n\n\tnlh = NLMSG_NEW(skb, pid, seq, event, sizeof(*t), flags);\n\n\tt = NLMSG_DATA(nlh);\n\tt->tca_family = AF_UNSPEC;\n\t\n\tx = (struct rtattr*) skb->tail;\n\tRTA_PUT(skb, TCA_ACT_TAB, 0, NULL);\n\n\tif (tcf_action_dump(skb, a, bind, ref) < 0)\n\t\tgoto rtattr_failure;\n\n\tx->rta_len = skb->tail - (u8*)x;\n\t\n\tnlh->nlmsg_len = skb->tail - b;\n\treturn skb->len;\n\nrtattr_failure:\nnlmsg_failure:\n\tskb_trim(skb, b - skb->data);\n\treturn -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': '[NETLINK]: Missing initializations in dumped data\n\nMostly missing initialization of padding fields of 1 or 2 bytes length,\ntwo instances of uninitialized nlmsgerr->msg of 16 bytes length.\n\nSigned-off-by: Patrick McHardy \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void __rta_fill(struct sk_buff *skb, int attrtype, int attrlen, const void *data)\n{\n\tstruct rtattr *rta;\n\tint size = RTA_LENGTH(attrlen);\n\n\trta = (struct rtattr*)skb_put(skb, RTA_ALIGN(size));\n\trta->rta_type = attrtype;\n\trta->rta_len = size;\n\tmemcpy(RTA_DATA(rta), data, attrlen);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': '[NETLINK]: Clear padding in netlink messages\n\nSigned-off-by: Patrick McHardy \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int main(int argc, char ** argv)\n{\n\tint c;\n\tunsigned long flags = MS_MANDLOCK;\n\tchar * orgoptions = NULL;\n\tchar * share_name = NULL;\n\tconst char * ipaddr = NULL;\n\tchar * uuid = NULL;\n\tchar * mountpoint = NULL;\n\tchar * options = NULL;\n\tchar * optionstail;\n\tchar * resolved_path = NULL;\n\tchar * temp;\n\tchar * dev_name;\n\tint rc = 0;\n\tint rsize = 0;\n\tint wsize = 0;\n\tint nomtab = 0;\n\tint uid = 0;\n\tint gid = 0;\n\tint optlen = 0;\n\tint orgoptlen = 0;\n\tsize_t options_size = 0;\n\tsize_t current_len;\n\tint retry = 0; /* set when we have to retry mount with uppercase */\n\tstruct addrinfo *addrhead = NULL, *addr;\n\tstruct utsname sysinfo;\n\tstruct mntent mountent;\n\tstruct sockaddr_in *addr4;\n\tstruct sockaddr_in6 *addr6;\n\tFILE * pmntfile;\n\n\t/* setlocale(LC_ALL, \"\");\n\tbindtextdomain(PACKAGE, LOCALEDIR);\n\ttextdomain(PACKAGE); */\n\n\tif(argc && argv)\n\t\tthisprogram = argv[0];\n\telse\n\t\tmount_cifs_usage(stderr);\n\n\tif(thisprogram == NULL)\n\t\tthisprogram = \"mount.cifs\";\n\n\tuname(&sysinfo);\n\t/* BB add workstation name and domain and pass down */\n\n/* #ifdef _GNU_SOURCE\n\tfprintf(stderr, \" node: %s machine: %s sysname %s domain %s\\n\", sysinfo.nodename,sysinfo.machine,sysinfo.sysname,sysinfo.domainname);\n#endif */\n\tif(argc > 2) {\n\t\tdev_name = argv[1];\n\t\tshare_name = strndup(argv[1], MAX_UNC_LEN);\n\t\tif (share_name == NULL) {\n\t\t\tfprintf(stderr, \"%s: %s\", argv[0], strerror(ENOMEM));\n\t\t\texit(EX_SYSERR);\n\t\t}\n\t\tmountpoint = argv[2];\n\t} else if (argc == 2) {\n\t\tif ((strcmp(argv[1], \"-V\") == 0) ||\n\t\t (strcmp(argv[1], \"--version\") == 0))\n\t\t{\n\t\t\tprint_cifs_mount_version();\n\t\t\texit(0);\n\t\t}\n\n\t\tif ((strcmp(argv[1], \"-h\") == 0) ||\n\t\t (strcmp(argv[1], \"-?\") == 0) ||\n\t\t (strcmp(argv[1], \"--help\") == 0))\n\t\t\tmount_cifs_usage(stdout);\n\n\t\tmount_cifs_usage(stderr);\n\t} else {\n\t\tmount_cifs_usage(stderr);\n\t}\n\n\n\t/* add sharename in opts string as unc= parm */\n\twhile ((c = getopt_long (argc, argv, \"afFhilL:no:O:rsSU:vVwt:\",\n\t\t\t longopts, NULL)) != -1) {\n\t\tswitch (c) {\n/* No code to do the following options yet */\n/*\tcase 'l':\n\t\tlist_with_volumelabel = 1;\n\t\tbreak;\n\tcase 'L':\n\t\tvolumelabel = optarg;\n\t\tbreak; */\n/*\tcase 'a':\t \n\t\t++mount_all;\n\t\tbreak; */\n\n\t\tcase '?':\n\t\tcase 'h':\t /* help */\n\t\t\tmount_cifs_usage(stdout);\n\t\tcase 'n':\n\t\t\t++nomtab;\n\t\t\tbreak;\n\t\tcase 'b':\n#ifdef MS_BIND\n\t\t\tflags |= MS_BIND;\n#else\n\t\t\tfprintf(stderr,\n\t\t\t\t\"option 'b' (MS_BIND) not supported\\n\");\n#endif\n\t\t\tbreak;\n\t\tcase 'm':\n#ifdef MS_MOVE\t\t \n\t\t\tflags |= MS_MOVE;\n#else\n\t\t\tfprintf(stderr,\n\t\t\t\t\"option 'm' (MS_MOVE) not supported\\n\");\n#endif\n\t\t\tbreak;\n\t\tcase 'o':\n\t\t\torgoptions = strdup(optarg);\n\t\t break;\n\t\tcase 'r': /* mount readonly */\n\t\t\tflags |= MS_RDONLY;\n\t\t\tbreak;\n\t\tcase 'U':\n\t\t\tuuid = optarg;\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\t++verboseflag;\n\t\t\tbreak;\n\t\tcase 'V':\n\t\t\tprint_cifs_mount_version();\n\t\t\texit (0);\n\t\tcase 'w':\n\t\t\tflags &= ~MS_RDONLY;\n\t\t\tbreak;\n\t\tcase 'R':\n\t\t\trsize = atoi(optarg) ;\n\t\t\tbreak;\n\t\tcase 'W':\n\t\t\twsize = atoi(optarg);\n\t\t\tbreak;\n\t\tcase '1':\n\t\t\tif (isdigit(*optarg)) {\n\t\t\t\tchar *ep;\n\n\t\t\t\tuid = strtoul(optarg, &ep, 10);\n\t\t\t\tif (*ep) {\n\t\t\t\t\tfprintf(stderr, \"bad uid value \\\"%s\\\"\\n\", optarg);\n\t\t\t\t\texit(EX_USAGE);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tstruct passwd *pw;\n\n\t\t\t\tif (!(pw = getpwnam(optarg))) {\n\t\t\t\t\tfprintf(stderr, \"bad user name \\\"%s\\\"\\n\", optarg);\n\t\t\t\t\texit(EX_USAGE);\n\t\t\t\t}\n\t\t\t\tuid = pw->pw_uid;\n\t\t\t\tendpwent();\n\t\t\t}\n\t\t\tbreak;\n\t\tcase '2':\n\t\t\tif (isdigit(*optarg)) {\n\t\t\t\tchar *ep;\n\n\t\t\t\tgid = strtoul(optarg, &ep, 10);\n\t\t\t\tif (*ep) {\n\t\t\t\t\tfprintf(stderr, \"bad gid value \\\"%s\\\"\\n\", optarg);\n\t\t\t\t\texit(EX_USAGE);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tstruct group *gr;\n\n\t\t\t\tif (!(gr = getgrnam(optarg))) {\n\t\t\t\t\tfprintf(stderr, \"bad user name \\\"%s\\\"\\n\", optarg);\n\t\t\t\t\texit(EX_USAGE);\n\t\t\t\t}\n\t\t\t\tgid = gr->gr_gid;\n\t\t\t\tendpwent();\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'u':\n\t\t\tgot_user = 1;\n\t\t\tuser_name = optarg;\n\t\t\tbreak;\n\t\tcase 'd':\n\t\t\tdomain_name = optarg; /* BB fix this - currently ignored */\n\t\t\tgot_domain = 1;\n\t\t\tbreak;\n\t\tcase 'p':\n\t\t\tif(mountpassword == NULL)\n\t\t\t\tmountpassword = (char *)calloc(MOUNT_PASSWD_SIZE+1,1);\n\t\t\tif(mountpassword) {\n\t\t\t\tgot_password = 1;\n\t\t\t\tstrlcpy(mountpassword,optarg,MOUNT_PASSWD_SIZE+1);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'S':\n\t\t\tget_password_from_file(0 /* stdin */,NULL);\n\t\t\tbreak;\n\t\tcase 't':\n\t\t\tbreak;\n\t\tcase 'f':\n\t\t\t++fakemnt;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tfprintf(stderr, \"unknown mount option %c\\n\",c);\n\t\t\tmount_cifs_usage(stderr);\n\t\t}\n\t}\n\n\tif((argc < 3) || (dev_name == NULL) || (mountpoint == NULL)) {\n\t\tmount_cifs_usage(stderr);\n\t}\n\n\t/* make sure mountpoint is legit */\n\trc = chdir(mountpoint);\n\tif (rc) {\n\t\tfprintf(stderr, \"Couldn't chdir to %s: %s\\n\", mountpoint,\n\t\t\t\tstrerror(errno));\n\t\trc = EX_USAGE;\n\t\tgoto mount_exit;\n\t}\n\n\trc = check_mountpoint(thisprogram, mountpoint);\n\tif (rc)\n\t\tgoto mount_exit;\n\n\t/* sanity check for unprivileged mounts */\n\tif (getuid()) {\n\t\trc = check_fstab(thisprogram, mountpoint, dev_name,\n\t\t\t\t &orgoptions);\n\t\tif (rc)\n\t\t\tgoto mount_exit;\n\n\t\t/* enable any default user mount flags */\n\t\tflags |= CIFS_SETUID_FLAGS;\n\t}\n\n\tif (getenv(\"PASSWD\")) {\n\t\tif(mountpassword == NULL)\n\t\t\tmountpassword = (char *)calloc(MOUNT_PASSWD_SIZE+1,1);\n\t\tif(mountpassword) {\n\t\t\tstrlcpy(mountpassword,getenv(\"PASSWD\"),MOUNT_PASSWD_SIZE+1);\n\t\t\tgot_password = 1;\n\t\t}\n\t} else if (getenv(\"PASSWD_FD\")) {\n\t\tget_password_from_file(atoi(getenv(\"PASSWD_FD\")),NULL);\n\t} else if (getenv(\"PASSWD_FILE\")) {\n\t\tget_password_from_file(0, getenv(\"PASSWD_FILE\"));\n\t}\n\n if (orgoptions && parse_options(&orgoptions, &flags)) {\n rc = EX_USAGE;\n\t\tgoto mount_exit;\n\t}\n\n\tif (getuid()) {\n#if !CIFS_LEGACY_SETUID_CHECK\n\t\tif (!(flags & (MS_USERS|MS_USER))) {\n\t\t\tfprintf(stderr, \"%s: permission denied\\n\", thisprogram);\n\t\t\trc = EX_USAGE;\n\t\t\tgoto mount_exit;\n\t\t}\n#endif /* !CIFS_LEGACY_SETUID_CHECK */\n\t\t\n\t\tif (geteuid()) {\n\t\t\tfprintf(stderr, \"%s: not installed setuid - \\\"user\\\" \"\n\t\t\t\t\t\"CIFS mounts not supported.\",\n\t\t\t\t\tthisprogram);\n\t\t\trc = EX_FAIL;\n\t\t\tgoto mount_exit;\n\t\t}\n\t}\n\n\tflags &= ~(MS_USERS|MS_USER);\n\n\taddrhead = addr = parse_server(&share_name);\n\tif((addrhead == NULL) && (got_ip == 0)) {\n\t\tfprintf(stderr, \"No ip address specified and hostname not found\\n\");\n\t\trc = EX_USAGE;\n\t\tgoto mount_exit;\n\t}\n\t\n\t/* BB save off path and pop after mount returns? */\n\tresolved_path = (char *)malloc(PATH_MAX+1);\n\tif (!resolved_path) {\n\t\tfprintf(stderr, \"Unable to allocate memory.\\n\");\n\t\trc = EX_SYSERR;\n\t\tgoto mount_exit;\n\t}\n\n\t/* Note that if we can not canonicalize the name, we get\n\t another chance to see if it is valid when we chdir to it */\n\tif(!realpath(\".\", resolved_path)) {\n\t\tfprintf(stderr, \"Unable to resolve %s to canonical path: %s\\n\",\n\t\t\t\tmountpoint, strerror(errno));\n\t\trc = EX_SYSERR;\n\t\tgoto mount_exit;\n\t}\n\n\tmountpoint = resolved_path; \n\n\tif(got_user == 0) {\n\t\t/* Note that the password will not be retrieved from the\n\t\t USER env variable (ie user%password form) as there is\n\t\t already a PASSWD environment varaible */\n\t\tif (getenv(\"USER\"))\n\t\t\tuser_name = strdup(getenv(\"USER\"));\n\t\tif (user_name == NULL)\n\t\t\tuser_name = getusername();\n\t\tgot_user = 1;\n\t}\n \n\tif(got_password == 0) {\n\t\tchar *tmp_pass = getpass(\"Password: \"); /* BB obsolete sys call but\n\t\t\t\t\t\t\t no good replacement yet. */\n\t\tmountpassword = (char *)calloc(MOUNT_PASSWD_SIZE+1,1);\n\t\tif (!tmp_pass || !mountpassword) {\n\t\t\tfprintf(stderr, \"Password not entered, exiting\\n\");\n\t\t\texit(EX_USAGE);\n\t\t}\n\t\tstrlcpy(mountpassword, tmp_pass, MOUNT_PASSWD_SIZE+1);\n\t\tgot_password = 1;\n\t}\n\t/* FIXME launch daemon (handles dfs name resolution and credential change) \n\t remember to clear parms and overwrite password field before launching */\n\tif(orgoptions) {\n\t\toptlen = strlen(orgoptions);\n\t\torgoptlen = optlen;\n\t} else\n\t\toptlen = 0;\n\tif(share_name)\n\t\toptlen += strlen(share_name) + 4;\n\telse {\n\t\tfprintf(stderr, \"No server share name specified\\n\");\n\t\tfprintf(stderr, \"\\nMounting the DFS root for server not implemented yet\\n\");\n exit(EX_USAGE);\n\t}\n\tif(user_name)\n\t\toptlen += strlen(user_name) + 6;\n\toptlen += MAX_ADDRESS_LEN + 4;\n\tif(mountpassword)\n\t\toptlen += strlen(mountpassword) + 6;\nmount_retry:\n\tSAFE_FREE(options);\n\toptions_size = optlen + 10 + DOMAIN_SIZE;\n\toptions = (char *)malloc(options_size /* space for commas in password */ + 8 /* space for domain= , domain name itself was counted as part of the length username string above */);\n\n\tif(options == NULL) {\n\t\tfprintf(stderr, \"Could not allocate memory for mount options\\n\");\n\t\texit(EX_SYSERR);\n\t}\n\n\tstrlcpy(options, \"unc=\", options_size);\n\tstrlcat(options,share_name,options_size);\n\t/* scan backwards and reverse direction of slash */\n\ttemp = strrchr(options, '/');\n\tif(temp > options + 6)\n\t\t*temp = '\\\\';\n\tif(user_name) {\n\t\t/* check for syntax like user=domain\\user */\n\t\tif(got_domain == 0)\n\t\t\tdomain_name = check_for_domain(&user_name);\n\t\tstrlcat(options,\",user=\",options_size);\n\t\tstrlcat(options,user_name,options_size);\n\t}\n\tif(retry == 0) {\n\t\tif(domain_name) {\n\t\t\t/* extra length accounted for in option string above */\n\t\t\tstrlcat(options,\",domain=\",options_size);\n\t\t\tstrlcat(options,domain_name,options_size);\n\t\t}\n\t}\n\n\tstrlcat(options,\",ver=\",options_size);\n\tstrlcat(options,MOUNT_CIFS_VERSION_MAJOR,options_size);\n\n\tif(orgoptions) {\n\t\tstrlcat(options,\",\",options_size);\n\t\tstrlcat(options,orgoptions,options_size);\n\t}\n\tif(prefixpath) {\n\t\tstrlcat(options,\",prefixpath=\",options_size);\n\t\tstrlcat(options,prefixpath,options_size); /* no need to cat the / */\n\t}\n\n\t/* convert all '\\\\' to '/' in share portion so that /proc/mounts looks pretty */\n\treplace_char(dev_name, '\\\\', '/', strlen(share_name));\n\n\tif (!got_ip && addr) {\n\t\tstrlcat(options, \",ip=\", options_size);\n\t\tcurrent_len = strnlen(options, options_size);\n\t\toptionstail = options + current_len;\n\t\tswitch (addr->ai_addr->sa_family) {\n\t\tcase AF_INET6:\n\t\t\taddr6 = (struct sockaddr_in6 *) addr->ai_addr;\n\t\t\tipaddr = inet_ntop(AF_INET6, &addr6->sin6_addr, optionstail,\n\t\t\t\t\t options_size - current_len);\n\t\t\tbreak;\n\t\tcase AF_INET:\n\t\t\taddr4 = (struct sockaddr_in *) addr->ai_addr;\n\t\t\tipaddr = inet_ntop(AF_INET, &addr4->sin_addr, optionstail,\n\t\t\t\t\t options_size - current_len);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tipaddr = NULL;\n\t\t}\n\n\t\t/* if the address looks bogus, try the next one */\n\t\tif (!ipaddr) {\n\t\t\taddr = addr->ai_next;\n\t\t\tif (addr)\n\t\t\t\tgoto mount_retry;\n\t\t\trc = EX_SYSERR;\n\t\t\tgoto mount_exit;\n\t\t}\n\t}\n\n\tif (addr->ai_addr->sa_family == AF_INET6 && addr6->sin6_scope_id) {\n\t\tstrlcat(options, \"%\", options_size);\n\t\tcurrent_len = strnlen(options, options_size);\n\t\toptionstail = options + current_len;\n\t\tsnprintf(optionstail, options_size - current_len, \"%u\",\n\t\t\t addr6->sin6_scope_id);\n\t}\n\n\tif(verboseflag)\n\t\tfprintf(stderr, \"\\nmount.cifs kernel mount options: %s\", options);\n\n\tif (mountpassword) {\n\t\t/*\n\t\t * Commas have to be doubled, or else they will\n\t\t * look like the parameter separator\n\t\t */\n\t\tif(retry == 0)\n\t\t\tcheck_for_comma(&mountpassword);\n\t\tstrlcat(options,\",pass=\",options_size);\n\t\tstrlcat(options,mountpassword,options_size);\n\t\tif (verboseflag)\n\t\t\tfprintf(stderr, \",pass=********\");\n\t}\n\n\tif (verboseflag)\n\t\tfprintf(stderr, \"\\n\");\n\n\trc = check_mtab(thisprogram, dev_name, mountpoint);\n\tif (rc)\n\t\tgoto mount_exit;\n\n\tif (!fakemnt && mount(dev_name, \".\", cifs_fstype, flags, options)) {\n\t\tswitch (errno) {\n\t\tcase ECONNREFUSED:\n\t\tcase EHOSTUNREACH:\n\t\t\tif (addr) {\n\t\t\t\taddr = addr->ai_next;\n\t\t\t\tif (addr)\n\t\t\t\t\tgoto mount_retry;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase ENODEV:\n\t\t\tfprintf(stderr, \"mount error: cifs filesystem not supported by the system\\n\");\n\t\t\tbreak;\n\t\tcase ENXIO:\n\t\t\tif(retry == 0) {\n\t\t\t\tretry = 1;\n\t\t\t\tif (uppercase_string(dev_name) &&\n\t\t\t\t uppercase_string(share_name) &&\n\t\t\t\t uppercase_string(prefixpath)) {\n\t\t\t\t\tfprintf(stderr, \"retrying with upper case share name\\n\");\n\t\t\t\t\tgoto mount_retry;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfprintf(stderr, \"mount error(%d): %s\\n\", errno, strerror(errno));\n\t\tfprintf(stderr, \"Refer to the mount.cifs(8) manual page (e.g. man \"\n\t\t \"mount.cifs)\\n\");\n\t\trc = EX_FAIL;\n\t\tgoto mount_exit;\n\t}\n\n\tif (nomtab)\n\t\tgoto mount_exit;\n\tatexit(unlock_mtab);\n\trc = lock_mtab();\n\tif (rc) {\n\t\tfprintf(stderr, \"cannot lock mtab\");\n\t\tgoto mount_exit;\n\t}\n\tpmntfile = setmntent(MOUNTED, \"a+\");\n\tif (!pmntfile) {\n\t\tfprintf(stderr, \"could not update mount table\\n\");\n\t\tunlock_mtab();\n\t\trc = EX_FILEIO;\n\t\tgoto mount_exit;\n\t}\n\tmountent.mnt_fsname = dev_name;\n\tmountent.mnt_dir = mountpoint;\n\tmountent.mnt_type = (char *)(void *)cifs_fstype;\n\tmountent.mnt_opts = (char *)malloc(220);\n\tif(mountent.mnt_opts) {\n\t\tchar * mount_user = getusername();\n\t\tmemset(mountent.mnt_opts,0,200);\n\t\tif(flags & MS_RDONLY)\n\t\t\tstrlcat(mountent.mnt_opts,\"ro\",220);\n\t\telse\n\t\t\tstrlcat(mountent.mnt_opts,\"rw\",220);\n\t\tif(flags & MS_MANDLOCK)\n\t\t\tstrlcat(mountent.mnt_opts,\",mand\",220);\n\t\tif(flags & MS_NOEXEC)\n\t\t\tstrlcat(mountent.mnt_opts,\",noexec\",220);\n\t\tif(flags & MS_NOSUID)\n\t\t\tstrlcat(mountent.mnt_opts,\",nosuid\",220);\n\t\tif(flags & MS_NODEV)\n\t\t\tstrlcat(mountent.mnt_opts,\",nodev\",220);\n\t\tif(flags & MS_SYNCHRONOUS)\n\t\t\tstrlcat(mountent.mnt_opts,\",sync\",220);\n\t\tif(mount_user) {\n\t\t\tif(getuid() != 0) {\n\t\t\t\tstrlcat(mountent.mnt_opts,\n\t\t\t\t\t\",user=\", 220);\n\t\t\t\tstrlcat(mountent.mnt_opts,\n\t\t\t\t\tmount_user, 220);\n\t\t\t}\n\t\t}\n\t}\n\tmountent.mnt_freq = 0;\n\tmountent.mnt_passno = 0;\n\trc = addmntent(pmntfile,&mountent);\n\tendmntent(pmntfile);\n\tunlock_mtab();\n\tSAFE_FREE(mountent.mnt_opts);\n\tif (rc)\n\t\trc = EX_FILEIO;\nmount_exit:\n\tif(mountpassword) {\n\t\tint len = strlen(mountpassword);\n\t\tmemset(mountpassword,0,len);\n\t\tSAFE_FREE(mountpassword);\n\t}\n\n\tif (addrhead)\n\t\tfreeaddrinfo(addrhead);\n\tSAFE_FREE(options);\n\tSAFE_FREE(orgoptions);\n\tSAFE_FREE(resolved_path);\n\tSAFE_FREE(share_name);\n\texit(rc);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59'], 'message': 'mount.cifs: don't allow it to be run as setuid root program\n\nmount.cifs has been the subject of several \"security\" fire drills due to\ndistributions installing it as a setuid root program. This program has\nnot been properly audited for security and the Samba team highly\nrecommends that it not be installed as a setuid root program at this\ntime.\n\nTo make that abundantly clear, this patch forcibly disables the ability\nfor mount.cifs to run as a setuid root program. People are welcome to\ntrivially patch this out, but they do so at their own peril.\n\nA security audit and redesign of this program is in progress and we hope\nthat we'll be able to remove this in the near future.\n\nSigned-off-by: Jeff Layton '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int do_insn_fetch(struct x86_emulate_ctxt *ctxt,\n\t\t\t struct x86_emulate_ops *ops,\n\t\t\t unsigned long eip, void *dest, unsigned size)\n{\n\tint rc = 0;\n\n\teip += ctxt->cs_base;\n\twhile (size--) {\n\t\trc = do_fetch_insn_byte(ctxt, ops, eip++, dest++);\n\t\tif (rc)\n\t\t\treturn rc;\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'KVM: x86 emulator: limit instructions to 15 bytes\n\nWhile we are never normally passed an instruction that exceeds 15 bytes,\nsmp games can cause us to attempt to interpret one, which will cause\nlarge latencies in non-preempt hosts.\n\nCc: stable@kernel.org\nSigned-off-by: Avi Kivity '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: nma_gconf_connection_new (GConfClient *client, const char *conf_dir)\n{\n\tNMConnection *connection;\n\tNMAGConfConnection *gconf_connection;\n\n\tg_return_val_if_fail (GCONF_IS_CLIENT (client), NULL);\n\tg_return_val_if_fail (conf_dir != NULL, NULL);\n\n\t/* retrieve GConf data */\n\tconnection = nm_gconf_read_connection (client, conf_dir);\n\tif (connection) {\n\t\tgconf_connection = nma_gconf_connection_new_from_connection (client, conf_dir, connection);\n\t\tg_object_unref (connection);\n\t} else {\n\t\tnm_warning (\"No connection read from GConf at %s.\", conf_dir);\n\t\tgconf_connection = NULL;\n\t}\n\t\n\treturn gconf_connection;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'core: fix CA cert mishandling after cert file deletion (deb #560067) (rh #546793)\n\nIf a connection was created with a CA certificate, but the user later\nmoved or deleted that CA certificate, the applet would simply provide the\nconnection to NetworkManager without any CA certificate. This could cause\nNM to connect to the original network (or a network spoofing the original\nnetwork) without verifying the identity of the network as the user\nexpects.\n\nIn the future we can/should do better here by (1) alerting the user that\nsome connection is now no longer complete by flagging it in the connection\neditor or notifying the user somehow, and (2) by using a freaking' cert\nstore already (not that Linux has one yet).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: constructor (GType type,\n\t\t guint n_construct_params,\n\t\t GObjectConstructParam *construct_params)\n{\n\tGObject *object;\n\tNMAGConfConnectionPrivate *priv;\n\tNMConnection *connection;\n\tGError *error = NULL;\n\n\tobject = G_OBJECT_CLASS (nma_gconf_connection_parent_class)->constructor (type, n_construct_params, construct_params);\n\n\tif (!object)\n\t\treturn NULL;\n\n\tpriv = NMA_GCONF_CONNECTION_GET_PRIVATE (object);\n\n\tif (!priv->client) {\n\t\tnm_warning (\"GConfClient not provided.\");\n\t\tgoto err;\n\t}\n\n\tif (!priv->dir) {\n\t\tnm_warning (\"GConf directory not provided.\");\n\t\tgoto err;\n\t}\n\n\tconnection = nm_exported_connection_get_connection (NM_EXPORTED_CONNECTION (object));\n\n\tutils_fill_connection_certs (connection);\n\tif (!nm_connection_verify (connection, &error)) {\n\t\tutils_clear_filled_connection_certs (connection);\n\t\tg_warning (\"Invalid connection: '%s' / '%s' invalid: %d\",\n\t\t g_type_name (nm_connection_lookup_setting_type_by_quark (error->domain)),\n\t\t error->message, error->code);\n\t\tg_error_free (error);\n\t\tgoto err;\n\t}\n\tutils_clear_filled_connection_certs (connection);\n\n\tfill_vpn_user_name (connection);\n\n\treturn object;\n\n err:\n\tg_object_unref (object);\n\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'core: fix CA cert mishandling after cert file deletion (deb #560067) (rh #546793)\n\nIf a connection was created with a CA certificate, but the user later\nmoved or deleted that CA certificate, the applet would simply provide the\nconnection to NetworkManager without any CA certificate. This could cause\nNM to connect to the original network (or a network spoofing the original\nnetwork) without verifying the identity of the network as the user\nexpects.\n\nIn the future we can/should do better here by (1) alerting the user that\nsome connection is now no longer complete by flagging it in the connection\neditor or notifying the user somehow, and (2) by using a freaking' cert\nstore already (not that Linux has one yet).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int usb_host_handle_control(USBHostDevice *s, USBPacket *p)\n{\n struct usbdevfs_urb *urb;\n AsyncURB *aurb;\n int ret, value, index;\n\n /* \n * Process certain standard device requests.\n * These are infrequent and are processed synchronously.\n */\n value = le16_to_cpu(s->ctrl.req.wValue);\n index = le16_to_cpu(s->ctrl.req.wIndex);\n\n dprintf(\"husb: ctrl type 0x%x req 0x%x val 0x%x index %u len %u\\n\",\n s->ctrl.req.bRequestType, s->ctrl.req.bRequest, value, index, \n s->ctrl.len);\n\n if (s->ctrl.req.bRequestType == 0) {\n switch (s->ctrl.req.bRequest) {\n case USB_REQ_SET_ADDRESS:\n return usb_host_set_address(s, value);\n\n case USB_REQ_SET_CONFIGURATION:\n return usb_host_set_config(s, value & 0xff);\n }\n }\n\n if (s->ctrl.req.bRequestType == 1 &&\n s->ctrl.req.bRequest == USB_REQ_SET_INTERFACE)\n return usb_host_set_interface(s, index, value);\n\n /* The rest are asynchronous */\n\n aurb = async_alloc();\n aurb->hdev = s;\n aurb->packet = p;\n\n /* \n * Setup ctrl transfer.\n *\n * s->ctrl is layed out such that data buffer immediately follows\n * 'req' struct which is exactly what usbdevfs expects.\n */ \n urb = &aurb->urb;\n\n urb->type = USBDEVFS_URB_TYPE_CONTROL;\n urb->endpoint = p->devep;\n\n urb->buffer = &s->ctrl.req;\n urb->buffer_length = 8 + s->ctrl.len;\n\n urb->usercontext = s;\n\n ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);\n\n dprintf(\"husb: submit ctrl. len %u aurb %p\\n\", urb->buffer_length, aurb);\n\n if (ret < 0) {\n dprintf(\"husb: submit failed. errno %d\\n\", errno);\n async_free(aurb);\n\n switch(errno) {\n case ETIMEDOUT:\n return USB_RET_NAK;\n case EPIPE:\n default:\n return USB_RET_STALL;\n }\n }\n\n usb_defer_packet(p, async_cancel, aurb);\n return USB_RET_ASYNC;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'usb-linux.c: fix buffer overflow\n\nIn usb-linux.c:usb_host_handle_control, we pass a 1024-byte buffer and\nlength to the kernel. However, the length was provided by the caller\nof dev->handle_packet, and is not checked, so the kernel might provide\ntoo much data and overflow our buffer.\n\nFor example, hw/usb-uhci.c could set the length to 2047.\nhw/usb-ohci.c looks like it might go up to 4096 or 8192.\n\nThis causes a qemu crash, as reported here:\n http://www.mail-archive.com/kvm@vger.kernel.org/msg18447.html\n\nThis patch increases the usb-linux.c buffer size to 2048 to fix the\nspecific device reported, and adds a check to avoid the overflow in\nany case.\n\nSigned-off-by: Jim Paris \nSigned-off-by: Anthony Liguori '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static NTSTATUS smb_set_file_unix_link(connection_struct *conn,\n\t\t\t\t struct smb_request *req,\n\t\t\t\t const char *pdata,\n\t\t\t\t int total_data,\n\t\t\t\t const struct smb_filename *smb_fname)\n{\n\tchar *link_target = NULL;\n\tconst char *newname = smb_fname->base_name;\n\tNTSTATUS status = NT_STATUS_OK;\n\tTALLOC_CTX *ctx = talloc_tos();\n\n\t/* Set a symbolic link. */\n\t/* Don't allow this if follow links is false. */\n\n\tif (total_data == 0) {\n\t\treturn NT_STATUS_INVALID_PARAMETER;\n\t}\n\n\tif (!lp_symlinks(SNUM(conn))) {\n\t\treturn NT_STATUS_ACCESS_DENIED;\n\t}\n\n\tsrvstr_pull_talloc(ctx, pdata, req->flags2, &link_target, pdata,\n\t\t total_data, STR_TERMINATE);\n\n\tif (!link_target) {\n\t\treturn NT_STATUS_INVALID_PARAMETER;\n\t}\n\n\t/* !widelinks forces the target path to be within the share. */\n\t/* This means we can interpret the target as a pathname. */\n\tif (!lp_widelinks(SNUM(conn))) {\n\t\tchar *rel_name = NULL;\n\t\tchar *last_dirp = NULL;\n\n\t\tif (*link_target == '/') {\n\t\t\t/* No absolute paths allowed. */\n\t\t\treturn NT_STATUS_ACCESS_DENIED;\n\t\t}\n\t\trel_name = talloc_strdup(ctx,newname);\n\t\tif (!rel_name) {\n\t\t\treturn NT_STATUS_NO_MEMORY;\n\t\t}\n\t\tlast_dirp = strrchr_m(rel_name, '/');\n\t\tif (last_dirp) {\n\t\t\tlast_dirp[1] = '\\0';\n\t\t} else {\n\t\t\trel_name = talloc_strdup(ctx,\"./\");\n\t\t\tif (!rel_name) {\n\t\t\t\treturn NT_STATUS_NO_MEMORY;\n\t\t\t}\n\t\t}\n\t\trel_name = talloc_asprintf_append(rel_name,\n\t\t\t\t\"%s\",\n\t\t\t\tlink_target);\n\t\tif (!rel_name) {\n\t\t\treturn NT_STATUS_NO_MEMORY;\n\t\t}\n\n\t\tstatus = check_name(conn, rel_name);\n\t\tif (!NT_STATUS_IS_OK(status)) {\n\t\t\treturn status;\n\t\t}\n\t}\n\n\tDEBUG(10,(\"smb_set_file_unix_link: SMB_SET_FILE_UNIX_LINK doing symlink %s -> %s\\n\",\n\t\t\tnewname, link_target ));\n\n\tif (SMB_VFS_SYMLINK(conn,link_target,newname) != 0) {\n\t\treturn map_nt_error_from_unix(errno);\n\t}\n\n\treturn NT_STATUS_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-22'], 'message': 'Fix bug 7104 - \"wide links\" and \"unix extensions\" are incompatible.\n\nChange parameter \"wide links\" to default to \"no\".\nEnsure \"wide links = no\" if \"unix extensions = yes\" on a share.\nFix man pages to refect this.\n\nRemove \"within share\" checks for a UNIX symlink set - even if\nwidelinks = no. The server will not follow that link anyway.\n\nCorrect DEBUG message in check_reduced_name() to add missing \"\\n\"\nso it's really clear when a path is being denied as it's outside\nthe enclosing share path.\n\nJeremy.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: long do_io_submit(aio_context_t ctx_id, long nr,\n\t\t struct iocb __user *__user *iocbpp, bool compat)\n{\n\tstruct kioctx *ctx;\n\tlong ret = 0;\n\tint i;\n\tstruct hlist_head batch_hash[AIO_BATCH_HASH_SIZE] = { { 0, }, };\n\n\tif (unlikely(nr < 0))\n\t\treturn -EINVAL;\n\n\tif (unlikely(!access_ok(VERIFY_READ, iocbpp, (nr*sizeof(*iocbpp)))))\n\t\treturn -EFAULT;\n\n\tctx = lookup_ioctx(ctx_id);\n\tif (unlikely(!ctx)) {\n\t\tpr_debug(\"EINVAL: io_submit: invalid context id\\n\");\n\t\treturn -EINVAL;\n\t}\n\n\t/*\n\t * AKPM: should this return a partial result if some of the IOs were\n\t * successfully submitted?\n\t */\n\tfor (i=0; i \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'aio: check for multiplication overflow in do_io_submit\n\nTavis Ormandy pointed out that do_io_submit does not do proper bounds\nchecking on the passed-in iocb array:\n\n\u00a0 \u00a0 \u00a0 \u00a0if (unlikely(nr < 0))\n\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0return -EINVAL;\n\n\u00a0 \u00a0 \u00a0 \u00a0if (unlikely(!access_ok(VERIFY_READ, iocbpp, (nr*sizeof(iocbpp)))))\n\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0return -EFAULT; \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0^^^^^^^^^^^^^^^^^^\n\nThe attached patch checks for overflow, and if it is detected, the\nnumber of iocbs submitted is scaled down to a number that will fit in\nthe long. \u00a0This is an ok thing to do, as sys_io_submit is documented as\nreturning the number of iocbs submitted, so callers should handle a\nreturn value of less than the 'nr' argument passed in.\n\nReported-by: Tavis Ormandy \nSigned-off-by: Jeff Moyer \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void vmx_save_host_state(struct kvm_vcpu *vcpu)\n{\n\tstruct vcpu_vmx *vmx = to_vmx(vcpu);\n\tint i;\n\n\tif (vmx->host_state.loaded)\n\t\treturn;\n\n\tvmx->host_state.loaded = 1;\n\t/*\n\t * Set host fs and gs selectors. Unfortunately, 22.2.3 does not\n\t * allow segment selectors with cpl > 0 or ti == 1.\n\t */\n\tvmx->host_state.ldt_sel = kvm_read_ldt();\n\tvmx->host_state.gs_ldt_reload_needed = vmx->host_state.ldt_sel;\n\tvmx->host_state.fs_sel = kvm_read_fs();\n\tif (!(vmx->host_state.fs_sel & 7)) {\n\t\tvmcs_write16(HOST_FS_SELECTOR, vmx->host_state.fs_sel);\n\t\tvmx->host_state.fs_reload_needed = 0;\n\t} else {\n\t\tvmcs_write16(HOST_FS_SELECTOR, 0);\n\t\tvmx->host_state.fs_reload_needed = 1;\n\t}\n\tvmx->host_state.gs_sel = kvm_read_gs();\n\tif (!(vmx->host_state.gs_sel & 7))\n\t\tvmcs_write16(HOST_GS_SELECTOR, vmx->host_state.gs_sel);\n\telse {\n\t\tvmcs_write16(HOST_GS_SELECTOR, 0);\n\t\tvmx->host_state.gs_ldt_reload_needed = 1;\n\t}\n\n#ifdef CONFIG_X86_64\n\tvmcs_writel(HOST_FS_BASE, read_msr(MSR_FS_BASE));\n\tvmcs_writel(HOST_GS_BASE, read_msr(MSR_GS_BASE));\n#else\n\tvmcs_writel(HOST_FS_BASE, segment_base(vmx->host_state.fs_sel));\n\tvmcs_writel(HOST_GS_BASE, segment_base(vmx->host_state.gs_sel));\n#endif\n\n#ifdef CONFIG_X86_64\n\tif (is_long_mode(&vmx->vcpu)) {\n\t\trdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);\n\t\twrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);\n\t}\n#endif\n\tfor (i = 0; i < vmx->save_nmsrs; ++i)\n\t\tkvm_set_shared_msr(vmx->guest_msrs[i].index,\n\t\t\t\t vmx->guest_msrs[i].data,\n\t\t\t\t vmx->guest_msrs[i].mask);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': 'KVM: Fix fs/gs reload oops with invalid ldt\n\nkvm reloads the host's fs and gs blindly, however the underlying segment\ndescriptors may be invalid due to the user modifying the ldt after loading\nthem.\n\nFix by using the safe accessors (loadsegment() and load_gs_index()) instead\nof home grown unsafe versions.\n\nThis is CVE-2010-3698.\n\nKVM-Stable-Tag.\nSigned-off-by: Avi Kivity \nSigned-off-by: Marcelo Tosatti '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int packet_getname_spkt(struct socket *sock, struct sockaddr *uaddr,\n\t\t\t int *uaddr_len, int peer)\n{\n\tstruct net_device *dev;\n\tstruct sock *sk\t= sock->sk;\n\n\tif (peer)\n\t\treturn -EOPNOTSUPP;\n\n\tuaddr->sa_family = AF_PACKET;\n\trcu_read_lock();\n\tdev = dev_get_by_index_rcu(sock_net(sk), pkt_sk(sk)->ifindex);\n\tif (dev)\n\t\tstrlcpy(uaddr->sa_data, dev->name, 15);\n\telse\n\t\tmemset(uaddr->sa_data, 0, 14);\n\trcu_read_unlock();\n\t*uaddr_len = sizeof(*uaddr);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-909'], 'message': 'net: packet: fix information leak to userland\n\npacket_getname_spkt() doesn't initialize all members of sa_data field of\nsockaddr struct if strlen(dev->name) < 13. This structure is then copied\nto userland. It leads to leaking of contents of kernel stack memory.\nWe have to fully fill sa_data with strncpy() instead of strlcpy().\n\nThe same with packet_getname(): it doesn't initialize sll_pkttype field of\nsockaddr_ll. Set it to zero.\n\nSigned-off-by: Vasiliy Kulikov \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)\n{\n\tstruct udp_sock *up = udp_sk(sk);\n\tint rc;\n\tint is_udplite = IS_UDPLITE(sk);\n\n\t/*\n\t *\tCharge it to the socket, dropping if the queue is full.\n\t */\n\tif (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb))\n\t\tgoto drop;\n\tnf_reset(skb);\n\n\tif (up->encap_type) {\n\t\t/*\n\t\t * This is an encapsulation socket so pass the skb to\n\t\t * the socket's udp_encap_rcv() hook. Otherwise, just\n\t\t * fall through and pass this up the UDP socket.\n\t\t * up->encap_rcv() returns the following value:\n\t\t * =0 if skb was successfully passed to the encap\n\t\t * handler or was discarded by it.\n\t\t * >0 if skb should be passed on to UDP.\n\t\t * <0 if skb should be resubmitted as proto -N\n\t\t */\n\n\t\t/* if we're overly short, let UDP handle it */\n\t\tif (skb->len > sizeof(struct udphdr) &&\n\t\t up->encap_rcv != NULL) {\n\t\t\tint ret;\n\n\t\t\tret = (*up->encap_rcv)(sk, skb);\n\t\t\tif (ret <= 0) {\n\t\t\t\tUDP_INC_STATS_BH(sock_net(sk),\n\t\t\t\t\t\t UDP_MIB_INDATAGRAMS,\n\t\t\t\t\t\t is_udplite);\n\t\t\t\treturn -ret;\n\t\t\t}\n\t\t}\n\n\t\t/* FALLTHROUGH -- it's a UDP Packet */\n\t}\n\n\t/*\n\t * \tUDP-Lite specific tests, ignored on UDP sockets\n\t */\n\tif ((is_udplite & UDPLITE_RECV_CC) && UDP_SKB_CB(skb)->partial_cov) {\n\n\t\t/*\n\t\t * MIB statistics other than incrementing the error count are\n\t\t * disabled for the following two types of errors: these depend\n\t\t * on the application settings, not on the functioning of the\n\t\t * protocol stack as such.\n\t\t *\n\t\t * RFC 3828 here recommends (sec 3.3): \"There should also be a\n\t\t * way ... to ... at least let the receiving application block\n\t\t * delivery of packets with coverage values less than a value\n\t\t * provided by the application.\"\n\t\t */\n\t\tif (up->pcrlen == 0) { /* full coverage was set */\n\t\t\tLIMIT_NETDEBUG(KERN_WARNING \"UDPLITE: partial coverage \"\n\t\t\t\t\"%d while full coverage %d requested\\n\",\n\t\t\t\tUDP_SKB_CB(skb)->cscov, skb->len);\n\t\t\tgoto drop;\n\t\t}\n\t\t/* The next case involves violating the min. coverage requested\n\t\t * by the receiver. This is subtle: if receiver wants x and x is\n\t\t * greater than the buffersize/MTU then receiver will complain\n\t\t * that it wants x while sender emits packets of smaller size y.\n\t\t * Therefore the above ...()->partial_cov statement is essential.\n\t\t */\n\t\tif (UDP_SKB_CB(skb)->cscov < up->pcrlen) {\n\t\t\tLIMIT_NETDEBUG(KERN_WARNING\n\t\t\t\t\"UDPLITE: coverage %d too small, need min %d\\n\",\n\t\t\t\tUDP_SKB_CB(skb)->cscov, up->pcrlen);\n\t\t\tgoto drop;\n\t\t}\n\t}\n\n\tif (sk->sk_filter) {\n\t\tif (udp_lib_checksum_complete(skb))\n\t\t\tgoto drop;\n\t}\n\n\trc = 0;\n\n\tbh_lock_sock(sk);\n\tif (!sock_owned_by_user(sk))\n\t\trc = __udp_queue_rcv_skb(sk, skb);\n\telse if (sk_add_backlog(sk, skb)) {\n\t\tbh_unlock_sock(sk);\n\t\tgoto drop;\n\t}\n\tbh_unlock_sock(sk);\n\n\treturn rc;\n\ndrop:\n\tUDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS, is_udplite);\n\tatomic_inc(&sk->sk_drops);\n\tkfree_skb(skb);\n\treturn -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': 'net: sk_add_backlog() take rmem_alloc into account\n\nCurrent socket backlog limit is not enough to really stop DDOS attacks,\nbecause user thread spend many time to process a full backlog each\nround, and user might crazy spin on socket lock.\n\nWe should add backlog size and receive_queue size (aka rmem_alloc) to\npace writers, and let user run without being slow down too much.\n\nIntroduce a sk_rcvqueues_full() helper, to avoid taking socket lock in\nstress situations.\n\nUnder huge stress from a multiqueue/RPS enabled NIC, a single flow udp\nreceiver can now process ~200.000 pps (instead of ~100 pps before the\npatch) on a 8 core machine.\n\nSigned-off-by: Eric Dumazet \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: \nstatic int\nxmlXPathCompOpEvalPositionalPredicate(xmlXPathParserContextPtr ctxt,\n\t\t\t\t xmlXPathStepOpPtr op,\n\t\t\t\t xmlNodeSetPtr set,\n\t\t\t\t int contextSize,\n\t\t\t\t int minPos,\n\t\t\t\t int maxPos,\n\t\t\t\t int hasNsNodes)\n{\n if (op->ch1 != -1) {\n\txmlXPathCompExprPtr comp = ctxt->comp;\n\tif (comp->steps[op->ch1].op != XPATH_OP_PREDICATE) {\n\t /*\n\t * TODO: raise an internal error.\n\t */\n\t}\n\tcontextSize = xmlXPathCompOpEvalPredicate(ctxt,\n\t &comp->steps[op->ch1], set, contextSize, hasNsNodes);\n\tCHECK_ERROR0;\n\tif (contextSize <= 0)\n\t return(0);\n }\n /*\n * Check if the node set contains a sufficient number of nodes for\n * the requested range.\n */\n if (contextSize < minPos) {\n\txmlXPathNodeSetClear(set, hasNsNodes);\n\treturn(0);\n }\n if (op->ch2 == -1) {\n\t/*\n\t* TODO: Can this ever happen?\n\t*/\n\treturn (contextSize);\n } else {\n\txmlDocPtr oldContextDoc;\n\tint i, pos = 0, newContextSize = 0, contextPos = 0, res;\n\txmlXPathStepOpPtr exprOp;\n\txmlXPathObjectPtr contextObj = NULL, exprRes = NULL;\n\txmlNodePtr oldContextNode, contextNode = NULL;\n\txmlXPathContextPtr xpctxt = ctxt->context;\n\n#ifdef LIBXML_XPTR_ENABLED\n\t /*\n\t * URGENT TODO: Check the following:\n\t * We don't expect location sets if evaluating prediates, right?\n\t * Only filters should expect location sets, right?\n\t*/\n#endif /* LIBXML_XPTR_ENABLED */\n\n\t/*\n\t* Save old context.\n\t*/\n\toldContextNode = xpctxt->node;\n\toldContextDoc = xpctxt->doc;\n\t/*\n\t* Get the expression of this predicate.\n\t*/\n\texprOp = &ctxt->comp->steps[op->ch2];\n\tfor (i = 0; i < set->nodeNr; i++) {\n\t if (set->nodeTab[i] == NULL)\n\t\tcontinue;\n\n\t contextNode = set->nodeTab[i];\n\t xpctxt->node = contextNode;\n\t xpctxt->contextSize = contextSize;\n\t xpctxt->proximityPosition = ++contextPos;\n\n\t /*\n\t * Initialize the new set.\n\t * Also set the xpath document in case things like\n\t * key() evaluation are attempted on the predicate\n\t */\n\t if ((contextNode->type != XML_NAMESPACE_DECL) &&\n\t\t(contextNode->doc != NULL))\n\t\txpctxt->doc = contextNode->doc;\n\t /*\n\t * Evaluate the predicate expression with 1 context node\n\t * at a time; this node is packaged into a node set; this\n\t * node set is handed over to the evaluation mechanism.\n\t */\n\t if (contextObj == NULL)\n\t\tcontextObj = xmlXPathCacheNewNodeSet(xpctxt, contextNode);\n\t else\n\t\txmlXPathNodeSetAddUnique(contextObj->nodesetval,\n\t\t contextNode);\n\n\t valuePush(ctxt, contextObj);\n\t res = xmlXPathCompOpEvalToBoolean(ctxt, exprOp, 1);\n\n\t if ((ctxt->error != XPATH_EXPRESSION_OK) || (res == -1)) {\n\t xmlXPathObjectPtr tmp;\n\t\t/* pop the result */\n\t\ttmp = valuePop(ctxt);\n\t\txmlXPathReleaseObject(xpctxt, tmp);\n\t\t/* then pop off contextObj, which will be freed later */\n\t\tvaluePop(ctxt);\n\t\tgoto evaluation_error;\n\t }\n\n\t if (res)\n\t\tpos++;\n\n\t if (res && (pos >= minPos) && (pos <= maxPos)) {\n\t\t/*\n\t\t* Fits in the requested range.\n\t\t*/\n\t\tnewContextSize++;\n\t\tif (minPos == maxPos) {\n\t\t /*\n\t\t * Only 1 node was requested.\n\t\t */\n\t\t if (contextNode->type == XML_NAMESPACE_DECL) {\n\t\t\t/*\n\t\t\t* As always: take care of those nasty\n\t\t\t* namespace nodes.\n\t\t\t*/\n\t\t\tset->nodeTab[i] = NULL;\n\t\t }\n\t\t xmlXPathNodeSetClear(set, hasNsNodes);\n\t\t set->nodeNr = 1;\n\t\t set->nodeTab[0] = contextNode;\n\t\t goto evaluation_exit;\n\t\t}\n\t\tif (pos == maxPos) {\n\t\t /*\n\t\t * We are done.\n\t\t */\n\t\t xmlXPathNodeSetClearFromPos(set, i +1, hasNsNodes);\n\t\t goto evaluation_exit;\n\t\t}\n\t } else {\n\t\t/*\n\t\t* Remove the entry from the initial node set.\n\t\t*/\n\t\tset->nodeTab[i] = NULL;\n\t\tif (contextNode->type == XML_NAMESPACE_DECL)\n\t\t xmlXPathNodeSetFreeNs((xmlNsPtr) contextNode);\n\t }\n\t if (exprRes != NULL) {\n\t\txmlXPathReleaseObject(ctxt->context, exprRes);\n\t\texprRes = NULL;\n\t }\n\t if (ctxt->value == contextObj) {\n\t\t/*\n\t\t* Don't free the temporary XPath object holding the\n\t\t* context node, in order to avoid massive recreation\n\t\t* inside this loop.\n\t\t*/\n\t\tvaluePop(ctxt);\n\t\txmlXPathNodeSetClear(contextObj->nodesetval, hasNsNodes);\n\t } else {\n\t\t/*\n\t\t* The object was lost in the evaluation machinery.\n\t\t* Can this happen? Maybe in case of internal-errors.\n\t\t*/\n\t\tcontextObj = NULL;\n\t }\n\t}\n\tgoto evaluation_exit;\n\nevaluation_error:\n\txmlXPathNodeSetClear(set, hasNsNodes);\n\tnewContextSize = 0;\n\nevaluation_exit:\n\tif (contextObj != NULL) {\n\t if (ctxt->value == contextObj)\n\t\tvaluePop(ctxt);\n\t xmlXPathReleaseObject(xpctxt, contextObj);\n\t}\n\tif (exprRes != NULL)\n\t xmlXPathReleaseObject(ctxt->context, exprRes);\n\t/*\n\t* Reset/invalidate the context.\n\t*/\n\txpctxt->node = oldContextNode;\n\txpctxt->doc = oldContextDoc;\n\txpctxt->contextSize = -1;\n\txpctxt->proximityPosition = -1;\n\treturn(newContextSize);\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'Fix a potential freeing error in XPath'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int mainloop(CLIENT *client) {\n\tstruct nbd_request request;\n\tstruct nbd_reply reply;\n\tgboolean go_on=TRUE;\n#ifdef DODBG\n\tint i = 0;\n#endif\n\tnegotiate(client->net, client, NULL);\n\tDEBUG(\"Entering request loop!\\n\");\n\treply.magic = htonl(NBD_REPLY_MAGIC);\n\treply.error = 0;\n\twhile (go_on) {\n\t\tchar buf[BUFSIZE];\n\t\tsize_t len;\n#ifdef DODBG\n\t\ti++;\n\t\tprintf(\"%d: \", i);\n#endif\n\t\treadit(client->net, &request, sizeof(request));\n\t\trequest.from = ntohll(request.from);\n\t\trequest.type = ntohl(request.type);\n\n\t\tif (request.type==NBD_CMD_DISC) {\n\t\t\tmsg2(LOG_INFO, \"Disconnect request received.\");\n \tif (client->server->flags & F_COPYONWRITE) { \n\t\t\t\tif (client->difmap) g_free(client->difmap) ;\n \t\tclose(client->difffile);\n\t\t\t\tunlink(client->difffilename);\n\t\t\t\tfree(client->difffilename);\n\t\t\t}\n\t\t\tgo_on=FALSE;\n\t\t\tcontinue;\n\t\t}\n\n\t\tlen = ntohl(request.len);\n\n\t\tif (request.magic != htonl(NBD_REQUEST_MAGIC))\n\t\t\terr(\"Not enough magic.\");\n\t\tif (len > BUFSIZE + sizeof(struct nbd_reply))\n\t\t\terr(\"Request too big!\");\n#ifdef DODBG\n\t\tprintf(\"%s from %llu (%llu) len %d, \", request.type ? \"WRITE\" :\n\t\t\t\t\"READ\", (unsigned long long)request.from,\n\t\t\t\t(unsigned long long)request.from / 512, len);\n#endif\n\t\tmemcpy(reply.handle, request.handle, sizeof(reply.handle));\n\t\tif ((request.from + len) > (OFFT_MAX)) {\n\t\t\tDEBUG(\"[Number too large!]\");\n\t\t\tERROR(client, reply, EINVAL);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (((ssize_t)((off_t)request.from + len) > client->exportsize)) {\n\t\t\tDEBUG(\"[RANGE!]\");\n\t\t\tERROR(client, reply, EINVAL);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (request.type==NBD_CMD_WRITE) {\n\t\t\tDEBUG(\"wr: net->buf, \");\n\t\t\treadit(client->net, buf, len);\n\t\t\tDEBUG(\"buf->exp, \");\n\t\t\tif ((client->server->flags & F_READONLY) ||\n\t\t\t (client->server->flags & F_AUTOREADONLY)) {\n\t\t\t\tDEBUG(\"[WRITE to READONLY!]\");\n\t\t\t\tERROR(client, reply, EPERM);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (expwrite(request.from, buf, len, client)) {\n\t\t\t\tDEBUG(\"Write failed: %m\" );\n\t\t\t\tERROR(client, reply, errno);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tSEND(client->net, reply);\n\t\t\tDEBUG(\"OK!\\n\");\n\t\t\tcontinue;\n\t\t}\n\t\t/* READ */\n\n\t\tDEBUG(\"exp->buf, \");\n\t\tif (expread(request.from, buf + sizeof(struct nbd_reply), len, client)) {\n\t\t\tDEBUG(\"Read failed: %m\");\n\t\t\tERROR(client, reply, errno);\n\t\t\tcontinue;\n\t\t}\n\n\t\tDEBUG(\"buf->net, \");\n\t\tmemcpy(buf, &reply, sizeof(struct nbd_reply));\n\t\twriteit(client->net, buf, len + sizeof(struct nbd_reply));\n\t\tDEBUG(\"OK!\\n\");\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix buffer size checking\n\nYes, this means we've re-introduced CVE-2005-3534. Sigh.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int tpm_open(struct inode *inode, struct file *file)\n{\n\tint minor = iminor(inode);\n\tstruct tpm_chip *chip = NULL, *pos;\n\n\trcu_read_lock();\n\tlist_for_each_entry_rcu(pos, &tpm_chip_list, list) {\n\t\tif (pos->vendor.miscdev.minor == minor) {\n\t\t\tchip = pos;\n\t\t\tget_device(chip->dev);\n\t\t\tbreak;\n\t\t}\n\t}\n\trcu_read_unlock();\n\n\tif (!chip)\n\t\treturn -ENODEV;\n\n\tif (test_and_set_bit(0, &chip->is_open)) {\n\t\tdev_dbg(chip->dev, \"Another process owns this TPM\\n\");\n\t\tput_device(chip->dev);\n\t\treturn -EBUSY;\n\t}\n\n\tchip->data_buffer = kmalloc(TPM_BUFSIZE * sizeof(u8), GFP_KERNEL);\n\tif (chip->data_buffer == NULL) {\n\t\tclear_bit(0, &chip->is_open);\n\t\tput_device(chip->dev);\n\t\treturn -ENOMEM;\n\t}\n\n\tatomic_set(&chip->data_pending, 0);\n\n\tfile->private_data = chip;\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'char/tpm: Fix unitialized usage of data buffer\n\nThis patch fixes information leakage to the userspace by initializing\nthe data buffer to zero.\n\nReported-by: Peter Huewe \nSigned-off-by: Peter Huewe \nSigned-off-by: Marcel Selhorst \n[ Also removed the silly \"* sizeof(u8)\". If that isn't 1, we have way\n deeper problems than a simple multiplication can fix. - Linus ]\nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: network_init ()\n{\n#ifdef HAVE_GNUTLS\n char *ca_path, *ca_path2;\n\n gnutls_global_init ();\n gnutls_certificate_allocate_credentials (&gnutls_xcred);\n \n ca_path = string_expand_home (CONFIG_STRING(config_network_gnutls_ca_file));\n if (ca_path)\n {\n ca_path2 = string_replace (ca_path, \"%h\", weechat_home);\n if (ca_path2)\n {\n gnutls_certificate_set_x509_trust_file (gnutls_xcred, ca_path2,\n GNUTLS_X509_FMT_PEM);\n free (ca_path2);\n }\n free (ca_path);\n }\n gnutls_certificate_client_set_retrieve_function (gnutls_xcred,\n &hook_connect_gnutls_set_certificates);\n network_init_ok = 1;\n#endif\n#ifdef HAVE_GCRYPT\n gcry_check_version (GCRYPT_VERSION);\n gcry_control (GCRYCTL_DISABLE_SECMEM, 0);\n gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fix verification of SSL certificates by calling gnutls verify callback (patch #7459)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: do_ip6t_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)\n{\n\tint ret;\n\n\tif (!capable(CAP_NET_ADMIN))\n\t\treturn -EPERM;\n\n\tswitch (cmd) {\n\tcase IP6T_SO_GET_INFO:\n\t\tret = get_info(sock_net(sk), user, len, 0);\n\t\tbreak;\n\n\tcase IP6T_SO_GET_ENTRIES:\n\t\tret = get_entries(sock_net(sk), user, len);\n\t\tbreak;\n\n\tcase IP6T_SO_GET_REVISION_MATCH:\n\tcase IP6T_SO_GET_REVISION_TARGET: {\n\t\tstruct xt_get_revision rev;\n\t\tint target;\n\n\t\tif (*len != sizeof(rev)) {\n\t\t\tret = -EINVAL;\n\t\t\tbreak;\n\t\t}\n\t\tif (copy_from_user(&rev, user, sizeof(rev)) != 0) {\n\t\t\tret = -EFAULT;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (cmd == IP6T_SO_GET_REVISION_TARGET)\n\t\t\ttarget = 1;\n\t\telse\n\t\t\ttarget = 0;\n\n\t\ttry_then_request_module(xt_find_revision(AF_INET6, rev.name,\n\t\t\t\t\t\t\t rev.revision,\n\t\t\t\t\t\t\t target, &ret),\n\t\t\t\t\t\"ip6t_%s\", rev.name);\n\t\tbreak;\n\t}\n\n\tdefault:\n\t\tduprintf(\"do_ip6t_get_ctl: unknown request %i\\n\", cmd);\n\t\tret = -EINVAL;\n\t}\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'ipv6: netfilter: ip6_tables: fix infoleak to userspace\n\nStructures ip6t_replace, compat_ip6t_replace, and xt_get_revision are\ncopied from userspace. Fields of these structs that are\nzero-terminated strings are not checked. When they are used as argument\nto a format string containing \"%s\" in request_module(), some sensitive\ninformation is leaked to userspace via argument of spawned modprobe\nprocess.\n\nThe first bug was introduced before the git epoch; the second was\nintroduced in 3bc3fe5e (v2.6.25-rc1); the third is introduced by\n6b7d31fc (v2.6.15-rc1). To trigger the bug one should have\nCAP_NET_ADMIN.\n\nSigned-off-by: Vasiliy Kulikov \nSigned-off-by: Patrick McHardy '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: processBatchMultiRuleset(batch_t *pBatch)\n{\n\truleset_t *currRuleset;\n\tbatch_t snglRuleBatch;\n\tint i;\n\tint iStart;\t/* start index of partial batch */\n\tint iNew;\t/* index for new (temporary) batch */\n\tDEFiRet;\n\n\tCHKiRet(batchInit(&snglRuleBatch, pBatch->nElem));\n\tsnglRuleBatch.pbShutdownImmediate = pBatch->pbShutdownImmediate;\n\n\twhile(1) { /* loop broken inside */\n\t\t/* search for first unprocessed element */\n\t\tfor(iStart = 0 ; iStart < pBatch->nElem && pBatch->pElem[iStart].state == BATCH_STATE_DISC ; ++iStart)\n\t\t\t/* just search, no action */;\n\n\t\tif(iStart == pBatch->nElem)\n\t\t\tFINALIZE; /* everything processed */\n\n\t\t/* prepare temporary batch */\n\t\tcurrRuleset = batchElemGetRuleset(pBatch, iStart);\n\t\tiNew = 0;\n\t\tfor(i = iStart ; i < pBatch->nElem ; ++i) {\n\t\t\tif(batchElemGetRuleset(pBatch, i) == currRuleset) {\n\t\t\t\tbatchCopyElem(&(snglRuleBatch.pElem[iNew++]), &(pBatch->pElem[i]));\n\t\t\t\t/* We indicate the element also as done, so it will not be processed again */\n\t\t\t\tpBatch->pElem[i].state = BATCH_STATE_DISC;\n\t\t\t}\n\t\t}\n\t\tsnglRuleBatch.nElem = iNew; /* was left just right by the for loop */\n\t\tbatchSetSingleRuleset(&snglRuleBatch, 1);\n\t\t/* process temp batch */\n\t\tprocessBatch(&snglRuleBatch);\n\t}\n\tbatchFree(&snglRuleBatch);\n\nfinalize_it:\n\tRETiRet;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-772', 'CWE-401'], 'message': 'bugfix: fixed a memory leak and potential abort condition\n\nthis could happen if multiple rulesets were used and some output batches\ncontained messages belonging to more than one ruleset.\nfixes: http://bugzilla.adiscon.com/show_bug.cgi?id=226\nfixes: http://bugzilla.adiscon.com/show_bug.cgi?id=218'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void \nmono_reflection_create_dynamic_method (MonoReflectionDynamicMethod *mb)\n{\n\tReflectionMethodBuilder rmb;\n\tMonoMethodSignature *sig;\n\tMonoClass *klass;\n\tGSList *l;\n\tint i;\n\n\tsig = dynamic_method_to_signature (mb);\n\n\treflection_methodbuilder_from_dynamic_method (&rmb, mb);\n\n\t/*\n\t * Resolve references.\n\t */\n\t/* \n\t * Every second entry in the refs array is reserved for storing handle_class,\n\t * which is needed by the ldtoken implementation in the JIT.\n\t */\n\trmb.nrefs = mb->nrefs;\n\trmb.refs = g_new0 (gpointer, mb->nrefs + 1);\n\tfor (i = 0; i < mb->nrefs; i += 2) {\n\t\tMonoClass *handle_class;\n\t\tgpointer ref;\n\t\tMonoObject *obj = mono_array_get (mb->refs, MonoObject*, i);\n\n\t\tif (strcmp (obj->vtable->klass->name, \"DynamicMethod\") == 0) {\n\t\t\tMonoReflectionDynamicMethod *method = (MonoReflectionDynamicMethod*)obj;\n\t\t\t/*\n\t\t\t * The referenced DynamicMethod should already be created by the managed\n\t\t\t * code, except in the case of circular references. In that case, we store\n\t\t\t * method in the refs array, and fix it up later when the referenced \n\t\t\t * DynamicMethod is created.\n\t\t\t */\n\t\t\tif (method->mhandle) {\n\t\t\t\tref = method->mhandle;\n\t\t\t} else {\n\t\t\t\t/* FIXME: GC object stored in unmanaged memory */\n\t\t\t\tref = method;\n\n\t\t\t\t/* FIXME: GC object stored in unmanaged memory */\n\t\t\t\tmethod->referenced_by = g_slist_append (method->referenced_by, mb);\n\t\t\t}\n\t\t\thandle_class = mono_defaults.methodhandle_class;\n\t\t} else {\n\t\t\tMonoException *ex = NULL;\n\t\t\tref = resolve_object (mb->module->image, obj, &handle_class, NULL);\n\t\t\tif (!ref)\n\t\t\t\tex = mono_get_exception_type_load (NULL, NULL);\n\t\t\telse if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)\n\t\t\t\tex = mono_security_core_clr_ensure_dynamic_method_resolved_object (ref, handle_class);\n\n\t\t\tif (ex) {\n\t\t\t\tg_free (rmb.refs);\n\t\t\t\tmono_raise_exception (ex);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\trmb.refs [i] = ref; /* FIXME: GC object stored in unmanaged memory (change also resolve_object() signature) */\n\t\trmb.refs [i + 1] = handle_class;\n\t}\t\t\n\n\tklass = mb->owner ? mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)mb->owner)) : mono_defaults.object_class;\n\n\tmb->mhandle = reflection_methodbuilder_to_mono_method (klass, &rmb, sig);\n\n\t/* Fix up refs entries pointing at us */\n\tfor (l = mb->referenced_by; l; l = l->next) {\n\t\tMonoReflectionDynamicMethod *method = (MonoReflectionDynamicMethod*)l->data;\n\t\tMonoMethodWrapper *wrapper = (MonoMethodWrapper*)method->mhandle;\n\t\tgpointer *data;\n\t\t\n\t\tg_assert (method->mhandle);\n\n\t\tdata = (gpointer*)wrapper->method_data;\n\t\tfor (i = 0; i < GPOINTER_TO_UINT (data [0]); i += 2) {\n\t\t\tif ((data [i + 1] == mb) && (data [i + 1 + 1] == mono_defaults.methodhandle_class))\n\t\t\t\tdata [i + 1] = mb->mhandle;\n\t\t}\n\t}\n\tg_slist_free (mb->referenced_by);\n\n\tg_free (rmb.refs);\n\n\t/* ilgen is no longer needed */\n\tmb->ilgen = NULL; ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-264'], 'message': 'Don't use finalization to cleanup dynamic methods.\n\n * reflection.c: Use a reference queue to cleanup\n dynamic methods instead of finalization.\n\n * runtime.c: Shutdown the dynamic method queue\n before runtime cleanup begins.\n\n * DynamicMethod.cs: No longer finalizable.\n\n * icall-def.h: Remove unused dynamic method icall.\n\n Fixes #660422\n\n Implement a reference queue API.\n\n * gc.c: A reference queue allows one to queue\n callbcks for when objects are collected.\n It allows for safe cleanup of objects that can\n only be done when it is effectively collected.\n The major difference with regular finalization\n is that the collector makes sure the object\n was collected - and can't be resurrected.\n\n * gc-internal.h: Export entrypoints for the\n new API.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void virtio_blk_handle_write(VirtIOBlockReq *req, MultiReqBuffer *mrb)\n{\n BlockRequest *blkreq;\n uint64_t sector;\n\n sector = ldq_p(&req->out->sector);\n\n trace_virtio_blk_handle_write(req, sector, req->qiov.size / 512);\n\n if (sector & req->dev->sector_mask) {\n virtio_blk_rw_complete(req, -EIO);\n return;\n }\n\n if (mrb->num_writes == 32) {\n virtio_submit_multiwrite(req->dev->bs, mrb);\n }\n\n blkreq = &mrb->blkreq[mrb->num_writes];\n blkreq->sector = sector;\n blkreq->nb_sectors = req->qiov.size / BDRV_SECTOR_SIZE;\n blkreq->qiov = &req->qiov;\n blkreq->cb = virtio_blk_rw_complete;\n blkreq->opaque = req;\n blkreq->error = 0;\n\n mrb->num_writes++;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'virtio-blk: fail unaligned requests\n\nLike all block drivers virtio-blk should not allow small than block size\ngranularity access. But given that the protocol specifies a\nbyte unit length field we currently accept such requests, which cause\nqemu to abort() in lower layers. Add checks to the main read and\nwrite handlers to catch them early.\n\nReported-by: Conor Murphy \nTested-by: Conor Murphy \nSigned-off-by: Christoph Hellwig \nReviewed-by: Stefan Hajnoczi \nSigned-off-by: Kevin Wolf '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: const char *string_of_NPNVariable(int variable)\n{\n const char *str;\n\n switch (variable) {\n#define _(VAL) case VAL: str = #VAL; break;\n\t_(NPNVxDisplay);\n\t_(NPNVxtAppContext);\n\t_(NPNVnetscapeWindow);\n\t_(NPNVjavascriptEnabledBool);\n\t_(NPNVasdEnabledBool);\n\t_(NPNVisOfflineBool);\n\t_(NPNVserviceManager);\n\t_(NPNVDOMElement);\n\t_(NPNVDOMWindow);\n\t_(NPNVToolkit);\n\t_(NPNVSupportsXEmbedBool);\n\t_(NPNVWindowNPObject);\n\t_(NPNVPluginElementNPObject);\n\t_(NPNVSupportsWindowless);\n#undef _\n default:\n\tswitch (variable & 0xff) {\n#define _(VAL, VAR) case VAL: str = #VAR; break\n\t _(10, NPNVserviceManager);\n\t _(11, NPNVDOMElement);\n\t _(12, NPNVDOMWindow);\n\t _(13, NPNVToolkit);\n#undef _\n\tdefault:\n\t str = \"\";\n\t break;\n\t}\n\tbreak;\n }\n\n return str;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'Support all the new variables added'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int cli_hm_scan(const unsigned char *digest, uint32_t size, const char **virname, const struct cli_matcher *root, enum CLI_HASH_TYPE type) {\n const struct cli_htu32_element *item;\n unsigned int keylen;\n struct cli_sz_hash *szh;\n size_t l, r;\n\n if(!digest || !size || size == 0xffffffff || !root || !root->hm.sizehashes[type].capacity)\n\treturn CL_CLEAN;\n\n item = cli_htu32_find(&root->hm.sizehashes[type], size);\n if(!item)\n\treturn CL_CLEAN;\n\n szh = (struct cli_sz_hash *)item->data.as_ptr;\n keylen = hashlen[type];\n\n l = 0;\n r = szh->items;\n while(l <= r) {\n\tsize_t c = (l + r) / 2;\n\tint res = hm_cmp(digest, &szh->hash_array[keylen * c], keylen);\n\n\tif(res < 0) {\n\t if(!c)\n\t\tbreak;\n\t r = c - 1;\n\t} else if(res > 0)\n\t l = c + 1;\n\telse {\n\t if(virname)\n\t\t*virname = szh->virusnames[c];\n\t return CL_VIRUS;\n\t}\n }\n return CL_CLEAN;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'bb#2818'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: gdk_pixbuf__tiff_image_load (FILE *f, GError **error)\n{\n\treturn gdk_pixbuf__tiff_image_load_real (f, NULL, error);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Initial stab at getting the focus code to work.\n\nFri Jun 1 18:54:47 2001 Jonathan Blandford \n\n\t* gtk/gtktreeview.c: (gtk_tree_view_focus): Initial stab at\n\tgetting the focus code to work.\n\t(gtk_tree_view_class_init): Add a bunch of keybindings.\n\n\t* gtk/gtktreeviewcolumn.c\n\t(gtk_tree_view_column_set_cell_data_func):\n\ts/GtkCellDataFunc/GtkTreeCellDataFunc.\n\t(_gtk_tree_view_column_set_tree_view): Use \"notify::model\" instead\n\tof \"properties_changed\" to help justify the death of the latter\n\tsignal. (-:\n\n\t* tests/testtreefocus.c (main): Let some columns be focussable to\n\ttest focus better.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: gdk_pixbuf__tiff_image_stop_load (gpointer data,\n GError **error)\n{\n\tTiffData *context = (TiffData*) data;\n gboolean retval = FALSE;\n \n\tg_return_val_if_fail (data != NULL, TRUE);\n\n\tfflush (context->file);\n\trewind (context->file);\n\tif (context->all_okay) {\n GdkPixbuf *pixbuf;\n\t\tpixbuf = gdk_pixbuf__tiff_image_load_real (context->file, context, error);\n if (pixbuf != NULL)\n retval = TRUE;\n }\n\n\tfclose (context->file);\n\tunlink (context->tempname);\n\tg_free (context->tempname);\n\tg_free ((TiffData *) context);\n\n return TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Initial stab at getting the focus code to work.\n\nFri Jun 1 18:54:47 2001 Jonathan Blandford \n\n\t* gtk/gtktreeview.c: (gtk_tree_view_focus): Initial stab at\n\tgetting the focus code to work.\n\t(gtk_tree_view_class_init): Add a bunch of keybindings.\n\n\t* gtk/gtktreeviewcolumn.c\n\t(gtk_tree_view_column_set_cell_data_func):\n\ts/GtkCellDataFunc/GtkTreeCellDataFunc.\n\t(_gtk_tree_view_column_set_tree_view): Use \"notify::model\" instead\n\tof \"properties_changed\" to help justify the death of the latter\n\tsignal. (-:\n\n\t* tests/testtreefocus.c (main): Let some columns be focussable to\n\ttest focus better.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: jiffies_to_compat_timeval(unsigned long jiffies, struct compat_timeval *value)\n{\n\t/*\n\t * Convert jiffies to nanoseconds and separate with\n\t * one divide.\n\t */\n\tu64 nsec = (u64)jiffies * TICK_NSEC;\n\tlong rem;\n\tvalue->tv_sec = div_long_long_rem(nsec, NSEC_PER_SEC, &rem);\n\tvalue->tv_usec = rem / NSEC_PER_USEC;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'remove div_long_long_rem\n\nx86 is the only arch right now, which provides an optimized for\ndiv_long_long_rem and it has the downside that one has to be very careful that\nthe divide doesn't overflow.\n\nThe API is a little akward, as the arguments for the unsigned divide are\nsigned. The signed version also doesn't handle a negative divisor and\nproduces worse code on 64bit archs.\n\nThere is little incentive to keep this API alive, so this converts the few\nusers to the new API.\n\nSigned-off-by: Roman Zippel \nCc: Ralf Baechle \nCc: Ingo Molnar \nCc: Thomas Gleixner \nCc: john stultz \nCc: Christoph Lameter \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void sample_to_timespec(const clockid_t which_clock,\n\t\t\t union cpu_time_count cpu,\n\t\t\t struct timespec *tp)\n{\n\tif (CPUCLOCK_WHICH(which_clock) == CPUCLOCK_SCHED) {\n\t\ttp->tv_sec = div_long_long_rem(cpu.sched,\n\t\t\t\t\t NSEC_PER_SEC, &tp->tv_nsec);\n\t} else {\n\t\tcputime_to_timespec(cpu.cpu, tp);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'remove div_long_long_rem\n\nx86 is the only arch right now, which provides an optimized for\ndiv_long_long_rem and it has the downside that one has to be very careful that\nthe divide doesn't overflow.\n\nThe API is a little akward, as the arguments for the unsigned divide are\nsigned. The signed version also doesn't handle a negative divisor and\nproduces worse code on 64bit archs.\n\nThere is little incentive to keep this API alive, so this converts the few\nusers to the new API.\n\nSigned-off-by: Roman Zippel \nCc: Ralf Baechle \nCc: Ingo Molnar \nCc: Thomas Gleixner \nCc: john stultz \nCc: Christoph Lameter \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: valuePop(xmlXPathParserContextPtr ctxt)\n{\n xmlXPathObjectPtr ret;\n\n if ((ctxt == NULL) || (ctxt->valueNr <= 0))\n return (NULL);\n ctxt->valueNr--;\n if (ctxt->valueNr > 0)\n ctxt->value = ctxt->valueTab[ctxt->valueNr - 1];\n else\n ctxt->value = NULL;\n ret = ctxt->valueTab[ctxt->valueNr];\n ctxt->valueTab[ctxt->valueNr] = NULL;\n return (ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'Hardening of XPath evaluation\n\nAdd a mechanism of frame for XPath evaluation when entering a function\nor a scoped evaluation, also fix a potential problem in predicate\nevaluation.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int32_t scsi_send_command(SCSIRequest *req, uint8_t *buf)\n{\n SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);\n SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);\n int32_t len;\n uint8_t command;\n uint8_t *outbuf;\n int rc;\n\n command = buf[0];\n outbuf = (uint8_t *)r->iov.iov_base;\n DPRINTF(\"Command: lun=%d tag=0x%x data=0x%02x\", req->lun, req->tag, buf[0]);\n\n#ifdef DEBUG_SCSI\n {\n int i;\n for (i = 1; i < r->req.cmd.len; i++) {\n printf(\" 0x%02x\", buf[i]);\n }\n printf(\"\\n\");\n }\n#endif\n\n switch (command) {\n case TEST_UNIT_READY:\n case INQUIRY:\n case MODE_SENSE:\n case MODE_SENSE_10:\n case RESERVE:\n case RESERVE_10:\n case RELEASE:\n case RELEASE_10:\n case START_STOP:\n case ALLOW_MEDIUM_REMOVAL:\n case READ_CAPACITY_10:\n case READ_TOC:\n case GET_CONFIGURATION:\n case SERVICE_ACTION_IN_16:\n case VERIFY_10:\n rc = scsi_disk_emulate_command(r, outbuf);\n if (rc < 0) {\n return 0;\n }\n\n r->iov.iov_len = rc;\n break;\n case SYNCHRONIZE_CACHE:\n bdrv_acct_start(s->bs, &r->acct, 0, BDRV_ACCT_FLUSH);\n r->req.aiocb = bdrv_aio_flush(s->bs, scsi_flush_complete, r);\n if (r->req.aiocb == NULL) {\n scsi_flush_complete(r, -EIO);\n }\n return 0;\n case READ_6:\n case READ_10:\n case READ_12:\n case READ_16:\n len = r->req.cmd.xfer / s->qdev.blocksize;\n DPRINTF(\"Read (sector %\" PRId64 \", count %d)\\n\", r->req.cmd.lba, len);\n if (r->req.cmd.lba > s->max_lba)\n goto illegal_lba;\n r->sector = r->req.cmd.lba * s->cluster_size;\n r->sector_count = len * s->cluster_size;\n break;\n case WRITE_6:\n case WRITE_10:\n case WRITE_12:\n case WRITE_16:\n case WRITE_VERIFY_10:\n case WRITE_VERIFY_12:\n case WRITE_VERIFY_16:\n len = r->req.cmd.xfer / s->qdev.blocksize;\n DPRINTF(\"Write %s(sector %\" PRId64 \", count %d)\\n\",\n (command & 0xe) == 0xe ? \"And Verify \" : \"\",\n r->req.cmd.lba, len);\n if (r->req.cmd.lba > s->max_lba)\n goto illegal_lba;\n r->sector = r->req.cmd.lba * s->cluster_size;\n r->sector_count = len * s->cluster_size;\n break;\n case MODE_SELECT:\n DPRINTF(\"Mode Select(6) (len %lu)\\n\", (long)r->req.cmd.xfer);\n /* We don't support mode parameter changes.\n Allow the mode parameter header + block descriptors only. */\n if (r->req.cmd.xfer > 12) {\n goto fail;\n }\n break;\n case MODE_SELECT_10:\n DPRINTF(\"Mode Select(10) (len %lu)\\n\", (long)r->req.cmd.xfer);\n /* We don't support mode parameter changes.\n Allow the mode parameter header + block descriptors only. */\n if (r->req.cmd.xfer > 16) {\n goto fail;\n }\n break;\n case SEEK_6:\n case SEEK_10:\n DPRINTF(\"Seek(%d) (sector %\" PRId64 \")\\n\", command == SEEK_6 ? 6 : 10,\n r->req.cmd.lba);\n if (r->req.cmd.lba > s->max_lba) {\n goto illegal_lba;\n }\n break;\n case WRITE_SAME_16:\n len = r->req.cmd.xfer / s->qdev.blocksize;\n\n DPRINTF(\"WRITE SAME(16) (sector %\" PRId64 \", count %d)\\n\",\n r->req.cmd.lba, len);\n\n if (r->req.cmd.lba > s->max_lba) {\n goto illegal_lba;\n }\n\n /*\n * We only support WRITE SAME with the unmap bit set for now.\n */\n if (!(buf[1] & 0x8)) {\n goto fail;\n }\n\n rc = bdrv_discard(s->bs, r->req.cmd.lba * s->cluster_size,\n len * s->cluster_size);\n if (rc < 0) {\n /* XXX: better error code ?*/\n goto fail;\n }\n\n break;\n case REQUEST_SENSE:\n abort();\n default:\n DPRINTF(\"Unknown SCSI command (%2.2x)\\n\", buf[0]);\n scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE));\n return 0;\n fail:\n scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));\n return 0;\n illegal_lba:\n scsi_check_condition(r, SENSE_CODE(LBA_OUT_OF_RANGE));\n return 0;\n }\n if (r->sector_count == 0 && r->iov.iov_len == 0) {\n scsi_req_complete(&r->req, GOOD);\n }\n len = r->sector_count * 512 + r->iov.iov_len;\n if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {\n return -len;\n } else {\n if (!r->sector_count)\n r->sector_count = -1;\n return len;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'scsi-disk: lazily allocate bounce buffer\n\nIt will not be needed for reads and writes if the HBA provides a sglist.\nIn addition, this lets scsi-disk refuse commands with an excessive\nallocation length, as well as limit memory on usual well-behaved guests.\n\nSigned-off-by: Paolo Bonzini \nSigned-off-by: Kevin Wolf '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void list_proxy(char *server, void *data __attribute__((unused)), void *rock)\n{\n struct enum_rock *erock = (struct enum_rock *) rock;\n struct backend *be;\n int r;\n char *result;\n\n be = proxy_findserver(server, &nntp_protocol,\n\t\t\t nntp_userid ? nntp_userid : \"anonymous\",\n\t\t\t &backend_cached, &backend_current, NULL, nntp_in);\n if (!be) return;\n\n prot_printf(be->out, \"LIST %s %s\\r\\n\", erock->cmd, erock->wild);\n\n r = read_response(be, 0, &result);\n if (!r && !strncmp(result, \"215 \", 4)) {\n\twhile (!(r = read_response(be, 0, &result)) && result[0] != '.') {\n\t prot_printf(nntp_out, \"%s\", result);\n\t}\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-287'], 'message': 'Secunia SA46093 - make sure nntp authentication completes\n\nDiscovered by Stefan Cornelius, Secunia Research\n\nThe vulnerability is caused due to the access restriction for certain\ncommands only checking whether or not variable \"nntp_userid\" is non-NULL,\nwithout performing additional checks to verify that a complete, successful\nauthentication actually took place. The variable \"nntp_userid\" can be set to\npoint to a string holding the username (changing it to a non-NULL, thus\nallowing attackers to bypass the checks) by sending an \"AUTHINFO USER\"\ncommand. The variable is not reset to NULL until e.g. a wrong \"AUTHINFO\nPASS\" command is received. This can be exploited to bypass the\nauthentication mechanism and allows access to e.g. the \"NEWNEWS\" or the\n\"LIST NEWSGROUPS\" commands by sending an \"AUTHINFO USER\" command without a\nfollowing \"AUTHINFO PASS\" command.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: add_mtab(char *devname, char *mountpoint, unsigned long flags)\n{\n\tint rc = 0;\n\tchar *mount_user;\n\tstruct mntent mountent;\n\tFILE *pmntfile;\n\n\tatexit(unlock_mtab);\n\trc = lock_mtab();\n\tif (rc) {\n\t\tfprintf(stderr, \"cannot lock mtab\");\n\t\trc = EX_FILEIO;\n\t\tgoto add_mtab_exit;\n\t}\n\n\tpmntfile = setmntent(MOUNTED, \"a+\");\n\tif (!pmntfile) {\n\t\tfprintf(stderr, \"could not update mount table\\n\");\n\t\tunlock_mtab();\n\t\trc = EX_FILEIO;\n\t\tgoto add_mtab_exit;\n\t}\n\n\tmountent.mnt_fsname = devname;\n\tmountent.mnt_dir = mountpoint;\n\tmountent.mnt_type = (char *)(void *)cifs_fstype;\n\tmountent.mnt_opts = (char *)calloc(MTAB_OPTIONS_LEN, 1);\n\tif (mountent.mnt_opts) {\n\t\tif (flags & MS_RDONLY)\n\t\t\tstrlcat(mountent.mnt_opts, \"ro\", MTAB_OPTIONS_LEN);\n\t\telse\n\t\t\tstrlcat(mountent.mnt_opts, \"rw\", MTAB_OPTIONS_LEN);\n\n\t\tif (flags & MS_MANDLOCK)\n\t\t\tstrlcat(mountent.mnt_opts, \",mand\", MTAB_OPTIONS_LEN);\n\t\tif (flags & MS_NOEXEC)\n\t\t\tstrlcat(mountent.mnt_opts, \",noexec\", MTAB_OPTIONS_LEN);\n\t\tif (flags & MS_NOSUID)\n\t\t\tstrlcat(mountent.mnt_opts, \",nosuid\", MTAB_OPTIONS_LEN);\n\t\tif (flags & MS_NODEV)\n\t\t\tstrlcat(mountent.mnt_opts, \",nodev\", MTAB_OPTIONS_LEN);\n\t\tif (flags & MS_SYNCHRONOUS)\n\t\t\tstrlcat(mountent.mnt_opts, \",sync\", MTAB_OPTIONS_LEN);\n\t\tif (getuid() != 0) {\n\t\t\tstrlcat(mountent.mnt_opts, \",user=\", MTAB_OPTIONS_LEN);\n\t\t\tmount_user = getusername();\n\t\t\tif (mount_user)\n\t\t\t\tstrlcat(mountent.mnt_opts, mount_user,\n\t\t\t\t\tMTAB_OPTIONS_LEN);\n\t\t}\n\t}\n\tmountent.mnt_freq = 0;\n\tmountent.mnt_passno = 0;\n\trc = addmntent(pmntfile, &mountent);\n\tendmntent(pmntfile);\n\tunlock_mtab();\n\tSAFE_FREE(mountent.mnt_opts);\nadd_mtab_exit:\n\tif (rc) {\n\t\tfprintf(stderr, \"unable to add mount entry to mtab\\n\");\n\t\trc = EX_FILEIO;\n\t}\n\n\treturn rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'mount.cifs: guard against signals by unprivileged users\n\nIf mount.cifs is setuid root, then the unprivileged user who runs the\nprogram can send the mount.cifs process a signal and kill it. This is\nnot a huge problem unless we happen to be updating the mtab at the\ntime, in which case the mtab lockfiles might not get cleaned up.\n\nTo remedy this, have the privileged mount.cifs process set its real\nuid to the effective uid (usually, root). This prevents unprivileged\nusers from being able to signal the process.\n\nWhile we're at it, also mask off signals while we're updating the\nmtab. This leaves a SIGKILL by root as the only way to interrupt the\nmtab update, but there's really nothing we can do about that.\n\nSigned-off-by: Jeff Layton '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int32_t cli_bcapi_extract_new(struct cli_bc_ctx *ctx, int32_t id)\n{\n cli_ctx *cctx;\n int res = -1;\n\n cli_event_count(EV, BCEV_EXTRACTED);\n cli_dbgmsg(\"previous tempfile had %u bytes\\n\", ctx->written);\n if (!ctx->written)\n\treturn 0;\n if (ctx->ctx && cli_updatelimits(ctx->ctx, ctx->written))\n\treturn -1;\n ctx->written = 0;\n lseek(ctx->outfd, 0, SEEK_SET);\n cli_dbgmsg(\"bytecode: scanning extracted file %s\\n\", ctx->tempfile);\n cctx = (cli_ctx*)ctx->ctx;\n if (cctx) {\n\tcli_file_t current = cctx->container_type;\n\tif (ctx->containertype != CL_TYPE_ANY)\n\t cctx->container_type = ctx->containertype;\n\tres = cli_magic_scandesc(ctx->outfd, cctx);\n\tcctx->container_type = current;\n\tif (res == CL_VIRUS) {\n\t if (cctx->virname)\n\t\tctx->virname = *cctx->virname;\n\t ctx->found = 1;\n\t}\n }\n if ((cctx && cctx->engine->keeptmp) ||\n\t(ftruncate(ctx->outfd, 0) == -1)) {\n\n\tclose(ctx->outfd);\n\tif (!(cctx && cctx->engine->keeptmp) && ctx->tempfile)\n\t cli_unlink(ctx->tempfile);\n\tfree(ctx->tempfile);\n\tctx->tempfile = NULL;\n\tctx->outfd = 0;\n }\n cli_dbgmsg(\"bytecode: extracting new file with id %u\\n\", id);\n return res;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'fix recursion level crash (bb #3706).\n\nThanks to Stephane Chazelas for the analysis.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: set_routerstatus_from_routerinfo(routerstatus_t *rs,\n routerinfo_t *ri, time_t now,\n int naming, int listbadexits,\n int listbaddirs, int vote_on_hsdirs)\n{\n int unstable_version =\n !tor_version_as_new_as(ri->platform,\"0.1.1.16-rc-cvs\");\n memset(rs, 0, sizeof(routerstatus_t));\n\n rs->is_authority =\n router_digest_is_trusted_dir(ri->cache_info.identity_digest);\n\n /* Already set by compute_performance_thresholds. */\n rs->is_exit = ri->is_exit;\n rs->is_stable = ri->is_stable =\n router_is_active(ri, now) &&\n !dirserv_thinks_router_is_unreliable(now, ri, 1, 0) &&\n !unstable_version;\n rs->is_fast = ri->is_fast =\n router_is_active(ri, now) &&\n !dirserv_thinks_router_is_unreliable(now, ri, 0, 1);\n rs->is_running = ri->is_running; /* computed above */\n\n if (naming) {\n uint32_t name_status = dirserv_get_name_status(\n ri->cache_info.identity_digest, ri->nickname);\n rs->is_named = (naming && (name_status & FP_NAMED)) ? 1 : 0;\n rs->is_unnamed = (naming && (name_status & FP_UNNAMED)) ? 1 : 0;\n }\n rs->is_valid = ri->is_valid;\n\n if (rs->is_fast &&\n (router_get_advertised_bandwidth(ri) >= BANDWIDTH_TO_GUARANTEE_GUARD ||\n router_get_advertised_bandwidth(ri) >=\n MIN(guard_bandwidth_including_exits,\n guard_bandwidth_excluding_exits)) &&\n is_router_version_good_for_possible_guard(ri->platform)) {\n long tk = rep_hist_get_weighted_time_known(\n ri->cache_info.identity_digest, now);\n double wfu = rep_hist_get_weighted_fractional_uptime(\n ri->cache_info.identity_digest, now);\n rs->is_possible_guard = (wfu >= guard_wfu && tk >= guard_tk) ? 1 : 0;\n } else {\n rs->is_possible_guard = 0;\n }\n rs->is_bad_directory = listbaddirs && ri->is_bad_directory;\n rs->is_bad_exit = listbadexits && ri->is_bad_exit;\n ri->is_hs_dir = dirserv_thinks_router_is_hs_dir(ri, now);\n rs->is_hs_dir = vote_on_hsdirs && ri->is_hs_dir;\n rs->is_v2_dir = ri->dir_port != 0;\n\n if (!strcasecmp(ri->nickname, UNNAMED_ROUTER_NICKNAME))\n rs->is_named = rs->is_unnamed = 0;\n\n rs->published_on = ri->cache_info.published_on;\n memcpy(rs->identity_digest, ri->cache_info.identity_digest, DIGEST_LEN);\n memcpy(rs->descriptor_digest, ri->cache_info.signed_descriptor_digest,\n DIGEST_LEN);\n rs->addr = ri->addr;\n strlcpy(rs->nickname, ri->nickname, sizeof(rs->nickname));\n rs->or_port = ri->or_port;\n rs->dir_port = ri->dir_port;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'Add option to give guard flag to relays without the CVE-2011-2768 fix\n\nThis way, all of the DA operators can upgrade immediately, without nuking\nevery client's set of entry guards as soon as a majority of them upgrade.\n\nUntil enough guards have upgraded, a majority of dirauths should set this\nconfig option so that there are still enough guards in the network. After\na few days pass, all dirauths should use the default.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: xmlParsePI(xmlParserCtxtPtr ctxt) {\n xmlChar *buf = NULL;\n int len = 0;\n int size = XML_PARSER_BUFFER_SIZE;\n int cur, l;\n const xmlChar *target;\n xmlParserInputState state;\n int count = 0;\n\n if ((RAW == '<') && (NXT(1) == '?')) {\n\txmlParserInputPtr input = ctxt->input;\n\tstate = ctxt->instate;\n ctxt->instate = XML_PARSER_PI;\n\t/*\n\t * this is a Processing Instruction.\n\t */\n\tSKIP(2);\n\tSHRINK;\n\n\t/*\n\t * Parse the target name and check for special support like\n\t * namespace.\n\t */\n target = xmlParsePITarget(ctxt);\n\tif (target != NULL) {\n\t if ((RAW == '?') && (NXT(1) == '>')) {\n\t\tif (input != ctxt->input) {\n\t\t xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,\n\t \"PI declaration doesn't start and stop in the same entity\\n\");\n\t\t}\n\t\tSKIP(2);\n\n\t\t/*\n\t\t * SAX: PI detected.\n\t\t */\n\t\tif ((ctxt->sax) && (!ctxt->disableSAX) &&\n\t\t (ctxt->sax->processingInstruction != NULL))\n\t\t ctxt->sax->processingInstruction(ctxt->userData,\n\t\t target, NULL);\n\t\tctxt->instate = state;\n\t\treturn;\n\t }\n\t buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));\n\t if (buf == NULL) {\n\t\txmlErrMemory(ctxt, NULL);\n\t\tctxt->instate = state;\n\t\treturn;\n\t }\n\t cur = CUR;\n\t if (!IS_BLANK(cur)) {\n\t\txmlFatalErrMsgStr(ctxt, XML_ERR_SPACE_REQUIRED,\n\t\t\t \"ParsePI: PI %s space expected\\n\", target);\n\t }\n SKIP_BLANKS;\n\t cur = CUR_CHAR(l);\n\t while (IS_CHAR(cur) && /* checked */\n\t\t ((cur != '?') || (NXT(1) != '>'))) {\n\t\tif (len + 5 >= size) {\n\t\t xmlChar *tmp;\n\n\t\t size *= 2;\n\t\t tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar));\n\t\t if (tmp == NULL) {\n\t\t\txmlErrMemory(ctxt, NULL);\n\t\t\txmlFree(buf);\n\t\t\tctxt->instate = state;\n\t\t\treturn;\n\t\t }\n\t\t buf = tmp;\n\t\t}\n\t\tcount++;\n\t\tif (count > 50) {\n\t\t GROW;\n\t\t count = 0;\n\t\t}\n\t\tCOPY_BUF(l,buf,len,cur);\n\t\tNEXTL(l);\n\t\tcur = CUR_CHAR(l);\n\t\tif (cur == 0) {\n\t\t SHRINK;\n\t\t GROW;\n\t\t cur = CUR_CHAR(l);\n\t\t}\n\t }\n\t buf[len] = 0;\n\t if (cur != '?') {\n\t\txmlFatalErrMsgStr(ctxt, XML_ERR_PI_NOT_FINISHED,\n\t\t \"ParsePI: PI %s never end ...\\n\", target);\n\t } else {\n\t\tif (input != ctxt->input) {\n\t\t xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,\n\t \"PI declaration doesn't start and stop in the same entity\\n\");\n\t\t}\n\t\tSKIP(2);\n\n#ifdef LIBXML_CATALOG_ENABLED\n\t\tif (((state == XML_PARSER_MISC) ||\n\t (state == XML_PARSER_START)) &&\n\t\t (xmlStrEqual(target, XML_CATALOG_PI))) {\n\t\t xmlCatalogAllow allow = xmlCatalogGetDefaults();\n\t\t if ((allow == XML_CATA_ALLOW_DOCUMENT) ||\n\t\t\t(allow == XML_CATA_ALLOW_ALL))\n\t\t\txmlParseCatalogPI(ctxt, buf);\n\t\t}\n#endif\n\n\n\t\t/*\n\t\t * SAX: PI detected.\n\t\t */\n\t\tif ((ctxt->sax) && (!ctxt->disableSAX) &&\n\t\t (ctxt->sax->processingInstruction != NULL))\n\t\t ctxt->sax->processingInstruction(ctxt->userData,\n\t\t target, buf);\n\t }\n\t xmlFree(buf);\n\t} else {\n\t xmlFatalErr(ctxt, XML_ERR_PI_NOT_STARTED, NULL);\n\t}\n\tctxt->instate = state;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Make sure the parser returns when getting a Stop order\n\npatch backported from chromiun bug fixes, assuming author is Chris'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: char *suhosin_decrypt_single_cookie(char *name, int name_len, char *value, int value_len, char *key, char **where TSRMLS_DC)\n{\n\tchar buffer[4096];\n char buffer2[4096];\n int o_name_len = name_len;\n\tchar *buf = buffer, *buf2 = buffer2, *d, *d_url;\n\tint l;\n\n\tif (name_len > sizeof(buffer)-2) {\n\t\tbuf = estrndup(name, name_len);\n\t} else {\n\t\tmemcpy(buf, name, name_len);\n\t\tbuf[name_len] = 0;\n\t}\n\t\n\tname_len = php_url_decode(buf, name_len);\n normalize_varname(buf);\n name_len = strlen(buf);\n\t\n\tif (SUHOSIN_G(cookie_plainlist)) {\n\t\tif (zend_hash_exists(SUHOSIN_G(cookie_plainlist), buf, name_len+1)) {\ndecrypt_return_plain:\n\t\t\tif (buf != buffer) {\n\t\t\t\tefree(buf);\n\t\t\t}\n memcpy(*where, name, o_name_len);\n *where += o_name_len;\n **where = '='; *where +=1;\n\t memcpy(*where, value, value_len);\n\t *where += value_len;\n\t\t\treturn *where;\n\t\t}\n\t} else if (SUHOSIN_G(cookie_cryptlist)) {\n\t\tif (!zend_hash_exists(SUHOSIN_G(cookie_cryptlist), buf, name_len+1)) {\n\t\t\tgoto decrypt_return_plain;\n\t\t}\n\t}\n\t\n\t\n\tif (strlen(value) <= sizeof(buffer2)-2) {\n\t\tmemcpy(buf2, value, value_len);\n\t\tbuf2[value_len] = 0;\n\t} else {\n\t\tbuf2 = estrndup(value, value_len);\n\t}\n\t\n\tvalue_len = php_url_decode(buf2, value_len);\n\t\n\td = suhosin_decrypt_string(buf2, value_len, buf, name_len, key, &l, SUHOSIN_G(cookie_checkraddr) TSRMLS_CC);\n if (d == NULL) {\n goto skip_cookie;\n }\n\td_url = php_url_encode(d, l, &l);\n\tefree(d);\n memcpy(*where, name, o_name_len);\n *where += o_name_len;\n **where = '=';*where += 1;\n\tmemcpy(*where, d_url, l);\n\t*where += l;\n\tefree(d_url);\nskip_cookie:\n\tif (buf != buffer) {\n\t\tefree(buf);\n\t}\n\tif (buf2 != buffer2) {\n\t\tefree(buf2);\n\t}\n\treturn *where;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fixed stack based buffer overflow in transparent cookie encryption (see separate advisory)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: xmlDictComputeBigKey(const xmlChar* data, int namelen) {\n uint32_t hash;\n int i;\n\n if (namelen <= 0 || data == NULL) return(0);\n\n hash = 0;\n\n for (i = 0;i < namelen; i++) {\n hash += data[i];\n\thash += (hash << 10);\n\thash ^= (hash >> 6);\n }\n hash += (hash << 3);\n hash ^= (hash >> 11);\n hash += (hash << 15);\n\n return hash;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'Add hash randomization to hash and dict structures\n\nFollowing http://www.ocert.org/advisories/ocert-2011-003.html\nit seems that having hash randomization might be a good idea\nwhen using XML with untrusted data\n* configure.in: lookup for rand, srand and time\n* dict.c: add randomization to dictionaries hash tables\n* hash.c: add randomization to normal hash tables'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline void preempt_conditional_cli(struct pt_regs *regs)\n{\n\tif (regs->flags & X86_EFLAGS_IF)\n\t\tlocal_irq_disable();\n\tdec_preempt_count();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': 'x86: Do not disable preemption in int3 on 32bit\n\nPreemption must be disabled before enabling interrupts in do_trap\non x86_64 because the stack in use for int3 and debug is a per CPU\nstack set by th IST. But 32bit does not have an IST and the stack\nstill belongs to the current task and there is no problem in scheduling\nout the task.\n\nKeep preemption enabled on X86_32 when enabling interrupts for\ndo_trap().\n\nThe name of the function is changed from preempt_conditional_sti/cli()\nto conditional_sti/cli_ist(), to annotate that this function is used\nwhen the stack is on the IST.\n\nCc: stable-rt@vger.kernel.org\nSigned-off-by: Steven Rostedt \nSigned-off-by: Thomas Gleixner '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: peek_for_as4_capability (struct peer *peer, u_char length)\n{\n struct stream *s = BGP_INPUT (peer);\n size_t orig_getp = stream_get_getp (s);\n size_t end = orig_getp + length;\n as_t as4 = 0;\n \n /* The full capability parser will better flag the error.. */\n if (STREAM_READABLE(s) < length)\n return 0;\n\n if (BGP_DEBUG (as4, AS4))\n zlog_info (\"%s [AS4] rcv OPEN w/ OPTION parameter len: %u,\"\n \" peeking for as4\",\n\t peer->host, length);\n /* the error cases we DONT handle, we ONLY try to read as4 out of\n * correctly formatted options.\n */\n while (stream_get_getp(s) < end) \n {\n u_char opt_type;\n u_char opt_length;\n \n /* Check the length. */\n if (stream_get_getp (s) + 2 > end)\n goto end;\n \n /* Fetch option type and length. */\n opt_type = stream_getc (s);\n opt_length = stream_getc (s);\n \n /* Option length check. */\n if (stream_get_getp (s) + opt_length > end)\n goto end;\n \n if (opt_type == BGP_OPEN_OPT_CAP)\n {\n unsigned long capd_start = stream_get_getp (s);\n unsigned long capd_end = capd_start + opt_length;\n \n assert (capd_end <= end);\n \n\t while (stream_get_getp (s) < capd_end)\n\t {\n\t struct capability_header hdr;\n\t \n\t if (stream_get_getp (s) + 2 > capd_end)\n goto end;\n \n hdr.code = stream_getc (s);\n hdr.length = stream_getc (s);\n \n\t if ((stream_get_getp(s) + hdr.length) > capd_end)\n\t\tgoto end;\n\n\t if (hdr.code == CAPABILITY_CODE_AS4)\n\t {\n\t if (hdr.length != CAPABILITY_CODE_AS4_LEN)\n\t goto end;\n \n\t if (BGP_DEBUG (as4, AS4))\n\t zlog_info (\"[AS4] found AS4 capability, about to parse\");\n\t as4 = bgp_capability_as4 (peer, &hdr);\n\t \n\t goto end;\n }\n stream_forward_getp (s, hdr.length);\n\t }\n\t}\n }\n\nend:\n stream_set_getp (s, orig_getp);\n return as4;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'bgpd: Open option parse errors don't NOTIFY, resulting in abort & DoS\n\n* bgp_packet.c: (bgp_open_receive) Errors from bgp_open_option_parse are\n detected, and the code will stop processing the OPEN and return. However\n it does so without calling bgp_notify_send to send a NOTIFY - which means\n the peer FSM doesn't get stopped, and bgp_read will be called again later.\n Because it returns, it doesn't go through the code near the end of the\n function that removes the current message from the peer input streaam.\n Thus the next call to bgp_read will try to parse a half-parsed stream as\n if it were a new BGP message, leading to an assert later in the code when\n it tries to read stuff that isn't there. Add the required call to\n bgp_notify_send before returning.\n* bgp_open.c: (bgp_capability_as4) Be a bit stricter, check the length field\n corresponds to the only value it can be, which is the amount we're going to\n read off the stream. And make sure the capability flag gets set, so\n callers can know this capability was read, regardless.\n (peek_for_as4_capability) Let bgp_capability_as4 do the length check.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int pagemap_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end,\n\t\t\t struct mm_walk *walk)\n{\n\tstruct vm_area_struct *vma;\n\tstruct pagemapread *pm = walk->private;\n\tpte_t *pte;\n\tint err = 0;\n\n\tsplit_huge_page_pmd(walk->mm, pmd);\n\n\t/* find the first VMA at or above 'addr' */\n\tvma = find_vma(walk->mm, addr);\n\tfor (; addr != end; addr += PAGE_SIZE) {\n\t\tu64 pfn = PM_NOT_PRESENT;\n\n\t\t/* check to see if we've left 'vma' behind\n\t\t * and need a new, higher one */\n\t\tif (vma && (addr >= vma->vm_end))\n\t\t\tvma = find_vma(walk->mm, addr);\n\n\t\t/* check that 'vma' actually covers this address,\n\t\t * and that it isn't a huge page vma */\n\t\tif (vma && (vma->vm_start <= addr) &&\n\t\t !is_vm_hugetlb_page(vma)) {\n\t\t\tpte = pte_offset_map(pmd, addr);\n\t\t\tpfn = pte_to_pagemap_entry(*pte);\n\t\t\t/* unmap before userspace copy */\n\t\t\tpte_unmap(pte);\n\t\t}\n\t\terr = add_to_pagemap(addr, pfn, pm);\n\t\tif (err)\n\t\t\treturn err;\n\t}\n\n\tcond_resched();\n\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode\n\nIn some cases it may happen that pmd_none_or_clear_bad() is called with\nthe mmap_sem hold in read mode. In those cases the huge page faults can\nallocate hugepmds under pmd_none_or_clear_bad() and that can trigger a\nfalse positive from pmd_bad() that will not like to see a pmd\nmaterializing as trans huge.\n\nIt's not khugepaged causing the problem, khugepaged holds the mmap_sem\nin write mode (and all those sites must hold the mmap_sem in read mode\nto prevent pagetables to go away from under them, during code review it\nseems vm86 mode on 32bit kernels requires that too unless it's\nrestricted to 1 thread per process or UP builds). The race is only with\nthe huge pagefaults that can convert a pmd_none() into a\npmd_trans_huge().\n\nEffectively all these pmd_none_or_clear_bad() sites running with\nmmap_sem in read mode are somewhat speculative with the page faults, and\nthe result is always undefined when they run simultaneously. This is\nprobably why it wasn't common to run into this. For example if the\nmadvise(MADV_DONTNEED) runs zap_page_range() shortly before the page\nfault, the hugepage will not be zapped, if the page fault runs first it\nwill be zapped.\n\nAltering pmd_bad() not to error out if it finds hugepmds won't be enough\nto fix this, because zap_pmd_range would then proceed to call\nzap_pte_range (which would be incorrect if the pmd become a\npmd_trans_huge()).\n\nThe simplest way to fix this is to read the pmd in the local stack\n(regardless of what we read, no need of actual CPU barriers, only\ncompiler barrier needed), and be sure it is not changing under the code\nthat computes its value. Even if the real pmd is changing under the\nvalue we hold on the stack, we don't care. If we actually end up in\nzap_pte_range it means the pmd was not none already and it was not huge,\nand it can't become huge from under us (khugepaged locking explained\nabove).\n\nAll we need is to enforce that there is no way anymore that in a code\npath like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad\ncan run into a hugepmd. The overhead of a barrier() is just a compiler\ntweak and should not be measurable (I only added it for THP builds). I\ndon't exclude different compiler versions may have prevented the race\ntoo by caching the value of *pmd on the stack (that hasn't been\nverified, but it wouldn't be impossible considering\npmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines\nand there's no external function called in between pmd_trans_huge and\npmd_none_or_clear_bad).\n\n\t\tif (pmd_trans_huge(*pmd)) {\n\t\t\tif (next-addr != HPAGE_PMD_SIZE) {\n\t\t\t\tVM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem));\n\t\t\t\tsplit_huge_page_pmd(vma->vm_mm, pmd);\n\t\t\t} else if (zap_huge_pmd(tlb, vma, pmd, addr))\n\t\t\t\tcontinue;\n\t\t\t/* fall through */\n\t\t}\n\t\tif (pmd_none_or_clear_bad(pmd))\n\nBecause this race condition could be exercised without special\nprivileges this was reported in CVE-2012-1179.\n\nThe race was identified and fully explained by Ulrich who debugged it.\nI'm quoting his accurate explanation below, for reference.\n\n====== start quote =======\n mapcount 0 page_mapcount 1\n kernel BUG at mm/huge_memory.c:1384!\n\n At some point prior to the panic, a \"bad pmd ...\" message similar to the\n following is logged on the console:\n\n mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7).\n\n The \"bad pmd ...\" message is logged by pmd_clear_bad() before it clears\n the page's PMD table entry.\n\n 143 void pmd_clear_bad(pmd_t *pmd)\n 144 {\n -> 145 pmd_ERROR(*pmd);\n 146 pmd_clear(pmd);\n 147 }\n\n After the PMD table entry has been cleared, there is an inconsistency\n between the actual number of PMD table entries that are mapping the page\n and the page's map count (_mapcount field in struct page). When the page\n is subsequently reclaimed, __split_huge_page() detects this inconsistency.\n\n 1381 if (mapcount != page_mapcount(page))\n 1382 printk(KERN_ERR \"mapcount %d page_mapcount %d\\n\",\n 1383 mapcount, page_mapcount(page));\n -> 1384 BUG_ON(mapcount != page_mapcount(page));\n\n The root cause of the problem is a race of two threads in a multithreaded\n process. Thread B incurs a page fault on a virtual address that has never\n been accessed (PMD entry is zero) while Thread A is executing an madvise()\n system call on a virtual address within the same 2 MB (huge page) range.\n\n virtual address space\n .---------------------.\n | |\n | |\n .-|---------------------|\n | | |\n | | |<-- B(fault)\n | | |\n 2 MB | |/////////////////////|-.\n huge < |/////////////////////| > A(range)\n page | |/////////////////////|-'\n | | |\n | | |\n '-|---------------------|\n | |\n | |\n '---------------------'\n\n - Thread A is executing an madvise(..., MADV_DONTNEED) system call\n on the virtual address range \"A(range)\" shown in the picture.\n\n sys_madvise\n // Acquire the semaphore in shared mode.\n down_read(¤t->mm->mmap_sem)\n ...\n madvise_vma\n switch (behavior)\n case MADV_DONTNEED:\n madvise_dontneed\n zap_page_range\n unmap_vmas\n unmap_page_range\n zap_pud_range\n zap_pmd_range\n //\n // Assume that this huge page has never been accessed.\n // I.e. content of the PMD entry is zero (not mapped).\n //\n if (pmd_trans_huge(*pmd)) {\n // We don't get here due to the above assumption.\n }\n //\n // Assume that Thread B incurred a page fault and\n .---------> // sneaks in here as shown below.\n | //\n | if (pmd_none_or_clear_bad(pmd))\n | {\n | if (unlikely(pmd_bad(*pmd)))\n | pmd_clear_bad\n | {\n | pmd_ERROR\n | // Log \"bad pmd ...\" message here.\n | pmd_clear\n | // Clear the page's PMD entry.\n | // Thread B incremented the map count\n | // in page_add_new_anon_rmap(), but\n | // now the page is no longer mapped\n | // by a PMD entry (-> inconsistency).\n | }\n | }\n |\n v\n - Thread B is handling a page fault on virtual address \"B(fault)\" shown\n in the picture.\n\n ...\n do_page_fault\n __do_page_fault\n // Acquire the semaphore in shared mode.\n down_read_trylock(&mm->mmap_sem)\n ...\n handle_mm_fault\n if (pmd_none(*pmd) && transparent_hugepage_enabled(vma))\n // We get here due to the above assumption (PMD entry is zero).\n do_huge_pmd_anonymous_page\n alloc_hugepage_vma\n // Allocate a new transparent huge page here.\n ...\n __do_huge_pmd_anonymous_page\n ...\n spin_lock(&mm->page_table_lock)\n ...\n page_add_new_anon_rmap\n // Here we increment the page's map count (starts at -1).\n atomic_set(&page->_mapcount, 0)\n set_pmd_at\n // Here we set the page's PMD entry which will be cleared\n // when Thread A calls pmd_clear_bad().\n ...\n spin_unlock(&mm->page_table_lock)\n\n The mmap_sem does not prevent the race because both threads are acquiring\n it in shared mode (down_read). Thread B holds the page_table_lock while\n the page's map count and PMD table entry are updated. However, Thread A\n does not synchronize on that lock.\n\n====== end quote =======\n\n[akpm@linux-foundation.org: checkpatch fixes]\nReported-by: Ulrich Obergfell \nSigned-off-by: Andrea Arcangeli \nAcked-by: Johannes Weiner \nCc: Mel Gorman \nCc: Hugh Dickins \nCc: Dave Jones \nAcked-by: Larry Woodman \nAcked-by: Rik van Riel \nCc: \t\t[2.6.38+]\nCc: Mark Salter \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline unsigned long zap_pmd_range(struct mmu_gather *tlb,\n\t\t\t\tstruct vm_area_struct *vma, pud_t *pud,\n\t\t\t\tunsigned long addr, unsigned long end,\n\t\t\t\tstruct zap_details *details)\n{\n\tpmd_t *pmd;\n\tunsigned long next;\n\n\tpmd = pmd_offset(pud, addr);\n\tdo {\n\t\tnext = pmd_addr_end(addr, end);\n\t\tif (pmd_trans_huge(*pmd)) {\n\t\t\tif (next-addr != HPAGE_PMD_SIZE) {\n\t\t\t\tVM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem));\n\t\t\t\tsplit_huge_page_pmd(vma->vm_mm, pmd);\n\t\t\t} else if (zap_huge_pmd(tlb, vma, pmd, addr))\n\t\t\t\tcontinue;\n\t\t\t/* fall through */\n\t\t}\n\t\tif (pmd_none_or_clear_bad(pmd))\n\t\t\tcontinue;\n\t\tnext = zap_pte_range(tlb, vma, pmd, addr, next, details);\n\t\tcond_resched();\n\t} while (pmd++, addr = next, addr != end);\n\n\treturn addr;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode\n\nIn some cases it may happen that pmd_none_or_clear_bad() is called with\nthe mmap_sem hold in read mode. In those cases the huge page faults can\nallocate hugepmds under pmd_none_or_clear_bad() and that can trigger a\nfalse positive from pmd_bad() that will not like to see a pmd\nmaterializing as trans huge.\n\nIt's not khugepaged causing the problem, khugepaged holds the mmap_sem\nin write mode (and all those sites must hold the mmap_sem in read mode\nto prevent pagetables to go away from under them, during code review it\nseems vm86 mode on 32bit kernels requires that too unless it's\nrestricted to 1 thread per process or UP builds). The race is only with\nthe huge pagefaults that can convert a pmd_none() into a\npmd_trans_huge().\n\nEffectively all these pmd_none_or_clear_bad() sites running with\nmmap_sem in read mode are somewhat speculative with the page faults, and\nthe result is always undefined when they run simultaneously. This is\nprobably why it wasn't common to run into this. For example if the\nmadvise(MADV_DONTNEED) runs zap_page_range() shortly before the page\nfault, the hugepage will not be zapped, if the page fault runs first it\nwill be zapped.\n\nAltering pmd_bad() not to error out if it finds hugepmds won't be enough\nto fix this, because zap_pmd_range would then proceed to call\nzap_pte_range (which would be incorrect if the pmd become a\npmd_trans_huge()).\n\nThe simplest way to fix this is to read the pmd in the local stack\n(regardless of what we read, no need of actual CPU barriers, only\ncompiler barrier needed), and be sure it is not changing under the code\nthat computes its value. Even if the real pmd is changing under the\nvalue we hold on the stack, we don't care. If we actually end up in\nzap_pte_range it means the pmd was not none already and it was not huge,\nand it can't become huge from under us (khugepaged locking explained\nabove).\n\nAll we need is to enforce that there is no way anymore that in a code\npath like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad\ncan run into a hugepmd. The overhead of a barrier() is just a compiler\ntweak and should not be measurable (I only added it for THP builds). I\ndon't exclude different compiler versions may have prevented the race\ntoo by caching the value of *pmd on the stack (that hasn't been\nverified, but it wouldn't be impossible considering\npmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines\nand there's no external function called in between pmd_trans_huge and\npmd_none_or_clear_bad).\n\n\t\tif (pmd_trans_huge(*pmd)) {\n\t\t\tif (next-addr != HPAGE_PMD_SIZE) {\n\t\t\t\tVM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem));\n\t\t\t\tsplit_huge_page_pmd(vma->vm_mm, pmd);\n\t\t\t} else if (zap_huge_pmd(tlb, vma, pmd, addr))\n\t\t\t\tcontinue;\n\t\t\t/* fall through */\n\t\t}\n\t\tif (pmd_none_or_clear_bad(pmd))\n\nBecause this race condition could be exercised without special\nprivileges this was reported in CVE-2012-1179.\n\nThe race was identified and fully explained by Ulrich who debugged it.\nI'm quoting his accurate explanation below, for reference.\n\n====== start quote =======\n mapcount 0 page_mapcount 1\n kernel BUG at mm/huge_memory.c:1384!\n\n At some point prior to the panic, a \"bad pmd ...\" message similar to the\n following is logged on the console:\n\n mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7).\n\n The \"bad pmd ...\" message is logged by pmd_clear_bad() before it clears\n the page's PMD table entry.\n\n 143 void pmd_clear_bad(pmd_t *pmd)\n 144 {\n -> 145 pmd_ERROR(*pmd);\n 146 pmd_clear(pmd);\n 147 }\n\n After the PMD table entry has been cleared, there is an inconsistency\n between the actual number of PMD table entries that are mapping the page\n and the page's map count (_mapcount field in struct page). When the page\n is subsequently reclaimed, __split_huge_page() detects this inconsistency.\n\n 1381 if (mapcount != page_mapcount(page))\n 1382 printk(KERN_ERR \"mapcount %d page_mapcount %d\\n\",\n 1383 mapcount, page_mapcount(page));\n -> 1384 BUG_ON(mapcount != page_mapcount(page));\n\n The root cause of the problem is a race of two threads in a multithreaded\n process. Thread B incurs a page fault on a virtual address that has never\n been accessed (PMD entry is zero) while Thread A is executing an madvise()\n system call on a virtual address within the same 2 MB (huge page) range.\n\n virtual address space\n .---------------------.\n | |\n | |\n .-|---------------------|\n | | |\n | | |<-- B(fault)\n | | |\n 2 MB | |/////////////////////|-.\n huge < |/////////////////////| > A(range)\n page | |/////////////////////|-'\n | | |\n | | |\n '-|---------------------|\n | |\n | |\n '---------------------'\n\n - Thread A is executing an madvise(..., MADV_DONTNEED) system call\n on the virtual address range \"A(range)\" shown in the picture.\n\n sys_madvise\n // Acquire the semaphore in shared mode.\n down_read(¤t->mm->mmap_sem)\n ...\n madvise_vma\n switch (behavior)\n case MADV_DONTNEED:\n madvise_dontneed\n zap_page_range\n unmap_vmas\n unmap_page_range\n zap_pud_range\n zap_pmd_range\n //\n // Assume that this huge page has never been accessed.\n // I.e. content of the PMD entry is zero (not mapped).\n //\n if (pmd_trans_huge(*pmd)) {\n // We don't get here due to the above assumption.\n }\n //\n // Assume that Thread B incurred a page fault and\n .---------> // sneaks in here as shown below.\n | //\n | if (pmd_none_or_clear_bad(pmd))\n | {\n | if (unlikely(pmd_bad(*pmd)))\n | pmd_clear_bad\n | {\n | pmd_ERROR\n | // Log \"bad pmd ...\" message here.\n | pmd_clear\n | // Clear the page's PMD entry.\n | // Thread B incremented the map count\n | // in page_add_new_anon_rmap(), but\n | // now the page is no longer mapped\n | // by a PMD entry (-> inconsistency).\n | }\n | }\n |\n v\n - Thread B is handling a page fault on virtual address \"B(fault)\" shown\n in the picture.\n\n ...\n do_page_fault\n __do_page_fault\n // Acquire the semaphore in shared mode.\n down_read_trylock(&mm->mmap_sem)\n ...\n handle_mm_fault\n if (pmd_none(*pmd) && transparent_hugepage_enabled(vma))\n // We get here due to the above assumption (PMD entry is zero).\n do_huge_pmd_anonymous_page\n alloc_hugepage_vma\n // Allocate a new transparent huge page here.\n ...\n __do_huge_pmd_anonymous_page\n ...\n spin_lock(&mm->page_table_lock)\n ...\n page_add_new_anon_rmap\n // Here we increment the page's map count (starts at -1).\n atomic_set(&page->_mapcount, 0)\n set_pmd_at\n // Here we set the page's PMD entry which will be cleared\n // when Thread A calls pmd_clear_bad().\n ...\n spin_unlock(&mm->page_table_lock)\n\n The mmap_sem does not prevent the race because both threads are acquiring\n it in shared mode (down_read). Thread B holds the page_table_lock while\n the page's map count and PMD table entry are updated. However, Thread A\n does not synchronize on that lock.\n\n====== end quote =======\n\n[akpm@linux-foundation.org: checkpatch fixes]\nReported-by: Ulrich Obergfell \nSigned-off-by: Andrea Arcangeli \nAcked-by: Johannes Weiner \nCc: Mel Gorman \nCc: Hugh Dickins \nCc: Dave Jones \nAcked-by: Larry Woodman \nAcked-by: Rik van Riel \nCc: \t\t[2.6.38+]\nCc: Mark Salter \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: cdf_dump(void *v, size_t len)\n{\n\tsize_t i, j;\n\tunsigned char *p = v;\n\tchar abuf[16];\n\t(void)fprintf(stderr, \"%.4x: \", 0);\n\tfor (i = 0, j = 0; i < len; i++, p++) {\n\t\t(void)fprintf(stderr, \"%.2x \", *p);\n\t\tabuf[j++] = isprint(*p) ? *p : '.';\n\t\tif (j == 16) {\n\t\t\tj = 0;\n\t\t\tabuf[15] = '\\0';\n\t\t\t(void)fprintf(stderr, \"%s\\n%.4x: \", abuf, i + 1);\n\t\t}\n\t}\n\t(void)fprintf(stderr, \"\\n\");\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': '- add float and double types\n- fix debug printf formats\n- fix short stream sizes\n- don't fail if we don't know about a type'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ciphertext_to_compressed (gnutls_session_t session,\n gnutls_datum_t *ciphertext, \n uint8_t * compress_data,\n int compress_size,\n uint8_t type, record_parameters_st * params, \n uint64* sequence)\n{\n uint8_t tag[MAX_HASH_SIZE];\n uint8_t pad;\n int length, length_to_decrypt;\n uint16_t blocksize;\n int ret, i, pad_failed = 0;\n uint8_t preamble[MAX_PREAMBLE_SIZE];\n unsigned int preamble_size;\n unsigned int ver = gnutls_protocol_get_version (session);\n unsigned int tag_size = _gnutls_auth_cipher_tag_len (¶ms->read.cipher_state);\n unsigned int explicit_iv = _gnutls_version_has_explicit_iv (session->security_parameters.version);\n\n blocksize = gnutls_cipher_get_block_size (params->cipher_algorithm);\n\n /* actual decryption (inplace)\n */\n switch (_gnutls_cipher_is_block (params->cipher_algorithm))\n {\n case CIPHER_STREAM:\n /* The way AEAD ciphers are defined in RFC5246, it allows\n * only stream ciphers.\n */\n if (explicit_iv && _gnutls_auth_cipher_is_aead(¶ms->read.cipher_state))\n {\n uint8_t nonce[blocksize];\n /* Values in AEAD are pretty fixed in TLS 1.2 for 128-bit block\n */\n if (params->read.IV.data == NULL || params->read.IV.size != 4)\n return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);\n \n if (ciphertext->size < tag_size+AEAD_EXPLICIT_DATA_SIZE)\n return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH);\n\n memcpy(nonce, params->read.IV.data, AEAD_IMPLICIT_DATA_SIZE);\n memcpy(&nonce[AEAD_IMPLICIT_DATA_SIZE], ciphertext->data, AEAD_EXPLICIT_DATA_SIZE);\n \n _gnutls_auth_cipher_setiv(¶ms->read.cipher_state, nonce, AEAD_EXPLICIT_DATA_SIZE+AEAD_IMPLICIT_DATA_SIZE);\n\n ciphertext->data += AEAD_EXPLICIT_DATA_SIZE;\n ciphertext->size -= AEAD_EXPLICIT_DATA_SIZE;\n \n length_to_decrypt = ciphertext->size - tag_size;\n }\n else\n {\n if (ciphertext->size < tag_size)\n return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH);\n \n length_to_decrypt = ciphertext->size;\n }\n\n length = ciphertext->size - tag_size;\n\n /* Pass the type, version, length and compressed through\n * MAC.\n */\n preamble_size =\n make_preamble (UINT64DATA(*sequence), type,\n length, ver, preamble);\n\n ret = _gnutls_auth_cipher_add_auth (¶ms->read.cipher_state, preamble, preamble_size);\n if (ret < 0)\n return gnutls_assert_val(ret);\n\n if ((ret =\n _gnutls_auth_cipher_decrypt2 (¶ms->read.cipher_state,\n ciphertext->data, length_to_decrypt,\n ciphertext->data, ciphertext->size)) < 0)\n return gnutls_assert_val(ret);\n\n break;\n case CIPHER_BLOCK:\n if (ciphertext->size < MAX(blocksize, tag_size) || (ciphertext->size % blocksize != 0))\n return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH);\n\n /* ignore the IV in TLS 1.1+\n */\n if (explicit_iv)\n {\n _gnutls_auth_cipher_setiv(¶ms->read.cipher_state,\n ciphertext->data, blocksize);\n\n ciphertext->size -= blocksize;\n ciphertext->data += blocksize;\n\n if (ciphertext->size == 0)\n {\n gnutls_assert ();\n return GNUTLS_E_DECRYPTION_FAILED;\n }\n }\n\n /* we don't use the auth_cipher interface here, since\n * TLS with block ciphers is impossible to be used under such\n * an API. (the length of plaintext is required to calculate\n * auth_data, but it is not available before decryption).\n */\n if ((ret =\n _gnutls_cipher_decrypt (¶ms->read.cipher_state.cipher,\n ciphertext->data, ciphertext->size)) < 0)\n return gnutls_assert_val(ret);\n\n pad = ciphertext->data[ciphertext->size - 1] + 1; /* pad */\n\n if ((int) pad > (int) ciphertext->size - tag_size)\n {\n gnutls_assert ();\n _gnutls_record_log\n (\"REC[%p]: Short record length %d > %d - %d (under attack?)\\n\",\n session, pad, ciphertext->size, tag_size);\n /* We do not fail here. We check below for the\n * the pad_failed. If zero means success.\n */\n pad_failed = GNUTLS_E_DECRYPTION_FAILED;\n pad %= blocksize;\n }\n\n length = ciphertext->size - tag_size - pad;\n\n /* Check the pading bytes (TLS 1.x)\n */\n if (ver != GNUTLS_SSL3)\n for (i = 2; i < pad; i++)\n {\n if (ciphertext->data[ciphertext->size - i] !=\n ciphertext->data[ciphertext->size - 1])\n pad_failed = GNUTLS_E_DECRYPTION_FAILED;\n }\n\n if (length < 0)\n {\n /* Setting a proper length to prevent timing differences in\n * processing of records with invalid encryption.\n */\n length = ciphertext->size - tag_size;\n }\n\n /* Pass the type, version, length and compressed through\n * MAC.\n */\n preamble_size =\n make_preamble (UINT64DATA(*sequence), type,\n length, ver, preamble);\n ret = _gnutls_auth_cipher_add_auth (¶ms->read.cipher_state, preamble, preamble_size);\n if (ret < 0)\n return gnutls_assert_val(ret);\n\n ret = _gnutls_auth_cipher_add_auth (¶ms->read.cipher_state, ciphertext->data, length);\n if (ret < 0)\n return gnutls_assert_val(ret);\n\n break;\n default:\n return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);\n }\n\n ret = _gnutls_auth_cipher_tag(¶ms->read.cipher_state, tag, tag_size);\n if (ret < 0)\n return gnutls_assert_val(ret);\n\n /* This one was introduced to avoid a timing attack against the TLS\n * 1.0 protocol.\n */\n /* HMAC was not the same. \n */\n if (memcmp (tag, &ciphertext->data[length], tag_size) != 0 || pad_failed != 0)\n return gnutls_assert_val(GNUTLS_E_DECRYPTION_FAILED);\n\n /* copy the decrypted stuff to compress_data.\n */\n if (compress_size < length)\n return gnutls_assert_val(GNUTLS_E_DECOMPRESSION_FAILED);\n\n if (compress_data != ciphertext->data)\n memcpy (compress_data, ciphertext->data, length);\n\n return length;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'changes in packet parsing.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int phar_parse_tarfile(php_stream* fp, char *fname, int fname_len, char *alias, int alias_len, phar_archive_data** pphar, int is_data, php_uint32 compression, char **error TSRMLS_DC) /* {{{ */\n{\n\tchar buf[512], *actual_alias = NULL, *p;\n\tphar_entry_info entry = {0};\n\tsize_t pos = 0, read, totalsize;\n\ttar_header *hdr;\n\tphp_uint32 sum1, sum2, size, old;\n\tphar_archive_data *myphar, **actual;\n\tint last_was_longlink = 0;\n\n\tif (error) {\n\t\t*error = NULL;\n\t}\n\n\tphp_stream_seek(fp, 0, SEEK_END);\n\ttotalsize = php_stream_tell(fp);\n\tphp_stream_seek(fp, 0, SEEK_SET);\n\tread = php_stream_read(fp, buf, sizeof(buf));\n\n\tif (read != sizeof(buf)) {\n\t\tif (error) {\n\t\t\tspprintf(error, 4096, \"phar error: \\\"%s\\\" is not a tar file or is truncated\", fname);\n\t\t}\n\t\tphp_stream_close(fp);\n\t\treturn FAILURE;\n\t}\n\n\thdr = (tar_header*)buf;\n\told = (memcmp(hdr->magic, \"ustar\", sizeof(\"ustar\")-1) != 0);\n\n\tmyphar = (phar_archive_data *) pecalloc(1, sizeof(phar_archive_data), PHAR_G(persist));\n\tmyphar->is_persistent = PHAR_G(persist);\n\t/* estimate number of entries, can't be certain with tar files */\n\tzend_hash_init(&myphar->manifest, 2 + (totalsize >> 12),\n\t\tzend_get_hash_value, destroy_phar_manifest_entry, (zend_bool)myphar->is_persistent);\n\tzend_hash_init(&myphar->mounted_dirs, 5,\n\t\tzend_get_hash_value, NULL, (zend_bool)myphar->is_persistent);\n\tzend_hash_init(&myphar->virtual_dirs, 4 + (totalsize >> 11),\n\t\tzend_get_hash_value, NULL, (zend_bool)myphar->is_persistent);\n\tmyphar->is_tar = 1;\n\t/* remember whether this entire phar was compressed with gz/bzip2 */\n\tmyphar->flags = compression;\n\n\tentry.is_tar = 1;\n\tentry.is_crc_checked = 1;\n\tentry.phar = myphar;\n\tpos += sizeof(buf);\n\n\tdo {\n\t\tphar_entry_info *newentry;\n\n\t\tpos = php_stream_tell(fp);\n\t\thdr = (tar_header*) buf;\n\t\tsum1 = phar_tar_number(hdr->checksum, sizeof(hdr->checksum));\n\t\tif (sum1 == 0 && phar_tar_checksum(buf, sizeof(buf)) == 0) {\n\t\t\tbreak;\n\t\t}\n\t\tmemset(hdr->checksum, ' ', sizeof(hdr->checksum));\n\t\tsum2 = phar_tar_checksum(buf, old?sizeof(old_tar_header):sizeof(tar_header));\n\n\t\tsize = entry.uncompressed_filesize = entry.compressed_filesize =\n\t\t\tphar_tar_number(hdr->size, sizeof(hdr->size));\n\n\t\tif (((!old && hdr->prefix[0] == 0) || old) && strlen(hdr->name) == sizeof(\".phar/signature.bin\")-1 && !strncmp(hdr->name, \".phar/signature.bin\", sizeof(\".phar/signature.bin\")-1)) {\n\t\t\toff_t curloc;\n\n\t\t\tif (size > 511) {\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 4096, \"phar error: tar-based phar \\\"%s\\\" has signature that is larger than 511 bytes, cannot process\", fname);\n\t\t\t\t}\nbail:\n\t\t\t\tphp_stream_close(fp);\n\t\t\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\t\t\tcurloc = php_stream_tell(fp);\n\t\t\tread = php_stream_read(fp, buf, size);\n\t\t\tif (read != size) {\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 4096, \"phar error: tar-based phar \\\"%s\\\" signature cannot be read\", fname);\n\t\t\t\t}\n\t\t\t\tgoto bail;\n\t\t\t}\n#ifdef WORDS_BIGENDIAN\n# define PHAR_GET_32(buffer) \\\n\t(((((unsigned char*)(buffer))[3]) << 24) \\\n\t\t| ((((unsigned char*)(buffer))[2]) << 16) \\\n\t\t| ((((unsigned char*)(buffer))[1]) << 8) \\\n\t\t| (((unsigned char*)(buffer))[0]))\n#else\n# define PHAR_GET_32(buffer) (php_uint32) *(buffer)\n#endif\n\t\t\tmyphar->sig_flags = PHAR_GET_32(buf);\n\t\t\tif (FAILURE == phar_verify_signature(fp, php_stream_tell(fp) - size - 512, myphar->sig_flags, buf + 8, size - 8, fname, &myphar->signature, &myphar->sig_len, error TSRMLS_CC)) {\n\t\t\t\tif (error) {\n\t\t\t\t\tchar *save = *error;\n\t\t\t\t\tspprintf(error, 4096, \"phar error: tar-based phar \\\"%s\\\" signature cannot be verified: %s\", fname, save);\n\t\t\t\t\tefree(save);\n\t\t\t\t}\n\t\t\t\tgoto bail;\n\t\t\t}\n\t\t\tphp_stream_seek(fp, curloc + 512, SEEK_SET);\n\t\t\t/* signature checked out, let's ensure this is the last file in the phar */\n\t\t\tif (((hdr->typeflag == '\\0') || (hdr->typeflag == TAR_FILE)) && size > 0) {\n\t\t\t\t/* this is not good enough - seek succeeds even on truncated tars */\n\t\t\t\tphp_stream_seek(fp, 512, SEEK_CUR);\n\t\t\t\tif ((uint)php_stream_tell(fp) > totalsize) {\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\tspprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (truncated)\", fname);\n\t\t\t\t\t}\n\t\t\t\t\tphp_stream_close(fp);\n\t\t\t\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\t\t\t\treturn FAILURE;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tread = php_stream_read(fp, buf, sizeof(buf));\n\n\t\t\tif (read != sizeof(buf)) {\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (truncated)\", fname);\n\t\t\t\t}\n\t\t\t\tphp_stream_close(fp);\n\t\t\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\n\t\t\thdr = (tar_header*) buf;\n\t\t\tsum1 = phar_tar_number(hdr->checksum, sizeof(hdr->checksum));\n\n\t\t\tif (sum1 == 0 && phar_tar_checksum(buf, sizeof(buf)) == 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (error) {\n\t\t\t\tspprintf(error, 4096, \"phar error: \\\"%s\\\" has entries after signature, invalid phar\", fname);\n\t\t\t}\n\n\t\t\tgoto bail;\n\t\t}\n\n\t\tif (!last_was_longlink && hdr->typeflag == 'L') {\n\t\t\tlast_was_longlink = 1;\n\t\t\t/* support the ././@LongLink system for storing long filenames */\n\t\t\tentry.filename_len = entry.uncompressed_filesize;\n\n\t\t\t/* Check for overflow - bug 61065 */\n\t\t\tif (entry.filename_len == UINT_MAX) {\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (invalid entry size)\", fname);\n\t\t\t\t}\n\t\t\t\tphp_stream_close(fp);\n\t\t\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\t\t\tentry.filename = pemalloc(entry.filename_len+1, myphar->is_persistent);\n\n\t\t\tread = php_stream_read(fp, entry.filename, entry.filename_len);\n\t\t\tif (read != entry.filename_len) {\n\t\t\t\tefree(entry.filename);\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (truncated)\", fname);\n\t\t\t\t}\n\t\t\t\tphp_stream_close(fp);\n\t\t\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\t\t\tentry.filename[entry.filename_len] = '\\0';\n\n\t\t\t/* skip blank stuff */\n\t\t\tsize = ((size+511)&~511) - size;\n\n\t\t\t/* this is not good enough - seek succeeds even on truncated tars */\n\t\t\tphp_stream_seek(fp, size, SEEK_CUR);\n\t\t\tif ((uint)php_stream_tell(fp) > totalsize) {\n\t\t\t\tefree(entry.filename);\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (truncated)\", fname);\n\t\t\t\t}\n\t\t\t\tphp_stream_close(fp);\n\t\t\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\n\t\t\tread = php_stream_read(fp, buf, sizeof(buf));\n\t\n\t\t\tif (read != sizeof(buf)) {\n\t\t\t\tefree(entry.filename);\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (truncated)\", fname);\n\t\t\t\t}\n\t\t\t\tphp_stream_close(fp);\n\t\t\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\t\t\tcontinue;\n\t\t} else if (!last_was_longlink && !old && hdr->prefix[0] != 0) {\n\t\t\tchar name[256];\n\t\t\tint i, j;\n\n\t\t\tfor (i = 0; i < 155; i++) {\n\t\t\t\tname[i] = hdr->prefix[i];\n\t\t\t\tif (name[i] == '\\0') {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tname[i++] = '/';\n\t\t\tfor (j = 0; j < 100; j++) {\n\t\t\t\tname[i+j] = hdr->name[j];\n\t\t\t\tif (name[i+j] == '\\0') {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tentry.filename_len = i+j;\n\n\t\t\tif (name[entry.filename_len - 1] == '/') {\n\t\t\t\t/* some tar programs store directories with trailing slash */\n\t\t\t\tentry.filename_len--;\n\t\t\t}\n\t\t\tentry.filename = pestrndup(name, entry.filename_len, myphar->is_persistent);\n\t\t} else if (!last_was_longlink) {\n\t\t\tint i;\n\n\t\t\t/* calculate strlen, which can be no longer than 100 */\n\t\t\tfor (i = 0; i < 100; i++) {\n\t\t\t\tif (hdr->name[i] == '\\0') {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tentry.filename_len = i;\n\t\t\tentry.filename = pestrndup(hdr->name, i, myphar->is_persistent);\n\n\t\t\tif (entry.filename[entry.filename_len - 1] == '/') {\n\t\t\t\t/* some tar programs store directories with trailing slash */\n\t\t\t\tentry.filename[entry.filename_len - 1] = '\\0';\n\t\t\t\tentry.filename_len--;\n\t\t\t}\n\t\t}\n\t\tlast_was_longlink = 0;\n\n\t\tphar_add_virtual_dirs(myphar, entry.filename, entry.filename_len TSRMLS_CC);\n\n\t\tif (sum1 != sum2) {\n\t\t\tif (error) {\n\t\t\t\tspprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (checksum mismatch of file \\\"%s\\\")\", fname, entry.filename);\n\t\t\t}\n\t\t\tpefree(entry.filename, myphar->is_persistent);\n\t\t\tphp_stream_close(fp);\n\t\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\t\treturn FAILURE;\n\t\t}\n\n\t\tentry.tar_type = ((old & (hdr->typeflag == '\\0')) ? TAR_FILE : hdr->typeflag);\n\t\tentry.offset = entry.offset_abs = pos; /* header_offset unused in tar */\n\t\tentry.fp_type = PHAR_FP;\n\t\tentry.flags = phar_tar_number(hdr->mode, sizeof(hdr->mode)) & PHAR_ENT_PERM_MASK;\n\t\tentry.timestamp = phar_tar_number(hdr->mtime, sizeof(hdr->mtime));\n\t\tentry.is_persistent = myphar->is_persistent;\n#ifndef S_ISDIR\n#define S_ISDIR(mode)\t(((mode)&S_IFMT) == S_IFDIR)\n#endif\n\t\tif (old && entry.tar_type == TAR_FILE && S_ISDIR(entry.flags)) {\n\t\t\tentry.tar_type = TAR_DIR;\n\t\t}\n\n\t\tif (entry.tar_type == TAR_DIR) {\n\t\t\tentry.is_dir = 1;\n\t\t} else {\n\t\t\tentry.is_dir = 0;\n\t\t}\n\n\t\tentry.link = NULL;\n\n\t\tif (entry.tar_type == TAR_LINK) {\n\t\t\tif (!zend_hash_exists(&myphar->manifest, hdr->linkname, strlen(hdr->linkname))) {\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file - hard link to non-existent file \\\"%s\\\"\", fname, hdr->linkname);\n\t\t\t\t}\n\t\t\t\tpefree(entry.filename, entry.is_persistent);\n\t\t\t\tphp_stream_close(fp);\n\t\t\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\t\t\tentry.link = estrdup(hdr->linkname);\n\t\t} else if (entry.tar_type == TAR_SYMLINK) {\n\t\t\tentry.link = estrdup(hdr->linkname);\n\t\t}\n\t\tphar_set_inode(&entry TSRMLS_CC);\n\t\tzend_hash_add(&myphar->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info), (void **) &newentry);\n\n\t\tif (entry.is_persistent) {\n\t\t\t++entry.manifest_pos;\n\t\t}\n\n\t\tif (entry.filename_len >= sizeof(\".phar/.metadata\")-1 && !memcmp(entry.filename, \".phar/.metadata\", sizeof(\".phar/.metadata\")-1)) {\n\t\t\tif (FAILURE == phar_tar_process_metadata(newentry, fp TSRMLS_CC)) {\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 4096, \"phar error: tar-based phar \\\"%s\\\" has invalid metadata in magic file \\\"%s\\\"\", fname, entry.filename);\n\t\t\t\t}\n\t\t\t\tphp_stream_close(fp);\n\t\t\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\t\t}\n\n\t\tif (!actual_alias && entry.filename_len == sizeof(\".phar/alias.txt\")-1 && !strncmp(entry.filename, \".phar/alias.txt\", sizeof(\".phar/alias.txt\")-1)) {\n\t\t\t/* found explicit alias */\n\t\t\tif (size > 511) {\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 4096, \"phar error: tar-based phar \\\"%s\\\" has alias that is larger than 511 bytes, cannot process\", fname);\n\t\t\t\t}\n\t\t\t\tphp_stream_close(fp);\n\t\t\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\n\t\t\tread = php_stream_read(fp, buf, size);\n\n\t\t\tif (read == size) {\n\t\t\t\tbuf[size] = '\\0';\n\t\t\t\tif (!phar_validate_alias(buf, size)) {\n\t\t\t\t\tif (size > 50) {\n\t\t\t\t\t\tbuf[50] = '.';\n\t\t\t\t\t\tbuf[51] = '.';\n\t\t\t\t\t\tbuf[52] = '.';\n\t\t\t\t\t\tbuf[53] = '\\0';\n\t\t\t\t\t}\n\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\tspprintf(error, 4096, \"phar error: invalid alias \\\"%s\\\" in tar-based phar \\\"%s\\\"\", buf, fname);\n\t\t\t\t\t}\n\n\t\t\t\t\tphp_stream_close(fp);\n\t\t\t\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\t\t\t\treturn FAILURE;\n\t\t\t\t}\n\n\t\t\t\tactual_alias = pestrndup(buf, size, myphar->is_persistent);\n\t\t\t\tmyphar->alias = actual_alias;\n\t\t\t\tmyphar->alias_len = size;\n\t\t\t\tphp_stream_seek(fp, pos, SEEK_SET);\n\t\t\t} else {\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 4096, \"phar error: Unable to read alias from tar-based phar \\\"%s\\\"\", fname);\n\t\t\t\t}\n\n\t\t\t\tphp_stream_close(fp);\n\t\t\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\t\t}\n\n\t\tsize = (size+511)&~511;\n\n\t\tif (((hdr->typeflag == '\\0') || (hdr->typeflag == TAR_FILE)) && size > 0) {\n\t\t\t/* this is not good enough - seek succeeds even on truncated tars */\n\t\t\tphp_stream_seek(fp, size, SEEK_CUR);\n\t\t\tif ((uint)php_stream_tell(fp) > totalsize) {\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (truncated)\", fname);\n\t\t\t\t}\n\t\t\t\tphp_stream_close(fp);\n\t\t\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\t\t}\n\n\t\tread = php_stream_read(fp, buf, sizeof(buf));\n\n\t\tif (read != sizeof(buf)) {\n\t\t\tif (error) {\n\t\t\t\tspprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (truncated)\", fname);\n\t\t\t}\n\t\t\tphp_stream_close(fp);\n\t\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\t\treturn FAILURE;\n\t\t}\n\t} while (read != 0);\n\n\tif (zend_hash_exists(&(myphar->manifest), \".phar/stub.php\", sizeof(\".phar/stub.php\")-1)) {\n\t\tmyphar->is_data = 0;\n\t} else {\n\t\tmyphar->is_data = 1;\n\t}\n\n\t/* ensure signature set */\n\tif (!myphar->is_data && PHAR_G(require_hash) && !myphar->signature) {\n\t\tphp_stream_close(fp);\n\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\tif (error) {\n\t\t\tspprintf(error, 0, \"tar-based phar \\\"%s\\\" does not have a signature\", fname);\n\t\t}\n\t\treturn FAILURE;\n\t}\n\n\tmyphar->fname = pestrndup(fname, fname_len, myphar->is_persistent);\n#ifdef PHP_WIN32\n\tphar_unixify_path_separators(myphar->fname, fname_len);\n#endif\n\tmyphar->fname_len = fname_len;\n\tmyphar->fp = fp;\n\tp = strrchr(myphar->fname, '/');\n\n\tif (p) {\n\t\tmyphar->ext = memchr(p, '.', (myphar->fname + fname_len) - p);\n\t\tif (myphar->ext == p) {\n\t\t\tmyphar->ext = memchr(p + 1, '.', (myphar->fname + fname_len) - p - 1);\n\t\t}\n\t\tif (myphar->ext) {\n\t\t\tmyphar->ext_len = (myphar->fname + fname_len) - myphar->ext;\n\t\t}\n\t}\n\n\tphar_request_initialize(TSRMLS_C);\n\n\tif (SUCCESS != zend_hash_add(&(PHAR_GLOBALS->phar_fname_map), myphar->fname, fname_len, (void*)&myphar, sizeof(phar_archive_data*), (void **)&actual)) {\n\t\tif (error) {\n\t\t\tspprintf(error, 4096, \"phar error: Unable to add tar-based phar \\\"%s\\\" to phar registry\", fname);\n\t\t}\n\t\tphp_stream_close(fp);\n\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\treturn FAILURE;\n\t}\n\n\tmyphar = *actual;\n\n\tif (actual_alias) {\n\t\tphar_archive_data **fd_ptr;\n\n\t\tmyphar->is_temporary_alias = 0;\n\n\t\tif (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), actual_alias, myphar->alias_len, (void **)&fd_ptr)) {\n\t\t\tif (SUCCESS != phar_free_alias(*fd_ptr, actual_alias, myphar->alias_len TSRMLS_CC)) {\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 4096, \"phar error: Unable to add tar-based phar \\\"%s\\\", alias is already in use\", fname);\n\t\t\t\t}\n\t\t\t\tzend_hash_del(&(PHAR_GLOBALS->phar_fname_map), myphar->fname, fname_len);\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\t\t}\n\n\t\tzend_hash_add(&(PHAR_GLOBALS->phar_alias_map), actual_alias, myphar->alias_len, (void*)&myphar, sizeof(phar_archive_data*), NULL);\n\t} else {\n\t\tphar_archive_data **fd_ptr;\n\n\t\tif (alias_len) {\n\t\t\tif (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void **)&fd_ptr)) {\n\t\t\t\tif (SUCCESS != phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) {\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\tspprintf(error, 4096, \"phar error: Unable to add tar-based phar \\\"%s\\\", alias is already in use\", fname);\n\t\t\t\t\t}\n\t\t\t\t\tzend_hash_del(&(PHAR_GLOBALS->phar_fname_map), myphar->fname, fname_len);\n\t\t\t\t\treturn FAILURE;\n\t\t\t\t}\n\t\t\t}\n\t\t\tzend_hash_add(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void*)&myphar, sizeof(phar_archive_data*), NULL);\n\t\t\tmyphar->alias = pestrndup(alias, alias_len, myphar->is_persistent);\n\t\t\tmyphar->alias_len = alias_len;\n\t\t} else {\n\t\t\tmyphar->alias = pestrndup(myphar->fname, fname_len, myphar->is_persistent);\n\t\t\tmyphar->alias_len = fname_len;\n\t\t}\n\n\t\tmyphar->is_temporary_alias = 1;\n\t}\n\n\tif (pphar) {\n\t\t*pphar = myphar;\n\t}\n\n\treturn SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'fix unchecked emalloc'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void * calloc(size_t n, size_t lb)\n{\n if (lb && n > SIZE_MAX / lb)\n return NULL;\n# if defined(GC_LINUX_THREADS) /* && !defined(USE_PROC_FOR_LIBRARIES) */\n /* libpthread allocated some memory that is only pointed to by */\n /* mmapped thread stacks. Make sure it's not collectable. */\n {\n static GC_bool lib_bounds_set = FALSE;\n ptr_t caller = (ptr_t)__builtin_return_address(0);\n /* This test does not need to ensure memory visibility, since */\n /* the bounds will be set when/if we create another thread. */\n if (!EXPECT(lib_bounds_set, TRUE)) {\n GC_init_lib_bounds();\n lib_bounds_set = TRUE;\n }\n if (((word)caller >= (word)GC_libpthread_start\n && (word)caller < (word)GC_libpthread_end)\n || ((word)caller >= (word)GC_libld_start\n && (word)caller < (word)GC_libld_end))\n return GC_malloc_uncollectable(n*lb);\n /* The two ranges are actually usually adjacent, so there may */\n /* be a way to speed this up. */\n }\n# endif\n return((void *)REDIRECT_MALLOC(n*lb));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'Fix calloc-related code to prevent SIZE_MAX redefinition in sys headers\n\n* malloc.c: Include limits.h for SIZE_MAX.\n* malloc.c (SIZE_MAX, calloc): Define GC_SIZE_MAX instead of SIZE_MAX.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void xacct_add_tsk(struct taskstats *stats, struct task_struct *p)\n{\n\t/* convert pages-jiffies to Mbyte-usec */\n\tstats->coremem = jiffies_to_usecs(p->acct_rss_mem1) * PAGE_SIZE / MB;\n\tstats->virtmem = jiffies_to_usecs(p->acct_vm_mem1) * PAGE_SIZE / MB;\n\tif (p->mm) {\n\t\t/* adjust to KB unit */\n\t\tstats->hiwater_rss = p->mm->hiwater_rss * PAGE_SIZE / KB;\n\t\tstats->hiwater_vm = p->mm->hiwater_vm * PAGE_SIZE / KB;\n\t}\n\tstats->read_char\t= p->rchar;\n\tstats->write_char\t= p->wchar;\n\tstats->read_syscalls\t= p->syscr;\n\tstats->write_syscalls\t= p->syscw;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': '[PATCH] xacct_add_tsk: fix pure theoretical ->mm use-after-free\n\nParanoid fix. The task can free its ->mm after the 'if (p->mm)' check.\n\nSigned-off-by: Oleg Nesterov \nCc: Shailabh Nagar \nCc: Balbir Singh \nCc: Jay Lan \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int cbtls_verify(int ok, X509_STORE_CTX *ctx)\n{\n\tchar subject[1024]; /* Used for the subject name */\n\tchar issuer[1024]; /* Used for the issuer name */\n\tchar common_name[1024];\n\tchar cn_str[1024];\n\tchar buf[64];\n\tEAP_HANDLER *handler = NULL;\n\tX509 *client_cert;\n\tX509 *issuer_cert;\n\tSSL *ssl;\n\tint err, depth, lookup, loc;\n\tEAP_TLS_CONF *conf;\n\tint my_ok = ok;\n\tREQUEST *request;\n\tASN1_INTEGER *sn = NULL;\n\tASN1_TIME *asn_time = NULL;\n#ifdef HAVE_OPENSSL_OCSP_H\n\tX509_STORE *ocsp_store = NULL;\n#endif\n\n\tclient_cert = X509_STORE_CTX_get_current_cert(ctx);\n\terr = X509_STORE_CTX_get_error(ctx);\n\tdepth = X509_STORE_CTX_get_error_depth(ctx);\n\n\tlookup = depth;\n\n\t/*\n\t *\tLog client/issuing cert. If there's an error, log\n\t *\tissuing cert.\n\t */\n\tif ((lookup > 1) && !my_ok) lookup = 1;\n\n\t/*\n\t * Retrieve the pointer to the SSL of the connection currently treated\n\t * and the application specific data stored into the SSL object.\n\t */\n\tssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());\n\thandler = (EAP_HANDLER *)SSL_get_ex_data(ssl, 0);\n\trequest = handler->request;\n\tconf = (EAP_TLS_CONF *)SSL_get_ex_data(ssl, 1);\n#ifdef HAVE_OPENSSL_OCSP_H\n\tocsp_store = (X509_STORE *)SSL_get_ex_data(ssl, 2);\n#endif\n\n\n\t/*\n\t *\tGet the Serial Number\n\t */\n\tbuf[0] = '\\0';\n\tsn = X509_get_serialNumber(client_cert);\n\n\t/*\n\t *\tFor this next bit, we create the attributes *only* if\n\t *\twe're at the client or issuing certificate.\n\t */\n\tif ((lookup <= 1) && sn && (sn->length < (sizeof(buf) / 2))) {\n\t\tchar *p = buf;\n\t\tint i;\n\n\t\tfor (i = 0; i < sn->length; i++) {\n\t\t\tsprintf(p, \"%02x\", (unsigned int)sn->data[i]);\n\t\t\tp += 2;\n\t\t}\n\t\tpairadd(&handler->certs,\n\t\t\tpairmake(cert_attr_names[EAPTLS_SERIAL][lookup], buf, T_OP_SET));\n\t}\n\n\n\t/*\n\t *\tGet the Expiration Date\n\t */\n\tbuf[0] = '\\0';\n\tasn_time = X509_get_notAfter(client_cert);\n\tif ((lookup <= 1) && asn_time && (asn_time->length < MAX_STRING_LEN)) {\n\t\tmemcpy(buf, (char*) asn_time->data, asn_time->length);\n\t\tbuf[asn_time->length] = '\\0';\n\t\tpairadd(&handler->certs,\n\t\t\tpairmake(cert_attr_names[EAPTLS_EXPIRATION][lookup], buf, T_OP_SET));\n\t}\n\n\t/*\n\t *\tGet the Subject & Issuer\n\t */\n\tsubject[0] = issuer[0] = '\\0';\n\tX509_NAME_oneline(X509_get_subject_name(client_cert), subject,\n\t\t\t sizeof(subject));\n\tsubject[sizeof(subject) - 1] = '\\0';\n\tif ((lookup <= 1) && subject[0] && (strlen(subject) < MAX_STRING_LEN)) {\n\t\tpairadd(&handler->certs,\n\t\t\tpairmake(cert_attr_names[EAPTLS_SUBJECT][lookup], subject, T_OP_SET));\n\t}\n\n\tX509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), issuer,\n\t\t\t sizeof(issuer));\n\tissuer[sizeof(issuer) - 1] = '\\0';\n\tif ((lookup <= 1) && issuer[0] && (strlen(issuer) < MAX_STRING_LEN)) {\n\t\tpairadd(&handler->certs,\n\t\t\tpairmake(cert_attr_names[EAPTLS_ISSUER][lookup], issuer, T_OP_SET));\n\t}\n\n\t/*\n\t *\tGet the Common Name, if there is a subject.\n\t */\n\tX509_NAME_get_text_by_NID(X509_get_subject_name(client_cert),\n\t\t\t\t NID_commonName, common_name, sizeof(common_name));\n\tcommon_name[sizeof(common_name) - 1] = '\\0';\n\tif ((lookup <= 1) && common_name[0] && subject[0] && (strlen(common_name) < MAX_STRING_LEN)) {\n\t\tpairadd(&handler->certs,\n\t\t\tpairmake(cert_attr_names[EAPTLS_CN][lookup], common_name, T_OP_SET));\n\t}\n\n#ifdef GEN_EMAIL\n\t/*\n\t *\tGet the RFC822 Subject Alternative Name\n\t */\n\tloc = X509_get_ext_by_NID(client_cert, NID_subject_alt_name, 0);\n\tif (lookup <= 1 && loc >= 0) {\n\t\tX509_EXTENSION *ext = NULL;\n\t\tGENERAL_NAMES *names = NULL;\n\t\tint i;\n\n\t\tif ((ext = X509_get_ext(client_cert, loc)) &&\n\t\t (names = X509V3_EXT_d2i(ext))) {\n\t\t\tfor (i = 0; i < sk_GENERAL_NAME_num(names); i++) {\n\t\t\t\tGENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);\n\n\t\t\t\tswitch (name->type) {\n\t\t\t\tcase GEN_EMAIL:\n\t\t\t\t\tif (ASN1_STRING_length(name->d.rfc822Name) >= MAX_STRING_LEN)\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tpairadd(&handler->certs,\n\t\t\t\t\t\tpairmake(cert_attr_names[EAPTLS_SAN_EMAIL][lookup],\n\t\t\t\t\t\t\t ASN1_STRING_data(name->d.rfc822Name), T_OP_SET));\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\t/* XXX TODO handle other SAN types */\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (names != NULL)\n\t\t\tsk_GENERAL_NAME_free(names);\n\t}\n#endif\t/* GEN_EMAIL */\n\n\t/*\n\t *\tIf the CRL has expired, that might still be OK.\n\t */\n\tif (!my_ok &&\n\t (conf->allow_expired_crl) &&\n\t (err == X509_V_ERR_CRL_HAS_EXPIRED)) {\n\t\tmy_ok = 1;\n\t\tX509_STORE_CTX_set_error( ctx, 0 );\n\t}\n\n\tif (!my_ok) {\n\t\tconst char *p = X509_verify_cert_error_string(err);\n\t\tradlog(L_ERR,\"--> verify error:num=%d:%s\\n\",err, p);\n\t\tradius_pairmake(request, &request->packet->vps,\n\t\t\t\t\"Module-Failure-Message\", p, T_OP_SET);\n\t\treturn my_ok;\n\t}\n\n\tswitch (ctx->error) {\n\n\tcase X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:\n\t\tradlog(L_ERR, \"issuer= %s\\n\", issuer);\n\t\tbreak;\n\tcase X509_V_ERR_CERT_NOT_YET_VALID:\n\tcase X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:\n\t\tradlog(L_ERR, \"notBefore=\");\n#if 0\n\t\tASN1_TIME_print(bio_err, X509_get_notBefore(ctx->current_cert));\n#endif\n\t\tbreak;\n\tcase X509_V_ERR_CERT_HAS_EXPIRED:\n\tcase X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:\n\t\tradlog(L_ERR, \"notAfter=\");\n#if 0\n\t\tASN1_TIME_print(bio_err, X509_get_notAfter(ctx->current_cert));\n#endif\n\t\tbreak;\n\t}\n\n\t/*\n\t *\tIf we're at the actual client cert, apply additional\n\t *\tchecks.\n\t */\n\tif (depth == 0) {\n\t\t/*\n\t\t *\tIf the conf tells us to, check cert issuer\n\t\t *\tagainst the specified value and fail\n\t\t *\tverification if they don't match.\n\t\t */\n\t\tif (conf->check_cert_issuer &&\n\t\t (strcmp(issuer, conf->check_cert_issuer) != 0)) {\n\t\t\tradlog(L_AUTH, \"rlm_eap_tls: Certificate issuer (%s) does not match specified value (%s)!\", issuer, conf->check_cert_issuer);\n \t\t\tmy_ok = 0;\n \t\t}\n\n\t\t/*\n\t\t *\tIf the conf tells us to, check the CN in the\n\t\t *\tcert against xlat'ed value, but only if the\n\t\t *\tprevious checks passed.\n\t\t */\n\t\tif (my_ok && conf->check_cert_cn) {\n\t\t\tif (!radius_xlat(cn_str, sizeof(cn_str), conf->check_cert_cn, handler->request, NULL)) {\n\t\t\t\tradlog(L_ERR, \"rlm_eap_tls (%s): xlat failed.\",\n\t\t\t\t conf->check_cert_cn);\n\t\t\t\t/* if this fails, fail the verification */\n\t\t\t\tmy_ok = 0;\n\t\t\t} else {\n\t\t\t\tRDEBUG2(\"checking certificate CN (%s) with xlat'ed value (%s)\", common_name, cn_str);\n\t\t\t\tif (strcmp(cn_str, common_name) != 0) {\n\t\t\t\t\tradlog(L_AUTH, \"rlm_eap_tls: Certificate CN (%s) does not match specified value (%s)!\", common_name, cn_str);\n\t\t\t\t\tmy_ok = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t} /* check_cert_cn */\n\n#ifdef HAVE_OPENSSL_OCSP_H\n\t\tif (my_ok && conf->ocsp_enable){\n\t\t\tRDEBUG2(\"--> Starting OCSP Request\");\n\t\t\tif(X509_STORE_CTX_get1_issuer(&issuer_cert, ctx, client_cert)!=1) {\n\t\t\t\tradlog(L_ERR, \"Error: Couldn't get issuer_cert for %s\", common_name);\n\t\t\t}\n\t\t\tmy_ok = ocsp_check(ocsp_store, issuer_cert, client_cert, conf);\n\t\t}\n#endif\n\n\t\twhile (conf->verify_client_cert_cmd) {\n\t\t\tchar filename[256];\n\t\t\tint fd;\n\t\t\tFILE *fp;\n\n\t\t\tsnprintf(filename, sizeof(filename), \"%s/%s.client.XXXXXXXX\",\n\t\t\t\t conf->verify_tmp_dir, progname);\n\t\t\tfd = mkstemp(filename);\n\t\t\tif (fd < 0) {\n\t\t\t\tRDEBUG(\"Failed creating file in %s: %s\",\n\t\t\t\t conf->verify_tmp_dir, strerror(errno));\n\t\t\t\tbreak;\t\t\t\t \n\t\t\t}\n\n\t\t\tfp = fdopen(fd, \"w\");\n\t\t\tif (!fp) {\n\t\t\t\tRDEBUG(\"Failed opening file %s: %s\",\n\t\t\t\t filename, strerror(errno));\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (!PEM_write_X509(fp, client_cert)) {\n\t\t\t\tfclose(fp);\n\t\t\t\tRDEBUG(\"Failed writing certificate to file\");\n\t\t\t\tgoto do_unlink;\n\t\t\t}\n\t\t\tfclose(fp);\n\n\t\t\tif (!radius_pairmake(request, &request->packet->vps,\n\t\t\t\t\t \"TLS-Client-Cert-Filename\",\n\t\t\t\t\t filename, T_OP_SET)) {\n\t\t\t\tRDEBUG(\"Failed creating TLS-Client-Cert-Filename\");\n\t\t\t\t\n\t\t\t\tgoto do_unlink;\n\t\t\t}\n\n\t\t\tRDEBUG(\"Verifying client certificate: %s\",\n\t\t\t conf->verify_client_cert_cmd);\n\t\t\tif (radius_exec_program(conf->verify_client_cert_cmd,\n\t\t\t\t\t\trequest, 1, NULL, 0, \n\t\t\t\t\t\trequest->packet->vps,\n\t\t\t\t\t\tNULL, 1) != 0) {\n\t\t\t\tradlog(L_AUTH, \"rlm_eap_tls: Certificate CN (%s) fails external verification!\", common_name);\n\t\t\t\tmy_ok = 0;\n\t\t\t} else {\n\t\t\t\tRDEBUG(\"Client certificate CN %s passed external validation\", common_name);\n\t\t\t}\n\n\t\tdo_unlink:\n\t\t\tunlink(filename);\n\t\t\tbreak;\n\t\t}\n\n\n\t} /* depth == 0 */\n\n\tif (debug_flag > 0) {\n\t\tRDEBUG2(\"chain-depth=%d, \", depth);\n\t\tRDEBUG2(\"error=%d\", err);\n\n\t\tRDEBUG2(\"--> User-Name = %s\", handler->identity);\n\t\tRDEBUG2(\"--> BUF-Name = %s\", common_name);\n\t\tRDEBUG2(\"--> subject = %s\", subject);\n\t\tRDEBUG2(\"--> issuer = %s\", issuer);\n\t\tRDEBUG2(\"--> verify return:%d\", my_ok);\n\t}\n\treturn my_ok;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix CVE-2012-3547. Found by Timo Warns'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int ip_setup_cork(struct sock *sk, struct inet_cork *cork,\n\t\t\t struct ipcm_cookie *ipc, struct rtable **rtp)\n{\n\tstruct inet_sock *inet = inet_sk(sk);\n\tstruct ip_options *opt;\n\tstruct rtable *rt;\n\n\t/*\n\t * setup for corking.\n\t */\n\topt = ipc->opt;\n\tif (opt) {\n\t\tif (cork->opt == NULL) {\n\t\t\tcork->opt = kmalloc(sizeof(struct ip_options) + 40,\n\t\t\t\t\t sk->sk_allocation);\n\t\t\tif (unlikely(cork->opt == NULL))\n\t\t\t\treturn -ENOBUFS;\n\t\t}\n\t\tmemcpy(cork->opt, opt, sizeof(struct ip_options) + opt->optlen);\n\t\tcork->flags |= IPCORK_OPT;\n\t\tcork->addr = ipc->addr;\n\t}\n\trt = *rtp;\n\tif (unlikely(!rt))\n\t\treturn -EFAULT;\n\t/*\n\t * We steal reference to this route, caller should not release it\n\t */\n\t*rtp = NULL;\n\tcork->fragsize = inet->pmtudisc == IP_PMTUDISC_PROBE ?\n\t\t\t rt->dst.dev->mtu : dst_mtu(rt->dst.path);\n\tcork->dst = &rt->dst;\n\tcork->length = 0;\n\tcork->tx_flags = ipc->tx_flags;\n\tcork->page = NULL;\n\tcork->off = 0;\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'inet: add RCU protection to inet->opt\n\nWe lack proper synchronization to manipulate inet->opt ip_options\n\nProblem is ip_make_skb() calls ip_setup_cork() and\nip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options),\nwithout any protection against another thread manipulating inet->opt.\n\nAnother thread can change inet->opt pointer and free old one under us.\n\nUse RCU to protect inet->opt (changed to inet->inet_opt).\n\nInstead of handling atomic refcounts, just copy ip_options when\nnecessary, to avoid cache line dirtying.\n\nWe cant insert an rcu_head in struct ip_options since its included in\nskb->cb[], so this patch is large because I had to introduce a new\nip_options_rcu structure.\n\nSigned-off-by: Eric Dumazet \nCc: Herbert Xu \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int ip_options_get_finish(struct net *net, struct ip_options **optp,\n\t\t\t\t struct ip_options *opt, int optlen)\n{\n\twhile (optlen & 3)\n\t\topt->__data[optlen++] = IPOPT_END;\n\topt->optlen = optlen;\n\tif (optlen && ip_options_compile(net, opt, NULL)) {\n\t\tkfree(opt);\n\t\treturn -EINVAL;\n\t}\n\tkfree(*optp);\n\t*optp = opt;\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'inet: add RCU protection to inet->opt\n\nWe lack proper synchronization to manipulate inet->opt ip_options\n\nProblem is ip_make_skb() calls ip_setup_cork() and\nip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options),\nwithout any protection against another thread manipulating inet->opt.\n\nAnother thread can change inet->opt pointer and free old one under us.\n\nUse RCU to protect inet->opt (changed to inet->inet_opt).\n\nInstead of handling atomic refcounts, just copy ip_options when\nnecessary, to avoid cache line dirtying.\n\nWe cant insert an rcu_head in struct ip_options since its included in\nskb->cb[], so this patch is large because I had to introduce a new\nip_options_rcu structure.\n\nSigned-off-by: Eric Dumazet \nCc: Herbert Xu \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static struct rtable *icmp_route_lookup(struct net *net, struct sk_buff *skb_in,\n\t\t\t\t\tconst struct iphdr *iph,\n\t\t\t\t\t__be32 saddr, u8 tos,\n\t\t\t\t\tint type, int code,\n\t\t\t\t\tstruct icmp_bxm *param)\n{\n\tstruct flowi4 fl4 = {\n\t\t.daddr = (param->replyopts.srr ?\n\t\t\t param->replyopts.faddr : iph->saddr),\n\t\t.saddr = saddr,\n\t\t.flowi4_tos = RT_TOS(tos),\n\t\t.flowi4_proto = IPPROTO_ICMP,\n\t\t.fl4_icmp_type = type,\n\t\t.fl4_icmp_code = code,\n\t};\n\tstruct rtable *rt, *rt2;\n\tint err;\n\n\tsecurity_skb_classify_flow(skb_in, flowi4_to_flowi(&fl4));\n\trt = __ip_route_output_key(net, &fl4);\n\tif (IS_ERR(rt))\n\t\treturn rt;\n\n\t/* No need to clone since we're just using its address. */\n\trt2 = rt;\n\n\tif (!fl4.saddr)\n\t\tfl4.saddr = rt->rt_src;\n\n\trt = (struct rtable *) xfrm_lookup(net, &rt->dst,\n\t\t\t\t\t flowi4_to_flowi(&fl4), NULL, 0);\n\tif (!IS_ERR(rt)) {\n\t\tif (rt != rt2)\n\t\t\treturn rt;\n\t} else if (PTR_ERR(rt) == -EPERM) {\n\t\trt = NULL;\n\t} else\n\t\treturn rt;\n\n\terr = xfrm_decode_session_reverse(skb_in, flowi4_to_flowi(&fl4), AF_INET);\n\tif (err)\n\t\tgoto relookup_failed;\n\n\tif (inet_addr_type(net, fl4.saddr) == RTN_LOCAL) {\n\t\trt2 = __ip_route_output_key(net, &fl4);\n\t\tif (IS_ERR(rt2))\n\t\t\terr = PTR_ERR(rt2);\n\t} else {\n\t\tstruct flowi4 fl4_2 = {};\n\t\tunsigned long orefdst;\n\n\t\tfl4_2.daddr = fl4.saddr;\n\t\trt2 = ip_route_output_key(net, &fl4_2);\n\t\tif (IS_ERR(rt2)) {\n\t\t\terr = PTR_ERR(rt2);\n\t\t\tgoto relookup_failed;\n\t\t}\n\t\t/* Ugh! */\n\t\torefdst = skb_in->_skb_refdst; /* save old refdst */\n\t\terr = ip_route_input(skb_in, fl4.daddr, fl4.saddr,\n\t\t\t\t RT_TOS(tos), rt2->dst.dev);\n\n\t\tdst_release(&rt2->dst);\n\t\trt2 = skb_rtable(skb_in);\n\t\tskb_in->_skb_refdst = orefdst; /* restore old refdst */\n\t}\n\n\tif (err)\n\t\tgoto relookup_failed;\n\n\trt2 = (struct rtable *) xfrm_lookup(net, &rt2->dst,\n\t\t\t\t\t flowi4_to_flowi(&fl4), NULL,\n\t\t\t\t\t XFRM_LOOKUP_ICMP);\n\tif (!IS_ERR(rt2)) {\n\t\tdst_release(&rt->dst);\n\t\trt = rt2;\n\t} else if (PTR_ERR(rt2) == -EPERM) {\n\t\tif (rt)\n\t\t\tdst_release(&rt->dst);\n\t\treturn rt2;\n\t} else {\n\t\terr = PTR_ERR(rt2);\n\t\tgoto relookup_failed;\n\t}\n\treturn rt;\n\nrelookup_failed:\n\tif (rt)\n\t\treturn rt;\n\treturn ERR_PTR(err);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'inet: add RCU protection to inet->opt\n\nWe lack proper synchronization to manipulate inet->opt ip_options\n\nProblem is ip_make_skb() calls ip_setup_cork() and\nip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options),\nwithout any protection against another thread manipulating inet->opt.\n\nAnother thread can change inet->opt pointer and free old one under us.\n\nUse RCU to protect inet->opt (changed to inet->inet_opt).\n\nInstead of handling atomic refcounts, just copy ip_options when\nnecessary, to avoid cache line dirtying.\n\nWe cant insert an rcu_head in struct ip_options since its included in\nskb->cb[], so this patch is large because I had to introduce a new\nip_options_rcu structure.\n\nSigned-off-by: Eric Dumazet \nCc: Herbert Xu \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ppm_load_read_header(FILE *fp,\n pnm_struct *img)\n{\n /* PPM Headers Variable Declaration */\n gchar *ptr;\n //gchar *retval;\n gchar header[MAX_CHARS_IN_ROW];\n gint maxval;\n\n /* Check the PPM file Type P2 or P5 */\n fgets (header,MAX_CHARS_IN_ROW,fp);\n\n if (header[0] != ASCII_P ||\n (header[1] != PIXMAP_ASCII &&\n header[1] != PIXMAP_RAW))\n {\n g_warning (\"Image is not a portable pixmap\");\n return FALSE;\n }\n\n img->type = header[1];\n\n /* Check the Comments */\n fgets (header,MAX_CHARS_IN_ROW,fp);\n while(header[0] == '#')\n {\n fgets (header,MAX_CHARS_IN_ROW,fp);\n }\n\n /* Get Width and Height */\n img->width = strtol (header,&ptr,0);\n img->height = atoi (ptr);\n\n fgets (header,MAX_CHARS_IN_ROW,fp);\n maxval = strtol (header,&ptr,0);\n\n if ((maxval != 255) && (maxval != 65535))\n {\n g_warning (\"Image is not an 8-bit or 16-bit portable pixmap\");\n return FALSE;\n }\n\n switch (maxval)\n {\n case 255:\n img->bpc = sizeof (guchar);\n break;\n\n case 65535:\n img->bpc = sizeof (gushort);\n break;\n\n default:\n g_warning (\"%s: Programmer stupidity error\", G_STRLOC);\n }\n\n /* Later on, img->numsamples is multiplied with img->bpc to allocate\n * memory. Ensure it doesn't overflow. */\n if (!img->width || !img->height ||\n G_MAXSIZE / img->width / img->height / CHANNEL_COUNT < img->bpc)\n {\n g_warning (\"Illegal width/height: %ld/%ld\", img->width, img->height);\n return FALSE;\n }\n img->numsamples = img->width * img->height * CHANNEL_COUNT;\n\n return TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'ppm-load: CVE-2012-4433: add plausibility checks for header fields\n\nRefuse values that are non-decimal, negative or overflow the target\ntype.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int ext4_split_unwritten_extents(handle_t *handle,\n\t\t\t\t\tstruct inode *inode,\n\t\t\t\t\tstruct ext4_map_blocks *map,\n\t\t\t\t\tstruct ext4_ext_path *path,\n\t\t\t\t\tint flags)\n{\n\text4_lblk_t eof_block;\n\text4_lblk_t ee_block;\n\tstruct ext4_extent *ex;\n\tunsigned int ee_len;\n\tint split_flag = 0, depth;\n\n\text_debug(\"ext4_split_unwritten_extents: inode %lu, logical\"\n\t\t\"block %llu, max_blocks %u\\n\", inode->i_ino,\n\t\t(unsigned long long)map->m_lblk, map->m_len);\n\n\teof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>\n\t\tinode->i_sb->s_blocksize_bits;\n\tif (eof_block < map->m_lblk + map->m_len)\n\t\teof_block = map->m_lblk + map->m_len;\n\t/*\n\t * It is safe to convert extent to initialized via explicit\n\t * zeroout only if extent is fully insde i_size or new_size.\n\t */\n\tdepth = ext_depth(inode);\n\tex = path[depth].p_ext;\n\tee_block = le32_to_cpu(ex->ee_block);\n\tee_len = ext4_ext_get_actual_len(ex);\n\n\tsplit_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;\n\tsplit_flag |= EXT4_EXT_MARK_UNINIT2;\n\n\tflags |= EXT4_GET_BLOCKS_PRE_IO;\n\treturn ext4_split_extent(handle, inode, path, map, split_flag, flags);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'ext4: race-condition protection for ext4_convert_unwritten_extents_endio\n\nWe assumed that at the time we call ext4_convert_unwritten_extents_endio()\nextent in question is fully inside [map.m_lblk, map->m_len] because\nit was already split during submission. But this may not be true due to\na race between writeback vs fallocate.\n\nIf extent in question is larger than requested we will split it again.\nSpecial precautions should being done if zeroout required because\n[map.m_lblk, map->m_len] already contains valid data.\n\nSigned-off-by: Dmitry Monakhov \nSigned-off-by: \"Theodore Ts'o\" \nCc: stable@vger.kernel.org'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: transit_state_consume_1char (struct dfa *d, int s, unsigned char const **pp,\n int *match_lens, int *mbclen, position_set *pps)\n{\n int i, j;\n int s1, s2;\n int* work_mbls;\n status_transit_state rs = TRANSIT_STATE_DONE;\n\n /* Calculate the length of the (single/multi byte) character\n to which p points. */\n *mbclen = (mblen_buf[*pp - buf_begin] == 0)? 1\n : mblen_buf[*pp - buf_begin];\n\n /* Calculate the state which can be reached from the state `s' by\n consuming `*mbclen' single bytes from the buffer. */\n s1 = s;\n for (i = 0; i < *mbclen; i++)\n {\n s2 = s1;\n rs = transit_state_singlebyte(d, s2, (*pp)++, &s1);\n }\n /* Copy the positions contained by `s1' to the set `pps'. */\n copy(&(d->states[s1].elems), pps);\n\n /* Check (inputed)match_lens, and initialize if it is NULL. */\n if (match_lens == NULL && d->states[s].mbps.nelem != 0)\n work_mbls = check_matching_with_multibyte_ops(d, s, *pp - buf_begin);\n else\n work_mbls = match_lens;\n\n /* Add all of the positions which can be reached from `s' by consuming\n a single character. */\n for (i = 0; i < d->states[s].mbps.nelem ; i++)\n {\n if (work_mbls[i] == *mbclen)\n for (j = 0; j < d->follows[d->states[s].mbps.elems[i].index].nelem;\n j++)\n insert(d->follows[d->states[s].mbps.elems[i].index].elems[j],\n pps);\n }\n\n if (match_lens == NULL && work_mbls != NULL)\n free(work_mbls);\n return rs;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix some core dumps with long lines etc.\n\nThese problems mostly occur because the code attempts to stuff\nsizes into int or into unsigned int; this doesn't work on most\n64-bit hosts and the errors can lead to core dumps.\n* NEWS: Document this.\n* src/dfa.c (token): Typedef to ptrdiff_t, since the enum's\nrange could be as small as -128 .. 127 on practical hosts.\n(position.index): Now size_t, not unsigned int.\n(leaf_set.elems): Now size_t *, not unsigned int *.\n(dfa_state.hash, struct mb_char_classes.nchars, .nch_classes)\n(.nranges, .nequivs, .ncoll_elems, struct dfa.cindex, .calloc, .tindex)\n(.talloc, .depth, .nleaves, .nregexps, .nmultibyte_prop, .nmbcsets):\n(.mbcsets_alloc): Now size_t, not int.\n(dfa_state.first_end): Now token, not int.\n(state_num): New type.\n(struct mb_char_classes.cset): Now ptrdiff_t, not int.\n(struct dfa.utf8_anychar_classes): Now token[5], not int[5].\n(struct dfa.sindex, .salloc, .tralloc): Now state_num, not int.\n(struct dfa.trans, .realtrans, .fails): Now state_num **, not int **.\n(struct dfa.newlines): Now state_num *, not int *.\n(prtok): Don't assume 'token' is no wider than int.\n(lexleft, parens, depth): Now size_t, not int.\n(charclass_index, nsubtoks)\n(parse_bracket_exp, addtok, copytoks, closure, insert, merge, delete)\n(state_index, epsclosure, state_separate_contexts)\n(dfaanalyze, dfastate, build_state, realloc_trans_if_necessary)\n(transit_state_singlebyte, match_anychar, match_mb_charset)\n(check_matching_with_multibyte_ops, transit_state_consume_1char)\n(transit_state, dfaexec, free_mbdata, dfaoptimize, dfafree)\n(freelist, enlist, addlists, inboth, dfamust):\nDon't assume indexes fit in 'int'.\n(lex): Avoid overflow in string-to-{hi,lo} conversions.\n(dfaanalyze): Redo indexing so that it works with size_t values,\nwhich cannot go negative.\n* src/dfa.h (dfaexec): Count argument is now size_t *, not int *.\n(dfastate): State numbers are now ptrdiff_t, not int.\n* src/dfasearch.c: Include \"intprops.h\", for TYPE_MAXIMUM.\n(kwset_exact_matches): Now size_t, not int.\n(EGexecute): Don't assume indexes fit in 'int'.\nCheck for overflow before converting a ptrdiff_t to a regoff_t,\nas regoff_t is narrower than ptrdiff_t in 64-bit glibc (contra POSIX).\nCheck for memory exhaustion in re_search rather than treating\nit merely as failure to match; use xalloc_die () to report any error.\n* src/kwset.c (struct trie.accepting): Now size_t, not unsigned int.\n(struct kwset.words): Now ptrdiff_t, not int.\n* src/kwset.h (struct kwsmatch.index): Now size_t, not int.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: check_matching_with_multibyte_ops (struct dfa *d, int s, int idx)\n{\n int i;\n int* rarray;\n\n MALLOC(rarray, d->states[s].mbps.nelem);\n for (i = 0; i < d->states[s].mbps.nelem; ++i)\n {\n position pos = d->states[s].mbps.elems[i];\n switch(d->tokens[pos.index])\n {\n case ANYCHAR:\n rarray[i] = match_anychar(d, s, pos, idx);\n break;\n case MBCSET:\n rarray[i] = match_mb_charset(d, s, pos, idx);\n break;\n default:\n break; /* cannot happen. */\n }\n }\n return rarray;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix some core dumps with long lines etc.\n\nThese problems mostly occur because the code attempts to stuff\nsizes into int or into unsigned int; this doesn't work on most\n64-bit hosts and the errors can lead to core dumps.\n* NEWS: Document this.\n* src/dfa.c (token): Typedef to ptrdiff_t, since the enum's\nrange could be as small as -128 .. 127 on practical hosts.\n(position.index): Now size_t, not unsigned int.\n(leaf_set.elems): Now size_t *, not unsigned int *.\n(dfa_state.hash, struct mb_char_classes.nchars, .nch_classes)\n(.nranges, .nequivs, .ncoll_elems, struct dfa.cindex, .calloc, .tindex)\n(.talloc, .depth, .nleaves, .nregexps, .nmultibyte_prop, .nmbcsets):\n(.mbcsets_alloc): Now size_t, not int.\n(dfa_state.first_end): Now token, not int.\n(state_num): New type.\n(struct mb_char_classes.cset): Now ptrdiff_t, not int.\n(struct dfa.utf8_anychar_classes): Now token[5], not int[5].\n(struct dfa.sindex, .salloc, .tralloc): Now state_num, not int.\n(struct dfa.trans, .realtrans, .fails): Now state_num **, not int **.\n(struct dfa.newlines): Now state_num *, not int *.\n(prtok): Don't assume 'token' is no wider than int.\n(lexleft, parens, depth): Now size_t, not int.\n(charclass_index, nsubtoks)\n(parse_bracket_exp, addtok, copytoks, closure, insert, merge, delete)\n(state_index, epsclosure, state_separate_contexts)\n(dfaanalyze, dfastate, build_state, realloc_trans_if_necessary)\n(transit_state_singlebyte, match_anychar, match_mb_charset)\n(check_matching_with_multibyte_ops, transit_state_consume_1char)\n(transit_state, dfaexec, free_mbdata, dfaoptimize, dfafree)\n(freelist, enlist, addlists, inboth, dfamust):\nDon't assume indexes fit in 'int'.\n(lex): Avoid overflow in string-to-{hi,lo} conversions.\n(dfaanalyze): Redo indexing so that it works with size_t values,\nwhich cannot go negative.\n* src/dfa.h (dfaexec): Count argument is now size_t *, not int *.\n(dfastate): State numbers are now ptrdiff_t, not int.\n* src/dfasearch.c: Include \"intprops.h\", for TYPE_MAXIMUM.\n(kwset_exact_matches): Now size_t, not int.\n(EGexecute): Don't assume indexes fit in 'int'.\nCheck for overflow before converting a ptrdiff_t to a regoff_t,\nas regoff_t is narrower than ptrdiff_t in 64-bit glibc (contra POSIX).\nCheck for memory exhaustion in re_search rather than treating\nit merely as failure to match; use xalloc_die () to report any error.\n* src/kwset.c (struct trie.accepting): Now size_t, not unsigned int.\n(struct kwset.words): Now ptrdiff_t, not int.\n* src/kwset.h (struct kwsmatch.index): Now size_t, not int.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: transit_state_singlebyte (struct dfa *d, int s, unsigned char const *p,\n int *next_state)\n{\n int *t;\n int works = s;\n\n status_transit_state rval = TRANSIT_STATE_IN_PROGRESS;\n\n while (rval == TRANSIT_STATE_IN_PROGRESS)\n {\n if ((t = d->trans[works]) != NULL)\n {\n works = t[*p];\n rval = TRANSIT_STATE_DONE;\n if (works < 0)\n works = 0;\n }\n else if (works < 0)\n {\n if (p == buf_end)\n {\n /* At the moment, it must not happen. */\n abort ();\n }\n works = 0;\n }\n else if (d->fails[works])\n {\n works = d->fails[works][*p];\n rval = TRANSIT_STATE_DONE;\n }\n else\n {\n build_state(works, d);\n }\n }\n *next_state = works;\n return rval;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix some core dumps with long lines etc.\n\nThese problems mostly occur because the code attempts to stuff\nsizes into int or into unsigned int; this doesn't work on most\n64-bit hosts and the errors can lead to core dumps.\n* NEWS: Document this.\n* src/dfa.c (token): Typedef to ptrdiff_t, since the enum's\nrange could be as small as -128 .. 127 on practical hosts.\n(position.index): Now size_t, not unsigned int.\n(leaf_set.elems): Now size_t *, not unsigned int *.\n(dfa_state.hash, struct mb_char_classes.nchars, .nch_classes)\n(.nranges, .nequivs, .ncoll_elems, struct dfa.cindex, .calloc, .tindex)\n(.talloc, .depth, .nleaves, .nregexps, .nmultibyte_prop, .nmbcsets):\n(.mbcsets_alloc): Now size_t, not int.\n(dfa_state.first_end): Now token, not int.\n(state_num): New type.\n(struct mb_char_classes.cset): Now ptrdiff_t, not int.\n(struct dfa.utf8_anychar_classes): Now token[5], not int[5].\n(struct dfa.sindex, .salloc, .tralloc): Now state_num, not int.\n(struct dfa.trans, .realtrans, .fails): Now state_num **, not int **.\n(struct dfa.newlines): Now state_num *, not int *.\n(prtok): Don't assume 'token' is no wider than int.\n(lexleft, parens, depth): Now size_t, not int.\n(charclass_index, nsubtoks)\n(parse_bracket_exp, addtok, copytoks, closure, insert, merge, delete)\n(state_index, epsclosure, state_separate_contexts)\n(dfaanalyze, dfastate, build_state, realloc_trans_if_necessary)\n(transit_state_singlebyte, match_anychar, match_mb_charset)\n(check_matching_with_multibyte_ops, transit_state_consume_1char)\n(transit_state, dfaexec, free_mbdata, dfaoptimize, dfafree)\n(freelist, enlist, addlists, inboth, dfamust):\nDon't assume indexes fit in 'int'.\n(lex): Avoid overflow in string-to-{hi,lo} conversions.\n(dfaanalyze): Redo indexing so that it works with size_t values,\nwhich cannot go negative.\n* src/dfa.h (dfaexec): Count argument is now size_t *, not int *.\n(dfastate): State numbers are now ptrdiff_t, not int.\n* src/dfasearch.c: Include \"intprops.h\", for TYPE_MAXIMUM.\n(kwset_exact_matches): Now size_t, not int.\n(EGexecute): Don't assume indexes fit in 'int'.\nCheck for overflow before converting a ptrdiff_t to a regoff_t,\nas regoff_t is narrower than ptrdiff_t in 64-bit glibc (contra POSIX).\nCheck for memory exhaustion in re_search rather than treating\nit merely as failure to match; use xalloc_die () to report any error.\n* src/kwset.c (struct trie.accepting): Now size_t, not unsigned int.\n(struct kwset.words): Now ptrdiff_t, not int.\n* src/kwset.h (struct kwsmatch.index): Now size_t, not int.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: dfaexec (struct dfa *d, char const *begin, char *end,\n int allow_nl, int *count, int *backref)\n{\n int s, s1;\t\t/* Current state. */\n unsigned char const *p; /* Current input character. */\n int **trans, *t;\t/* Copy of d->trans so it can be optimized\n into a register. */\n unsigned char eol = eolbyte;\t/* Likewise for eolbyte. */\n unsigned char saved_end;\n\n if (! d->tralloc)\n build_state_zero(d);\n\n s = s1 = 0;\n p = (unsigned char const *) begin;\n trans = d->trans;\n saved_end = *(unsigned char *) end;\n *end = eol;\n\n if (d->mb_cur_max > 1)\n {\n MALLOC(mblen_buf, end - begin + 2);\n MALLOC(inputwcs, end - begin + 2);\n memset(&mbs, 0, sizeof(mbstate_t));\n prepare_wc_buf ((const char *) p, end);\n }\n\n for (;;)\n {\n if (d->mb_cur_max > 1)\n while ((t = trans[s]) != NULL)\n {\n if (p > buf_end)\n break;\n s1 = s;\n SKIP_REMAINS_MB_IF_INITIAL_STATE(s, p);\n\n if (d->states[s].mbps.nelem == 0)\n {\n s = t[*p++];\n continue;\n }\n\n /* Falling back to the glibc matcher in this case gives\n better performance (up to 25% better on [a-z], for\n example) and enables support for collating symbols and\n equivalence classes. */\n if (backref)\n {\n *backref = 1;\n free(mblen_buf);\n free(inputwcs);\n *end = saved_end;\n return (char *) p;\n }\n\n /* Can match with a multibyte character (and multi character\n collating element). Transition table might be updated. */\n s = transit_state(d, s, &p);\n trans = d->trans;\n }\n else\n {\n while ((t = trans[s]) != NULL)\n {\n s1 = t[*p++];\n if ((t = trans[s1]) == NULL)\n {\n int tmp = s; s = s1; s1 = tmp; /* swap */\n break;\n }\n s = t[*p++];\n }\n }\n\n if (s >= 0 && (char *) p <= end && d->fails[s])\n {\n if (d->success[s] & sbit[*p])\n {\n if (backref)\n *backref = (d->states[s].backref != 0);\n if (d->mb_cur_max > 1)\n {\n free(mblen_buf);\n free(inputwcs);\n }\n *end = saved_end;\n return (char *) p;\n }\n\n s1 = s;\n if (d->mb_cur_max > 1)\n {\n /* Can match with a multibyte character (and multicharacter\n collating element). Transition table might be updated. */\n s = transit_state(d, s, &p);\n trans = d->trans;\n }\n else\n s = d->fails[s][*p++];\n continue;\n }\n\n /* If the previous character was a newline, count it. */\n if ((char *) p <= end && p[-1] == eol)\n {\n if (count)\n ++*count;\n\n if (d->mb_cur_max > 1)\n prepare_wc_buf ((const char *) p, end);\n }\n\n /* Check if we've run off the end of the buffer. */\n if ((char *) p > end)\n {\n if (d->mb_cur_max > 1)\n {\n free(mblen_buf);\n free(inputwcs);\n }\n *end = saved_end;\n return NULL;\n }\n\n if (s >= 0)\n {\n build_state(s, d);\n trans = d->trans;\n continue;\n }\n\n if (p[-1] == eol && allow_nl)\n {\n s = d->newlines[s1];\n continue;\n }\n\n s = 0;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix some core dumps with long lines etc.\n\nThese problems mostly occur because the code attempts to stuff\nsizes into int or into unsigned int; this doesn't work on most\n64-bit hosts and the errors can lead to core dumps.\n* NEWS: Document this.\n* src/dfa.c (token): Typedef to ptrdiff_t, since the enum's\nrange could be as small as -128 .. 127 on practical hosts.\n(position.index): Now size_t, not unsigned int.\n(leaf_set.elems): Now size_t *, not unsigned int *.\n(dfa_state.hash, struct mb_char_classes.nchars, .nch_classes)\n(.nranges, .nequivs, .ncoll_elems, struct dfa.cindex, .calloc, .tindex)\n(.talloc, .depth, .nleaves, .nregexps, .nmultibyte_prop, .nmbcsets):\n(.mbcsets_alloc): Now size_t, not int.\n(dfa_state.first_end): Now token, not int.\n(state_num): New type.\n(struct mb_char_classes.cset): Now ptrdiff_t, not int.\n(struct dfa.utf8_anychar_classes): Now token[5], not int[5].\n(struct dfa.sindex, .salloc, .tralloc): Now state_num, not int.\n(struct dfa.trans, .realtrans, .fails): Now state_num **, not int **.\n(struct dfa.newlines): Now state_num *, not int *.\n(prtok): Don't assume 'token' is no wider than int.\n(lexleft, parens, depth): Now size_t, not int.\n(charclass_index, nsubtoks)\n(parse_bracket_exp, addtok, copytoks, closure, insert, merge, delete)\n(state_index, epsclosure, state_separate_contexts)\n(dfaanalyze, dfastate, build_state, realloc_trans_if_necessary)\n(transit_state_singlebyte, match_anychar, match_mb_charset)\n(check_matching_with_multibyte_ops, transit_state_consume_1char)\n(transit_state, dfaexec, free_mbdata, dfaoptimize, dfafree)\n(freelist, enlist, addlists, inboth, dfamust):\nDon't assume indexes fit in 'int'.\n(lex): Avoid overflow in string-to-{hi,lo} conversions.\n(dfaanalyze): Redo indexing so that it works with size_t values,\nwhich cannot go negative.\n* src/dfa.h (dfaexec): Count argument is now size_t *, not int *.\n(dfastate): State numbers are now ptrdiff_t, not int.\n* src/dfasearch.c: Include \"intprops.h\", for TYPE_MAXIMUM.\n(kwset_exact_matches): Now size_t, not int.\n(EGexecute): Don't assume indexes fit in 'int'.\nCheck for overflow before converting a ptrdiff_t to a regoff_t,\nas regoff_t is narrower than ptrdiff_t in 64-bit glibc (contra POSIX).\nCheck for memory exhaustion in re_search rather than treating\nit merely as failure to match; use xalloc_die () to report any error.\n* src/kwset.c (struct trie.accepting): Now size_t, not unsigned int.\n(struct kwset.words): Now ptrdiff_t, not int.\n* src/kwset.h (struct kwsmatch.index): Now size_t, not int.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: get_nondigit_option (int argc, char *const *argv, int *default_context)\n{\n static int prev_digit_optind = -1;\n int opt, this_digit_optind, was_digit;\n char buf[sizeof (uintmax_t) * CHAR_BIT + 4];\n char *p = buf;\n\n was_digit = 0;\n this_digit_optind = optind;\n while (opt = getopt_long (argc, (char **) argv, short_options, long_options,\n NULL),\n '0' <= opt && opt <= '9')\n {\n if (prev_digit_optind != this_digit_optind || !was_digit)\n {\n /* Reset to start another context length argument. */\n p = buf;\n }\n else\n {\n /* Suppress trivial leading zeros, to avoid incorrect\n diagnostic on strings like 00000000000. */\n p -= buf[0] == '0';\n }\n\n if (p == buf + sizeof buf - 4)\n {\n /* Too many digits. Append \"...\" to make context_length_arg\n complain about \"X...\", where X contains the digits seen\n so far. */\n strcpy (p, \"...\");\n p += 3;\n break;\n }\n *p++ = opt;\n\n was_digit = 1;\n prev_digit_optind = this_digit_optind;\n this_digit_optind = optind;\n }\n if (p != buf)\n {\n *p = '\\0';\n context_length_arg (buf, default_context);\n }\n\n return opt;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix integer-overflow issues in main program\n\n* NEWS: Document this.\n* bootstrap.conf (gnulib_modules): Add inttypes, xstrtoimax.\nRemove xstrtoumax.\n* src/main.c: Include , for INTMAX_MAX, PRIdMAX.\n(context_length_arg, prtext, grepbuf, grep, grepfile)\n(get_nondigit_option, main):\nUse intmax_t, not int, for line counts.\n(context_length_arg, main): Silently ceiling line counts\nto maximum value, since there's no practical difference between\ndoing that and using infinite-precision arithmetic.\n(out_before, out_after, pending): Now intmax_t, not int.\n(max_count, outleft): Now intmax_t, not off_t.\n(prepend_args, prepend_default_options, main):\nUse size_t, not int, for sizes.\n(prepend_default_options): Check for int and size_t overflow.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: cib_tls_close(cib_t * cib)\n{\n cib_remote_opaque_t *private = cib->variant_opaque;\n\n shutdown(private->command.socket, SHUT_RDWR); /* no more receptions */\n shutdown(private->callback.socket, SHUT_RDWR); /* no more receptions */\n close(private->command.socket);\n close(private->callback.socket);\n\n#ifdef HAVE_GNUTLS_GNUTLS_H\n if (private->command.encrypted) {\n gnutls_bye(*(private->command.session), GNUTLS_SHUT_RDWR);\n gnutls_deinit(*(private->command.session));\n gnutls_free(private->command.session);\n\n gnutls_bye(*(private->callback.session), GNUTLS_SHUT_RDWR);\n gnutls_deinit(*(private->callback.session));\n gnutls_free(private->callback.session);\n\n gnutls_anon_free_client_credentials(anon_cred_c);\n gnutls_global_deinit();\n }\n#endif\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'High: core: Internal tls api improvements for reuse with future LRMD tls backend.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: cib_tls_signon(cib_t * cib, struct remote_connection_s *connection)\n{\n int sock;\n cib_remote_opaque_t *private = cib->variant_opaque;\n struct sockaddr_in addr;\n int rc = 0;\n char *server = private->server;\n\n int ret_ga;\n struct addrinfo *res;\n struct addrinfo hints;\n\n xmlNode *answer = NULL;\n xmlNode *login = NULL;\n\n static struct mainloop_fd_callbacks cib_fd_callbacks = \n {\n .dispatch = cib_remote_dispatch,\n .destroy = cib_remote_connection_destroy,\n };\n\n connection->socket = 0;\n connection->session = NULL;\n\n /* create socket */\n sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);\n if (sock == -1) {\n crm_perror(LOG_ERR, \"Socket creation failed\");\n return -1;\n }\n\n /* getaddrinfo */\n bzero(&hints, sizeof(struct addrinfo));\n hints.ai_flags = AI_CANONNAME;\n hints.ai_family = AF_INET;\n hints.ai_socktype = SOCK_RAW;\n\n if (hints.ai_family == AF_INET6) {\n hints.ai_protocol = IPPROTO_ICMPV6;\n } else {\n hints.ai_protocol = IPPROTO_ICMP;\n }\n\n crm_debug(\"Looking up %s\", server);\n ret_ga = getaddrinfo(server, NULL, &hints, &res);\n if (ret_ga) {\n crm_err(\"getaddrinfo: %s\", gai_strerror(ret_ga));\n close(sock);\n return -1;\n }\n\n if (res->ai_canonname) {\n server = res->ai_canonname;\n }\n\n crm_debug(\"Got address %s for %s\", server, private->server);\n\n if (!res->ai_addr) {\n fprintf(stderr, \"getaddrinfo failed\");\n crm_exit(1);\n }\n#if 1\n memcpy(&addr, res->ai_addr, res->ai_addrlen);\n#else\n /* connect to server */\n memset(&addr, 0, sizeof(addr));\n addr.sin_family = AF_INET;\n addr.sin_addr.s_addr = inet_addr(server);\n#endif\n addr.sin_port = htons(private->port);\n\n if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == -1) {\n crm_perror(LOG_ERR, \"Connection to %s:%d failed\", server, private->port);\n close(sock);\n return -1;\n }\n\n if (connection->encrypted) {\n /* initialize GnuTls lib */\n#ifdef HAVE_GNUTLS_GNUTLS_H\n gnutls_global_init();\n gnutls_anon_allocate_client_credentials(&anon_cred_c);\n\n /* bind the socket to GnuTls lib */\n connection->session = create_tls_session(sock, GNUTLS_CLIENT);\n if (connection->session == NULL) {\n crm_perror(LOG_ERR, \"Session creation for %s:%d failed\", server, private->port);\n close(sock);\n cib_tls_close(cib);\n return -1;\n }\n#else\n return -EPROTONOSUPPORT;\n#endif\n } else {\n connection->session = GUINT_TO_POINTER(sock);\n }\n\n /* login to server */\n login = create_xml_node(NULL, \"cib_command\");\n crm_xml_add(login, \"op\", \"authenticate\");\n crm_xml_add(login, \"user\", private->user);\n crm_xml_add(login, \"password\", private->passwd);\n crm_xml_add(login, \"hidden\", \"password\");\n\n crm_send_remote_msg(connection->session, login, connection->encrypted);\n free_xml(login);\n\n answer = crm_recv_remote_msg(connection->session, connection->encrypted);\n crm_log_xml_trace(answer, \"Reply\");\n if (answer == NULL) {\n rc = -EPROTO;\n\n } else {\n /* grab the token */\n const char *msg_type = crm_element_value(answer, F_CIB_OPERATION);\n const char *tmp_ticket = crm_element_value(answer, F_CIB_CLIENTID);\n\n if (safe_str_neq(msg_type, CRM_OP_REGISTER)) {\n crm_err(\"Invalid registration message: %s\", msg_type);\n rc = -EPROTO;\n\n } else if (tmp_ticket == NULL) {\n rc = -EPROTO;\n\n } else {\n connection->token = strdup(tmp_ticket);\n }\n }\n\n if (rc != 0) {\n cib_tls_close(cib);\n }\n\n connection->socket = sock;\n connection->source = mainloop_add_fd(\"cib-remote\", G_PRIORITY_HIGH, connection->socket, cib, &cib_fd_callbacks);\n return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'High: core: Internal tls api improvements for reuse with future LRMD tls backend.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: refresh_account (GoaProvider *provider,\n GoaClient *client,\n GoaObject *object,\n GtkWindow *parent,\n GError **error)\n{\n AddAccountData data;\n GVariantBuilder builder;\n GoaAccount *account;\n GoaHttpClient *http_client;\n GtkWidget *dialog;\n GtkWidget *vbox;\n gboolean ret;\n const gchar *password;\n const gchar *username;\n gchar *uri;\n gchar *uri_webdav;\n gint response;\n\n g_return_val_if_fail (GOA_IS_OWNCLOUD_PROVIDER (provider), FALSE);\n g_return_val_if_fail (GOA_IS_CLIENT (client), FALSE);\n g_return_val_if_fail (GOA_IS_OBJECT (object), FALSE);\n g_return_val_if_fail (parent == NULL || GTK_IS_WINDOW (parent), FALSE);\n g_return_val_if_fail (error == NULL || *error == NULL, FALSE);\n\n http_client = NULL;\n uri = NULL;\n uri_webdav = NULL;\n\n ret = FALSE;\n\n dialog = gtk_dialog_new_with_buttons (NULL,\n parent,\n GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,\n GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,\n NULL);\n gtk_container_set_border_width (GTK_CONTAINER (dialog), 12);\n gtk_window_set_modal (GTK_WINDOW (dialog), TRUE);\n gtk_window_set_resizable (GTK_WINDOW (dialog), FALSE);\n\n vbox = gtk_dialog_get_content_area (GTK_DIALOG (dialog));\n gtk_box_set_spacing (GTK_BOX (vbox), 12);\n\n memset (&data, 0, sizeof (AddAccountData));\n data.cancellable = g_cancellable_new ();\n data.loop = g_main_loop_new (NULL, FALSE);\n data.dialog = GTK_DIALOG (dialog);\n data.error = NULL;\n\n create_account_details_ui (provider, GTK_DIALOG (dialog), GTK_BOX (vbox), FALSE, &data);\n\n uri = goa_util_lookup_keyfile_string (object, \"Uri\");\n gtk_entry_set_text (GTK_ENTRY (data.uri), uri);\n gtk_editable_set_editable (GTK_EDITABLE (data.uri), FALSE);\n\n account = goa_object_peek_account (object);\n username = goa_account_get_identity (account);\n gtk_entry_set_text (GTK_ENTRY (data.username), username);\n gtk_editable_set_editable (GTK_EDITABLE (data.username), FALSE);\n\n gtk_widget_show_all (dialog);\n g_signal_connect (dialog, \"response\", G_CALLBACK (dialog_response_cb), &data);\n\n http_client = goa_http_client_new ();\n uri_webdav = g_strconcat (uri, WEBDAV_ENDPOINT, NULL);\n\n http_again:\n response = gtk_dialog_run (GTK_DIALOG (dialog));\n if (response != GTK_RESPONSE_OK)\n {\n g_set_error (&data.error,\n GOA_ERROR,\n GOA_ERROR_DIALOG_DISMISSED,\n _(\"Dialog was dismissed\"));\n goto out;\n }\n\n password = gtk_entry_get_text (GTK_ENTRY (data.password));\n g_cancellable_reset (data.cancellable);\n goa_http_client_check (http_client,\n uri_webdav,\n username,\n password,\n data.cancellable,\n check_cb,\n &data);\n gtk_widget_set_sensitive (data.connect_button, FALSE);\n gtk_widget_show (data.progress_grid);\n g_main_loop_run (data.loop);\n\n if (g_cancellable_is_cancelled (data.cancellable))\n {\n g_prefix_error (&data.error,\n _(\"Dialog was dismissed (%s, %d): \"),\n g_quark_to_string (data.error->domain),\n data.error->code);\n data.error->domain = GOA_ERROR;\n data.error->code = GOA_ERROR_DIALOG_DISMISSED;\n goto out;\n }\n else if (data.error != NULL)\n {\n gchar *markup;\n\n markup = g_strdup_printf (\"%s: %s\",\n _(\"Error connecting to ownCloud server\"),\n data.error->message);\n g_clear_error (&data.error);\n\n gtk_label_set_markup (GTK_LABEL (data.cluebar_label), markup);\n g_free (markup);\n\n gtk_button_set_label (GTK_BUTTON (data.connect_button), _(\"_Try Again\"));\n gtk_widget_set_no_show_all (data.cluebar, FALSE);\n gtk_widget_show_all (data.cluebar);\n goto http_again;\n }\n\n /* TODO: run in worker thread */\n g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);\n g_variant_builder_add (&builder, \"{sv}\", \"password\", g_variant_new_string (password));\n\n if (!goa_utils_store_credentials_for_object_sync (provider,\n object,\n g_variant_builder_end (&builder),\n NULL, /* GCancellable */\n &data.error))\n goto out;\n\n goa_account_call_ensure_credentials (account,\n NULL, /* GCancellable */\n NULL, NULL); /* callback, user_data */\n\n ret = TRUE;\n\n out:\n if (data.error != NULL)\n g_propagate_error (error, data.error);\n\n gtk_widget_destroy (dialog);\n g_free (uri);\n g_free (uri_webdav);\n if (data.loop != NULL)\n g_main_loop_unref (data.loop);\n g_clear_object (&data.cancellable);\n g_clear_object (&http_client);\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Guard against invalid SSL certificates\n\nNone of the branded providers (eg., Google, Facebook and Windows Live)\nshould ever have an invalid certificate. So set \"ssl-strict\" on the\nSoupSession object being used by GoaWebView.\n\nProviders like ownCloud and Exchange might have to deal with\ncertificates that are not up to the mark. eg., self-signed\ncertificates. For those, show a warning when the account is being\ncreated, and only proceed if the user decides to ignore it. In any\ncase, save the status of the certificate that was used to create the\naccount. So an account created with a valid certificate will never\nwork with an invalid one, and one created with an invalid certificate\nwill not throw any further warnings.\n\nFixes: CVE-2013-0240'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: goa_web_view_init (GoaWebView *self)\n{\n GoaWebViewPrivate *priv;\n GtkWidget *scrolled_window;\n SoupCookieJar *cookie_jar;\n SoupSession *session;\n WebKitWebSettings *settings;\n\n self->priv = GOA_WEB_VIEW_GET_PRIVATE (self);\n priv = self->priv;\n\n session = webkit_get_default_session ();\n\n soup_session_add_feature_by_type (session, SOUP_TYPE_PROXY_RESOLVER_GNOME);\n g_object_set (session, \"accept-language-auto\", TRUE, NULL);\n\n soup_session_remove_feature_by_type (session, SOUP_TYPE_COOKIE_JAR);\n cookie_jar = soup_cookie_jar_new ();\n soup_session_add_feature (session, SOUP_SESSION_FEATURE (cookie_jar));\n g_object_unref (cookie_jar);\n\n gtk_style_context_add_class (gtk_widget_get_style_context (GTK_WIDGET (self)),\n GTK_STYLE_CLASS_OSD);\n\n scrolled_window = gtk_scrolled_window_new (NULL, NULL);\n gtk_widget_set_size_request (scrolled_window, 500, 400);\n gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (scrolled_window), GTK_SHADOW_IN);\n gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_window),\n GTK_POLICY_AUTOMATIC,\n GTK_POLICY_AUTOMATIC);\n gtk_container_add (GTK_CONTAINER (self), scrolled_window);\n\n priv->web_view = webkit_web_view_new ();\n priv->status = WEBKIT_LOAD_PROVISIONAL;\n gtk_container_add (GTK_CONTAINER (scrolled_window), priv->web_view);\n\n settings = webkit_web_view_get_settings (WEBKIT_WEB_VIEW (priv->web_view));\n g_object_set (settings, \"user-stylesheet-uri\", \"file://\" PACKAGE_DATA_DIR \"/goawebview.css\", NULL);\n\n /* statusbar is hidden by default */\n priv->floating_bar = nautilus_floating_bar_new (NULL, FALSE);\n gtk_widget_set_halign (priv->floating_bar, GTK_ALIGN_START);\n gtk_widget_set_valign (priv->floating_bar, GTK_ALIGN_END);\n gtk_widget_set_no_show_all (priv->floating_bar, TRUE);\n gtk_overlay_add_overlay (GTK_OVERLAY (self), priv->floating_bar);\n\n priv->progress_bar = gtk_progress_bar_new ();\n gtk_widget_set_halign (priv->progress_bar, GTK_ALIGN_FILL);\n gtk_widget_set_valign (priv->progress_bar, GTK_ALIGN_START);\n gtk_overlay_add_overlay (GTK_OVERLAY (self), priv->progress_bar);\n\n priv->notify_progress_id = g_signal_connect (priv->web_view,\n \"notify::progress\",\n G_CALLBACK (web_view_notify_progress_cb),\n self);\n priv->notify_load_status_id = g_signal_connect (priv->web_view,\n \"notify::load-status\",\n G_CALLBACK (web_view_notify_load_status_cb),\n self);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Guard against invalid SSL certificates\n\nNone of the branded providers (eg., Google, Facebook and Windows Live)\nshould ever have an invalid certificate. So set \"ssl-strict\" on the\nSoupSession object being used by GoaWebView.\n\nProviders like ownCloud and Exchange might have to deal with\ncertificates that are not up to the mark. eg., self-signed\ncertificates. For those, show a warning when the account is being\ncreated, and only proceed if the user decides to ignore it. In any\ncase, save the status of the certificate that was used to create the\naccount. So an account created with a valid certificate will never\nwork with an invalid one, and one created with an invalid certificate\nwill not throw any further warnings.\n\nFixes: CVE-2013-0240'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: goa_http_client_check (GoaHttpClient *client,\n const gchar *uri,\n const gchar *username,\n const gchar *password,\n gboolean accept_ssl_errors,\n GCancellable *cancellable,\n GAsyncReadyCallback callback,\n gpointer user_data)\n{\n CheckData *data;\n CheckAuthData *auth;\n\n g_return_if_fail (GOA_IS_HTTP_CLIENT (client));\n g_return_if_fail (uri != NULL || uri[0] != '\\0');\n g_return_if_fail (username != NULL || username[0] != '\\0');\n g_return_if_fail (password != NULL || password[0] != '\\0');\n g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));\n\n data = g_slice_new0 (CheckData);\n data->res = g_simple_async_result_new (G_OBJECT (client), callback, user_data, goa_http_client_check);\n data->session = soup_session_async_new_with_options (SOUP_SESSION_SSL_USE_SYSTEM_CA_FILE, TRUE,\n SOUP_SESSION_SSL_STRICT, FALSE,\n SOUP_SESSION_USE_THREAD_CONTEXT, TRUE,\n NULL);\n\n data->accept_ssl_errors = accept_ssl_errors;\n\n data->msg = soup_message_new (SOUP_METHOD_GET, uri);\n soup_message_headers_append (data->msg->request_headers, \"Connection\", \"close\");\n\n if (cancellable != NULL)\n {\n data->cancellable = g_object_ref (cancellable);\n data->cancellable_id = g_cancellable_connect (data->cancellable,\n G_CALLBACK (http_client_check_cancelled_cb),\n data,\n NULL);\n g_simple_async_result_set_check_cancellable (data->res, data->cancellable);\n }\n\n auth = g_slice_new0 (CheckAuthData);\n auth->username = g_strdup (username);\n auth->password = g_strdup (password);\n g_signal_connect_data (data->session,\n \"authenticate\",\n G_CALLBACK (http_client_authenticate),\n auth,\n http_client_check_auth_data_free,\n 0);\n\n soup_session_queue_message (data->session, data->msg, http_client_check_response_cb, data);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Guard against invalid SSL certificates\n\nFor providers like Exchange which use libsoup to talk to a HTTPS\nserver it is not enough to warn the user about an invalid certificate.\nWe should make sure that we abort the connection before any\ncredentials have been sent.\n\nFixes: CVE-2013-1799'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void addReply(redisClient *c, robj *obj) {\n if (_installWriteEvent(c) != REDIS_OK) return;\n redisAssert(!server.vm_enabled || obj->storage == REDIS_VM_MEMORY);\n\n /* This is an important place where we can avoid copy-on-write\n * when there is a saving child running, avoiding touching the\n * refcount field of the object if it's not needed.\n *\n * If the encoding is RAW and there is room in the static buffer\n * we'll be able to send the object to the client without\n * messing with its page. */\n if (obj->encoding == REDIS_ENCODING_RAW) {\n if (_addReplyToBuffer(c,obj->ptr,sdslen(obj->ptr)) != REDIS_OK)\n _addReplyObjectToList(c,obj);\n } else {\n /* FIXME: convert the long into string and use _addReplyToBuffer()\n * instead of calling getDecodedObject. As this place in the\n * code is too performance critical. */\n obj = getDecodedObject(obj);\n if (_addReplyToBuffer(c,obj->ptr,sdslen(obj->ptr)) != REDIS_OK)\n _addReplyObjectToList(c,obj);\n decrRefCount(obj);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'initial changes needed to turn the current VM code into a cache system. Tons of work to do still.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: _gnutls_ciphertext2compressed (gnutls_session_t session,\n opaque * compress_data,\n int compress_size,\n gnutls_datum_t ciphertext, uint8_t type,\n record_parameters_st * params)\n{\n uint8_t MAC[MAX_HASH_SIZE];\n uint16_t c_length;\n unsigned int pad;\n int length;\n uint16_t blocksize;\n int ret, i, pad_failed = 0;\n opaque preamble[PREAMBLE_SIZE];\n int preamble_size;\n int ver = gnutls_protocol_get_version (session);\n int hash_size = _gnutls_hash_get_algo_len (params->mac_algorithm);\n\n blocksize = gnutls_cipher_get_block_size (params->cipher_algorithm);\n\n\n /* actual decryption (inplace)\n */\n switch (_gnutls_cipher_is_block (params->cipher_algorithm))\n {\n case CIPHER_STREAM:\n if ((ret =\n _gnutls_cipher_decrypt (¶ms->read.cipher_state,\n ciphertext.data, ciphertext.size)) < 0)\n {\n gnutls_assert ();\n return ret;\n }\n\n length = ciphertext.size - hash_size;\n\n break;\n case CIPHER_BLOCK:\n if ((ciphertext.size < blocksize) || (ciphertext.size % blocksize != 0))\n {\n gnutls_assert ();\n return GNUTLS_E_DECRYPTION_FAILED;\n }\n\n if ((ret =\n _gnutls_cipher_decrypt (¶ms->read.cipher_state,\n ciphertext.data, ciphertext.size)) < 0)\n {\n gnutls_assert ();\n return ret;\n }\n\n /* ignore the IV in TLS 1.1.\n */\n if (_gnutls_version_has_explicit_iv\n (session->security_parameters.version))\n {\n ciphertext.size -= blocksize;\n ciphertext.data += blocksize;\n }\n\n if (ciphertext.size < hash_size)\n {\n gnutls_assert ();\n return GNUTLS_E_DECRYPTION_FAILED;\n }\n pad = ciphertext.data[ciphertext.size - 1] + 1; /* pad */\n\n if ((int) pad > (int) ciphertext.size - hash_size)\n {\n gnutls_assert ();\n _gnutls_record_log\n (\"REC[%p]: Short record length %d > %d - %d (under attack?)\\n\",\n session, pad, ciphertext.size, hash_size);\n /* We do not fail here. We check below for the\n * the pad_failed. If zero means success.\n */\n pad_failed = GNUTLS_E_DECRYPTION_FAILED;\n }\n\n length = ciphertext.size - hash_size - pad;\n\n /* Check the pading bytes (TLS 1.x)\n */\n if (_gnutls_version_has_variable_padding (ver) && pad_failed == 0)\n for (i = 2; i <= pad; i++)\n {\n if (ciphertext.data[ciphertext.size - i] !=\n ciphertext.data[ciphertext.size - 1])\n pad_failed = GNUTLS_E_DECRYPTION_FAILED;\n }\n break;\n default:\n gnutls_assert ();\n return GNUTLS_E_INTERNAL_ERROR;\n }\n\n if (length < 0)\n length = 0;\n c_length = _gnutls_conv_uint16 ((uint16_t) length);\n\n /* Pass the type, version, length and compressed through\n * MAC.\n */\n if (params->mac_algorithm != GNUTLS_MAC_NULL)\n {\n digest_hd_st td;\n\n ret = mac_init (&td, params->mac_algorithm,\n params->read.mac_secret.data,\n params->read.mac_secret.size, ver);\n\n if (ret < 0)\n {\n gnutls_assert ();\n return GNUTLS_E_INTERNAL_ERROR;\n }\n\n preamble_size =\n make_preamble (UINT64DATA\n (params->read.sequence_number), type,\n c_length, ver, preamble);\n mac_hash (&td, preamble, preamble_size, ver);\n if (length > 0)\n mac_hash (&td, ciphertext.data, length, ver);\n\n mac_deinit (&td, MAC, ver);\n }\n\n /* This one was introduced to avoid a timing attack against the TLS\n * 1.0 protocol.\n */\n if (pad_failed != 0)\n {\n gnutls_assert ();\n return pad_failed;\n }\n\n /* HMAC was not the same. \n */\n if (memcmp (MAC, &ciphertext.data[length], hash_size) != 0)\n {\n gnutls_assert ();\n return GNUTLS_E_DECRYPTION_FAILED;\n }\n\n /* copy the decrypted stuff to compress_data.\n */\n if (compress_size < length)\n {\n gnutls_assert ();\n return GNUTLS_E_DECOMPRESSION_FAILED;\n }\n memcpy (compress_data, ciphertext.data, length);\n\n return length;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Fixes to avoid a timing attack in TLS CBC record parsing.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,\n\t\t\t struct inode *new_dir, struct dentry *new_dentry)\n{\n\tstruct btrfs_trans_handle *trans;\n\tstruct btrfs_root *root = BTRFS_I(old_dir)->root;\n\tstruct btrfs_root *dest = BTRFS_I(new_dir)->root;\n\tstruct inode *new_inode = new_dentry->d_inode;\n\tstruct inode *old_inode = old_dentry->d_inode;\n\tstruct timespec ctime = CURRENT_TIME;\n\tu64 index = 0;\n\tu64 root_objectid;\n\tint ret;\n\tu64 old_ino = btrfs_ino(old_inode);\n\n\tif (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)\n\t\treturn -EPERM;\n\n\t/* we only allow rename subvolume link between subvolumes */\n\tif (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)\n\t\treturn -EXDEV;\n\n\tif (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||\n\t (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))\n\t\treturn -ENOTEMPTY;\n\n\tif (S_ISDIR(old_inode->i_mode) && new_inode &&\n\t new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)\n\t\treturn -ENOTEMPTY;\n\t/*\n\t * we're using rename to replace one file with another.\n\t * and the replacement file is large. Start IO on it now so\n\t * we don't add too much work to the end of the transaction\n\t */\n\tif (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&\n\t old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)\n\t\tfilemap_flush(old_inode->i_mapping);\n\n\t/* close the racy window with snapshot create/destroy ioctl */\n\tif (old_ino == BTRFS_FIRST_FREE_OBJECTID)\n\t\tdown_read(&root->fs_info->subvol_sem);\n\t/*\n\t * We want to reserve the absolute worst case amount of items. So if\n\t * both inodes are subvols and we need to unlink them then that would\n\t * require 4 item modifications, but if they are both normal inodes it\n\t * would require 5 item modifications, so we'll assume their normal\n\t * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items\n\t * should cover the worst case number of items we'll modify.\n\t */\n\ttrans = btrfs_start_transaction(root, 20);\n\tif (IS_ERR(trans)) {\n ret = PTR_ERR(trans);\n goto out_notrans;\n }\n\n\tif (dest != root)\n\t\tbtrfs_record_root_in_trans(trans, dest);\n\n\tret = btrfs_set_inode_index(new_dir, &index);\n\tif (ret)\n\t\tgoto out_fail;\n\n\tif (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {\n\t\t/* force full log commit if subvolume involved. */\n\t\troot->fs_info->last_trans_log_full_commit = trans->transid;\n\t} else {\n\t\tret = btrfs_insert_inode_ref(trans, dest,\n\t\t\t\t\t new_dentry->d_name.name,\n\t\t\t\t\t new_dentry->d_name.len,\n\t\t\t\t\t old_ino,\n\t\t\t\t\t btrfs_ino(new_dir), index);\n\t\tif (ret)\n\t\t\tgoto out_fail;\n\t\t/*\n\t\t * this is an ugly little race, but the rename is required\n\t\t * to make sure that if we crash, the inode is either at the\n\t\t * old name or the new one. pinning the log transaction lets\n\t\t * us make sure we don't allow a log commit to come in after\n\t\t * we unlink the name but before we add the new name back in.\n\t\t */\n\t\tbtrfs_pin_log_trans(root);\n\t}\n\t/*\n\t * make sure the inode gets flushed if it is replacing\n\t * something.\n\t */\n\tif (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode))\n\t\tbtrfs_add_ordered_operation(trans, root, old_inode);\n\n\tinode_inc_iversion(old_dir);\n\tinode_inc_iversion(new_dir);\n\tinode_inc_iversion(old_inode);\n\told_dir->i_ctime = old_dir->i_mtime = ctime;\n\tnew_dir->i_ctime = new_dir->i_mtime = ctime;\n\told_inode->i_ctime = ctime;\n\n\tif (old_dentry->d_parent != new_dentry->d_parent)\n\t\tbtrfs_record_unlink_dir(trans, old_dir, old_inode, 1);\n\n\tif (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {\n\t\troot_objectid = BTRFS_I(old_inode)->root->root_key.objectid;\n\t\tret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,\n\t\t\t\t\told_dentry->d_name.name,\n\t\t\t\t\told_dentry->d_name.len);\n\t} else {\n\t\tret = __btrfs_unlink_inode(trans, root, old_dir,\n\t\t\t\t\told_dentry->d_inode,\n\t\t\t\t\told_dentry->d_name.name,\n\t\t\t\t\told_dentry->d_name.len);\n\t\tif (!ret)\n\t\t\tret = btrfs_update_inode(trans, root, old_inode);\n\t}\n\tif (ret) {\n\t\tbtrfs_abort_transaction(trans, root, ret);\n\t\tgoto out_fail;\n\t}\n\n\tif (new_inode) {\n\t\tinode_inc_iversion(new_inode);\n\t\tnew_inode->i_ctime = CURRENT_TIME;\n\t\tif (unlikely(btrfs_ino(new_inode) ==\n\t\t\t BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {\n\t\t\troot_objectid = BTRFS_I(new_inode)->location.objectid;\n\t\t\tret = btrfs_unlink_subvol(trans, dest, new_dir,\n\t\t\t\t\t\troot_objectid,\n\t\t\t\t\t\tnew_dentry->d_name.name,\n\t\t\t\t\t\tnew_dentry->d_name.len);\n\t\t\tBUG_ON(new_inode->i_nlink == 0);\n\t\t} else {\n\t\t\tret = btrfs_unlink_inode(trans, dest, new_dir,\n\t\t\t\t\t\t new_dentry->d_inode,\n\t\t\t\t\t\t new_dentry->d_name.name,\n\t\t\t\t\t\t new_dentry->d_name.len);\n\t\t}\n\t\tif (!ret && new_inode->i_nlink == 0) {\n\t\t\tret = btrfs_orphan_add(trans, new_dentry->d_inode);\n\t\t\tBUG_ON(ret);\n\t\t}\n\t\tif (ret) {\n\t\t\tbtrfs_abort_transaction(trans, root, ret);\n\t\t\tgoto out_fail;\n\t\t}\n\t}\n\n\tfixup_inode_flags(new_dir, old_inode);\n\n\tret = btrfs_add_link(trans, new_dir, old_inode,\n\t\t\t new_dentry->d_name.name,\n\t\t\t new_dentry->d_name.len, 0, index);\n\tif (ret) {\n\t\tbtrfs_abort_transaction(trans, root, ret);\n\t\tgoto out_fail;\n\t}\n\n\tif (old_ino != BTRFS_FIRST_FREE_OBJECTID) {\n\t\tstruct dentry *parent = new_dentry->d_parent;\n\t\tbtrfs_log_new_name(trans, old_inode, old_dir, parent);\n\t\tbtrfs_end_log_trans(root);\n\t}\nout_fail:\n\tbtrfs_end_transaction(trans, root);\nout_notrans:\n\tif (old_ino == BTRFS_FIRST_FREE_OBJECTID)\n\t\tup_read(&root->fs_info->subvol_sem);\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Btrfs: fix hash overflow handling\n\nThe handling for directory crc hash overflows was fairly obscure,\nsplit_leaf returns EOVERFLOW when we try to extend the item and that is\nsupposed to bubble up to userland. For a while it did so, but along the\nway we added better handling of errors and forced the FS readonly if we\nhit IO errors during the directory insertion.\n\nAlong the way, we started testing only for EEXIST and the EOVERFLOW case\nwas dropped. The end result is that we may force the FS readonly if we\ncatch a directory hash bucket overflow.\n\nThis fixes a few problem spots. First I add tests for EOVERFLOW in the\nplaces where we can safely just return the error up the chain.\n\nbtrfs_rename is harder though, because it tries to insert the new\ndirectory item only after it has already unlinked anything the rename\nwas going to overwrite. Rather than adding very complex logic, I added\na helper to test for the hash overflow case early while it is still safe\nto bail out.\n\nSnapshot and subvolume creation had a similar problem, so they are using\nthe new helper now too.\n\nSigned-off-by: Chris Mason \nReported-by: Pascal Junod '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline int pmd_large(pmd_t pte)\n{\n\treturn (pmd_flags(pte) & (_PAGE_PSE | _PAGE_PRESENT)) ==\n\t\t(_PAGE_PSE | _PAGE_PRESENT);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'mm: thp: fix pmd_present for split_huge_page and PROT_NONE with THP\n\nIn many places !pmd_present has been converted to pmd_none. For pmds\nthat's equivalent and pmd_none is quicker so using pmd_none is better.\n\nHowever (unless we delete pmd_present) we should provide an accurate\npmd_present too. This will avoid the risk of code thinking the pmd is non\npresent because it's under __split_huge_page_map, see the pmd_mknotpresent\nthere and the comment above it.\n\nIf the page has been mprotected as PROT_NONE, it would also lead to a\npmd_present false negative in the same way as the race with\nsplit_huge_page.\n\nBecause the PSE bit stays on at all times (both during split_huge_page and\nwhen the _PAGE_PROTNONE bit get set), we could only check for the PSE bit,\nbut checking the PROTNONE bit too is still good to remember pmd_present\nmust always keep PROT_NONE into account.\n\nThis explains a not reproducible BUG_ON that was seldom reported on the\nlists.\n\nThe same issue is in pmd_large, it would go wrong with both PROT_NONE and\nif it races with split_huge_page.\n\nSigned-off-by: Andrea Arcangeli \nAcked-by: Rik van Riel \nCc: Johannes Weiner \nCc: Hugh Dickins \nCc: Mel Gorman \nCc: \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void kvmclock_reset(struct kvm_vcpu *vcpu)\n{\n\tif (vcpu->arch.time_page) {\n\t\tkvm_release_page_dirty(vcpu->arch.time_page);\n\t\tvcpu->arch.time_page = NULL;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'KVM: x86: Convert MSR_KVM_SYSTEM_TIME to use gfn_to_hva_cache functions (CVE-2013-1797)\n\nThere is a potential use after free issue with the handling of\nMSR_KVM_SYSTEM_TIME. If the guest specifies a GPA in a movable or removable\nmemory such as frame buffers then KVM might continue to write to that\naddress even after it's removed via KVM_SET_USER_MEMORY_REGION. KVM pins\nthe page in memory so it's unlikely to cause an issue, but if the user\nspace component re-purposes the memory previously used for the guest, then\nthe guest will be able to corrupt that memory.\n\nTested: Tested against kvmclock unit test\n\nSigned-off-by: Andrew Honig \nSigned-off-by: Marcelo Tosatti '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static PHP_FUNCTION(libxml_disable_entity_loader)\n{\n\tzend_bool disable = 1;\n\txmlParserInputBufferCreateFilenameFunc old;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"|b\", &disable) == FAILURE) {\n\t\treturn;\n\t}\n\n\tif (disable == 0) {\n\t\told = xmlParserInputBufferCreateFilenameDefault(php_libxml_input_buffer_create_filename);\n\t} else {\n\t\told = xmlParserInputBufferCreateFilenameDefault(php_libxml_input_buffer_noload);\n\t}\n\n\tif (old == php_libxml_input_buffer_noload) {\n\t\tRETURN_TRUE;\n\t}\n\n\tRETURN_FALSE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Fixed external entity loading'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int dcbnl_getperm_hwaddr(struct net_device *netdev, struct nlmsghdr *nlh,\n\t\t\t\tu32 seq, struct nlattr **tb, struct sk_buff *skb)\n{\n\tu8 perm_addr[MAX_ADDR_LEN];\n\n\tif (!netdev->dcbnl_ops->getpermhwaddr)\n\t\treturn -EOPNOTSUPP;\n\n\tnetdev->dcbnl_ops->getpermhwaddr(netdev, perm_addr);\n\n\treturn nla_put(skb, DCB_ATTR_PERM_HWADDR, sizeof(perm_addr), perm_addr);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'dcbnl: fix various netlink info leaks\n\nThe dcb netlink interface leaks stack memory in various places:\n* perm_addr[] buffer is only filled at max with 12 of the 32 bytes but\n copied completely,\n* no in-kernel driver fills all fields of an IEEE 802.1Qaz subcommand,\n so we're leaking up to 58 bytes for ieee_ets structs, up to 136 bytes\n for ieee_pfc structs, etc.,\n* the same is true for CEE -- no in-kernel driver fills the whole\n struct,\n\nPrevent all of the above stack info leaks by properly initializing the\nbuffers/structures involved.\n\nSigned-off-by: Mathias Krause \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int __kvm_set_memory_region(struct kvm *kvm,\n\t\t\t struct kvm_userspace_memory_region *mem,\n\t\t\t int user_alloc)\n{\n\tint r;\n\tgfn_t base_gfn;\n\tunsigned long npages;\n\tunsigned long i;\n\tstruct kvm_memory_slot *memslot;\n\tstruct kvm_memory_slot old, new;\n\tstruct kvm_memslots *slots, *old_memslots;\n\n\tr = -EINVAL;\n\t/* General sanity checks */\n\tif (mem->memory_size & (PAGE_SIZE - 1))\n\t\tgoto out;\n\tif (mem->guest_phys_addr & (PAGE_SIZE - 1))\n\t\tgoto out;\n\tif (user_alloc && (mem->userspace_addr & (PAGE_SIZE - 1)))\n\t\tgoto out;\n\tif (mem->slot >= KVM_MEMORY_SLOTS + KVM_PRIVATE_MEM_SLOTS)\n\t\tgoto out;\n\tif (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)\n\t\tgoto out;\n\n\tmemslot = &kvm->memslots->memslots[mem->slot];\n\tbase_gfn = mem->guest_phys_addr >> PAGE_SHIFT;\n\tnpages = mem->memory_size >> PAGE_SHIFT;\n\n\tr = -EINVAL;\n\tif (npages > KVM_MEM_MAX_NR_PAGES)\n\t\tgoto out;\n\n\tif (!npages)\n\t\tmem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES;\n\n\tnew = old = *memslot;\n\n\tnew.id = mem->slot;\n\tnew.base_gfn = base_gfn;\n\tnew.npages = npages;\n\tnew.flags = mem->flags;\n\n\t/* Disallow changing a memory slot's size. */\n\tr = -EINVAL;\n\tif (npages && old.npages && npages != old.npages)\n\t\tgoto out_free;\n\n\t/* Check for overlaps */\n\tr = -EEXIST;\n\tfor (i = 0; i < KVM_MEMORY_SLOTS; ++i) {\n\t\tstruct kvm_memory_slot *s = &kvm->memslots->memslots[i];\n\n\t\tif (s == memslot || !s->npages)\n\t\t\tcontinue;\n\t\tif (!((base_gfn + npages <= s->base_gfn) ||\n\t\t (base_gfn >= s->base_gfn + s->npages)))\n\t\t\tgoto out_free;\n\t}\n\n\t/* Free page dirty bitmap if unneeded */\n\tif (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))\n\t\tnew.dirty_bitmap = NULL;\n\n\tr = -ENOMEM;\n\n\t/* Allocate if a slot is being created */\n#ifndef CONFIG_S390\n\tif (npages && !new.rmap) {\n\t\tnew.rmap = vzalloc(npages * sizeof(*new.rmap));\n\n\t\tif (!new.rmap)\n\t\t\tgoto out_free;\n\n\t\tnew.user_alloc = user_alloc;\n\t\tnew.userspace_addr = mem->userspace_addr;\n\t}\n\tif (!npages)\n\t\tgoto skip_lpage;\n\n\tfor (i = 0; i < KVM_NR_PAGE_SIZES - 1; ++i) {\n\t\tunsigned long ugfn;\n\t\tunsigned long j;\n\t\tint lpages;\n\t\tint level = i + 2;\n\n\t\t/* Avoid unused variable warning if no large pages */\n\t\t(void)level;\n\n\t\tif (new.lpage_info[i])\n\t\t\tcontinue;\n\n\t\tlpages = 1 + ((base_gfn + npages - 1)\n\t\t\t >> KVM_HPAGE_GFN_SHIFT(level));\n\t\tlpages -= base_gfn >> KVM_HPAGE_GFN_SHIFT(level);\n\n\t\tnew.lpage_info[i] = vzalloc(lpages * sizeof(*new.lpage_info[i]));\n\n\t\tif (!new.lpage_info[i])\n\t\t\tgoto out_free;\n\n\t\tif (base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))\n\t\t\tnew.lpage_info[i][0].write_count = 1;\n\t\tif ((base_gfn+npages) & (KVM_PAGES_PER_HPAGE(level) - 1))\n\t\t\tnew.lpage_info[i][lpages - 1].write_count = 1;\n\t\tugfn = new.userspace_addr >> PAGE_SHIFT;\n\t\t/*\n\t\t * If the gfn and userspace address are not aligned wrt each\n\t\t * other, or if explicitly asked to, disable large page\n\t\t * support for this slot\n\t\t */\n\t\tif ((base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||\n\t\t !largepages_enabled)\n\t\t\tfor (j = 0; j < lpages; ++j)\n\t\t\t\tnew.lpage_info[i][j].write_count = 1;\n\t}\n\nskip_lpage:\n\n\t/* Allocate page dirty bitmap if needed */\n\tif ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {\n\t\tif (kvm_create_dirty_bitmap(&new) < 0)\n\t\t\tgoto out_free;\n\t\t/* destroy any largepage mappings for dirty tracking */\n\t}\n#else /* not defined CONFIG_S390 */\n\tnew.user_alloc = user_alloc;\n\tif (user_alloc)\n\t\tnew.userspace_addr = mem->userspace_addr;\n#endif /* not defined CONFIG_S390 */\n\n\tif (!npages) {\n\t\tr = -ENOMEM;\n\t\tslots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);\n\t\tif (!slots)\n\t\t\tgoto out_free;\n\t\tmemcpy(slots, kvm->memslots, sizeof(struct kvm_memslots));\n\t\tif (mem->slot >= slots->nmemslots)\n\t\t\tslots->nmemslots = mem->slot + 1;\n\t\tslots->generation++;\n\t\tslots->memslots[mem->slot].flags |= KVM_MEMSLOT_INVALID;\n\n\t\told_memslots = kvm->memslots;\n\t\trcu_assign_pointer(kvm->memslots, slots);\n\t\tsynchronize_srcu_expedited(&kvm->srcu);\n\t\t/* From this point no new shadow pages pointing to a deleted\n\t\t * memslot will be created.\n\t\t *\n\t\t * validation of sp->gfn happens in:\n\t\t * \t- gfn_to_hva (kvm_read_guest, gfn_to_pfn)\n\t\t * \t- kvm_is_visible_gfn (mmu_check_roots)\n\t\t */\n\t\tkvm_arch_flush_shadow(kvm);\n\t\tkfree(old_memslots);\n\t}\n\n\tr = kvm_arch_prepare_memory_region(kvm, &new, old, mem, user_alloc);\n\tif (r)\n\t\tgoto out_free;\n\n\t/* map the pages in iommu page table */\n\tif (npages) {\n\t\tr = kvm_iommu_map_pages(kvm, &new);\n\t\tif (r)\n\t\t\tgoto out_free;\n\t}\n\n\tr = -ENOMEM;\n\tslots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);\n\tif (!slots)\n\t\tgoto out_free;\n\tmemcpy(slots, kvm->memslots, sizeof(struct kvm_memslots));\n\tif (mem->slot >= slots->nmemslots)\n\t\tslots->nmemslots = mem->slot + 1;\n\tslots->generation++;\n\n\t/* actual memory is freed via old in kvm_free_physmem_slot below */\n\tif (!npages) {\n\t\tnew.rmap = NULL;\n\t\tnew.dirty_bitmap = NULL;\n\t\tfor (i = 0; i < KVM_NR_PAGE_SIZES - 1; ++i)\n\t\t\tnew.lpage_info[i] = NULL;\n\t}\n\n\tslots->memslots[mem->slot] = new;\n\told_memslots = kvm->memslots;\n\trcu_assign_pointer(kvm->memslots, slots);\n\tsynchronize_srcu_expedited(&kvm->srcu);\n\n\tkvm_arch_commit_memory_region(kvm, mem, old, user_alloc);\n\n\tkvm_free_physmem_slot(&old, &new);\n\tkfree(old_memslots);\n\n\treturn 0;\n\nout_free:\n\tkvm_free_physmem_slot(&new, &old);\nout:\n\treturn r;\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-787'], 'message': 'KVM: Validate userspace_addr of memslot when registered\n\nThis way, we can avoid checking the user space address many times when\nwe read the guest memory.\n\nAlthough we can do the same for write if we check which slots are\nwritable, we do not care write now: reading the guest memory happens\nmore often than writing.\n\n[avi: change VERIFY_READ to VERIFY_WRITE]\n\nSigned-off-by: Takuya Yoshikawa \nSigned-off-by: Avi Kivity '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void pdf_parseobj(struct pdf_struct *pdf, struct pdf_obj *obj)\n{\n /* enough to hold common pdf names, we don't need all the names */\n char pdfname[64];\n const char *q2, *q3;\n const char *q = obj->start + pdf->map;\n const char *dict, *start;\n off_t dict_length;\n off_t bytesleft = obj_size(pdf, obj, 1);\n unsigned i, filters=0;\n enum objstate objstate = STATE_NONE;\n\n if (bytesleft < 0)\n\treturn;\n start = q;\n /* find start of dictionary */\n do {\n\tq2 = pdf_nextobject(q, bytesleft);\n\tbytesleft -= q2 -q;\n\tif (!q2 || bytesleft < 0) {\n\t return;\n\t}\n\tq3 = memchr(q-1, '<', q2-q+1);\n\tq2++;\n\tbytesleft--;\n\tq = q2;\n } while (!q3 || q3[1] != '<');\n dict = q3+2;\n q = dict;\n bytesleft = obj_size(pdf, obj, 1) - (q - start);\n /* find end of dictionary */\n do {\n\tq2 = pdf_nextobject(q, bytesleft);\n\tbytesleft -= q2 -q;\n\tif (!q2 || bytesleft < 0) {\n\t return;\n\t}\n\tq3 = memchr(q-1, '>', q2-q+1);\n\tq2++;\n\tbytesleft--;\n\tq = q2;\n } while (!q3 || q3[1] != '>');\n obj->flags |= 1 << OBJ_DICT;\n dict_length = q3 - dict;\n\n /* process pdf names */\n for (q = dict;dict_length > 0;) {\n\tint escapes = 0;\n\tq2 = memchr(q, '/', dict_length);\n\tif (!q2)\n\t break;\n\tdict_length -= q2 - q;\n\tq = q2;\n\t/* normalize PDF names */\n\tfor (i = 0;dict_length > 0 && (i < sizeof(pdfname)-1); i++) {\n\t q++;\n\t dict_length--;\n\t if (*q == '#') {\n\t\tif (cli_hex2str_to(q+1, pdfname+i, 2) == -1)\n\t\t break;\n\t\tq += 2;\n\t\tdict_length -= 2;\n\t\tescapes = 1;\n\t\tcontinue;\n\t }\n\t if (*q == ' ' || *q == '\\t' || *q == '\\r' || *q == '\\n' ||\n\t\t*q == '/' || *q == '>' || *q == ']' || *q == '[' || *q == '<'\n\t\t|| *q == '(')\n\t\tbreak;\n\t pdfname[i] = *q;\n\t}\n\tpdfname[i] = '\\0';\n\n\thandle_pdfname(pdf, obj, pdfname, escapes, &objstate);\n\tif (objstate == STATE_LINEARIZED) {\n\t long trailer_end, trailer;\n\t pdfobj_flag(pdf, obj, LINEARIZED_PDF);\n\t objstate = STATE_NONE;\n\t trailer_end = pdf_readint(q, dict_length, \"/H\");\n\t if (trailer_end > 0 && trailer_end < pdf->size) {\n\t\ttrailer = trailer_end - 1024;\n\t\tif (trailer < 0) trailer = 0;\n\t\tq2 = pdf->map + trailer;\n\t\tcli_dbgmsg(\"cli_pdf: looking for trailer in linearized pdf: %ld - %ld\\n\", trailer, trailer_end);\n\t\tpdf_parse_trailer(pdf, q2, trailer_end - trailer);\n\t\tif (pdf->fileID)\n\t\t cli_dbgmsg(\"cli_pdf: found fileID\\n\");\n\t }\n\t}\n\tif (objstate == STATE_LAUNCHACTION)\n\t pdfobj_flag(pdf, obj, HAS_LAUNCHACTION);\n\tif (dict_length > 0 && (objstate == STATE_JAVASCRIPT ||\n\t objstate == STATE_OPENACTION)) {\n\t if (objstate == STATE_OPENACTION)\n\t\tpdfobj_flag(pdf, obj, HAS_OPENACTION);\n\t q2 = pdf_nextobject(q, dict_length);\n\t if (q2 && isdigit(*q2)) {\n\t\tuint32_t objid = atoi(q2) << 8;\n\t\twhile (isdigit(*q2)) q2++;\n\t\tq2 = pdf_nextobject(q2, dict_length);\n\t\tif (q2 && isdigit(*q2)) {\n\t\t objid |= atoi(q2) & 0xff;\n\t\t q2 = pdf_nextobject(q2, dict_length);\n\t\t if (q2 && *q2 == 'R') {\n\t\t\tstruct pdf_obj *obj2;\n\t\t\tcli_dbgmsg(\"cli_pdf: found %s stored in indirect object %u %u\\n\",\n\t\t\t\t pdfname,\n\t\t\t\t objid >> 8, objid&0xff);\n\t\t\tobj2 = find_obj(pdf, obj, objid);\n\t\t\tif (obj2) {\n\t\t\t enum pdf_objflags flag = objstate == STATE_JAVASCRIPT ?\n\t\t\t\tOBJ_JAVASCRIPT : OBJ_OPENACTION;\n\t\t\t obj2->flags |= 1 << flag;\n\t\t\t obj->flags &= ~(1 << flag);\n\t\t\t} else {\n\t\t\t pdfobj_flag(pdf, obj, BAD_INDOBJ);\n\t\t\t}\n\t\t }\n\t\t}\n\t }\n\t objstate = STATE_NONE;\n\t}\n }\n for (i=0;iflags & (1 << act->set_objflag)) &&\n\t act->from_state == STATE_FILTER &&\n\t act->to_state == STATE_FILTER &&\n\t act->set_objflag != OBJ_FILTER_CRYPT &&\n\t act->set_objflag != OBJ_FILTER_STANDARD) {\n\t filters++;\n\t}\n }\n if (filters > 2) { /* more than 2 non-crypt filters */\n\tpdfobj_flag(pdf, obj, MANY_FILTERS);\n }\n if (obj->flags & ((1 << OBJ_SIGNED) | KNOWN_FILTERS))\n\tobj->flags &= ~(1 << OBJ_FILTER_UNKNOWN);\n if (obj->flags & (1 << OBJ_FILTER_UNKNOWN))\n\tpdfobj_flag(pdf, obj, UNKNOWN_FILTER);\n cli_dbgmsg(\"cli_pdf: %u %u obj flags: %02x\\n\", obj->id>>8, obj->id&0xff, obj->flags);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-189', 'CWE-79'], 'message': 'pdf: bb #7053'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int iscsi_add_notunderstood_response(\n\tchar *key,\n\tchar *value,\n\tstruct iscsi_param_list *param_list)\n{\n\tstruct iscsi_extra_response *extra_response;\n\n\tif (strlen(value) > VALUE_MAXLEN) {\n\t\tpr_err(\"Value for notunderstood key \\\"%s\\\" exceeds %d,\"\n\t\t\t\" protocol error.\\n\", key, VALUE_MAXLEN);\n\t\treturn -1;\n\t}\n\n\textra_response = kzalloc(sizeof(struct iscsi_extra_response), GFP_KERNEL);\n\tif (!extra_response) {\n\t\tpr_err(\"Unable to allocate memory for\"\n\t\t\t\" struct iscsi_extra_response.\\n\");\n\t\treturn -1;\n\t}\n\tINIT_LIST_HEAD(&extra_response->er_list);\n\n\tstrncpy(extra_response->key, key, strlen(key) + 1);\n\tstrncpy(extra_response->value, NOTUNDERSTOOD,\n\t\t\tstrlen(NOTUNDERSTOOD) + 1);\n\n\tlist_add_tail(&extra_response->er_list,\n\t\t\t¶m_list->extra_response_list);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'iscsi-target: fix heap buffer overflow on error\n\nIf a key was larger than 64 bytes, as checked by iscsi_check_key(), the\nerror response packet, generated by iscsi_add_notunderstood_response(),\nwould still attempt to copy the entire key into the packet, overflowing\nthe structure on the heap.\n\nRemote preauthentication kernel memory corruption was possible if a\ntarget was configured and listening on the network.\n\nCVE-2013-2850\n\nSigned-off-by: Kees Cook \nCc: stable@vger.kernel.org\nSigned-off-by: Nicholas Bellinger '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void b43_request_firmware(struct work_struct *work)\n{\n\tstruct b43_wl *wl = container_of(work,\n\t\t\t struct b43_wl, firmware_load);\n\tstruct b43_wldev *dev = wl->current_dev;\n\tstruct b43_request_fw_context *ctx;\n\tunsigned int i;\n\tint err;\n\tconst char *errmsg;\n\n\tctx = kzalloc(sizeof(*ctx), GFP_KERNEL);\n\tif (!ctx)\n\t\treturn;\n\tctx->dev = dev;\n\n\tctx->req_type = B43_FWTYPE_PROPRIETARY;\n\terr = b43_try_request_fw(ctx);\n\tif (!err)\n\t\tgoto start_ieee80211; /* Successfully loaded it. */\n\t/* Was fw version known? */\n\tif (ctx->fatal_failure)\n\t\tgoto out;\n\n\t/* proprietary fw not found, try open source */\n\tctx->req_type = B43_FWTYPE_OPENSOURCE;\n\terr = b43_try_request_fw(ctx);\n\tif (!err)\n\t\tgoto start_ieee80211; /* Successfully loaded it. */\n\tif(ctx->fatal_failure)\n\t\tgoto out;\n\n\t/* Could not find a usable firmware. Print the errors. */\n\tfor (i = 0; i < B43_NR_FWTYPES; i++) {\n\t\terrmsg = ctx->errors[i];\n\t\tif (strlen(errmsg))\n\t\t\tb43err(dev->wl, errmsg);\n\t}\n\tb43_print_fw_helptext(dev->wl, 1);\n\tgoto out;\n\nstart_ieee80211:\n\twl->hw->queues = B43_QOS_QUEUE_NUM;\n\tif (!modparam_qos || dev->fw.opensource)\n\t\twl->hw->queues = 1;\n\n\terr = ieee80211_register_hw(wl->hw);\n\tif (err)\n\t\tgoto err_one_core_detach;\n\twl->hw_registred = true;\n\tb43_leds_register(wl->current_dev);\n\tgoto out;\n\nerr_one_core_detach:\n\tb43_one_core_detach(dev->dev);\n\nout:\n\tkfree(ctx);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-134'], 'message': 'b43: stop format string leaking into error msgs\n\nThe module parameter \"fwpostfix\" is userspace controllable, unfiltered,\nand is used to define the firmware filename. b43_do_request_fw() populates\nctx->errors[] on error, containing the firmware filename. b43err()\nparses its arguments as a format string. For systems with b43 hardware,\nthis could lead to a uid-0 to ring-0 escalation.\n\nCVE-2013-2852\n\nSigned-off-by: Kees Cook \nCc: stable@vger.kernel.org\nSigned-off-by: John W. Linville '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: AlgorithmEnum* ZRtp::findBestSASType(ZrtpPacketHello *hello) {\n\n int i;\n int ii;\n int numAlgosOffered;\n AlgorithmEnum* algosOffered[ZrtpConfigure::maxNoOfAlgos+1];\n\n int numAlgosConf;\n AlgorithmEnum* algosConf[ZrtpConfigure::maxNoOfAlgos+1];\n\n int num = hello->getNumSas();\n if (num == 0) {\n return &zrtpSasTypes.getByName(mandatorySasType);\n }\n // Buildlist of configured SAS algorithm names\n numAlgosConf = configureAlgos.getNumConfiguredAlgos(SasType);\n for (i = 0; i < numAlgosConf; i++) {\n algosConf[i] = &configureAlgos.getAlgoAt(SasType, i);\n }\n // Build list of offered known algos in Hello,\n for (numAlgosOffered = 0, i = 0; i < num; i++) {\n algosOffered[numAlgosOffered] = &zrtpSasTypes.getByName((const char*)hello->getSasType(i++));\n if (!algosOffered[numAlgosOffered]->isValid())\n continue;\n numAlgosOffered++;\n }\n // Lookup offered algos in configured algos. Prefer algorithms that appear first in Hello packet (offered).\n for (i = 0; i < numAlgosOffered; i++) {\n for (ii = 0; ii < numAlgosConf; ii++) {\n if (*(int32_t*)(algosOffered[i]->getName()) == *(int32_t*)(algosConf[ii]->getName())) {\n return algosConf[ii];\n }\n }\n }\n // If we don't have a match - use the mandatory algorithm\n return &zrtpSasTypes.getByName(mandatorySasType);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix vulnerabilities found and reported by Mark Dowd\n\n- limit length of memcpy\n- limit number of offered algorithms in Hello packet\n- length check in PING packet\n- fix a small coding error'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void AuthorizationSession::addAuthorizedPrincipal(Principal* principal) {\n\n // Log out any already-logged-in user on the same database as \"principal\".\n logoutDatabase(principal->getName().getDB().toString()); // See SERVER-8144.\n\n _authenticatedPrincipals.add(principal);\n if (!principal->isImplicitPrivilegeAcquisitionEnabled())\n return;\n _acquirePrivilegesForPrincipalFromDatabase(ADMIN_DBNAME, principal->getName());\n principal->markDatabaseAsProbed(ADMIN_DBNAME);\n const std::string dbname = principal->getName().getDB().toString();\n _acquirePrivilegesForPrincipalFromDatabase(dbname, principal->getName());\n principal->markDatabaseAsProbed(dbname);\n _externalState->onAddAuthorizedPrincipal(principal);\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'SERVER-9983 Do not needlessly lock when looking up privileges for the __system@local user.\n\nUncorrected, this can cause replica set heartbeats to stall behind operations\nthat hold the read lock for a long time.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int credssp_skip_ts_request(int length)\n{\n\tlength += ber_skip_integer(2);\n\tlength += ber_skip_contextual_tag(3);\n\tlength += der_skip_sequence_tag(length);\n\treturn length;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed a range of BER boundary encoding bugs which would occur when any NLA packet hit the 127 character mark. Removed ber#get_content_length as it was not behaving deterministically.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int credssp_server_authenticate(rdpCredssp* credssp)\n{\n\tUINT32 cbMaxToken;\n\tULONG fContextReq;\n\tULONG pfContextAttr;\n\tSECURITY_STATUS status;\n\tCredHandle credentials;\n\tTimeStamp expiration;\n\tPSecPkgInfo pPackageInfo;\n\tSecBuffer input_buffer;\n\tSecBuffer output_buffer;\n\tSecBufferDesc input_buffer_desc;\n\tSecBufferDesc output_buffer_desc;\n\tBOOL have_context;\n\tBOOL have_input_buffer;\n\tBOOL have_pub_key_auth;\n\n\tsspi_GlobalInit();\n\n\tif (credssp_ntlm_server_init(credssp) == 0)\n\t\treturn 0;\n\n#ifdef WITH_NATIVE_SSPI\n\tif (!credssp->SspiModule)\n\t\tcredssp->SspiModule = _tcsdup(_T(\"secur32.dll\"));\n#endif\n\n\tif (credssp->SspiModule)\n\t{\n\t\tHMODULE hSSPI;\n\t\tINIT_SECURITY_INTERFACE pInitSecurityInterface;\n\n\t\thSSPI = LoadLibrary(credssp->SspiModule);\n\n\t\tif (!hSSPI)\n\t\t{\n\t\t\t_tprintf(_T(\"Failed to load SSPI module: %s\\n\"), credssp->SspiModule);\n\t\t\treturn 0;\n\t\t}\n\n#ifdef UNICODE\n\t\tpInitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress(hSSPI, \"InitSecurityInterfaceW\");\n#else\n\t\tpInitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress(hSSPI, \"InitSecurityInterfaceA\");\n#endif\n\n\t\tcredssp->table = (*pInitSecurityInterface)();\n\t}\n#ifndef WITH_NATIVE_SSPI\n\telse\n\t{\n\t\tcredssp->table = InitSecurityInterface();\n\t}\n#endif\n\n\tstatus = credssp->table->QuerySecurityPackageInfo(NLA_PKG_NAME, &pPackageInfo);\n\n\tif (status != SEC_E_OK)\n\t{\n\t\tfprintf(stderr, \"QuerySecurityPackageInfo status: 0x%08X\\n\", status);\n\t\treturn 0;\n\t}\n\n\tcbMaxToken = pPackageInfo->cbMaxToken;\n\n\tstatus = credssp->table->AcquireCredentialsHandle(NULL, NLA_PKG_NAME,\n\t\t\tSECPKG_CRED_INBOUND, NULL, NULL, NULL, NULL, &credentials, &expiration);\n\n\tif (status != SEC_E_OK)\n\t{\n\t\tfprintf(stderr, \"AcquireCredentialsHandle status: 0x%08X\\n\", status);\n\t\treturn 0;\n\t}\n\n\thave_context = FALSE;\n\thave_input_buffer = FALSE;\n\thave_pub_key_auth = FALSE;\n\tZeroMemory(&input_buffer, sizeof(SecBuffer));\n\tZeroMemory(&output_buffer, sizeof(SecBuffer));\n\tZeroMemory(&input_buffer_desc, sizeof(SecBufferDesc));\n\tZeroMemory(&output_buffer_desc, sizeof(SecBufferDesc));\n\tZeroMemory(&credssp->ContextSizes, sizeof(SecPkgContext_Sizes));\n\n\t/* \n\t * from tspkg.dll: 0x00000112\n\t * ASC_REQ_MUTUAL_AUTH\n\t * ASC_REQ_CONFIDENTIALITY\n\t * ASC_REQ_ALLOCATE_MEMORY\n\t */\n\n\tfContextReq = 0;\n\tfContextReq |= ASC_REQ_MUTUAL_AUTH;\n\tfContextReq |= ASC_REQ_CONFIDENTIALITY;\n\n\tfContextReq |= ASC_REQ_CONNECTION;\n\tfContextReq |= ASC_REQ_USE_SESSION_KEY;\n\n\tfContextReq |= ASC_REQ_REPLAY_DETECT;\n\tfContextReq |= ASC_REQ_SEQUENCE_DETECT;\n\n\tfContextReq |= ASC_REQ_EXTENDED_ERROR;\n\n\twhile (TRUE)\n\t{\n\t\tinput_buffer_desc.ulVersion = SECBUFFER_VERSION;\n\t\tinput_buffer_desc.cBuffers = 1;\n\t\tinput_buffer_desc.pBuffers = &input_buffer;\n\t\tinput_buffer.BufferType = SECBUFFER_TOKEN;\n\n\t\t/* receive authentication token */\n\n\t\tinput_buffer_desc.ulVersion = SECBUFFER_VERSION;\n\t\tinput_buffer_desc.cBuffers = 1;\n\t\tinput_buffer_desc.pBuffers = &input_buffer;\n\t\tinput_buffer.BufferType = SECBUFFER_TOKEN;\n\n\t\tif (credssp_recv(credssp) < 0)\n\t\t\treturn -1;\n\n#ifdef WITH_DEBUG_CREDSSP\n\t\tfprintf(stderr, \"Receiving Authentication Token\\n\");\n\t\tcredssp_buffer_print(credssp);\n#endif\n\n\t\tinput_buffer.pvBuffer = credssp->negoToken.pvBuffer;\n\t\tinput_buffer.cbBuffer = credssp->negoToken.cbBuffer;\n\n\t\tif (credssp->negoToken.cbBuffer < 1)\n\t\t{\n\t\t\tfprintf(stderr, \"CredSSP: invalid negoToken!\\n\");\n\t\t\treturn -1;\n\t\t}\n\n\t\toutput_buffer_desc.ulVersion = SECBUFFER_VERSION;\n\t\toutput_buffer_desc.cBuffers = 1;\n\t\toutput_buffer_desc.pBuffers = &output_buffer;\n\t\toutput_buffer.BufferType = SECBUFFER_TOKEN;\n\t\toutput_buffer.cbBuffer = cbMaxToken;\n\t\toutput_buffer.pvBuffer = malloc(output_buffer.cbBuffer);\n\n\t\tstatus = credssp->table->AcceptSecurityContext(&credentials,\n\t\t\thave_context? &credssp->context: NULL,\n\t\t\t&input_buffer_desc, fContextReq, SECURITY_NATIVE_DREP, &credssp->context,\n\t\t\t&output_buffer_desc, &pfContextAttr, &expiration);\n\n\t\tcredssp->negoToken.pvBuffer = output_buffer.pvBuffer;\n\t\tcredssp->negoToken.cbBuffer = output_buffer.cbBuffer;\n\n\t\tif ((status == SEC_I_COMPLETE_AND_CONTINUE) || (status == SEC_I_COMPLETE_NEEDED))\n\t\t{\n\t\t\tif (credssp->table->CompleteAuthToken != NULL)\n\t\t\t\tcredssp->table->CompleteAuthToken(&credssp->context, &output_buffer_desc);\n\n\t\t\tif (status == SEC_I_COMPLETE_NEEDED)\n\t\t\t\tstatus = SEC_E_OK;\n\t\t\telse if (status == SEC_I_COMPLETE_AND_CONTINUE)\n\t\t\t\tstatus = SEC_I_CONTINUE_NEEDED;\n\t\t}\n\n\t\tif (status == SEC_E_OK)\n\t\t{\n\t\t\thave_pub_key_auth = TRUE;\n\n\t\t\tif (credssp->table->QueryContextAttributes(&credssp->context, SECPKG_ATTR_SIZES, &credssp->ContextSizes) != SEC_E_OK)\n\t\t\t{\n\t\t\t\tfprintf(stderr, \"QueryContextAttributes SECPKG_ATTR_SIZES failure\\n\");\n\t\t\t\treturn 0;\n\t\t\t}\n\n\t\t\tif (credssp_decrypt_public_key_echo(credssp) != SEC_E_OK)\n\t\t\t{\n\t\t\t\tfprintf(stderr, \"Error: could not verify client's public key echo\\n\");\n\t\t\t\treturn -1;\n\t\t\t}\n\n\t\t\tsspi_SecBufferFree(&credssp->negoToken);\n\t\t\tcredssp->negoToken.pvBuffer = NULL;\n\t\t\tcredssp->negoToken.cbBuffer = 0;\n\n\t\t\tcredssp_encrypt_public_key_echo(credssp);\n\t\t}\n\n\t\tif ((status != SEC_E_OK) && (status != SEC_I_CONTINUE_NEEDED))\n\t\t{\n\t\t\tfprintf(stderr, \"AcceptSecurityContext status: 0x%08X\\n\", status);\n\t\t\treturn -1;\n\t\t}\n\n\t\t/* send authentication token */\n\n#ifdef WITH_DEBUG_CREDSSP\n\t\tfprintf(stderr, \"Sending Authentication Token\\n\");\n\t\tcredssp_buffer_print(credssp);\n#endif\n\n\t\tcredssp_send(credssp);\n\t\tcredssp_buffer_free(credssp);\n\n\t\tif (status != SEC_I_CONTINUE_NEEDED)\n\t\t\tbreak;\n\n\t\thave_context = TRUE;\n\t}\n\n\t/* Receive encrypted credentials */\n\n\tif (credssp_recv(credssp) < 0)\n\t\treturn -1;\n\n\tif (credssp_decrypt_ts_credentials(credssp) != SEC_E_OK)\n\t{\n\t\tfprintf(stderr, \"Could not decrypt TSCredentials status: 0x%08X\\n\", status);\n\t\treturn 0;\n\t}\n\n\tif (status != SEC_E_OK)\n\t{\n\t\tfprintf(stderr, \"AcceptSecurityContext status: 0x%08X\\n\", status);\n\t\treturn 0;\n\t}\n\n\tstatus = credssp->table->ImpersonateSecurityContext(&credssp->context);\n\n\tif (status != SEC_E_OK)\n\t{\n\t\tfprintf(stderr, \"ImpersonateSecurityContext status: 0x%08X\\n\", status);\n\t\treturn 0;\n\t}\n\telse\n\t{\n\t\tstatus = credssp->table->RevertSecurityContext(&credssp->context);\n\n\t\tif (status != SEC_E_OK)\n\t\t{\n\t\t\tfprintf(stderr, \"RevertSecurityContext status: 0x%08X\\n\", status);\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\tcredssp->table->FreeContextBuffer(pPackageInfo);\n\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed a range of BER boundary encoding bugs which would occur when any NLA packet hit the 127 character mark. Removed ber#get_content_length as it was not behaving deterministically.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: BOOL ber_read_enumerated(wStream* s, BYTE* enumerated, BYTE count)\n{\n\tint length;\n\n\tif(!ber_read_universal_tag(s, BER_TAG_ENUMERATED, FALSE) ||\n\t\t!ber_read_length(s, &length))\n\t\treturn FALSE;\n\n\tif (length != 1 || Stream_GetRemainingLength(s) < 1)\n\t\treturn FALSE;\n\n\tStream_Read_UINT8(s, *enumerated);\n\n\t/* check that enumerated value falls within expected range */\n\tif (*enumerated + 1 > count)\n\t\treturn FALSE;\n\n\treturn TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed a range of BER boundary encoding bugs which would occur when any NLA packet hit the 127 character mark. Removed ber#get_content_length as it was not behaving deterministically.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ber_write_integer(wStream* s, UINT32 value)\n{\n\tber_write_universal_tag(s, BER_TAG_INTEGER, FALSE);\n\n\tif (value < 0x80)\n\t{\n\t\tber_write_length(s, 1);\n\t\tStream_Write_UINT8(s, value);\n\t\treturn 3;\n\t}\n\telse if (value < 0x8000)\n\t{\n\t\tber_write_length(s, 2);\n\t\tStream_Write_UINT16_BE(s, value);\n\t\treturn 4;\n\t}\n\telse if (value < 0x800000)\n\t{\n\t\tber_write_length(s, 3);\n\t\tStream_Write_UINT8(s, (value >> 16));\n\t\tStream_Write_UINT16_BE(s, (value & 0xFFFF));\n\t\treturn 5;\n\t}\n\telse if (value < 0x80000000)\n\t{\n\t\tber_write_length(s, 4);\n\t\tStream_Write_UINT32_BE(s, value);\n\t\treturn 6;\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Finished merging missing changes from pull request #1257 (https://github.com/FreeRDP/FreeRDP/pull/1257 - commit 0dc22d5). Correctly report the length of ts_password_creds.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void* sspi_SecureHandleGetUpperPointer(SecHandle* handle)\n{\n\tvoid* pointer;\n\n\tif (!handle)\n\t\treturn NULL;\n\n\tpointer = (void*) ~((size_t) handle->dwUpper);\n\n\treturn pointer;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-125'], 'message': 'nla: invalidate sec handle after creation\n\nIf sec pointer isn't invalidated after creation it is not possible\nto check if the upper and lower pointers are valid.\n\nThis fixes a segfault in the server part if the client disconnects before\nthe authentication was finished.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: xmlParseChunk(xmlParserCtxtPtr ctxt, const char *chunk, int size,\n int terminate) {\n int end_in_lf = 0;\n int remain = 0;\n size_t old_avail = 0;\n size_t avail = 0;\n\n if (ctxt == NULL)\n return(XML_ERR_INTERNAL_ERROR);\n if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1))\n return(ctxt->errNo);\n if (ctxt->instate == XML_PARSER_EOF)\n return(-1);\n if (ctxt->instate == XML_PARSER_START)\n xmlDetectSAX2(ctxt);\n if ((size > 0) && (chunk != NULL) && (!terminate) &&\n (chunk[size - 1] == '\\r')) {\n\tend_in_lf = 1;\n\tsize--;\n }\n\nxmldecl_done:\n\n if ((size > 0) && (chunk != NULL) && (ctxt->input != NULL) &&\n (ctxt->input->buf != NULL) && (ctxt->instate != XML_PARSER_EOF)) {\n\tsize_t base = xmlBufGetInputBase(ctxt->input->buf->buffer, ctxt->input);\n\tsize_t cur = ctxt->input->cur - ctxt->input->base;\n\tint res;\n\n old_avail = xmlBufUse(ctxt->input->buf->buffer);\n /*\n * Specific handling if we autodetected an encoding, we should not\n * push more than the first line ... which depend on the encoding\n * And only push the rest once the final encoding was detected\n */\n if ((ctxt->instate == XML_PARSER_START) && (ctxt->input != NULL) &&\n (ctxt->input->buf != NULL) && (ctxt->input->buf->encoder != NULL)) {\n unsigned int len = 45;\n\n if ((xmlStrcasestr(BAD_CAST ctxt->input->buf->encoder->name,\n BAD_CAST \"UTF-16\")) ||\n (xmlStrcasestr(BAD_CAST ctxt->input->buf->encoder->name,\n BAD_CAST \"UTF16\")))\n len = 90;\n else if ((xmlStrcasestr(BAD_CAST ctxt->input->buf->encoder->name,\n BAD_CAST \"UCS-4\")) ||\n (xmlStrcasestr(BAD_CAST ctxt->input->buf->encoder->name,\n BAD_CAST \"UCS4\")))\n len = 180;\n\n if (ctxt->input->buf->rawconsumed < len)\n len -= ctxt->input->buf->rawconsumed;\n\n /*\n * Change size for reading the initial declaration only\n * if size is greater than len. Otherwise, memmove in xmlBufferAdd\n * will blindly copy extra bytes from memory.\n */\n if ((unsigned int) size > len) {\n remain = size - len;\n size = len;\n } else {\n remain = 0;\n }\n }\n\tres = xmlParserInputBufferPush(ctxt->input->buf, size, chunk);\n\tif (res < 0) {\n\t ctxt->errNo = XML_PARSER_EOF;\n\t ctxt->disableSAX = 1;\n\t return (XML_PARSER_EOF);\n\t}\n xmlBufSetInputBaseCur(ctxt->input->buf->buffer, ctxt->input, base, cur);\n#ifdef DEBUG_PUSH\n\txmlGenericError(xmlGenericErrorContext, \"PP: pushed %d\\n\", size);\n#endif\n\n } else if (ctxt->instate != XML_PARSER_EOF) {\n\tif ((ctxt->input != NULL) && ctxt->input->buf != NULL) {\n\t xmlParserInputBufferPtr in = ctxt->input->buf;\n\t if ((in->encoder != NULL) && (in->buffer != NULL) &&\n\t\t (in->raw != NULL)) {\n\t\tint nbchars;\n\t\tsize_t base = xmlBufGetInputBase(in->buffer, ctxt->input);\n\t\tsize_t current = ctxt->input->cur - ctxt->input->base;\n\n\t\tnbchars = xmlCharEncInput(in, terminate);\n\t\tif (nbchars < 0) {\n\t\t /* TODO 2.6.0 */\n\t\t xmlGenericError(xmlGenericErrorContext,\n\t\t\t\t \"xmlParseChunk: encoder error\\n\");\n\t\t return(XML_ERR_INVALID_ENCODING);\n\t\t}\n\t\txmlBufSetInputBaseCur(in->buffer, ctxt->input, base, current);\n\t }\n\t}\n }\n if (remain != 0) {\n xmlParseTryOrFinish(ctxt, 0);\n } else {\n if ((ctxt->input != NULL) && (ctxt->input->buf != NULL))\n avail = xmlBufUse(ctxt->input->buf->buffer);\n /*\n * Depending on the current state it may not be such\n * a good idea to try parsing if there is nothing in the chunk\n * which would be worth doing a parser state transition and we\n * need to wait for more data\n */\n if ((terminate) || (avail > XML_MAX_TEXT_LENGTH) ||\n (old_avail == 0) || (avail == 0) ||\n (xmlParseCheckTransition(ctxt,\n (const char *)&ctxt->input->base[old_avail],\n avail - old_avail)))\n xmlParseTryOrFinish(ctxt, terminate);\n }\n if ((ctxt->input != NULL) &&\n (((ctxt->input->end - ctxt->input->cur) > XML_MAX_LOOKUP_LIMIT) ||\n ((ctxt->input->cur - ctxt->input->base) > XML_MAX_LOOKUP_LIMIT)) &&\n ((ctxt->options & XML_PARSE_HUGE) == 0)) {\n xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, \"Huge input lookup\");\n ctxt->instate = XML_PARSER_EOF;\n }\n if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1))\n return(ctxt->errNo);\n\n if (remain != 0) {\n chunk += size;\n size = remain;\n remain = 0;\n goto xmldecl_done;\n }\n if ((end_in_lf == 1) && (ctxt->input != NULL) &&\n (ctxt->input->buf != NULL)) {\n\tsize_t base = xmlBufGetInputBase(ctxt->input->buf->buffer,\n\t\t\t\t\t ctxt->input);\n\tsize_t current = ctxt->input->cur - ctxt->input->base;\n\n\txmlParserInputBufferPush(ctxt->input->buf, 1, \"\\r\");\n\n\txmlBufSetInputBaseCur(ctxt->input->buf->buffer, ctxt->input,\n\t\t\t base, current);\n }\n if (terminate) {\n\t/*\n\t * Check for termination\n\t */\n\tint cur_avail = 0;\n\n\tif (ctxt->input != NULL) {\n\t if (ctxt->input->buf == NULL)\n\t\tcur_avail = ctxt->input->length -\n\t\t\t (ctxt->input->cur - ctxt->input->base);\n\t else\n\t\tcur_avail = xmlBufUse(ctxt->input->buf->buffer) -\n\t\t\t (ctxt->input->cur - ctxt->input->base);\n\t}\n\n\tif ((ctxt->instate != XML_PARSER_EOF) &&\n\t (ctxt->instate != XML_PARSER_EPILOG)) {\n\t xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL);\n\t}\n\tif ((ctxt->instate == XML_PARSER_EPILOG) && (cur_avail > 0)) {\n\t xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL);\n\t}\n\tif (ctxt->instate != XML_PARSER_EOF) {\n\t if ((ctxt->sax) && (ctxt->sax->endDocument != NULL))\n\t\tctxt->sax->endDocument(ctxt->userData);\n\t}\n\tctxt->instate = XML_PARSER_EOF;\n }\n if (ctxt->wellFormed == 0)\n\treturn((xmlParserErrors) ctxt->errNo);\n else\n return(0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Improve handling of xmlStopParser()\n\nAdd a specific parser error\nTry to stop parsing as quickly as possible'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void _xml_startElementHandler(void *userData, const XML_Char *name, const XML_Char **attributes)\n{\n\txml_parser *parser = (xml_parser *)userData;\n\tconst char **attrs = (const char **) attributes;\n\tchar *tag_name;\n\tchar *att, *val;\n\tint val_len;\n\tzval *retval, *args[3];\n\n\tif (parser) {\n\t\tparser->level++;\n\n\t\ttag_name = _xml_decode_tag(parser, name);\n\n\t\tif (parser->startElementHandler) {\n\t\t\targs[0] = _xml_resource_zval(parser->index);\n\t\t\targs[1] = _xml_string_zval(((char *) tag_name) + parser->toffset);\n\t\t\tMAKE_STD_ZVAL(args[2]);\n\t\t\tarray_init(args[2]);\n\n\t\t\twhile (attributes && *attributes) {\n\t\t\t\tatt = _xml_decode_tag(parser, attributes[0]);\n\t\t\t\tval = xml_utf8_decode(attributes[1], strlen(attributes[1]), &val_len, parser->target_encoding);\n\n\t\t\t\tadd_assoc_stringl(args[2], att, val, val_len, 0);\n\n\t\t\t\tattributes += 2;\n\n\t\t\t\tefree(att);\n\t\t\t}\n\t\t\t\n\t\t\tif ((retval = xml_call_handler(parser, parser->startElementHandler, parser->startElementPtr, 3, args))) {\n\t\t\t\tzval_ptr_dtor(&retval);\n\t\t\t}\n\t\t} \n\n\t\tif (parser->data) {\n\t\t\tzval *tag, *atr;\n\t\t\tint atcnt = 0;\n\n\t\t\tMAKE_STD_ZVAL(tag);\n\t\t\tMAKE_STD_ZVAL(atr);\n\n\t\t\tarray_init(tag);\n\t\t\tarray_init(atr);\n\n\t\t\t_xml_add_to_info(parser,((char *) tag_name) + parser->toffset);\n\n\t\t\tadd_assoc_string(tag,\"tag\",((char *) tag_name) + parser->toffset,1); /* cast to avoid gcc-warning */\n\t\t\tadd_assoc_string(tag,\"type\",\"open\",1);\n\t\t\tadd_assoc_long(tag,\"level\",parser->level);\n\n\t\t\tparser->ltags[parser->level-1] = estrdup(tag_name);\n\t\t\tparser->lastwasopen = 1;\n\n\t\t\tattributes = (const XML_Char **) attrs;\n\n\t\t\twhile (attributes && *attributes) {\n\t\t\t\tatt = _xml_decode_tag(parser, attributes[0]);\n\t\t\t\tval = xml_utf8_decode(attributes[1], strlen(attributes[1]), &val_len, parser->target_encoding);\n\t\t\t\t\n\t\t\t\tadd_assoc_stringl(atr,att,val,val_len,0);\n\n\t\t\t\tatcnt++;\n\t\t\t\tattributes += 2;\n\n\t\t\t\tefree(att);\n\t\t\t}\n\n\t\t\tif (atcnt) {\n\t\t\t\tzend_hash_add(Z_ARRVAL_P(tag),\"attributes\",sizeof(\"attributes\"),&atr,sizeof(zval*),NULL);\n\t\t\t} else {\n\t\t\t\tzval_ptr_dtor(&atr);\n\t\t\t}\n\n\t\t\tzend_hash_next_index_insert(Z_ARRVAL_P(parser->data),&tag,sizeof(zval*),(void *) &parser->ctag);\n\t\t}\n\n\t\tefree(tag_name);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'truncate results at depth of 255 to prevent corruption'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int __br_mdb_del(struct net_bridge *br, struct br_mdb_entry *entry)\n{\n\tstruct net_bridge_mdb_htable *mdb;\n\tstruct net_bridge_mdb_entry *mp;\n\tstruct net_bridge_port_group *p;\n\tstruct net_bridge_port_group __rcu **pp;\n\tstruct br_ip ip;\n\tint err = -EINVAL;\n\n\tif (!netif_running(br->dev) || br->multicast_disabled)\n\t\treturn -EINVAL;\n\n\tif (timer_pending(&br->multicast_querier_timer))\n\t\treturn -EBUSY;\n\n\tip.proto = entry->addr.proto;\n\tif (ip.proto == htons(ETH_P_IP))\n\t\tip.u.ip4 = entry->addr.u.ip4;\n#if IS_ENABLED(CONFIG_IPV6)\n\telse\n\t\tip.u.ip6 = entry->addr.u.ip6;\n#endif\n\n\tspin_lock_bh(&br->multicast_lock);\n\tmdb = mlock_dereference(br->mdb, br);\n\n\tmp = br_mdb_ip_get(mdb, &ip);\n\tif (!mp)\n\t\tgoto unlock;\n\n\tfor (pp = &mp->ports;\n\t (p = mlock_dereference(*pp, br)) != NULL;\n\t pp = &p->next) {\n\t\tif (!p->port || p->port->dev->ifindex != entry->ifindex)\n\t\t\tcontinue;\n\n\t\tif (p->port->state == BR_STATE_DISABLED)\n\t\t\tgoto unlock;\n\n\t\trcu_assign_pointer(*pp, p->next);\n\t\thlist_del_init(&p->mglist);\n\t\tdel_timer(&p->timer);\n\t\tcall_rcu_bh(&p->rcu, br_multicast_free_pg);\n\t\terr = 0;\n\n\t\tif (!mp->ports && !mp->mglist &&\n\t\t netif_running(br->dev))\n\t\t\tmod_timer(&mp->timer, jiffies);\n\t\tbreak;\n\t}\n\nunlock:\n\tspin_unlock_bh(&br->multicast_lock);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'bridge: fix some kernel warning in multicast timer\n\nSeveral people reported the warning: \"kernel BUG at kernel/timer.c:729!\"\nand the stack trace is:\n\n\t#7 [ffff880214d25c10] mod_timer+501 at ffffffff8106d905\n\t#8 [ffff880214d25c50] br_multicast_del_pg.isra.20+261 at ffffffffa0731d25 [bridge]\n\t#9 [ffff880214d25c80] br_multicast_disable_port+88 at ffffffffa0732948 [bridge]\n\t#10 [ffff880214d25cb0] br_stp_disable_port+154 at ffffffffa072bcca [bridge]\n\t#11 [ffff880214d25ce8] br_device_event+520 at ffffffffa072a4e8 [bridge]\n\t#12 [ffff880214d25d18] notifier_call_chain+76 at ffffffff8164aafc\n\t#13 [ffff880214d25d50] raw_notifier_call_chain+22 at ffffffff810858f6\n\t#14 [ffff880214d25d60] call_netdevice_notifiers+45 at ffffffff81536aad\n\t#15 [ffff880214d25d80] dev_close_many+183 at ffffffff81536d17\n\t#16 [ffff880214d25dc0] rollback_registered_many+168 at ffffffff81537f68\n\t#17 [ffff880214d25de8] rollback_registered+49 at ffffffff81538101\n\t#18 [ffff880214d25e10] unregister_netdevice_queue+72 at ffffffff815390d8\n\t#19 [ffff880214d25e30] __tun_detach+272 at ffffffffa074c2f0 [tun]\n\t#20 [ffff880214d25e88] tun_chr_close+45 at ffffffffa074c4bd [tun]\n\t#21 [ffff880214d25ea8] __fput+225 at ffffffff8119b1f1\n\t#22 [ffff880214d25ef0] ____fput+14 at ffffffff8119b3fe\n\t#23 [ffff880214d25f00] task_work_run+159 at ffffffff8107cf7f\n\t#24 [ffff880214d25f30] do_notify_resume+97 at ffffffff810139e1\n\t#25 [ffff880214d25f50] int_signal+18 at ffffffff8164f292\n\nthis is due to I forgot to check if mp->timer is armed in\nbr_multicast_del_pg(). This bug is introduced by\ncommit 9f00b2e7cf241fa389733d41b6 (bridge: only expire the mdb entry\nwhen query is received).\n\nSame for __br_mdb_del().\n\nTested-by: poma \nReported-by: LiYonghua <809674045@qq.com>\nReported-by: Robert Hancock \nCc: Herbert Xu \nCc: Stephen Hemminger \nCc: \"David S. Miller\" \nSigned-off-by: Cong Wang \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: \tFileDescriptor connectToHelperAgent() {\n\t\tTRACE_POINT();\n\t\tFileDescriptor conn;\n\t\t\n\t\ttry {\n\t\t\tconn = connectToUnixServer(agentsStarter.getRequestSocketFilename());\n\t\t\twriteExact(conn, agentsStarter.getRequestSocketPassword());\n\t\t} catch (const SystemException &e) {\n\t\t\tif (e.code() == EPIPE || e.code() == ECONNREFUSED || e.code() == ENOENT) {\n\t\t\t\tUPDATE_TRACE_POINT();\n\t\t\t\tbool connected = false;\n\t\t\t\t\n\t\t\t\t// Maybe the helper agent crashed. First wait 50 ms.\n\t\t\t\tusleep(50000);\n\t\t\t\t\n\t\t\t\t// Then try to reconnect to the helper agent for the\n\t\t\t\t// next 5 seconds.\n\t\t\t\ttime_t deadline = time(NULL) + 5;\n\t\t\t\twhile (!connected && time(NULL) < deadline) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconn = connectToUnixServer(agentsStarter.getRequestSocketFilename());\n\t\t\t\t\t\twriteExact(conn, agentsStarter.getRequestSocketPassword());\n\t\t\t\t\t\tconnected = true;\n\t\t\t\t\t} catch (const SystemException &e) {\n\t\t\t\t\t\tif (e.code() == EPIPE || e.code() == ECONNREFUSED || e.code() == ENOENT) {\n\t\t\t\t\t\t\t// Looks like the helper agent hasn't been\n\t\t\t\t\t\t\t// restarted yet. Wait between 20 and 100 ms.\n\t\t\t\t\t\t\tusleep(20000 + rand() % 80000);\n\t\t\t\t\t\t\t// Don't care about thread-safety of rand()\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tthrow;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (!connected) {\n\t\t\t\t\tUPDATE_TRACE_POINT();\n\t\t\t\t\tthrow IOException(\"Cannot connect to the helper agent\");\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthrow;\n\t\t\t}\n\t\t}\n\t\treturn conn;\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59'], 'message': 'Fixed a problem with graceful web server restarts.\nThis problem was introduced in 4.0.6 during the attempt to fix issue #910.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void php_session_reset_id(TSRMLS_D) /* {{{ */\n{\n\tint module_number = PS(module_number);\n\n\tif (PS(use_cookies) && PS(send_cookie)) {\n\t\tphp_session_send_cookie(TSRMLS_C);\n\t\tPS(send_cookie) = 0;\n\t}\n\n\t/* if the SID constant exists, destroy it. */\n\tzend_hash_del(EG(zend_constants), \"sid\", sizeof(\"sid\"));\n\n\tif (PS(define_sid)) {\n\t\tsmart_str var = {0};\n\n\t\tsmart_str_appends(&var, PS(session_name));\n\t\tsmart_str_appendc(&var, '=');\n\t\tsmart_str_appends(&var, PS(id));\n\t\tsmart_str_0(&var);\n\t\tREGISTER_STRINGL_CONSTANT(\"SID\", var.c, var.len, 0);\n\t} else {\n\t\tREGISTER_STRINGL_CONSTANT(\"SID\", STR_EMPTY_ALLOC(), 0, 0);\n\t}\n\n\tif (PS(apply_trans_sid)) {\n\t\tphp_url_scanner_reset_vars(TSRMLS_C);\n\t\tphp_url_scanner_add_var(PS(session_name), strlen(PS(session_name)), PS(id), strlen(PS(id)), 1 TSRMLS_CC);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'Strict session'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: PHP_FUNCTION(openssl_x509_parse)\n{\n\tzval ** zcert;\n\tX509 * cert = NULL;\n\tlong certresource = -1;\n\tint i;\n\tzend_bool useshortnames = 1;\n\tchar * tmpstr;\n\tzval * subitem;\n\tX509_EXTENSION *extension;\n\tchar *extname;\n\tBIO *bio_out;\n\tBUF_MEM *bio_buf;\n\tchar buf[256];\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"Z|b\", &zcert, &useshortnames) == FAILURE) {\n\t\treturn;\n\t}\n\tcert = php_openssl_x509_from_zval(zcert, 0, &certresource TSRMLS_CC);\n\tif (cert == NULL) {\n\t\tRETURN_FALSE;\n\t}\n\tarray_init(return_value);\n\n\tif (cert->name) {\n\t\tadd_assoc_string(return_value, \"name\", cert->name, 1);\n\t}\n/*\tadd_assoc_bool(return_value, \"valid\", cert->valid); */\n\n\tadd_assoc_name_entry(return_value, \"subject\", \t\tX509_get_subject_name(cert), useshortnames TSRMLS_CC);\n\t/* hash as used in CA directories to lookup cert by subject name */\n\t{\n\t\tchar buf[32];\n\t\tsnprintf(buf, sizeof(buf), \"%08lx\", X509_subject_name_hash(cert));\n\t\tadd_assoc_string(return_value, \"hash\", buf, 1);\n\t}\n\n\tadd_assoc_name_entry(return_value, \"issuer\", \t\tX509_get_issuer_name(cert), useshortnames TSRMLS_CC);\n\tadd_assoc_long(return_value, \"version\", \t\t\tX509_get_version(cert));\n\n\tadd_assoc_string(return_value, \"serialNumber\", i2s_ASN1_INTEGER(NULL, X509_get_serialNumber(cert)), 1);\n\n\tadd_assoc_asn1_string(return_value, \"validFrom\", \tX509_get_notBefore(cert));\n\tadd_assoc_asn1_string(return_value, \"validTo\", \t\tX509_get_notAfter(cert));\n\n\tadd_assoc_long(return_value, \"validFrom_time_t\", \tasn1_time_to_time_t(X509_get_notBefore(cert) TSRMLS_CC));\n\tadd_assoc_long(return_value, \"validTo_time_t\", \t\tasn1_time_to_time_t(X509_get_notAfter(cert) TSRMLS_CC));\n\n\ttmpstr = (char *)X509_alias_get0(cert, NULL);\n\tif (tmpstr) {\n\t\tadd_assoc_string(return_value, \"alias\", tmpstr, 1);\n\t}\n/*\n\tadd_assoc_long(return_value, \"signaturetypeLONG\", X509_get_signature_type(cert));\n\tadd_assoc_string(return_value, \"signaturetype\", OBJ_nid2sn(X509_get_signature_type(cert)), 1);\n\tadd_assoc_string(return_value, \"signaturetypeLN\", OBJ_nid2ln(X509_get_signature_type(cert)), 1);\n*/\n\tMAKE_STD_ZVAL(subitem);\n\tarray_init(subitem);\n\n\t/* NOTE: the purposes are added as integer keys - the keys match up to the X509_PURPOSE_SSL_XXX defines\n\t in x509v3.h */\n\tfor (i = 0; i < X509_PURPOSE_get_count(); i++) {\n\t\tint id, purpset;\n\t\tchar * pname;\n\t\tX509_PURPOSE * purp;\n\t\tzval * subsub;\n\n\t\tMAKE_STD_ZVAL(subsub);\n\t\tarray_init(subsub);\n\n\t\tpurp = X509_PURPOSE_get0(i);\n\t\tid = X509_PURPOSE_get_id(purp);\n\n\t\tpurpset = X509_check_purpose(cert, id, 0);\n\t\tadd_index_bool(subsub, 0, purpset);\n\n\t\tpurpset = X509_check_purpose(cert, id, 1);\n\t\tadd_index_bool(subsub, 1, purpset);\n\n\t\tpname = useshortnames ? X509_PURPOSE_get0_sname(purp) : X509_PURPOSE_get0_name(purp);\n\t\tadd_index_string(subsub, 2, pname, 1);\n\n\t\t/* NOTE: if purpset > 1 then it's a warning - we should mention it ? */\n\n\t\tadd_index_zval(subitem, id, subsub);\n\t}\n\tadd_assoc_zval(return_value, \"purposes\", subitem);\n\n\tMAKE_STD_ZVAL(subitem);\n\tarray_init(subitem);\n\n\n\tfor (i = 0; i < X509_get_ext_count(cert); i++) {\n\t\textension = X509_get_ext(cert, i);\n\t\tif (OBJ_obj2nid(X509_EXTENSION_get_object(extension)) != NID_undef) {\n\t\t\textname = (char *)OBJ_nid2sn(OBJ_obj2nid(X509_EXTENSION_get_object(extension)));\n\t\t} else {\n\t\t\tOBJ_obj2txt(buf, sizeof(buf)-1, X509_EXTENSION_get_object(extension), 1);\n\t\t\textname = buf;\n\t\t}\n\t\tbio_out = BIO_new(BIO_s_mem());\n\t\tif (X509V3_EXT_print(bio_out, extension, 0, 0)) {\n\t\t\tBIO_get_mem_ptr(bio_out, &bio_buf);\n\t\t\tadd_assoc_stringl(subitem, extname, bio_buf->data, bio_buf->length, 1);\n\t\t} else {\n\t\t\tadd_assoc_asn1_string(subitem, extname, X509_EXTENSION_get_data(extension));\n\t\t}\n\t\tBIO_free(bio_out);\n\t}\n\tadd_assoc_zval(return_value, \"extensions\", subitem);\n\n\tif (certresource == -1 && cert) {\n\t\tX509_free(cert);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fix CVE-2013-4073 - handling of certs with null bytes'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int CLASS parse_tiff_ifd (int base)\n{\n unsigned entries, tag, type, len, plen=16, save;\n int ifd, use_cm=0, cfa, i, j, c, ima_len=0;\n int blrr=1, blrc=1, dblack[] = { 0,0,0,0 };\n char software[64], *cbuf, *cp;\n uchar cfa_pat[16], cfa_pc[] = { 0,1,2,3 }, tab[256];\n double cc[4][4], cm[4][3], cam_xyz[4][3], num;\n double ab[]={ 1,1,1,1 }, asn[] = { 0,0,0,0 }, xyz[] = { 1,1,1 };\n unsigned sony_curve[] = { 0,0,0,0,0,4095 };\n unsigned *buf, sony_offset=0, sony_length=0, sony_key=0;\n struct jhead jh;\n#ifndef LIBRAW_LIBRARY_BUILD\n FILE *sfp;\n#endif\n\n if (tiff_nifds >= sizeof tiff_ifd / sizeof tiff_ifd[0])\n return 1;\n ifd = tiff_nifds++;\n for (j=0; j < 4; j++)\n for (i=0; i < 4; i++)\n cc[j][i] = i == j;\n entries = get2();\n if (entries > 512) return 1;\n while (entries--) {\n tiff_get (base, &tag, &type, &len, &save);\n switch (tag) {\n case 5: width = get2(); break;\n case 6: height = get2(); break;\n case 7: width += get2(); break;\n case 9: filters = get2(); break;\n case 17: case 18:\n\tif (type == 3 && len == 1)\n\t cam_mul[(tag-17)*2] = get2() / 256.0;\n\tbreak;\n case 23:\n\tif (type == 3) iso_speed = get2();\n\tbreak;\n case 36: case 37: case 38:\n\tcam_mul[tag-0x24] = get2();\n\tbreak;\n case 39:\n\tif (len < 50 || cam_mul[0]) break;\n\tfseek (ifp, 12, SEEK_CUR);\n\tFORC3 cam_mul[c] = get2();\n\tbreak;\n case 46:\n\tif (type != 7 || fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) break;\n\tthumb_offset = ftell(ifp) - 2;\n\tthumb_length = len;\n\tbreak;\n case 61440:\t\t\t/* Fuji HS10 table */\n\tparse_tiff_ifd (base);\n\tbreak;\n case 2: case 256: case 61441:\t/* ImageWidth */\n\ttiff_ifd[ifd].t_width = getint(type);\n\tbreak;\n case 3: case 257: case 61442:\t/* ImageHeight */\n\ttiff_ifd[ifd].t_height = getint(type);\n\tbreak;\n case 258:\t\t\t\t/* BitsPerSample */\n case 61443:\n\ttiff_ifd[ifd].samples = len & 7;\n\ttiff_ifd[ifd].bps = getint(type);\n\tbreak;\n case 61446:\n\traw_height = 0;\n\tload_raw = &CLASS packed_load_raw;\n\tload_flags = get4() && (filters=0x16161616) ? 24:80;\n\tbreak;\n case 259:\t\t\t\t/* Compression */\n\ttiff_ifd[ifd].comp = getint(type);\n\tbreak;\n case 262:\t\t\t\t/* PhotometricInterpretation */\n\ttiff_ifd[ifd].phint = get2();\n\tbreak;\n case 270:\t\t\t\t/* ImageDescription */\n\tfread (desc, 512, 1, ifp);\n\tbreak;\n case 271:\t\t\t\t/* Make */\n\tfgets (make, 64, ifp);\n\tbreak;\n case 272:\t\t\t\t/* Model */\n\tfgets (model, 64, ifp);\n\tbreak;\n case 280:\t\t\t\t/* Panasonic RW2 offset */\n\tif (type != 4) break;\n\tload_raw = &CLASS panasonic_load_raw;\n\tload_flags = 0x2008;\n case 273:\t\t\t\t/* StripOffset */\n case 513:\t\t\t\t/* JpegIFOffset */\n case 61447:\n\ttiff_ifd[ifd].offset = get4()+base;\n\tif (!tiff_ifd[ifd].bps && tiff_ifd[ifd].offset > 0) {\n\t fseek (ifp, tiff_ifd[ifd].offset, SEEK_SET);\n\t if (ljpeg_start (&jh, 1)) {\n\t tiff_ifd[ifd].comp = 6;\n\t tiff_ifd[ifd].t_width = jh.wide;\n\t tiff_ifd[ifd].t_height = jh.high;\n\t tiff_ifd[ifd].bps = jh.bits;\n\t tiff_ifd[ifd].samples = jh.clrs;\n\t if (!(jh.sraw || (jh.clrs & 1)))\n\t tiff_ifd[ifd].t_width *= jh.clrs;\n\t i = order;\n\t parse_tiff (tiff_ifd[ifd].offset + 12);\n\t order = i;\n\t }\n\t}\n\tbreak;\n case 274:\t\t\t\t/* Orientation */\n\ttiff_ifd[ifd].t_flip = \"50132467\"[get2() & 7]-'0';\n\tbreak;\n case 277:\t\t\t\t/* SamplesPerPixel */\n\ttiff_ifd[ifd].samples = getint(type) & 7;\n\tbreak;\n case 279:\t\t\t\t/* StripByteCounts */\n case 514:\n case 61448:\n\ttiff_ifd[ifd].bytes = get4();\n\tbreak;\n case 61454:\n\tFORC3 cam_mul[(4-c) % 3] = getint(type);\n\tbreak;\n case 305: case 11:\t\t/* Software */\n\tfgets (software, 64, ifp);\n\tif (!strncmp(software,\"Adobe\",5) ||\n\t !strncmp(software,\"dcraw\",5) ||\n\t !strncmp(software,\"UFRaw\",5) ||\n\t !strncmp(software,\"Bibble\",6) ||\n\t !strncmp(software,\"Nikon Scan\",10) ||\n\t !strcmp (software,\"Digital Photo Professional\"))\n\t is_raw = 0;\n\tbreak;\n case 306:\t\t\t\t/* DateTime */\n\tget_timestamp(0);\n\tbreak;\n case 315:\t\t\t\t/* Artist */\n\tfread (artist, 64, 1, ifp);\n\tbreak;\n case 322:\t\t\t\t/* TileWidth */\n\ttiff_ifd[ifd].t_tile_width = getint(type);\n\tbreak;\n case 323:\t\t\t\t/* TileLength */\n\ttiff_ifd[ifd].t_tile_length = getint(type);\n\tbreak;\n case 324:\t\t\t\t/* TileOffsets */\n\ttiff_ifd[ifd].offset = len > 1 ? ftell(ifp) : get4();\n\tif (len == 4) {\n\t load_raw = &CLASS sinar_4shot_load_raw;\n\t is_raw = 5;\n\t}\n\tbreak;\n#ifdef LIBRAW_LIBRARY_BUILD\n case 325:\t\t\t\t/* TileByteCount */\n tiff_ifd[ifd].tile_maxbytes = 0;\n for(int jj=0;jj tiff_ifd[ifd].tile_maxbytes) tiff_ifd[ifd].tile_maxbytes=s;\n }\n\tbreak;\n#endif\n case 330:\t\t\t\t/* SubIFDs */\n\tif (!strcmp(model,\"DSLR-A100\") && tiff_ifd[ifd].t_width == 3872) {\n\t load_raw = &CLASS sony_arw_load_raw;\n\t data_offset = get4()+base;\n\t ifd++; break;\n\t}\n\twhile (len--) {\n\t i = ftell(ifp);\n\t fseek (ifp, get4()+base, SEEK_SET);\n\t if (parse_tiff_ifd (base)) break;\n\t fseek (ifp, i+4, SEEK_SET);\n\t}\n\tbreak;\n case 400:\n\tstrcpy (make, \"Sarnoff\");\n\tmaximum = 0xfff;\n\tbreak;\n case 28688:\n\tFORC4 sony_curve[c+1] = get2() >> 2 & 0xfff;\n\tfor (i=0; i < 5; i++)\n\t for (j = sony_curve[i]+1; j <= sony_curve[i+1]; j++)\n\t curve[j] = curve[j-1] + (1 << i);\n\tbreak;\n case 29184: sony_offset = get4(); break;\n case 29185: sony_length = get4(); break;\n case 29217: sony_key = get4(); break;\n case 29264:\n\tparse_minolta (ftell(ifp));\n\traw_width = 0;\n\tbreak;\n case 29443:\n\tFORC4 cam_mul[c ^ (c < 2)] = get2();\n\tbreak;\n case 29459:\n\tFORC4 cam_mul[c] = get2();\n\ti = (cam_mul[1] == 1024 && cam_mul[2] == 1024) << 1;\n\tSWAP (cam_mul[i],cam_mul[i+1])\n\tbreak;\n case 33405:\t\t\t/* Model2 */\n\tfgets (model2, 64, ifp);\n\tbreak;\n case 33422:\t\t\t/* CFAPattern */\n case 64777:\t\t\t/* Kodak P-series */\n\tif ((plen=len) > 16) plen = 16;\n\tfread (cfa_pat, 1, plen, ifp);\n\tfor (colors=cfa=i=0; i < plen; i++) {\n\t colors += !(cfa & (1 << cfa_pat[i]));\n\t cfa |= 1 << cfa_pat[i];\n\t}\n\tif (cfa == 070) memcpy (cfa_pc,\"\\003\\004\\005\",3);\t/* CMY */\n\tif (cfa == 072) memcpy (cfa_pc,\"\\005\\003\\004\\001\",4);\t/* GMCY */\n\tgoto guess_cfa_pc;\n case 33424:\n case 65024:\n\tfseek (ifp, get4()+base, SEEK_SET);\n\tparse_kodak_ifd (base);\n\tbreak;\n case 33434:\t\t\t/* ExposureTime */\n\tshutter = getreal(type);\n\tbreak;\n case 33437:\t\t\t/* FNumber */\n\taperture = getreal(type);\n\tbreak;\n case 34306:\t\t\t/* Leaf white balance */\n\tFORC4 cam_mul[c ^ 1] = 4096.0 / get2();\n\tbreak;\n case 34307:\t\t\t/* Leaf CatchLight color matrix */\n\tfread (software, 1, 7, ifp);\n\tif (strncmp(software,\"MATRIX\",6)) break;\n\tcolors = 4;\n\tfor (raw_color = i=0; i < 3; i++) {\n\t FORC4 fscanf (ifp, \"%f\", &rgb_cam[i][c^1]);\n\t if (!use_camera_wb) continue;\n\t num = 0;\n\t FORC4 num += rgb_cam[i][c];\n\t FORC4 rgb_cam[i][c] /= num;\n\t}\n\tbreak;\n case 34310:\t\t\t/* Leaf metadata */\n\tparse_mos (ftell(ifp));\n case 34303:\n\tstrcpy (make, \"Leaf\");\n\tbreak;\n case 34665:\t\t\t/* EXIF tag */\n\tfseek (ifp, get4()+base, SEEK_SET);\n\tparse_exif (base);\n\tbreak;\n case 34853:\t\t\t/* GPSInfo tag */\n\tfseek (ifp, get4()+base, SEEK_SET);\n\tparse_gps (base);\n\tbreak;\n case 34675:\t\t\t/* InterColorProfile */\n case 50831:\t\t\t/* AsShotICCProfile */\n\tprofile_offset = ftell(ifp);\n\tprofile_length = len;\n\tbreak;\n case 37122:\t\t\t/* CompressedBitsPerPixel */\n\tkodak_cbpp = get4();\n\tbreak;\n case 37386:\t\t\t/* FocalLength */\n\tfocal_len = getreal(type);\n\tbreak;\n case 37393:\t\t\t/* ImageNumber */\n\tshot_order = getint(type);\n\tbreak;\n case 37400:\t\t\t/* old Kodak KDC tag */\n\tfor (raw_color = i=0; i < 3; i++) {\n\t getreal(type);\n\t FORC3 rgb_cam[i][c] = getreal(type);\n\t}\n\tbreak;\n case 46275:\t\t\t/* Imacon tags */\n\tstrcpy (make, \"Imacon\");\n\tdata_offset = ftell(ifp);\n\tima_len = len;\n\tbreak;\n case 46279:\n\tif (!ima_len) break;\n\tfseek (ifp, 38, SEEK_CUR);\n case 46274:\n\tfseek (ifp, 40, SEEK_CUR);\n\traw_width = get4();\n\traw_height = get4();\n\tleft_margin = get4() & 7;\n\twidth = raw_width - left_margin - (get4() & 7);\n\ttop_margin = get4() & 7;\n\theight = raw_height - top_margin - (get4() & 7);\n\tif (raw_width == 7262 && ima_len == 234317952 ) {\n\t height = 5412;\n\t width = 7216;\n\t left_margin = 7;\n filters=0;\n\t} else \tif (raw_width == 7262) {\n\t height = 5444;\n\t width = 7244;\n\t left_margin = 7;\n\t}\n\tfseek (ifp, 52, SEEK_CUR);\n\tFORC3 cam_mul[c] = getreal(11);\n\tfseek (ifp, 114, SEEK_CUR);\n\tflip = (get2() >> 7) * 90;\n\tif (width * height * 6 == ima_len) {\n\t if (flip % 180 == 90) SWAP(width,height);\n\t raw_width = width;\n\t raw_height = height;\n\t left_margin = top_margin = filters = flip = 0;\n\t}\n\tsprintf (model, \"Ixpress %d-Mp\", height*width/1000000);\n\tload_raw = &CLASS imacon_full_load_raw;\n\tif (filters) {\n\t if (left_margin & 1) filters = 0x61616161;\n\t load_raw = &CLASS unpacked_load_raw;\n\t}\n\tmaximum = 0xffff;\n\tbreak;\n case 50454:\t\t\t/* Sinar tag */\n case 50455:\n\tif (!(cbuf = (char *) malloc(len))) break;\n\tfread (cbuf, 1, len, ifp);\n\tfor (cp = cbuf-1; cp && cp < cbuf+len; cp = strchr(cp,'\\n'))\n\t if (!strncmp (++cp,\"Neutral \",8))\n\t sscanf (cp+8, \"%f %f %f\", cam_mul, cam_mul+1, cam_mul+2);\n\tfree (cbuf);\n\tbreak;\n case 50458:\n\tif (!make[0]) strcpy (make, \"Hasselblad\");\n\tbreak;\n case 50459:\t\t\t/* Hasselblad tag */\n\ti = order;\n\tj = ftell(ifp);\n\tc = tiff_nifds;\n\torder = get2();\n\tfseek (ifp, j+(get2(),get4()), SEEK_SET);\n\tparse_tiff_ifd (j);\n\tmaximum = 0xffff;\n\ttiff_nifds = c;\n\torder = i;\n\tbreak;\n case 50706:\t\t\t/* DNGVersion */\n\tFORC4 dng_version = (dng_version << 8) + fgetc(ifp);\n\tif (!make[0]) strcpy (make, \"DNG\");\n\tis_raw = 1;\n\tbreak;\n case 50710:\t\t\t/* CFAPlaneColor */\n\tif (len > 4) len = 4;\n\tcolors = len;\n\tfread (cfa_pc, 1, colors, ifp);\nguess_cfa_pc:\n\tFORCC tab[cfa_pc[c]] = c;\n\tcdesc[c] = 0;\n\tfor (i=16; i--; )\n\t filters = filters << 2 | tab[cfa_pat[i % plen]];\n\tbreak;\n case 50711:\t\t\t/* CFALayout */\n\tif (get2() == 2) {\n\t fuji_width = 1;\n\t filters = 0x49494949;\n\t}\n\tbreak;\n case 291:\n case 50712:\t\t\t/* LinearizationTable */\n\tlinear_table (len);\n\tbreak;\n case 50713:\t\t\t/* BlackLevelRepeatDim */\n\tblrr = get2();\n\tblrc = get2();\n\tbreak;\n case 61450:\n\tblrr = blrc = 2;\n case 50714:\t\t\t/* BlackLevel */\n\tblack = getreal(type);\n\tif (!filters || !~filters) break;\n\tdblack[0] = black;\n\tdblack[1] = (blrc == 2) ? getreal(type):dblack[0];\n\tdblack[2] = (blrr == 2) ? getreal(type):dblack[0];\n\tdblack[3] = (blrc == 2 && blrr == 2) ? getreal(type):dblack[1];\n\tif (colors == 3)\n\t filters |= ((filters >> 2 & 0x22222222) |\n\t\t (filters << 2 & 0x88888888)) & filters << 1;\n\tFORC4 cblack[filters >> (c << 1) & 3] = dblack[c];\n\tblack = 0;\n\tbreak;\n case 50715:\t\t\t/* BlackLevelDeltaH */\n case 50716:\t\t\t/* BlackLevelDeltaV */\n\tfor (num=i=0; i < len; i++)\n\t num += getreal(type);\n\tblack += num/len + 0.5;\n\tbreak;\n case 50717:\t\t\t/* WhiteLevel */\n\tmaximum = getint(type);\n\tbreak;\n case 50718:\t\t\t/* DefaultScale */\n\tpixel_aspect = getreal(type);\n\tpixel_aspect /= getreal(type);\n\tbreak;\n case 50721:\t\t\t/* ColorMatrix1 */\n case 50722:\t\t\t/* ColorMatrix2 */\n\tFORCC for (j=0; j < 3; j++)\n\t cm[c][j] = getreal(type);\n\tuse_cm = 1;\n\tbreak;\n case 50723:\t\t\t/* CameraCalibration1 */\n case 50724:\t\t\t/* CameraCalibration2 */\n\tfor (i=0; i < colors; i++)\n\t FORCC cc[i][c] = getreal(type);\n\tbreak;\n case 50727:\t\t\t/* AnalogBalance */\n\tFORCC ab[c] = getreal(type);\n\tbreak;\n case 50728:\t\t\t/* AsShotNeutral */\n\tFORCC asn[c] = getreal(type);\n\tbreak;\n case 50729:\t\t\t/* AsShotWhiteXY */\n\txyz[0] = getreal(type);\n\txyz[1] = getreal(type);\n\txyz[2] = 1 - xyz[0] - xyz[1];\n\tFORC3 xyz[c] /= d65_white[c];\n\tbreak;\n case 50740:\t\t\t/* DNGPrivateData */\n\tif (dng_version) break;\n\tparse_minolta (j = get4()+base);\n\tfseek (ifp, j, SEEK_SET);\n\tparse_tiff_ifd (base);\n\tbreak;\n case 50752:\n\tread_shorts (cr2_slice, 3);\n\tbreak;\n case 50829:\t\t\t/* ActiveArea */\n\ttop_margin = getint(type);\n\tleft_margin = getint(type);\n\theight = getint(type) - top_margin;\n\twidth = getint(type) - left_margin;\n\tbreak;\n case 50830:\t\t\t/* MaskedAreas */\n for (i=0; i < len && i < 32; i++)\n\t mask[0][i] = getint(type);\n\tblack = 0;\n\tbreak;\n case 51009:\t\t\t/* OpcodeList2 */\n\tmeta_offset = ftell(ifp);\n\tbreak;\n case 64772:\t\t\t/* Kodak P-series */\n\tif (len < 13) break;\n\tfseek (ifp, 16, SEEK_CUR);\n\tdata_offset = get4();\n\tfseek (ifp, 28, SEEK_CUR);\n\tdata_offset += get4();\n\tload_raw = &CLASS packed_load_raw;\n\tbreak;\n case 65026:\n\tif (type == 2) fgets (model2, 64, ifp);\n }\n fseek (ifp, save, SEEK_SET);\n }\n if (sony_length && (buf = (unsigned *) malloc(sony_length))) {\n fseek (ifp, sony_offset, SEEK_SET);\n fread (buf, sony_length, 1, ifp);\n sony_decrypt (buf, sony_length/4, 1, sony_key);\n#ifndef LIBRAW_LIBRARY_BUILD\n sfp = ifp;\n if ((ifp = tmpfile())) {\n fwrite (buf, sony_length, 1, ifp);\n fseek (ifp, 0, SEEK_SET);\n parse_tiff_ifd (-sony_offset);\n fclose (ifp);\n }\n ifp = sfp;\n#else\n if( !ifp->tempbuffer_open(buf,sony_length))\n {\n parse_tiff_ifd(-sony_offset);\n ifp->tempbuffer_close();\n }\n#endif\n free (buf);\n }\n for (i=0; i < colors; i++)\n FORCC cc[i][c] *= ab[i];\n if (use_cm) {\n FORCC for (i=0; i < 3; i++)\n for (cam_xyz[c][i]=j=0; j < colors; j++)\n\tcam_xyz[c][i] += cc[c][j] * cm[j][i] * xyz[i];\n cam_xyz_coeff (cam_xyz);\n }\n if (asn[0]) {\n cam_mul[3] = 0;\n FORCC cam_mul[c] = 1 / asn[c];\n }\n if (!use_cm)\n FORCC pre_mul[c] /= cc[c][c];\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'cumulated data checks patch'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int read_exceptions(struct pstore *ps,\n\t\t\t int (*callback)(void *callback_context, chunk_t old,\n\t\t\t\t\t chunk_t new),\n\t\t\t void *callback_context)\n{\n\tint r, full = 1;\n\n\t/*\n\t * Keeping reading chunks and inserting exceptions until\n\t * we find a partially full area.\n\t */\n\tfor (ps->current_area = 0; full; ps->current_area++) {\n\t\tr = area_io(ps, READ);\n\t\tif (r)\n\t\t\treturn r;\n\n\t\tr = insert_exceptions(ps, callback, callback_context, &full);\n\t\tif (r)\n\t\t\treturn r;\n\t}\n\n\tps->current_area--;\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-264'], 'message': 'dm snapshot: fix data corruption\n\nThis patch fixes a particular type of data corruption that has been\nencountered when loading a snapshot's metadata from disk.\n\nWhen we allocate a new chunk in persistent_prepare, we increment\nps->next_free and we make sure that it doesn't point to a metadata area\nby further incrementing it if necessary.\n\nWhen we load metadata from disk on device activation, ps->next_free is\npositioned after the last used data chunk. However, if this last used\ndata chunk is followed by a metadata area, ps->next_free is positioned\nerroneously to the metadata area. A newly-allocated chunk is placed at\nthe same location as the metadata area, resulting in data or metadata\ncorruption.\n\nThis patch changes the code so that ps->next_free skips the metadata\narea when metadata are loaded in function read_exceptions.\n\nThe patch also moves a piece of code from persistent_prepare_exception\nto a separate function skip_metadata to avoid code duplication.\n\nCVE-2013-4299\n\nSigned-off-by: Mikulas Patocka \nCc: stable@vger.kernel.org\nCc: Mike Snitzer \nSigned-off-by: Alasdair G Kergon '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int main( int argc, char *argv[] )\n{\n int keysize;\n unsigned long i, j, tsc;\n unsigned char tmp[64];\n#if defined(POLARSSL_ARC4_C)\n arc4_context arc4;\n#endif\n#if defined(POLARSSL_DES_C)\n des3_context des3;\n des_context des;\n#endif\n#if defined(POLARSSL_AES_C)\n aes_context aes;\n#if defined(POLARSSL_GCM_C)\n gcm_context gcm;\n#endif\n#endif\n#if defined(POLARSSL_BLOWFISH_C)\n blowfish_context blowfish;\n#endif\n#if defined(POLARSSL_CAMELLIA_C)\n camellia_context camellia;\n#endif\n#if defined(POLARSSL_RSA_C) && defined(POLARSSL_BIGNUM_C) && \\\n defined(POLARSSL_GENPRIME)\n rsa_context rsa;\n#endif\n#if defined(POLARSSL_HAVEGE_C)\n havege_state hs;\n#endif\n#if defined(POLARSSL_CTR_DRBG_C)\n ctr_drbg_context ctr_drbg;\n#endif\n ((void) argc);\n ((void) argv);\n\n memset( buf, 0xAA, sizeof( buf ) );\n\n printf( \"\\n\" );\n\n#if defined(POLARSSL_MD4_C)\n printf( HEADER_FORMAT, \"MD4\" );\n fflush( stdout );\n\n set_alarm( 1 );\n for( i = 1; ! alarmed; i++ )\n md4( buf, BUFSIZE, tmp );\n\n tsc = hardclock();\n for( j = 0; j < 1024; j++ )\n md4( buf, BUFSIZE, tmp );\n\n printf( \"%9lu Kb/s, %9lu cycles/byte\\n\", i * BUFSIZE / 1024,\n ( hardclock() - tsc ) / ( j * BUFSIZE ) );\n#endif\n\n#if defined(POLARSSL_MD5_C)\n printf( HEADER_FORMAT, \"MD5\" );\n fflush( stdout );\n\n set_alarm( 1 );\n for( i = 1; ! alarmed; i++ )\n md5( buf, BUFSIZE, tmp );\n\n tsc = hardclock();\n for( j = 0; j < 1024; j++ )\n md5( buf, BUFSIZE, tmp );\n\n printf( \"%9lu Kb/s, %9lu cycles/byte\\n\", i * BUFSIZE / 1024,\n ( hardclock() - tsc ) / ( j * BUFSIZE ) );\n#endif\n\n#if defined(POLARSSL_SHA1_C)\n printf( HEADER_FORMAT, \"SHA-1\" );\n fflush( stdout );\n\n set_alarm( 1 );\n for( i = 1; ! alarmed; i++ )\n sha1( buf, BUFSIZE, tmp );\n\n tsc = hardclock();\n for( j = 0; j < 1024; j++ )\n sha1( buf, BUFSIZE, tmp );\n\n printf( \"%9lu Kb/s, %9lu cycles/byte\\n\", i * BUFSIZE / 1024,\n ( hardclock() - tsc ) / ( j * BUFSIZE ) );\n#endif\n\n#if defined(POLARSSL_SHA2_C)\n printf( HEADER_FORMAT, \"SHA-256\" );\n fflush( stdout );\n\n set_alarm( 1 );\n for( i = 1; ! alarmed; i++ )\n sha2( buf, BUFSIZE, tmp, 0 );\n\n tsc = hardclock();\n for( j = 0; j < 1024; j++ )\n sha2( buf, BUFSIZE, tmp, 0 );\n\n printf( \"%9lu Kb/s, %9lu cycles/byte\\n\", i * BUFSIZE / 1024,\n ( hardclock() - tsc ) / ( j * BUFSIZE ) );\n#endif\n\n#if defined(POLARSSL_SHA4_C)\n printf( HEADER_FORMAT, \"SHA-512\" );\n fflush( stdout );\n\n set_alarm( 1 );\n for( i = 1; ! alarmed; i++ )\n sha4( buf, BUFSIZE, tmp, 0 );\n\n tsc = hardclock();\n for( j = 0; j < 1024; j++ )\n sha4( buf, BUFSIZE, tmp, 0 );\n\n printf( \"%9lu Kb/s, %9lu cycles/byte\\n\", i * BUFSIZE / 1024,\n ( hardclock() - tsc ) / ( j * BUFSIZE ) );\n#endif\n\n#if defined(POLARSSL_ARC4_C)\n printf( HEADER_FORMAT, \"ARC4\" );\n fflush( stdout );\n\n arc4_setup( &arc4, tmp, 32 );\n\n set_alarm( 1 );\n for( i = 1; ! alarmed; i++ )\n arc4_crypt( &arc4, BUFSIZE, buf, buf );\n\n tsc = hardclock();\n for( j = 0; j < 1024; j++ )\n arc4_crypt( &arc4, BUFSIZE, buf, buf );\n\n printf( \"%9lu Kb/s, %9lu cycles/byte\\n\", i * BUFSIZE / 1024,\n ( hardclock() - tsc ) / ( j * BUFSIZE ) );\n#endif\n\n#if defined(POLARSSL_DES_C)\n printf( HEADER_FORMAT, \"3DES\" );\n fflush( stdout );\n\n des3_set3key_enc( &des3, tmp );\n\n set_alarm( 1 );\n for( i = 1; ! alarmed; i++ )\n des3_crypt_cbc( &des3, DES_ENCRYPT, BUFSIZE, tmp, buf, buf );\n\n tsc = hardclock();\n for( j = 0; j < 1024; j++ )\n des3_crypt_cbc( &des3, DES_ENCRYPT, BUFSIZE, tmp, buf, buf );\n\n printf( \"%9lu Kb/s, %9lu cycles/byte\\n\", i * BUFSIZE / 1024,\n ( hardclock() - tsc ) / ( j * BUFSIZE ) );\n\n printf( HEADER_FORMAT, \"DES\" );\n fflush( stdout );\n\n des_setkey_enc( &des, tmp );\n\n set_alarm( 1 );\n for( i = 1; ! alarmed; i++ )\n des_crypt_cbc( &des, DES_ENCRYPT, BUFSIZE, tmp, buf, buf );\n\n tsc = hardclock();\n for( j = 0; j < 1024; j++ )\n des_crypt_cbc( &des, DES_ENCRYPT, BUFSIZE, tmp, buf, buf );\n\n printf( \"%9lu Kb/s, %9lu cycles/byte\\n\", i * BUFSIZE / 1024,\n ( hardclock() - tsc ) / ( j * BUFSIZE ) );\n#endif\n\n#if defined(POLARSSL_AES_C)\n for( keysize = 128; keysize <= 256; keysize += 64 )\n {\n printf( \" AES-CBC-%d : \", keysize );\n fflush( stdout );\n\n memset( buf, 0, sizeof( buf ) );\n memset( tmp, 0, sizeof( tmp ) );\n aes_setkey_enc( &aes, tmp, keysize );\n\n set_alarm( 1 );\n\n for( i = 1; ! alarmed; i++ )\n aes_crypt_cbc( &aes, AES_ENCRYPT, BUFSIZE, tmp, buf, buf );\n\n tsc = hardclock();\n for( j = 0; j < 4096; j++ )\n aes_crypt_cbc( &aes, AES_ENCRYPT, BUFSIZE, tmp, buf, buf );\n\n printf( \"%9lu Kb/s, %9lu cycles/byte\\n\", i * BUFSIZE / 1024,\n ( hardclock() - tsc ) / ( j * BUFSIZE ) );\n }\n#if defined(POLARSSL_GCM_C)\n for( keysize = 128; keysize <= 256; keysize += 64 )\n {\n printf( \" AES-GCM-%d : \", keysize );\n fflush( stdout );\n\n memset( buf, 0, sizeof( buf ) );\n memset( tmp, 0, sizeof( tmp ) );\n gcm_init( &gcm, tmp, keysize );\n\n set_alarm( 1 );\n\n for( i = 1; ! alarmed; i++ )\n gcm_crypt_and_tag( &gcm, GCM_ENCRYPT, BUFSIZE, tmp, 12, NULL, 0, buf, buf, 16, tmp );\n\n tsc = hardclock();\n for( j = 0; j < 4096; j++ )\n gcm_crypt_and_tag( &gcm, GCM_ENCRYPT, BUFSIZE, tmp, 12, NULL, 0, buf, buf, 16, tmp );\n\n printf( \"%9lu Kb/s, %9lu cycles/byte\\n\", i * BUFSIZE / 1024,\n ( hardclock() - tsc ) / ( j * BUFSIZE ) );\n }\n#endif\n#endif\n\n#if defined(POLARSSL_CAMELLIA_C)\n for( keysize = 128; keysize <= 256; keysize += 64 )\n {\n printf( \" CAMELLIA-CBC-%d: \", keysize );\n fflush( stdout );\n\n memset( buf, 0, sizeof( buf ) );\n memset( tmp, 0, sizeof( tmp ) );\n camellia_setkey_enc( &camellia, tmp, keysize );\n\n set_alarm( 1 );\n\n for( i = 1; ! alarmed; i++ )\n camellia_crypt_cbc( &camellia, CAMELLIA_ENCRYPT, BUFSIZE, tmp, buf, buf );\n\n tsc = hardclock();\n for( j = 0; j < 4096; j++ )\n camellia_crypt_cbc( &camellia, CAMELLIA_ENCRYPT, BUFSIZE, tmp, buf, buf );\n\n printf( \"%9lu Kb/s, %9lu cycles/byte\\n\", i * BUFSIZE / 1024,\n ( hardclock() - tsc ) / ( j * BUFSIZE ) );\n }\n#endif\n\n#if defined(POLARSSL_BLOWFISH_C)\n for( keysize = 128; keysize <= 256; keysize += 64 )\n {\n printf( \" BLOWFISH-CBC-%d: \", keysize );\n fflush( stdout );\n\n memset( buf, 0, sizeof( buf ) );\n memset( tmp, 0, sizeof( tmp ) );\n blowfish_setkey( &blowfish, tmp, keysize );\n\n set_alarm( 1 );\n\n for( i = 1; ! alarmed; i++ )\n blowfish_crypt_cbc( &blowfish, BLOWFISH_ENCRYPT, BUFSIZE, tmp, buf, buf );\n\n tsc = hardclock();\n for( j = 0; j < 4096; j++ )\n blowfish_crypt_cbc( &blowfish, BLOWFISH_ENCRYPT, BUFSIZE, tmp, buf, buf );\n\n printf( \"%9lu Kb/s, %9lu cycles/byte\\n\", i * BUFSIZE / 1024,\n ( hardclock() - tsc ) / ( j * BUFSIZE ) );\n }\n#endif\n\n#if defined(POLARSSL_HAVEGE_C)\n printf( HEADER_FORMAT, \"HAVEGE\" );\n fflush( stdout );\n\n havege_init( &hs );\n\n set_alarm( 1 );\n for( i = 1; ! alarmed; i++ )\n havege_random( &hs, buf, BUFSIZE );\n\n tsc = hardclock();\n for( j = 1; j < 1024; j++ )\n havege_random( &hs, buf, BUFSIZE );\n\n printf( \"%9lu Kb/s, %9lu cycles/byte\\n\", i * BUFSIZE / 1024,\n ( hardclock() - tsc ) / ( j * BUFSIZE ) );\n#endif\n\n#if defined(POLARSSL_CTR_DRBG_C)\n printf( HEADER_FORMAT, \"CTR_DRBG (NOPR)\" );\n fflush( stdout );\n\n if( ctr_drbg_init( &ctr_drbg, myrand, NULL, NULL, 0 ) != 0 )\n exit(1);\n\n set_alarm( 1 );\n for( i = 1; ! alarmed; i++ )\n if( ctr_drbg_random( &ctr_drbg, buf, BUFSIZE ) != 0 )\n exit(1);\n\n tsc = hardclock();\n for( j = 1; j < 1024; j++ )\n if( ctr_drbg_random( &ctr_drbg, buf, BUFSIZE ) != 0 )\n exit(1);\n\n printf( \"%9lu Kb/s, %9lu cycles/byte\\n\", i * BUFSIZE / 1024,\n ( hardclock() - tsc ) / ( j * BUFSIZE ) );\n\n printf( HEADER_FORMAT, \"CTR_DRBG (PR)\" );\n fflush( stdout );\n\n if( ctr_drbg_init( &ctr_drbg, myrand, NULL, NULL, 0 ) != 0 )\n exit(1);\n\n ctr_drbg_set_prediction_resistance( &ctr_drbg, CTR_DRBG_PR_ON );\n\n set_alarm( 1 );\n for( i = 1; ! alarmed; i++ )\n if( ctr_drbg_random( &ctr_drbg, buf, BUFSIZE ) != 0 )\n exit(1);\n\n tsc = hardclock();\n for( j = 1; j < 1024; j++ )\n if( ctr_drbg_random( &ctr_drbg, buf, BUFSIZE ) != 0 )\n exit(1);\n\n printf( \"%9lu Kb/s, %9lu cycles/byte\\n\", i * BUFSIZE / 1024,\n ( hardclock() - tsc ) / ( j * BUFSIZE ) );\n#endif\n\n#if defined(POLARSSL_RSA_C) && defined(POLARSSL_BIGNUM_C) && \\\n defined(POLARSSL_GENPRIME)\n rsa_init( &rsa, RSA_PKCS_V15, 0 );\n rsa_gen_key( &rsa, myrand, NULL, 1024, 65537 );\n\n printf( HEADER_FORMAT, \"RSA-1024\" );\n fflush( stdout );\n set_alarm( 3 );\n\n for( i = 1; ! alarmed; i++ )\n {\n buf[0] = 0;\n rsa_public( &rsa, buf, buf );\n }\n\n printf( \"%9lu public/s\\n\", i / 3 );\n\n printf( HEADER_FORMAT, \"RSA-1024\" );\n fflush( stdout );\n set_alarm( 3 );\n\n for( i = 1; ! alarmed; i++ )\n {\n buf[0] = 0;\n rsa_private( &rsa, buf, buf );\n }\n\n printf( \"%9lu private/s\\n\", i / 3 );\n\n rsa_free( &rsa );\n\n rsa_init( &rsa, RSA_PKCS_V15, 0 );\n rsa_gen_key( &rsa, myrand, NULL, 2048, 65537 );\n\n printf( HEADER_FORMAT, \"RSA-2048\" );\n fflush( stdout );\n set_alarm( 3 );\n\n for( i = 1; ! alarmed; i++ )\n {\n buf[0] = 0;\n rsa_public( &rsa, buf, buf );\n }\n\n printf( \"%9lu public/s\\n\", i / 3 );\n\n printf( HEADER_FORMAT, \"RSA-2048\" );\n fflush( stdout );\n set_alarm( 3 );\n\n for( i = 1; ! alarmed; i++ )\n {\n buf[0] = 0;\n rsa_private( &rsa, buf, buf );\n }\n\n printf( \"%9lu private/s\\n\", i / 3 );\n\n rsa_free( &rsa );\n\n rsa_init( &rsa, RSA_PKCS_V15, 0 );\n rsa_gen_key( &rsa, myrand, NULL, 4096, 65537 );\n\n printf( HEADER_FORMAT, \"RSA-4096\" );\n fflush( stdout );\n set_alarm( 3 );\n\n for( i = 1; ! alarmed; i++ )\n {\n buf[0] = 0;\n rsa_public( &rsa, buf, buf );\n }\n\n printf( \"%9lu public/s\\n\", i / 3 );\n\n printf( HEADER_FORMAT, \"RSA-4096\" );\n fflush( stdout );\n set_alarm( 3 );\n\n for( i = 1; ! alarmed; i++ )\n {\n buf[0] = 0;\n rsa_private( &rsa, buf, buf );\n }\n\n printf( \"%9lu private/s\\n\", i / 3 );\n\n rsa_free( &rsa );\n#endif\n\n printf( \"\\n\" );\n\n#if defined(_WIN32)\n printf( \" Press Enter to exit this program.\\n\" );\n fflush( stdout ); getchar();\n#endif\n\n return( 0 );\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int rsa_rsassa_pkcs1_v15_sign( rsa_context *ctx,\n int mode,\n int hash_id,\n unsigned int hashlen,\n const unsigned char *hash,\n unsigned char *sig )\n{\n size_t nb_pad, olen;\n unsigned char *p = sig;\n\n if( ctx->padding != RSA_PKCS_V15 )\n return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );\n\n olen = ctx->len;\n\n switch( hash_id )\n {\n case SIG_RSA_RAW:\n nb_pad = olen - 3 - hashlen;\n break;\n\n case SIG_RSA_MD2:\n case SIG_RSA_MD4:\n case SIG_RSA_MD5:\n nb_pad = olen - 3 - 34;\n break;\n\n case SIG_RSA_SHA1:\n nb_pad = olen - 3 - 35;\n break;\n\n case SIG_RSA_SHA224:\n nb_pad = olen - 3 - 47;\n break;\n\n case SIG_RSA_SHA256:\n nb_pad = olen - 3 - 51;\n break;\n\n case SIG_RSA_SHA384:\n nb_pad = olen - 3 - 67;\n break;\n\n case SIG_RSA_SHA512:\n nb_pad = olen - 3 - 83;\n break;\n\n\n default:\n return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );\n }\n\n if( ( nb_pad < 8 ) || ( nb_pad > olen ) )\n return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );\n\n *p++ = 0;\n *p++ = RSA_SIGN;\n memset( p, 0xFF, nb_pad );\n p += nb_pad;\n *p++ = 0;\n\n switch( hash_id )\n {\n case SIG_RSA_RAW:\n memcpy( p, hash, hashlen );\n break;\n\n case SIG_RSA_MD2:\n memcpy( p, ASN1_HASH_MDX, 18 );\n memcpy( p + 18, hash, 16 );\n p[13] = 2; break;\n\n case SIG_RSA_MD4:\n memcpy( p, ASN1_HASH_MDX, 18 );\n memcpy( p + 18, hash, 16 );\n p[13] = 4; break;\n\n case SIG_RSA_MD5:\n memcpy( p, ASN1_HASH_MDX, 18 );\n memcpy( p + 18, hash, 16 );\n p[13] = 5; break;\n\n case SIG_RSA_SHA1:\n memcpy( p, ASN1_HASH_SHA1, 15 );\n memcpy( p + 15, hash, 20 );\n break;\n\n case SIG_RSA_SHA224:\n memcpy( p, ASN1_HASH_SHA2X, 19 );\n memcpy( p + 19, hash, 28 );\n p[1] += 28; p[14] = 4; p[18] += 28; break;\n\n case SIG_RSA_SHA256:\n memcpy( p, ASN1_HASH_SHA2X, 19 );\n memcpy( p + 19, hash, 32 );\n p[1] += 32; p[14] = 1; p[18] += 32; break;\n\n case SIG_RSA_SHA384:\n memcpy( p, ASN1_HASH_SHA2X, 19 );\n memcpy( p + 19, hash, 48 );\n p[1] += 48; p[14] = 2; p[18] += 48; break;\n\n case SIG_RSA_SHA512:\n memcpy( p, ASN1_HASH_SHA2X, 19 );\n memcpy( p + 19, hash, 64 );\n p[1] += 64; p[14] = 3; p[18] += 64; break;\n\n default:\n return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );\n }\n\n return( ( mode == RSA_PUBLIC )\n ? rsa_public( ctx, sig, sig )\n : rsa_private( ctx, sig, sig ) );\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int rsa_self_test( int verbose )\n{\n size_t len;\n rsa_context rsa;\n unsigned char rsa_plaintext[PT_LEN];\n unsigned char rsa_decrypted[PT_LEN];\n unsigned char rsa_ciphertext[KEY_LEN];\n#if defined(POLARSSL_SHA1_C)\n unsigned char sha1sum[20];\n#endif\n\n rsa_init( &rsa, RSA_PKCS_V15, 0 );\n\n rsa.len = KEY_LEN;\n mpi_read_string( &rsa.N , 16, RSA_N );\n mpi_read_string( &rsa.E , 16, RSA_E );\n mpi_read_string( &rsa.D , 16, RSA_D );\n mpi_read_string( &rsa.P , 16, RSA_P );\n mpi_read_string( &rsa.Q , 16, RSA_Q );\n mpi_read_string( &rsa.DP, 16, RSA_DP );\n mpi_read_string( &rsa.DQ, 16, RSA_DQ );\n mpi_read_string( &rsa.QP, 16, RSA_QP );\n\n if( verbose != 0 )\n printf( \" RSA key validation: \" );\n\n if( rsa_check_pubkey( &rsa ) != 0 ||\n rsa_check_privkey( &rsa ) != 0 )\n {\n if( verbose != 0 )\n printf( \"failed\\n\" );\n\n return( 1 );\n }\n\n if( verbose != 0 )\n printf( \"passed\\n PKCS#1 encryption : \" );\n\n memcpy( rsa_plaintext, RSA_PT, PT_LEN );\n\n if( rsa_pkcs1_encrypt( &rsa, &myrand, NULL, RSA_PUBLIC, PT_LEN,\n rsa_plaintext, rsa_ciphertext ) != 0 )\n {\n if( verbose != 0 )\n printf( \"failed\\n\" );\n\n return( 1 );\n }\n\n if( verbose != 0 )\n printf( \"passed\\n PKCS#1 decryption : \" );\n\n if( rsa_pkcs1_decrypt( &rsa, RSA_PRIVATE, &len,\n rsa_ciphertext, rsa_decrypted,\n sizeof(rsa_decrypted) ) != 0 )\n {\n if( verbose != 0 )\n printf( \"failed\\n\" );\n\n return( 1 );\n }\n\n if( memcmp( rsa_decrypted, rsa_plaintext, len ) != 0 )\n {\n if( verbose != 0 )\n printf( \"failed\\n\" );\n\n return( 1 );\n }\n\n#if defined(POLARSSL_SHA1_C)\n if( verbose != 0 )\n printf( \"passed\\n PKCS#1 data sign : \" );\n\n sha1( rsa_plaintext, PT_LEN, sha1sum );\n\n if( rsa_pkcs1_sign( &rsa, NULL, NULL, RSA_PRIVATE, SIG_RSA_SHA1, 20,\n sha1sum, rsa_ciphertext ) != 0 )\n {\n if( verbose != 0 )\n printf( \"failed\\n\" );\n\n return( 1 );\n }\n\n if( verbose != 0 )\n printf( \"passed\\n PKCS#1 sig. verify: \" );\n\n if( rsa_pkcs1_verify( &rsa, RSA_PUBLIC, SIG_RSA_SHA1, 20,\n sha1sum, rsa_ciphertext ) != 0 )\n {\n if( verbose != 0 )\n printf( \"failed\\n\" );\n\n return( 1 );\n }\n\n if( verbose != 0 )\n printf( \"passed\\n\\n\" );\n#endif /* POLARSSL_SHA1_C */\n\n rsa_free( &rsa );\n\n return( 0 );\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int main( int argc, char *argv[] )\n{\n ((void) argc);\n ((void) argv);\n\n printf(\"POLARSSL_AES_C and/or POLARSSL_DHM_C and/or POLARSSL_ENTROPY_C \"\n \"and/or POLARSSL_NET_C and/or POLARSSL_RSA_C and/or \"\n \"POLARSSL_SHA1_C and/or POLARSSL_FS_IO and/or \"\n \"POLARSSL_CTR_DBRG_C not defined.\\n\");\n return( 0 );\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int dane_verify_session_crt (\n dane_state_t s,\n\tgnutls_session_t session,\n\tconst char * hostname, const char* proto, unsigned int port,\n\tunsigned int sflags, unsigned int vflags,\n\tunsigned int *verify)\n{\nconst gnutls_datum_t *cert_list;\nunsigned int cert_list_size = 0;\nunsigned int type;\n\n\tcert_list = gnutls_certificate_get_peers(session, &cert_list_size);\n\tif (cert_list_size == 0) {\n\t\treturn gnutls_assert_val(DANE_E_NO_CERT);\n\t}\n\t\n\ttype = gnutls_certificate_type_get(session);\n\t\n\treturn dane_verify_crt(s, cert_list, cert_list_size, type, hostname, proto, port, sflags, vflags, verify);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Adding dane_raw_tlsa to allow initialization of dane_query_t from DANE records based on external DNS resolutions. Also fixing a buffer overflow.\n\nSigned-off-by: Nikos Mavrogiannopoulos '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: long do_msgsnd(int msqid, long mtype, void __user *mtext,\n\t\tsize_t msgsz, int msgflg)\n{\n\tstruct msg_queue *msq;\n\tstruct msg_msg *msg;\n\tint err;\n\tstruct ipc_namespace *ns;\n\n\tns = current->nsproxy->ipc_ns;\n\n\tif (msgsz > ns->msg_ctlmax || (long) msgsz < 0 || msqid < 0)\n\t\treturn -EINVAL;\n\tif (mtype < 1)\n\t\treturn -EINVAL;\n\n\tmsg = load_msg(mtext, msgsz);\n\tif (IS_ERR(msg))\n\t\treturn PTR_ERR(msg);\n\n\tmsg->m_type = mtype;\n\tmsg->m_ts = msgsz;\n\n\tmsq = msg_lock_check(ns, msqid);\n\tif (IS_ERR(msq)) {\n\t\terr = PTR_ERR(msq);\n\t\tgoto out_free;\n\t}\n\n\tfor (;;) {\n\t\tstruct msg_sender s;\n\n\t\terr = -EACCES;\n\t\tif (ipcperms(ns, &msq->q_perm, S_IWUGO))\n\t\t\tgoto out_unlock_free;\n\n\t\terr = security_msg_queue_msgsnd(msq, msg, msgflg);\n\t\tif (err)\n\t\t\tgoto out_unlock_free;\n\n\t\tif (msgsz + msq->q_cbytes <= msq->q_qbytes &&\n\t\t\t\t1 + msq->q_qnum <= msq->q_qbytes) {\n\t\t\tbreak;\n\t\t}\n\n\t\t/* queue full, wait: */\n\t\tif (msgflg & IPC_NOWAIT) {\n\t\t\terr = -EAGAIN;\n\t\t\tgoto out_unlock_free;\n\t\t}\n\t\tss_add(msq, &s);\n\t\tipc_rcu_getref(msq);\n\t\tmsg_unlock(msq);\n\t\tschedule();\n\n\t\tipc_lock_by_ptr(&msq->q_perm);\n\t\tipc_rcu_putref(msq);\n\t\tif (msq->q_perm.deleted) {\n\t\t\terr = -EIDRM;\n\t\t\tgoto out_unlock_free;\n\t\t}\n\t\tss_del(&s);\n\n\t\tif (signal_pending(current)) {\n\t\t\terr = -ERESTARTNOHAND;\n\t\t\tgoto out_unlock_free;\n\t\t}\n\t}\n\n\tmsq->q_lspid = task_tgid_vnr(current);\n\tmsq->q_stime = get_seconds();\n\n\tif (!pipelined_send(msq, msg)) {\n\t\t/* no one is waiting for this message, enqueue it */\n\t\tlist_add_tail(&msg->m_list, &msq->q_messages);\n\t\tmsq->q_cbytes += msgsz;\n\t\tmsq->q_qnum++;\n\t\tatomic_add(msgsz, &ns->msg_bytes);\n\t\tatomic_inc(&ns->msg_hdrs);\n\t}\n\n\terr = 0;\n\tmsg = NULL;\n\nout_unlock_free:\n\tmsg_unlock(msq);\nout_free:\n\tif (msg != NULL)\n\t\tfree_msg(msg);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'ipc,sem: fine grained locking for semtimedop\n\nIntroduce finer grained locking for semtimedop, to handle the common case\nof a program wanting to manipulate one semaphore from an array with\nmultiple semaphores.\n\nIf the call is a semop manipulating just one semaphore in an array with\nmultiple semaphores, only take the lock for that semaphore itself.\n\nIf the call needs to manipulate multiple semaphores, or another caller is\nin a transaction that manipulates multiple semaphores, the sem_array lock\nis taken, as well as all the locks for the individual semaphores.\n\nOn a 24 CPU system, performance numbers with the semop-multi\ntest with N threads and N semaphores, look like this:\n\n\tvanilla\t\tDavidlohr's\tDavidlohr's +\tDavidlohr's +\nthreads\t\t\tpatches\t\trwlock patches\tv3 patches\n10\t610652\t\t726325\t\t1783589\t\t2142206\n20\t341570\t\t365699\t\t1520453\t\t1977878\n30\t288102\t\t307037\t\t1498167\t\t2037995\n40\t290714\t\t305955\t\t1612665\t\t2256484\n50\t288620\t\t312890\t\t1733453\t\t2650292\n60\t289987\t\t306043\t\t1649360\t\t2388008\n70\t291298\t\t306347\t\t1723167\t\t2717486\n80\t290948\t\t305662\t\t1729545\t\t2763582\n90\t290996\t\t306680\t\t1736021\t\t2757524\n100\t292243\t\t306700\t\t1773700\t\t3059159\n\n[davidlohr.bueso@hp.com: do not call sem_lock when bogus sma]\n[davidlohr.bueso@hp.com: make refcounter atomic]\nSigned-off-by: Rik van Riel \nSuggested-by: Linus Torvalds \nAcked-by: Davidlohr Bueso \nCc: Chegu Vinod \nCc: Jason Low \nReviewed-by: Michel Lespinasse \nCc: Peter Hurley \nCc: Stanislav Kinsbursky \nTested-by: Emmanuel Benisty \nTested-by: Sedat Dilek \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline void sem_lock_and_putref(struct sem_array *sma)\n{\n\tipc_lock_by_ptr(&sma->sem_perm);\n\tipc_rcu_putref(sma);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'ipc,sem: fine grained locking for semtimedop\n\nIntroduce finer grained locking for semtimedop, to handle the common case\nof a program wanting to manipulate one semaphore from an array with\nmultiple semaphores.\n\nIf the call is a semop manipulating just one semaphore in an array with\nmultiple semaphores, only take the lock for that semaphore itself.\n\nIf the call needs to manipulate multiple semaphores, or another caller is\nin a transaction that manipulates multiple semaphores, the sem_array lock\nis taken, as well as all the locks for the individual semaphores.\n\nOn a 24 CPU system, performance numbers with the semop-multi\ntest with N threads and N semaphores, look like this:\n\n\tvanilla\t\tDavidlohr's\tDavidlohr's +\tDavidlohr's +\nthreads\t\t\tpatches\t\trwlock patches\tv3 patches\n10\t610652\t\t726325\t\t1783589\t\t2142206\n20\t341570\t\t365699\t\t1520453\t\t1977878\n30\t288102\t\t307037\t\t1498167\t\t2037995\n40\t290714\t\t305955\t\t1612665\t\t2256484\n50\t288620\t\t312890\t\t1733453\t\t2650292\n60\t289987\t\t306043\t\t1649360\t\t2388008\n70\t291298\t\t306347\t\t1723167\t\t2717486\n80\t290948\t\t305662\t\t1729545\t\t2763582\n90\t290996\t\t306680\t\t1736021\t\t2757524\n100\t292243\t\t306700\t\t1773700\t\t3059159\n\n[davidlohr.bueso@hp.com: do not call sem_lock when bogus sma]\n[davidlohr.bueso@hp.com: make refcounter atomic]\nSigned-off-by: Rik van Riel \nSuggested-by: Linus Torvalds \nAcked-by: Davidlohr Bueso \nCc: Chegu Vinod \nCc: Jason Low \nReviewed-by: Michel Lespinasse \nCc: Peter Hurley \nCc: Stanislav Kinsbursky \nTested-by: Emmanuel Benisty \nTested-by: Sedat Dilek \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static gg_action_t gg_handle_tls_negotiation(struct gg_session *sess, struct gg_event *e, enum gg_state_t next_state, enum gg_state_t alt_state, enum gg_state_t alt2_state)\n{\n\tint valid_hostname = 0;\n\n#ifdef GG_CONFIG_HAVE_GNUTLS\n\tunsigned int status;\n\tint res;\n\n\tgg_debug_session(sess, GG_DEBUG_MISC, \"// gg_watch_fd() GG_STATE_TLS_NEGOTIATION\\n\");\n\n\tfor (;;) {\n\t\tres = gnutls_handshake(GG_SESSION_GNUTLS(sess));\n\n\t\tif (res == GNUTLS_E_AGAIN) {\n\t\t\tgg_debug_session(sess, GG_DEBUG_MISC, \"// gg_watch_fd() TLS handshake GNUTLS_E_AGAIN\\n\");\n\n\t\t\tif (gnutls_record_get_direction(GG_SESSION_GNUTLS(sess)) == 0)\n\t\t\t\tsess->check = GG_CHECK_READ;\n\t\t\telse\n\t\t\t\tsess->check = GG_CHECK_WRITE;\n\t\t\tsess->timeout = GG_DEFAULT_TIMEOUT;\n\t\t\treturn GG_ACTION_WAIT;\n\t\t}\n\n\t\tif (res == GNUTLS_E_INTERRUPTED) {\n\t\t\tgg_debug_session(sess, GG_DEBUG_MISC, \"// gg_watch_fd() TLS handshake GNUTLS_E_INTERRUPTED\\n\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (res != GNUTLS_E_SUCCESS) {\n\t\t\tgg_debug_session(sess, GG_DEBUG_MISC, \"// gg_watch_fd() TLS handshake error: %d, %s\\n\", res, gnutls_strerror(res));\n\t\t\te->event.failure = GG_FAILURE_TLS;\n\t\t\treturn GG_ACTION_FAIL;\n\t\t}\n\n\t\tbreak;\n\t}\n\n\tgg_debug_session(sess, GG_DEBUG_MISC, \"// gg_watch_fd() TLS negotiation succeded:\\n\");\n\tgg_debug_session(sess, GG_DEBUG_MISC, \"// cipher: VERS-%s:%s:%s:%s:COMP-%s\\n\",\n\t\tgnutls_protocol_get_name(gnutls_protocol_get_version(GG_SESSION_GNUTLS(sess))),\n\t\tgnutls_cipher_get_name(gnutls_cipher_get(GG_SESSION_GNUTLS(sess))),\n\t\tgnutls_kx_get_name(gnutls_kx_get(GG_SESSION_GNUTLS(sess))),\n\t\tgnutls_mac_get_name(gnutls_mac_get(GG_SESSION_GNUTLS(sess))),\n\t\tgnutls_compression_get_name(gnutls_compression_get(GG_SESSION_GNUTLS(sess))));\n\n\tif (gnutls_certificate_type_get(GG_SESSION_GNUTLS(sess)) == GNUTLS_CRT_X509) {\n\t\tunsigned int peer_count;\n\t\tconst gnutls_datum_t *peers;\n\t\tgnutls_x509_crt_t cert;\n\n\t\tif (gnutls_x509_crt_init(&cert) == 0) {\n\t\t\tpeers = gnutls_certificate_get_peers(GG_SESSION_GNUTLS(sess), &peer_count);\n\n\t\t\tif (peers != NULL) {\n\t\t\t\tchar buf[256];\n\t\t\t\tsize_t size;\n\n\t\t\t\tif (gnutls_x509_crt_import(cert, &peers[0], GNUTLS_X509_FMT_DER) == 0) {\n\t\t\t\t\tsize = sizeof(buf);\n\t\t\t\t\tgnutls_x509_crt_get_dn(cert, buf, &size);\n\t\t\t\t\tgg_debug_session(sess, GG_DEBUG_MISC, \"// cert subject: %s\\n\", buf);\n\t\t\t\t\tsize = sizeof(buf);\n\t\t\t\t\tgnutls_x509_crt_get_issuer_dn(cert, buf, &size);\n\t\t\t\t\tgg_debug_session(sess, GG_DEBUG_MISC, \"// cert issuer: %s\\n\", buf);\n\n\t\t\t\t\tif (gnutls_x509_crt_check_hostname(cert, sess->connect_host) != 0)\n\t\t\t\t\t\tvalid_hostname = 1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tgnutls_x509_crt_deinit(cert);\n\t\t}\n\t}\n\n\tres = gnutls_certificate_verify_peers2(GG_SESSION_GNUTLS(sess), &status);\n\n\tif (res != 0) {\n\t\tgg_debug_session(sess, GG_DEBUG_MISC, \"//\u00a0\u00a0 WARNING! unable to verify peer certificate: %d, %s\\n\", res, gnutls_strerror(res));\n\n\t\tif (sess->ssl_flag == GG_SSL_REQUIRED) {\n\t\t\te->event.failure = GG_FAILURE_TLS;\n\t\t\treturn GG_ACTION_FAIL;\n\t\t}\n\t} else {\n\t\tgg_debug_session(sess, GG_DEBUG_MISC, \"// verified peer certificate\\n\");\n\t}\n\n\n#elif defined GG_CONFIG_HAVE_OPENSSL\n\n\tX509 *peer;\n\tint res;\n\n\tgg_debug_session(sess, GG_DEBUG_MISC, \"// gg_watch_fd() %s\\n\", gg_debug_state(sess->state));\n\n\tres = SSL_connect(GG_SESSION_OPENSSL(sess));\n\n\tif (res <= 0) {\n\t\tint err;\n\t\t\n\t\terr = SSL_get_error(GG_SESSION_OPENSSL(sess), res);\n\n\t\tif (res == 0) {\n\t\t\tgg_debug_session(sess, GG_DEBUG_MISC, \"// gg_watch_fd() disconnected during TLS negotiation\\n\");\n\t\t\te->event.failure = GG_FAILURE_TLS;\n\t\t\treturn GG_ACTION_FAIL;\n\t\t}\n\n\t\tif (err == SSL_ERROR_WANT_READ) {\n\t\t\tgg_debug_session(sess, GG_DEBUG_MISC, \"// gg_watch_fd() SSL_connect() wants to read\\n\");\n\n\t\t\tsess->check = GG_CHECK_READ;\n\t\t\tsess->timeout = GG_DEFAULT_TIMEOUT;\n\t\t\treturn GG_ACTION_WAIT;\n\t\t} else if (err == SSL_ERROR_WANT_WRITE) {\n\t\t\tgg_debug_session(sess, GG_DEBUG_MISC, \"// gg_watch_fd() SSL_connect() wants to write\\n\");\n\n\t\t\tsess->check = GG_CHECK_WRITE;\n\t\t\tsess->timeout = GG_DEFAULT_TIMEOUT;\n\t\t\treturn GG_ACTION_WAIT;\n\t\t} else {\n\t\t\tchar buf[256];\n\n\t\t\tERR_error_string_n(ERR_get_error(), buf, sizeof(buf));\n\n\t\t\tgg_debug_session(sess, GG_DEBUG_MISC, \"// gg_watch_fd() SSL_connect() bailed out: %s\\n\", buf);\n\n\t\t\te->event.failure = GG_FAILURE_TLS;\n\t\t\treturn GG_ACTION_FAIL;\n\t\t}\n\t}\n\n\tgg_debug_session(sess, GG_DEBUG_MISC, \"// gg_watch_fd() TLS negotiation succeded:\\n// cipher: %s\\n\", SSL_get_cipher_name(GG_SESSION_OPENSSL(sess)));\n\n\tpeer = SSL_get_peer_certificate(GG_SESSION_OPENSSL(sess));\n\n\tif (peer == NULL) {\n\t\tgg_debug_session(sess, GG_DEBUG_MISC, \"// WARNING! unable to get peer certificate!\\n\");\n\n\t\tif (sess->ssl_flag == GG_SSL_REQUIRED) {\n\t\t\te->event.failure = GG_FAILURE_TLS;\n\t\t\treturn GG_ACTION_FAIL;\n\t\t}\n\t} else {\n\t\tchar buf[256];\n\t\tlong res;\n\n\t\tX509_NAME_oneline(X509_get_subject_name(peer), buf, sizeof(buf));\n\t\tgg_debug_session(sess, GG_DEBUG_MISC, \"// cert subject: %s\\n\", buf);\n\n\t\tX509_NAME_oneline(X509_get_issuer_name(peer), buf, sizeof(buf));\n\t\tgg_debug_session(sess, GG_DEBUG_MISC, \"// cert issuer: %s\\n\", buf);\n\n\t\tres = SSL_get_verify_result(GG_SESSION_OPENSSL(sess));\n\n\t\tif (res != X509_V_OK) {\n\t\t\tgg_debug_session(sess, GG_DEBUG_MISC, \"//\u00a0\u00a0 WARNING! unable to verify peer certificate! res=%ld\\n\", res);\n\n\t\t\tif (sess->ssl_flag == GG_SSL_REQUIRED) {\n\t\t\t\te->event.failure = GG_FAILURE_TLS;\n\t\t\t\treturn GG_ACTION_FAIL;\n\t\t\t}\n\t\t} else {\n\t\t\tgg_debug_session(sess, GG_DEBUG_MISC, \"// verified peer certificate\\n\");\n\t\t}\n\n\t\tif (X509_NAME_get_text_by_NID(X509_get_subject_name(peer), NID_commonName, buf, sizeof(buf)) == -1)\n\t\t\tbuf[0] = 0;\n\n\t\t/* Obs\u0142uga certyfikat\u00f3w z wieloznacznikiem */\n\t\tif (strchr(buf, '*') == buf && strchr(buf + 1, '*') == NULL) {\n\t\t\tchar *tmp;\n\n\t\t\ttmp = strchr(sess->connect_host, '.');\n\n\t\t\tif (tmp != NULL)\n\t\t\t\tvalid_hostname = (strcasecmp(tmp, buf + 1) == 0);\n\t\t} else {\n\t\t\tvalid_hostname = (strcasecmp(sess->connect_host, buf) == 0);\n\t\t}\n\t}\n\n#else\n\n\tgg_debug_session(sess, GG_DEBUG_MISC, \"// gg_watch_fd() no SSL support\\n\");\n\te->event.failure = GG_FAILURE_TLS;\n\treturn GG_ACTION_FAIL;\n\n#endif\n\n\tif (!valid_hostname) {\n\t\tgg_debug_session(sess, GG_DEBUG_MISC, \"//\u00a0\u00a0 WARNING! unable to verify hostname\\n\");\n\n\t\tif (sess->ssl_flag == GG_SSL_REQUIRED) {\n\t\t\te->event.failure = GG_FAILURE_TLS;\n\t\t\treturn GG_ACTION_FAIL;\n\t\t}\n\t}\n\n\tsess->state = next_state;\n\tsess->check = GG_CHECK_READ;\n\tsess->timeout = GG_DEFAULT_TIMEOUT;\n\n\treturn GG_ACTION_WAIT;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Poprawna weryfikacja certyfikatu za pomoc\u0105 GnuTLS.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void\nBfree(Bigint *v)\n{\n if (v) {\n ACQUIRE_DTOA_LOCK(0);\n v->next = freelist[v->k];\n freelist[v->k] = v;\n FREE_DTOA_LOCK(0);\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'util.c: ignore too long fraction part\n\n* util.c (ruby_strtod): ignore too long fraction part, which does not\n affect the result.\n\ngit-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@43775 b2dd03c8-39d4-4d8f-98ff-823fe69b080e'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static JSON_INLINE size_t num_buckets(hashtable_t *hashtable)\n{\n return primes[hashtable->num_buckets];\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'CVE-2013-6401: Change hash function, randomize hashes\n\nThanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing\nand testing.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void test_simple()\n{\n json_set_alloc_funcs(my_malloc, my_free);\n create_and_free_complex_object();\n\n if(malloc_called != 20 || free_called != 20)\n fail(\"Custom allocation failed\");\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'CVE-2013-6401: Change hash function, randomize hashes\n\nThanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing\nand testing.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int pn_recvmsg(struct kiocb *iocb, struct sock *sk,\n\t\t\tstruct msghdr *msg, size_t len, int noblock,\n\t\t\tint flags, int *addr_len)\n{\n\tstruct sk_buff *skb = NULL;\n\tstruct sockaddr_pn sa;\n\tint rval = -EOPNOTSUPP;\n\tint copylen;\n\n\tif (flags & ~(MSG_PEEK|MSG_TRUNC|MSG_DONTWAIT|MSG_NOSIGNAL|\n\t\t\tMSG_CMSG_COMPAT))\n\t\tgoto out_nofree;\n\n\tif (addr_len)\n\t\t*addr_len = sizeof(sa);\n\n\tskb = skb_recv_datagram(sk, flags, noblock, &rval);\n\tif (skb == NULL)\n\t\tgoto out_nofree;\n\n\tpn_skb_get_src_sockaddr(skb, &sa);\n\n\tcopylen = skb->len;\n\tif (len < copylen) {\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t\tcopylen = len;\n\t}\n\n\trval = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copylen);\n\tif (rval) {\n\t\trval = -EFAULT;\n\t\tgoto out;\n\t}\n\n\trval = (flags & MSG_TRUNC) ? skb->len : copylen;\n\n\tif (msg->msg_name != NULL)\n\t\tmemcpy(msg->msg_name, &sa, sizeof(struct sockaddr_pn));\n\nout:\n\tskb_free_datagram(sk, skb);\n\nout_nofree:\n\treturn rval;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'inet: prevent leakage of uninitialized memory to user in recv syscalls\n\nOnly update *addr_len when we actually fill in sockaddr, otherwise we\ncan return uninitialized memory from the stack to the caller in the\nrecvfrom, recvmmsg and recvmsg syscalls. Drop the the (addr_len == NULL)\nchecks because we only get called with a valid addr_len pointer either\nfrom sock_common_recvmsg or inet_recvmsg.\n\nIf a blocking read waits on a socket which is concurrently shut down we\nnow return zero and set msg_msgnamelen to 0.\n\nReported-by: mpb \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ipv6_recv_rxpmtu(struct sock *sk, struct msghdr *msg, int len)\n{\n\tstruct ipv6_pinfo *np = inet6_sk(sk);\n\tstruct sk_buff *skb;\n\tstruct sockaddr_in6 *sin;\n\tstruct ip6_mtuinfo mtu_info;\n\tint err;\n\tint copied;\n\n\terr = -EAGAIN;\n\tskb = xchg(&np->rxpmtu, NULL);\n\tif (skb == NULL)\n\t\tgoto out;\n\n\tcopied = skb->len;\n\tif (copied > len) {\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t\tcopied = len;\n\t}\n\terr = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);\n\tif (err)\n\t\tgoto out_free_skb;\n\n\tsock_recv_timestamp(msg, sk, skb);\n\n\tmemcpy(&mtu_info, IP6CBMTU(skb), sizeof(mtu_info));\n\n\tsin = (struct sockaddr_in6 *)msg->msg_name;\n\tif (sin) {\n\t\tsin->sin6_family = AF_INET6;\n\t\tsin->sin6_flowinfo = 0;\n\t\tsin->sin6_port = 0;\n\t\tsin->sin6_scope_id = mtu_info.ip6m_addr.sin6_scope_id;\n\t\tsin->sin6_addr = mtu_info.ip6m_addr.sin6_addr;\n\t}\n\n\tput_cmsg(msg, SOL_IPV6, IPV6_PATHMTU, sizeof(mtu_info), &mtu_info);\n\n\terr = copied;\n\nout_free_skb:\n\tkfree_skb(skb);\nout:\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'inet: fix addr_len/msg->msg_namelen assignment in recv_error and rxpmtu functions\n\nCommit bceaa90240b6019ed73b49965eac7d167610be69 (\"inet: prevent leakage\nof uninitialized memory to user in recv syscalls\") conditionally updated\naddr_len if the msg_name is written to. The recv_error and rxpmtu\nfunctions relied on the recvmsg functions to set up addr_len before.\n\nAs this does not happen any more we have to pass addr_len to those\nfunctions as well and set it to the size of the corresponding sockaddr\nlength.\n\nThis broke traceroute and such.\n\nFixes: bceaa90240b6 (\"inet: prevent leakage of uninitialized memory to user in recv syscalls\")\nReported-by: Brad Spengler \nReported-by: Tom Labanowski\nCc: mpb \nCc: David S. Miller \nCc: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int msPostGISLayerSetTimeFilter(layerObj *lp, const char *timestring, const char *timefield)\n{\n char **atimes, **aranges = NULL;\n int numtimes=0,i=0,numranges=0;\n size_t buffer_size = 512;\n char buffer[512], bufferTmp[512];\n\n buffer[0] = '\\0';\n bufferTmp[0] = '\\0';\n\n if (!lp || !timestring || !timefield)\n return MS_FALSE;\n\n /* discrete time */\n if (strstr(timestring, \",\") == NULL &&\n strstr(timestring, \"/\") == NULL) { /* discrete time */\n createPostgresTimeCompareSimple(timefield, timestring, buffer, buffer_size);\n } else {\n\n /* multiple times, or ranges */\n atimes = msStringSplit (timestring, ',', &numtimes);\n if (atimes == NULL || numtimes < 1)\n return MS_FALSE;\n\n strlcat(buffer, \"(\", buffer_size);\n for(i=0; ifilteritem) free(lp->filteritem);\n lp->filteritem = msStrdup(timefield);\n if (&lp->filter) {\n /* if the filter is set and it's a string type, concatenate it with\n the time. If not just free it */\n if (lp->filter.type == MS_EXPRESSION) {\n snprintf(bufferTmp, buffer_size, \"(%s) and %s\", lp->filter.string, buffer);\n loadExpressionString(&lp->filter, bufferTmp);\n } else {\n freeExpression(&lp->filter);\n loadExpressionString(&lp->filter, buffer);\n }\n }\n\n\n return MS_TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-89'], 'message': 'Fix potential SQL Injection with postgis TIME filters (#4834)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int BSONTool::run() {\n _objcheck = hasParam( \"objcheck\" );\n\n if ( hasParam( \"filter\" ) )\n _matcher.reset( new Matcher( fromjson( getParam( \"filter\" ) ) ) );\n\n return doRun();\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'SERVER-7769 - turn objcheck on by default and use new fast bson validate'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void UrlParser::parse(char ch)\n {\n switch(_state)\n {\n case state_0:\n if (ch == '=')\n _state = state_value;\n else if (ch == '&')\n ;\n else if (ch == '%')\n _state = state_keyesc;\n else\n {\n _key = ch;\n _state = state_key;\n }\n break;\n\n case state_key:\n if (ch == '=')\n _state = state_value;\n else if (ch == '&')\n {\n _q.add(_key);\n _key.clear();\n _state = state_0;\n }\n else if (ch == '%')\n _state = state_keyesc;\n else\n _key += ch;\n break;\n\n case state_value:\n if (ch == '%')\n _state = state_valueesc;\n else if (ch == '&')\n {\n _q.add(_key, _value);\n _key.clear();\n _value.clear();\n _state = state_0;\n }\n else if (ch == '+')\n _value += ' ';\n else\n _value += ch;\n break;\n\n case state_keyesc:\n case state_valueesc:\n if (ch >= '0' && ch <= '9')\n {\n ++_cnt;\n _v = (_v << 4) + (ch - '0');\n }\n else if (ch >= 'a' && ch <= 'f')\n {\n ++_cnt;\n _v = (_v << 4) + (ch - 'a' + 10);\n }\n else if (ch >= 'A' && ch <= 'F')\n {\n ++_cnt;\n _v = (_v << 4) + (ch - 'A' + 10);\n }\n else\n {\n if (_cnt == 0)\n {\n if (_state == state_keyesc)\n _state = state_key;\n else\n _state = state_value;\n parse('%');\n }\n else\n {\n if (_state == state_keyesc)\n {\n _key += static_cast(_v);\n _state = state_key;\n }\n else\n {\n _value += static_cast(_v);\n _state = state_value;\n }\n\n _cnt = 0;\n _v = 0;\n }\n\n parse(ch);\n break;\n }\n\n if (_cnt >= 2)\n {\n if (_state == state_keyesc)\n {\n _key += static_cast(_v);\n _state = state_key;\n }\n else\n {\n _value += static_cast(_v);\n _state = state_value;\n }\n _cnt = 0;\n _v = 0;\n }\n\n break;\n\n }\n\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'fix parsing double % in query parameters'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: \tvoid verifyDirectoryPermissions(const string &path) {\n\t\tTRACE_POINT();\n\t\tstruct stat buf;\n\n\t\tif (stat(path.c_str(), &buf) == -1) {\n\t\t\tint e = errno;\n\t\t\tthrow FileSystemException(\"Cannot stat() \" + path, e, path);\n\t\t} else if (buf.st_mode != (S_IFDIR | parseModeString(\"u=rwx,g=rx,o=rx\"))) {\n\t\t\tthrow RuntimeException(\"Tried to reuse existing server instance directory \" +\n\t\t\t\tpath + \", but it has wrong permissions\");\n\t\t} else if (buf.st_uid != geteuid() || buf.st_gid != getegid()) {\n\t\t\t/* The server instance directory is always created by the Watchdog. Its UID/GID never\n\t\t\t * changes because:\n\t\t\t * 1. Disabling user switching only lowers the privilege of the HelperAgent.\n\t\t\t * 2. For the UID/GID to change, the web server must be completely restarted\n\t\t\t * (not just graceful reload) so that the control process can change its UID/GID.\n\t\t\t * This causes the PID to change, so that an entirely new server instance\n\t\t\t * directory is created.\n\t\t\t */\n\t\t\tthrow RuntimeException(\"Tried to reuse existing server instance directory \" +\n\t\t\t\tpath + \", but it has wrong owner and group\");\n\t\t}\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'Fix a symlink-related security vulnerability.\n\nThe fix in commit 34b10878 and contained a small attack time window in\nbetween two filesystem operations. This has been fixed.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: PHP_FUNCTION(imageaffinematrixconcat)\n{\n\tdouble m1[6];\n\tdouble m2[6];\n\tdouble mr[6];\n\n\tzval **tmp;\n\tzval *z_m1;\n\tzval *z_m2;\n\tint i, nelems;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"aa\", &z_m1, &z_m2) == FAILURE) {\n\t\treturn;\n\t}\n\n\tif (((nelems = zend_hash_num_elements(Z_ARRVAL_P(z_m1))) != 6) || (nelems = zend_hash_num_elements(Z_ARRVAL_P(z_m2))) != 6) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Affine arrays must have six elements\");\n\t\tRETURN_FALSE;\n\t}\n\n\tfor (i = 0; i < 6; i++) {\n\t\tif (zend_hash_index_find(Z_ARRVAL_P(z_m1), i, (void **) &tmp) == SUCCESS) {\n\t\t\tswitch (Z_TYPE_PP(tmp)) {\n\t\t\t\tcase IS_LONG:\n\t\t\t\t\tm1[i] = Z_LVAL_PP(tmp);\n\t\t\t\t\tbreak;\n\t\t\t\tcase IS_DOUBLE:\n\t\t\t\t\tm1[i] = Z_DVAL_PP(tmp);\n\t\t\t\t\tbreak;\n\t\t\t\tcase IS_STRING:\n\t\t\t\t\tconvert_to_double_ex(tmp);\n\t\t\t\t\tm1[i] = Z_DVAL_PP(tmp);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Invalid type for element %i\", i);\n\t\t\t\t\tRETURN_FALSE;\n\t\t\t}\n\t\t}\n\t\tif (zend_hash_index_find(Z_ARRVAL_P(z_m2), i, (void **) &tmp) == SUCCESS) {\n\t\t\tswitch (Z_TYPE_PP(tmp)) {\n\t\t\t\tcase IS_LONG:\n\t\t\t\t\tm2[i] = Z_LVAL_PP(tmp);\n\t\t\t\t\tbreak;\n\t\t\t\tcase IS_DOUBLE:\n\t\t\t\t\tm2[i] = Z_DVAL_PP(tmp);\n\t\t\t\t\tbreak;\n\t\t\t\tcase IS_STRING:\n\t\t\t\t\tconvert_to_double_ex(tmp);\n\t\t\t\t\tm2[i] = Z_DVAL_PP(tmp);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Invalid type for element %i\", i);\n\t\t\t\t\tRETURN_FALSE;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (gdAffineConcat (mr, m1, m2) != GD_TRUE) {\n\t\tRETURN_FALSE;\n\t}\n\n\tarray_init(return_value);\n\tfor (i = 0; i < 6; i++) {\n\t\tadd_index_double(return_value, i, mr[i]);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Fixed bug #66356 (Heap Overflow Vulnerability in imagecrop())\n\nAnd also fixed the bug: arguments are altered after some calls'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: fmgr_sql_validator(PG_FUNCTION_ARGS)\n{\n\tOid\t\t\tfuncoid = PG_GETARG_OID(0);\n\tHeapTuple\ttuple;\n\tForm_pg_proc proc;\n\tList\t *raw_parsetree_list;\n\tList\t *querytree_list;\n\tListCell *lc;\n\tbool\t\tisnull;\n\tDatum\t\ttmp;\n\tchar\t *prosrc;\n\tparse_error_callback_arg callback_arg;\n\tErrorContextCallback sqlerrcontext;\n\tbool\t\thaspolyarg;\n\tint\t\t\ti;\n\n\ttuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));\n\tif (!HeapTupleIsValid(tuple))\n\t\telog(ERROR, \"cache lookup failed for function %u\", funcoid);\n\tproc = (Form_pg_proc) GETSTRUCT(tuple);\n\n\t/* Disallow pseudotype result */\n\t/* except for RECORD, VOID, or polymorphic */\n\tif (get_typtype(proc->prorettype) == TYPTYPE_PSEUDO &&\n\t\tproc->prorettype != RECORDOID &&\n\t\tproc->prorettype != VOIDOID &&\n\t\t!IsPolymorphicType(proc->prorettype))\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),\n\t\t\t\t errmsg(\"SQL functions cannot return type %s\",\n\t\t\t\t\t\tformat_type_be(proc->prorettype))));\n\n\t/* Disallow pseudotypes in arguments */\n\t/* except for polymorphic */\n\thaspolyarg = false;\n\tfor (i = 0; i < proc->pronargs; i++)\n\t{\n\t\tif (get_typtype(proc->proargtypes.values[i]) == TYPTYPE_PSEUDO)\n\t\t{\n\t\t\tif (IsPolymorphicType(proc->proargtypes.values[i]))\n\t\t\t\thaspolyarg = true;\n\t\t\telse\n\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),\n\t\t\t\t\t errmsg(\"SQL functions cannot have arguments of type %s\",\n\t\t\t\t\t\t\tformat_type_be(proc->proargtypes.values[i]))));\n\t\t}\n\t}\n\n\t/* Postpone body checks if !check_function_bodies */\n\tif (check_function_bodies)\n\t{\n\t\ttmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);\n\t\tif (isnull)\n\t\t\telog(ERROR, \"null prosrc\");\n\n\t\tprosrc = TextDatumGetCString(tmp);\n\n\t\t/*\n\t\t * Setup error traceback support for ereport().\n\t\t */\n\t\tcallback_arg.proname = NameStr(proc->proname);\n\t\tcallback_arg.prosrc = prosrc;\n\n\t\tsqlerrcontext.callback = sql_function_parse_error_callback;\n\t\tsqlerrcontext.arg = (void *) &callback_arg;\n\t\tsqlerrcontext.previous = error_context_stack;\n\t\terror_context_stack = &sqlerrcontext;\n\n\t\t/*\n\t\t * We can't do full prechecking of the function definition if there\n\t\t * are any polymorphic input types, because actual datatypes of\n\t\t * expression results will be unresolvable. The check will be done at\n\t\t * runtime instead.\n\t\t *\n\t\t * We can run the text through the raw parser though; this will at\n\t\t * least catch silly syntactic errors.\n\t\t */\n\t\traw_parsetree_list = pg_parse_query(prosrc);\n\n\t\tif (!haspolyarg)\n\t\t{\n\t\t\t/*\n\t\t\t * OK to do full precheck: analyze and rewrite the queries, then\n\t\t\t * verify the result type.\n\t\t\t */\n\t\t\tSQLFunctionParseInfoPtr pinfo;\n\n\t\t\t/* But first, set up parameter information */\n\t\t\tpinfo = prepare_sql_fn_parse_info(tuple, NULL, InvalidOid);\n\n\t\t\tquerytree_list = NIL;\n\t\t\tforeach(lc, raw_parsetree_list)\n\t\t\t{\n\t\t\t\tNode\t *parsetree = (Node *) lfirst(lc);\n\t\t\t\tList\t *querytree_sublist;\n\n\t\t\t\tquerytree_sublist = pg_analyze_and_rewrite_params(parsetree,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t prosrc,\n\t\t\t\t\t\t\t\t\t (ParserSetupHook) sql_fn_parser_setup,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t pinfo);\n\t\t\t\tquerytree_list = list_concat(querytree_list,\n\t\t\t\t\t\t\t\t\t\t\t querytree_sublist);\n\t\t\t}\n\n\t\t\t(void) check_sql_fn_retval(funcoid, proc->prorettype,\n\t\t\t\t\t\t\t\t\t querytree_list,\n\t\t\t\t\t\t\t\t\t NULL, NULL);\n\t\t}\n\n\t\terror_context_stack = sqlerrcontext.previous;\n\t}\n\n\tReleaseSysCache(tuple);\n\n\tPG_RETURN_VOID();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'Prevent privilege escalation in explicit calls to PL validators.\n\nThe primary role of PL validators is to be called implicitly during\nCREATE FUNCTION, but they are also normal functions that a user can call\nexplicitly. Add a permissions check to each validator to ensure that a\nuser cannot use explicit validator calls to achieve things he could not\notherwise achieve. Back-patch to 8.4 (all supported versions).\nNon-core procedural language extensions ought to make the same two-line\nchange to their own validators.\n\nAndres Freund, reviewed by Tom Lane and Noah Misch.\n\nSecurity: CVE-2014-0061'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString)\n{\n\tRelation\trel;\n\tParseState *pstate;\n\tCreateStmtContext cxt;\n\tList\t *result;\n\tList\t *save_alist;\n\tListCell *lcmd,\n\t\t\t *l;\n\tList\t *newcmds = NIL;\n\tbool\t\tskipValidation = true;\n\tAlterTableCmd *newcmd;\n\tLOCKMODE\tlockmode;\n\n\t/*\n\t * We must not scribble on the passed-in AlterTableStmt, so copy it. (This\n\t * is overkill, but easy.)\n\t */\n\tstmt = (AlterTableStmt *) copyObject(stmt);\n\n\t/*\n\t * Determine the appropriate lock level for this list of subcommands.\n\t */\n\tlockmode = AlterTableGetLockLevel(stmt->cmds);\n\n\t/*\n\t * Acquire appropriate lock on the target relation, which will be held\n\t * until end of transaction. This ensures any decisions we make here\n\t * based on the state of the relation will still be good at execution. We\n\t * must get lock now because execution will later require it; taking a\n\t * lower grade lock now and trying to upgrade later risks deadlock. Any\n\t * new commands we add after this must not upgrade the lock level\n\t * requested here.\n\t */\n\trel = relation_openrv_extended(stmt->relation, lockmode, stmt->missing_ok);\n\tif (rel == NULL)\n\t{\n\t\t/* this message is consistent with relation_openrv */\n\t\tereport(NOTICE,\n\t\t\t\t(errmsg(\"relation \\\"%s\\\" does not exist, skipping\",\n\t\t\t\t\t\tstmt->relation->relname)));\n\t\treturn NIL;\n\t}\n\n\t/* Set up pstate and CreateStmtContext */\n\tpstate = make_parsestate(NULL);\n\tpstate->p_sourcetext = queryString;\n\n\tcxt.pstate = pstate;\n\tif (stmt->relkind == OBJECT_FOREIGN_TABLE)\n\t{\n\t\tcxt.stmtType = \"ALTER FOREIGN TABLE\";\n\t\tcxt.isforeign = true;\n\t}\n\telse\n\t{\n\t\tcxt.stmtType = \"ALTER TABLE\";\n\t\tcxt.isforeign = false;\n\t}\n\tcxt.relation = stmt->relation;\n\tcxt.rel = rel;\n\tcxt.inhRelations = NIL;\n\tcxt.isalter = true;\n\tcxt.hasoids = false;\t\t/* need not be right */\n\tcxt.columns = NIL;\n\tcxt.ckconstraints = NIL;\n\tcxt.fkconstraints = NIL;\n\tcxt.ixconstraints = NIL;\n\tcxt.inh_indexes = NIL;\n\tcxt.blist = NIL;\n\tcxt.alist = NIL;\n\tcxt.pkey = NULL;\n\n\t/*\n\t * The only subtypes that currently require parse transformation handling\n\t * are ADD COLUMN and ADD CONSTRAINT. These largely re-use code from\n\t * CREATE TABLE.\n\t */\n\tforeach(lcmd, stmt->cmds)\n\t{\n\t\tAlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);\n\n\t\tswitch (cmd->subtype)\n\t\t{\n\t\t\tcase AT_AddColumn:\n\t\t\tcase AT_AddColumnToView:\n\t\t\t\t{\n\t\t\t\t\tColumnDef *def = (ColumnDef *) cmd->def;\n\n\t\t\t\t\tAssert(IsA(def, ColumnDef));\n\t\t\t\t\ttransformColumnDefinition(&cxt, def);\n\n\t\t\t\t\t/*\n\t\t\t\t\t * If the column has a non-null default, we can't skip\n\t\t\t\t\t * validation of foreign keys.\n\t\t\t\t\t */\n\t\t\t\t\tif (def->raw_default != NULL)\n\t\t\t\t\t\tskipValidation = false;\n\n\t\t\t\t\t/*\n\t\t\t\t\t * All constraints are processed in other ways. Remove the\n\t\t\t\t\t * original list\n\t\t\t\t\t */\n\t\t\t\t\tdef->constraints = NIL;\n\n\t\t\t\t\tnewcmds = lappend(newcmds, cmd);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\tcase AT_AddConstraint:\n\n\t\t\t\t/*\n\t\t\t\t * The original AddConstraint cmd node doesn't go to newcmds\n\t\t\t\t */\n\t\t\t\tif (IsA(cmd->def, Constraint))\n\t\t\t\t{\n\t\t\t\t\ttransformTableConstraint(&cxt, (Constraint *) cmd->def);\n\t\t\t\t\tif (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)\n\t\t\t\t\t\tskipValidation = false;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\telog(ERROR, \"unrecognized node type: %d\",\n\t\t\t\t\t\t (int) nodeTag(cmd->def));\n\t\t\t\tbreak;\n\n\t\t\tcase AT_ProcessedConstraint:\n\n\t\t\t\t/*\n\t\t\t\t * Already-transformed ADD CONSTRAINT, so just make it look\n\t\t\t\t * like the standard case.\n\t\t\t\t */\n\t\t\t\tcmd->subtype = AT_AddConstraint;\n\t\t\t\tnewcmds = lappend(newcmds, cmd);\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tnewcmds = lappend(newcmds, cmd);\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t/*\n\t * transformIndexConstraints wants cxt.alist to contain only index\n\t * statements, so transfer anything we already have into save_alist\n\t * immediately.\n\t */\n\tsave_alist = cxt.alist;\n\tcxt.alist = NIL;\n\n\t/* Postprocess index and FK constraints */\n\ttransformIndexConstraints(&cxt);\n\n\ttransformFKConstraints(&cxt, skipValidation, true);\n\n\t/*\n\t * Push any index-creation commands into the ALTER, so that they can be\n\t * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that\n\t * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint\n\t * subcommand has already been through transformIndexStmt.\n\t */\n\tforeach(l, cxt.alist)\n\t{\n\t\tIndexStmt *idxstmt = (IndexStmt *) lfirst(l);\n\n\t\tAssert(IsA(idxstmt, IndexStmt));\n\t\tidxstmt = transformIndexStmt(idxstmt, queryString);\n\t\tnewcmd = makeNode(AlterTableCmd);\n\t\tnewcmd->subtype = OidIsValid(idxstmt->indexOid) ? AT_AddIndexConstraint : AT_AddIndex;\n\t\tnewcmd->def = (Node *) idxstmt;\n\t\tnewcmds = lappend(newcmds, newcmd);\n\t}\n\tcxt.alist = NIL;\n\n\t/* Append any CHECK or FK constraints to the commands list */\n\tforeach(l, cxt.ckconstraints)\n\t{\n\t\tnewcmd = makeNode(AlterTableCmd);\n\t\tnewcmd->subtype = AT_AddConstraint;\n\t\tnewcmd->def = (Node *) lfirst(l);\n\t\tnewcmds = lappend(newcmds, newcmd);\n\t}\n\tforeach(l, cxt.fkconstraints)\n\t{\n\t\tnewcmd = makeNode(AlterTableCmd);\n\t\tnewcmd->subtype = AT_AddConstraint;\n\t\tnewcmd->def = (Node *) lfirst(l);\n\t\tnewcmds = lappend(newcmds, newcmd);\n\t}\n\n\t/* Close rel but keep lock */\n\trelation_close(rel, NoLock);\n\n\t/*\n\t * Output results.\n\t */\n\tstmt->cmds = newcmds;\n\n\tresult = lappend(cxt.blist, stmt);\n\tresult = list_concat(result, cxt.alist);\n\tresult = list_concat(result, save_alist);\n\n\treturn result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'Avoid repeated name lookups during table and index DDL.\n\nIf the name lookups come to different conclusions due to concurrent\nactivity, we might perform some parts of the DDL on a different table\nthan other parts. At least in the case of CREATE INDEX, this can be\nused to cause the permissions checks to be performed against a\ndifferent table than the index creation, allowing for a privilege\nescalation attack.\n\nThis changes the calling convention for DefineIndex, CreateTrigger,\ntransformIndexStmt, transformAlterTableStmt, CheckIndexCompatible\n(in 9.2 and newer), and AlterTable (in 9.1 and older). In addition,\nCheckRelationOwnership is removed in 9.2 and newer and the calling\nconvention is changed in older branches. A field has also been added\nto the Constraint node (FkConstraint in 8.4). Third-party code calling\nthese functions or using the Constraint node will require updating.\n\nReport by Andres Freund. Patch by Robert Haas and Andres Freund,\nreviewed by Tom Lane.\n\nSecurity: CVE-2014-0062'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: _copyConstraint(const Constraint *from)\n{\n\tConstraint *newnode = makeNode(Constraint);\n\n\tCOPY_SCALAR_FIELD(contype);\n\tCOPY_STRING_FIELD(conname);\n\tCOPY_SCALAR_FIELD(deferrable);\n\tCOPY_SCALAR_FIELD(initdeferred);\n\tCOPY_LOCATION_FIELD(location);\n\tCOPY_SCALAR_FIELD(is_no_inherit);\n\tCOPY_NODE_FIELD(raw_expr);\n\tCOPY_STRING_FIELD(cooked_expr);\n\tCOPY_NODE_FIELD(keys);\n\tCOPY_NODE_FIELD(exclusions);\n\tCOPY_NODE_FIELD(options);\n\tCOPY_STRING_FIELD(indexname);\n\tCOPY_STRING_FIELD(indexspace);\n\tCOPY_STRING_FIELD(access_method);\n\tCOPY_NODE_FIELD(where_clause);\n\tCOPY_NODE_FIELD(pktable);\n\tCOPY_NODE_FIELD(fk_attrs);\n\tCOPY_NODE_FIELD(pk_attrs);\n\tCOPY_SCALAR_FIELD(fk_matchtype);\n\tCOPY_SCALAR_FIELD(fk_upd_action);\n\tCOPY_SCALAR_FIELD(fk_del_action);\n\tCOPY_NODE_FIELD(old_conpfeqop);\n\tCOPY_SCALAR_FIELD(skip_validation);\n\tCOPY_SCALAR_FIELD(initially_valid);\n\n\treturn newnode;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'Avoid repeated name lookups during table and index DDL.\n\nIf the name lookups come to different conclusions due to concurrent\nactivity, we might perform some parts of the DDL on a different table\nthan other parts. At least in the case of CREATE INDEX, this can be\nused to cause the permissions checks to be performed against a\ndifferent table than the index creation, allowing for a privilege\nescalation attack.\n\nThis changes the calling convention for DefineIndex, CreateTrigger,\ntransformIndexStmt, transformAlterTableStmt, CheckIndexCompatible\n(in 9.2 and newer), and AlterTable (in 9.1 and older). In addition,\nCheckRelationOwnership is removed in 9.2 and newer and the calling\nconvention is changed in older branches. A field has also been added\nto the Constraint node (FkConstraint in 8.4). Third-party code calling\nthese functions or using the Constraint node will require updating.\n\nReport by Andres Freund. Patch by Robert Haas and Andres Freund,\nreviewed by Tom Lane.\n\nSecurity: CVE-2014-0062'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: makepol(QPRS_STATE *state)\n{\n\tint32\t\tval = 0,\n\t\t\t\ttype;\n\tint32\t\tlenval = 0;\n\tchar\t *strval = NULL;\n\tint32\t\tstack[STACKDEPTH];\n\tint32\t\tlenstack = 0;\n\tuint16\t\tflag = 0;\n\n\twhile ((type = gettoken_query(state, &val, &lenval, &strval, &flag)) != END)\n\t{\n\t\tswitch (type)\n\t\t{\n\t\t\tcase VAL:\n\t\t\t\tpushval_asis(state, VAL, strval, lenval, flag);\n\t\t\t\twhile (lenstack && (stack[lenstack - 1] == (int32) '&' ||\n\t\t\t\t\t\t\t\t\tstack[lenstack - 1] == (int32) '!'))\n\t\t\t\t{\n\t\t\t\t\tlenstack--;\n\t\t\t\t\tpushquery(state, OPR, stack[lenstack], 0, 0, 0);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase OPR:\n\t\t\t\tif (lenstack && val == (int32) '|')\n\t\t\t\t\tpushquery(state, OPR, val, 0, 0, 0);\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (lenstack == STACKDEPTH)\n\t\t\t\t\t\t/* internal error */\n\t\t\t\t\t\telog(ERROR, \"stack too short\");\n\t\t\t\t\tstack[lenstack] = val;\n\t\t\t\t\tlenstack++;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase OPEN:\n\t\t\t\tif (makepol(state) == ERR)\n\t\t\t\t\treturn ERR;\n\t\t\t\twhile (lenstack && (stack[lenstack - 1] == (int32) '&' ||\n\t\t\t\t\t\t\t\t\tstack[lenstack - 1] == (int32) '!'))\n\t\t\t\t{\n\t\t\t\t\tlenstack--;\n\t\t\t\t\tpushquery(state, OPR, stack[lenstack], 0, 0, 0);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase CLOSE:\n\t\t\t\twhile (lenstack)\n\t\t\t\t{\n\t\t\t\t\tlenstack--;\n\t\t\t\t\tpushquery(state, OPR, stack[lenstack], 0, 0, 0);\n\t\t\t\t};\n\t\t\t\treturn END;\n\t\t\t\tbreak;\n\t\t\tcase ERR:\n\t\t\tdefault:\n\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t(errcode(ERRCODE_SYNTAX_ERROR),\n\t\t\t\t\t\t errmsg(\"syntax error\")));\n\n\t\t\t\treturn ERR;\n\n\t\t}\n\t}\n\twhile (lenstack)\n\t{\n\t\tlenstack--;\n\t\tpushquery(state, OPR, stack[lenstack], 0, 0, 0);\n\t};\n\treturn END;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Predict integer overflow to avoid buffer overruns.\n\nSeveral functions, mostly type input functions, calculated an allocation\nsize such that the calculation wrapped to a small positive value when\narguments implied a sufficiently-large requirement. Writes past the end\nof the inadvertent small allocation followed shortly thereafter.\nCoverity identified the path_in() vulnerability; code inspection led to\nthe rest. In passing, add check_stack_depth() to prevent stack overflow\nin related functions.\n\nBack-patch to 8.4 (all supported versions). The non-comment hstore\nchanges touch code that did not exist in 8.4, so that part stops at 9.0.\n\nNoah Misch and Heikki Linnakangas, reviewed by Tom Lane.\n\nSecurity: CVE-2014-0064'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: varbit_in(PG_FUNCTION_ARGS)\n{\n\tchar\t *input_string = PG_GETARG_CSTRING(0);\n\n#ifdef NOT_USED\n\tOid\t\t\ttypelem = PG_GETARG_OID(1);\n#endif\n\tint32\t\tatttypmod = PG_GETARG_INT32(2);\n\tVarBit\t *result;\t\t\t/* The resulting bit string\t\t\t */\n\tchar\t *sp;\t\t\t\t/* pointer into the character string */\n\tbits8\t *r;\t\t\t\t/* pointer into the result */\n\tint\t\t\tlen,\t\t\t/* Length of the whole data structure */\n\t\t\t\tbitlen,\t\t\t/* Number of bits in the bit string */\n\t\t\t\tslen;\t\t\t/* Length of the input string\t\t */\n\tbool\t\tbit_not_hex;\t/* false = hex string true = bit string */\n\tint\t\t\tbc;\n\tbits8\t\tx = 0;\n\n\t/* Check that the first character is a b or an x */\n\tif (input_string[0] == 'b' || input_string[0] == 'B')\n\t{\n\t\tbit_not_hex = true;\n\t\tsp = input_string + 1;\n\t}\n\telse if (input_string[0] == 'x' || input_string[0] == 'X')\n\t{\n\t\tbit_not_hex = false;\n\t\tsp = input_string + 1;\n\t}\n\telse\n\t{\n\t\tbit_not_hex = true;\n\t\tsp = input_string;\n\t}\n\n\tslen = strlen(sp);\n\t/* Determine bitlength from input string */\n\tif (bit_not_hex)\n\t\tbitlen = slen;\n\telse\n\t\tbitlen = slen * 4;\n\n\t/*\n\t * Sometimes atttypmod is not supplied. If it is supplied we need to make\n\t * sure that the bitstring fits.\n\t */\n\tif (atttypmod <= 0)\n\t\tatttypmod = bitlen;\n\telse if (bitlen > atttypmod)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_STRING_DATA_RIGHT_TRUNCATION),\n\t\t\t\t errmsg(\"bit string too long for type bit varying(%d)\",\n\t\t\t\t\t\tatttypmod)));\n\n\tlen = VARBITTOTALLEN(bitlen);\n\t/* set to 0 so that *r is always initialised and string is zero-padded */\n\tresult = (VarBit *) palloc0(len);\n\tSET_VARSIZE(result, len);\n\tVARBITLEN(result) = Min(bitlen, atttypmod);\n\n\tr = VARBITS(result);\n\tif (bit_not_hex)\n\t{\n\t\t/* Parse the bit representation of the string */\n\t\t/* We know it fits, as bitlen was compared to atttypmod */\n\t\tx = HIGHBIT;\n\t\tfor (; *sp; sp++)\n\t\t{\n\t\t\tif (*sp == '1')\n\t\t\t\t*r |= x;\n\t\t\telse if (*sp != '0')\n\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),\n\t\t\t\t\t\t errmsg(\"\\\"%c\\\" is not a valid binary digit\",\n\t\t\t\t\t\t\t\t*sp)));\n\n\t\t\tx >>= 1;\n\t\t\tif (x == 0)\n\t\t\t{\n\t\t\t\tx = HIGHBIT;\n\t\t\t\tr++;\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\t/* Parse the hex representation of the string */\n\t\tfor (bc = 0; *sp; sp++)\n\t\t{\n\t\t\tif (*sp >= '0' && *sp <= '9')\n\t\t\t\tx = (bits8) (*sp - '0');\n\t\t\telse if (*sp >= 'A' && *sp <= 'F')\n\t\t\t\tx = (bits8) (*sp - 'A') + 10;\n\t\t\telse if (*sp >= 'a' && *sp <= 'f')\n\t\t\t\tx = (bits8) (*sp - 'a') + 10;\n\t\t\telse\n\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),\n\t\t\t\t\t\t errmsg(\"\\\"%c\\\" is not a valid hexadecimal digit\",\n\t\t\t\t\t\t\t\t*sp)));\n\n\t\t\tif (bc)\n\t\t\t{\n\t\t\t\t*r++ |= x;\n\t\t\t\tbc = 0;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t*r = x << 4;\n\t\t\t\tbc = 1;\n\t\t\t}\n\t\t}\n\t}\n\n\tPG_RETURN_VARBIT_P(result);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Predict integer overflow to avoid buffer overruns.\n\nSeveral functions, mostly type input functions, calculated an allocation\nsize such that the calculation wrapped to a small positive value when\narguments implied a sufficiently-large requirement. Writes past the end\nof the inadvertent small allocation followed shortly thereafter.\nCoverity identified the path_in() vulnerability; code inspection led to\nthe rest. In passing, add check_stack_depth() to prevent stack overflow\nin related functions.\n\nBack-patch to 8.4 (all supported versions). The non-comment hstore\nchanges touch code that did not exist in 8.4, so that part stops at 9.0.\n\nNoah Misch and Heikki Linnakangas, reviewed by Tom Lane.\n\nSecurity: CVE-2014-0064'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: parse_tsquery(char *buf,\n\t\t\t PushFunction pushval,\n\t\t\t Datum opaque,\n\t\t\t bool isplain)\n{\n\tstruct TSQueryParserStateData state;\n\tint\t\t\ti;\n\tTSQuery\t\tquery;\n\tint\t\t\tcommonlen;\n\tQueryItem *ptr;\n\tListCell *cell;\n\n\t/* init state */\n\tstate.buffer = buf;\n\tstate.buf = buf;\n\tstate.state = (isplain) ? WAITSINGLEOPERAND : WAITFIRSTOPERAND;\n\tstate.count = 0;\n\tstate.polstr = NIL;\n\n\t/* init value parser's state */\n\tstate.valstate = init_tsvector_parser(state.buffer, true, true);\n\n\t/* init list of operand */\n\tstate.sumlen = 0;\n\tstate.lenop = 64;\n\tstate.curop = state.op = (char *) palloc(state.lenop);\n\t*(state.curop) = '\\0';\n\n\t/* parse query & make polish notation (postfix, but in reverse order) */\n\tmakepol(&state, pushval, opaque);\n\n\tclose_tsvector_parser(state.valstate);\n\n\tif (list_length(state.polstr) == 0)\n\t{\n\t\tereport(NOTICE,\n\t\t\t\t(errmsg(\"text-search query doesn't contain lexemes: \\\"%s\\\"\",\n\t\t\t\t\t\tstate.buffer)));\n\t\tquery = (TSQuery) palloc(HDRSIZETQ);\n\t\tSET_VARSIZE(query, HDRSIZETQ);\n\t\tquery->size = 0;\n\t\treturn query;\n\t}\n\n\t/* Pack the QueryItems in the final TSQuery struct to return to caller */\n\tcommonlen = COMPUTESIZE(list_length(state.polstr), state.sumlen);\n\tquery = (TSQuery) palloc0(commonlen);\n\tSET_VARSIZE(query, commonlen);\n\tquery->size = list_length(state.polstr);\n\tptr = GETQUERY(query);\n\n\t/* Copy QueryItems to TSQuery */\n\ti = 0;\n\tforeach(cell, state.polstr)\n\t{\n\t\tQueryItem *item = (QueryItem *) lfirst(cell);\n\n\t\tswitch (item->type)\n\t\t{\n\t\t\tcase QI_VAL:\n\t\t\t\tmemcpy(&ptr[i], item, sizeof(QueryOperand));\n\t\t\t\tbreak;\n\t\t\tcase QI_VALSTOP:\n\t\t\t\tptr[i].type = QI_VALSTOP;\n\t\t\t\tbreak;\n\t\t\tcase QI_OPR:\n\t\t\t\tmemcpy(&ptr[i], item, sizeof(QueryOperator));\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\telog(ERROR, \"unrecognized QueryItem type: %d\", item->type);\n\t\t}\n\t\ti++;\n\t}\n\n\t/* Copy all the operand strings to TSQuery */\n\tmemcpy((void *) GETOPERAND(query), (void *) state.op, state.sumlen);\n\tpfree(state.op);\n\n\t/* Set left operand pointers for every operator. */\n\tfindoprnd(ptr, query->size);\n\n\treturn query;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Predict integer overflow to avoid buffer overruns.\n\nSeveral functions, mostly type input functions, calculated an allocation\nsize such that the calculation wrapped to a small positive value when\narguments implied a sufficiently-large requirement. Writes past the end\nof the inadvertent small allocation followed shortly thereafter.\nCoverity identified the path_in() vulnerability; code inspection led to\nthe rest. In passing, add check_stack_depth() to prevent stack overflow\nin related functions.\n\nBack-patch to 8.4 (all supported versions). The non-comment hstore\nchanges touch code that did not exist in 8.4, so that part stops at 9.0.\n\nNoah Misch and Heikki Linnakangas, reviewed by Tom Lane.\n\nSecurity: CVE-2014-0064'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: validate_exec(const char *path)\n{\n\tstruct stat buf;\n\tint\t\t\tis_r;\n\tint\t\t\tis_x;\n\n#ifdef WIN32\n\tchar\t\tpath_exe[MAXPGPATH + sizeof(\".exe\") - 1];\n\n\t/* Win32 requires a .exe suffix for stat() */\n\tif (strlen(path) >= strlen(\".exe\") &&\n\t\tpg_strcasecmp(path + strlen(path) - strlen(\".exe\"), \".exe\") != 0)\n\t{\n\t\tstrcpy(path_exe, path);\n\t\tstrcat(path_exe, \".exe\");\n\t\tpath = path_exe;\n\t}\n#endif\n\n\t/*\n\t * Ensure that the file exists and is a regular file.\n\t *\n\t * XXX if you have a broken system where stat() looks at the symlink\n\t * instead of the underlying file, you lose.\n\t */\n\tif (stat(path, &buf) < 0)\n\t\treturn -1;\n\n\tif (!S_ISREG(buf.st_mode))\n\t\treturn -1;\n\n\t/*\n\t * Ensure that the file is both executable and readable (required for\n\t * dynamic loading).\n\t */\n#ifndef WIN32\n\tis_r = (access(path, R_OK) == 0);\n\tis_x = (access(path, X_OK) == 0);\n#else\n\tis_r = buf.st_mode & S_IRUSR;\n\tis_x = buf.st_mode & S_IXUSR;\n#endif\n\treturn is_x ? (is_r ? 0 : -2) : -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Prevent potential overruns of fixed-size buffers.\n\nCoverity identified a number of places in which it couldn't prove that a\nstring being copied into a fixed-size buffer would fit. We believe that\nmost, perhaps all of these are in fact safe, or are copying data that is\ncoming from a trusted source so that any overrun is not really a security\nissue. Nonetheless it seems prudent to forestall any risk by using\nstrlcpy() and similar functions.\n\nFixes by Peter Eisentraut and Jozef Mlich based on Coverity reports.\n\nIn addition, fix a potential null-pointer-dereference crash in\ncontrib/chkpass. The crypt(3) function is defined to return NULL on\nfailure, but chkpass.c didn't check for that before using the result.\nThe main practical case in which this could be an issue is if libc is\nconfigured to refuse to execute unapproved hashing algorithms (e.g.,\n\"FIPS mode\"). This ideally should've been a separate commit, but\nsince it touches code adjacent to one of the buffer overrun changes,\nI included it in this commit to avoid last-minute merge issues.\nThis issue was reported by Honza Horak.\n\nSecurity: CVE-2014-0065 for buffer overruns, CVE-2014-0066 for crypt()'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: resolve_symlinks(char *path)\n{\n#ifdef HAVE_READLINK\n\tstruct stat buf;\n\tchar\t\torig_wd[MAXPGPATH],\n\t\t\t\tlink_buf[MAXPGPATH];\n\tchar\t *fname;\n\n\t/*\n\t * To resolve a symlink properly, we have to chdir into its directory and\n\t * then chdir to where the symlink points; otherwise we may fail to\n\t * resolve relative links correctly (consider cases involving mount\n\t * points, for example). After following the final symlink, we use\n\t * getcwd() to figure out where the heck we're at.\n\t *\n\t * One might think we could skip all this if path doesn't point to a\n\t * symlink to start with, but that's wrong. We also want to get rid of\n\t * any directory symlinks that are present in the given path. We expect\n\t * getcwd() to give us an accurate, symlink-free path.\n\t */\n\tif (!getcwd(orig_wd, MAXPGPATH))\n\t{\n\t\tlog_error(_(\"could not identify current directory: %s\"),\n\t\t\t\t strerror(errno));\n\t\treturn -1;\n\t}\n\n\tfor (;;)\n\t{\n\t\tchar\t *lsep;\n\t\tint\t\t\trllen;\n\n\t\tlsep = last_dir_separator(path);\n\t\tif (lsep)\n\t\t{\n\t\t\t*lsep = '\\0';\n\t\t\tif (chdir(path) == -1)\n\t\t\t{\n\t\t\t\tlog_error4(_(\"could not change directory to \\\"%s\\\": %s\"), path, strerror(errno));\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tfname = lsep + 1;\n\t\t}\n\t\telse\n\t\t\tfname = path;\n\n\t\tif (lstat(fname, &buf) < 0 ||\n\t\t\t!S_ISLNK(buf.st_mode))\n\t\t\tbreak;\n\n\t\trllen = readlink(fname, link_buf, sizeof(link_buf));\n\t\tif (rllen < 0 || rllen >= sizeof(link_buf))\n\t\t{\n\t\t\tlog_error(_(\"could not read symbolic link \\\"%s\\\"\"), fname);\n\t\t\treturn -1;\n\t\t}\n\t\tlink_buf[rllen] = '\\0';\n\t\tstrcpy(path, link_buf);\n\t}\n\n\t/* must copy final component out of 'path' temporarily */\n\tstrcpy(link_buf, fname);\n\n\tif (!getcwd(path, MAXPGPATH))\n\t{\n\t\tlog_error(_(\"could not identify current directory: %s\"),\n\t\t\t\t strerror(errno));\n\t\treturn -1;\n\t}\n\tjoin_path_components(path, path, link_buf);\n\tcanonicalize_path(path);\n\n\tif (chdir(orig_wd) == -1)\n\t{\n\t\tlog_error4(_(\"could not change directory to \\\"%s\\\": %s\"), orig_wd, strerror(errno));\n\t\treturn -1;\n\t}\n#endif /* HAVE_READLINK */\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Prevent potential overruns of fixed-size buffers.\n\nCoverity identified a number of places in which it couldn't prove that a\nstring being copied into a fixed-size buffer would fit. We believe that\nmost, perhaps all of these are in fact safe, or are copying data that is\ncoming from a trusted source so that any overrun is not really a security\nissue. Nonetheless it seems prudent to forestall any risk by using\nstrlcpy() and similar functions.\n\nFixes by Peter Eisentraut and Jozef Mlich based on Coverity reports.\n\nIn addition, fix a potential null-pointer-dereference crash in\ncontrib/chkpass. The crypt(3) function is defined to return NULL on\nfailure, but chkpass.c didn't check for that before using the result.\nThe main practical case in which this could be an issue is if libc is\nconfigured to refuse to execute unapproved hashing algorithms (e.g.,\n\"FIPS mode\"). This ideally should've been a separate commit, but\nsince it touches code adjacent to one of the buffer overrun changes,\nI included it in this commit to avoid last-minute merge issues.\nThis issue was reported by Honza Horak.\n\nSecurity: CVE-2014-0065 for buffer overruns, CVE-2014-0066 for crypt()'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int usb_device_post_load(void *opaque, int version_id)\n{\n USBDevice *dev = opaque;\n\n if (dev->state == USB_STATE_NOTATTACHED) {\n dev->attached = 0;\n } else {\n dev->attached = 1;\n }\n if (dev->setup_index >= sizeof(dev->data_buf) ||\n dev->setup_len >= sizeof(dev->data_buf)) {\n return -EINVAL;\n }\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'usb: sanity check setup_index+setup_len in post_load\n\nCVE-2013-4541\n\ns->setup_len and s->setup_index are fed into usb_packet_copy as\nsize/offset into s->data_buf, it's possible for invalid state to exploit\nthis to load arbitrary data.\n\nsetup_len and setup_index should be checked to make sure\nthey are not negative.\n\nCc: Gerd Hoffmann \nSigned-off-by: Michael S. Tsirkin \nReviewed-by: Gerd Hoffmann \nSigned-off-by: Juan Quintela '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: _gnutls_x509_verify_certificate (const gnutls_x509_crt_t * certificate_list,\n\t\t\t\t int clist_size,\n\t\t\t\t const gnutls_x509_crt_t * trusted_cas,\n\t\t\t\t int tcas_size,\n\t\t\t\t const gnutls_x509_crl_t * CRLs,\n\t\t\t\t int crls_size, unsigned int flags)\n{\n int i = 0, ret;\n unsigned int status = 0, output;\n\n if (clist_size > 1)\n {\n /* Check if the last certificate in the path is self signed.\n * In that case ignore it (a certificate is trusted only if it\n * leads to a trusted party by us, not the server's).\n *\n * This prevents from verifying self signed certificates against\n * themselves. This (although not bad) caused verification\n * failures on some root self signed certificates that use the\n * MD2 algorithm.\n */\n if (gnutls_x509_crt_check_issuer (certificate_list[clist_size - 1],\n\t\t\t\t certificate_list[clist_size - 1]) > 0)\n\t{\n\t clist_size--;\n\t}\n }\n\n /* We want to shorten the chain by removing the cert that matches\n * one of the certs we trust and all the certs after that i.e. if\n * cert chain is A signed-by B signed-by C signed-by D (signed-by\n * self-signed E but already removed above), and we trust B, remove\n * B, C and D. We must leave the first cert on chain. */\n if (clist_size > 1 && !(flags & GNUTLS_VERIFY_DO_NOT_ALLOW_SAME))\n {\n for (i = 1; i < clist_size; i++)\n\t{\n\t int j;\n\n\t for (j = 0; j < tcas_size; j++)\n\t {\n\t if (check_if_same_cert (certificate_list[i],\n\t\t\t\t trusted_cas[j]) == 0)\n\t\t{\n\t\t clist_size = i;\n\t\t break;\n\t\t}\n\t }\n\t /* clist_size may have been changed which gets out of loop */\n\t}\n }\n\n /* Verify the last certificate in the certificate path\n * against the trusted CA certificate list.\n *\n * If no CAs are present returns CERT_INVALID. Thus works\n * in self signed etc certificates.\n */\n ret = _gnutls_verify_certificate2 (certificate_list[clist_size - 1],\n\t\t\t\t trusted_cas, tcas_size, flags, &output);\n if (ret == 0)\n {\n /* if the last certificate in the certificate\n * list is invalid, then the certificate is not\n * trusted.\n */\n gnutls_assert ();\n status |= output;\n status |= GNUTLS_CERT_INVALID;\n return status;\n }\n\n /* Check for revoked certificates in the chain\n */\n#ifdef ENABLE_PKI\n for (i = 0; i < clist_size; i++)\n {\n ret = gnutls_x509_crt_check_revocation (certificate_list[i],\n\t\t\t\t\t CRLs, crls_size);\n if (ret == 1)\n\t{\t\t\t/* revoked */\n\t status |= GNUTLS_CERT_REVOKED;\n\t status |= GNUTLS_CERT_INVALID;\n\t return status;\n\t}\n }\n#endif\n\n /* Verify the certificate path (chain)\n */\n for (i = clist_size - 1; i > 0; i--)\n {\n if (i - 1 < 0)\n\tbreak;\n\n /* note that here we disable this V1 CA flag. So that no version 1\n * certificates can exist in a supplied chain.\n */\n if (!(flags & GNUTLS_VERIFY_ALLOW_ANY_X509_V1_CA_CRT))\n\tflags ^= GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT;\n if ((ret =\n\t _gnutls_verify_certificate2 (certificate_list[i - 1],\n\t\t\t\t\t&certificate_list[i], 1, flags,\n\t\t\t\t\tNULL)) == 0)\n\t{\n\t status |= GNUTLS_CERT_INVALID;\n\t return status;\n\t}\n }\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'Corrected bit disable (was flipping instead).\nInitialy reported by Daniel Kahn Gillmor on 9/1/2008. Many thanks to\nmoog@sysdev.oucs.ox.ac.uk for bringing this into my attention.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: \nprivate int\nmget(struct magic_set *ms, const unsigned char *s, struct magic *m,\n size_t nbytes, size_t o, unsigned int cont_level, int mode, int text,\n int flip, int recursion_level, int *printed_something,\n int *need_separator, int *returnval)\n{\n\tuint32_t soffset, offset = ms->offset;\n\tuint32_t count = m->str_range;\n\tint rv, oneed_separator;\n\tchar *sbuf, *rbuf;\n\tunion VALUETYPE *p = &ms->ms_value;\n\tstruct mlist ml;\n\n\tif (recursion_level >= 20) {\n\t\tfile_error(ms, 0, \"recursion nesting exceeded\");\n\t\treturn -1;\n\t}\n\n\tif (mcopy(ms, p, m->type, m->flag & INDIR, s, (uint32_t)(offset + o),\n\t (uint32_t)nbytes, count) == -1)\n\t\treturn -1;\n\n\tif ((ms->flags & MAGIC_DEBUG) != 0) {\n\t\tfprintf(stderr, \"mget(type=%d, flag=%x, offset=%u, o=%zu, \"\n\t\t \"nbytes=%zu, count=%u)\\n\", m->type, m->flag, offset, o,\n\t\t nbytes, count);\n\t\tmdebug(offset, (char *)(void *)p, sizeof(union VALUETYPE));\n\t}\n\n\tif (m->flag & INDIR) {\n\t\tint off = m->in_offset;\n\t\tif (m->in_op & FILE_OPINDIRECT) {\n\t\t\tconst union VALUETYPE *q = CAST(const union VALUETYPE *,\n\t\t\t ((const void *)(s + offset + off)));\n\t\t\tswitch (cvt_flip(m->in_type, flip)) {\n\t\t\tcase FILE_BYTE:\n\t\t\t\toff = q->b;\n\t\t\t\tbreak;\n\t\t\tcase FILE_SHORT:\n\t\t\t\toff = q->h;\n\t\t\t\tbreak;\n\t\t\tcase FILE_BESHORT:\n\t\t\t\toff = (short)((q->hs[0]<<8)|(q->hs[1]));\n\t\t\t\tbreak;\n\t\t\tcase FILE_LESHORT:\n\t\t\t\toff = (short)((q->hs[1]<<8)|(q->hs[0]));\n\t\t\t\tbreak;\n\t\t\tcase FILE_LONG:\n\t\t\t\toff = q->l;\n\t\t\t\tbreak;\n\t\t\tcase FILE_BELONG:\n\t\t\tcase FILE_BEID3:\n\t\t\t\toff = (int32_t)((q->hl[0]<<24)|(q->hl[1]<<16)|\n\t\t\t\t\t\t (q->hl[2]<<8)|(q->hl[3]));\n\t\t\t\tbreak;\n\t\t\tcase FILE_LEID3:\n\t\t\tcase FILE_LELONG:\n\t\t\t\toff = (int32_t)((q->hl[3]<<24)|(q->hl[2]<<16)|\n\t\t\t\t\t\t (q->hl[1]<<8)|(q->hl[0]));\n\t\t\t\tbreak;\n\t\t\tcase FILE_MELONG:\n\t\t\t\toff = (int32_t)((q->hl[1]<<24)|(q->hl[0]<<16)|\n\t\t\t\t\t\t (q->hl[3]<<8)|(q->hl[2]));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif ((ms->flags & MAGIC_DEBUG) != 0)\n\t\t\t\tfprintf(stderr, \"indirect offs=%u\\n\", off);\n\t\t}\n\t\tswitch (cvt_flip(m->in_type, flip)) {\n\t\tcase FILE_BYTE:\n\t\t\tif (nbytes < (offset + 1))\n\t\t\t\treturn 0;\n\t\t\tif (off) {\n\t\t\t\tswitch (m->in_op & FILE_OPS_MASK) {\n\t\t\t\tcase FILE_OPAND:\n\t\t\t\t\toffset = p->b & off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPOR:\n\t\t\t\t\toffset = p->b | off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPXOR:\n\t\t\t\t\toffset = p->b ^ off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPADD:\n\t\t\t\t\toffset = p->b + off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMINUS:\n\t\t\t\t\toffset = p->b - off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMULTIPLY:\n\t\t\t\t\toffset = p->b * off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPDIVIDE:\n\t\t\t\t\toffset = p->b / off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMODULO:\n\t\t\t\t\toffset = p->b % off;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\toffset = p->b;\n\t\t\tif (m->in_op & FILE_OPINVERSE)\n\t\t\t\toffset = ~offset;\n\t\t\tbreak;\n\t\tcase FILE_BESHORT:\n\t\t\tif (nbytes < (offset + 2))\n\t\t\t\treturn 0;\n\t\t\tif (off) {\n\t\t\t\tswitch (m->in_op & FILE_OPS_MASK) {\n\t\t\t\tcase FILE_OPAND:\n\t\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t\t (p->hs[1])) &\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPOR:\n\t\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t\t (p->hs[1])) |\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPXOR:\n\t\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t\t (p->hs[1])) ^\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPADD:\n\t\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t\t (p->hs[1])) +\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMINUS:\n\t\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t\t (p->hs[1])) -\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMULTIPLY:\n\t\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t\t (p->hs[1])) *\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPDIVIDE:\n\t\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t\t (p->hs[1])) /\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMODULO:\n\t\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t\t (p->hs[1])) %\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\toffset = (short)((p->hs[0]<<8)|\n\t\t\t\t\t\t (p->hs[1]));\n\t\t\tif (m->in_op & FILE_OPINVERSE)\n\t\t\t\toffset = ~offset;\n\t\t\tbreak;\n\t\tcase FILE_LESHORT:\n\t\t\tif (nbytes < (offset + 2))\n\t\t\t\treturn 0;\n\t\t\tif (off) {\n\t\t\t\tswitch (m->in_op & FILE_OPS_MASK) {\n\t\t\t\tcase FILE_OPAND:\n\t\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t\t (p->hs[0])) &\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPOR:\n\t\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t\t (p->hs[0])) |\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPXOR:\n\t\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t\t (p->hs[0])) ^\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPADD:\n\t\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t\t (p->hs[0])) +\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMINUS:\n\t\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t\t (p->hs[0])) -\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMULTIPLY:\n\t\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t\t (p->hs[0])) *\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPDIVIDE:\n\t\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t\t (p->hs[0])) /\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMODULO:\n\t\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t\t (p->hs[0])) %\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\toffset = (short)((p->hs[1]<<8)|\n\t\t\t\t\t\t (p->hs[0]));\n\t\t\tif (m->in_op & FILE_OPINVERSE)\n\t\t\t\toffset = ~offset;\n\t\t\tbreak;\n\t\tcase FILE_SHORT:\n\t\t\tif (nbytes < (offset + 2))\n\t\t\t\treturn 0;\n\t\t\tif (off) {\n\t\t\t\tswitch (m->in_op & FILE_OPS_MASK) {\n\t\t\t\tcase FILE_OPAND:\n\t\t\t\t\toffset = p->h & off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPOR:\n\t\t\t\t\toffset = p->h | off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPXOR:\n\t\t\t\t\toffset = p->h ^ off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPADD:\n\t\t\t\t\toffset = p->h + off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMINUS:\n\t\t\t\t\toffset = p->h - off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMULTIPLY:\n\t\t\t\t\toffset = p->h * off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPDIVIDE:\n\t\t\t\t\toffset = p->h / off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMODULO:\n\t\t\t\t\toffset = p->h % off;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t\toffset = p->h;\n\t\t\tif (m->in_op & FILE_OPINVERSE)\n\t\t\t\toffset = ~offset;\n\t\t\tbreak;\n\t\tcase FILE_BELONG:\n\t\tcase FILE_BEID3:\n\t\t\tif (nbytes < (offset + 4))\n\t\t\t\treturn 0;\n\t\t\tif (off) {\n\t\t\t\tswitch (m->in_op & FILE_OPS_MASK) {\n\t\t\t\tcase FILE_OPAND:\n\t\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t\t (p->hl[3])) &\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPOR:\n\t\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t\t (p->hl[3])) |\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPXOR:\n\t\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t\t (p->hl[3])) ^\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPADD:\n\t\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t\t (p->hl[3])) +\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMINUS:\n\t\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t\t (p->hl[3])) -\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMULTIPLY:\n\t\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t\t (p->hl[3])) *\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPDIVIDE:\n\t\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t\t (p->hl[3])) /\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMODULO:\n\t\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t\t (p->hl[3])) %\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\toffset = (int32_t)((p->hl[0]<<24)|\n\t\t\t\t\t\t (p->hl[1]<<16)|\n\t\t\t\t\t\t (p->hl[2]<<8)|\n\t\t\t\t\t\t (p->hl[3]));\n\t\t\tif (m->in_op & FILE_OPINVERSE)\n\t\t\t\toffset = ~offset;\n\t\t\tbreak;\n\t\tcase FILE_LELONG:\n\t\tcase FILE_LEID3:\n\t\t\tif (nbytes < (offset + 4))\n\t\t\t\treturn 0;\n\t\t\tif (off) {\n\t\t\t\tswitch (m->in_op & FILE_OPS_MASK) {\n\t\t\t\tcase FILE_OPAND:\n\t\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t\t (p->hl[0])) &\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPOR:\n\t\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t\t (p->hl[0])) |\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPXOR:\n\t\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t\t (p->hl[0])) ^\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPADD:\n\t\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t\t (p->hl[0])) +\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMINUS:\n\t\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t\t (p->hl[0])) -\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMULTIPLY:\n\t\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t\t (p->hl[0])) *\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPDIVIDE:\n\t\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t\t (p->hl[0])) /\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMODULO:\n\t\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t\t (p->hl[0])) %\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\toffset = (int32_t)((p->hl[3]<<24)|\n\t\t\t\t\t\t (p->hl[2]<<16)|\n\t\t\t\t\t\t (p->hl[1]<<8)|\n\t\t\t\t\t\t (p->hl[0]));\n\t\t\tif (m->in_op & FILE_OPINVERSE)\n\t\t\t\toffset = ~offset;\n\t\t\tbreak;\n\t\tcase FILE_MELONG:\n\t\t\tif (nbytes < (offset + 4))\n\t\t\t\treturn 0;\n\t\t\tif (off) {\n\t\t\t\tswitch (m->in_op & FILE_OPS_MASK) {\n\t\t\t\tcase FILE_OPAND:\n\t\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t\t (p->hl[2])) &\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPOR:\n\t\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t\t (p->hl[2])) |\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPXOR:\n\t\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t\t (p->hl[2])) ^\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPADD:\n\t\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t\t (p->hl[2])) +\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMINUS:\n\t\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t\t (p->hl[2])) -\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMULTIPLY:\n\t\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t\t (p->hl[2])) *\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPDIVIDE:\n\t\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t\t (p->hl[2])) /\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMODULO:\n\t\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t\t (p->hl[2])) %\n\t\t\t\t\t\t off;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\toffset = (int32_t)((p->hl[1]<<24)|\n\t\t\t\t\t\t (p->hl[0]<<16)|\n\t\t\t\t\t\t (p->hl[3]<<8)|\n\t\t\t\t\t\t (p->hl[2]));\n\t\t\tif (m->in_op & FILE_OPINVERSE)\n\t\t\t\toffset = ~offset;\n\t\t\tbreak;\n\t\tcase FILE_LONG:\n\t\t\tif (nbytes < (offset + 4))\n\t\t\t\treturn 0;\n\t\t\tif (off) {\n\t\t\t\tswitch (m->in_op & FILE_OPS_MASK) {\n\t\t\t\tcase FILE_OPAND:\n\t\t\t\t\toffset = p->l & off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPOR:\n\t\t\t\t\toffset = p->l | off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPXOR:\n\t\t\t\t\toffset = p->l ^ off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPADD:\n\t\t\t\t\toffset = p->l + off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMINUS:\n\t\t\t\t\toffset = p->l - off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMULTIPLY:\n\t\t\t\t\toffset = p->l * off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPDIVIDE:\n\t\t\t\t\toffset = p->l / off;\n\t\t\t\t\tbreak;\n\t\t\t\tcase FILE_OPMODULO:\n\t\t\t\t\toffset = p->l % off;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\toffset = p->l;\n\t\t\tif (m->in_op & FILE_OPINVERSE)\n\t\t\t\toffset = ~offset;\n\t\t\tbreak;\n\t\t}\n\n\t\tswitch (cvt_flip(m->in_type, flip)) {\n\t\tcase FILE_LEID3:\n\t\tcase FILE_BEID3:\n\t\t\toffset = ((((offset >> 0) & 0x7f) << 0) |\n\t\t\t\t (((offset >> 8) & 0x7f) << 7) |\n\t\t\t\t (((offset >> 16) & 0x7f) << 14) |\n\t\t\t\t (((offset >> 24) & 0x7f) << 21)) + 10;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t\tif (m->flag & INDIROFFADD) {\n\t\t\toffset += ms->c.li[cont_level-1].off;\n\t\t\tif (offset == 0) {\n\t\t\t\tif ((ms->flags & MAGIC_DEBUG) != 0)\n\t\t\t\t\tfprintf(stderr,\n\t\t\t\t\t \"indirect *zero* offset\\n\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif ((ms->flags & MAGIC_DEBUG) != 0)\n\t\t\t\tfprintf(stderr, \"indirect +offs=%u\\n\", offset);\n\t\t}\n\t\tif (mcopy(ms, p, m->type, 0, s, offset, nbytes, count) == -1)\n\t\t\treturn -1;\n\t\tms->offset = offset;\n\n\t\tif ((ms->flags & MAGIC_DEBUG) != 0) {\n\t\t\tmdebug(offset, (char *)(void *)p,\n\t\t\t sizeof(union VALUETYPE));\n\t\t}\n\t}\n\n\t/* Verify we have enough data to match magic type */\n\tswitch (m->type) {\n\tcase FILE_BYTE:\n\t\tif (nbytes < (offset + 1)) /* should always be true */\n\t\t\treturn 0;\n\t\tbreak;\n\n\tcase FILE_SHORT:\n\tcase FILE_BESHORT:\n\tcase FILE_LESHORT:\n\t\tif (nbytes < (offset + 2))\n\t\t\treturn 0;\n\t\tbreak;\n\n\tcase FILE_LONG:\n\tcase FILE_BELONG:\n\tcase FILE_LELONG:\n\tcase FILE_MELONG:\n\tcase FILE_DATE:\n\tcase FILE_BEDATE:\n\tcase FILE_LEDATE:\n\tcase FILE_MEDATE:\n\tcase FILE_LDATE:\n\tcase FILE_BELDATE:\n\tcase FILE_LELDATE:\n\tcase FILE_MELDATE:\n\tcase FILE_FLOAT:\n\tcase FILE_BEFLOAT:\n\tcase FILE_LEFLOAT:\n\t\tif (nbytes < (offset + 4))\n\t\t\treturn 0;\n\t\tbreak;\n\n\tcase FILE_DOUBLE:\n\tcase FILE_BEDOUBLE:\n\tcase FILE_LEDOUBLE:\n\t\tif (nbytes < (offset + 8))\n\t\t\treturn 0;\n\t\tbreak;\n\n\tcase FILE_STRING:\n\tcase FILE_PSTRING:\n\tcase FILE_SEARCH:\n\t\tif (nbytes < (offset + m->vallen))\n\t\t\treturn 0;\n\t\tbreak;\n\n\tcase FILE_REGEX:\n\t\tif (nbytes < offset)\n\t\t\treturn 0;\n\t\tbreak;\n\n\tcase FILE_INDIRECT:\n\t\tif (offset == 0)\n\t\t\treturn 0;\n\t\tif (nbytes < offset)\n\t\t\treturn 0;\n\t\tsbuf = ms->o.buf;\n\t\tsoffset = ms->offset;\n\t\tms->o.buf = NULL;\n\t\tms->offset = 0;\n\t\trv = file_softmagic(ms, s + offset, nbytes - offset,\n\t\t recursion_level, BINTEST, text);\n\t\tif ((ms->flags & MAGIC_DEBUG) != 0)\n\t\t\tfprintf(stderr, \"indirect @offs=%u[%d]\\n\", offset, rv);\n\t\trbuf = ms->o.buf;\n\t\tms->o.buf = sbuf;\n\t\tms->offset = soffset;\n\t\tif (rv == 1) {\n\t\t\tif ((ms->flags & (MAGIC_MIME|MAGIC_APPLE)) == 0 &&\n\t\t\t file_printf(ms, m->desc, offset) == -1) {\n\t\t\t\tif (rbuf) {\n\t\t\t\t\tefree(rbuf);\n\t\t\t\t}\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tif (file_printf(ms, \"%s\", rbuf) == -1) {\n\t\t\t\tif (rbuf) {\n\t\t\t\t\tefree(rbuf);\n\t\t\t\t}\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t\tif (rbuf) {\n\t\t\tefree(rbuf);\n\t\t}\n\t\treturn rv;\n\n\tcase FILE_USE:\n\t\tif (nbytes < offset)\n\t\t\treturn 0;\n\t\tsbuf = m->value.s;\n\t\tif (*sbuf == '^') {\n\t\t\tsbuf++;\n\t\t\tflip = !flip;\n\t\t}\n\t\tif (file_magicfind(ms, sbuf, &ml) == -1) {\n\t\t\tfile_error(ms, 0, \"cannot find entry `%s'\", sbuf);\n\t\t\treturn -1;\n\t\t}\n\n\t\toneed_separator = *need_separator;\n\t\tif (m->flag & NOSPACE)\n\t\t\t*need_separator = 0;\n\t\trv = match(ms, ml.magic, ml.nmagic, s, nbytes, offset + o,\n\t\t mode, text, flip, recursion_level, printed_something,\n\t\t need_separator, returnval);\n\t\tif (rv != 1)\n\t\t *need_separator = oneed_separator;\n\t\treturn rv;\n\n\tcase FILE_NAME:\n\t\tif (file_printf(ms, \"%s\", m->desc) == -1)\n\t\t\treturn -1;\n\t\treturn 1;\n\tcase FILE_DEFAULT:\t/* nothing to check */\n\tdefault:\n\t\tbreak;\n\t}\n\tif (!mconvert(ms, m, flip))\n\t\treturn 0; ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fixed Bug #66820 out-of-bounds memory access in fileinfo\n\nUpstream fix:\nhttps://github.com/glensc/file/commit/447558595a3650db2886cd2f416ad0beba965801\n\nNotice, test changed, with upstream agreement:\n-define OFFSET_OOB(n, o, i)\t((n) < (o) || (i) >= ((n) - (o)))\n+define OFFSET_OOB(n, o, i)\t((n) < (o) || (i) > ((n) - (o)))'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int64_t qcow2_alloc_clusters(BlockDriverState *bs, int64_t size)\n{\n int64_t offset;\n int ret;\n\n BLKDBG_EVENT(bs->file, BLKDBG_CLUSTER_ALLOC);\n offset = alloc_clusters_noref(bs, size);\n if (offset < 0) {\n return offset;\n }\n\n ret = update_refcount(bs, offset, size, 1, QCOW2_DISCARD_NEVER);\n if (ret < 0) {\n return ret;\n }\n\n return offset;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'qcow2: Don't rely on free_cluster_index in alloc_refcount_block() (CVE-2014-0147)\n\nfree_cluster_index is only correct if update_refcount() was called from\nan allocation function, and even there it's brittle because it's used to\nprotect unfinished allocations which still have a refcount of 0 - if it\nmoves in the wrong place, the unfinished allocation can be corrupted.\n\nSo not using it any more seems to be a good idea. Instead, use the\nfirst requested cluster to do the calculations. Return -EAGAIN if\nunfinished allocations could become invalid and let the caller restart\nits search for some free clusters.\n\nThe context of creating a snapsnot is one situation where\nupdate_refcount() is called outside of a cluster allocation. For this\ncase, the change fixes a buffer overflow if a cluster is referenced in\nan L2 table that cannot be represented by an existing refcount block.\n(new_table[refcount_table_index] was out of bounds)\n\n[Bump the qemu-iotests 026 refblock_alloc.write leak count from 10 to\n11.\n--Stefan]\n\nSigned-off-by: Kevin Wolf \nReviewed-by: Max Reitz \nSigned-off-by: Stefan Hajnoczi '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: skb_zerocopy(struct sk_buff *to, const struct sk_buff *from, int len, int hlen)\n{\n\tint i, j = 0;\n\tint plen = 0; /* length of skb->head fragment */\n\tstruct page *page;\n\tunsigned int offset;\n\n\tBUG_ON(!from->head_frag && !hlen);\n\n\t/* dont bother with small payloads */\n\tif (len <= skb_tailroom(to)) {\n\t\tskb_copy_bits(from, 0, skb_put(to, len), len);\n\t\treturn;\n\t}\n\n\tif (hlen) {\n\t\tskb_copy_bits(from, 0, skb_put(to, hlen), hlen);\n\t\tlen -= hlen;\n\t} else {\n\t\tplen = min_t(int, skb_headlen(from), len);\n\t\tif (plen) {\n\t\t\tpage = virt_to_head_page(from->head);\n\t\t\toffset = from->data - (unsigned char *)page_address(page);\n\t\t\t__skb_fill_page_desc(to, 0, page, offset, plen);\n\t\t\tget_page(page);\n\t\t\tj = 1;\n\t\t\tlen -= plen;\n\t\t}\n\t}\n\n\tto->truesize += len + plen;\n\tto->len += len + plen;\n\tto->data_len += len + plen;\n\n\tfor (i = 0; i < skb_shinfo(from)->nr_frags; i++) {\n\t\tif (!len)\n\t\t\tbreak;\n\t\tskb_shinfo(to)->frags[j] = skb_shinfo(from)->frags[i];\n\t\tskb_shinfo(to)->frags[j].size = min_t(int, skb_shinfo(to)->frags[j].size, len);\n\t\tlen -= skb_shinfo(to)->frags[j].size;\n\t\tskb_frag_ref(to, j);\n\t\tj++;\n\t}\n\tskb_shinfo(to)->nr_frags = j;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'core, nfqueue, openvswitch: Orphan frags in skb_zerocopy and handle errors\n\nskb_zerocopy can copy elements of the frags array between skbs, but it doesn't\norphan them. Also, it doesn't handle errors, so this patch takes care of that\nas well, and modify the callers accordingly. skb_tx_error() is also added to\nthe callers so they will signal the failed delivery towards the creator of the\nskb.\n\nSigned-off-by: Zoltan Kiss \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int hostmatch(const char *hostname, const char *pattern)\n{\n for(;;) {\n char c = *pattern++;\n\n if(c == '\\0')\n return (*hostname ? HOST_NOMATCH : HOST_MATCH);\n\n if(c == '*') {\n c = *pattern;\n if(c == '\\0') /* \"*\\0\" matches anything remaining */\n return HOST_MATCH;\n\n while(*hostname) {\n /* The only recursive function in libcurl! */\n if(hostmatch(hostname++,pattern) == HOST_MATCH)\n return HOST_MATCH;\n }\n break;\n }\n\n if(Curl_raw_toupper(c) != Curl_raw_toupper(*hostname++))\n break;\n }\n return HOST_NOMATCH;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'use hostmatch function from latest curl (addresses CVE-2014-0139)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int vdi_create(const char *filename, QEMUOptionParameter *options,\n Error **errp)\n{\n int fd;\n int result = 0;\n uint64_t bytes = 0;\n uint32_t blocks;\n size_t block_size = DEFAULT_CLUSTER_SIZE;\n uint32_t image_type = VDI_TYPE_DYNAMIC;\n VdiHeader header;\n size_t i;\n size_t bmap_size;\n\n logout(\"\\n\");\n\n /* Read out options. */\n while (options && options->name) {\n if (!strcmp(options->name, BLOCK_OPT_SIZE)) {\n bytes = options->value.n;\n#if defined(CONFIG_VDI_BLOCK_SIZE)\n } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) {\n if (options->value.n) {\n /* TODO: Additional checks (SECTOR_SIZE * 2^n, ...). */\n block_size = options->value.n;\n }\n#endif\n#if defined(CONFIG_VDI_STATIC_IMAGE)\n } else if (!strcmp(options->name, BLOCK_OPT_STATIC)) {\n if (options->value.n) {\n image_type = VDI_TYPE_STATIC;\n }\n#endif\n }\n options++;\n }\n\n fd = qemu_open(filename,\n O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE,\n 0644);\n if (fd < 0) {\n return -errno;\n }\n\n /* We need enough blocks to store the given disk size,\n so always round up. */\n blocks = (bytes + block_size - 1) / block_size;\n\n bmap_size = blocks * sizeof(uint32_t);\n bmap_size = ((bmap_size + SECTOR_SIZE - 1) & ~(SECTOR_SIZE -1));\n\n memset(&header, 0, sizeof(header));\n pstrcpy(header.text, sizeof(header.text), VDI_TEXT);\n header.signature = VDI_SIGNATURE;\n header.version = VDI_VERSION_1_1;\n header.header_size = 0x180;\n header.image_type = image_type;\n header.offset_bmap = 0x200;\n header.offset_data = 0x200 + bmap_size;\n header.sector_size = SECTOR_SIZE;\n header.disk_size = bytes;\n header.block_size = block_size;\n header.blocks_in_image = blocks;\n if (image_type == VDI_TYPE_STATIC) {\n header.blocks_allocated = blocks;\n }\n uuid_generate(header.uuid_image);\n uuid_generate(header.uuid_last_snap);\n /* There is no need to set header.uuid_link or header.uuid_parent here. */\n#if defined(CONFIG_VDI_DEBUG)\n vdi_header_print(&header);\n#endif\n vdi_header_to_le(&header);\n if (write(fd, &header, sizeof(header)) < 0) {\n result = -errno;\n }\n\n if (bmap_size > 0) {\n uint32_t *bmap = g_malloc0(bmap_size);\n for (i = 0; i < blocks; i++) {\n if (image_type == VDI_TYPE_STATIC) {\n bmap[i] = i;\n } else {\n bmap[i] = VDI_UNALLOCATED;\n }\n }\n if (write(fd, bmap, bmap_size) < 0) {\n result = -errno;\n }\n g_free(bmap);\n }\n\n if (image_type == VDI_TYPE_STATIC) {\n if (ftruncate(fd, sizeof(header) + bmap_size + blocks * block_size)) {\n result = -errno;\n }\n }\n\n if (close(fd) < 0) {\n result = -errno;\n }\n\n return result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'vdi: add bounds checks for blocks_in_image and disk_size header fields (CVE-2014-0144)\n\nThe maximum blocks_in_image is 0xffffffff / 4, which also limits the\nmaximum disk_size for a VDI image to 1024TB. Note that this is the maximum\nsize that QEMU will currently support with this driver, not necessarily the\nmaximum size allowed by the image format.\n\nThis also fixes an incorrect error message, a bug introduced by commit\n5b7aa9b56d1bfc79916262f380c3fc7961becb50 (Reported by Stefan Weil)\n\nSigned-off-by: Jeff Cody \nSigned-off-by: Kevin Wolf \nSigned-off-by: Stefan Hajnoczi '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int xenvif_kthread_guest_rx(void *data)\n{\n\tstruct xenvif *vif = data;\n\tstruct sk_buff *skb;\n\n\twhile (!kthread_should_stop()) {\n\t\twait_event_interruptible(vif->wq,\n\t\t\t\t\t rx_work_todo(vif) ||\n\t\t\t\t\t kthread_should_stop());\n\t\tif (kthread_should_stop())\n\t\t\tbreak;\n\n\t\tif (vif->rx_queue_purge) {\n\t\t\tskb_queue_purge(&vif->rx_queue);\n\t\t\tvif->rx_queue_purge = false;\n\t\t}\n\n\t\tif (!skb_queue_empty(&vif->rx_queue))\n\t\t\txenvif_rx_action(vif);\n\n\t\tif (skb_queue_empty(&vif->rx_queue) &&\n\t\t netif_queue_stopped(vif->dev)) {\n\t\t\tdel_timer_sync(&vif->wake_queue);\n\t\t\txenvif_start_queue(vif);\n\t\t}\n\n\t\tcond_resched();\n\t}\n\n\t/* Bin any remaining skbs */\n\twhile ((skb = skb_dequeue(&vif->rx_queue)) != NULL)\n\t\tdev_kfree_skb(skb);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'xen-netback: disable rogue vif in kthread context\n\nWhen netback discovers frontend is sending malformed packet it will\ndisables the interface which serves that frontend.\n\nHowever disabling a network interface involving taking a mutex which\ncannot be done in softirq context, so we need to defer this process to\nkthread context.\n\nThis patch does the following:\n1. introduce a flag to indicate the interface is disabled.\n2. check that flag in TX path, don't do any work if it's true.\n3. check that flag in RX path, turn off that interface if it's true.\n\nThe reason to disable it in RX path is because RX uses kthread. After\nthis change the behavior of netback is still consistent -- it won't do\nany TX work for a rogue frontend, and the interface will be eventually\nturned off.\n\nAlso change a \"continue\" to \"break\" after xenvif_fatal_tx_err, as it\ndoesn't make sense to continue processing packets if frontend is rogue.\n\nThis is a fix for XSA-90.\n\nReported-by: T\u00f6r\u00f6k Edwin \nSigned-off-by: Wei Liu \nCc: Ian Campbell \nReviewed-by: David Vrabel \nAcked-by: Ian Campbell \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static struct kioctx *ioctx_alloc(unsigned nr_events)\n{\n\tstruct mm_struct *mm = current->mm;\n\tstruct kioctx *ctx;\n\tint err = -ENOMEM;\n\n\t/*\n\t * We keep track of the number of available ringbuffer slots, to prevent\n\t * overflow (reqs_available), and we also use percpu counters for this.\n\t *\n\t * So since up to half the slots might be on other cpu's percpu counters\n\t * and unavailable, double nr_events so userspace sees what they\n\t * expected: additionally, we move req_batch slots to/from percpu\n\t * counters at a time, so make sure that isn't 0:\n\t */\n\tnr_events = max(nr_events, num_possible_cpus() * 4);\n\tnr_events *= 2;\n\n\t/* Prevent overflows */\n\tif ((nr_events > (0x10000000U / sizeof(struct io_event))) ||\n\t (nr_events > (0x10000000U / sizeof(struct kiocb)))) {\n\t\tpr_debug(\"ENOMEM: nr_events too high\\n\");\n\t\treturn ERR_PTR(-EINVAL);\n\t}\n\n\tif (!nr_events || (unsigned long)nr_events > (aio_max_nr * 2UL))\n\t\treturn ERR_PTR(-EAGAIN);\n\n\tctx = kmem_cache_zalloc(kioctx_cachep, GFP_KERNEL);\n\tif (!ctx)\n\t\treturn ERR_PTR(-ENOMEM);\n\n\tctx->max_reqs = nr_events;\n\n\tif (percpu_ref_init(&ctx->users, free_ioctx_users))\n\t\tgoto err;\n\n\tif (percpu_ref_init(&ctx->reqs, free_ioctx_reqs))\n\t\tgoto err;\n\n\tspin_lock_init(&ctx->ctx_lock);\n\tspin_lock_init(&ctx->completion_lock);\n\tmutex_init(&ctx->ring_lock);\n\tinit_waitqueue_head(&ctx->wait);\n\n\tINIT_LIST_HEAD(&ctx->active_reqs);\n\n\tctx->cpu = alloc_percpu(struct kioctx_cpu);\n\tif (!ctx->cpu)\n\t\tgoto err;\n\n\tif (aio_setup_ring(ctx) < 0)\n\t\tgoto err;\n\n\tatomic_set(&ctx->reqs_available, ctx->nr_events - 1);\n\tctx->req_batch = (ctx->nr_events - 1) / (num_possible_cpus() * 4);\n\tif (ctx->req_batch < 1)\n\t\tctx->req_batch = 1;\n\n\t/* limit the number of system wide aios */\n\tspin_lock(&aio_nr_lock);\n\tif (aio_nr + nr_events > (aio_max_nr * 2UL) ||\n\t aio_nr + nr_events < aio_nr) {\n\t\tspin_unlock(&aio_nr_lock);\n\t\terr = -EAGAIN;\n\t\tgoto err;\n\t}\n\taio_nr += ctx->max_reqs;\n\tspin_unlock(&aio_nr_lock);\n\n\tpercpu_ref_get(&ctx->users); /* io_setup() will drop this ref */\n\n\terr = ioctx_add_table(ctx, mm);\n\tif (err)\n\t\tgoto err_cleanup;\n\n\tpr_debug(\"allocated ioctx %p[%ld]: mm=%p mask=0x%x\\n\",\n\t\t ctx, ctx->user_id, mm, ctx->nr_events);\n\treturn ctx;\n\nerr_cleanup:\n\taio_nr_sub(ctx->max_reqs);\nerr:\n\taio_free_ring(ctx);\n\tfree_percpu(ctx->cpu);\n\tfree_percpu(ctx->reqs.pcpu_count);\n\tfree_percpu(ctx->users.pcpu_count);\n\tkmem_cache_free(kioctx_cachep, ctx);\n\tpr_debug(\"error allocating ioctx %d\\n\", err);\n\treturn ERR_PTR(err);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'aio: prevent double free in ioctx_alloc\n\nioctx_alloc() calls aio_setup_ring() to allocate a ring. If aio_setup_ring()\nfails to do so it would call aio_free_ring() before returning, but\nioctx_alloc() would call aio_free_ring() again causing a double free of\nthe ring.\n\nThis is easily reproducible from userspace.\n\nSigned-off-by: Sasha Levin \nSigned-off-by: Benjamin LaHaise '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int route_doit(struct sk_buff *skb, struct nlmsghdr *nlh)\n{\n\tstruct net *net = sock_net(skb->sk);\n\tstruct nlattr *tb[RTA_MAX+1];\n\tstruct net_device *dev;\n\tstruct rtmsg *rtm;\n\tint err;\n\tu8 dst;\n\n\tif (!capable(CAP_NET_ADMIN))\n\t\treturn -EPERM;\n\n\tif (!capable(CAP_SYS_ADMIN))\n\t\treturn -EPERM;\n\n\tASSERT_RTNL();\n\n\terr = nlmsg_parse(nlh, sizeof(*rtm), tb, RTA_MAX, rtm_phonet_policy);\n\tif (err < 0)\n\t\treturn err;\n\n\trtm = nlmsg_data(nlh);\n\tif (rtm->rtm_table != RT_TABLE_MAIN || rtm->rtm_type != RTN_UNICAST)\n\t\treturn -EINVAL;\n\tif (tb[RTA_DST] == NULL || tb[RTA_OIF] == NULL)\n\t\treturn -EINVAL;\n\tdst = nla_get_u8(tb[RTA_DST]);\n\tif (dst & 3) /* Phonet addresses only have 6 high-order bits */\n\t\treturn -EINVAL;\n\n\tdev = __dev_get_by_index(net, nla_get_u32(tb[RTA_OIF]));\n\tif (dev == NULL)\n\t\treturn -ENODEV;\n\n\tif (nlh->nlmsg_type == RTM_NEWROUTE)\n\t\terr = phonet_route_add(dev, dst);\n\telse\n\t\terr = phonet_route_del(dev, dst);\n\tif (!err)\n\t\trtm_phonet_notify(nlh->nlmsg_type, dev, dst);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'net: Use netlink_ns_capable to verify the permisions of netlink messages\n\nIt is possible by passing a netlink socket to a more privileged\nexecutable and then to fool that executable into writing to the socket\ndata that happens to be valid netlink message to do something that\nprivileged executable did not intend to do.\n\nTo keep this from happening replace bare capable and ns_capable calls\nwith netlink_capable, netlink_net_calls and netlink_ns_capable calls.\nWhich act the same as the previous calls except they verify that the\nopener of the socket had the desired permissions as well.\n\nReported-by: Andy Lutomirski \nSigned-off-by: \"Eric W. Biederman\" \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int dn_fib_rtm_newroute(struct sk_buff *skb, struct nlmsghdr *nlh)\n{\n\tstruct net *net = sock_net(skb->sk);\n\tstruct dn_fib_table *tb;\n\tstruct rtmsg *r = nlmsg_data(nlh);\n\tstruct nlattr *attrs[RTA_MAX+1];\n\tint err;\n\n\tif (!capable(CAP_NET_ADMIN))\n\t\treturn -EPERM;\n\n\tif (!net_eq(net, &init_net))\n\t\treturn -EINVAL;\n\n\terr = nlmsg_parse(nlh, sizeof(*r), attrs, RTA_MAX, rtm_dn_policy);\n\tif (err < 0)\n\t\treturn err;\n\n\ttb = dn_fib_get_table(rtm_get_table(attrs, r->rtm_table), 1);\n\tif (!tb)\n\t\treturn -ENOBUFS;\n\n\treturn tb->insert(tb, r, attrs, nlh, &NETLINK_CB(skb));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'net: Use netlink_ns_capable to verify the permisions of netlink messages\n\nIt is possible by passing a netlink socket to a more privileged\nexecutable and then to fool that executable into writing to the socket\ndata that happens to be valid netlink message to do something that\nprivileged executable did not intend to do.\n\nTo keep this from happening replace bare capable and ns_capable calls\nwith netlink_capable, netlink_net_calls and netlink_ns_capable calls.\nWhich act the same as the previous calls except they verify that the\nopener of the socket had the desired permissions as well.\n\nReported-by: Andy Lutomirski \nSigned-off-by: \"Eric W. Biederman\" \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int tc_ctl_action(struct sk_buff *skb, struct nlmsghdr *n)\n{\n\tstruct net *net = sock_net(skb->sk);\n\tstruct nlattr *tca[TCA_ACT_MAX + 1];\n\tu32 portid = skb ? NETLINK_CB(skb).portid : 0;\n\tint ret = 0, ovr = 0;\n\n\tif ((n->nlmsg_type != RTM_GETACTION) && !capable(CAP_NET_ADMIN))\n\t\treturn -EPERM;\n\n\tret = nlmsg_parse(n, sizeof(struct tcamsg), tca, TCA_ACT_MAX, NULL);\n\tif (ret < 0)\n\t\treturn ret;\n\n\tif (tca[TCA_ACT_TAB] == NULL) {\n\t\tpr_notice(\"tc_ctl_action: received NO action attribs\\n\");\n\t\treturn -EINVAL;\n\t}\n\n\t/* n->nlmsg_flags & NLM_F_CREATE */\n\tswitch (n->nlmsg_type) {\n\tcase RTM_NEWACTION:\n\t\t/* we are going to assume all other flags\n\t\t * imply create only if it doesn't exist\n\t\t * Note that CREATE | EXCL implies that\n\t\t * but since we want avoid ambiguity (eg when flags\n\t\t * is zero) then just set this\n\t\t */\n\t\tif (n->nlmsg_flags & NLM_F_REPLACE)\n\t\t\tovr = 1;\nreplay:\n\t\tret = tcf_action_add(net, tca[TCA_ACT_TAB], n, portid, ovr);\n\t\tif (ret == -EAGAIN)\n\t\t\tgoto replay;\n\t\tbreak;\n\tcase RTM_DELACTION:\n\t\tret = tca_action_gd(net, tca[TCA_ACT_TAB], n,\n\t\t\t\t portid, RTM_DELACTION);\n\t\tbreak;\n\tcase RTM_GETACTION:\n\t\tret = tca_action_gd(net, tca[TCA_ACT_TAB], n,\n\t\t\t\t portid, RTM_GETACTION);\n\t\tbreak;\n\tdefault:\n\t\tBUG();\n\t}\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'net: Use netlink_ns_capable to verify the permisions of netlink messages\n\nIt is possible by passing a netlink socket to a more privileged\nexecutable and then to fool that executable into writing to the socket\ndata that happens to be valid netlink message to do something that\nprivileged executable did not intend to do.\n\nTo keep this from happening replace bare capable and ns_capable calls\nwith netlink_capable, netlink_net_calls and netlink_ns_capable calls.\nWhich act the same as the previous calls except they verify that the\nopener of the socket had the desired permissions as well.\n\nReported-by: Andy Lutomirski \nSigned-off-by: \"Eric W. Biederman\" \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void unqueue_me_pi(struct futex_q *q)\n{\n\tWARN_ON(plist_node_empty(&q->list));\n\tplist_del(&q->list, &q->list.plist);\n\n\tBUG_ON(!q->pi_state);\n\tfree_pi_state(q->pi_state);\n\tq->pi_state = NULL;\n\n\tspin_unlock(q->lock_ptr);\n\n\tdrop_futex_key_refs(&q->key);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'futex: Fix errors in nested key ref-counting\n\nfutex_wait() is leaking key references due to futex_wait_setup()\nacquiring an additional reference via the queue_lock() routine. The\nnested key ref-counting has been masking bugs and complicating code\nanalysis. queue_lock() is only called with a previously ref-counted\nkey, so remove the additional ref-counting from the queue_(un)lock()\nfunctions.\n\nAlso futex_wait_requeue_pi() drops one key reference too many in\nunqueue_me_pi(). Remove the key reference handling from\nunqueue_me_pi(). This was paired with a queue_lock() in\nfutex_lock_pi(), so the count remains unchanged.\n\nDocument remaining nested key ref-counting sites.\n\nSigned-off-by: Darren Hart \nReported-and-tested-by: Matthieu Fertr\u00e9\nReported-by: Louis Rilling\nCc: Peter Zijlstra \nCc: Eric Dumazet \nCc: John Kacur \nCc: Rusty Russell \nLKML-Reference: <4CBB17A8.70401@linux.intel.com>\nSigned-off-by: Thomas Gleixner \nCc: stable@kernel.org'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int cap_bprm_set_creds(struct linux_binprm *bprm)\n{\n\tconst struct cred *old = current_cred();\n\tstruct cred *new = bprm->cred;\n\tbool effective, has_cap = false;\n\tint ret;\n\n\teffective = false;\n\tret = get_file_caps(bprm, &effective, &has_cap);\n\tif (ret < 0)\n\t\treturn ret;\n\n\tif (!issecure(SECURE_NOROOT)) {\n\t\t/*\n\t\t * If the legacy file capability is set, then don't set privs\n\t\t * for a setuid root binary run by a non-root user. Do set it\n\t\t * for a root user just to cause least surprise to an admin.\n\t\t */\n\t\tif (has_cap && new->uid != 0 && new->euid == 0) {\n\t\t\twarn_setuid_and_fcaps_mixed(bprm->filename);\n\t\t\tgoto skip;\n\t\t}\n\t\t/*\n\t\t * To support inheritance of root-permissions and suid-root\n\t\t * executables under compatibility mode, we override the\n\t\t * capability sets for the file.\n\t\t *\n\t\t * If only the real uid is 0, we do not set the effective bit.\n\t\t */\n\t\tif (new->euid == 0 || new->uid == 0) {\n\t\t\t/* pP' = (cap_bset & ~0) | (pI & ~0) */\n\t\t\tnew->cap_permitted = cap_combine(old->cap_bset,\n\t\t\t\t\t\t\t old->cap_inheritable);\n\t\t}\n\t\tif (new->euid == 0)\n\t\t\teffective = true;\n\t}\nskip:\n\n\t/* Don't let someone trace a set[ug]id/setpcap binary with the revised\n\t * credentials unless they have the appropriate permit\n\t */\n\tif ((new->euid != old->uid ||\n\t new->egid != old->gid ||\n\t !cap_issubset(new->cap_permitted, old->cap_permitted)) &&\n\t bprm->unsafe & ~LSM_UNSAFE_PTRACE_CAP) {\n\t\t/* downgrade; they get no more than they had, and maybe less */\n\t\tif (!capable(CAP_SETUID)) {\n\t\t\tnew->euid = new->uid;\n\t\t\tnew->egid = new->gid;\n\t\t}\n\t\tnew->cap_permitted = cap_intersect(new->cap_permitted,\n\t\t\t\t\t\t old->cap_permitted);\n\t}\n\n\tnew->suid = new->fsuid = new->euid;\n\tnew->sgid = new->fsgid = new->egid;\n\n\tif (effective)\n\t\tnew->cap_effective = new->cap_permitted;\n\telse\n\t\tcap_clear(new->cap_effective);\n\tbprm->cap_effective = effective;\n\n\t/*\n\t * Audit candidate if current->cap_effective is set\n\t *\n\t * We do not bother to audit if 3 things are true:\n\t * 1) cap_effective has all caps\n\t * 2) we are root\n\t * 3) root is supposed to have all caps (SECURE_NOROOT)\n\t * Since this is just a normal root execing a process.\n\t *\n\t * Number 1 above might fail if you don't have a full bset, but I think\n\t * that is interesting information to audit.\n\t */\n\tif (!cap_isclear(new->cap_effective)) {\n\t\tif (!cap_issubset(CAP_FULL_SET, new->cap_effective) ||\n\t\t new->euid != 0 || new->uid != 0 ||\n\t\t issecure(SECURE_NOROOT)) {\n\t\t\tret = audit_log_bprm_fcaps(bprm, new, old);\n\t\t\tif (ret < 0)\n\t\t\t\treturn ret;\n\t\t}\n\t}\n\n\tnew->securebits &= ~issecure_mask(SECURE_KEEP_CAPS);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'Add PR_{GET,SET}_NO_NEW_PRIVS to prevent execve from granting privs\n\nWith this change, calling\n prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)\ndisables privilege granting operations at execve-time. For example, a\nprocess will not be able to execute a setuid binary to change their uid\nor gid if this bit is set. The same is true for file capabilities.\n\nAdditionally, LSM_UNSAFE_NO_NEW_PRIVS is defined to ensure that\nLSMs respect the requested behavior.\n\nTo determine if the NO_NEW_PRIVS bit is set, a task may call\n prctl(PR_GET_NO_NEW_PRIVS, 0, 0, 0, 0);\nIt returns 1 if set and 0 if it is not set. If any of the arguments are\nnon-zero, it will return -1 and set errno to -EINVAL.\n(PR_SET_NO_NEW_PRIVS behaves similarly.)\n\nThis functionality is desired for the proposed seccomp filter patch\nseries. By using PR_SET_NO_NEW_PRIVS, it allows a task to modify the\nsystem call behavior for itself and its child tasks without being\nable to impact the behavior of a more privileged task.\n\nAnother potential use is making certain privileged operations\nunprivileged. For example, chroot may be considered \"safe\" if it cannot\naffect privileged tasks.\n\nNote, this patch causes execve to fail when PR_SET_NO_NEW_PRIVS is\nset and AppArmor is in use. It is fixed in a subsequent patch.\n\nSigned-off-by: Andy Lutomirski \nSigned-off-by: Will Drewry \nAcked-by: Eric Paris \nAcked-by: Kees Cook \n\nv18: updated change desc\nv17: using new define values as per 3.4\nSigned-off-by: James Morris '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void wsgi_setup_access(WSGIDaemonProcess *daemon)\n{\n /* Setup the umask for the effective user. */\n\n if (daemon->group->umask != -1)\n umask(daemon->group->umask);\n\n /* Change to chroot environment. */\n\n if (daemon->group->root) {\n if (chroot(daemon->group->root) == -1) {\n ap_log_error(APLOG_MARK, WSGI_LOG_ALERT(errno), wsgi_server,\n \"mod_wsgi (pid=%d): Unable to change root \"\n \"directory to '%s'.\", getpid(), daemon->group->root);\n }\n }\n\n /* Setup the working directory.*/\n\n if (daemon->group->home) {\n if (chdir(daemon->group->home) == -1) {\n ap_log_error(APLOG_MARK, WSGI_LOG_ALERT(errno), wsgi_server,\n \"mod_wsgi (pid=%d): Unable to change working \"\n \"directory to '%s'.\", getpid(), daemon->group->home);\n }\n }\n else if (geteuid()) {\n struct passwd *pwent;\n\n pwent = getpwuid(geteuid());\n\n if (pwent) {\n if (chdir(pwent->pw_dir) == -1) {\n ap_log_error(APLOG_MARK, WSGI_LOG_ALERT(errno), wsgi_server,\n \"mod_wsgi (pid=%d): Unable to change working \"\n \"directory to '%s'.\", getpid(), pwent->pw_dir);\n }\n }\n else {\n ap_log_error(APLOG_MARK, WSGI_LOG_ALERT(errno), wsgi_server,\n \"mod_wsgi (pid=%d): Unable to determine home \"\n \"directory for uid=%ld.\", getpid(), (long)geteuid());\n }\n }\n else {\n struct passwd *pwent;\n\n pwent = getpwuid(daemon->group->uid);\n\n if (pwent) {\n if (chdir(pwent->pw_dir) == -1) {\n ap_log_error(APLOG_MARK, WSGI_LOG_ALERT(errno), wsgi_server,\n \"mod_wsgi (pid=%d): Unable to change working \"\n \"directory to '%s'.\", getpid(), pwent->pw_dir);\n }\n }\n else {\n ap_log_error(APLOG_MARK, WSGI_LOG_ALERT(errno), wsgi_server,\n \"mod_wsgi (pid=%d): Unable to determine home \"\n \"directory for uid=%ld.\", getpid(),\n (long)daemon->group->uid);\n }\n }\n\n /* Don't bother switch user/group if not root. */\n\n if (geteuid())\n return;\n\n /* Setup the daemon process real and effective group. */\n\n if (setgid(daemon->group->gid) == -1) {\n ap_log_error(APLOG_MARK, WSGI_LOG_ALERT(errno), wsgi_server,\n \"mod_wsgi (pid=%d): Unable to set group id to gid=%u.\",\n getpid(), (unsigned)daemon->group->gid);\n }\n else {\n if (daemon->group->groups) {\n if (setgroups(daemon->group->groups_count,\n daemon->group->groups) == -1) {\n ap_log_error(APLOG_MARK, WSGI_LOG_ALERT(errno),\n wsgi_server, \"mod_wsgi (pid=%d): Unable \"\n \"to set supplementary groups for uname=%s \"\n \"of '%s'.\", getpid(), daemon->group->user,\n daemon->group->groups_list);\n }\n }\n else if (initgroups(daemon->group->user, daemon->group->gid) == -1) {\n ap_log_error(APLOG_MARK, WSGI_LOG_ALERT(errno),\n wsgi_server, \"mod_wsgi (pid=%d): Unable \"\n \"to set groups for uname=%s and gid=%u.\", getpid(),\n daemon->group->user, (unsigned)daemon->group->gid);\n }\n }\n\n /* Setup the daemon process real and effective user. */\n\n if (setuid(daemon->group->uid) == -1) {\n ap_log_error(APLOG_MARK, WSGI_LOG_ALERT(errno), wsgi_server,\n \"mod_wsgi (pid=%d): Unable to change to uid=%ld.\",\n getpid(), (long)daemon->group->uid);\n }\n\n /*\n * Linux prevents generation of core dumps after setuid()\n * has been used. Attempt to reenable ability to dump core\n * so that the CoreDumpDirectory directive still works.\n */\n\n#if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)\n /* This applies to Linux 2.4 and later. */\n if (ap_coredumpdir_configured) {\n if (prctl(PR_SET_DUMPABLE, 1)) {\n ap_log_error(APLOG_MARK, WSGI_LOG_ALERT(errno), wsgi_server,\n \"mod_wsgi (pid=%d): Set dumpable failed. This child \"\n \"will not coredump after software errors.\", getpid());\n }\n }\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'Local privilege escalation when using daemon mode. (CVE-2014-0240)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: asn1_get_octet_der (const unsigned char *der, int der_len,\n\t\t int *ret_len, unsigned char *str, int str_size,\n\t\t int *str_len)\n{\n int len_len = 0;\n\n if (der_len <= 0)\n return ASN1_GENERIC_ERROR;\n\n /* if(str==NULL) return ASN1_SUCCESS; */\n *str_len = asn1_get_length_der (der, der_len, &len_len);\n\n if (*str_len < 0)\n return ASN1_DER_ERROR;\n\n *ret_len = *str_len + len_len;\n if (str_size >= *str_len)\n {\n if (*str_len > 0)\n memcpy (str, der + len_len, *str_len);\n }\n else\n {\n return ASN1_MEM_ERROR;\n }\n\n return ASN1_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Allow a NULL value in asn1_read_value() for all types.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: lookup_pi_state(u32 uval, struct futex_hash_bucket *hb,\n\t\tunion futex_key *key, struct futex_pi_state **ps,\n\t\tstruct task_struct *task)\n{\n\tstruct futex_pi_state *pi_state = NULL;\n\tstruct futex_q *this, *next;\n\tstruct task_struct *p;\n\tpid_t pid = uval & FUTEX_TID_MASK;\n\n\tplist_for_each_entry_safe(this, next, &hb->chain, list) {\n\t\tif (match_futex(&this->key, key)) {\n\t\t\t/*\n\t\t\t * Another waiter already exists - bump up\n\t\t\t * the refcount and return its pi_state:\n\t\t\t */\n\t\t\tpi_state = this->pi_state;\n\t\t\t/*\n\t\t\t * Userspace might have messed up non-PI and PI futexes\n\t\t\t */\n\t\t\tif (unlikely(!pi_state))\n\t\t\t\treturn -EINVAL;\n\n\t\t\tWARN_ON(!atomic_read(&pi_state->refcount));\n\n\t\t\t/*\n\t\t\t * When pi_state->owner is NULL then the owner died\n\t\t\t * and another waiter is on the fly. pi_state->owner\n\t\t\t * is fixed up by the task which acquires\n\t\t\t * pi_state->rt_mutex.\n\t\t\t *\n\t\t\t * We do not check for pid == 0 which can happen when\n\t\t\t * the owner died and robust_list_exit() cleared the\n\t\t\t * TID.\n\t\t\t */\n\t\t\tif (pid && pi_state->owner) {\n\t\t\t\t/*\n\t\t\t\t * Bail out if user space manipulated the\n\t\t\t\t * futex value.\n\t\t\t\t */\n\t\t\t\tif (pid != task_pid_vnr(pi_state->owner))\n\t\t\t\t\treturn -EINVAL;\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Protect against a corrupted uval. If uval\n\t\t\t * is 0x80000000 then pid is 0 and the waiter\n\t\t\t * bit is set. So the deadlock check in the\n\t\t\t * calling code has failed and we did not fall\n\t\t\t * into the check above due to !pid.\n\t\t\t */\n\t\t\tif (task && pi_state->owner == task)\n\t\t\t\treturn -EDEADLK;\n\n\t\t\tatomic_inc(&pi_state->refcount);\n\t\t\t*ps = pi_state;\n\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\t/*\n\t * We are the first waiter - try to look up the real owner and attach\n\t * the new pi_state to it, but bail out when TID = 0\n\t */\n\tif (!pid)\n\t\treturn -ESRCH;\n\tp = futex_find_get_task(pid);\n\tif (!p)\n\t\treturn -ESRCH;\n\n\tif (!p->mm) {\n\t\tput_task_struct(p);\n\t\treturn -EPERM;\n\t}\n\n\t/*\n\t * We need to look at the task state flags to figure out,\n\t * whether the task is exiting. To protect against the do_exit\n\t * change of the task flags, we do this protected by\n\t * p->pi_lock:\n\t */\n\traw_spin_lock_irq(&p->pi_lock);\n\tif (unlikely(p->flags & PF_EXITING)) {\n\t\t/*\n\t\t * The task is on the way out. When PF_EXITPIDONE is\n\t\t * set, we know that the task has finished the\n\t\t * cleanup:\n\t\t */\n\t\tint ret = (p->flags & PF_EXITPIDONE) ? -ESRCH : -EAGAIN;\n\n\t\traw_spin_unlock_irq(&p->pi_lock);\n\t\tput_task_struct(p);\n\t\treturn ret;\n\t}\n\n\tpi_state = alloc_pi_state();\n\n\t/*\n\t * Initialize the pi_mutex in locked state and make 'p'\n\t * the owner of it:\n\t */\n\trt_mutex_init_proxy_locked(&pi_state->pi_mutex, p);\n\n\t/* Store the key for possible exit cleanups: */\n\tpi_state->key = *key;\n\n\tWARN_ON(!list_empty(&pi_state->list));\n\tlist_add(&pi_state->list, &p->pi_state_list);\n\tpi_state->owner = p;\n\traw_spin_unlock_irq(&p->pi_lock);\n\n\tput_task_struct(p);\n\n\t*ps = pi_state;\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-269'], 'message': 'futex: Make lookup_pi_state more robust\n\nThe current implementation of lookup_pi_state has ambigous handling of\nthe TID value 0 in the user space futex. We can get into the kernel\neven if the TID value is 0, because either there is a stale waiters bit\nor the owner died bit is set or we are called from the requeue_pi path\nor from user space just for fun.\n\nThe current code avoids an explicit sanity check for pid = 0 in case\nthat kernel internal state (waiters) are found for the user space\naddress. This can lead to state leakage and worse under some\ncircumstances.\n\nHandle the cases explicit:\n\n Waiter | pi_state | pi->owner | uTID | uODIED | ?\n\n [1] NULL | --- | --- | 0 | 0/1 | Valid\n [2] NULL | --- | --- | >0 | 0/1 | Valid\n\n [3] Found | NULL | -- | Any | 0/1 | Invalid\n\n [4] Found | Found | NULL | 0 | 1 | Valid\n [5] Found | Found | NULL | >0 | 1 | Invalid\n\n [6] Found | Found | task | 0 | 1 | Valid\n\n [7] Found | Found | NULL | Any | 0 | Invalid\n\n [8] Found | Found | task | ==taskTID | 0/1 | Valid\n [9] Found | Found | task | 0 | 0 | Invalid\n [10] Found | Found | task | !=taskTID | 0/1 | Invalid\n\n [1] Indicates that the kernel can acquire the futex atomically. We\n came came here due to a stale FUTEX_WAITERS/FUTEX_OWNER_DIED bit.\n\n [2] Valid, if TID does not belong to a kernel thread. If no matching\n thread is found then it indicates that the owner TID has died.\n\n [3] Invalid. The waiter is queued on a non PI futex\n\n [4] Valid state after exit_robust_list(), which sets the user space\n value to FUTEX_WAITERS | FUTEX_OWNER_DIED.\n\n [5] The user space value got manipulated between exit_robust_list()\n and exit_pi_state_list()\n\n [6] Valid state after exit_pi_state_list() which sets the new owner in\n the pi_state but cannot access the user space value.\n\n [7] pi_state->owner can only be NULL when the OWNER_DIED bit is set.\n\n [8] Owner and user space value match\n\n [9] There is no transient state which sets the user space TID to 0\n except exit_robust_list(), but this is indicated by the\n FUTEX_OWNER_DIED bit. See [4]\n\n[10] There is no transient state which leaves owner and user space\n TID out of sync.\n\nSigned-off-by: Thomas Gleixner \nCc: Kees Cook \nCc: Will Drewry \nCc: Darren Hart \nCc: stable@vger.kernel.org\nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int FUZ_SecurityTest()\n{\n char* output;\n char* input;\n int i, r;\n\n printf(\"Overflow test (issue 52)...\\n\");\n input = (char*) malloc (20<<20);\n output = (char*) malloc (20<<20);\n input[0] = 0x0F;\n input[1] = 0x00;\n input[2] = 0x00;\n for(i = 3; i < 16840000; i++)\n input[i] = 0xff;\n r = LZ4_decompress_fast(input, output, 20<<20);\n\n free(input);\n free(output);\n printf(\" Passed (return = %i < 0)\\n\",r);\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fixed : issue 52 (reported by Ludwig Strigeus)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int __poke_user_compat(struct task_struct *child,\n\t\t\t addr_t addr, addr_t data)\n{\n\tstruct compat_user *dummy32 = NULL;\n\t__u32 tmp = (__u32) data;\n\taddr_t offset;\n\n\tif (addr < (addr_t) &dummy32->regs.acrs) {\n\t\tstruct pt_regs *regs = task_pt_regs(child);\n\t\t/*\n\t\t * psw, gprs, acrs and orig_gpr2 are stored on the stack\n\t\t */\n\t\tif (addr == (addr_t) &dummy32->regs.psw.mask) {\n\t\t\t__u32 mask = PSW32_MASK_USER;\n\n\t\t\tmask |= is_ri_task(child) ? PSW32_MASK_RI : 0;\n\t\t\t/* Build a 64 bit psw mask from 31 bit mask. */\n\t\t\tif ((tmp & ~mask) != PSW32_USER_BITS)\n\t\t\t\t/* Invalid psw mask. */\n\t\t\t\treturn -EINVAL;\n\t\t\tregs->psw.mask = (regs->psw.mask & ~PSW_MASK_USER) |\n\t\t\t\t(regs->psw.mask & PSW_MASK_BA) |\n\t\t\t\t(__u64)(tmp & mask) << 32;\n\t\t} else if (addr == (addr_t) &dummy32->regs.psw.addr) {\n\t\t\t/* Build a 64 bit psw address from 31 bit address. */\n\t\t\tregs->psw.addr = (__u64) tmp & PSW32_ADDR_INSN;\n\t\t\t/* Transfer 31 bit amode bit to psw mask. */\n\t\t\tregs->psw.mask = (regs->psw.mask & ~PSW_MASK_BA) |\n\t\t\t\t(__u64)(tmp & PSW32_ADDR_AMODE);\n\t\t} else {\n\t\t\t/* gpr 0-15 */\n\t\t\t*(__u32*)((addr_t) ®s->psw + addr*2 + 4) = tmp;\n\t\t}\n\t} else if (addr < (addr_t) (&dummy32->regs.orig_gpr2)) {\n\t\t/*\n\t\t * access registers are stored in the thread structure\n\t\t */\n\t\toffset = addr - (addr_t) &dummy32->regs.acrs;\n\t\t*(__u32*)((addr_t) &child->thread.acrs + offset) = tmp;\n\n\t} else if (addr == (addr_t) (&dummy32->regs.orig_gpr2)) {\n\t\t/*\n\t\t * orig_gpr2 is stored on the kernel stack\n\t\t */\n\t\t*(__u32*)((addr_t) &task_pt_regs(child)->orig_gpr2 + 4) = tmp;\n\n\t} else if (addr < (addr_t) &dummy32->regs.fp_regs) {\n\t\t/*\n\t\t * prevent writess of padding hole between\n\t\t * orig_gpr2 and fp_regs on s390.\n\t\t */\n\t\treturn 0;\n\n\t} else if (addr < (addr_t) (&dummy32->regs.fp_regs + 1)) {\n\t\t/*\n\t\t * floating point regs. are stored in the thread structure \n\t\t */\n\t\tif (addr == (addr_t) &dummy32->regs.fp_regs.fpc &&\n\t\t test_fp_ctl(tmp))\n\t\t\treturn -EINVAL;\n\t offset = addr - (addr_t) &dummy32->regs.fp_regs;\n\t\t*(__u32 *)((addr_t) &child->thread.fp_regs + offset) = tmp;\n\n\t} else if (addr < (addr_t) (&dummy32->regs.per_info + 1)) {\n\t\t/*\n\t\t * Handle access to the per_info structure.\n\t\t */\n\t\taddr -= (addr_t) &dummy32->regs.per_info;\n\t\t__poke_user_per_compat(child, addr, data);\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264', 'CWE-269'], 'message': 's390/ptrace: fix PSW mask check\n\nThe PSW mask check of the PTRACE_POKEUSR_AREA command is incorrect.\nThe PSW_MASK_USER define contains the PSW_MASK_ASC bits, the ptrace\ninterface accepts all combinations for the address-space-control\nbits. To protect the kernel space the PSW mask check in ptrace needs\nto reject the address-space-control bit combination for home space.\n\nFixes CVE-2014-3534\n\nCc: stable@vger.kernel.org\nSigned-off-by: Martin Schwidefsky '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: expand_string_internal(uschar *string, BOOL ket_ends, uschar **left,\n BOOL skipping, BOOL honour_dollar, BOOL *resetok_p)\n{\nint ptr = 0;\nint size = Ustrlen(string)+ 64;\nint item_type;\nuschar *yield = store_get(size);\nuschar *s = string;\nuschar *save_expand_nstring[EXPAND_MAXN+1];\nint save_expand_nlength[EXPAND_MAXN+1];\nBOOL resetok = TRUE;\n\nexpand_string_forcedfail = FALSE;\nexpand_string_message = US\"\";\n\nwhile (*s != 0)\n {\n uschar *value;\n uschar name[256];\n\n /* \\ escapes the next character, which must exist, or else\n the expansion fails. There's a special escape, \\N, which causes\n copying of the subject verbatim up to the next \\N. Otherwise,\n the escapes are the standard set. */\n\n if (*s == '\\\\')\n {\n if (s[1] == 0)\n {\n expand_string_message = US\"\\\\ at end of string\";\n goto EXPAND_FAILED;\n }\n\n if (s[1] == 'N')\n {\n uschar *t = s + 2;\n for (s = t; *s != 0; s++) if (*s == '\\\\' && s[1] == 'N') break;\n yield = string_cat(yield, &size, &ptr, t, s - t);\n if (*s != 0) s += 2;\n }\n\n else\n {\n uschar ch[1];\n ch[0] = string_interpret_escape(&s);\n s++;\n yield = string_cat(yield, &size, &ptr, ch, 1);\n }\n\n continue;\n }\n\n /*{*/\n /* Anything other than $ is just copied verbatim, unless we are\n looking for a terminating } character. */\n\n /*{*/\n if (ket_ends && *s == '}') break;\n\n if (*s != '$' || !honour_dollar)\n {\n yield = string_cat(yield, &size, &ptr, s++, 1);\n continue;\n }\n\n /* No { after the $ - must be a plain name or a number for string\n match variable. There has to be a fudge for variables that are the\n names of header fields preceded by \"$header_\" because header field\n names can contain any printing characters except space and colon.\n For those that don't like typing this much, \"$h_\" is a synonym for\n \"$header_\". A non-existent header yields a NULL value; nothing is\n inserted. */\t/*}*/\n\n if (isalpha((*(++s))))\n {\n int len;\n int newsize = 0;\n\n s = read_name(name, sizeof(name), s, US\"_\");\n\n /* If this is the first thing to be expanded, release the pre-allocated\n buffer. */\n\n if (ptr == 0 && yield != NULL)\n {\n if (resetok) store_reset(yield);\n yield = NULL;\n size = 0;\n }\n\n /* Header */\n\n if (Ustrncmp(name, \"h_\", 2) == 0 ||\n Ustrncmp(name, \"rh_\", 3) == 0 ||\n Ustrncmp(name, \"bh_\", 3) == 0 ||\n Ustrncmp(name, \"header_\", 7) == 0 ||\n Ustrncmp(name, \"rheader_\", 8) == 0 ||\n Ustrncmp(name, \"bheader_\", 8) == 0)\n {\n BOOL want_raw = (name[0] == 'r')? TRUE : FALSE;\n uschar *charset = (name[0] == 'b')? NULL : headers_charset;\n s = read_header_name(name, sizeof(name), s);\n value = find_header(name, FALSE, &newsize, want_raw, charset);\n\n /* If we didn't find the header, and the header contains a closing brace\n character, this may be a user error where the terminating colon\n has been omitted. Set a flag to adjust the error message in this case.\n But there is no error here - nothing gets inserted. */\n\n if (value == NULL)\n {\n if (Ustrchr(name, '}') != NULL) malformed_header = TRUE;\n continue;\n }\n }\n\n /* Variable */\n\n else\n {\n value = find_variable(name, FALSE, skipping, &newsize);\n if (value == NULL)\n {\n expand_string_message =\n string_sprintf(\"unknown variable name \\\"%s\\\"\", name);\n check_variable_error_message(name);\n goto EXPAND_FAILED;\n }\n }\n\n /* If the data is known to be in a new buffer, newsize will be set to the\n size of that buffer. If this is the first thing in an expansion string,\n yield will be NULL; just point it at the new store instead of copying. Many\n expansion strings contain just one reference, so this is a useful\n optimization, especially for humungous headers. */\n\n len = Ustrlen(value);\n if (yield == NULL && newsize != 0)\n {\n yield = value;\n size = newsize;\n ptr = len;\n }\n else yield = string_cat(yield, &size, &ptr, value, len);\n\n continue;\n }\n\n if (isdigit(*s))\n {\n int n;\n s = read_number(&n, s);\n if (n >= 0 && n <= expand_nmax)\n yield = string_cat(yield, &size, &ptr, expand_nstring[n],\n expand_nlength[n]);\n continue;\n }\n\n /* Otherwise, if there's no '{' after $ it's an error. */\t\t/*}*/\n\n if (*s != '{')\t\t\t\t\t\t\t/*}*/\n {\n expand_string_message = US\"$ not followed by letter, digit, or {\";\t/*}*/\n goto EXPAND_FAILED;\n }\n\n /* After { there can be various things, but they all start with\n an initial word, except for a number for a string match variable. */\n\n if (isdigit((*(++s))))\n {\n int n;\n s = read_number(&n, s);\t\t/*{*/\n if (*s++ != '}')\n {\t\t\t\t\t/*{*/\n expand_string_message = US\"} expected after number\";\n goto EXPAND_FAILED;\n }\n if (n >= 0 && n <= expand_nmax)\n yield = string_cat(yield, &size, &ptr, expand_nstring[n],\n expand_nlength[n]);\n continue;\n }\n\n if (!isalpha(*s))\n {\n expand_string_message = US\"letter or digit expected after ${\";\t/*}*/\n goto EXPAND_FAILED;\n }\n\n /* Allow \"-\" in names to cater for substrings with negative\n arguments. Since we are checking for known names after { this is\n OK. */\n\n s = read_name(name, sizeof(name), s, US\"_-\");\n item_type = chop_match(name, item_table, sizeof(item_table)/sizeof(uschar *));\n\n switch(item_type)\n {\n /* Call an ACL from an expansion. We feed data in via $acl_arg1 - $acl_arg9.\n If the ACL returns accept or reject we return content set by \"message =\"\n There is currently no limit on recursion; this would have us call\n acl_check_internal() directly and get a current level from somewhere.\n See also the acl expansion condition ECOND_ACL and the traditional\n acl modifier ACLC_ACL.\n Assume that the function has side-effects on the store that must be preserved.\n */\n\n case EITEM_ACL:\n /* ${acl {name} {arg1}{arg2}...} */\n {\n uschar *sub[10];\t/* name + arg1-arg9 (which must match number of acl_arg[]) */\n uschar *user_msg;\n\n switch(read_subs(sub, 10, 1, &s, skipping, TRUE, US\"acl\", &resetok))\n {\n case 1: goto EXPAND_FAILED_CURLY;\n case 2:\n case 3: goto EXPAND_FAILED;\n }\n if (skipping) continue;\n\n resetok = FALSE;\n switch(eval_acl(sub, sizeof(sub)/sizeof(*sub), &user_msg))\n\t{\n\tcase OK:\n\tcase FAIL:\n\t DEBUG(D_expand)\n\t debug_printf(\"acl expansion yield: %s\\n\", user_msg);\n\t if (user_msg)\n yield = string_cat(yield, &size, &ptr, user_msg, Ustrlen(user_msg));\n\t continue;\n\n\tcase DEFER:\n expand_string_forcedfail = TRUE;\n\tdefault:\n expand_string_message = string_sprintf(\"error from acl \\\"%s\\\"\", sub[0]);\n\t goto EXPAND_FAILED;\n\t}\n }\n\n /* Handle conditionals - preserve the values of the numerical expansion\n variables in case they get changed by a regular expression match in the\n condition. If not, they retain their external settings. At the end\n of this \"if\" section, they get restored to their previous values. */\n\n case EITEM_IF:\n {\n BOOL cond = FALSE;\n uschar *next_s;\n int save_expand_nmax =\n save_expand_strings(save_expand_nstring, save_expand_nlength);\n\n while (isspace(*s)) s++;\n next_s = eval_condition(s, &resetok, skipping? NULL : &cond);\n if (next_s == NULL) goto EXPAND_FAILED; /* message already set */\n\n DEBUG(D_expand)\n debug_printf(\"condition: %.*s\\n result: %s\\n\", (int)(next_s - s), s,\n cond? \"true\" : \"false\");\n\n s = next_s;\n\n /* The handling of \"yes\" and \"no\" result strings is now in a separate\n function that is also used by ${lookup} and ${extract} and ${run}. */\n\n switch(process_yesno(\n skipping, /* were previously skipping */\n cond, /* success/failure indicator */\n lookup_value, /* value to reset for string2 */\n &s, /* input pointer */\n &yield, /* output pointer */\n &size, /* output size */\n &ptr, /* output current point */\n US\"if\", /* condition type */\n\t &resetok))\n {\n case 1: goto EXPAND_FAILED; /* when all is well, the */\n case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */\n }\n\n /* Restore external setting of expansion variables for continuation\n at this level. */\n\n restore_expand_strings(save_expand_nmax, save_expand_nstring,\n save_expand_nlength);\n continue;\n }\n\n /* Handle database lookups unless locked out. If \"skipping\" is TRUE, we are\n expanding an internal string that isn't actually going to be used. All we\n need to do is check the syntax, so don't do a lookup at all. Preserve the\n values of the numerical expansion variables in case they get changed by a\n partial lookup. If not, they retain their external settings. At the end\n of this \"lookup\" section, they get restored to their previous values. */\n\n case EITEM_LOOKUP:\n {\n int stype, partial, affixlen, starflags;\n int expand_setup = 0;\n int nameptr = 0;\n uschar *key, *filename, *affix;\n uschar *save_lookup_value = lookup_value;\n int save_expand_nmax =\n save_expand_strings(save_expand_nstring, save_expand_nlength);\n\n if ((expand_forbid & RDO_LOOKUP) != 0)\n {\n expand_string_message = US\"lookup expansions are not permitted\";\n goto EXPAND_FAILED;\n }\n\n /* Get the key we are to look up for single-key+file style lookups.\n Otherwise set the key NULL pro-tem. */\n\n while (isspace(*s)) s++;\n if (*s == '{')\t\t\t\t\t/*}*/\n {\n key = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok);\n if (key == NULL) goto EXPAND_FAILED;\t\t/*{*/\n if (*s++ != '}') goto EXPAND_FAILED_CURLY;\n while (isspace(*s)) s++;\n }\n else key = NULL;\n\n /* Find out the type of database */\n\n if (!isalpha(*s))\n {\n expand_string_message = US\"missing lookup type\";\n goto EXPAND_FAILED;\n }\n\n /* The type is a string that may contain special characters of various\n kinds. Allow everything except space or { to appear; the actual content\n is checked by search_findtype_partial. */\t\t/*}*/\n\n while (*s != 0 && *s != '{' && !isspace(*s))\t/*}*/\n {\n if (nameptr < sizeof(name) - 1) name[nameptr++] = *s;\n s++;\n }\n name[nameptr] = 0;\n while (isspace(*s)) s++;\n\n /* Now check for the individual search type and any partial or default\n options. Only those types that are actually in the binary are valid. */\n\n stype = search_findtype_partial(name, &partial, &affix, &affixlen,\n &starflags);\n if (stype < 0)\n {\n expand_string_message = search_error_message;\n goto EXPAND_FAILED;\n }\n\n /* Check that a key was provided for those lookup types that need it,\n and was not supplied for those that use the query style. */\n\n if (!mac_islookup(stype, lookup_querystyle|lookup_absfilequery))\n {\n if (key == NULL)\n {\n expand_string_message = string_sprintf(\"missing {key} for single-\"\n \"key \\\"%s\\\" lookup\", name);\n goto EXPAND_FAILED;\n }\n }\n else\n {\n if (key != NULL)\n {\n expand_string_message = string_sprintf(\"a single key was given for \"\n \"lookup type \\\"%s\\\", which is not a single-key lookup type\", name);\n goto EXPAND_FAILED;\n }\n }\n\n /* Get the next string in brackets and expand it. It is the file name for\n single-key+file lookups, and the whole query otherwise. In the case of\n queries that also require a file name (e.g. sqlite), the file name comes\n first. */\n\n if (*s != '{') goto EXPAND_FAILED_CURLY;\n filename = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok);\n if (filename == NULL) goto EXPAND_FAILED;\n if (*s++ != '}') goto EXPAND_FAILED_CURLY;\n while (isspace(*s)) s++;\n\n /* If this isn't a single-key+file lookup, re-arrange the variables\n to be appropriate for the search_ functions. For query-style lookups,\n there is just a \"key\", and no file name. For the special query-style +\n file types, the query (i.e. \"key\") starts with a file name. */\n\n if (key == NULL)\n {\n while (isspace(*filename)) filename++;\n key = filename;\n\n if (mac_islookup(stype, lookup_querystyle))\n {\n filename = NULL;\n }\n else\n {\n if (*filename != '/')\n {\n expand_string_message = string_sprintf(\n \"absolute file name expected for \\\"%s\\\" lookup\", name);\n goto EXPAND_FAILED;\n }\n while (*key != 0 && !isspace(*key)) key++;\n if (*key != 0) *key++ = 0;\n }\n }\n\n /* If skipping, don't do the next bit - just lookup_value == NULL, as if\n the entry was not found. Note that there is no search_close() function.\n Files are left open in case of re-use. At suitable places in higher logic,\n search_tidyup() is called to tidy all open files. This can save opening\n the same file several times. However, files may also get closed when\n others are opened, if too many are open at once. The rule is that a\n handle should not be used after a second search_open().\n\n Request that a partial search sets up $1 and maybe $2 by passing\n expand_setup containing zero. If its value changes, reset expand_nmax,\n since new variables will have been set. Note that at the end of this\n \"lookup\" section, the old numeric variables are restored. */\n\n if (skipping)\n lookup_value = NULL;\n else\n {\n void *handle = search_open(filename, stype, 0, NULL, NULL);\n if (handle == NULL)\n {\n expand_string_message = search_error_message;\n goto EXPAND_FAILED;\n }\n lookup_value = search_find(handle, filename, key, partial, affix,\n affixlen, starflags, &expand_setup);\n if (search_find_defer)\n {\n expand_string_message =\n string_sprintf(\"lookup of \\\"%s\\\" gave DEFER: %s\",\n string_printing2(key, FALSE), search_error_message);\n goto EXPAND_FAILED;\n }\n if (expand_setup > 0) expand_nmax = expand_setup;\n }\n\n /* The handling of \"yes\" and \"no\" result strings is now in a separate\n function that is also used by ${if} and ${extract}. */\n\n switch(process_yesno(\n skipping, /* were previously skipping */\n lookup_value != NULL, /* success/failure indicator */\n save_lookup_value, /* value to reset for string2 */\n &s, /* input pointer */\n &yield, /* output pointer */\n &size, /* output size */\n &ptr, /* output current point */\n US\"lookup\", /* condition type */\n\t &resetok))\n {\n case 1: goto EXPAND_FAILED; /* when all is well, the */\n case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */\n }\n\n /* Restore external setting of expansion variables for carrying on\n at this level, and continue. */\n\n restore_expand_strings(save_expand_nmax, save_expand_nstring,\n save_expand_nlength);\n continue;\n }\n\n /* If Perl support is configured, handle calling embedded perl subroutines,\n unless locked out at this time. Syntax is ${perl{sub}} or ${perl{sub}{arg}}\n or ${perl{sub}{arg1}{arg2}} or up to a maximum of EXIM_PERL_MAX_ARGS\n arguments (defined below). */\n\n #define EXIM_PERL_MAX_ARGS 8\n\n case EITEM_PERL:\n #ifndef EXIM_PERL\n expand_string_message = US\"\\\"${perl\\\" encountered, but this facility \"\t/*}*/\n \"is not included in this binary\";\n goto EXPAND_FAILED;\n\n #else /* EXIM_PERL */\n {\n uschar *sub_arg[EXIM_PERL_MAX_ARGS + 2];\n uschar *new_yield;\n\n if ((expand_forbid & RDO_PERL) != 0)\n {\n expand_string_message = US\"Perl calls are not permitted\";\n goto EXPAND_FAILED;\n }\n\n switch(read_subs(sub_arg, EXIM_PERL_MAX_ARGS + 1, 1, &s, skipping, TRUE,\n US\"perl\", &resetok))\n {\n case 1: goto EXPAND_FAILED_CURLY;\n case 2:\n case 3: goto EXPAND_FAILED;\n }\n\n /* If skipping, we don't actually do anything */\n\n if (skipping) continue;\n\n /* Start the interpreter if necessary */\n\n if (!opt_perl_started)\n {\n uschar *initerror;\n if (opt_perl_startup == NULL)\n {\n expand_string_message = US\"A setting of perl_startup is needed when \"\n \"using the Perl interpreter\";\n goto EXPAND_FAILED;\n }\n DEBUG(D_any) debug_printf(\"Starting Perl interpreter\\n\");\n initerror = init_perl(opt_perl_startup);\n if (initerror != NULL)\n {\n expand_string_message =\n string_sprintf(\"error in perl_startup code: %s\\n\", initerror);\n goto EXPAND_FAILED;\n }\n opt_perl_started = TRUE;\n }\n\n /* Call the function */\n\n sub_arg[EXIM_PERL_MAX_ARGS + 1] = NULL;\n new_yield = call_perl_cat(yield, &size, &ptr, &expand_string_message,\n sub_arg[0], sub_arg + 1);\n\n /* NULL yield indicates failure; if the message pointer has been set to\n NULL, the yield was undef, indicating a forced failure. Otherwise the\n message will indicate some kind of Perl error. */\n\n if (new_yield == NULL)\n {\n if (expand_string_message == NULL)\n {\n expand_string_message =\n string_sprintf(\"Perl subroutine \\\"%s\\\" returned undef to force \"\n \"failure\", sub_arg[0]);\n expand_string_forcedfail = TRUE;\n }\n goto EXPAND_FAILED;\n }\n\n /* Yield succeeded. Ensure forcedfail is unset, just in case it got\n set during a callback from Perl. */\n\n expand_string_forcedfail = FALSE;\n yield = new_yield;\n continue;\n }\n #endif /* EXIM_PERL */\n\n /* Transform email address to \"prvs\" scheme to use\n as BATV-signed return path */\n\n case EITEM_PRVS:\n {\n uschar *sub_arg[3];\n uschar *p,*domain;\n\n switch(read_subs(sub_arg, 3, 2, &s, skipping, TRUE, US\"prvs\", &resetok))\n {\n case 1: goto EXPAND_FAILED_CURLY;\n case 2:\n case 3: goto EXPAND_FAILED;\n }\n\n /* If skipping, we don't actually do anything */\n if (skipping) continue;\n\n /* sub_arg[0] is the address */\n domain = Ustrrchr(sub_arg[0],'@');\n if ( (domain == NULL) || (domain == sub_arg[0]) || (Ustrlen(domain) == 1) )\n {\n expand_string_message = US\"prvs first argument must be a qualified email address\";\n goto EXPAND_FAILED;\n }\n\n /* Calculate the hash. The second argument must be a single-digit\n key number, or unset. */\n\n if (sub_arg[2] != NULL &&\n (!isdigit(sub_arg[2][0]) || sub_arg[2][1] != 0))\n {\n expand_string_message = US\"prvs second argument must be a single digit\";\n goto EXPAND_FAILED;\n }\n\n p = prvs_hmac_sha1(sub_arg[0],sub_arg[1],sub_arg[2],prvs_daystamp(7));\n if (p == NULL)\n {\n expand_string_message = US\"prvs hmac-sha1 conversion failed\";\n goto EXPAND_FAILED;\n }\n\n /* Now separate the domain from the local part */\n *domain++ = '\\0';\n\n yield = string_cat(yield,&size,&ptr,US\"prvs=\",5);\n string_cat(yield,&size,&ptr,(sub_arg[2] != NULL) ? sub_arg[2] : US\"0\", 1);\n string_cat(yield,&size,&ptr,prvs_daystamp(7),3);\n string_cat(yield,&size,&ptr,p,6);\n string_cat(yield,&size,&ptr,US\"=\",1);\n string_cat(yield,&size,&ptr,sub_arg[0],Ustrlen(sub_arg[0]));\n string_cat(yield,&size,&ptr,US\"@\",1);\n string_cat(yield,&size,&ptr,domain,Ustrlen(domain));\n\n continue;\n }\n\n /* Check a prvs-encoded address for validity */\n\n case EITEM_PRVSCHECK:\n {\n uschar *sub_arg[3];\n int mysize = 0, myptr = 0;\n const pcre *re;\n uschar *p;\n\n /* TF: Ugliness: We want to expand parameter 1 first, then set\n up expansion variables that are used in the expansion of\n parameter 2. So we clone the string for the first\n expansion, where we only expand parameter 1.\n\n PH: Actually, that isn't necessary. The read_subs() function is\n designed to work this way for the ${if and ${lookup expansions. I've\n tidied the code.\n */\n\n /* Reset expansion variables */\n prvscheck_result = NULL;\n prvscheck_address = NULL;\n prvscheck_keynum = NULL;\n\n switch(read_subs(sub_arg, 1, 1, &s, skipping, FALSE, US\"prvs\", &resetok))\n {\n case 1: goto EXPAND_FAILED_CURLY;\n case 2:\n case 3: goto EXPAND_FAILED;\n }\n\n re = regex_must_compile(US\"^prvs\\\\=([0-9])([0-9]{3})([A-F0-9]{6})\\\\=(.+)\\\\@(.+)$\",\n TRUE,FALSE);\n\n if (regex_match_and_setup(re,sub_arg[0],0,-1))\n {\n uschar *local_part = string_copyn(expand_nstring[4],expand_nlength[4]);\n uschar *key_num = string_copyn(expand_nstring[1],expand_nlength[1]);\n uschar *daystamp = string_copyn(expand_nstring[2],expand_nlength[2]);\n uschar *hash = string_copyn(expand_nstring[3],expand_nlength[3]);\n uschar *domain = string_copyn(expand_nstring[5],expand_nlength[5]);\n\n DEBUG(D_expand) debug_printf(\"prvscheck localpart: %s\\n\", local_part);\n DEBUG(D_expand) debug_printf(\"prvscheck key number: %s\\n\", key_num);\n DEBUG(D_expand) debug_printf(\"prvscheck daystamp: %s\\n\", daystamp);\n DEBUG(D_expand) debug_printf(\"prvscheck hash: %s\\n\", hash);\n DEBUG(D_expand) debug_printf(\"prvscheck domain: %s\\n\", domain);\n\n /* Set up expansion variables */\n prvscheck_address = string_cat(NULL, &mysize, &myptr, local_part, Ustrlen(local_part));\n string_cat(prvscheck_address,&mysize,&myptr,US\"@\",1);\n string_cat(prvscheck_address,&mysize,&myptr,domain,Ustrlen(domain));\n prvscheck_address[myptr] = '\\0';\n prvscheck_keynum = string_copy(key_num);\n\n /* Now expand the second argument */\n switch(read_subs(sub_arg, 1, 1, &s, skipping, FALSE, US\"prvs\", &resetok))\n {\n case 1: goto EXPAND_FAILED_CURLY;\n case 2:\n case 3: goto EXPAND_FAILED;\n }\n\n /* Now we have the key and can check the address. */\n\n p = prvs_hmac_sha1(prvscheck_address, sub_arg[0], prvscheck_keynum,\n daystamp);\n\n if (p == NULL)\n {\n expand_string_message = US\"hmac-sha1 conversion failed\";\n goto EXPAND_FAILED;\n }\n\n DEBUG(D_expand) debug_printf(\"prvscheck: received hash is %s\\n\", hash);\n DEBUG(D_expand) debug_printf(\"prvscheck: own hash is %s\\n\", p);\n\n if (Ustrcmp(p,hash) == 0)\n {\n /* Success, valid BATV address. Now check the expiry date. */\n uschar *now = prvs_daystamp(0);\n unsigned int inow = 0,iexpire = 1;\n\n (void)sscanf(CS now,\"%u\",&inow);\n (void)sscanf(CS daystamp,\"%u\",&iexpire);\n\n /* When \"iexpire\" is < 7, a \"flip\" has occured.\n Adjust \"inow\" accordingly. */\n if ( (iexpire < 7) && (inow >= 993) ) inow = 0;\n\n if (iexpire >= inow)\n {\n prvscheck_result = US\"1\";\n DEBUG(D_expand) debug_printf(\"prvscheck: success, $pvrs_result set to 1\\n\");\n }\n else\n {\n prvscheck_result = NULL;\n DEBUG(D_expand) debug_printf(\"prvscheck: signature expired, $pvrs_result unset\\n\");\n }\n }\n else\n {\n prvscheck_result = NULL;\n DEBUG(D_expand) debug_printf(\"prvscheck: hash failure, $pvrs_result unset\\n\");\n }\n\n /* Now expand the final argument. We leave this till now so that\n it can include $prvscheck_result. */\n\n switch(read_subs(sub_arg, 1, 0, &s, skipping, TRUE, US\"prvs\", &resetok))\n {\n case 1: goto EXPAND_FAILED_CURLY;\n case 2:\n case 3: goto EXPAND_FAILED;\n }\n\n if (sub_arg[0] == NULL || *sub_arg[0] == '\\0')\n yield = string_cat(yield,&size,&ptr,prvscheck_address,Ustrlen(prvscheck_address));\n else\n yield = string_cat(yield,&size,&ptr,sub_arg[0],Ustrlen(sub_arg[0]));\n\n /* Reset the \"internal\" variables afterwards, because they are in\n dynamic store that will be reclaimed if the expansion succeeded. */\n\n prvscheck_address = NULL;\n prvscheck_keynum = NULL;\n }\n else\n {\n /* Does not look like a prvs encoded address, return the empty string.\n We need to make sure all subs are expanded first, so as to skip over\n the entire item. */\n\n switch(read_subs(sub_arg, 2, 1, &s, skipping, TRUE, US\"prvs\", &resetok))\n {\n case 1: goto EXPAND_FAILED_CURLY;\n case 2:\n case 3: goto EXPAND_FAILED;\n }\n }\n\n continue;\n }\n\n /* Handle \"readfile\" to insert an entire file */\n\n case EITEM_READFILE:\n {\n FILE *f;\n uschar *sub_arg[2];\n\n if ((expand_forbid & RDO_READFILE) != 0)\n {\n expand_string_message = US\"file insertions are not permitted\";\n goto EXPAND_FAILED;\n }\n\n switch(read_subs(sub_arg, 2, 1, &s, skipping, TRUE, US\"readfile\", &resetok))\n {\n case 1: goto EXPAND_FAILED_CURLY;\n case 2:\n case 3: goto EXPAND_FAILED;\n }\n\n /* If skipping, we don't actually do anything */\n\n if (skipping) continue;\n\n /* Open the file and read it */\n\n f = Ufopen(sub_arg[0], \"rb\");\n if (f == NULL)\n {\n expand_string_message = string_open_failed(errno, \"%s\", sub_arg[0]);\n goto EXPAND_FAILED;\n }\n\n yield = cat_file(f, yield, &size, &ptr, sub_arg[1]);\n (void)fclose(f);\n continue;\n }\n\n /* Handle \"readsocket\" to insert data from a Unix domain socket */\n\n case EITEM_READSOCK:\n {\n int fd;\n int timeout = 5;\n int save_ptr = ptr;\n FILE *f;\n struct sockaddr_un sockun; /* don't call this \"sun\" ! */\n uschar *arg;\n uschar *sub_arg[4];\n\n if ((expand_forbid & RDO_READSOCK) != 0)\n {\n expand_string_message = US\"socket insertions are not permitted\";\n goto EXPAND_FAILED;\n }\n\n /* Read up to 4 arguments, but don't do the end of item check afterwards,\n because there may be a string for expansion on failure. */\n\n switch(read_subs(sub_arg, 4, 2, &s, skipping, FALSE, US\"readsocket\", &resetok))\n {\n case 1: goto EXPAND_FAILED_CURLY;\n case 2: /* Won't occur: no end check */\n case 3: goto EXPAND_FAILED;\n }\n\n /* Sort out timeout, if given */\n\n if (sub_arg[2] != NULL)\n {\n timeout = readconf_readtime(sub_arg[2], 0, FALSE);\n if (timeout < 0)\n {\n expand_string_message = string_sprintf(\"bad time value %s\",\n sub_arg[2]);\n goto EXPAND_FAILED;\n }\n }\n else sub_arg[3] = NULL; /* No eol if no timeout */\n\n /* If skipping, we don't actually do anything. Otherwise, arrange to\n connect to either an IP or a Unix socket. */\n\n if (!skipping)\n {\n /* Handle an IP (internet) domain */\n\n if (Ustrncmp(sub_arg[0], \"inet:\", 5) == 0)\n {\n int port;\n uschar *server_name = sub_arg[0] + 5;\n uschar *port_name = Ustrrchr(server_name, ':');\n\n /* Sort out the port */\n\n if (port_name == NULL)\n {\n expand_string_message =\n string_sprintf(\"missing port for readsocket %s\", sub_arg[0]);\n goto EXPAND_FAILED;\n }\n *port_name++ = 0; /* Terminate server name */\n\n if (isdigit(*port_name))\n {\n uschar *end;\n port = Ustrtol(port_name, &end, 0);\n if (end != port_name + Ustrlen(port_name))\n {\n expand_string_message =\n string_sprintf(\"invalid port number %s\", port_name);\n goto EXPAND_FAILED;\n }\n }\n else\n {\n struct servent *service_info = getservbyname(CS port_name, \"tcp\");\n if (service_info == NULL)\n {\n expand_string_message = string_sprintf(\"unknown port \\\"%s\\\"\",\n port_name);\n goto EXPAND_FAILED;\n }\n port = ntohs(service_info->s_port);\n }\n\n\t if ((fd = ip_connectedsocket(SOCK_STREAM, server_name, port, port,\n\t\t timeout, NULL, &expand_string_message)) < 0)\n goto SOCK_FAIL;\n }\n\n /* Handle a Unix domain socket */\n\n else\n {\n int rc;\n if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)\n {\n expand_string_message = string_sprintf(\"failed to create socket: %s\",\n strerror(errno));\n goto SOCK_FAIL;\n }\n\n sockun.sun_family = AF_UNIX;\n sprintf(sockun.sun_path, \"%.*s\", (int)(sizeof(sockun.sun_path)-1),\n sub_arg[0]);\n\n sigalrm_seen = FALSE;\n alarm(timeout);\n rc = connect(fd, (struct sockaddr *)(&sockun), sizeof(sockun));\n alarm(0);\n if (sigalrm_seen)\n {\n expand_string_message = US \"socket connect timed out\";\n goto SOCK_FAIL;\n }\n if (rc < 0)\n {\n expand_string_message = string_sprintf(\"failed to connect to socket \"\n \"%s: %s\", sub_arg[0], strerror(errno));\n goto SOCK_FAIL;\n }\n }\n\n DEBUG(D_expand) debug_printf(\"connected to socket %s\\n\", sub_arg[0]);\n\n\t/* Allow sequencing of test actions */\n\tif (running_in_test_harness) millisleep(100);\n\n /* Write the request string, if not empty */\n\n if (sub_arg[1][0] != 0)\n {\n int len = Ustrlen(sub_arg[1]);\n DEBUG(D_expand) debug_printf(\"writing \\\"%s\\\" to socket\\n\",\n sub_arg[1]);\n if (write(fd, sub_arg[1], len) != len)\n {\n expand_string_message = string_sprintf(\"request write to socket \"\n \"failed: %s\", strerror(errno));\n goto SOCK_FAIL;\n }\n }\n\n /* Shut down the sending side of the socket. This helps some servers to\n recognise that it is their turn to do some work. Just in case some\n system doesn't have this function, make it conditional. */\n\n #ifdef SHUT_WR\n shutdown(fd, SHUT_WR);\n #endif\n\n\tif (running_in_test_harness) millisleep(100);\n\n /* Now we need to read from the socket, under a timeout. The function\n that reads a file can be used. */\n\n f = fdopen(fd, \"rb\");\n sigalrm_seen = FALSE;\n alarm(timeout);\n yield = cat_file(f, yield, &size, &ptr, sub_arg[3]);\n alarm(0);\n (void)fclose(f);\n\n /* After a timeout, we restore the pointer in the result, that is,\n make sure we add nothing from the socket. */\n\n if (sigalrm_seen)\n {\n ptr = save_ptr;\n expand_string_message = US \"socket read timed out\";\n goto SOCK_FAIL;\n }\n }\n\n /* The whole thing has worked (or we were skipping). If there is a\n failure string following, we need to skip it. */\n\n if (*s == '{')\n {\n if (expand_string_internal(s+1, TRUE, &s, TRUE, TRUE, &resetok) == NULL)\n goto EXPAND_FAILED;\n if (*s++ != '}') goto EXPAND_FAILED_CURLY;\n while (isspace(*s)) s++;\n }\n if (*s++ != '}') goto EXPAND_FAILED_CURLY;\n continue;\n\n /* Come here on failure to create socket, connect socket, write to the\n socket, or timeout on reading. If another substring follows, expand and\n use it. Otherwise, those conditions give expand errors. */\n\n SOCK_FAIL:\n if (*s != '{') goto EXPAND_FAILED;\n DEBUG(D_any) debug_printf(\"%s\\n\", expand_string_message);\n arg = expand_string_internal(s+1, TRUE, &s, FALSE, TRUE, &resetok);\n if (arg == NULL) goto EXPAND_FAILED;\n yield = string_cat(yield, &size, &ptr, arg, Ustrlen(arg));\n if (*s++ != '}') goto EXPAND_FAILED_CURLY;\n while (isspace(*s)) s++;\n if (*s++ != '}') goto EXPAND_FAILED_CURLY;\n continue;\n }\n\n /* Handle \"run\" to execute a program. */\n\n case EITEM_RUN:\n {\n FILE *f;\n uschar *arg;\n uschar **argv;\n pid_t pid;\n int fd_in, fd_out;\n int lsize = 0;\n int lptr = 0;\n\n if ((expand_forbid & RDO_RUN) != 0)\n {\n expand_string_message = US\"running a command is not permitted\";\n goto EXPAND_FAILED;\n }\n\n while (isspace(*s)) s++;\n if (*s != '{') goto EXPAND_FAILED_CURLY;\n arg = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok);\n if (arg == NULL) goto EXPAND_FAILED;\n while (isspace(*s)) s++;\n if (*s++ != '}') goto EXPAND_FAILED_CURLY;\n\n if (skipping) /* Just pretend it worked when we're skipping */\n {\n runrc = 0;\n }\n else\n {\n if (!transport_set_up_command(&argv, /* anchor for arg list */\n arg, /* raw command */\n FALSE, /* don't expand the arguments */\n 0, /* not relevant when... */\n NULL, /* no transporting address */\n US\"${run} expansion\", /* for error messages */\n &expand_string_message)) /* where to put error message */\n {\n goto EXPAND_FAILED;\n }\n\n /* Create the child process, making it a group leader. */\n\n pid = child_open(argv, NULL, 0077, &fd_in, &fd_out, TRUE);\n\n if (pid < 0)\n {\n expand_string_message =\n string_sprintf(\"couldn't create child process: %s\", strerror(errno));\n goto EXPAND_FAILED;\n }\n\n /* Nothing is written to the standard input. */\n\n (void)close(fd_in);\n\n /* Read the pipe to get the command's output into $value (which is kept\n in lookup_value). Read during execution, so that if the output exceeds\n the OS pipe buffer limit, we don't block forever. */\n\n f = fdopen(fd_out, \"rb\");\n sigalrm_seen = FALSE;\n alarm(60);\n lookup_value = cat_file(f, lookup_value, &lsize, &lptr, NULL);\n alarm(0);\n (void)fclose(f);\n\n /* Wait for the process to finish, applying the timeout, and inspect its\n return code for serious disasters. Simple non-zero returns are passed on.\n */\n\n if (sigalrm_seen == TRUE || (runrc = child_close(pid, 30)) < 0)\n {\n if (sigalrm_seen == TRUE || runrc == -256)\n {\n expand_string_message = string_sprintf(\"command timed out\");\n killpg(pid, SIGKILL); /* Kill the whole process group */\n }\n\n else if (runrc == -257)\n expand_string_message = string_sprintf(\"wait() failed: %s\",\n strerror(errno));\n\n else\n expand_string_message = string_sprintf(\"command killed by signal %d\",\n -runrc);\n\n goto EXPAND_FAILED;\n }\n }\n\n /* Process the yes/no strings; $value may be useful in both cases */\n\n switch(process_yesno(\n skipping, /* were previously skipping */\n runrc == 0, /* success/failure indicator */\n lookup_value, /* value to reset for string2 */\n &s, /* input pointer */\n &yield, /* output pointer */\n &size, /* output size */\n &ptr, /* output current point */\n US\"run\", /* condition type */\n\t &resetok))\n {\n case 1: goto EXPAND_FAILED; /* when all is well, the */\n case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */\n }\n\n continue;\n }\n\n /* Handle character translation for \"tr\" */\n\n case EITEM_TR:\n {\n int oldptr = ptr;\n int o2m;\n uschar *sub[3];\n\n switch(read_subs(sub, 3, 3, &s, skipping, TRUE, US\"tr\", &resetok))\n {\n case 1: goto EXPAND_FAILED_CURLY;\n case 2:\n case 3: goto EXPAND_FAILED;\n }\n\n yield = string_cat(yield, &size, &ptr, sub[0], Ustrlen(sub[0]));\n o2m = Ustrlen(sub[2]) - 1;\n\n if (o2m >= 0) for (; oldptr < ptr; oldptr++)\n {\n uschar *m = Ustrrchr(sub[1], yield[oldptr]);\n if (m != NULL)\n {\n int o = m - sub[1];\n yield[oldptr] = sub[2][(o < o2m)? o : o2m];\n }\n }\n\n continue;\n }\n\n /* Handle \"hash\", \"length\", \"nhash\", and \"substr\" when they are given with\n expanded arguments. */\n\n case EITEM_HASH:\n case EITEM_LENGTH:\n case EITEM_NHASH:\n case EITEM_SUBSTR:\n {\n int i;\n int len;\n uschar *ret;\n int val[2] = { 0, -1 };\n uschar *sub[3];\n\n /* \"length\" takes only 2 arguments whereas the others take 2 or 3.\n Ensure that sub[2] is set in the ${length } case. */\n\n sub[2] = NULL;\n switch(read_subs(sub, (item_type == EITEM_LENGTH)? 2:3, 2, &s, skipping,\n TRUE, name, &resetok))\n {\n case 1: goto EXPAND_FAILED_CURLY;\n case 2:\n case 3: goto EXPAND_FAILED;\n }\n\n /* Juggle the arguments if there are only two of them: always move the\n string to the last position and make ${length{n}{str}} equivalent to\n ${substr{0}{n}{str}}. See the defaults for val[] above. */\n\n if (sub[2] == NULL)\n {\n sub[2] = sub[1];\n sub[1] = NULL;\n if (item_type == EITEM_LENGTH)\n {\n sub[1] = sub[0];\n sub[0] = NULL;\n }\n }\n\n for (i = 0; i < 2; i++)\n {\n if (sub[i] == NULL) continue;\n val[i] = (int)Ustrtol(sub[i], &ret, 10);\n if (*ret != 0 || (i != 0 && val[i] < 0))\n {\n expand_string_message = string_sprintf(\"\\\"%s\\\" is not a%s number \"\n \"(in \\\"%s\\\" expansion)\", sub[i], (i != 0)? \" positive\" : \"\", name);\n goto EXPAND_FAILED;\n }\n }\n\n ret =\n (item_type == EITEM_HASH)?\n compute_hash(sub[2], val[0], val[1], &len) :\n (item_type == EITEM_NHASH)?\n compute_nhash(sub[2], val[0], val[1], &len) :\n extract_substr(sub[2], val[0], val[1], &len);\n\n if (ret == NULL) goto EXPAND_FAILED;\n yield = string_cat(yield, &size, &ptr, ret, len);\n continue;\n }\n\n /* Handle HMAC computation: ${hmac{}{}{}}\n This code originally contributed by Steve Haslam. It currently supports\n the use of MD5 and SHA-1 hashes.\n\n We need some workspace that is large enough to handle all the supported\n hash types. Use macros to set the sizes rather than be too elaborate. */\n\n #define MAX_HASHLEN 20\n #define MAX_HASHBLOCKLEN 64\n\n case EITEM_HMAC:\n {\n uschar *sub[3];\n md5 md5_base;\n sha1 sha1_base;\n void *use_base;\n int type, i;\n int hashlen; /* Number of octets for the hash algorithm's output */\n int hashblocklen; /* Number of octets the hash algorithm processes */\n uschar *keyptr, *p;\n unsigned int keylen;\n\n uschar keyhash[MAX_HASHLEN];\n uschar innerhash[MAX_HASHLEN];\n uschar finalhash[MAX_HASHLEN];\n uschar finalhash_hex[2*MAX_HASHLEN];\n uschar innerkey[MAX_HASHBLOCKLEN];\n uschar outerkey[MAX_HASHBLOCKLEN];\n\n switch (read_subs(sub, 3, 3, &s, skipping, TRUE, name, &resetok))\n {\n case 1: goto EXPAND_FAILED_CURLY;\n case 2:\n case 3: goto EXPAND_FAILED;\n }\n\n if (Ustrcmp(sub[0], \"md5\") == 0)\n {\n type = HMAC_MD5;\n use_base = &md5_base;\n hashlen = 16;\n hashblocklen = 64;\n }\n else if (Ustrcmp(sub[0], \"sha1\") == 0)\n {\n type = HMAC_SHA1;\n use_base = &sha1_base;\n hashlen = 20;\n hashblocklen = 64;\n }\n else\n {\n expand_string_message =\n string_sprintf(\"hmac algorithm \\\"%s\\\" is not recognised\", sub[0]);\n goto EXPAND_FAILED;\n }\n\n keyptr = sub[1];\n keylen = Ustrlen(keyptr);\n\n /* If the key is longer than the hash block length, then hash the key\n first */\n\n if (keylen > hashblocklen)\n {\n chash_start(type, use_base);\n chash_end(type, use_base, keyptr, keylen, keyhash);\n keyptr = keyhash;\n keylen = hashlen;\n }\n\n /* Now make the inner and outer key values */\n\n memset(innerkey, 0x36, hashblocklen);\n memset(outerkey, 0x5c, hashblocklen);\n\n for (i = 0; i < keylen; i++)\n {\n innerkey[i] ^= keyptr[i];\n outerkey[i] ^= keyptr[i];\n }\n\n /* Now do the hashes */\n\n chash_start(type, use_base);\n chash_mid(type, use_base, innerkey);\n chash_end(type, use_base, sub[2], Ustrlen(sub[2]), innerhash);\n\n chash_start(type, use_base);\n chash_mid(type, use_base, outerkey);\n chash_end(type, use_base, innerhash, hashlen, finalhash);\n\n /* Encode the final hash as a hex string */\n\n p = finalhash_hex;\n for (i = 0; i < hashlen; i++)\n {\n *p++ = hex_digits[(finalhash[i] & 0xf0) >> 4];\n *p++ = hex_digits[finalhash[i] & 0x0f];\n }\n\n DEBUG(D_any) debug_printf(\"HMAC[%s](%.*s,%.*s)=%.*s\\n\", sub[0],\n (int)keylen, keyptr, Ustrlen(sub[2]), sub[2], hashlen*2, finalhash_hex);\n\n yield = string_cat(yield, &size, &ptr, finalhash_hex, hashlen*2);\n }\n\n continue;\n\n /* Handle global substitution for \"sg\" - like Perl's s/xxx/yyy/g operator.\n We have to save the numerical variables and restore them afterwards. */\n\n case EITEM_SG:\n {\n const pcre *re;\n int moffset, moffsetextra, slen;\n int roffset;\n int emptyopt;\n const uschar *rerror;\n uschar *subject;\n uschar *sub[3];\n int save_expand_nmax =\n save_expand_strings(save_expand_nstring, save_expand_nlength);\n\n switch(read_subs(sub, 3, 3, &s, skipping, TRUE, US\"sg\", &resetok))\n {\n case 1: goto EXPAND_FAILED_CURLY;\n case 2:\n case 3: goto EXPAND_FAILED;\n }\n\n /* Compile the regular expression */\n\n re = pcre_compile(CS sub[1], PCRE_COPT, (const char **)&rerror, &roffset,\n NULL);\n\n if (re == NULL)\n {\n expand_string_message = string_sprintf(\"regular expression error in \"\n \"\\\"%s\\\": %s at offset %d\", sub[1], rerror, roffset);\n goto EXPAND_FAILED;\n }\n\n /* Now run a loop to do the substitutions as often as necessary. It ends\n when there are no more matches. Take care over matches of the null string;\n do the same thing as Perl does. */\n\n subject = sub[0];\n slen = Ustrlen(sub[0]);\n moffset = moffsetextra = 0;\n emptyopt = 0;\n\n for (;;)\n {\n int ovector[3*(EXPAND_MAXN+1)];\n int n = pcre_exec(re, NULL, CS subject, slen, moffset + moffsetextra,\n PCRE_EOPT | emptyopt, ovector, sizeof(ovector)/sizeof(int));\n int nn;\n uschar *insert;\n\n /* No match - if we previously set PCRE_NOTEMPTY after a null match, this\n is not necessarily the end. We want to repeat the match from one\n character further along, but leaving the basic offset the same (for\n copying below). We can't be at the end of the string - that was checked\n before setting PCRE_NOTEMPTY. If PCRE_NOTEMPTY is not set, we are\n finished; copy the remaining string and end the loop. */\n\n if (n < 0)\n {\n if (emptyopt != 0)\n {\n moffsetextra = 1;\n emptyopt = 0;\n continue;\n }\n yield = string_cat(yield, &size, &ptr, subject+moffset, slen-moffset);\n break;\n }\n\n /* Match - set up for expanding the replacement. */\n\n if (n == 0) n = EXPAND_MAXN + 1;\n expand_nmax = 0;\n for (nn = 0; nn < n*2; nn += 2)\n {\n expand_nstring[expand_nmax] = subject + ovector[nn];\n expand_nlength[expand_nmax++] = ovector[nn+1] - ovector[nn];\n }\n expand_nmax--;\n\n /* Copy the characters before the match, plus the expanded insertion. */\n\n yield = string_cat(yield, &size, &ptr, subject + moffset,\n ovector[0] - moffset);\n insert = expand_string(sub[2]);\n if (insert == NULL) goto EXPAND_FAILED;\n yield = string_cat(yield, &size, &ptr, insert, Ustrlen(insert));\n\n moffset = ovector[1];\n moffsetextra = 0;\n emptyopt = 0;\n\n /* If we have matched an empty string, first check to see if we are at\n the end of the subject. If so, the loop is over. Otherwise, mimic\n what Perl's /g options does. This turns out to be rather cunning. First\n we set PCRE_NOTEMPTY and PCRE_ANCHORED and try the match a non-empty\n string at the same point. If this fails (picked up above) we advance to\n the next character. */\n\n if (ovector[0] == ovector[1])\n {\n if (ovector[0] == slen) break;\n emptyopt = PCRE_NOTEMPTY | PCRE_ANCHORED;\n }\n }\n\n /* All done - restore numerical variables. */\n\n restore_expand_strings(save_expand_nmax, save_expand_nstring,\n save_expand_nlength);\n continue;\n }\n\n /* Handle keyed and numbered substring extraction. If the first argument\n consists entirely of digits, then a numerical extraction is assumed. */\n\n case EITEM_EXTRACT:\n {\n int i;\n int j = 2;\n int field_number = 1;\n BOOL field_number_set = FALSE;\n uschar *save_lookup_value = lookup_value;\n uschar *sub[3];\n int save_expand_nmax =\n save_expand_strings(save_expand_nstring, save_expand_nlength);\n\n /* Read the arguments */\n\n for (i = 0; i < j; i++)\n {\n while (isspace(*s)) s++;\n if (*s == '{') \t\t\t\t\t\t/*}*/\n {\n sub[i] = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok);\n if (sub[i] == NULL) goto EXPAND_FAILED;\t\t/*{*/\n if (*s++ != '}') goto EXPAND_FAILED_CURLY;\n\n /* After removal of leading and trailing white space, the first\n argument must not be empty; if it consists entirely of digits\n (optionally preceded by a minus sign), this is a numerical\n extraction, and we expect 3 arguments. */\n\n if (i == 0)\n {\n int len;\n int x = 0;\n uschar *p = sub[0];\n\n while (isspace(*p)) p++;\n sub[0] = p;\n\n len = Ustrlen(p);\n while (len > 0 && isspace(p[len-1])) len--;\n p[len] = 0;\n\n if (*p == 0 && !skipping)\n {\n expand_string_message = US\"first argument of \\\"extract\\\" must \"\n \"not be empty\";\n goto EXPAND_FAILED;\n }\n\n if (*p == '-')\n {\n field_number = -1;\n p++;\n }\n while (*p != 0 && isdigit(*p)) x = x * 10 + *p++ - '0';\n if (*p == 0)\n {\n field_number *= x;\n j = 3; /* Need 3 args */\n field_number_set = TRUE;\n }\n }\n }\n else goto EXPAND_FAILED_CURLY;\n }\n\n /* Extract either the numbered or the keyed substring into $value. If\n skipping, just pretend the extraction failed. */\n\n lookup_value = skipping? NULL : field_number_set?\n expand_gettokened(field_number, sub[1], sub[2]) :\n expand_getkeyed(sub[0], sub[1]);\n\n /* If no string follows, $value gets substituted; otherwise there can\n be yes/no strings, as for lookup or if. */\n\n switch(process_yesno(\n skipping, /* were previously skipping */\n lookup_value != NULL, /* success/failure indicator */\n save_lookup_value, /* value to reset for string2 */\n &s, /* input pointer */\n &yield, /* output pointer */\n &size, /* output size */\n &ptr, /* output current point */\n US\"extract\", /* condition type */\n\t &resetok))\n {\n case 1: goto EXPAND_FAILED; /* when all is well, the */\n case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */\n }\n\n /* All done - restore numerical variables. */\n\n restore_expand_strings(save_expand_nmax, save_expand_nstring,\n save_expand_nlength);\n\n continue;\n }\n\n /* return the Nth item from a list */\n\n case EITEM_LISTEXTRACT:\n {\n int i;\n int field_number = 1;\n uschar *save_lookup_value = lookup_value;\n uschar *sub[2];\n int save_expand_nmax =\n save_expand_strings(save_expand_nstring, save_expand_nlength);\n\n /* Read the field & list arguments */\n\n for (i = 0; i < 2; i++)\n {\n while (isspace(*s)) s++;\n if (*s != '{')\t\t\t\t\t/*}*/\n\t goto EXPAND_FAILED_CURLY;\n\n\tsub[i] = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok);\n\tif (!sub[i]) goto EXPAND_FAILED;\t\t/*{*/\n\tif (*s++ != '}') goto EXPAND_FAILED_CURLY;\n\n\t/* After removal of leading and trailing white space, the first\n\targument must be numeric and nonempty. */\n\n\tif (i == 0)\n\t {\n\t int len;\n\t int x = 0;\n\t uschar *p = sub[0];\n\n\t while (isspace(*p)) p++;\n\t sub[0] = p;\n\n\t len = Ustrlen(p);\n\t while (len > 0 && isspace(p[len-1])) len--;\n\t p[len] = 0;\n\n\t if (!*p && !skipping)\n\t {\n\t expand_string_message = US\"first argument of \\\"listextract\\\" must \"\n\t \"not be empty\";\n\t goto EXPAND_FAILED;\n\t }\n\n\t if (*p == '-')\n\t {\n\t field_number = -1;\n\t p++;\n\t }\n\t while (*p && isdigit(*p)) x = x * 10 + *p++ - '0';\n\t if (*p)\n\t {\n\t expand_string_message = US\"first argument of \\\"listextract\\\" must \"\n\t \"be numeric\";\n\t goto EXPAND_FAILED;\n\t }\n\t field_number *= x;\n\t }\n }\n\n /* Extract the numbered element into $value. If\n skipping, just pretend the extraction failed. */\n\n lookup_value = skipping? NULL : expand_getlistele(field_number, sub[1]);\n\n /* If no string follows, $value gets substituted; otherwise there can\n be yes/no strings, as for lookup or if. */\n\n switch(process_yesno(\n skipping, /* were previously skipping */\n lookup_value != NULL, /* success/failure indicator */\n save_lookup_value, /* value to reset for string2 */\n &s, /* input pointer */\n &yield, /* output pointer */\n &size, /* output size */\n &ptr, /* output current point */\n US\"extract\", /* condition type */\n\t &resetok))\n {\n case 1: goto EXPAND_FAILED; /* when all is well, the */\n case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */\n }\n\n /* All done - restore numerical variables. */\n\n restore_expand_strings(save_expand_nmax, save_expand_nstring,\n save_expand_nlength);\n\n continue;\n }\n\n#ifdef SUPPORT_TLS\n case EITEM_CERTEXTRACT:\n {\n uschar *save_lookup_value = lookup_value;\n uschar *sub[2];\n int save_expand_nmax =\n save_expand_strings(save_expand_nstring, save_expand_nlength);\n\n /* Read the field argument */\n while (isspace(*s)) s++;\n if (*s != '{')\t\t\t\t\t/*}*/\n\tgoto EXPAND_FAILED_CURLY;\n sub[0] = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok);\n if (!sub[0]) goto EXPAND_FAILED;\t\t/*{*/\n if (*s++ != '}') goto EXPAND_FAILED_CURLY;\n /* strip spaces fore & aft */\n {\n int len;\n uschar *p = sub[0];\n\n while (isspace(*p)) p++;\n sub[0] = p;\n\n len = Ustrlen(p);\n while (len > 0 && isspace(p[len-1])) len--;\n p[len] = 0;\n }\n\n /* inspect the cert argument */\n while (isspace(*s)) s++;\n if (*s != '{')\t\t\t\t\t/*}*/\n\tgoto EXPAND_FAILED_CURLY;\n if (*++s != '$')\n {\n\texpand_string_message = US\"second argument of \\\"certextract\\\" must \"\n\t \"be a certificate variable\";\n\tgoto EXPAND_FAILED;\n\t}\n sub[1] = expand_string_internal(s+1, TRUE, &s, skipping, FALSE, &resetok);\n if (!sub[1]) goto EXPAND_FAILED;\t\t/*{*/\n if (*s++ != '}') goto EXPAND_FAILED_CURLY;\n\n if (skipping)\n\tlookup_value = NULL;\n else\n\t{\n\tlookup_value = expand_getcertele(sub[0], sub[1]);\n\tif (*expand_string_message) goto EXPAND_FAILED;\n\t}\n switch(process_yesno(\n skipping, /* were previously skipping */\n lookup_value != NULL, /* success/failure indicator */\n save_lookup_value, /* value to reset for string2 */\n &s, /* input pointer */\n &yield, /* output pointer */\n &size, /* output size */\n &ptr, /* output current point */\n US\"extract\", /* condition type */\n\t &resetok))\n {\n case 1: goto EXPAND_FAILED; /* when all is well, the */\n case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */\n }\n\n restore_expand_strings(save_expand_nmax, save_expand_nstring,\n save_expand_nlength);\n continue;\n }\n#endif\t/*SUPPORT_TLS*/\n\n /* Handle list operations */\n\n case EITEM_FILTER:\n case EITEM_MAP:\n case EITEM_REDUCE:\n {\n int sep = 0;\n int save_ptr = ptr;\n uschar outsep[2] = { '\\0', '\\0' };\n uschar *list, *expr, *temp;\n uschar *save_iterate_item = iterate_item;\n uschar *save_lookup_value = lookup_value;\n\n while (isspace(*s)) s++;\n if (*s++ != '{') goto EXPAND_FAILED_CURLY;\n\n list = expand_string_internal(s, TRUE, &s, skipping, TRUE, &resetok);\n if (list == NULL) goto EXPAND_FAILED;\n if (*s++ != '}') goto EXPAND_FAILED_CURLY;\n\n if (item_type == EITEM_REDUCE)\n {\n while (isspace(*s)) s++;\n if (*s++ != '{') goto EXPAND_FAILED_CURLY;\n temp = expand_string_internal(s, TRUE, &s, skipping, TRUE, &resetok);\n if (temp == NULL) goto EXPAND_FAILED;\n lookup_value = temp;\n if (*s++ != '}') goto EXPAND_FAILED_CURLY;\n }\n\n while (isspace(*s)) s++;\n if (*s++ != '{') goto EXPAND_FAILED_CURLY;\n\n expr = s;\n\n /* For EITEM_FILTER, call eval_condition once, with result discarded (as\n if scanning a \"false\" part). This allows us to find the end of the\n condition, because if the list is empty, we won't actually evaluate the\n condition for real. For EITEM_MAP and EITEM_REDUCE, do the same, using\n the normal internal expansion function. */\n\n if (item_type == EITEM_FILTER)\n {\n temp = eval_condition(expr, &resetok, NULL);\n if (temp != NULL) s = temp;\n }\n else\n {\n temp = expand_string_internal(s, TRUE, &s, TRUE, TRUE, &resetok);\n }\n\n if (temp == NULL)\n {\n expand_string_message = string_sprintf(\"%s inside \\\"%s\\\" item\",\n expand_string_message, name);\n goto EXPAND_FAILED;\n }\n\n while (isspace(*s)) s++;\n if (*s++ != '}')\n {\t\t\t\t\t\t/*{*/\n expand_string_message = string_sprintf(\"missing } at end of condition \"\n \"or expression inside \\\"%s\\\"\", name);\n goto EXPAND_FAILED;\n }\n\n while (isspace(*s)) s++;\t\t\t\t/*{*/\n if (*s++ != '}')\n {\t\t\t\t\t\t/*{*/\n expand_string_message = string_sprintf(\"missing } at end of \\\"%s\\\"\",\n name);\n goto EXPAND_FAILED;\n }\n\n /* If we are skipping, we can now just move on to the next item. When\n processing for real, we perform the iteration. */\n\n if (skipping) continue;\n while ((iterate_item = string_nextinlist(&list, &sep, NULL, 0)) != NULL)\n {\n *outsep = (uschar)sep; /* Separator as a string */\n\n DEBUG(D_expand) debug_printf(\"%s: $item = \\\"%s\\\"\\n\", name, iterate_item);\n\n if (item_type == EITEM_FILTER)\n {\n BOOL condresult;\n if (eval_condition(expr, &resetok, &condresult) == NULL)\n {\n iterate_item = save_iterate_item;\n lookup_value = save_lookup_value;\n expand_string_message = string_sprintf(\"%s inside \\\"%s\\\" condition\",\n expand_string_message, name);\n goto EXPAND_FAILED;\n }\n DEBUG(D_expand) debug_printf(\"%s: condition is %s\\n\", name,\n condresult? \"true\":\"false\");\n if (condresult)\n temp = iterate_item; /* TRUE => include this item */\n else\n continue; /* FALSE => skip this item */\n }\n\n /* EITEM_MAP and EITEM_REDUCE */\n\n else\n {\n temp = expand_string_internal(expr, TRUE, NULL, skipping, TRUE, &resetok);\n if (temp == NULL)\n {\n iterate_item = save_iterate_item;\n expand_string_message = string_sprintf(\"%s inside \\\"%s\\\" item\",\n expand_string_message, name);\n goto EXPAND_FAILED;\n }\n if (item_type == EITEM_REDUCE)\n {\n lookup_value = temp; /* Update the value of $value */\n continue; /* and continue the iteration */\n }\n }\n\n /* We reach here for FILTER if the condition is true, always for MAP,\n and never for REDUCE. The value in \"temp\" is to be added to the output\n list that is being created, ensuring that any occurrences of the\n separator character are doubled. Unless we are dealing with the first\n item of the output list, add in a space if the new item begins with the\n separator character, or is an empty string. */\n\n if (ptr != save_ptr && (temp[0] == *outsep || temp[0] == 0))\n yield = string_cat(yield, &size, &ptr, US\" \", 1);\n\n /* Add the string in \"temp\" to the output list that we are building,\n This is done in chunks by searching for the separator character. */\n\n for (;;)\n {\n size_t seglen = Ustrcspn(temp, outsep);\n yield = string_cat(yield, &size, &ptr, temp, seglen + 1);\n\n /* If we got to the end of the string we output one character\n too many; backup and end the loop. Otherwise arrange to double the\n separator. */\n\n if (temp[seglen] == '\\0') { ptr--; break; }\n yield = string_cat(yield, &size, &ptr, outsep, 1);\n temp += seglen + 1;\n }\n\n /* Output a separator after the string: we will remove the redundant\n final one at the end. */\n\n yield = string_cat(yield, &size, &ptr, outsep, 1);\n } /* End of iteration over the list loop */\n\n /* REDUCE has generated no output above: output the final value of\n $value. */\n\n if (item_type == EITEM_REDUCE)\n {\n yield = string_cat(yield, &size, &ptr, lookup_value,\n Ustrlen(lookup_value));\n lookup_value = save_lookup_value; /* Restore $value */\n }\n\n /* FILTER and MAP generate lists: if they have generated anything, remove\n the redundant final separator. Even though an empty item at the end of a\n list does not count, this is tidier. */\n\n else if (ptr != save_ptr) ptr--;\n\n /* Restore preserved $item */\n\n iterate_item = save_iterate_item;\n continue;\n }\n\n\n /* If ${dlfunc } support is configured, handle calling dynamically-loaded\n functions, unless locked out at this time. Syntax is ${dlfunc{file}{func}}\n or ${dlfunc{file}{func}{arg}} or ${dlfunc{file}{func}{arg1}{arg2}} or up to\n a maximum of EXPAND_DLFUNC_MAX_ARGS arguments (defined below). */\n\n #define EXPAND_DLFUNC_MAX_ARGS 8\n\n case EITEM_DLFUNC:\n #ifndef EXPAND_DLFUNC\n expand_string_message = US\"\\\"${dlfunc\\\" encountered, but this facility \"\t/*}*/\n \"is not included in this binary\";\n goto EXPAND_FAILED;\n\n #else /* EXPAND_DLFUNC */\n {\n tree_node *t;\n exim_dlfunc_t *func;\n uschar *result;\n int status, argc;\n uschar *argv[EXPAND_DLFUNC_MAX_ARGS + 3];\n\n if ((expand_forbid & RDO_DLFUNC) != 0)\n {\n expand_string_message =\n US\"dynamically-loaded functions are not permitted\";\n goto EXPAND_FAILED;\n }\n\n switch(read_subs(argv, EXPAND_DLFUNC_MAX_ARGS + 2, 2, &s, skipping,\n TRUE, US\"dlfunc\", &resetok))\n {\n case 1: goto EXPAND_FAILED_CURLY;\n case 2:\n case 3: goto EXPAND_FAILED;\n }\n\n /* If skipping, we don't actually do anything */\n\n if (skipping) continue;\n\n /* Look up the dynamically loaded object handle in the tree. If it isn't\n found, dlopen() the file and put the handle in the tree for next time. */\n\n t = tree_search(dlobj_anchor, argv[0]);\n if (t == NULL)\n {\n void *handle = dlopen(CS argv[0], RTLD_LAZY);\n if (handle == NULL)\n {\n expand_string_message = string_sprintf(\"dlopen \\\"%s\\\" failed: %s\",\n argv[0], dlerror());\n log_write(0, LOG_MAIN|LOG_PANIC, \"%s\", expand_string_message);\n goto EXPAND_FAILED;\n }\n t = store_get_perm(sizeof(tree_node) + Ustrlen(argv[0]));\n Ustrcpy(t->name, argv[0]);\n t->data.ptr = handle;\n (void)tree_insertnode(&dlobj_anchor, t);\n }\n\n /* Having obtained the dynamically loaded object handle, look up the\n function pointer. */\n\n func = (exim_dlfunc_t *)dlsym(t->data.ptr, CS argv[1]);\n if (func == NULL)\n {\n expand_string_message = string_sprintf(\"dlsym \\\"%s\\\" in \\\"%s\\\" failed: \"\n \"%s\", argv[1], argv[0], dlerror());\n log_write(0, LOG_MAIN|LOG_PANIC, \"%s\", expand_string_message);\n goto EXPAND_FAILED;\n }\n\n /* Call the function and work out what to do with the result. If it\n returns OK, we have a replacement string; if it returns DEFER then\n expansion has failed in a non-forced manner; if it returns FAIL then\n failure was forced; if it returns ERROR or any other value there's a\n problem, so panic slightly. In any case, assume that the function has\n side-effects on the store that must be preserved. */\n\n resetok = FALSE;\n result = NULL;\n for (argc = 0; argv[argc] != NULL; argc++);\n status = func(&result, argc - 2, &argv[2]);\n if(status == OK)\n {\n if (result == NULL) result = US\"\";\n yield = string_cat(yield, &size, &ptr, result, Ustrlen(result));\n continue;\n }\n else\n {\n expand_string_message = result == NULL ? US\"(no message)\" : result;\n if(status == FAIL_FORCED) expand_string_forcedfail = TRUE;\n else if(status != FAIL)\n log_write(0, LOG_MAIN|LOG_PANIC, \"dlfunc{%s}{%s} failed (%d): %s\",\n argv[0], argv[1], status, expand_string_message);\n goto EXPAND_FAILED;\n }\n }\n #endif /* EXPAND_DLFUNC */\n }\t/* EITEM_* switch */\n\n /* Control reaches here if the name is not recognized as one of the more\n complicated expansion items. Check for the \"operator\" syntax (name terminated\n by a colon). Some of the operators have arguments, separated by _ from the\n name. */\n\n if (*s == ':')\n {\n int c;\n uschar *arg = NULL;\n uschar *sub;\n var_entry *vp = NULL;\n\n /* Owing to an historical mis-design, an underscore may be part of the\n operator name, or it may introduce arguments. We therefore first scan the\n table of names that contain underscores. If there is no match, we cut off\n the arguments and then scan the main table. */\n\n if ((c = chop_match(name, op_table_underscore,\n\tsizeof(op_table_underscore)/sizeof(uschar *))) < 0)\n {\n arg = Ustrchr(name, '_');\n if (arg != NULL) *arg = 0;\n c = chop_match(name, op_table_main,\n sizeof(op_table_main)/sizeof(uschar *));\n if (c >= 0) c += sizeof(op_table_underscore)/sizeof(uschar *);\n if (arg != NULL) *arg++ = '_'; /* Put back for error messages */\n }\n\n /* Deal specially with operators that might take a certificate variable\n as we do not want to do the usual expansion. For most, expand the string.*/\n switch(c)\n {\n#ifdef SUPPORT_TLS\n case EOP_MD5:\n case EOP_SHA1:\n case EOP_SHA256:\n\tif (s[1] == '$')\n\t {\n\t uschar * s1 = s;\n\t sub = expand_string_internal(s+2, TRUE, &s1, skipping,\n\t\t FALSE, &resetok);\n\t if (!sub) goto EXPAND_FAILED;\t\t/*{*/\n\t if (*s1 != '}') goto EXPAND_FAILED_CURLY;\n\t if ((vp = find_var_ent(sub)) && vp->type == vtype_cert)\n\t {\n\t s = s1+1;\n\t break;\n\t }\n\t vp = NULL;\n\t }\n /*FALLTHROUGH*/\n#endif\n default:\n\tsub = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok);\n\tif (!sub) goto EXPAND_FAILED;\n\ts++;\n\tbreak;\n }\n\n /* If we are skipping, we don't need to perform the operation at all.\n This matters for operations like \"mask\", because the data may not be\n in the correct format when skipping. For example, the expression may test\n for the existence of $sender_host_address before trying to mask it. For\n other operations, doing them may not fail, but it is a waste of time. */\n\n if (skipping && c >= 0) continue;\n\n /* Otherwise, switch on the operator type */\n\n switch(c)\n {\n case EOP_BASE62:\n {\n uschar *t;\n unsigned long int n = Ustrtoul(sub, &t, 10);\n if (*t != 0)\n {\n expand_string_message = string_sprintf(\"argument for base62 \"\n \"operator is \\\"%s\\\", which is not a decimal number\", sub);\n goto EXPAND_FAILED;\n }\n t = string_base62(n);\n yield = string_cat(yield, &size, &ptr, t, Ustrlen(t));\n continue;\n }\n\n /* Note that for Darwin and Cygwin, BASE_62 actually has the value 36 */\n\n case EOP_BASE62D:\n {\n uschar buf[16];\n uschar *tt = sub;\n unsigned long int n = 0;\n while (*tt != 0)\n {\n uschar *t = Ustrchr(base62_chars, *tt++);\n if (t == NULL)\n {\n expand_string_message = string_sprintf(\"argument for base62d \"\n \"operator is \\\"%s\\\", which is not a base %d number\", sub,\n BASE_62);\n goto EXPAND_FAILED;\n }\n n = n * BASE_62 + (t - base62_chars);\n }\n (void)sprintf(CS buf, \"%ld\", n);\n yield = string_cat(yield, &size, &ptr, buf, Ustrlen(buf));\n continue;\n }\n\n case EOP_EXPAND:\n {\n uschar *expanded = expand_string_internal(sub, FALSE, NULL, skipping, TRUE, &resetok);\n if (expanded == NULL)\n {\n expand_string_message =\n string_sprintf(\"internal expansion of \\\"%s\\\" failed: %s\", sub,\n expand_string_message);\n goto EXPAND_FAILED;\n }\n yield = string_cat(yield, &size, &ptr, expanded, Ustrlen(expanded));\n continue;\n }\n\n case EOP_LC:\n {\n int count = 0;\n uschar *t = sub - 1;\n while (*(++t) != 0) { *t = tolower(*t); count++; }\n yield = string_cat(yield, &size, &ptr, sub, count);\n continue;\n }\n\n case EOP_UC:\n {\n int count = 0;\n uschar *t = sub - 1;\n while (*(++t) != 0) { *t = toupper(*t); count++; }\n yield = string_cat(yield, &size, &ptr, sub, count);\n continue;\n }\n\n case EOP_MD5:\n#ifdef SUPPORT_TLS\n\tif (vp && *(void **)vp->value)\n\t {\n\t uschar * cp = tls_cert_fprt_md5(*(void **)vp->value);\n\t yield = string_cat(yield, &size, &ptr, cp, Ustrlen(cp));\n\t }\n\telse\n#endif\n\t {\n\t md5 base;\n\t uschar digest[16];\n\t int j;\n\t char st[33];\n\t md5_start(&base);\n\t md5_end(&base, sub, Ustrlen(sub), digest);\n\t for(j = 0; j < 16; j++) sprintf(st+2*j, \"%02x\", digest[j]);\n\t yield = string_cat(yield, &size, &ptr, US st, (int)strlen(st));\n\t }\n continue;\n\n case EOP_SHA1:\n#ifdef SUPPORT_TLS\n\tif (vp && *(void **)vp->value)\n\t {\n\t uschar * cp = tls_cert_fprt_sha1(*(void **)vp->value);\n\t yield = string_cat(yield, &size, &ptr, cp, Ustrlen(cp));\n\t }\n\telse\n#endif\n\t {\n\t sha1 base;\n\t uschar digest[20];\n\t int j;\n\t char st[41];\n\t sha1_start(&base);\n\t sha1_end(&base, sub, Ustrlen(sub), digest);\n\t for(j = 0; j < 20; j++) sprintf(st+2*j, \"%02X\", digest[j]);\n\t yield = string_cat(yield, &size, &ptr, US st, (int)strlen(st));\n\t }\n continue;\n\n case EOP_SHA256:\n#ifdef SUPPORT_TLS\n\tif (vp && *(void **)vp->value)\n\t {\n\t uschar * cp = tls_cert_fprt_sha256(*(void **)vp->value);\n\t yield = string_cat(yield, &size, &ptr, cp, (int)Ustrlen(cp));\n\t }\n\telse\n#endif\n\t expand_string_message = US\"sha256 only supported for certificates\";\n continue;\n\n /* Convert hex encoding to base64 encoding */\n\n case EOP_HEX2B64:\n {\n int c = 0;\n int b = -1;\n uschar *in = sub;\n uschar *out = sub;\n uschar *enc;\n\n for (enc = sub; *enc != 0; enc++)\n {\n if (!isxdigit(*enc))\n {\n expand_string_message = string_sprintf(\"\\\"%s\\\" is not a hex \"\n \"string\", sub);\n goto EXPAND_FAILED;\n }\n c++;\n }\n\n if ((c & 1) != 0)\n {\n expand_string_message = string_sprintf(\"\\\"%s\\\" contains an odd \"\n \"number of characters\", sub);\n goto EXPAND_FAILED;\n }\n\n while ((c = *in++) != 0)\n {\n if (isdigit(c)) c -= '0';\n else c = toupper(c) - 'A' + 10;\n if (b == -1)\n {\n b = c << 4;\n }\n else\n {\n *out++ = b | c;\n b = -1;\n }\n }\n\n enc = auth_b64encode(sub, out - sub);\n yield = string_cat(yield, &size, &ptr, enc, Ustrlen(enc));\n continue;\n }\n\n /* Convert octets outside 0x21..0x7E to \\xXX form */\n\n case EOP_HEXQUOTE:\n\t{\n uschar *t = sub - 1;\n while (*(++t) != 0)\n {\n if (*t < 0x21 || 0x7E < *t)\n yield = string_cat(yield, &size, &ptr,\n\t string_sprintf(\"\\\\x%02x\", *t), 4);\n\t else\n\t yield = string_cat(yield, &size, &ptr, t, 1);\n }\n\tcontinue;\n\t}\n\n /* count the number of list elements */\n\n case EOP_LISTCOUNT:\n {\n\tint cnt = 0;\n\tint sep = 0;\n\tuschar * cp;\n\tuschar buffer[256];\n\n\twhile (string_nextinlist(&sub, &sep, buffer, sizeof(buffer)) != NULL) cnt++;\n\tcp = string_sprintf(\"%d\", cnt);\n yield = string_cat(yield, &size, &ptr, cp, Ustrlen(cp));\n continue;\n }\n\n /* expand a named list given the name */\n /* handles nested named lists; requotes as colon-sep list */\n\n case EOP_LISTNAMED:\n\t{\n\ttree_node *t = NULL;\n\tuschar * list;\n\tint sep = 0;\n\tuschar * item;\n\tuschar * suffix = US\"\";\n\tBOOL needsep = FALSE;\n\tuschar buffer[256];\n\n\tif (*sub == '+') sub++;\n\tif (arg == NULL)\t/* no-argument version */\n\t {\n\t if (!(t = tree_search(addresslist_anchor, sub)) &&\n\t !(t = tree_search(domainlist_anchor, sub)) &&\n\t !(t = tree_search(hostlist_anchor, sub)))\n\t t = tree_search(localpartlist_anchor, sub);\n\t }\n\telse switch(*arg)\t/* specific list-type version */\n\t {\n\t case 'a': t = tree_search(addresslist_anchor, sub); suffix = US\"_a\"; break;\n\t case 'd': t = tree_search(domainlist_anchor, sub); suffix = US\"_d\"; break;\n\t case 'h': t = tree_search(hostlist_anchor, sub); suffix = US\"_h\"; break;\n\t case 'l': t = tree_search(localpartlist_anchor, sub); suffix = US\"_l\"; break;\n\t default:\n expand_string_message = string_sprintf(\"bad suffix on \\\"list\\\" operator\");\n\t goto EXPAND_FAILED;\n\t }\n\n\tif(!t)\n\t {\n expand_string_message = string_sprintf(\"\\\"%s\\\" is not a %snamed list\",\n sub, !arg?\"\"\n\t : *arg=='a'?\"address \"\n\t : *arg=='d'?\"domain \"\n\t : *arg=='h'?\"host \"\n\t : *arg=='l'?\"localpart \"\n\t : 0);\n\t goto EXPAND_FAILED;\n\t }\n\n\tlist = ((namedlist_block *)(t->data.ptr))->string;\n\n\twhile ((item = string_nextinlist(&list, &sep, buffer, sizeof(buffer))) != NULL)\n\t {\n\t uschar * buf = US\" : \";\n\t if (needsep)\n\t yield = string_cat(yield, &size, &ptr, buf, 3);\n\t else\n\t needsep = TRUE;\n\n\t if (*item == '+')\t/* list item is itself a named list */\n\t {\n\t uschar * sub = string_sprintf(\"${listnamed%s:%s}\", suffix, item);\n\t item = expand_string_internal(sub, FALSE, NULL, FALSE, TRUE, &resetok);\n\t }\n\t else if (sep != ':')\t/* item from non-colon-sep list, re-quote for colon list-separator */\n\t {\n\t char * cp;\n\t char tok[3];\n\t tok[0] = sep; tok[1] = ':'; tok[2] = 0;\n\t while ((cp= strpbrk((const char *)item, tok)))\n\t {\n yield = string_cat(yield, &size, &ptr, item, cp-(char *)item);\n\t if (*cp++ == ':')\t/* colon in a non-colon-sep list item, needs doubling */\n\t {\n yield = string_cat(yield, &size, &ptr, US\"::\", 2);\n\t item = (uschar *)cp;\n\t\t}\n\t else\t\t/* sep in item; should already be doubled; emit once */\n\t {\n yield = string_cat(yield, &size, &ptr, (uschar *)tok, 1);\n\t\tif (*cp == sep) cp++;\n\t item = (uschar *)cp;\n\t\t}\n\t }\n\t }\n yield = string_cat(yield, &size, &ptr, item, Ustrlen(item));\n\t }\n continue;\n\t}\n\n /* mask applies a mask to an IP address; for example the result of\n ${mask:131.111.10.206/28} is 131.111.10.192/28. */\n\n case EOP_MASK:\n {\n int count;\n uschar *endptr;\n int binary[4];\n int mask, maskoffset;\n int type = string_is_ip_address(sub, &maskoffset);\n uschar buffer[64];\n\n if (type == 0)\n {\n expand_string_message = string_sprintf(\"\\\"%s\\\" is not an IP address\",\n sub);\n goto EXPAND_FAILED;\n }\n\n if (maskoffset == 0)\n {\n expand_string_message = string_sprintf(\"missing mask value in \\\"%s\\\"\",\n sub);\n goto EXPAND_FAILED;\n }\n\n mask = Ustrtol(sub + maskoffset + 1, &endptr, 10);\n\n if (*endptr != 0 || mask < 0 || mask > ((type == 4)? 32 : 128))\n {\n expand_string_message = string_sprintf(\"mask value too big in \\\"%s\\\"\",\n sub);\n goto EXPAND_FAILED;\n }\n\n /* Convert the address to binary integer(s) and apply the mask */\n\n sub[maskoffset] = 0;\n count = host_aton(sub, binary);\n host_mask(count, binary, mask);\n\n /* Convert to masked textual format and add to output. */\n\n yield = string_cat(yield, &size, &ptr, buffer,\n host_nmtoa(count, binary, mask, buffer, '.'));\n continue;\n }\n\n case EOP_ADDRESS:\n case EOP_LOCAL_PART:\n case EOP_DOMAIN:\n {\n uschar *error;\n int start, end, domain;\n uschar *t = parse_extract_address(sub, &error, &start, &end, &domain,\n FALSE);\n if (t != NULL)\n {\n if (c != EOP_DOMAIN)\n {\n if (c == EOP_LOCAL_PART && domain != 0) end = start + domain - 1;\n yield = string_cat(yield, &size, &ptr, sub+start, end-start);\n }\n else if (domain != 0)\n {\n domain += start;\n yield = string_cat(yield, &size, &ptr, sub+domain, end-domain);\n }\n }\n continue;\n }\n\n case EOP_ADDRESSES:\n {\n uschar outsep[2] = { ':', '\\0' };\n uschar *address, *error;\n int save_ptr = ptr;\n int start, end, domain; /* Not really used */\n\n while (isspace(*sub)) sub++;\n if (*sub == '>') { *outsep = *++sub; ++sub; }\n parse_allow_group = TRUE;\n\n for (;;)\n {\n uschar *p = parse_find_address_end(sub, FALSE);\n uschar saveend = *p;\n *p = '\\0';\n address = parse_extract_address(sub, &error, &start, &end, &domain,\n FALSE);\n *p = saveend;\n\n /* Add the address to the output list that we are building. This is\n done in chunks by searching for the separator character. At the\n start, unless we are dealing with the first address of the output\n list, add in a space if the new address begins with the separator\n character, or is an empty string. */\n\n if (address != NULL)\n {\n if (ptr != save_ptr && address[0] == *outsep)\n yield = string_cat(yield, &size, &ptr, US\" \", 1);\n\n for (;;)\n {\n size_t seglen = Ustrcspn(address, outsep);\n yield = string_cat(yield, &size, &ptr, address, seglen + 1);\n\n /* If we got to the end of the string we output one character\n too many. */\n\n if (address[seglen] == '\\0') { ptr--; break; }\n yield = string_cat(yield, &size, &ptr, outsep, 1);\n address += seglen + 1;\n }\n\n /* Output a separator after the string: we will remove the\n redundant final one at the end. */\n\n yield = string_cat(yield, &size, &ptr, outsep, 1);\n }\n\n if (saveend == '\\0') break;\n sub = p + 1;\n }\n\n /* If we have generated anything, remove the redundant final\n separator. */\n\n if (ptr != save_ptr) ptr--;\n parse_allow_group = FALSE;\n continue;\n }\n\n\n /* quote puts a string in quotes if it is empty or contains anything\n other than alphamerics, underscore, dot, or hyphen.\n\n quote_local_part puts a string in quotes if RFC 2821/2822 requires it to\n be quoted in order to be a valid local part.\n\n In both cases, newlines and carriage returns are converted into \\n and \\r\n respectively */\n\n case EOP_QUOTE:\n case EOP_QUOTE_LOCAL_PART:\n if (arg == NULL)\n {\n BOOL needs_quote = (*sub == 0); /* TRUE for empty string */\n uschar *t = sub - 1;\n\n if (c == EOP_QUOTE)\n {\n while (!needs_quote && *(++t) != 0)\n needs_quote = !isalnum(*t) && !strchr(\"_-.\", *t);\n }\n else /* EOP_QUOTE_LOCAL_PART */\n {\n while (!needs_quote && *(++t) != 0)\n needs_quote = !isalnum(*t) &&\n strchr(\"!#$%&'*+-/=?^_`{|}~\", *t) == NULL &&\n (*t != '.' || t == sub || t[1] == 0);\n }\n\n if (needs_quote)\n {\n yield = string_cat(yield, &size, &ptr, US\"\\\"\", 1);\n t = sub - 1;\n while (*(++t) != 0)\n {\n if (*t == '\\n')\n yield = string_cat(yield, &size, &ptr, US\"\\\\n\", 2);\n else if (*t == '\\r')\n yield = string_cat(yield, &size, &ptr, US\"\\\\r\", 2);\n else\n {\n if (*t == '\\\\' || *t == '\"')\n yield = string_cat(yield, &size, &ptr, US\"\\\\\", 1);\n yield = string_cat(yield, &size, &ptr, t, 1);\n }\n }\n yield = string_cat(yield, &size, &ptr, US\"\\\"\", 1);\n }\n else yield = string_cat(yield, &size, &ptr, sub, Ustrlen(sub));\n continue;\n }\n\n /* quote_lookuptype does lookup-specific quoting */\n\n else\n {\n int n;\n uschar *opt = Ustrchr(arg, '_');\n\n if (opt != NULL) *opt++ = 0;\n\n n = search_findtype(arg, Ustrlen(arg));\n if (n < 0)\n {\n expand_string_message = search_error_message;\n goto EXPAND_FAILED;\n }\n\n if (lookup_list[n]->quote != NULL)\n sub = (lookup_list[n]->quote)(sub, opt);\n else if (opt != NULL) sub = NULL;\n\n if (sub == NULL)\n {\n expand_string_message = string_sprintf(\n \"\\\"%s\\\" unrecognized after \\\"${quote_%s\\\"\",\n opt, arg);\n goto EXPAND_FAILED;\n }\n\n yield = string_cat(yield, &size, &ptr, sub, Ustrlen(sub));\n continue;\n }\n\n /* rx quote sticks in \\ before any non-alphameric character so that\n the insertion works in a regular expression. */\n\n case EOP_RXQUOTE:\n {\n uschar *t = sub - 1;\n while (*(++t) != 0)\n {\n if (!isalnum(*t))\n yield = string_cat(yield, &size, &ptr, US\"\\\\\", 1);\n yield = string_cat(yield, &size, &ptr, t, 1);\n }\n continue;\n }\n\n /* RFC 2047 encodes, assuming headers_charset (default ISO 8859-1) as\n prescribed by the RFC, if there are characters that need to be encoded */\n\n case EOP_RFC2047:\n {\n uschar buffer[2048];\n uschar *string = parse_quote_2047(sub, Ustrlen(sub), headers_charset,\n buffer, sizeof(buffer), FALSE);\n yield = string_cat(yield, &size, &ptr, string, Ustrlen(string));\n continue;\n }\n\n /* RFC 2047 decode */\n\n case EOP_RFC2047D:\n {\n int len;\n uschar *error;\n uschar *decoded = rfc2047_decode(sub, check_rfc2047_length,\n headers_charset, '?', &len, &error);\n if (error != NULL)\n {\n expand_string_message = error;\n goto EXPAND_FAILED;\n }\n yield = string_cat(yield, &size, &ptr, decoded, len);\n continue;\n }\n\n /* from_utf8 converts UTF-8 to 8859-1, turning non-existent chars into\n underscores */\n\n case EOP_FROM_UTF8:\n {\n while (*sub != 0)\n {\n int c;\n uschar buff[4];\n GETUTF8INC(c, sub);\n if (c > 255) c = '_';\n buff[0] = c;\n yield = string_cat(yield, &size, &ptr, buff, 1);\n }\n continue;\n }\n\n\t /* replace illegal UTF-8 sequences by replacement character */\n\t \n #define UTF8_REPLACEMENT_CHAR US\"?\"\n\n case EOP_UTF8CLEAN:\n {\n int seq_len, index = 0;\n int bytes_left = 0;\n uschar seq_buff[4];\t\t\t/* accumulate utf-8 here */\n \n while (*sub != 0)\n\t {\n\t int complete;\n\t long codepoint;\n\t uschar c;\n\n\t complete = 0;\n\t c = *sub++;\n\t if (bytes_left)\n\t {\n\t if ((c & 0xc0) != 0x80)\n\t {\n\t\t /* wrong continuation byte; invalidate all bytes */\n\t complete = 1; /* error */\n\t }\n\t else\n\t {\n\t codepoint = (codepoint << 6) | (c & 0x3f);\n\t seq_buff[index++] = c;\n\t if (--bytes_left == 0)\t\t/* codepoint complete */\n\t\t{\n\t\tif(codepoint > 0x10FFFF)\t/* is it too large? */\n\t\t complete = -1;\t/* error */\n\t\telse\n\t\t {\t\t/* finished; output utf-8 sequence */\n\t\t yield = string_cat(yield, &size, &ptr, seq_buff, seq_len);\n\t\t index = 0;\n\t\t }\n\t\t}\n\t }\n\t }\n\t else\t/* no bytes left: new sequence */\n\t {\n\t if((c & 0x80) == 0)\t/* 1-byte sequence, US-ASCII, keep it */\n\t {\n\t yield = string_cat(yield, &size, &ptr, &c, 1);\n\t continue;\n\t }\n\t if((c & 0xe0) == 0xc0)\t\t/* 2-byte sequence */\n\t {\n\t if(c == 0xc0 || c == 0xc1)\t/* 0xc0 and 0xc1 are illegal */\n\t\tcomplete = -1;\n\t else\n\t\t{\n\t\t bytes_left = 1;\n\t\t codepoint = c & 0x1f;\n\t\t}\n\t }\n\t else if((c & 0xf0) == 0xe0)\t\t/* 3-byte sequence */\n\t {\n\t bytes_left = 2;\n\t codepoint = c & 0x0f;\n\t }\n\t else if((c & 0xf8) == 0xf0)\t\t/* 4-byte sequence */\n\t {\n\t bytes_left = 3;\n\t codepoint = c & 0x07;\n\t }\n\t else\t/* invalid or too long (RFC3629 allows only 4 bytes) */\n\t complete = -1;\n\n\t seq_buff[index++] = c;\n\t seq_len = bytes_left + 1;\n\t }\t\t/* if(bytes_left) */\n\n\t if (complete != 0)\n\t {\n\t bytes_left = index = 0;\n\t yield = string_cat(yield, &size, &ptr, UTF8_REPLACEMENT_CHAR, 1);\n\t }\n\t if ((complete == 1) && ((c & 0x80) == 0))\n\t { /* ASCII character follows incomplete sequence */\n\t yield = string_cat(yield, &size, &ptr, &c, 1);\n\t }\n\t }\n continue;\n }\n\n /* escape turns all non-printing characters into escape sequences. */\n\n case EOP_ESCAPE:\n {\n uschar *t = string_printing(sub);\n yield = string_cat(yield, &size, &ptr, t, Ustrlen(t));\n continue;\n }\n\n /* Handle numeric expression evaluation */\n\n case EOP_EVAL:\n case EOP_EVAL10:\n {\n uschar *save_sub = sub;\n uschar *error = NULL;\n int_eximarith_t n = eval_expr(&sub, (c == EOP_EVAL10), &error, FALSE);\n if (error != NULL)\n {\n expand_string_message = string_sprintf(\"error in expression \"\n \"evaluation: %s (after processing \\\"%.*s\\\")\", error, sub-save_sub,\n save_sub);\n goto EXPAND_FAILED;\n }\n sprintf(CS var_buffer, PR_EXIM_ARITH, n);\n yield = string_cat(yield, &size, &ptr, var_buffer, Ustrlen(var_buffer));\n continue;\n }\n\n /* Handle time period formating */\n\n case EOP_TIME_EVAL:\n {\n int n = readconf_readtime(sub, 0, FALSE);\n if (n < 0)\n {\n expand_string_message = string_sprintf(\"string \\\"%s\\\" is not an \"\n \"Exim time interval in \\\"%s\\\" operator\", sub, name);\n goto EXPAND_FAILED;\n }\n sprintf(CS var_buffer, \"%d\", n);\n yield = string_cat(yield, &size, &ptr, var_buffer, Ustrlen(var_buffer));\n continue;\n }\n\n case EOP_TIME_INTERVAL:\n {\n int n;\n uschar *t = read_number(&n, sub);\n if (*t != 0) /* Not A Number*/\n {\n expand_string_message = string_sprintf(\"string \\\"%s\\\" is not a \"\n \"positive number in \\\"%s\\\" operator\", sub, name);\n goto EXPAND_FAILED;\n }\n t = readconf_printtime(n);\n yield = string_cat(yield, &size, &ptr, t, Ustrlen(t));\n continue;\n }\n\n /* Convert string to base64 encoding */\n\n case EOP_STR2B64:\n {\n uschar *encstr = auth_b64encode(sub, Ustrlen(sub));\n yield = string_cat(yield, &size, &ptr, encstr, Ustrlen(encstr));\n continue;\n }\n\n /* strlen returns the length of the string */\n\n case EOP_STRLEN:\n {\n uschar buff[24];\n (void)sprintf(CS buff, \"%d\", Ustrlen(sub));\n yield = string_cat(yield, &size, &ptr, buff, Ustrlen(buff));\n continue;\n }\n\n /* length_n or l_n takes just the first n characters or the whole string,\n whichever is the shorter;\n\n substr_m_n, and s_m_n take n characters from offset m; negative m take\n from the end; l_n is synonymous with s_0_n. If n is omitted in substr it\n takes the rest, either to the right or to the left.\n\n hash_n or h_n makes a hash of length n from the string, yielding n\n characters from the set a-z; hash_n_m makes a hash of length n, but\n uses m characters from the set a-zA-Z0-9.\n\n nhash_n returns a single number between 0 and n-1 (in text form), while\n nhash_n_m returns a div/mod hash as two numbers \"a/b\". The first lies\n between 0 and n-1 and the second between 0 and m-1. */\n\n case EOP_LENGTH:\n case EOP_L:\n case EOP_SUBSTR:\n case EOP_S:\n case EOP_HASH:\n case EOP_H:\n case EOP_NHASH:\n case EOP_NH:\n {\n int sign = 1;\n int value1 = 0;\n int value2 = -1;\n int *pn;\n int len;\n uschar *ret;\n\n if (arg == NULL)\n {\n expand_string_message = string_sprintf(\"missing values after %s\",\n name);\n goto EXPAND_FAILED;\n }\n\n /* \"length\" has only one argument, effectively being synonymous with\n substr_0_n. */\n\n if (c == EOP_LENGTH || c == EOP_L)\n {\n pn = &value2;\n value2 = 0;\n }\n\n /* The others have one or two arguments; for \"substr\" the first may be\n negative. The second being negative means \"not supplied\". */\n\n else\n {\n pn = &value1;\n if (name[0] == 's' && *arg == '-') { sign = -1; arg++; }\n }\n\n /* Read up to two numbers, separated by underscores */\n\n ret = arg;\n while (*arg != 0)\n {\n if (arg != ret && *arg == '_' && pn == &value1)\n {\n pn = &value2;\n value2 = 0;\n if (arg[1] != 0) arg++;\n }\n else if (!isdigit(*arg))\n {\n expand_string_message =\n string_sprintf(\"non-digit after underscore in \\\"%s\\\"\", name);\n goto EXPAND_FAILED;\n }\n else *pn = (*pn)*10 + *arg++ - '0';\n }\n value1 *= sign;\n\n /* Perform the required operation */\n\n ret =\n (c == EOP_HASH || c == EOP_H)?\n compute_hash(sub, value1, value2, &len) :\n (c == EOP_NHASH || c == EOP_NH)?\n compute_nhash(sub, value1, value2, &len) :\n extract_substr(sub, value1, value2, &len);\n\n if (ret == NULL) goto EXPAND_FAILED;\n yield = string_cat(yield, &size, &ptr, ret, len);\n continue;\n }\n\n /* Stat a path */\n\n case EOP_STAT:\n {\n uschar *s;\n uschar smode[12];\n uschar **modetable[3];\n int i;\n mode_t mode;\n struct stat st;\n\n if ((expand_forbid & RDO_EXISTS) != 0)\n {\n expand_string_message = US\"Use of the stat() expansion is not permitted\";\n goto EXPAND_FAILED;\n }\n\n if (stat(CS sub, &st) < 0)\n {\n expand_string_message = string_sprintf(\"stat(%s) failed: %s\",\n sub, strerror(errno));\n goto EXPAND_FAILED;\n }\n mode = st.st_mode;\n switch (mode & S_IFMT)\n {\n case S_IFIFO: smode[0] = 'p'; break;\n case S_IFCHR: smode[0] = 'c'; break;\n case S_IFDIR: smode[0] = 'd'; break;\n case S_IFBLK: smode[0] = 'b'; break;\n case S_IFREG: smode[0] = '-'; break;\n default: smode[0] = '?'; break;\n }\n\n modetable[0] = ((mode & 01000) == 0)? mtable_normal : mtable_sticky;\n modetable[1] = ((mode & 02000) == 0)? mtable_normal : mtable_setid;\n modetable[2] = ((mode & 04000) == 0)? mtable_normal : mtable_setid;\n\n for (i = 0; i < 3; i++)\n {\n memcpy(CS(smode + 7 - i*3), CS(modetable[i][mode & 7]), 3);\n mode >>= 3;\n }\n\n smode[10] = 0;\n s = string_sprintf(\"mode=%04lo smode=%s inode=%ld device=%ld links=%ld \"\n \"uid=%ld gid=%ld size=\" OFF_T_FMT \" atime=%ld mtime=%ld ctime=%ld\",\n (long)(st.st_mode & 077777), smode, (long)st.st_ino,\n (long)st.st_dev, (long)st.st_nlink, (long)st.st_uid,\n (long)st.st_gid, st.st_size, (long)st.st_atime,\n (long)st.st_mtime, (long)st.st_ctime);\n yield = string_cat(yield, &size, &ptr, s, Ustrlen(s));\n continue;\n }\n\n /* vaguely random number less than N */\n\n case EOP_RANDINT:\n {\n int_eximarith_t max;\n uschar *s;\n\n max = expand_string_integer(sub, TRUE);\n if (expand_string_message != NULL)\n goto EXPAND_FAILED;\n s = string_sprintf(\"%d\", vaguely_random_number((int)max));\n yield = string_cat(yield, &size, &ptr, s, Ustrlen(s));\n continue;\n }\n\n /* Reverse IP, including IPv6 to dotted-nibble */\n\n case EOP_REVERSE_IP:\n {\n int family, maskptr;\n uschar reversed[128];\n\n family = string_is_ip_address(sub, &maskptr);\n if (family == 0)\n {\n expand_string_message = string_sprintf(\n \"reverse_ip() not given an IP address [%s]\", sub);\n goto EXPAND_FAILED;\n }\n invert_address(reversed, sub);\n yield = string_cat(yield, &size, &ptr, reversed, Ustrlen(reversed));\n continue;\n }\n\n /* Unknown operator */\n\n default:\n expand_string_message =\n string_sprintf(\"unknown expansion operator \\\"%s\\\"\", name);\n goto EXPAND_FAILED;\n }\n }\n\n /* Handle a plain name. If this is the first thing in the expansion, release\n the pre-allocated buffer. If the result data is known to be in a new buffer,\n newsize will be set to the size of that buffer, and we can just point at that\n store instead of copying. Many expansion strings contain just one reference,\n so this is a useful optimization, especially for humungous headers\n ($message_headers). */\n\t\t\t\t\t\t/*{*/\n if (*s++ == '}')\n {\n int len;\n int newsize = 0;\n if (ptr == 0)\n {\n if (resetok) store_reset(yield);\n yield = NULL;\n size = 0;\n }\n value = find_variable(name, FALSE, skipping, &newsize);\n if (value == NULL)\n {\n expand_string_message =\n string_sprintf(\"unknown variable in \\\"${%s}\\\"\", name);\n check_variable_error_message(name);\n goto EXPAND_FAILED;\n }\n len = Ustrlen(value);\n if (yield == NULL && newsize != 0)\n {\n yield = value;\n size = newsize;\n ptr = len;\n }\n else yield = string_cat(yield, &size, &ptr, value, len);\n continue;\n }\n\n /* Else there's something wrong */\n\n expand_string_message =\n string_sprintf(\"\\\"${%s\\\" is not a known operator (or a } is missing \"\n \"in a variable reference)\", name);\n goto EXPAND_FAILED;\n }\n\n/* If we hit the end of the string when ket_ends is set, there is a missing\nterminating brace. */\n\nif (ket_ends && *s == 0)\n {\n expand_string_message = malformed_header?\n US\"missing } at end of string - could be header name not terminated by colon\"\n :\n US\"missing } at end of string\";\n goto EXPAND_FAILED;\n }\n\n/* Expansion succeeded; yield may still be NULL here if nothing was actually\nadded to the string. If so, set up an empty string. Add a terminating zero. If\nleft != NULL, return a pointer to the terminator. */\n\nif (yield == NULL) yield = store_get(1);\nyield[ptr] = 0;\nif (left != NULL) *left = s;\n\n/* Any stacking store that was used above the final string is no longer needed.\nIn many cases the final string will be the first one that was got and so there\nwill be optimal store usage. */\n\nif (resetok) store_reset(yield + ptr + 1);\nelse if (resetok_p) *resetok_p = FALSE;\n\nDEBUG(D_expand)\n {\n debug_printf(\"expanding: %.*s\\n result: %s\\n\", (int)(s - string), string,\n yield);\n if (skipping) debug_printf(\"skipping: result is not used\\n\");\n }\nreturn yield;\n\n/* This is the failure exit: easiest to program with a goto. We still need\nto update the pointer to the terminator, for cases of nested calls with \"fail\".\n*/\n\nEXPAND_FAILED_CURLY:\nexpand_string_message = malformed_header?\n US\"missing or misplaced { or } - could be header name not terminated by colon\"\n :\n US\"missing or misplaced { or }\";\n\n/* At one point, Exim reset the store to yield (if yield was not NULL), but\nthat is a bad idea, because expand_string_message is in dynamic store. */\n\nEXPAND_FAILED:\nif (left != NULL) *left = s;\nDEBUG(D_expand)\n {\n debug_printf(\"failed to expand: %s\\n\", string);\n debug_printf(\" error message: %s\\n\", expand_string_message);\n if (expand_string_forcedfail) debug_printf(\"failure was forced\\n\");\n }\nif (resetok_p) *resetok_p = resetok;\nreturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'Only expand integers for integer math once'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int do_remount(struct path *path, int flags, int mnt_flags,\n\t\t void *data)\n{\n\tint err;\n\tstruct super_block *sb = path->mnt->mnt_sb;\n\tstruct mount *mnt = real_mount(path->mnt);\n\n\tif (!check_mnt(mnt))\n\t\treturn -EINVAL;\n\n\tif (path->dentry != path->mnt->mnt_root)\n\t\treturn -EINVAL;\n\n\terr = security_sb_remount(sb, data);\n\tif (err)\n\t\treturn err;\n\n\tdown_write(&sb->s_umount);\n\tif (flags & MS_BIND)\n\t\terr = change_mount_flags(path->mnt, flags);\n\telse if (!capable(CAP_SYS_ADMIN))\n\t\terr = -EPERM;\n\telse\n\t\terr = do_remount_sb(sb, flags, data, 0);\n\tif (!err) {\n\t\tlock_mount_hash();\n\t\tmnt_flags |= mnt->mnt.mnt_flags & ~MNT_USER_SETTABLE_MASK;\n\t\tmnt->mnt.mnt_flags = mnt_flags;\n\t\ttouch_mnt_namespace(mnt->mnt_ns);\n\t\tunlock_mount_hash();\n\t}\n\tup_write(&sb->s_umount);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-269'], 'message': 'mnt: Move the test for MNT_LOCK_READONLY from change_mount_flags into do_remount\n\nThere are no races as locked mount flags are guaranteed to never change.\n\nMoving the test into do_remount makes it more visible, and ensures all\nfilesystem remounts pass the MNT_LOCK_READONLY permission check. This\nsecond case is not an issue today as filesystem remounts are guarded\nby capable(CAP_DAC_ADMIN) and thus will always fail in less privileged\nmount namespaces, but it could become an issue in the future.\n\nCc: stable@vger.kernel.org\nAcked-by: Serge E. Hallyn \nSigned-off-by: \"Eric W. Biederman\" '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void qemu_spice_create_host_primary(SimpleSpiceDisplay *ssd)\n{\n QXLDevSurfaceCreate surface;\n\n memset(&surface, 0, sizeof(surface));\n\n dprint(1, \"%s/%d: %dx%d\\n\", __func__, ssd->qxl.id,\n surface_width(ssd->ds), surface_height(ssd->ds));\n\n surface.format = SPICE_SURFACE_FMT_32_xRGB;\n surface.width = surface_width(ssd->ds);\n surface.height = surface_height(ssd->ds);\n surface.stride = -surface.width * 4;\n surface.mouse_mode = true;\n surface.flags = 0;\n surface.type = 0;\n surface.mem = (uintptr_t)ssd->buf;\n surface.group_id = MEMSLOT_GROUP_HOST;\n\n qemu_spice_create_primary_surface(ssd, 0, &surface, QXL_SYNC);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'spice: make sure we don't overflow ssd->buf\n\nRelated spice-only bug. We have a fixed 16 MB buffer here, being\npresented to the spice-server as qxl video memory in case spice is\nused with a non-qxl card. It's also used with qxl in vga mode.\n\nWhen using display resolutions requiring more than 16 MB of memory we\nare going to overflow that buffer. In theory the guest can write,\nindirectly via spice-server. The spice-server clears the memory after\nsetting a new video mode though, triggering a segfault in the overflow\ncase, so qemu crashes before the guest has a chance to do something\nevil.\n\nFix that by switching to dynamic allocation for the buffer.\n\nCVE-2014-3615\n\nCc: qemu-stable@nongnu.org\nCc: secalert@redhat.com\nSigned-off-by: Gerd Hoffmann \nReviewed-by: Laszlo Ersek '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: evbuffer_copyout(struct evbuffer *buf, void *data_out, size_t datlen)\n{\n\t/*XXX fails badly on sendfile case. */\n\tstruct evbuffer_chain *chain;\n\tchar *data = data_out;\n\tsize_t nread;\n\tev_ssize_t result = 0;\n\n\tEVBUFFER_LOCK(buf);\n\n\tchain = buf->first;\n\n\tif (datlen >= buf->total_len)\n\t\tdatlen = buf->total_len;\n\n\tif (datlen == 0)\n\t\tgoto done;\n\n\tif (buf->freeze_start) {\n\t\tresult = -1;\n\t\tgoto done;\n\t}\n\n\tnread = datlen;\n\n\twhile (datlen && datlen >= chain->off) {\n\t\tmemcpy(data, chain->buffer + chain->misalign, chain->off);\n\t\tdata += chain->off;\n\t\tdatlen -= chain->off;\n\n\t\tchain = chain->next;\n\t\tEVUTIL_ASSERT(chain || datlen==0);\n\t}\n\n\tif (datlen) {\n\t\tEVUTIL_ASSERT(chain);\n\t\tmemcpy(data, chain->buffer + chain->misalign, datlen);\n\t}\n\n\tresult = nread;\ndone:\n\tEVBUFFER_UNLOCK(buf);\n\treturn result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'Fix CVE-2014-6272 in Libevent 2.0\n\nFor this fix, we need to make sure that passing too-large inputs to\nthe evbuffer functions can't make us do bad things with the heap.\n\nAlso, lower the maximum chunk size to the lower of off_t, size_t maximum.\n\nThis is necessary since otherwise we could get into an infinite loop\nif we make a chunk that 'misalign' cannot index into.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: evbuffer_add_file(struct evbuffer *outbuf, int fd,\n ev_off_t offset, ev_off_t length)\n{\n#if defined(USE_SENDFILE) || defined(_EVENT_HAVE_MMAP)\n\tstruct evbuffer_chain *chain;\n\tstruct evbuffer_chain_fd *info;\n#endif\n#if defined(USE_SENDFILE)\n\tint sendfile_okay = 1;\n#endif\n\tint ok = 1;\n\n#if defined(USE_SENDFILE)\n\tif (use_sendfile) {\n\t\tEVBUFFER_LOCK(outbuf);\n\t\tsendfile_okay = outbuf->flags & EVBUFFER_FLAG_DRAINS_TO_FD;\n\t\tEVBUFFER_UNLOCK(outbuf);\n\t}\n\n\tif (use_sendfile && sendfile_okay) {\n\t\tchain = evbuffer_chain_new(sizeof(struct evbuffer_chain_fd));\n\t\tif (chain == NULL) {\n\t\t\tevent_warn(\"%s: out of memory\", __func__);\n\t\t\treturn (-1);\n\t\t}\n\n\t\tchain->flags |= EVBUFFER_SENDFILE | EVBUFFER_IMMUTABLE;\n\t\tchain->buffer = NULL;\t/* no reading possible */\n\t\tchain->buffer_len = length + offset;\n\t\tchain->off = length;\n\t\tchain->misalign = offset;\n\n\t\tinfo = EVBUFFER_CHAIN_EXTRA(struct evbuffer_chain_fd, chain);\n\t\tinfo->fd = fd;\n\n\t\tEVBUFFER_LOCK(outbuf);\n\t\tif (outbuf->freeze_end) {\n\t\t\tmm_free(chain);\n\t\t\tok = 0;\n\t\t} else {\n\t\t\toutbuf->n_add_for_cb += length;\n\t\t\tevbuffer_chain_insert(outbuf, chain);\n\t\t}\n\t} else\n#endif\n#if defined(_EVENT_HAVE_MMAP)\n\tif (use_mmap) {\n\t\tvoid *mapped = mmap(NULL, length + offset, PROT_READ,\n#ifdef MAP_NOCACHE\n\t\t MAP_NOCACHE |\n#endif\n#ifdef MAP_FILE\n\t\t MAP_FILE |\n#endif\n\t\t MAP_PRIVATE,\n\t\t fd, 0);\n\t\t/* some mmap implementations require offset to be a multiple of\n\t\t * the page size. most users of this api, are likely to use 0\n\t\t * so mapping everything is not likely to be a problem.\n\t\t * TODO(niels): determine page size and round offset to that\n\t\t * page size to avoid mapping too much memory.\n\t\t */\n\t\tif (mapped == MAP_FAILED) {\n\t\t\tevent_warn(\"%s: mmap(%d, %d, %zu) failed\",\n\t\t\t __func__, fd, 0, (size_t)(offset + length));\n\t\t\treturn (-1);\n\t\t}\n\t\tchain = evbuffer_chain_new(sizeof(struct evbuffer_chain_fd));\n\t\tif (chain == NULL) {\n\t\t\tevent_warn(\"%s: out of memory\", __func__);\n\t\t\tmunmap(mapped, length);\n\t\t\treturn (-1);\n\t\t}\n\n\t\tchain->flags |= EVBUFFER_MMAP | EVBUFFER_IMMUTABLE;\n\t\tchain->buffer = mapped;\n\t\tchain->buffer_len = length + offset;\n\t\tchain->off = length + offset;\n\n\t\tinfo = EVBUFFER_CHAIN_EXTRA(struct evbuffer_chain_fd, chain);\n\t\tinfo->fd = fd;\n\n\t\tEVBUFFER_LOCK(outbuf);\n\t\tif (outbuf->freeze_end) {\n\t\t\tinfo->fd = -1;\n\t\t\tevbuffer_chain_free(chain);\n\t\t\tok = 0;\n\t\t} else {\n\t\t\toutbuf->n_add_for_cb += length;\n\n\t\t\tevbuffer_chain_insert(outbuf, chain);\n\n\t\t\t/* we need to subtract whatever we don't need */\n\t\t\tevbuffer_drain(outbuf, offset);\n\t\t}\n\t} else\n#endif\n\t{\n\t\t/* the default implementation */\n\t\tstruct evbuffer *tmp = evbuffer_new();\n\t\tev_ssize_t read;\n\n\t\tif (tmp == NULL)\n\t\t\treturn (-1);\n\n#ifdef WIN32\n#define lseek _lseeki64\n#endif\n\t\tif (lseek(fd, offset, SEEK_SET) == -1) {\n\t\t\tevbuffer_free(tmp);\n\t\t\treturn (-1);\n\t\t}\n\n\t\t/* we add everything to a temporary buffer, so that we\n\t\t * can abort without side effects if the read fails.\n\t\t */\n\t\twhile (length) {\n\t\t\tread = evbuffer_readfile(tmp, fd, (ev_ssize_t)length);\n\t\t\tif (read == -1) {\n\t\t\t\tevbuffer_free(tmp);\n\t\t\t\treturn (-1);\n\t\t\t}\n\n\t\t\tlength -= read;\n\t\t}\n\n\t\tEVBUFFER_LOCK(outbuf);\n\t\tif (outbuf->freeze_end) {\n\t\t\tevbuffer_free(tmp);\n\t\t\tok = 0;\n\t\t} else {\n\t\t\tevbuffer_add_buffer(outbuf, tmp);\n\t\t\tevbuffer_free(tmp);\n\n#ifdef WIN32\n#define close _close\n#endif\n\t\t\tclose(fd);\n\t\t}\n\t}\n\n\tif (ok)\n\t\tevbuffer_invoke_callbacks(outbuf);\n\tEVBUFFER_UNLOCK(outbuf);\n\n\treturn ok ? 0 : -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'Fix CVE-2014-6272 in Libevent 2.0\n\nFor this fix, we need to make sure that passing too-large inputs to\nthe evbuffer functions can't make us do bad things with the heap.\n\nAlso, lower the maximum chunk size to the lower of off_t, size_t maximum.\n\nThis is necessary since otherwise we could get into an infinite loop\nif we make a chunk that 'misalign' cannot index into.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: evbuffer_read(struct evbuffer *buf, evutil_socket_t fd, int howmuch)\n{\n\tstruct evbuffer_chain **chainp;\n\tint n;\n\tint result;\n\n#ifdef USE_IOVEC_IMPL\n\tint nvecs, i, remaining;\n#else\n\tstruct evbuffer_chain *chain;\n\tunsigned char *p;\n#endif\n\n\tEVBUFFER_LOCK(buf);\n\n\tif (buf->freeze_end) {\n\t\tresult = -1;\n\t\tgoto done;\n\t}\n\n\tn = get_n_bytes_readable_on_socket(fd);\n\tif (n <= 0 || n > EVBUFFER_MAX_READ)\n\t\tn = EVBUFFER_MAX_READ;\n\tif (howmuch < 0 || howmuch > n)\n\t\thowmuch = n;\n\n#ifdef USE_IOVEC_IMPL\n\t/* Since we can use iovecs, we're willing to use the last\n\t * NUM_READ_IOVEC chains. */\n\tif (evbuffer_expand_fast_(buf, howmuch, NUM_READ_IOVEC) == -1) {\n\t\tresult = -1;\n\t\tgoto done;\n\t} else {\n\t\tIOV_TYPE vecs[NUM_READ_IOVEC];\n#ifdef EVBUFFER_IOVEC_IS_NATIVE_\n\t\tnvecs = evbuffer_read_setup_vecs_(buf, howmuch, vecs,\n\t\t NUM_READ_IOVEC, &chainp, 1);\n#else\n\t\t/* We aren't using the native struct iovec. Therefore,\n\t\t we are on win32. */\n\t\tstruct evbuffer_iovec ev_vecs[NUM_READ_IOVEC];\n\t\tnvecs = evbuffer_read_setup_vecs_(buf, howmuch, ev_vecs, 2,\n\t\t &chainp, 1);\n\n\t\tfor (i=0; i < nvecs; ++i)\n\t\t\tWSABUF_FROM_EVBUFFER_IOV(&vecs[i], &ev_vecs[i]);\n#endif\n\n#ifdef _WIN32\n\t\t{\n\t\t\tDWORD bytesRead;\n\t\t\tDWORD flags=0;\n\t\t\tif (WSARecv(fd, vecs, nvecs, &bytesRead, &flags, NULL, NULL)) {\n\t\t\t\t/* The read failed. It might be a close,\n\t\t\t\t * or it might be an error. */\n\t\t\t\tif (WSAGetLastError() == WSAECONNABORTED)\n\t\t\t\t\tn = 0;\n\t\t\t\telse\n\t\t\t\t\tn = -1;\n\t\t\t} else\n\t\t\t\tn = bytesRead;\n\t\t}\n#else\n\t\tn = readv(fd, vecs, nvecs);\n#endif\n\t}\n\n#else /*!USE_IOVEC_IMPL*/\n\t/* If we don't have FIONREAD, we might waste some space here */\n\t/* XXX we _will_ waste some space here if there is any space left\n\t * over on buf->last. */\n\tif ((chain = evbuffer_expand_singlechain(buf, howmuch)) == NULL) {\n\t\tresult = -1;\n\t\tgoto done;\n\t}\n\n\t/* We can append new data at this point */\n\tp = chain->buffer + chain->misalign + chain->off;\n\n#ifndef _WIN32\n\tn = read(fd, p, howmuch);\n#else\n\tn = recv(fd, p, howmuch, 0);\n#endif\n#endif /* USE_IOVEC_IMPL */\n\n\tif (n == -1) {\n\t\tresult = -1;\n\t\tgoto done;\n\t}\n\tif (n == 0) {\n\t\tresult = 0;\n\t\tgoto done;\n\t}\n\n#ifdef USE_IOVEC_IMPL\n\tremaining = n;\n\tfor (i=0; i < nvecs; ++i) {\n\t\tev_ssize_t space = (ev_ssize_t) CHAIN_SPACE_LEN(*chainp);\n\t\tif (space < remaining) {\n\t\t\t(*chainp)->off += space;\n\t\t\tremaining -= (int)space;\n\t\t} else {\n\t\t\t(*chainp)->off += remaining;\n\t\t\tbuf->last_with_datap = chainp;\n\t\t\tbreak;\n\t\t}\n\t\tchainp = &(*chainp)->next;\n\t}\n#else\n\tchain->off += n;\n\tadvance_last_with_data(buf);\n#endif\n\tbuf->total_len += n;\n\tbuf->n_add_for_cb += n;\n\n\t/* Tell someone about changes in this buffer */\n\tevbuffer_invoke_callbacks_(buf);\n\tresult = n;\ndone:\n\tEVBUFFER_UNLOCK(buf);\n\treturn result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'Fix CVE-2014-6272 in Libevent 2.1\n\nFor this fix, we need to make sure that passing too-large inputs to\nthe evbuffer functions can't make us do bad things with the heap.\n\nAlso, lower the maximum chunk size to the lower of off_t, size_t maximum.\n\nThis is necessary since otherwise we could get into an infinite loop\nif we make a chunk that 'misalign' cannot index into.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: kadm5_randkey_principal_3(void *server_handle,\n krb5_principal principal,\n krb5_boolean keepold,\n int n_ks_tuple, krb5_key_salt_tuple *ks_tuple,\n krb5_keyblock **keyblocks,\n int *n_keys)\n{\n krb5_db_entry *kdb;\n osa_princ_ent_rec adb;\n krb5_int32 now;\n kadm5_policy_ent_rec pol;\n int ret, last_pwd;\n krb5_boolean have_pol = FALSE;\n kadm5_server_handle_t handle = server_handle;\n krb5_keyblock *act_mkey;\n krb5_kvno act_kvno;\n int new_n_ks_tuple = 0;\n krb5_key_salt_tuple *new_ks_tuple = NULL;\n\n if (keyblocks)\n *keyblocks = NULL;\n\n CHECK_HANDLE(server_handle);\n\n krb5_clear_error_message(handle->context);\n\n if (principal == NULL)\n return EINVAL;\n\n if ((ret = kdb_get_entry(handle, principal, &kdb, &adb)))\n return(ret);\n\n ret = apply_keysalt_policy(handle, adb.policy, n_ks_tuple, ks_tuple,\n &new_n_ks_tuple, &new_ks_tuple);\n if (ret)\n goto done;\n\n if (krb5_principal_compare(handle->context, principal, hist_princ)) {\n /* If changing the history entry, the new entry must have exactly one\n * key. */\n if (keepold)\n return KADM5_PROTECT_PRINCIPAL;\n new_n_ks_tuple = 1;\n }\n\n ret = kdb_get_active_mkey(handle, &act_kvno, &act_mkey);\n if (ret)\n goto done;\n\n ret = krb5_dbe_crk(handle->context, act_mkey, new_ks_tuple, new_n_ks_tuple,\n keepold, kdb);\n if (ret)\n goto done;\n\n ret = krb5_dbe_update_mkvno(handle->context, kdb, act_kvno);\n if (ret)\n goto done;\n\n kdb->attributes &= ~KRB5_KDB_REQUIRES_PWCHANGE;\n\n ret = krb5_timeofday(handle->context, &now);\n if (ret)\n goto done;\n\n if ((adb.aux_attributes & KADM5_POLICY)) {\n ret = get_policy(handle, adb.policy, &pol, &have_pol);\n if (ret)\n goto done;\n }\n if (have_pol) {\n ret = krb5_dbe_lookup_last_pwd_change(handle->context, kdb, &last_pwd);\n if (ret)\n goto done;\n\n#if 0\n /*\n * The spec says this check is overridden if the caller has\n * modify privilege. The admin server therefore makes this\n * check itself (in chpass_principal_wrapper, misc.c). A\n * local caller implicitly has all authorization bits.\n */\n if((now - last_pwd) < pol.pw_min_life &&\n !(kdb->attributes & KRB5_KDB_REQUIRES_PWCHANGE)) {\n ret = KADM5_PASS_TOOSOON;\n goto done;\n }\n#endif\n\n if (pol.pw_max_life)\n kdb->pw_expiration = now + pol.pw_max_life;\n else\n kdb->pw_expiration = 0;\n } else {\n kdb->pw_expiration = 0;\n }\n\n ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now);\n if (ret)\n goto done;\n\n /* unlock principal on this KDC */\n kdb->fail_auth_count = 0;\n\n if (keyblocks) {\n ret = decrypt_key_data(handle->context,\n kdb->n_key_data, kdb->key_data,\n keyblocks, n_keys);\n if (ret)\n goto done;\n }\n\n /* key data changed, let the database provider know */\n kdb->mask = KADM5_KEY_DATA | KADM5_FAIL_AUTH_COUNT;\n /* | KADM5_RANDKEY_USED */;\n\n ret = k5_kadm5_hook_chpass(handle->context, handle->hook_handles,\n KADM5_HOOK_STAGE_PRECOMMIT, principal, keepold,\n new_n_ks_tuple, new_ks_tuple, NULL);\n if (ret)\n goto done;\n if ((ret = kdb_put_entry(handle, kdb, &adb)))\n goto done;\n\n (void) k5_kadm5_hook_chpass(handle->context, handle->hook_handles,\n KADM5_HOOK_STAGE_POSTCOMMIT, principal,\n keepold, new_n_ks_tuple, new_ks_tuple, NULL);\n ret = KADM5_OK;\ndone:\n free(new_ks_tuple);\n kdb_free_entry(handle, kdb, &adb);\n if (have_pol)\n kadm5_free_policy_ent(handle->lhandle, &pol);\n\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-522', 'CWE-255'], 'message': 'Return only new keys in randkey [CVE-2014-5351]\n\nIn kadmind's randkey operation, if a client specifies the keepold\nflag, do not include the preserved old keys in the response.\n\nCVE-2014-5351:\n\nAn authenticated remote attacker can retrieve the current keys for a\nservice principal when generating a new set of keys for that\nprincipal. The attacker needs to be authenticated as a user who has\nthe elevated privilege for randomizing the keys of other principals.\n\nNormally, when a Kerberos administrator randomizes the keys of a\nservice principal, kadmind returns only the new keys. This prevents\nan administrator who lacks legitimate privileged access to a service\nfrom forging tickets to authenticate to that service. If the\n\"keepold\" flag to the kadmin randkey RPC operation is true, kadmind\nretains the old keys in the KDC database as intended, but also\nunexpectedly returns the old keys to the client, which exposes the\nservice to ticket forgery attacks from the administrator.\n\nA mitigating factor is that legitimate clients of the affected service\nwill start failing to authenticate to the service once they begin to\nreceive service tickets encrypted in the new keys. The affected\nservice will be unable to decrypt the newly issued tickets, possibly\nalerting the legitimate administrator of the affected service.\n\nCVSSv2: AV:N/AC:H/Au:S/C:P/I:N/A:N/E:POC/RL:OF/RC:C\n\n[tlyu@mit.edu: CVE description and CVSS score]\n\nticket: 8018 (new)\ntarget_version: 1.13\ntags: pullup'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void __net_random_once_deferred(struct work_struct *w)\n{\n\tstruct __net_random_once_work *work =\n\t\tcontainer_of(w, struct __net_random_once_work, work);\n\tif (!static_key_enabled(work->key))\n\t\tstatic_key_slow_inc(work->key);\n\tkfree(work);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'net: avoid dependency of net_get_random_once on nop patching\n\nnet_get_random_once depends on the static keys infrastructure to patch up\nthe branch to the slow path during boot. This was realized by abusing the\nstatic keys api and defining a new initializer to not enable the call\nsite while still indicating that the branch point should get patched\nup. This was needed to have the fast path considered likely by gcc.\n\nThe static key initialization during boot up normally walks through all\nthe registered keys and either patches in ideal nops or enables the jump\nsite but omitted that step on x86 if ideal nops where already placed at\nstatic_key branch points. Thus net_get_random_once branches not always\nbecame active.\n\nThis patch switches net_get_random_once to the ordinary static_key\napi and thus places the kernel fast path in the - by gcc considered -\nunlikely path. Microbenchmarks on Intel and AMD x86-64 showed that\nthe unlikely path actually beats the likely path in terms of cycle cost\nand that different nop patterns did not make much difference, thus this\nswitch should not be noticeable.\n\nFixes: a48e42920ff38b (\"net: introduce new macro net_get_random_once\")\nReported-by: Tuomas R\u00e4s\u00e4nen \nCc: Linus Torvalds \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: _gnutls_server_select_suite(gnutls_session_t session, uint8_t * data,\n\t\t\t unsigned int datalen)\n{\n\tint ret;\n\tunsigned int i, j, cipher_suites_size;\n\tsize_t pk_algos_size;\n\tuint8_t cipher_suites[MAX_CIPHERSUITE_SIZE];\n\tint retval;\n\tgnutls_pk_algorithm_t pk_algos[MAX_ALGOS];\t/* will hold the pk algorithms\n\t\t\t\t\t\t\t * supported by the peer.\n\t\t\t\t\t\t\t */\n\n\tfor (i = 0; i < datalen; i += 2) {\n\t\t/* TLS_RENEGO_PROTECTION_REQUEST = { 0x00, 0xff } */\n\t\tif (session->internals.priorities.sr != SR_DISABLED &&\n\t\t data[i] == GNUTLS_RENEGO_PROTECTION_REQUEST_MAJOR &&\n\t\t data[i + 1] == GNUTLS_RENEGO_PROTECTION_REQUEST_MINOR) {\n\t\t\t_gnutls_handshake_log\n\t\t\t (\"HSK[%p]: Received safe renegotiation CS\\n\",\n\t\t\t session);\n\t\t\tretval = _gnutls_ext_sr_recv_cs(session);\n\t\t\tif (retval < 0) {\n\t\t\t\tgnutls_assert();\n\t\t\t\treturn retval;\n\t\t\t}\n\t\t}\n\n\t\t/* TLS_FALLBACK_SCSV */\n\t\tif (data[i] == GNUTLS_FALLBACK_SCSV_MAJOR &&\n\t\t data[i + 1] == GNUTLS_FALLBACK_SCSV_MINOR) {\n\t\t\t_gnutls_handshake_log\n\t\t\t (\"HSK[%p]: Received fallback CS\\n\",\n\t\t\t session);\n\n\t\t\tif (gnutls_protocol_get_version(session) !=\n\t\t\t GNUTLS_TLS_VERSION_MAX)\n\t\t\t\treturn GNUTLS_E_INAPPROPRIATE_FALLBACK;\n\t\t}\n\t}\n\n\tpk_algos_size = MAX_ALGOS;\n\tret =\n\t server_find_pk_algos_in_ciphersuites(data, datalen, pk_algos,\n\t\t\t\t\t\t &pk_algos_size);\n\tif (ret < 0)\n\t\treturn gnutls_assert_val(ret);\n\n\tret =\n\t _gnutls_supported_ciphersuites(session, cipher_suites,\n\t\t\t\t\t sizeof(cipher_suites));\n\tif (ret < 0)\n\t\treturn gnutls_assert_val(ret);\n\n\tcipher_suites_size = ret;\n\n\t/* Here we remove any ciphersuite that does not conform\n\t * the certificate requested, or to the\n\t * authentication requested (e.g. SRP).\n\t */\n\tret =\n\t _gnutls_remove_unwanted_ciphersuites(session, cipher_suites,\n\t\t\t\t\t\t cipher_suites_size,\n\t\t\t\t\t\t pk_algos, pk_algos_size);\n\tif (ret <= 0) {\n\t\tgnutls_assert();\n\t\tif (ret < 0)\n\t\t\treturn ret;\n\t\telse\n\t\t\treturn GNUTLS_E_UNKNOWN_CIPHER_SUITE;\n\t}\n\n\tcipher_suites_size = ret;\n\n\t/* Data length should be zero mod 2 since\n\t * every ciphersuite is 2 bytes. (this check is needed\n\t * see below).\n\t */\n\tif (datalen % 2 != 0) {\n\t\tgnutls_assert();\n\t\treturn GNUTLS_E_UNEXPECTED_PACKET_LENGTH;\n\t}\n\n\tmemset(session->security_parameters.cipher_suite, 0, 2);\n\n\tretval = GNUTLS_E_UNKNOWN_CIPHER_SUITE;\n\n\t_gnutls_handshake_log\n\t (\"HSK[%p]: Requested cipher suites[size: %d]: \\n\", session,\n\t (int) datalen);\n\n\tif (session->internals.priorities.server_precedence == 0) {\n\t\tfor (j = 0; j < datalen; j += 2) {\n\t\t\t_gnutls_handshake_log(\"\\t0x%.2x, 0x%.2x %s\\n\",\n\t\t\t\t\t data[j], data[j + 1],\n\t\t\t\t\t _gnutls_cipher_suite_get_name\n\t\t\t\t\t (&data[j]));\n\t\t\tfor (i = 0; i < cipher_suites_size; i += 2) {\n\t\t\t\tif (memcmp(&cipher_suites[i], &data[j], 2)\n\t\t\t\t == 0) {\n\t\t\t\t\t_gnutls_handshake_log\n\t\t\t\t\t (\"HSK[%p]: Selected cipher suite: %s\\n\",\n\t\t\t\t\t session,\n\t\t\t\t\t _gnutls_cipher_suite_get_name\n\t\t\t\t\t (&data[j]));\n\t\t\t\t\tmemcpy(session->\n\t\t\t\t\t security_parameters.\n\t\t\t\t\t cipher_suite,\n\t\t\t\t\t &cipher_suites[i], 2);\n\t\t\t\t\t_gnutls_epoch_set_cipher_suite\n\t\t\t\t\t (session, EPOCH_NEXT,\n\t\t\t\t\t session->security_parameters.\n\t\t\t\t\t cipher_suite);\n\n\n\t\t\t\t\tretval = 0;\n\t\t\t\t\tgoto finish;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\t\t/* server selects */\n\n\t\tfor (i = 0; i < cipher_suites_size; i += 2) {\n\t\t\tfor (j = 0; j < datalen; j += 2) {\n\t\t\t\tif (memcmp(&cipher_suites[i], &data[j], 2)\n\t\t\t\t == 0) {\n\t\t\t\t\t_gnutls_handshake_log\n\t\t\t\t\t (\"HSK[%p]: Selected cipher suite: %s\\n\",\n\t\t\t\t\t session,\n\t\t\t\t\t _gnutls_cipher_suite_get_name\n\t\t\t\t\t (&data[j]));\n\t\t\t\t\tmemcpy(session->\n\t\t\t\t\t security_parameters.\n\t\t\t\t\t cipher_suite,\n\t\t\t\t\t &cipher_suites[i], 2);\n\t\t\t\t\t_gnutls_epoch_set_cipher_suite\n\t\t\t\t\t (session, EPOCH_NEXT,\n\t\t\t\t\t session->security_parameters.\n\t\t\t\t\t cipher_suite);\n\n\n\t\t\t\t\tretval = 0;\n\t\t\t\t\tgoto finish;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n finish:\n\n\tif (retval != 0) {\n\t\tgnutls_assert();\n\t\treturn retval;\n\t}\n\n\t/* check if the credentials (username, public key etc.) are ok\n\t */\n\tif (_gnutls_get_kx_cred\n\t (session,\n\t _gnutls_cipher_suite_get_kx_algo(session->security_parameters.\n\t\t\t\t\t cipher_suite)) == NULL) {\n\t\tgnutls_assert();\n\t\treturn GNUTLS_E_INSUFFICIENT_CREDENTIALS;\n\t}\n\n\n\t/* set the mod_auth_st to the appropriate struct\n\t * according to the KX algorithm. This is needed since all the\n\t * handshake functions are read from there;\n\t */\n\tsession->internals.auth_struct =\n\t _gnutls_kx_auth_struct(_gnutls_cipher_suite_get_kx_algo\n\t\t\t\t (session->security_parameters.\n\t\t\t\t cipher_suite));\n\tif (session->internals.auth_struct == NULL) {\n\n\t\t_gnutls_handshake_log\n\t\t (\"HSK[%p]: Cannot find the appropriate handler for the KX algorithm\\n\",\n\t\t session);\n\t\tgnutls_assert();\n\t\treturn GNUTLS_E_INTERNAL_ERROR;\n\t}\n\n\treturn 0;\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'handshake: check inappropriate fallback against the configured max version\n\nThat allows to operate on a server which is explicitly configured to\nutilize earlier than TLS 1.2 versions.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size,\n int clazz, int swap, size_t align, int *flags)\n{\n\tElf32_Nhdr nh32;\n\tElf64_Nhdr nh64;\n\tsize_t noff, doff;\n#ifdef ELFCORE\n\tint os_style = -1;\n#endif\n\tuint32_t namesz, descsz;\n\tunsigned char *nbuf = CAST(unsigned char *, vbuf);\n\n\t(void)memcpy(xnh_addr, &nbuf[offset], xnh_sizeof);\n\toffset += xnh_sizeof;\n\n\tnamesz = xnh_namesz;\n\tdescsz = xnh_descsz;\n\tif ((namesz == 0) && (descsz == 0)) {\n\t\t/*\n\t\t * We're out of note headers.\n\t\t */\n\t\treturn (offset >= size) ? offset : size;\n\t}\n\n\tif (namesz & 0x80000000) {\n\t (void)file_printf(ms, \", bad note name size 0x%lx\",\n\t\t(unsigned long)namesz);\n\t return offset;\n\t}\n\n\tif (descsz & 0x80000000) {\n\t (void)file_printf(ms, \", bad note description size 0x%lx\",\n\t\t(unsigned long)descsz);\n\t return offset;\n\t}\n\n\n\tnoff = offset;\n\tdoff = ELF_ALIGN(offset + namesz);\n\n\tif (offset + namesz > size) {\n\t\t/*\n\t\t * We're past the end of the buffer.\n\t\t */\n\t\treturn doff;\n\t}\n\n\toffset = ELF_ALIGN(doff + descsz);\n\tif (doff + descsz > size) {\n\t\t/*\n\t\t * We're past the end of the buffer.\n\t\t */\n\t\treturn (offset >= size) ? offset : size;\n\t}\n\n\tif ((*flags & (FLAGS_DID_NOTE|FLAGS_DID_BUILD_ID)) ==\n\t (FLAGS_DID_NOTE|FLAGS_DID_BUILD_ID))\n\t\tgoto core;\n\n\tif (namesz == 5 && strcmp((char *)&nbuf[noff], \"SuSE\") == 0 &&\n\t xnh_type == NT_GNU_VERSION && descsz == 2) {\n\t file_printf(ms, \", for SuSE %d.%d\", nbuf[doff], nbuf[doff + 1]);\n\t}\n\tif (namesz == 4 && strcmp((char *)&nbuf[noff], \"GNU\") == 0 &&\n\t xnh_type == NT_GNU_VERSION && descsz == 16) {\n\t\tuint32_t desc[4];\n\t\t(void)memcpy(desc, &nbuf[doff], sizeof(desc));\n\n\t\tif (file_printf(ms, \", for GNU/\") == -1)\n\t\t\treturn size;\n\t\tswitch (elf_getu32(swap, desc[0])) {\n\t\tcase GNU_OS_LINUX:\n\t\t\tif (file_printf(ms, \"Linux\") == -1)\n\t\t\t\treturn size;\n\t\t\tbreak;\n\t\tcase GNU_OS_HURD:\n\t\t\tif (file_printf(ms, \"Hurd\") == -1)\n\t\t\t\treturn size;\n\t\t\tbreak;\n\t\tcase GNU_OS_SOLARIS:\n\t\t\tif (file_printf(ms, \"Solaris\") == -1)\n\t\t\t\treturn size;\n\t\t\tbreak;\n\t\tcase GNU_OS_KFREEBSD:\n\t\t\tif (file_printf(ms, \"kFreeBSD\") == -1)\n\t\t\t\treturn size;\n\t\t\tbreak;\n\t\tcase GNU_OS_KNETBSD:\n\t\t\tif (file_printf(ms, \"kNetBSD\") == -1)\n\t\t\t\treturn size;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (file_printf(ms, \"\") == -1)\n\t\t\t\treturn size; \n\t\t}\n\t\tif (file_printf(ms, \" %d.%d.%d\", elf_getu32(swap, desc[1]),\n\t\t elf_getu32(swap, desc[2]), elf_getu32(swap, desc[3])) == -1)\n\t\t\treturn size;\n\t\t*flags |= FLAGS_DID_NOTE;\n\t\treturn size;\n\t}\n\n\tif (namesz == 4 && strcmp((char *)&nbuf[noff], \"GNU\") == 0 &&\n\t xnh_type == NT_GNU_BUILD_ID && (descsz == 16 || descsz == 20)) {\n\t uint8_t desc[20];\n\t uint32_t i;\n\t if (file_printf(ms, \", BuildID[%s]=\", descsz == 16 ? \"md5/uuid\" :\n\t\t\"sha1\") == -1)\n\t\t return size;\n\t (void)memcpy(desc, &nbuf[doff], descsz);\n\t for (i = 0; i < descsz; i++)\n\t\tif (file_printf(ms, \"%02x\", desc[i]) == -1)\n\t\t return size;\n\t *flags |= FLAGS_DID_BUILD_ID;\n\t}\n\n\tif (namesz == 4 && strcmp((char *)&nbuf[noff], \"PaX\") == 0 &&\n\t xnh_type == NT_NETBSD_PAX && descsz == 4) {\n\t\tstatic const char *pax[] = {\n\t\t \"+mprotect\",\n\t\t \"-mprotect\",\n\t\t \"+segvguard\",\n\t\t \"-segvguard\",\n\t\t \"+ASLR\",\n\t\t \"-ASLR\",\n\t\t};\n\t\tuint32_t desc;\n\t\tsize_t i;\n\t\tint did = 0;\n\n\t\t(void)memcpy(&desc, &nbuf[doff], sizeof(desc));\n\t\tdesc = elf_getu32(swap, desc);\n\n\t\tif (desc && file_printf(ms, \", PaX: \") == -1)\n\t\t\treturn size;\n\n\t\tfor (i = 0; i < __arraycount(pax); i++) {\n\t\t\tif (((1 << i) & desc) == 0)\n\t\t\t\tcontinue;\n\t\t\tif (file_printf(ms, \"%s%s\", did++ ? \",\" : \"\",\n\t\t\t pax[i]) == -1)\n\t\t\t\treturn size;\n\t\t}\n\t}\n\n\tif (namesz == 7 && strcmp((char *)&nbuf[noff], \"NetBSD\") == 0) {\n\t\tswitch (xnh_type) {\n\t\tcase NT_NETBSD_VERSION:\n\t\t\tif (descsz == 4) {\n\t\t\t\tdo_note_netbsd_version(ms, swap, &nbuf[doff]);\n\t\t\t\t*flags |= FLAGS_DID_NOTE;\n\t\t\t\treturn size;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase NT_NETBSD_MARCH:\n\t\t\tif (file_printf(ms, \", compiled for: %.*s\", (int)descsz,\n\t\t\t (const char *)&nbuf[doff]) == -1)\n\t\t\t\treturn size;\n\t\t\tbreak;\n\t\tcase NT_NETBSD_CMODEL:\n\t\t\tif (file_printf(ms, \", compiler model: %.*s\",\n\t\t\t (int)descsz, (const char *)&nbuf[doff]) == -1)\n\t\t\t\treturn size;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (file_printf(ms, \", note=%u\", xnh_type) == -1)\n\t\t\t\treturn size;\n\t\t\tbreak;\n\t\t}\n\t\treturn size;\n\t}\n\n\tif (namesz == 8 && strcmp((char *)&nbuf[noff], \"FreeBSD\") == 0) {\n\t \tif (xnh_type == NT_FREEBSD_VERSION && descsz == 4) {\n\t\t\tdo_note_freebsd_version(ms, swap, &nbuf[doff]);\n\t\t\t*flags |= FLAGS_DID_NOTE;\n\t\t\treturn size;\n\t\t}\n\t}\n\n\tif (namesz == 8 && strcmp((char *)&nbuf[noff], \"OpenBSD\") == 0 &&\n\t xnh_type == NT_OPENBSD_VERSION && descsz == 4) {\n\t\tif (file_printf(ms, \", for OpenBSD\") == -1)\n\t\t\treturn size;\n\t\t/* Content of note is always 0 */\n\t\t*flags |= FLAGS_DID_NOTE;\n\t\treturn size;\n\t}\n\n\tif (namesz == 10 && strcmp((char *)&nbuf[noff], \"DragonFly\") == 0 &&\n\t xnh_type == NT_DRAGONFLY_VERSION && descsz == 4) {\n\t\tuint32_t desc;\n\t\tif (file_printf(ms, \", for DragonFly\") == -1)\n\t\t\treturn size;\n\t\t(void)memcpy(&desc, &nbuf[doff], sizeof(desc));\n\t\tdesc = elf_getu32(swap, desc);\n\t\tif (file_printf(ms, \" %d.%d.%d\", desc / 100000,\n\t\t desc / 10000 % 10, desc % 10000) == -1)\n\t\t\treturn size;\n\t\t*flags |= FLAGS_DID_NOTE;\n\t\treturn size;\n\t}\n\ncore:\n\t/*\n\t * Sigh. The 2.0.36 kernel in Debian 2.1, at\n\t * least, doesn't correctly implement name\n\t * sections, in core dumps, as specified by\n\t * the \"Program Linking\" section of \"UNIX(R) System\n\t * V Release 4 Programmer's Guide: ANSI C and\n\t * Programming Support Tools\", because my copy\n\t * clearly says \"The first 'namesz' bytes in 'name'\n\t * contain a *null-terminated* [emphasis mine]\n\t * character representation of the entry's owner\n\t * or originator\", but the 2.0.36 kernel code\n\t * doesn't include the terminating null in the\n\t * name....\n\t */\n\tif ((namesz == 4 && strncmp((char *)&nbuf[noff], \"CORE\", 4) == 0) ||\n\t (namesz == 5 && strcmp((char *)&nbuf[noff], \"CORE\") == 0)) {\n\t\tos_style = OS_STYLE_SVR4;\n\t} \n\n\tif ((namesz == 8 && strcmp((char *)&nbuf[noff], \"FreeBSD\") == 0)) {\n\t\tos_style = OS_STYLE_FREEBSD;\n\t}\n\n\tif ((namesz >= 11 && strncmp((char *)&nbuf[noff], \"NetBSD-CORE\", 11)\n\t == 0)) {\n\t\tos_style = OS_STYLE_NETBSD;\n\t}\n\n#ifdef ELFCORE\n\tif ((*flags & FLAGS_DID_CORE) != 0)\n\t\treturn size;\n\n\tif (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) {\n\t\tif (file_printf(ms, \", %s-style\", os_style_names[os_style])\n\t\t == -1)\n\t\t\treturn size;\n\t\t*flags |= FLAGS_DID_CORE_STYLE;\n\t}\n\n\tswitch (os_style) {\n\tcase OS_STYLE_NETBSD:\n\t\tif (xnh_type == NT_NETBSD_CORE_PROCINFO) {\n\t\t\tuint32_t signo;\n\t\t\t/*\n\t\t\t * Extract the program name. It is at\n\t\t\t * offset 0x7c, and is up to 32-bytes,\n\t\t\t * including the terminating NUL.\n\t\t\t */\n\t\t\tif (file_printf(ms, \", from '%.31s'\",\n\t\t\t &nbuf[doff + 0x7c]) == -1)\n\t\t\t\treturn size;\n\t\t\t\n\t\t\t/*\n\t\t\t * Extract the signal number. It is at\n\t\t\t * offset 0x08.\n\t\t\t */\n\t\t\t(void)memcpy(&signo, &nbuf[doff + 0x08],\n\t\t\t sizeof(signo));\n\t\t\tif (file_printf(ms, \" (signal %u)\",\n\t\t\t elf_getu32(swap, signo)) == -1)\n\t\t\t\treturn size;\n\t\t\t*flags |= FLAGS_DID_CORE;\n\t\t\treturn size;\n\t\t}\n\t\tbreak;\n\n\tdefault:\n\t\tif (xnh_type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) {\n\t\t\tsize_t i, j;\n\t\t\tunsigned char c;\n\t\t\t/*\n\t\t\t * Extract the program name. We assume\n\t\t\t * it to be 16 characters (that's what it\n\t\t\t * is in SunOS 5.x and Linux).\n\t\t\t *\n\t\t\t * Unfortunately, it's at a different offset\n\t\t\t * in various OSes, so try multiple offsets.\n\t\t\t * If the characters aren't all printable,\n\t\t\t * reject it.\n\t\t\t */\n\t\t\tfor (i = 0; i < NOFFSETS; i++) {\n\t\t\t\tunsigned char *cname, *cp;\n\t\t\t\tsize_t reloffset = prpsoffsets(i);\n\t\t\t\tsize_t noffset = doff + reloffset;\n\t\t\t\tsize_t k;\n\t\t\t\tfor (j = 0; j < 16; j++, noffset++,\n\t\t\t\t reloffset++) {\n\t\t\t\t\t/*\n\t\t\t\t\t * Make sure we're not past\n\t\t\t\t\t * the end of the buffer; if\n\t\t\t\t\t * we are, just give up.\n\t\t\t\t\t */\n\t\t\t\t\tif (noffset >= size)\n\t\t\t\t\t\tgoto tryanother;\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Make sure we're not past\n\t\t\t\t\t * the end of the contents;\n\t\t\t\t\t * if we are, this obviously\n\t\t\t\t\t * isn't the right offset.\n\t\t\t\t\t */\n\t\t\t\t\tif (reloffset >= descsz)\n\t\t\t\t\t\tgoto tryanother;\n\n\t\t\t\t\tc = nbuf[noffset];\n\t\t\t\t\tif (c == '\\0') {\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * A '\\0' at the\n\t\t\t\t\t\t * beginning is\n\t\t\t\t\t\t * obviously wrong.\n\t\t\t\t\t\t * Any other '\\0'\n\t\t\t\t\t\t * means we're done.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tif (j == 0)\n\t\t\t\t\t\t\tgoto tryanother;\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * A nonprintable\n\t\t\t\t\t\t * character is also\n\t\t\t\t\t\t * wrong.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tif (!isprint(c) || isquote(c))\n\t\t\t\t\t\t\tgoto tryanother;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t/*\n\t\t\t\t * Well, that worked.\n\t\t\t\t */\n\n\t\t\t\t/*\n\t\t\t\t * Try next offsets, in case this match is\n\t\t\t\t * in the middle of a string.\n\t\t\t\t */\n\t\t\t\tfor (k = i + 1 ; k < NOFFSETS ; k++) {\n\t\t\t\t\tsize_t no;\n\t\t\t\t\tint adjust = 1;\n\t\t\t\t\tif (prpsoffsets(k) >= prpsoffsets(i))\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tfor (no = doff + prpsoffsets(k);\n\t\t\t\t\t no < doff + prpsoffsets(i); no++)\n\t\t\t\t\t\tadjust = adjust\n\t\t\t\t\t\t && isprint(nbuf[no]);\n\t\t\t\t\tif (adjust)\n\t\t\t\t\t\ti = k;\n\t\t\t\t}\n\n\t\t\t\tcname = (unsigned char *)\n\t\t\t\t &nbuf[doff + prpsoffsets(i)];\n\t\t\t\tfor (cp = cname; *cp && isprint(*cp); cp++)\n\t\t\t\t\tcontinue;\n\t\t\t\t/*\n\t\t\t\t * Linux apparently appends a space at the end\n\t\t\t\t * of the command line: remove it.\n\t\t\t\t */\n\t\t\t\twhile (cp > cname && isspace(cp[-1]))\n\t\t\t\t\tcp--;\n\t\t\t\tif (file_printf(ms, \", from '%.*s'\",\n\t\t\t\t (int)(cp - cname), cname) == -1)\n\t\t\t\t\treturn size;\n\t\t\t\t*flags |= FLAGS_DID_CORE;\n\t\t\t\treturn size;\n\n\t\t\ttryanother:\n\t\t\t\t;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n#endif\n\treturn offset;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fix note bounds reading, Francisco Alonso / Red Hat'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int kvm_iommu_map_pages(struct kvm *kvm, struct kvm_memory_slot *slot)\n{\n\tgfn_t gfn, end_gfn;\n\tpfn_t pfn;\n\tint r = 0;\n\tstruct iommu_domain *domain = kvm->arch.iommu_domain;\n\tint flags;\n\n\t/* check if iommu exists and in use */\n\tif (!domain)\n\t\treturn 0;\n\n\tgfn = slot->base_gfn;\n\tend_gfn = gfn + slot->npages;\n\n\tflags = IOMMU_READ;\n\tif (!(slot->flags & KVM_MEM_READONLY))\n\t\tflags |= IOMMU_WRITE;\n\tif (!kvm->arch.iommu_noncoherent)\n\t\tflags |= IOMMU_CACHE;\n\n\n\twhile (gfn < end_gfn) {\n\t\tunsigned long page_size;\n\n\t\t/* Check if already mapped */\n\t\tif (iommu_iova_to_phys(domain, gfn_to_gpa(gfn))) {\n\t\t\tgfn += 1;\n\t\t\tcontinue;\n\t\t}\n\n\t\t/* Get the page size we could use to map */\n\t\tpage_size = kvm_host_page_size(kvm, gfn);\n\n\t\t/* Make sure the page_size does not exceed the memslot */\n\t\twhile ((gfn + (page_size >> PAGE_SHIFT)) > end_gfn)\n\t\t\tpage_size >>= 1;\n\n\t\t/* Make sure gfn is aligned to the page size we want to map */\n\t\twhile ((gfn << PAGE_SHIFT) & (page_size - 1))\n\t\t\tpage_size >>= 1;\n\n\t\t/* Make sure hva is aligned to the page size we want to map */\n\t\twhile (__gfn_to_hva_memslot(slot, gfn) & (page_size - 1))\n\t\t\tpage_size >>= 1;\n\n\t\t/*\n\t\t * Pin all pages we are about to map in memory. This is\n\t\t * important because we unmap and unpin in 4kb steps later.\n\t\t */\n\t\tpfn = kvm_pin_pages(slot, gfn, page_size);\n\t\tif (is_error_noslot_pfn(pfn)) {\n\t\t\tgfn += 1;\n\t\t\tcontinue;\n\t\t}\n\n\t\t/* Map into IO address space */\n\t\tr = iommu_map(domain, gfn_to_gpa(gfn), pfn_to_hpa(pfn),\n\t\t\t page_size, flags);\n\t\tif (r) {\n\t\t\tprintk(KERN_ERR \"kvm_iommu_map_address:\"\n\t\t\t \"iommu failed to map pfn=%llx\\n\", pfn);\n\t\t\tkvm_unpin_pages(kvm, pfn, page_size);\n\t\t\tgoto unmap_pages;\n\t\t}\n\n\t\tgfn += page_size >> PAGE_SHIFT;\n\n\n\t}\n\n\treturn 0;\n\nunmap_pages:\n\tkvm_iommu_put_pages(kvm, slot->base_gfn, gfn - slot->base_gfn);\n\treturn r;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'kvm: fix excessive pages un-pinning in kvm_iommu_map error path.\n\nThe third parameter of kvm_unpin_pages() when called from\nkvm_iommu_map_pages() is wrong, it should be the number of pages to un-pin\nand not the page size.\n\nThis error was facilitated with an inconsistent API: kvm_pin_pages() takes\na size, but kvn_unpin_pages() takes a number of pages, so fix the problem\nby matching the two.\n\nThis was introduced by commit 350b8bd (\"kvm: iommu: fix the third parameter\nof kvm_iommu_put_pages (CVE-2014-3601)\"), which fixes the lack of\nun-pinning for pages intended to be un-pinned (i.e. memory leak) but\nunfortunately potentially aggravated the number of pages we un-pin that\nshould have stayed pinned. As far as I understand though, the same\npractical mitigations apply.\n\nThis issue was found during review of Red Hat 6.6 patches to prepare\nKsplice rebootless updates.\n\nThanks to Vegard for his time on a late Friday evening to help me in\nunderstanding this code.\n\nFixes: 350b8bd (\"kvm: iommu: fix the third parameter of... (CVE-2014-3601)\")\nCc: stable@vger.kernel.org\nSigned-off-by: Quentin Casasnovas \nSigned-off-by: Vegard Nossum \nSigned-off-by: Jamie Iles \nReviewed-by: Sasha Levin \nSigned-off-by: Paolo Bonzini '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int x509_get_name( unsigned char **p, const unsigned char *end,\n x509_name *cur )\n{\n int ret;\n size_t len;\n const unsigned char *end2;\n x509_name *use;\n\n if( ( ret = asn1_get_tag( p, end, &len,\n ASN1_CONSTRUCTED | ASN1_SET ) ) != 0 )\n return( POLARSSL_ERR_X509_INVALID_NAME + ret );\n\n end2 = end;\n end = *p + len;\n use = cur;\n\n do\n {\n if( ( ret = x509_get_attr_type_value( p, end, use ) ) != 0 )\n return( ret );\n\n if( *p != end )\n {\n use->next = (x509_name *) polarssl_malloc(\n sizeof( x509_name ) );\n\n if( use->next == NULL )\n return( POLARSSL_ERR_X509_MALLOC_FAILED );\n\n memset( use->next, 0, sizeof( x509_name ) );\n\n use = use->next;\n }\n }\n while( *p != end );\n\n /*\n * recurse until end of SEQUENCE is reached\n */\n if( *p == end2 )\n return( 0 );\n\n cur->next = (x509_name *) polarssl_malloc(\n sizeof( x509_name ) );\n\n if( cur->next == NULL )\n return( POLARSSL_ERR_X509_MALLOC_FAILED );\n\n memset( cur->next, 0, sizeof( x509_name ) );\n\n return( x509_get_name( p, end2, cur->next ) );\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Fix memory leak while parsing some X.509 certs'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: xfs_file_splice_write(\n\tstruct pipe_inode_info\t*pipe,\n\tstruct file\t\t*outfilp,\n\tloff_t\t\t\t*ppos,\n\tsize_t\t\t\tcount,\n\tunsigned int\t\tflags)\n{\n\tstruct inode\t\t*inode = outfilp->f_mapping->host;\n\tstruct xfs_inode\t*ip = XFS_I(inode);\n\tint\t\t\tioflags = 0;\n\tssize_t\t\t\tret;\n\n\tXFS_STATS_INC(xs_write_calls);\n\n\tif (outfilp->f_mode & FMODE_NOCMTIME)\n\t\tioflags |= IO_INVIS;\n\n\tif (XFS_FORCED_SHUTDOWN(ip->i_mount))\n\t\treturn -EIO;\n\n\txfs_ilock(ip, XFS_IOLOCK_EXCL);\n\n\ttrace_xfs_file_splice_write(ip, count, *ppos, ioflags);\n\n\tret = generic_file_splice_write(pipe, outfilp, ppos, count, flags);\n\tif (ret > 0)\n\t\tXFS_STATS_ADD(xs_write_bytes, ret);\n\n\txfs_iunlock(ip, XFS_IOLOCK_EXCL);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': '->splice_write() via ->write_iter()\n\niter_file_splice_write() - a ->splice_write() instance that gathers the\npipe buffers, builds a bio_vec-based iov_iter covering those and feeds\nit to ->write_iter(). A bunch of simple cases coverted to that...\n\n[AV: fixed the braino spotted by Cyrill]\n\nSigned-off-by: Al Viro '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: dotraplinkage void do_stack_segment(struct pt_regs *regs, long error_code)\n{\n\tenum ctx_state prev_state;\n\n\tprev_state = exception_enter();\n\tif (notify_die(DIE_TRAP, \"stack segment\", regs, error_code,\n\t\t X86_TRAP_SS, SIGBUS) != NOTIFY_STOP) {\n\t\tpreempt_conditional_sti(regs);\n\t\tdo_trap(X86_TRAP_SS, SIGBUS, \"stack segment\", regs, error_code, NULL);\n\t\tpreempt_conditional_cli(regs);\n\t}\n\texception_exit(prev_state);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-17'], 'message': 'x86_64, traps: Stop using IST for #SS\n\nOn a 32-bit kernel, this has no effect, since there are no IST stacks.\n\nOn a 64-bit kernel, #SS can only happen in user code, on a failed iret\nto user space, a canonical violation on access via RSP or RBP, or a\ngenuine stack segment violation in 32-bit kernel code. The first two\ncases don't need IST, and the latter two cases are unlikely fatal bugs,\nand promoting them to double faults would be fine.\n\nThis fixes a bug in which the espfix64 code mishandles a stack segment\nviolation.\n\nThis saves 4k of memory per CPU and a tiny bit of code.\n\nSigned-off-by: Andy Lutomirski \nReviewed-by: Thomas Gleixner \nCc: stable@vger.kernel.org\nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: main(int argc, char *argv[])\n{\n\tint c;\n\tsize_t i;\n\tint action = 0, didsomefiles = 0, errflg = 0;\n\tint flags = 0, e = 0;\n\tstruct magic_set *magic = NULL;\n\tint longindex;\n\tconst char *magicfile = NULL;\t\t/* where the magic is\t*/\n\n\t/* makes islower etc work for other langs */\n#ifdef HAVE_SETLOCALE\n\t(void)setlocale(LC_CTYPE, \"\");\n#endif\n\n#ifdef __EMX__\n\t/* sh-like wildcard expansion! Shouldn't hurt at least ... */\n\t_wildcard(&argc, &argv);\n#endif\n\n\tif ((progname = strrchr(argv[0], '/')) != NULL)\n\t\tprogname++;\n\telse\n\t\tprogname = argv[0];\n\n#ifdef S_IFLNK\n\tflags |= getenv(\"POSIXLY_CORRECT\") ? MAGIC_SYMLINK : 0;\n#endif\n\twhile ((c = getopt_long(argc, argv, OPTSTRING, long_options,\n\t &longindex)) != -1)\n\t\tswitch (c) {\n\t\tcase 0 :\n\t\t\tswitch (longindex) {\n\t\t\tcase 0:\n\t\t\t\thelp();\n\t\t\t\tbreak;\n\t\t\tcase 10:\n\t\t\t\tflags |= MAGIC_APPLE;\n\t\t\t\tbreak;\n\t\t\tcase 11:\n\t\t\t\tflags |= MAGIC_MIME_TYPE;\n\t\t\t\tbreak;\n\t\t\tcase 12:\n\t\t\t\tflags |= MAGIC_MIME_ENCODING;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase '0':\n\t\t\tnulsep = 1;\n\t\t\tbreak;\n\t\tcase 'b':\n\t\t\tbflag++;\n\t\t\tbreak;\n\t\tcase 'c':\n\t\t\taction = FILE_CHECK;\n\t\t\tbreak;\n\t\tcase 'C':\n\t\t\taction = FILE_COMPILE;\n\t\t\tbreak;\n\t\tcase 'd':\n\t\t\tflags |= MAGIC_DEBUG|MAGIC_CHECK;\n\t\t\tbreak;\n\t\tcase 'E':\n\t\t\tflags |= MAGIC_ERROR;\n\t\t\tbreak;\n\t\tcase 'e':\n\t\t\tfor (i = 0; i < sizeof(nv) / sizeof(nv[0]); i++)\n\t\t\t\tif (strcmp(nv[i].name, optarg) == 0)\n\t\t\t\t\tbreak;\n\n\t\t\tif (i == sizeof(nv) / sizeof(nv[0]))\n\t\t\t\terrflg++;\n\t\t\telse\n\t\t\t\tflags |= nv[i].value;\n\t\t\tbreak;\n\n\t\tcase 'f':\n\t\t\tif(action)\n\t\t\t\tusage();\n\t\t\tif (magic == NULL)\n\t\t\t\tif ((magic = load(magicfile, flags)) == NULL)\n\t\t\t\t\treturn 1;\n\t\t\te |= unwrap(magic, optarg);\n\t\t\t++didsomefiles;\n\t\t\tbreak;\n\t\tcase 'F':\n\t\t\tseparator = optarg;\n\t\t\tbreak;\n\t\tcase 'i':\n\t\t\tflags |= MAGIC_MIME;\n\t\t\tbreak;\n\t\tcase 'k':\n\t\t\tflags |= MAGIC_CONTINUE;\n\t\t\tbreak;\n\t\tcase 'l':\n\t\t\taction = FILE_LIST;\n\t\t\tbreak;\n\t\tcase 'm':\n\t\t\tmagicfile = optarg;\n\t\t\tbreak;\n\t\tcase 'n':\n\t\t\t++nobuffer;\n\t\t\tbreak;\n\t\tcase 'N':\n\t\t\t++nopad;\n\t\t\tbreak;\n#if defined(HAVE_UTIME) || defined(HAVE_UTIMES)\n\t\tcase 'p':\n\t\t\tflags |= MAGIC_PRESERVE_ATIME;\n\t\t\tbreak;\n#endif\n\t\tcase 'r':\n\t\t\tflags |= MAGIC_RAW;\n\t\t\tbreak;\n\t\tcase 's':\n\t\t\tflags |= MAGIC_DEVICES;\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\tif (magicfile == NULL)\n\t\t\t\tmagicfile = magic_getpath(magicfile, action);\n\t\t\t(void)fprintf(stdout, \"%s-%s\\n\", progname, VERSION);\n\t\t\t(void)fprintf(stdout, \"magic file from %s\\n\",\n\t\t\t\t magicfile);\n\t\t\treturn 0;\n\t\tcase 'z':\n\t\t\tflags |= MAGIC_COMPRESS;\n\t\t\tbreak;\n#ifdef S_IFLNK\n\t\tcase 'L':\n\t\t\tflags |= MAGIC_SYMLINK;\n\t\t\tbreak;\n\t\tcase 'h':\n\t\t\tflags &= ~MAGIC_SYMLINK;\n\t\t\tbreak;\n#endif\n\t\tcase '?':\n\t\tdefault:\n\t\t\terrflg++;\n\t\t\tbreak;\n\t\t}\n\n\tif (errflg) {\n\t\tusage();\n\t}\n\tif (e)\n\t\treturn e;\n\n\tif (MAGIC_VERSION != magic_version())\n\t\t(void)fprintf(stderr, \"%s: compiled magic version [%d] \"\n\t\t \"does not match with shared library magic version [%d]\\n\",\n\t\t progname, MAGIC_VERSION, magic_version());\n\n\tswitch(action) {\n\tcase FILE_CHECK:\n\tcase FILE_COMPILE:\n\tcase FILE_LIST:\n\t\t/*\n\t\t * Don't try to check/compile ~/.magic unless we explicitly\n\t\t * ask for it.\n\t\t */\n\t\tmagic = magic_open(flags|MAGIC_CHECK);\n\t\tif (magic == NULL) {\n\t\t\t(void)fprintf(stderr, \"%s: %s\\n\", progname,\n\t\t\t strerror(errno));\n\t\t\treturn 1;\n\t\t}\n\t\tswitch(action) {\n\t\tcase FILE_CHECK:\n\t\t\tc = magic_check(magic, magicfile);\n\t\t\tbreak;\n\t\tcase FILE_COMPILE:\n\t\t\tc = magic_compile(magic, magicfile);\n\t\t\tbreak;\n\t\tcase FILE_LIST:\n\t\t\tc = magic_list(magic, magicfile);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tabort();\n\t\t}\n\t\tif (c == -1) {\n\t\t\t(void)fprintf(stderr, \"%s: %s\\n\", progname,\n\t\t\t magic_error(magic));\n\t\t\treturn 1;\n\t\t}\n\t\treturn 0;\n\tdefault:\n\t\tif (magic == NULL)\n\t\t\tif ((magic = load(magicfile, flags)) == NULL)\n\t\t\t\treturn 1;\n\t\tbreak;\n\t}\n\n\tif (optind == argc) {\n\t\tif (!didsomefiles)\n\t\t\tusage();\n\t}\n\telse {\n\t\tsize_t j, wid, nw;\n\t\tfor (wid = 0, j = (size_t)optind; j < (size_t)argc; j++) {\n\t\t\tnw = file_mbswidth(argv[j]);\n\t\t\tif (nw > wid)\n\t\t\t\twid = nw;\n\t\t}\n\t\t/*\n\t\t * If bflag is only set twice, set it depending on\n\t\t * number of files [this is undocumented, and subject to change]\n\t\t */\n\t\tif (bflag == 2) {\n\t\t\tbflag = optind >= argc - 1;\n\t\t}\n\t\tfor (; optind < argc; optind++)\n\t\t\te |= process(magic, argv[optind], wid);\n\t}\n\n\tif (magic)\n\t\tmagic_close(magic);\n\treturn e;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'bump recursion to 15, and allow it to be set from the command line.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size,\n int clazz, int swap, size_t align, int *flags)\n{\n\tElf32_Nhdr nh32;\n\tElf64_Nhdr nh64;\n\tsize_t noff, doff;\n#ifdef ELFCORE\n\tint os_style = -1;\n#endif\n\tuint32_t namesz, descsz;\n\tunsigned char *nbuf = CAST(unsigned char *, vbuf);\n\tchar sbuf[512];\n\n\tif (xnh_sizeof + offset > size) {\n\t\t/*\n\t\t * We're out of note headers.\n\t\t */\n\t\treturn xnh_sizeof + offset;\n\t}\n\n\t(void)memcpy(xnh_addr, &nbuf[offset], xnh_sizeof);\n\toffset += xnh_sizeof;\n\n\tnamesz = xnh_namesz;\n\tdescsz = xnh_descsz;\n\tif ((namesz == 0) && (descsz == 0)) {\n\t\t/*\n\t\t * We're out of note headers.\n\t\t */\n\t\treturn (offset >= size) ? offset : size;\n\t}\n\n\tif (namesz & 0x80000000) {\n\t (void)file_printf(ms, \", bad note name size 0x%lx\",\n\t\t(unsigned long)namesz);\n\t return 0;\n\t}\n\n\tif (descsz & 0x80000000) {\n\t (void)file_printf(ms, \", bad note description size 0x%lx\",\n\t\t(unsigned long)descsz);\n\t return 0;\n\t}\n\n\n\tnoff = offset;\n\tdoff = ELF_ALIGN(offset + namesz);\n\n\tif (offset + namesz > size) {\n\t\t/*\n\t\t * We're past the end of the buffer.\n\t\t */\n\t\treturn doff;\n\t}\n\n\toffset = ELF_ALIGN(doff + descsz);\n\tif (doff + descsz > size) {\n\t\t/*\n\t\t * We're past the end of the buffer.\n\t\t */\n\t\treturn (offset >= size) ? offset : size;\n\t}\n\n\tif ((*flags & (FLAGS_DID_NOTE|FLAGS_DID_BUILD_ID)) ==\n\t (FLAGS_DID_NOTE|FLAGS_DID_BUILD_ID))\n\t\tgoto core;\n\n\tif (namesz == 5 && strcmp((char *)&nbuf[noff], \"SuSE\") == 0 &&\n\t xnh_type == NT_GNU_VERSION && descsz == 2) {\n\t file_printf(ms, \", for SuSE %d.%d\", nbuf[doff], nbuf[doff + 1]);\n\t}\n\tif (namesz == 4 && strcmp((char *)&nbuf[noff], \"GNU\") == 0 &&\n\t xnh_type == NT_GNU_VERSION && descsz == 16) {\n\t\tuint32_t desc[4];\n\t\t(void)memcpy(desc, &nbuf[doff], sizeof(desc));\n\n\t\tif (file_printf(ms, \", for GNU/\") == -1)\n\t\t\treturn size;\n\t\tswitch (elf_getu32(swap, desc[0])) {\n\t\tcase GNU_OS_LINUX:\n\t\t\tif (file_printf(ms, \"Linux\") == -1)\n\t\t\t\treturn size;\n\t\t\tbreak;\n\t\tcase GNU_OS_HURD:\n\t\t\tif (file_printf(ms, \"Hurd\") == -1)\n\t\t\t\treturn size;\n\t\t\tbreak;\n\t\tcase GNU_OS_SOLARIS:\n\t\t\tif (file_printf(ms, \"Solaris\") == -1)\n\t\t\t\treturn size;\n\t\t\tbreak;\n\t\tcase GNU_OS_KFREEBSD:\n\t\t\tif (file_printf(ms, \"kFreeBSD\") == -1)\n\t\t\t\treturn size;\n\t\t\tbreak;\n\t\tcase GNU_OS_KNETBSD:\n\t\t\tif (file_printf(ms, \"kNetBSD\") == -1)\n\t\t\t\treturn size;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (file_printf(ms, \"\") == -1)\n\t\t\t\treturn size; \n\t\t}\n\t\tif (file_printf(ms, \" %d.%d.%d\", elf_getu32(swap, desc[1]),\n\t\t elf_getu32(swap, desc[2]), elf_getu32(swap, desc[3])) == -1)\n\t\t\treturn size;\n\t\t*flags |= FLAGS_DID_NOTE;\n\t\treturn size;\n\t}\n\n\tif (namesz == 4 && strcmp((char *)&nbuf[noff], \"GNU\") == 0 &&\n\t xnh_type == NT_GNU_BUILD_ID && (descsz == 16 || descsz == 20)) {\n\t uint8_t desc[20];\n\t uint32_t i;\n\t if (file_printf(ms, \", BuildID[%s]=\", descsz == 16 ? \"md5/uuid\" :\n\t\t\"sha1\") == -1)\n\t\t return size;\n\t (void)memcpy(desc, &nbuf[doff], descsz);\n\t for (i = 0; i < descsz; i++)\n\t\tif (file_printf(ms, \"%02x\", desc[i]) == -1)\n\t\t return size;\n\t *flags |= FLAGS_DID_BUILD_ID;\n\t}\n\n\tif (namesz == 4 && strcmp((char *)&nbuf[noff], \"PaX\") == 0 &&\n\t xnh_type == NT_NETBSD_PAX && descsz == 4) {\n\t\tstatic const char *pax[] = {\n\t\t \"+mprotect\",\n\t\t \"-mprotect\",\n\t\t \"+segvguard\",\n\t\t \"-segvguard\",\n\t\t \"+ASLR\",\n\t\t \"-ASLR\",\n\t\t};\n\t\tuint32_t desc;\n\t\tsize_t i;\n\t\tint did = 0;\n\n\t\t(void)memcpy(&desc, &nbuf[doff], sizeof(desc));\n\t\tdesc = elf_getu32(swap, desc);\n\n\t\tif (desc && file_printf(ms, \", PaX: \") == -1)\n\t\t\treturn size;\n\n\t\tfor (i = 0; i < __arraycount(pax); i++) {\n\t\t\tif (((1 << i) & desc) == 0)\n\t\t\t\tcontinue;\n\t\t\tif (file_printf(ms, \"%s%s\", did++ ? \",\" : \"\",\n\t\t\t pax[i]) == -1)\n\t\t\t\treturn size;\n\t\t}\n\t}\n\n\tif (namesz == 7 && strcmp((char *)&nbuf[noff], \"NetBSD\") == 0) {\n\t\tswitch (xnh_type) {\n\t\tcase NT_NETBSD_VERSION:\n\t\t\tif (descsz == 4) {\n\t\t\t\tdo_note_netbsd_version(ms, swap, &nbuf[doff]);\n\t\t\t\t*flags |= FLAGS_DID_NOTE;\n\t\t\t\treturn size;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase NT_NETBSD_MARCH:\n\t\t\tif (file_printf(ms, \", compiled for: %.*s\", (int)descsz,\n\t\t\t (const char *)&nbuf[doff]) == -1)\n\t\t\t\treturn size;\n\t\t\tbreak;\n\t\tcase NT_NETBSD_CMODEL:\n\t\t\tif (file_printf(ms, \", compiler model: %.*s\",\n\t\t\t (int)descsz, (const char *)&nbuf[doff]) == -1)\n\t\t\t\treturn size;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (file_printf(ms, \", note=%u\", xnh_type) == -1)\n\t\t\t\treturn size;\n\t\t\tbreak;\n\t\t}\n\t\treturn size;\n\t}\n\n\tif (namesz == 8 && strcmp((char *)&nbuf[noff], \"FreeBSD\") == 0) {\n\t \tif (xnh_type == NT_FREEBSD_VERSION && descsz == 4) {\n\t\t\tdo_note_freebsd_version(ms, swap, &nbuf[doff]);\n\t\t\t*flags |= FLAGS_DID_NOTE;\n\t\t\treturn size;\n\t\t}\n\t}\n\n\tif (namesz == 8 && strcmp((char *)&nbuf[noff], \"OpenBSD\") == 0 &&\n\t xnh_type == NT_OPENBSD_VERSION && descsz == 4) {\n\t\tif (file_printf(ms, \", for OpenBSD\") == -1)\n\t\t\treturn size;\n\t\t/* Content of note is always 0 */\n\t\t*flags |= FLAGS_DID_NOTE;\n\t\treturn size;\n\t}\n\n\tif (namesz == 10 && strcmp((char *)&nbuf[noff], \"DragonFly\") == 0 &&\n\t xnh_type == NT_DRAGONFLY_VERSION && descsz == 4) {\n\t\tuint32_t desc;\n\t\tif (file_printf(ms, \", for DragonFly\") == -1)\n\t\t\treturn size;\n\t\t(void)memcpy(&desc, &nbuf[doff], sizeof(desc));\n\t\tdesc = elf_getu32(swap, desc);\n\t\tif (file_printf(ms, \" %d.%d.%d\", desc / 100000,\n\t\t desc / 10000 % 10, desc % 10000) == -1)\n\t\t\treturn size;\n\t\t*flags |= FLAGS_DID_NOTE;\n\t\treturn size;\n\t}\n\ncore:\n\t/*\n\t * Sigh. The 2.0.36 kernel in Debian 2.1, at\n\t * least, doesn't correctly implement name\n\t * sections, in core dumps, as specified by\n\t * the \"Program Linking\" section of \"UNIX(R) System\n\t * V Release 4 Programmer's Guide: ANSI C and\n\t * Programming Support Tools\", because my copy\n\t * clearly says \"The first 'namesz' bytes in 'name'\n\t * contain a *null-terminated* [emphasis mine]\n\t * character representation of the entry's owner\n\t * or originator\", but the 2.0.36 kernel code\n\t * doesn't include the terminating null in the\n\t * name....\n\t */\n\tif ((namesz == 4 && strncmp((char *)&nbuf[noff], \"CORE\", 4) == 0) ||\n\t (namesz == 5 && strcmp((char *)&nbuf[noff], \"CORE\") == 0)) {\n\t\tos_style = OS_STYLE_SVR4;\n\t} \n\n\tif ((namesz == 8 && strcmp((char *)&nbuf[noff], \"FreeBSD\") == 0)) {\n\t\tos_style = OS_STYLE_FREEBSD;\n\t}\n\n\tif ((namesz >= 11 && strncmp((char *)&nbuf[noff], \"NetBSD-CORE\", 11)\n\t == 0)) {\n\t\tos_style = OS_STYLE_NETBSD;\n\t}\n\n#ifdef ELFCORE\n\tif ((*flags & FLAGS_DID_CORE) != 0)\n\t\treturn size;\n\n\tif (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) {\n\t\tif (file_printf(ms, \", %s-style\", os_style_names[os_style])\n\t\t == -1)\n\t\t\treturn size;\n\t\t*flags |= FLAGS_DID_CORE_STYLE;\n\t}\n\n\tswitch (os_style) {\n\tcase OS_STYLE_NETBSD:\n\t\tif (xnh_type == NT_NETBSD_CORE_PROCINFO) {\n\t\t\tuint32_t signo;\n\t\t\t/*\n\t\t\t * Extract the program name. It is at\n\t\t\t * offset 0x7c, and is up to 32-bytes,\n\t\t\t * including the terminating NUL.\n\t\t\t */\n\t\t\tif (file_printf(ms, \", from '%.31s'\",\n\t\t\t file_printable(sbuf, sizeof(sbuf),\n\t\t\t (const char *)&nbuf[doff + 0x7c])) == -1)\n\t\t\t\treturn size;\n\t\t\t\n\t\t\t/*\n\t\t\t * Extract the signal number. It is at\n\t\t\t * offset 0x08.\n\t\t\t */\n\t\t\t(void)memcpy(&signo, &nbuf[doff + 0x08],\n\t\t\t sizeof(signo));\n\t\t\tif (file_printf(ms, \" (signal %u)\",\n\t\t\t elf_getu32(swap, signo)) == -1)\n\t\t\t\treturn size;\n\t\t\t*flags |= FLAGS_DID_CORE;\n\t\t\treturn size;\n\t\t}\n\t\tbreak;\n\n\tdefault:\n\t\tif (xnh_type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) {\n\t\t\tsize_t i, j;\n\t\t\tunsigned char c;\n\t\t\t/*\n\t\t\t * Extract the program name. We assume\n\t\t\t * it to be 16 characters (that's what it\n\t\t\t * is in SunOS 5.x and Linux).\n\t\t\t *\n\t\t\t * Unfortunately, it's at a different offset\n\t\t\t * in various OSes, so try multiple offsets.\n\t\t\t * If the characters aren't all printable,\n\t\t\t * reject it.\n\t\t\t */\n\t\t\tfor (i = 0; i < NOFFSETS; i++) {\n\t\t\t\tunsigned char *cname, *cp;\n\t\t\t\tsize_t reloffset = prpsoffsets(i);\n\t\t\t\tsize_t noffset = doff + reloffset;\n\t\t\t\tsize_t k;\n\t\t\t\tfor (j = 0; j < 16; j++, noffset++,\n\t\t\t\t reloffset++) {\n\t\t\t\t\t/*\n\t\t\t\t\t * Make sure we're not past\n\t\t\t\t\t * the end of the buffer; if\n\t\t\t\t\t * we are, just give up.\n\t\t\t\t\t */\n\t\t\t\t\tif (noffset >= size)\n\t\t\t\t\t\tgoto tryanother;\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Make sure we're not past\n\t\t\t\t\t * the end of the contents;\n\t\t\t\t\t * if we are, this obviously\n\t\t\t\t\t * isn't the right offset.\n\t\t\t\t\t */\n\t\t\t\t\tif (reloffset >= descsz)\n\t\t\t\t\t\tgoto tryanother;\n\n\t\t\t\t\tc = nbuf[noffset];\n\t\t\t\t\tif (c == '\\0') {\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * A '\\0' at the\n\t\t\t\t\t\t * beginning is\n\t\t\t\t\t\t * obviously wrong.\n\t\t\t\t\t\t * Any other '\\0'\n\t\t\t\t\t\t * means we're done.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tif (j == 0)\n\t\t\t\t\t\t\tgoto tryanother;\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * A nonprintable\n\t\t\t\t\t\t * character is also\n\t\t\t\t\t\t * wrong.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tif (!isprint(c) || isquote(c))\n\t\t\t\t\t\t\tgoto tryanother;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t/*\n\t\t\t\t * Well, that worked.\n\t\t\t\t */\n\n\t\t\t\t/*\n\t\t\t\t * Try next offsets, in case this match is\n\t\t\t\t * in the middle of a string.\n\t\t\t\t */\n\t\t\t\tfor (k = i + 1 ; k < NOFFSETS ; k++) {\n\t\t\t\t\tsize_t no;\n\t\t\t\t\tint adjust = 1;\n\t\t\t\t\tif (prpsoffsets(k) >= prpsoffsets(i))\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tfor (no = doff + prpsoffsets(k);\n\t\t\t\t\t no < doff + prpsoffsets(i); no++)\n\t\t\t\t\t\tadjust = adjust\n\t\t\t\t\t\t && isprint(nbuf[no]);\n\t\t\t\t\tif (adjust)\n\t\t\t\t\t\ti = k;\n\t\t\t\t}\n\n\t\t\t\tcname = (unsigned char *)\n\t\t\t\t &nbuf[doff + prpsoffsets(i)];\n\t\t\t\tfor (cp = cname; *cp && isprint(*cp); cp++)\n\t\t\t\t\tcontinue;\n\t\t\t\t/*\n\t\t\t\t * Linux apparently appends a space at the end\n\t\t\t\t * of the command line: remove it.\n\t\t\t\t */\n\t\t\t\twhile (cp > cname && isspace(cp[-1]))\n\t\t\t\t\tcp--;\n\t\t\t\tif (file_printf(ms, \", from '%.*s'\",\n\t\t\t\t (int)(cp - cname), cname) == -1)\n\t\t\t\t\treturn size;\n\t\t\t\t*flags |= FLAGS_DID_CORE;\n\t\t\t\treturn size;\n\n\t\t\ttryanother:\n\t\t\t\t;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n#endif\n\treturn offset;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': '- Add a limit to the number of ELF notes processed (Suggested by Alexander\n Cherepanov)\n- Restructure ELF note printing so that we don't print the same message\n multiple times on repeated notes of the same kind.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void jpc_qmfb_join_col(jpc_fix_t *a, int numrows, int stride,\n int parity)\n{\n\n\tint bufsize = JPC_CEILDIVPOW2(numrows, 1);\n#if !defined(HAVE_VLA)\n\tjpc_fix_t joinbuf[QMFB_JOINBUFSIZE];\n#else\n\tjpc_fix_t joinbuf[bufsize];\n#endif\n\tjpc_fix_t *buf = joinbuf;\n\tregister jpc_fix_t *srcptr;\n\tregister jpc_fix_t *dstptr;\n\tregister int n;\n\tint hstartcol;\n\n#if !defined(HAVE_VLA)\n\t/* Allocate memory for the join buffer from the heap. */\n\tif (bufsize > QMFB_JOINBUFSIZE) {\n\t\tif (!(buf = jas_malloc(bufsize * sizeof(jpc_fix_t)))) {\n\t\t\t/* We have no choice but to commit suicide. */\n\t\t\tabort();\n\t\t}\n\t}\n#endif\n\n\thstartcol = (numrows + 1 - parity) >> 1;\n\n\t/* Save the samples from the lowpass channel. */\n\tn = hstartcol;\n\tsrcptr = &a[0];\n\tdstptr = buf;\n\twhile (n-- > 0) {\n\t\t*dstptr = *srcptr;\n\t\tsrcptr += stride;\n\t\t++dstptr;\n\t}\n\t/* Copy the samples from the highpass channel into place. */\n\tsrcptr = &a[hstartcol * stride];\n\tdstptr = &a[(1 - parity) * stride];\n\tn = numrows - hstartcol;\n\twhile (n-- > 0) {\n\t\t*dstptr = *srcptr;\n\t\tdstptr += 2 * stride;\n\t\tsrcptr += stride;\n\t}\n\t/* Copy the samples from the lowpass channel into place. */\n\tsrcptr = buf;\n\tdstptr = &a[parity * stride];\n\tn = hstartcol;\n\twhile (n-- > 0) {\n\t\t*dstptr = *srcptr;\n\t\tdstptr += 2 * stride;\n\t\t++srcptr;\n\t}\n\n#if !defined(HAVE_VLA)\n\t/* If the join buffer was allocated on the heap, free this memory. */\n\tif (buf != joinbuf) {\n\t\tjas_free(buf);\n\t}\n#endif\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'CVE-2014-8158'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: kg_unseal(minor_status, context_handle, input_token_buffer,\n message_buffer, conf_state, qop_state, toktype)\n OM_uint32 *minor_status;\n gss_ctx_id_t context_handle;\n gss_buffer_t input_token_buffer;\n gss_buffer_t message_buffer;\n int *conf_state;\n gss_qop_t *qop_state;\n int toktype;\n{\n krb5_gss_ctx_id_rec *ctx;\n unsigned char *ptr;\n unsigned int bodysize;\n int err;\n int toktype2;\n int vfyflags = 0;\n OM_uint32 ret;\n\n ctx = (krb5_gss_ctx_id_rec *) context_handle;\n\n if (! ctx->established) {\n *minor_status = KG_CTX_INCOMPLETE;\n return(GSS_S_NO_CONTEXT);\n }\n\n /* parse the token, leave the data in message_buffer, setting conf_state */\n\n /* verify the header */\n\n ptr = (unsigned char *) input_token_buffer->value;\n\n\n err = g_verify_token_header(ctx->mech_used,\n &bodysize, &ptr, -1,\n input_token_buffer->length,\n vfyflags);\n if (err) {\n *minor_status = err;\n return GSS_S_DEFECTIVE_TOKEN;\n }\n\n if (bodysize < 2) {\n *minor_status = (OM_uint32)G_BAD_TOK_HEADER;\n return GSS_S_DEFECTIVE_TOKEN;\n }\n\n toktype2 = load_16_be(ptr);\n\n ptr += 2;\n bodysize -= 2;\n\n switch (toktype2) {\n case KG2_TOK_MIC_MSG:\n case KG2_TOK_WRAP_MSG:\n case KG2_TOK_DEL_CTX:\n ret = gss_krb5int_unseal_token_v3(&ctx->k5_context, minor_status, ctx,\n ptr, bodysize, message_buffer,\n conf_state, qop_state, toktype);\n break;\n case KG_TOK_MIC_MSG:\n case KG_TOK_WRAP_MSG:\n case KG_TOK_DEL_CTX:\n ret = kg_unseal_v1(ctx->k5_context, minor_status, ctx, ptr, bodysize,\n message_buffer, conf_state, qop_state,\n toktype);\n break;\n default:\n *minor_status = (OM_uint32)G_BAD_TOK_HEADER;\n ret = GSS_S_DEFECTIVE_TOKEN;\n break;\n }\n\n if (ret != 0)\n save_error_info (*minor_status, ctx->k5_context);\n\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'Fix gss_process_context_token() [CVE-2014-5352]\n\n[MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not\nactually delete the context; that leaves the caller with a dangling\npointer and no way to know that it is invalid. Instead, mark the\ncontext as terminated, and check for terminated contexts in the GSS\nfunctions which expect established contexts. Also add checks in\nexport_sec_context and pseudo_random, and adjust t_prf.c for the\npseudo_random check.\n\nticket: 8055 (new)\ntarget_version: 1.13.1\ntags: pullup'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: kg_seal_iov(OM_uint32 *minor_status,\n gss_ctx_id_t context_handle,\n int conf_req_flag,\n gss_qop_t qop_req,\n int *conf_state,\n gss_iov_buffer_desc *iov,\n int iov_count,\n int toktype)\n{\n krb5_gss_ctx_id_rec *ctx;\n krb5_error_code code;\n krb5_context context;\n\n if (qop_req != 0) {\n *minor_status = (OM_uint32)G_UNKNOWN_QOP;\n return GSS_S_FAILURE;\n }\n\n ctx = (krb5_gss_ctx_id_rec *)context_handle;\n if (!ctx->established) {\n *minor_status = KG_CTX_INCOMPLETE;\n return GSS_S_NO_CONTEXT;\n }\n\n if (conf_req_flag && kg_integ_only_iov(iov, iov_count)) {\n /* may be more sensible to return an error here */\n conf_req_flag = FALSE;\n }\n\n context = ctx->k5_context;\n switch (ctx->proto) {\n case 0:\n code = make_seal_token_v1_iov(context, ctx, conf_req_flag,\n conf_state, iov, iov_count, toktype);\n break;\n case 1:\n code = gss_krb5int_make_seal_token_v3_iov(context, ctx, conf_req_flag,\n conf_state, iov, iov_count, toktype);\n break;\n default:\n code = G_UNKNOWN_QOP;\n break;\n }\n\n if (code != 0) {\n *minor_status = code;\n save_error_info(*minor_status, context);\n return GSS_S_FAILURE;\n }\n\n *minor_status = 0;\n\n return GSS_S_COMPLETE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'Fix gss_process_context_token() [CVE-2014-5352]\n\n[MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not\nactually delete the context; that leaves the caller with a dangling\npointer and no way to know that it is invalid. Instead, mark the\ncontext as terminated, and check for terminated contexts in the GSS\nfunctions which expect established contexts. Also add checks in\nexport_sec_context and pseudo_random, and adjust t_prf.c for the\npseudo_random check.\n\nticket: 8055 (new)\ntarget_version: 1.13.1\ntags: pullup'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: _bt_check_unique(Relation rel, IndexTuple itup, Relation heapRel,\n\t\t\t\t Buffer buf, OffsetNumber offset, ScanKey itup_scankey,\n\t\t\t\t IndexUniqueCheck checkUnique, bool *is_unique)\n{\n\tTupleDesc\titupdesc = RelationGetDescr(rel);\n\tint\t\t\tnatts = rel->rd_rel->relnatts;\n\tSnapshotData SnapshotDirty;\n\tOffsetNumber maxoff;\n\tPage\t\tpage;\n\tBTPageOpaque opaque;\n\tBuffer\t\tnbuf = InvalidBuffer;\n\tbool\t\tfound = false;\n\n\t/* Assume unique until we find a duplicate */\n\t*is_unique = true;\n\n\tInitDirtySnapshot(SnapshotDirty);\n\n\tpage = BufferGetPage(buf);\n\topaque = (BTPageOpaque) PageGetSpecialPointer(page);\n\tmaxoff = PageGetMaxOffsetNumber(page);\n\n\t/*\n\t * Scan over all equal tuples, looking for live conflicts.\n\t */\n\tfor (;;)\n\t{\n\t\tItemId\t\tcuritemid;\n\t\tIndexTuple\tcuritup;\n\t\tBlockNumber nblkno;\n\n\t\t/*\n\t\t * make sure the offset points to an actual item before trying to\n\t\t * examine it...\n\t\t */\n\t\tif (offset <= maxoff)\n\t\t{\n\t\t\tcuritemid = PageGetItemId(page, offset);\n\n\t\t\t/*\n\t\t\t * We can skip items that are marked killed.\n\t\t\t *\n\t\t\t * Formerly, we applied _bt_isequal() before checking the kill\n\t\t\t * flag, so as to fall out of the item loop as soon as possible.\n\t\t\t * However, in the presence of heavy update activity an index may\n\t\t\t * contain many killed items with the same key; running\n\t\t\t * _bt_isequal() on each killed item gets expensive. Furthermore\n\t\t\t * it is likely that the non-killed version of each key appears\n\t\t\t * first, so that we didn't actually get to exit any sooner\n\t\t\t * anyway. So now we just advance over killed items as quickly as\n\t\t\t * we can. We only apply _bt_isequal() when we get to a non-killed\n\t\t\t * item or the end of the page.\n\t\t\t */\n\t\t\tif (!ItemIdIsDead(curitemid))\n\t\t\t{\n\t\t\t\tItemPointerData htid;\n\t\t\t\tbool\t\tall_dead;\n\n\t\t\t\t/*\n\t\t\t\t * _bt_compare returns 0 for (1,NULL) and (1,NULL) - this's\n\t\t\t\t * how we handling NULLs - and so we must not use _bt_compare\n\t\t\t\t * in real comparison, but only for ordering/finding items on\n\t\t\t\t * pages. - vadim 03/24/97\n\t\t\t\t */\n\t\t\t\tif (!_bt_isequal(itupdesc, page, offset, natts, itup_scankey))\n\t\t\t\t\tbreak;\t\t/* we're past all the equal tuples */\n\n\t\t\t\t/* okay, we gotta fetch the heap tuple ... */\n\t\t\t\tcuritup = (IndexTuple) PageGetItem(page, curitemid);\n\t\t\t\thtid = curitup->t_tid;\n\n\t\t\t\t/*\n\t\t\t\t * If we are doing a recheck, we expect to find the tuple we\n\t\t\t\t * are rechecking. It's not a duplicate, but we have to keep\n\t\t\t\t * scanning.\n\t\t\t\t */\n\t\t\t\tif (checkUnique == UNIQUE_CHECK_EXISTING &&\n\t\t\t\t\tItemPointerCompare(&htid, &itup->t_tid) == 0)\n\t\t\t\t{\n\t\t\t\t\tfound = true;\n\t\t\t\t}\n\n\t\t\t\t/*\n\t\t\t\t * We check the whole HOT-chain to see if there is any tuple\n\t\t\t\t * that satisfies SnapshotDirty. This is necessary because we\n\t\t\t\t * have just a single index entry for the entire chain.\n\t\t\t\t */\n\t\t\t\telse if (heap_hot_search(&htid, heapRel, &SnapshotDirty,\n\t\t\t\t\t\t\t\t\t\t &all_dead))\n\t\t\t\t{\n\t\t\t\t\tTransactionId xwait;\n\n\t\t\t\t\t/*\n\t\t\t\t\t * It is a duplicate. If we are only doing a partial\n\t\t\t\t\t * check, then don't bother checking if the tuple is being\n\t\t\t\t\t * updated in another transaction. Just return the fact\n\t\t\t\t\t * that it is a potential conflict and leave the full\n\t\t\t\t\t * check till later.\n\t\t\t\t\t */\n\t\t\t\t\tif (checkUnique == UNIQUE_CHECK_PARTIAL)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (nbuf != InvalidBuffer)\n\t\t\t\t\t\t\t_bt_relbuf(rel, nbuf);\n\t\t\t\t\t\t*is_unique = false;\n\t\t\t\t\t\treturn InvalidTransactionId;\n\t\t\t\t\t}\n\n\t\t\t\t\t/*\n\t\t\t\t\t * If this tuple is being updated by other transaction\n\t\t\t\t\t * then we have to wait for its commit/abort.\n\t\t\t\t\t */\n\t\t\t\t\txwait = (TransactionIdIsValid(SnapshotDirty.xmin)) ?\n\t\t\t\t\t\tSnapshotDirty.xmin : SnapshotDirty.xmax;\n\n\t\t\t\t\tif (TransactionIdIsValid(xwait))\n\t\t\t\t\t{\n\t\t\t\t\t\tif (nbuf != InvalidBuffer)\n\t\t\t\t\t\t\t_bt_relbuf(rel, nbuf);\n\t\t\t\t\t\t/* Tell _bt_doinsert to wait... */\n\t\t\t\t\t\treturn xwait;\n\t\t\t\t\t}\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Otherwise we have a definite conflict. But before\n\t\t\t\t\t * complaining, look to see if the tuple we want to insert\n\t\t\t\t\t * is itself now committed dead --- if so, don't complain.\n\t\t\t\t\t * This is a waste of time in normal scenarios but we must\n\t\t\t\t\t * do it to support CREATE INDEX CONCURRENTLY.\n\t\t\t\t\t *\n\t\t\t\t\t * We must follow HOT-chains here because during\n\t\t\t\t\t * concurrent index build, we insert the root TID though\n\t\t\t\t\t * the actual tuple may be somewhere in the HOT-chain.\n\t\t\t\t\t * While following the chain we might not stop at the\n\t\t\t\t\t * exact tuple which triggered the insert, but that's OK\n\t\t\t\t\t * because if we find a live tuple anywhere in this chain,\n\t\t\t\t\t * we have a unique key conflict. The other live tuple is\n\t\t\t\t\t * not part of this chain because it had a different index\n\t\t\t\t\t * entry.\n\t\t\t\t\t */\n\t\t\t\t\thtid = itup->t_tid;\n\t\t\t\t\tif (heap_hot_search(&htid, heapRel, SnapshotSelf, NULL))\n\t\t\t\t\t{\n\t\t\t\t\t\t/* Normal case --- it's still live */\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * It's been deleted, so no error, and no need to\n\t\t\t\t\t\t * continue searching\n\t\t\t\t\t\t */\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\t/*\n\t\t\t\t\t * This is a definite conflict. Break the tuple down into\n\t\t\t\t\t * datums and report the error. But first, make sure we\n\t\t\t\t\t * release the buffer locks we're holding ---\n\t\t\t\t\t * BuildIndexValueDescription could make catalog accesses,\n\t\t\t\t\t * which in the worst case might touch this same index and\n\t\t\t\t\t * cause deadlocks.\n\t\t\t\t\t */\n\t\t\t\t\tif (nbuf != InvalidBuffer)\n\t\t\t\t\t\t_bt_relbuf(rel, nbuf);\n\t\t\t\t\t_bt_relbuf(rel, buf);\n\n\t\t\t\t\t{\n\t\t\t\t\t\tDatum\t\tvalues[INDEX_MAX_KEYS];\n\t\t\t\t\t\tbool\t\tisnull[INDEX_MAX_KEYS];\n\n\t\t\t\t\t\tindex_deform_tuple(itup, RelationGetDescr(rel),\n\t\t\t\t\t\t\t\t\t\t values, isnull);\n\t\t\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t\t\t(errcode(ERRCODE_UNIQUE_VIOLATION),\n\t\t\t\t\t\t\t\t errmsg(\"duplicate key value violates unique constraint \\\"%s\\\"\",\n\t\t\t\t\t\t\t\t\t\tRelationGetRelationName(rel)),\n\t\t\t\t\t\t\t\t errdetail(\"Key %s already exists.\",\n\t\t\t\t\t\t\t\t\t\t BuildIndexValueDescription(rel,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvalues, isnull)),\n\t\t\t\t\t\t\t\t errtableconstraint(heapRel,\n\t\t\t\t\t\t\t\t\t\t\t RelationGetRelationName(rel))));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (all_dead)\n\t\t\t\t{\n\t\t\t\t\t/*\n\t\t\t\t\t * The conflicting tuple (or whole HOT chain) is dead to\n\t\t\t\t\t * everyone, so we may as well mark the index entry\n\t\t\t\t\t * killed.\n\t\t\t\t\t */\n\t\t\t\t\tItemIdMarkDead(curitemid);\n\t\t\t\t\topaque->btpo_flags |= BTP_HAS_GARBAGE;\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Mark buffer with a dirty hint, since state is not\n\t\t\t\t\t * crucial. Be sure to mark the proper buffer dirty.\n\t\t\t\t\t */\n\t\t\t\t\tif (nbuf != InvalidBuffer)\n\t\t\t\t\t\tMarkBufferDirtyHint(nbuf, true);\n\t\t\t\t\telse\n\t\t\t\t\t\tMarkBufferDirtyHint(buf, true);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * Advance to next tuple to continue checking.\n\t\t */\n\t\tif (offset < maxoff)\n\t\t\toffset = OffsetNumberNext(offset);\n\t\telse\n\t\t{\n\t\t\t/* If scankey == hikey we gotta check the next page too */\n\t\t\tif (P_RIGHTMOST(opaque))\n\t\t\t\tbreak;\n\t\t\tif (!_bt_isequal(itupdesc, page, P_HIKEY,\n\t\t\t\t\t\t\t natts, itup_scankey))\n\t\t\t\tbreak;\n\t\t\t/* Advance to next non-dead page --- there must be one */\n\t\t\tfor (;;)\n\t\t\t{\n\t\t\t\tnblkno = opaque->btpo_next;\n\t\t\t\tnbuf = _bt_relandgetbuf(rel, nbuf, nblkno, BT_READ);\n\t\t\t\tpage = BufferGetPage(nbuf);\n\t\t\t\topaque = (BTPageOpaque) PageGetSpecialPointer(page);\n\t\t\t\tif (!P_IGNORE(opaque))\n\t\t\t\t\tbreak;\n\t\t\t\tif (P_RIGHTMOST(opaque))\n\t\t\t\t\telog(ERROR, \"fell off the end of index \\\"%s\\\"\",\n\t\t\t\t\t\t RelationGetRelationName(rel));\n\t\t\t}\n\t\t\tmaxoff = PageGetMaxOffsetNumber(page);\n\t\t\toffset = P_FIRSTDATAKEY(opaque);\n\t\t}\n\t}\n\n\t/*\n\t * If we are doing a recheck then we should have found the tuple we are\n\t * checking. Otherwise there's something very wrong --- probably, the\n\t * index is on a non-immutable expression.\n\t */\n\tif (checkUnique == UNIQUE_CHECK_EXISTING && !found)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_INTERNAL_ERROR),\n\t\t\t\t errmsg(\"failed to re-find tuple within index \\\"%s\\\"\",\n\t\t\t\t\t\tRelationGetRelationName(rel)),\n\t\t errhint(\"This may be because of a non-immutable index expression.\"),\n\t\t\t\t errtableconstraint(heapRel,\n\t\t\t\t\t\t\t\t\tRelationGetRelationName(rel))));\n\n\tif (nbuf != InvalidBuffer)\n\t\t_bt_relbuf(rel, nbuf);\n\n\treturn InvalidTransactionId;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-209'], 'message': 'Fix column-privilege leak in error-message paths\n\nWhile building error messages to return to the user,\nBuildIndexValueDescription, ExecBuildSlotValueDescription and\nri_ReportViolation would happily include the entire key or entire row in\nthe result returned to the user, even if the user didn't have access to\nview all of the columns being included.\n\nInstead, include only those columns which the user is providing or which\nthe user has select rights on. If the user does not have any rights\nto view the table or any of the columns involved then no detail is\nprovided and a NULL value is returned from BuildIndexValueDescription\nand ExecBuildSlotValueDescription. Note that, for key cases, the user\nmust have access to all of the columns for the key to be shown; a\npartial key will not be returned.\n\nFurther, in master only, do not return any data for cases where row\nsecurity is enabled on the relation and row security should be applied\nfor the user. This required a bit of refactoring and moving of things\naround related to RLS- note the addition of utils/misc/rls.c.\n\nBack-patch all the way, as column-level privileges are now in all\nsupported versions.\n\nThis has been assigned CVE-2014-8161, but since the issue and the patch\nhave already been publicized on pgsql-hackers, there's no point in trying\nto hide this commit.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ri_ReportViolation(const RI_ConstraintInfo *riinfo,\n\t\t\t\t Relation pk_rel, Relation fk_rel,\n\t\t\t\t HeapTuple violator, TupleDesc tupdesc,\n\t\t\t\t int queryno, bool spi_err)\n{\n\tStringInfoData key_names;\n\tStringInfoData key_values;\n\tbool\t\tonfk;\n\tconst int16 *attnums;\n\tint\t\t\tidx;\n\n\tif (spi_err)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_INTERNAL_ERROR),\n\t\t\t\t errmsg(\"referential integrity query on \\\"%s\\\" from constraint \\\"%s\\\" on \\\"%s\\\" gave unexpected result\",\n\t\t\t\t\t\tRelationGetRelationName(pk_rel),\n\t\t\t\t\t\tNameStr(riinfo->conname),\n\t\t\t\t\t\tRelationGetRelationName(fk_rel)),\n\t\t\t\t errhint(\"This is most likely due to a rule having rewritten the query.\")));\n\n\t/*\n\t * Determine which relation to complain about. If tupdesc wasn't passed\n\t * by caller, assume the violator tuple came from there.\n\t */\n\tonfk = (queryno == RI_PLAN_CHECK_LOOKUPPK);\n\tif (onfk)\n\t{\n\t\tattnums = riinfo->fk_attnums;\n\t\tif (tupdesc == NULL)\n\t\t\ttupdesc = fk_rel->rd_att;\n\t}\n\telse\n\t{\n\t\tattnums = riinfo->pk_attnums;\n\t\tif (tupdesc == NULL)\n\t\t\ttupdesc = pk_rel->rd_att;\n\t}\n\n\t/* Get printable versions of the keys involved */\n\tinitStringInfo(&key_names);\n\tinitStringInfo(&key_values);\n\tfor (idx = 0; idx < riinfo->nkeys; idx++)\n\t{\n\t\tint\t\t\tfnum = attnums[idx];\n\t\tchar\t *name,\n\t\t\t\t *val;\n\n\t\tname = SPI_fname(tupdesc, fnum);\n\t\tval = SPI_getvalue(violator, tupdesc, fnum);\n\t\tif (!val)\n\t\t\tval = \"null\";\n\n\t\tif (idx > 0)\n\t\t{\n\t\t\tappendStringInfoString(&key_names, \", \");\n\t\t\tappendStringInfoString(&key_values, \", \");\n\t\t}\n\t\tappendStringInfoString(&key_names, name);\n\t\tappendStringInfoString(&key_values, val);\n\t}\n\n\tif (onfk)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_FOREIGN_KEY_VIOLATION),\n\t\t\t\t errmsg(\"insert or update on table \\\"%s\\\" violates foreign key constraint \\\"%s\\\"\",\n\t\t\t\t\t\tRelationGetRelationName(fk_rel),\n\t\t\t\t\t\tNameStr(riinfo->conname)),\n\t\t\t\t errdetail(\"Key (%s)=(%s) is not present in table \\\"%s\\\".\",\n\t\t\t\t\t\t key_names.data, key_values.data,\n\t\t\t\t\t\t RelationGetRelationName(pk_rel)),\n\t\t\t\t errtableconstraint(fk_rel, NameStr(riinfo->conname))));\n\telse\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_FOREIGN_KEY_VIOLATION),\n\t\t\t\t errmsg(\"update or delete on table \\\"%s\\\" violates foreign key constraint \\\"%s\\\" on table \\\"%s\\\"\",\n\t\t\t\t\t\tRelationGetRelationName(pk_rel),\n\t\t\t\t\t\tNameStr(riinfo->conname),\n\t\t\t\t\t\tRelationGetRelationName(fk_rel)),\n\t\t\terrdetail(\"Key (%s)=(%s) is still referenced from table \\\"%s\\\".\",\n\t\t\t\t\t key_names.data, key_values.data,\n\t\t\t\t\t RelationGetRelationName(fk_rel)),\n\t\t\t\t errtableconstraint(fk_rel, NameStr(riinfo->conname))));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-209'], 'message': 'Fix column-privilege leak in error-message paths\n\nWhile building error messages to return to the user,\nBuildIndexValueDescription, ExecBuildSlotValueDescription and\nri_ReportViolation would happily include the entire key or entire row in\nthe result returned to the user, even if the user didn't have access to\nview all of the columns being included.\n\nInstead, include only those columns which the user is providing or which\nthe user has select rights on. If the user does not have any rights\nto view the table or any of the columns involved then no detail is\nprovided and a NULL value is returned from BuildIndexValueDescription\nand ExecBuildSlotValueDescription. Note that, for key cases, the user\nmust have access to all of the columns for the key to be shown; a\npartial key will not be returned.\n\nFurther, in master only, do not return any data for cases where row\nsecurity is enabled on the relation and row security should be applied\nfor the user. This required a bit of refactoring and moving of things\naround related to RLS- note the addition of utils/misc/rls.c.\n\nBack-patch all the way, as column-level privileges are now in all\nsupported versions.\n\nThis has been assigned CVE-2014-8161, but since the issue and the patch\nhave already been publicized on pgsql-hackers, there's no point in trying\nto hide this commit.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: set_hunkmax (void)\n{\n if (!p_line)\n\tp_line = (char **) malloc (hunkmax * sizeof *p_line);\n if (!p_len)\n\tp_len = (size_t *) malloc (hunkmax * sizeof *p_len);\n if (!p_Char)\n\tp_Char = malloc (hunkmax * sizeof *p_Char);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'Fail when out of memory in set_hunkmax()\n\nsrc/pch.c (another_hunk): Call set_hunkmax() from here to make sure it is\ncalled even when falling back from plan A to plan B.\n(open_patch_file): No need to call set_hunkmax() anymore.\nsrc/pch.c (set_hunkmax): Fail when out of memory. Make static.\nsrc/pch.h: Remove set_hunkmax() prototype.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int em_sysenter(struct x86_emulate_ctxt *ctxt)\n{\n\tconst struct x86_emulate_ops *ops = ctxt->ops;\n\tstruct desc_struct cs, ss;\n\tu64 msr_data;\n\tu16 cs_sel, ss_sel;\n\tu64 efer = 0;\n\n\tops->get_msr(ctxt, MSR_EFER, &efer);\n\t/* inject #GP if in real mode */\n\tif (ctxt->mode == X86EMUL_MODE_REAL)\n\t\treturn emulate_gp(ctxt, 0);\n\n\t/*\n\t * Not recognized on AMD in compat mode (but is recognized in legacy\n\t * mode).\n\t */\n\tif ((ctxt->mode == X86EMUL_MODE_PROT32) && (efer & EFER_LMA)\n\t && !vendor_intel(ctxt))\n\t\treturn emulate_ud(ctxt);\n\n\t/* sysenter/sysexit have not been tested in 64bit mode. */\n\tif (ctxt->mode == X86EMUL_MODE_PROT64)\n\t\treturn X86EMUL_UNHANDLEABLE;\n\n\tsetup_syscalls_segments(ctxt, &cs, &ss);\n\n\tops->get_msr(ctxt, MSR_IA32_SYSENTER_CS, &msr_data);\n\tswitch (ctxt->mode) {\n\tcase X86EMUL_MODE_PROT32:\n\t\tif ((msr_data & 0xfffc) == 0x0)\n\t\t\treturn emulate_gp(ctxt, 0);\n\t\tbreak;\n\tcase X86EMUL_MODE_PROT64:\n\t\tif (msr_data == 0x0)\n\t\t\treturn emulate_gp(ctxt, 0);\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\n\tctxt->eflags &= ~(EFLG_VM | EFLG_IF);\n\tcs_sel = (u16)msr_data;\n\tcs_sel &= ~SELECTOR_RPL_MASK;\n\tss_sel = cs_sel + 8;\n\tss_sel &= ~SELECTOR_RPL_MASK;\n\tif (ctxt->mode == X86EMUL_MODE_PROT64 || (efer & EFER_LMA)) {\n\t\tcs.d = 0;\n\t\tcs.l = 1;\n\t}\n\n\tops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS);\n\tops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS);\n\n\tops->get_msr(ctxt, MSR_IA32_SYSENTER_EIP, &msr_data);\n\tctxt->_eip = msr_data;\n\n\tops->get_msr(ctxt, MSR_IA32_SYSENTER_ESP, &msr_data);\n\t*reg_write(ctxt, VCPU_REGS_RSP) = msr_data;\n\n\treturn X86EMUL_CONTINUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362', 'CWE-269'], 'message': 'KVM: x86: SYSENTER emulation is broken\n\nSYSENTER emulation is broken in several ways:\n1. It misses the case of 16-bit code segments completely (CVE-2015-0239).\n2. MSR_IA32_SYSENTER_CS is checked in 64-bit mode incorrectly (bits 0 and 1 can\n still be set without causing #GP).\n3. MSR_IA32_SYSENTER_EIP and MSR_IA32_SYSENTER_ESP are not masked in\n legacy-mode.\n4. There is some unneeded code.\n\nFix it.\n\nCc: stable@vger.linux.org\nSigned-off-by: Nadav Amit \nSigned-off-by: Paolo Bonzini '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: fmtfloat(double value, char type, int forcesign, int leftjust,\n\t\t int minlen, int zpad, int precision, int pointflag,\n\t\t PrintfTarget *target)\n{\n\tint\t\t\tsignvalue = 0;\n\tint\t\t\tvallen;\n\tchar\t\tfmt[32];\n\tchar\t\tconvert[512];\n\tint\t\t\tpadlen = 0;\t\t/* amount to pad */\n\n\t/* we rely on regular C library's sprintf to do the basic conversion */\n\tif (pointflag)\n\t\tsprintf(fmt, \"%%.%d%c\", precision, type);\n\telse\n\t\tsprintf(fmt, \"%%%c\", type);\n\n\tif (adjust_sign((value < 0), forcesign, &signvalue))\n\t\tvalue = -value;\n\n\tvallen = sprintf(convert, fmt, value);\n\n\tadjust_padlen(minlen, vallen, leftjust, &padlen);\n\n\tleading_pad(zpad, &signvalue, &padlen, target);\n\n\tdostr(convert, vallen, target);\n\n\ttrailing_pad(&padlen, target);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'port/snprintf(): fix overflow and do padding\n\nPrevent port/snprintf() from overflowing its local fixed-size\nbuffer and pad to the desired number of digits with zeros, even\nif the precision is beyond the ability of the native sprintf().\nport/snprintf() is only used on systems that lack a native\nsnprintf().\n\nReported by Bruce Momjian. Patch by Tom Lane.\tBackpatch to all\nsupported versions.\n\nSecurity: CVE-2015-0242'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: pg_GSS_recvauth(Port *port)\n{\n\tOM_uint32\tmaj_stat,\n\t\t\t\tmin_stat,\n\t\t\t\tlmin_s,\n\t\t\t\tgflags;\n\tint\t\t\tmtype;\n\tint\t\t\tret;\n\tStringInfoData buf;\n\tgss_buffer_desc gbuf;\n\n\t/*\n\t * GSS auth is not supported for protocol versions before 3, because it\n\t * relies on the overall message length word to determine the GSS payload\n\t * size in AuthenticationGSSContinue and PasswordMessage messages. (This\n\t * is, in fact, a design error in our GSS support, because protocol\n\t * messages are supposed to be parsable without relying on the length\n\t * word; but it's not worth changing it now.)\n\t */\n\tif (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)\n\t\tereport(FATAL,\n\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t errmsg(\"GSSAPI is not supported in protocol version 2\")));\n\n\tif (pg_krb_server_keyfile && strlen(pg_krb_server_keyfile) > 0)\n\t{\n\t\t/*\n\t\t * Set default Kerberos keytab file for the Krb5 mechanism.\n\t\t *\n\t\t * setenv(\"KRB5_KTNAME\", pg_krb_server_keyfile, 0); except setenv()\n\t\t * not always available.\n\t\t */\n\t\tif (getenv(\"KRB5_KTNAME\") == NULL)\n\t\t{\n\t\t\tsize_t\t\tkt_len = strlen(pg_krb_server_keyfile) + 14;\n\t\t\tchar\t *kt_path = malloc(kt_len);\n\n\t\t\tif (!kt_path)\n\t\t\t{\n\t\t\t\tereport(LOG,\n\t\t\t\t\t\t(errcode(ERRCODE_OUT_OF_MEMORY),\n\t\t\t\t\t\t errmsg(\"out of memory\")));\n\t\t\t\treturn STATUS_ERROR;\n\t\t\t}\n\t\t\tsnprintf(kt_path, kt_len, \"KRB5_KTNAME=%s\", pg_krb_server_keyfile);\n\t\t\tputenv(kt_path);\n\t\t}\n\t}\n\n\t/*\n\t * We accept any service principal that's present in our keytab. This\n\t * increases interoperability between kerberos implementations that see\n\t * for example case sensitivity differently, while not really opening up\n\t * any vector of attack.\n\t */\n\tport->gss->cred = GSS_C_NO_CREDENTIAL;\n\n\t/*\n\t * Initialize sequence with an empty context\n\t */\n\tport->gss->ctx = GSS_C_NO_CONTEXT;\n\n\t/*\n\t * Loop through GSSAPI message exchange. This exchange can consist of\n\t * multiple messags sent in both directions. First message is always from\n\t * the client. All messages from client to server are password packets\n\t * (type 'p').\n\t */\n\tdo\n\t{\n\t\tmtype = pq_getbyte();\n\t\tif (mtype != 'p')\n\t\t{\n\t\t\t/* Only log error if client didn't disconnect. */\n\t\t\tif (mtype != EOF)\n\t\t\t\tereport(COMMERROR,\n\t\t\t\t\t\t(errcode(ERRCODE_PROTOCOL_VIOLATION),\n\t\t\t\t\t\t errmsg(\"expected GSS response, got message type %d\",\n\t\t\t\t\t\t\t\tmtype)));\n\t\t\treturn STATUS_ERROR;\n\t\t}\n\n\t\t/* Get the actual GSS token */\n\t\tinitStringInfo(&buf);\n\t\tif (pq_getmessage(&buf, PG_MAX_AUTH_TOKEN_LENGTH))\n\t\t{\n\t\t\t/* EOF - pq_getmessage already logged error */\n\t\t\tpfree(buf.data);\n\t\t\treturn STATUS_ERROR;\n\t\t}\n\n\t\t/* Map to GSSAPI style buffer */\n\t\tgbuf.length = buf.len;\n\t\tgbuf.value = buf.data;\n\n\t\telog(DEBUG4, \"Processing received GSS token of length %u\",\n\t\t\t (unsigned int) gbuf.length);\n\n\t\tmaj_stat = gss_accept_sec_context(\n\t\t\t\t\t\t\t\t\t\t &min_stat,\n\t\t\t\t\t\t\t\t\t\t &port->gss->ctx,\n\t\t\t\t\t\t\t\t\t\t port->gss->cred,\n\t\t\t\t\t\t\t\t\t\t &gbuf,\n\t\t\t\t\t\t\t\t\t\t GSS_C_NO_CHANNEL_BINDINGS,\n\t\t\t\t\t\t\t\t\t\t &port->gss->name,\n\t\t\t\t\t\t\t\t\t\t NULL,\n\t\t\t\t\t\t\t\t\t\t &port->gss->outbuf,\n\t\t\t\t\t\t\t\t\t\t &gflags,\n\t\t\t\t\t\t\t\t\t\t NULL,\n\t\t\t\t\t\t\t\t\t\t NULL);\n\n\t\t/* gbuf no longer used */\n\t\tpfree(buf.data);\n\n\t\telog(DEBUG5, \"gss_accept_sec_context major: %d, \"\n\t\t\t \"minor: %d, outlen: %u, outflags: %x\",\n\t\t\t maj_stat, min_stat,\n\t\t\t (unsigned int) port->gss->outbuf.length, gflags);\n\n\t\tif (port->gss->outbuf.length != 0)\n\t\t{\n\t\t\t/*\n\t\t\t * Negotiation generated data to be sent to the client.\n\t\t\t */\n\t\t\telog(DEBUG4, \"sending GSS response token of length %u\",\n\t\t\t\t (unsigned int) port->gss->outbuf.length);\n\n\t\t\tsendAuthRequest(port, AUTH_REQ_GSS_CONT);\n\n\t\t\tgss_release_buffer(&lmin_s, &port->gss->outbuf);\n\t\t}\n\n\t\tif (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)\n\t\t{\n\t\t\tgss_delete_sec_context(&lmin_s, &port->gss->ctx, GSS_C_NO_BUFFER);\n\t\t\tpg_GSS_error(ERROR,\n\t\t\t\t\t gettext_noop(\"accepting GSS security context failed\"),\n\t\t\t\t\t\t maj_stat, min_stat);\n\t\t}\n\n\t\tif (maj_stat == GSS_S_CONTINUE_NEEDED)\n\t\t\telog(DEBUG4, \"GSS continue needed\");\n\n\t} while (maj_stat == GSS_S_CONTINUE_NEEDED);\n\n\tif (port->gss->cred != GSS_C_NO_CREDENTIAL)\n\t{\n\t\t/*\n\t\t * Release service principal credentials\n\t\t */\n\t\tgss_release_cred(&min_stat, &port->gss->cred);\n\t}\n\n\t/*\n\t * GSS_S_COMPLETE indicates that authentication is now complete.\n\t *\n\t * Get the name of the user that authenticated, and compare it to the pg\n\t * username that was specified for the connection.\n\t */\n\tmaj_stat = gss_display_name(&min_stat, port->gss->name, &gbuf, NULL);\n\tif (maj_stat != GSS_S_COMPLETE)\n\t\tpg_GSS_error(ERROR,\n\t\t\t\t\t gettext_noop(\"retrieving GSS user name failed\"),\n\t\t\t\t\t maj_stat, min_stat);\n\n\t/*\n\t * Split the username at the realm separator\n\t */\n\tif (strchr(gbuf.value, '@'))\n\t{\n\t\tchar\t *cp = strchr(gbuf.value, '@');\n\n\t\t/*\n\t\t * If we are not going to include the realm in the username that is\n\t\t * passed to the ident map, destructively modify it here to remove the\n\t\t * realm. Then advance past the separator to check the realm.\n\t\t */\n\t\tif (!port->hba->include_realm)\n\t\t\t*cp = '\\0';\n\t\tcp++;\n\n\t\tif (port->hba->krb_realm != NULL && strlen(port->hba->krb_realm))\n\t\t{\n\t\t\t/*\n\t\t\t * Match the realm part of the name first\n\t\t\t */\n\t\t\tif (pg_krb_caseins_users)\n\t\t\t\tret = pg_strcasecmp(port->hba->krb_realm, cp);\n\t\t\telse\n\t\t\t\tret = strcmp(port->hba->krb_realm, cp);\n\n\t\t\tif (ret)\n\t\t\t{\n\t\t\t\t/* GSS realm does not match */\n\t\t\t\telog(DEBUG2,\n\t\t\t\t \"GSSAPI realm (%s) and configured realm (%s) don't match\",\n\t\t\t\t\t cp, port->hba->krb_realm);\n\t\t\t\tgss_release_buffer(&lmin_s, &gbuf);\n\t\t\t\treturn STATUS_ERROR;\n\t\t\t}\n\t\t}\n\t}\n\telse if (port->hba->krb_realm && strlen(port->hba->krb_realm))\n\t{\n\t\telog(DEBUG2,\n\t\t\t \"GSSAPI did not return realm but realm matching was requested\");\n\n\t\tgss_release_buffer(&lmin_s, &gbuf);\n\t\treturn STATUS_ERROR;\n\t}\n\n\tret = check_usermap(port->hba->usermap, port->user_name, gbuf.value,\n\t\t\t\t\t\tpg_krb_caseins_users);\n\n\tgss_release_buffer(&lmin_s, &gbuf);\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-89'], 'message': 'Be more careful to not lose sync in the FE/BE protocol.\n\nIf any error occurred while we were in the middle of reading a protocol\nmessage from the client, we could lose sync, and incorrectly try to\ninterpret a part of another message as a new protocol message. That will\nusually lead to an \"invalid frontend message\" error that terminates the\nconnection. However, this is a security issue because an attacker might\nbe able to deliberately cause an error, inject a Query message in what's\nsupposed to be just user data, and have the server execute it.\n\nWe were quite careful to not have CHECK_FOR_INTERRUPTS() calls or other\noperations that could ereport(ERROR) in the middle of processing a message,\nbut a query cancel interrupt or statement timeout could nevertheless cause\nit to happen. Also, the V2 fastpath and COPY handling were not so careful.\nIt's very difficult to recover in the V2 COPY protocol, so we will just\nterminate the connection on error. In practice, that's what happened\npreviously anyway, as we lost protocol sync.\n\nTo fix, add a new variable in pqcomm.c, PqCommReadingMsg, that is set\nwhenever we're in the middle of reading a message. When it's set, we cannot\nsafely ERROR out and continue running, because we might've read only part\nof a message. PqCommReadingMsg acts somewhat similarly to critical sections\nin that if an error occurs while it's set, the error handler will force the\nconnection to be terminated, as if the error was FATAL. It's not\nimplemented by promoting ERROR to FATAL in elog.c, like ERROR is promoted\nto PANIC in critical sections, because we want to be able to use\nPG_TRY/CATCH to recover and regain protocol sync. pq_getmessage() takes\nadvantage of that to prevent an OOM error from terminating the connection.\n\nTo prevent unnecessary connection terminations, add a holdoff mechanism\nsimilar to HOLD/RESUME_INTERRUPTS() that can be used hold off query cancel\ninterrupts, but still allow die interrupts. The rules on which interrupts\nare processed when are now a bit more complicated, so refactor\nProcessInterrupts() and the calls to it in signal handlers so that the\nsignal handlers always call it if ImmediateInterruptOK is set, and\nProcessInterrupts() can decide to not do anything if the other conditions\nare not met.\n\nReported by Emil Lenngren. Patch reviewed by Noah Misch and Andres Freund.\nBackpatch to all supported versions.\n\nSecurity: CVE-2015-0244'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: CopyGetData(CopyState cstate, void *databuf, int minread, int maxread)\n{\n\tint\t\t\tbytesread = 0;\n\n\tswitch (cstate->copy_dest)\n\t{\n\t\tcase COPY_FILE:\n\t\t\tbytesread = fread(databuf, 1, maxread, cstate->copy_file);\n\t\t\tif (ferror(cstate->copy_file))\n\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t(errcode_for_file_access(),\n\t\t\t\t\t\t errmsg(\"could not read from COPY file: %m\")));\n\t\t\tbreak;\n\t\tcase COPY_OLD_FE:\n\n\t\t\t/*\n\t\t\t * We cannot read more than minread bytes (which in practice is 1)\n\t\t\t * because old protocol doesn't have any clear way of separating\n\t\t\t * the COPY stream from following data. This is slow, but not any\n\t\t\t * slower than the code path was originally, and we don't care\n\t\t\t * much anymore about the performance of old protocol.\n\t\t\t */\n\t\t\tif (pq_getbytes((char *) databuf, minread))\n\t\t\t{\n\t\t\t\t/* Only a \\. terminator is legal EOF in old protocol */\n\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t(errcode(ERRCODE_CONNECTION_FAILURE),\n\t\t\t\t\t\t errmsg(\"unexpected EOF on client connection with an open transaction\")));\n\t\t\t}\n\t\t\tbytesread = minread;\n\t\t\tbreak;\n\t\tcase COPY_NEW_FE:\n\t\t\twhile (maxread > 0 && bytesread < minread && !cstate->fe_eof)\n\t\t\t{\n\t\t\t\tint\t\t\tavail;\n\n\t\t\t\twhile (cstate->fe_msgbuf->cursor >= cstate->fe_msgbuf->len)\n\t\t\t\t{\n\t\t\t\t\t/* Try to receive another message */\n\t\t\t\t\tint\t\t\tmtype;\n\n\t\t\treadmessage:\n\t\t\t\t\tmtype = pq_getbyte();\n\t\t\t\t\tif (mtype == EOF)\n\t\t\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t\t\t(errcode(ERRCODE_CONNECTION_FAILURE),\n\t\t\t\t\t\t\t\t errmsg(\"unexpected EOF on client connection with an open transaction\")));\n\t\t\t\t\tif (pq_getmessage(cstate->fe_msgbuf, 0))\n\t\t\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t\t\t(errcode(ERRCODE_CONNECTION_FAILURE),\n\t\t\t\t\t\t\t\t errmsg(\"unexpected EOF on client connection with an open transaction\")));\n\t\t\t\t\tswitch (mtype)\n\t\t\t\t\t{\n\t\t\t\t\t\tcase 'd':\t\t/* CopyData */\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'c':\t\t/* CopyDone */\n\t\t\t\t\t\t\t/* COPY IN correctly terminated by frontend */\n\t\t\t\t\t\t\tcstate->fe_eof = true;\n\t\t\t\t\t\t\treturn bytesread;\n\t\t\t\t\t\tcase 'f':\t\t/* CopyFail */\n\t\t\t\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t\t\t\t(errcode(ERRCODE_QUERY_CANCELED),\n\t\t\t\t\t\t\t\t\t errmsg(\"COPY from stdin failed: %s\",\n\t\t\t\t\t\t\t\t\t pq_getmsgstring(cstate->fe_msgbuf))));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'H':\t\t/* Flush */\n\t\t\t\t\t\tcase 'S':\t\t/* Sync */\n\n\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t * Ignore Flush/Sync for the convenience of client\n\t\t\t\t\t\t\t * libraries (such as libpq) that may send those\n\t\t\t\t\t\t\t * without noticing that the command they just\n\t\t\t\t\t\t\t * sent was COPY.\n\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\tgoto readmessage;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t\t\t\t(errcode(ERRCODE_PROTOCOL_VIOLATION),\n\t\t\t\t\t\t\t\t\t errmsg(\"unexpected message type 0x%02X during COPY from stdin\",\n\t\t\t\t\t\t\t\t\t\t\tmtype)));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tavail = cstate->fe_msgbuf->len - cstate->fe_msgbuf->cursor;\n\t\t\t\tif (avail > maxread)\n\t\t\t\t\tavail = maxread;\n\t\t\t\tpq_copymsgbytes(cstate->fe_msgbuf, databuf, avail);\n\t\t\t\tdatabuf = (void *) ((char *) databuf + avail);\n\t\t\t\tmaxread -= avail;\n\t\t\t\tbytesread += avail;\n\t\t\t}\n\t\t\tbreak;\n\t}\n\n\treturn bytesread;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-89'], 'message': 'Be more careful to not lose sync in the FE/BE protocol.\n\nIf any error occurred while we were in the middle of reading a protocol\nmessage from the client, we could lose sync, and incorrectly try to\ninterpret a part of another message as a new protocol message. That will\nusually lead to an \"invalid frontend message\" error that terminates the\nconnection. However, this is a security issue because an attacker might\nbe able to deliberately cause an error, inject a Query message in what's\nsupposed to be just user data, and have the server execute it.\n\nWe were quite careful to not have CHECK_FOR_INTERRUPTS() calls or other\noperations that could ereport(ERROR) in the middle of processing a message,\nbut a query cancel interrupt or statement timeout could nevertheless cause\nit to happen. Also, the V2 fastpath and COPY handling were not so careful.\nIt's very difficult to recover in the V2 COPY protocol, so we will just\nterminate the connection on error. In practice, that's what happened\npreviously anyway, as we lost protocol sync.\n\nTo fix, add a new variable in pqcomm.c, PqCommReadingMsg, that is set\nwhenever we're in the middle of reading a message. When it's set, we cannot\nsafely ERROR out and continue running, because we might've read only part\nof a message. PqCommReadingMsg acts somewhat similarly to critical sections\nin that if an error occurs while it's set, the error handler will force the\nconnection to be terminated, as if the error was FATAL. It's not\nimplemented by promoting ERROR to FATAL in elog.c, like ERROR is promoted\nto PANIC in critical sections, because we want to be able to use\nPG_TRY/CATCH to recover and regain protocol sync. pq_getmessage() takes\nadvantage of that to prevent an OOM error from terminating the connection.\n\nTo prevent unnecessary connection terminations, add a holdoff mechanism\nsimilar to HOLD/RESUME_INTERRUPTS() that can be used hold off query cancel\ninterrupts, but still allow die interrupts. The rules on which interrupts\nare processed when are now a bit more complicated, so refactor\nProcessInterrupts() and the calls to it in signal handlers so that the\nsignal handlers always call it if ImmediateInterruptOK is set, and\nProcessInterrupts() can decide to not do anything if the other conditions\nare not met.\n\nReported by Emil Lenngren. Patch reviewed by Noah Misch and Andres Freund.\nBackpatch to all supported versions.\n\nSecurity: CVE-2015-0244'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: dophn_exec(struct magic_set *ms, int clazz, int swap, int fd, off_t off,\n int num, size_t size, off_t fsize, int *flags, int sh_num)\n{\n\tElf32_Phdr ph32;\n\tElf64_Phdr ph64;\n\tconst char *linking_style = \"statically\";\n\tconst char *interp = \"\";\n\tunsigned char nbuf[BUFSIZ];\n\tchar ibuf[BUFSIZ];\n\tssize_t bufsize;\n\tsize_t offset, align, len;\n\t\n\tif (size != xph_sizeof) {\n\t\tif (file_printf(ms, \", corrupted program header size\") == -1)\n\t\t\treturn -1;\n\t\treturn 0;\n\t}\n\n \tfor ( ; num; num--) {\n\t\tif (pread(fd, xph_addr, xph_sizeof, off) == -1) {\n\t\t\tfile_badread(ms);\n\t\t\treturn -1;\n\t\t}\n\n\t\toff += size;\n\t\tbufsize = 0;\n\t\talign = 4;\n\n\t\t/* Things we can determine before we seek */\n\t\tswitch (xph_type) {\n\t\tcase PT_DYNAMIC:\n\t\t\tlinking_style = \"dynamically\";\n\t\t\tbreak;\n\t\tcase PT_NOTE:\n\t\t\tif (sh_num)\t/* Did this through section headers */\n\t\t\t\tcontinue;\n\t\t\tif (((align = xph_align) & 0x80000000UL) != 0 ||\n\t\t\t align < 4) {\n\t\t\t\tif (file_printf(ms, \n\t\t\t\t \", invalid note alignment 0x%lx\",\n\t\t\t\t (unsigned long)align) == -1)\n\t\t\t\t\treturn -1;\n\t\t\t\talign = 4;\n\t\t\t}\n\t\t\t/*FALLTHROUGH*/\n\t\tcase PT_INTERP:\n\t\t\tlen = xph_filesz < sizeof(nbuf) ? xph_filesz\n\t\t\t : sizeof(nbuf);\n\t\t\tbufsize = pread(fd, nbuf, len, xph_offset);\n\t\t\tif (bufsize == -1) {\n\t\t\t\tfile_badread(ms);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (fsize != SIZE_UNKNOWN && xph_offset > fsize) {\n\t\t\t\t/* Maybe warn here? */\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Things we can determine when we seek */\n\t\tswitch (xph_type) {\n\t\tcase PT_INTERP:\n\t\t\tif (bufsize && nbuf[0]) {\n\t\t\t\tnbuf[bufsize - 1] = '\\0';\n\t\t\t\tinterp = (const char *)nbuf;\n\t\t\t} else\n\t\t\t\tinterp = \"*empty*\";\n\t\t\tbreak;\n\t\tcase PT_NOTE:\n\t\t\t/*\n\t\t\t * This is a PT_NOTE section; loop through all the notes\n\t\t\t * in the section.\n\t\t\t */\n\t\t\toffset = 0;\n\t\t\tfor (;;) {\n\t\t\t\tif (offset >= (size_t)bufsize)\n\t\t\t\t\tbreak;\n\t\t\t\toffset = donote(ms, nbuf, offset,\n\t\t\t\t (size_t)bufsize, clazz, swap, align,\n\t\t\t\t flags);\n\t\t\t\tif (offset == 0)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (file_printf(ms, \", %s linked\", linking_style)\n\t == -1)\n\t\treturn -1;\n\tif (interp[0])\n\t\tif (file_printf(ms, \", interpreter %s\",\n\t\t file_printable(ibuf, sizeof(ibuf), interp)) == -1)\n\t\t\treturn -1;\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-703'], 'message': 'Bail out on partial reads, from Alexander Cherepanov'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: v3_keyid (gcry_mpi_t a, u32 *ki)\n{\n byte *buffer, *p;\n size_t nbytes;\n\n if (gcry_mpi_print (GCRYMPI_FMT_USG, NULL, 0, &nbytes, a ))\n BUG ();\n /* fixme: allocate it on the stack */\n buffer = xmalloc (nbytes);\n if (gcry_mpi_print( GCRYMPI_FMT_USG, buffer, nbytes, NULL, a ))\n BUG ();\n if (nbytes < 8) /* oops */\n ki[0] = ki[1] = 0;\n else\n {\n p = buffer + nbytes - 8;\n ki[0] = (p[0] << 24) | (p[1] <<16) | (p[2] << 8) | p[3];\n p += 4;\n ki[1] = (p[0] << 24) | (p[1] <<16) | (p[2] << 8) | p[3];\n }\n xfree (buffer);\n return ki[1];\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Use inline functions to convert buffer data to scalars.\n\n* common/host2net.h (buf16_to_ulong, buf16_to_uint): New.\n(buf16_to_ushort, buf16_to_u16): New.\n(buf32_to_size_t, buf32_to_ulong, buf32_to_uint, buf32_to_u32): New.\n--\n\nCommit 91b826a38880fd8a989318585eb502582636ddd8 was not enough to\navoid all sign extension on shift problems. Hanno B\u00f6ck found a case\nwith an invalid read due to this problem. To fix that once and for\nall almost all uses of \"<< 24\" and \"<< 8\" are changed by this patch to\nuse an inline function from host2net.h.\n\nSigned-off-by: Werner Koch '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: parse (IOBUF inp, PACKET * pkt, int onlykeypkts, off_t * retpos,\n int *skip, IOBUF out, int do_skip\n#ifdef DEBUG_PARSE_PACKET\n , const char *dbg_w, const char *dbg_f, int dbg_l\n#endif\n )\n{\n int rc = 0, c, ctb, pkttype, lenbytes;\n unsigned long pktlen;\n byte hdr[8];\n int hdrlen;\n int new_ctb = 0, partial = 0;\n int with_uid = (onlykeypkts == 2);\n off_t pos;\n\n *skip = 0;\n assert (!pkt->pkt.generic);\n if (retpos || list_mode)\n {\n pos = iobuf_tell (inp);\n if (retpos)\n *retpos = pos;\n }\n else\n pos = 0; /* (silence compiler warning) */\n\n if ((ctb = iobuf_get (inp)) == -1)\n {\n rc = -1;\n goto leave;\n }\n hdrlen = 0;\n hdr[hdrlen++] = ctb;\n if (!(ctb & 0x80))\n {\n log_error (\"%s: invalid packet (ctb=%02x)\\n\", iobuf_where (inp), ctb);\n rc = gpg_error (GPG_ERR_INV_PACKET);\n goto leave;\n }\n pktlen = 0;\n new_ctb = !!(ctb & 0x40);\n if (new_ctb)\n {\n pkttype = ctb & 0x3f;\n if ((c = iobuf_get (inp)) == -1)\n\t{\n\t log_error (\"%s: 1st length byte missing\\n\", iobuf_where (inp));\n\t rc = gpg_error (GPG_ERR_INV_PACKET);\n\t goto leave;\n\t}\n\n\n hdr[hdrlen++] = c;\n if (c < 192)\n pktlen = c;\n else if (c < 224)\n {\n pktlen = (c - 192) * 256;\n if ((c = iobuf_get (inp)) == -1)\n {\n log_error (\"%s: 2nd length byte missing\\n\",\n iobuf_where (inp));\n rc = gpg_error (GPG_ERR_INV_PACKET);\n goto leave;\n }\n hdr[hdrlen++] = c;\n pktlen += c + 192;\n }\n else if (c == 255)\n {\n pktlen = (hdr[hdrlen++] = iobuf_get_noeof (inp)) << 24;\n pktlen |= (hdr[hdrlen++] = iobuf_get_noeof (inp)) << 16;\n pktlen |= (hdr[hdrlen++] = iobuf_get_noeof (inp)) << 8;\n if ((c = iobuf_get (inp)) == -1)\n {\n log_error (\"%s: 4 byte length invalid\\n\", iobuf_where (inp));\n rc = gpg_error (GPG_ERR_INV_PACKET);\n goto leave;\n }\n pktlen |= (hdr[hdrlen++] = c);\n }\n else /* Partial body length. */\n {\n switch (pkttype)\n {\n case PKT_PLAINTEXT:\n case PKT_ENCRYPTED:\n case PKT_ENCRYPTED_MDC:\n case PKT_COMPRESSED:\n iobuf_set_partial_block_mode (inp, c & 0xff);\n pktlen = 0;\t/* To indicate partial length. */\n partial = 1;\n break;\n\n default:\n log_error (\"%s: partial length for invalid\"\n \" packet type %d\\n\", iobuf_where (inp), pkttype);\n rc = gpg_error (GPG_ERR_INV_PACKET);\n goto leave;\n }\n }\n\n }\n else\n {\n pkttype = (ctb >> 2) & 0xf;\n lenbytes = ((ctb & 3) == 3) ? 0 : (1 << (ctb & 3));\n if (!lenbytes)\n\t{\n\t pktlen = 0;\t/* Don't know the value. */\n\t /* This isn't really partial, but we can treat it the same\n\t in a \"read until the end\" sort of way. */\n\t partial = 1;\n\t if (pkttype != PKT_ENCRYPTED && pkttype != PKT_PLAINTEXT\n\t && pkttype != PKT_COMPRESSED)\n\t {\n\t log_error (\"%s: indeterminate length for invalid\"\n\t\t\t \" packet type %d\\n\", iobuf_where (inp), pkttype);\n\t rc = gpg_error (GPG_ERR_INV_PACKET);\n\t goto leave;\n\t }\n\t}\n else\n\t{\n\t for (; lenbytes; lenbytes--)\n\t {\n\t pktlen <<= 8;\n\t pktlen |= hdr[hdrlen++] = iobuf_get_noeof (inp);\n\t }\n\t}\n }\n\n if (pktlen == (unsigned long) (-1))\n {\n /* With some probability this is caused by a problem in the\n * the uncompressing layer - in some error cases it just loops\n * and spits out 0xff bytes. */\n log_error (\"%s: garbled packet detected\\n\", iobuf_where (inp));\n g10_exit (2);\n }\n\n if (out && pkttype)\n {\n rc = iobuf_write (out, hdr, hdrlen);\n if (!rc)\n\trc = copy_packet (inp, out, pkttype, pktlen, partial);\n goto leave;\n }\n\n if (with_uid && pkttype == PKT_USER_ID)\n ;\n else if (do_skip\n\t || !pkttype\n\t || (onlykeypkts && pkttype != PKT_PUBLIC_SUBKEY\n\t && pkttype != PKT_PUBLIC_KEY\n\t && pkttype != PKT_SECRET_SUBKEY && pkttype != PKT_SECRET_KEY))\n {\n iobuf_skip_rest (inp, pktlen, partial);\n *skip = 1;\n rc = 0;\n goto leave;\n }\n\n if (DBG_PACKET)\n {\n#ifdef DEBUG_PARSE_PACKET\n log_debug (\"parse_packet(iob=%d): type=%d length=%lu%s (%s.%s.%d)\\n\",\n\t\t iobuf_id (inp), pkttype, pktlen, new_ctb ? \" (new_ctb)\" : \"\",\n\t\t dbg_w, dbg_f, dbg_l);\n#else\n log_debug (\"parse_packet(iob=%d): type=%d length=%lu%s\\n\",\n\t\t iobuf_id (inp), pkttype, pktlen,\n\t\t new_ctb ? \" (new_ctb)\" : \"\");\n#endif\n }\n\n if (list_mode)\n es_fprintf (listfp, \"# off=%lu ctb=%02x tag=%d hlen=%d plen=%lu%s%s\\n\",\n (unsigned long)pos, ctb, pkttype, hdrlen, pktlen,\n partial? \" partial\":\"\",\n new_ctb? \" new-ctb\":\"\");\n\n pkt->pkttype = pkttype;\n rc = GPG_ERR_UNKNOWN_PACKET;\t/* default error */\n switch (pkttype)\n {\n case PKT_PUBLIC_KEY:\n case PKT_PUBLIC_SUBKEY:\n case PKT_SECRET_KEY:\n case PKT_SECRET_SUBKEY:\n pkt->pkt.public_key = xmalloc_clear (sizeof *pkt->pkt.public_key);\n rc = parse_key (inp, pkttype, pktlen, hdr, hdrlen, pkt);\n break;\n case PKT_SYMKEY_ENC:\n rc = parse_symkeyenc (inp, pkttype, pktlen, pkt);\n break;\n case PKT_PUBKEY_ENC:\n rc = parse_pubkeyenc (inp, pkttype, pktlen, pkt);\n break;\n case PKT_SIGNATURE:\n pkt->pkt.signature = xmalloc_clear (sizeof *pkt->pkt.signature);\n rc = parse_signature (inp, pkttype, pktlen, pkt->pkt.signature);\n break;\n case PKT_ONEPASS_SIG:\n pkt->pkt.onepass_sig = xmalloc_clear (sizeof *pkt->pkt.onepass_sig);\n rc = parse_onepass_sig (inp, pkttype, pktlen, pkt->pkt.onepass_sig);\n break;\n case PKT_USER_ID:\n rc = parse_user_id (inp, pkttype, pktlen, pkt);\n break;\n case PKT_ATTRIBUTE:\n pkt->pkttype = pkttype = PKT_USER_ID;\t/* we store it in the userID */\n rc = parse_attribute (inp, pkttype, pktlen, pkt);\n break;\n case PKT_OLD_COMMENT:\n case PKT_COMMENT:\n rc = parse_comment (inp, pkttype, pktlen, pkt);\n break;\n case PKT_RING_TRUST:\n parse_trust (inp, pkttype, pktlen, pkt);\n rc = 0;\n break;\n case PKT_PLAINTEXT:\n rc = parse_plaintext (inp, pkttype, pktlen, pkt, new_ctb, partial);\n break;\n case PKT_COMPRESSED:\n rc = parse_compressed (inp, pkttype, pktlen, pkt, new_ctb);\n break;\n case PKT_ENCRYPTED:\n case PKT_ENCRYPTED_MDC:\n rc = parse_encrypted (inp, pkttype, pktlen, pkt, new_ctb, partial);\n break;\n case PKT_MDC:\n rc = parse_mdc (inp, pkttype, pktlen, pkt, new_ctb);\n break;\n case PKT_GPG_CONTROL:\n rc = parse_gpg_control (inp, pkttype, pktlen, pkt, partial);\n break;\n case PKT_MARKER:\n rc = parse_marker (inp, pkttype, pktlen);\n break;\n default:\n skip_packet (inp, pkttype, pktlen, partial);\n break;\n }\n\n leave:\n /* FIXME: Do we leak in case of an error? */\n if (!rc && iobuf_error (inp))\n rc = GPG_ERR_INV_KEYRING;\n\n /* FIXME: We use only the error code for now to avoid problems with\n callers which have not been checked to always use gpg_err_code()\n when comparing error codes. */\n return rc == -1? -1 : gpg_err_code (rc);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Use inline functions to convert buffer data to scalars.\n\n* common/host2net.h (buf16_to_ulong, buf16_to_uint): New.\n(buf16_to_ushort, buf16_to_u16): New.\n(buf32_to_size_t, buf32_to_ulong, buf32_to_uint, buf32_to_u32): New.\n--\n\nCommit 91b826a38880fd8a989318585eb502582636ddd8 was not enough to\navoid all sign extension on shift problems. Hanno B\u00f6ck found a case\nwith an invalid read due to this problem. To fix that once and for\nall almost all uses of \"<< 24\" and \"<< 8\" are changed by this patch to\nuse an inline function from host2net.h.\n\nSigned-off-by: Werner Koch '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: control_pcsc_wrapped (int slot, pcsc_dword_t ioctl_code,\n const unsigned char *cntlbuf, size_t len,\n unsigned char *buffer, pcsc_dword_t *buflen)\n{\n long err = PCSC_E_NOT_TRANSACTED;\n reader_table_t slotp;\n unsigned char msgbuf[9];\n int i, n;\n size_t full_len;\n\n slotp = reader_table + slot;\n\n msgbuf[0] = 0x06; /* CONTROL command. */\n msgbuf[1] = ((len + 4) >> 24);\n msgbuf[2] = ((len + 4) >> 16);\n msgbuf[3] = ((len + 4) >> 8);\n msgbuf[4] = ((len + 4) );\n msgbuf[5] = (ioctl_code >> 24);\n msgbuf[6] = (ioctl_code >> 16);\n msgbuf[7] = (ioctl_code >> 8);\n msgbuf[8] = (ioctl_code );\n if ( writen (slotp->pcsc.req_fd, msgbuf, 9)\n || writen (slotp->pcsc.req_fd, cntlbuf, len))\n {\n log_error (\"error sending PC/SC CONTROL request: %s\\n\",\n strerror (errno));\n goto command_failed;\n }\n\n /* Read the response. */\n if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)\n {\n log_error (\"error receiving PC/SC CONTROL response: %s\\n\",\n i? strerror (errno) : \"premature EOF\");\n goto command_failed;\n }\n len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];\n if (msgbuf[0] != 0x81 || len < 4)\n {\n log_error (\"invalid response header from PC/SC received\\n\");\n goto command_failed;\n }\n len -= 4; /* Already read the error code. */\n err = PCSC_ERR_MASK ((msgbuf[5] << 24) | (msgbuf[6] << 16)\n | (msgbuf[7] << 8 ) | msgbuf[8]);\n if (err)\n {\n log_error (\"pcsc_control failed: %s (0x%lx)\\n\",\n pcsc_error_string (err), err);\n return pcsc_error_to_sw (err);\n }\n\n full_len = len;\n\n n = *buflen < len ? *buflen : len;\n if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len)) || len != n)\n {\n log_error (\"error receiving PC/SC CONTROL response: %s\\n\",\n i? strerror (errno) : \"premature EOF\");\n goto command_failed;\n }\n *buflen = n;\n\n full_len -= len;\n if (full_len)\n {\n log_error (\"pcsc_send_apdu: provided buffer too short - truncated\\n\");\n err = PCSC_E_INVALID_VALUE;\n }\n /* We need to read any rest of the response, to keep the\n protocol running. */\n while (full_len)\n {\n unsigned char dummybuf[128];\n\n n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf);\n if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n)\n {\n log_error (\"error receiving PC/SC CONTROL response: %s\\n\",\n i? strerror (errno) : \"premature EOF\");\n goto command_failed;\n }\n full_len -= n;\n }\n\n if (!err)\n return 0;\n\n command_failed:\n close (slotp->pcsc.req_fd);\n close (slotp->pcsc.rsp_fd);\n slotp->pcsc.req_fd = -1;\n slotp->pcsc.rsp_fd = -1;\n if (slotp->pcsc.pid != -1)\n kill (slotp->pcsc.pid, SIGTERM);\n slotp->pcsc.pid = (pid_t)(-1);\n slotp->used = 0;\n return pcsc_error_to_sw (err);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Use inline functions to convert buffer data to scalars.\n\n* common/host2net.h (buf16_to_ulong, buf16_to_uint): New.\n(buf16_to_ushort, buf16_to_u16): New.\n(buf32_to_size_t, buf32_to_ulong, buf32_to_uint, buf32_to_u32): New.\n--\n\nCommit 91b826a38880fd8a989318585eb502582636ddd8 was not enough to\navoid all sign extension on shift problems. Hanno B\u00f6ck found a case\nwith an invalid read due to this problem. To fix that once and for\nall almost all uses of \"<< 24\" and \"<< 8\" are changed by this patch to\nuse an inline function from host2net.h.\n\nSigned-off-by: Werner Koch '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: get16 (const byte *buffer)\n{\n ulong a;\n a = *buffer << 8;\n a |= buffer[1];\n return a;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Use inline functions to convert buffer data to scalars.\n\n* common/host2net.h (buf16_to_ulong, buf16_to_uint): New.\n(buf16_to_ushort, buf16_to_u16): New.\n(buf32_to_size_t, buf32_to_ulong, buf32_to_uint, buf32_to_u32): New.\n--\n\nCommit 91b826a38880fd8a989318585eb502582636ddd8 was not enough to\navoid all sign extension on shift problems. Hanno B\u00f6ck found a case\nwith an invalid read due to this problem. To fix that once and for\nall almost all uses of \"<< 24\" and \"<< 8\" are changed by this patch to\nuse an inline function from host2net.h.\n\nSigned-off-by: Werner Koch '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: buffer_to_u32( const byte *buffer )\n{\n unsigned long a;\n a = *buffer << 24;\n a |= buffer[1] << 16;\n a |= buffer[2] << 8;\n a |= buffer[3];\n return a;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Use inline functions to convert buffer data to scalars.\n\n* common/host2net.h (buf16_to_ulong, buf16_to_uint): New.\n(buf16_to_ushort, buf16_to_u16): New.\n(buf32_to_size_t, buf32_to_ulong, buf32_to_uint, buf32_to_u32): New.\n--\n\nCommit 91b826a38880fd8a989318585eb502582636ddd8 was not enough to\navoid all sign extension on shift problems. Hanno B\u00f6ck found a case\nwith an invalid read due to this problem. To fix that once and for\nall almost all uses of \"<< 24\" and \"<< 8\" are changed by this patch to\nuse an inline function from host2net.h.\n\nSigned-off-by: Werner Koch '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: xfs_attr3_leaf_list_int(\n\tstruct xfs_buf\t\t\t*bp,\n\tstruct xfs_attr_list_context\t*context)\n{\n\tstruct attrlist_cursor_kern\t*cursor;\n\tstruct xfs_attr_leafblock\t*leaf;\n\tstruct xfs_attr3_icleaf_hdr\tichdr;\n\tstruct xfs_attr_leaf_entry\t*entries;\n\tstruct xfs_attr_leaf_entry\t*entry;\n\tint\t\t\t\tretval;\n\tint\t\t\t\ti;\n\n\ttrace_xfs_attr_list_leaf(context);\n\n\tleaf = bp->b_addr;\n\txfs_attr3_leaf_hdr_from_disk(&ichdr, leaf);\n\tentries = xfs_attr3_leaf_entryp(leaf);\n\n\tcursor = context->cursor;\n\tcursor->initted = 1;\n\n\t/*\n\t * Re-find our place in the leaf block if this is a new syscall.\n\t */\n\tif (context->resynch) {\n\t\tentry = &entries[0];\n\t\tfor (i = 0; i < ichdr.count; entry++, i++) {\n\t\t\tif (be32_to_cpu(entry->hashval) == cursor->hashval) {\n\t\t\t\tif (cursor->offset == context->dupcnt) {\n\t\t\t\t\tcontext->dupcnt = 0;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcontext->dupcnt++;\n\t\t\t} else if (be32_to_cpu(entry->hashval) >\n\t\t\t\t\tcursor->hashval) {\n\t\t\t\tcontext->dupcnt = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (i == ichdr.count) {\n\t\t\ttrace_xfs_attr_list_notfound(context);\n\t\t\treturn 0;\n\t\t}\n\t} else {\n\t\tentry = &entries[0];\n\t\ti = 0;\n\t}\n\tcontext->resynch = 0;\n\n\t/*\n\t * We have found our place, start copying out the new attributes.\n\t */\n\tretval = 0;\n\tfor (; i < ichdr.count; entry++, i++) {\n\t\tif (be32_to_cpu(entry->hashval) != cursor->hashval) {\n\t\t\tcursor->hashval = be32_to_cpu(entry->hashval);\n\t\t\tcursor->offset = 0;\n\t\t}\n\n\t\tif (entry->flags & XFS_ATTR_INCOMPLETE)\n\t\t\tcontinue;\t\t/* skip incomplete entries */\n\n\t\tif (entry->flags & XFS_ATTR_LOCAL) {\n\t\t\txfs_attr_leaf_name_local_t *name_loc =\n\t\t\t\txfs_attr3_leaf_name_local(leaf, i);\n\n\t\t\tretval = context->put_listent(context,\n\t\t\t\t\t\tentry->flags,\n\t\t\t\t\t\tname_loc->nameval,\n\t\t\t\t\t\t(int)name_loc->namelen,\n\t\t\t\t\t\tbe16_to_cpu(name_loc->valuelen),\n\t\t\t\t\t\t&name_loc->nameval[name_loc->namelen]);\n\t\t\tif (retval)\n\t\t\t\treturn retval;\n\t\t} else {\n\t\t\txfs_attr_leaf_name_remote_t *name_rmt =\n\t\t\t\txfs_attr3_leaf_name_remote(leaf, i);\n\n\t\t\tint valuelen = be32_to_cpu(name_rmt->valuelen);\n\n\t\t\tif (context->put_value) {\n\t\t\t\txfs_da_args_t args;\n\n\t\t\t\tmemset((char *)&args, 0, sizeof(args));\n\t\t\t\targs.dp = context->dp;\n\t\t\t\targs.whichfork = XFS_ATTR_FORK;\n\t\t\t\targs.valuelen = valuelen;\n\t\t\t\targs.value = kmem_alloc(valuelen, KM_SLEEP | KM_NOFS);\n\t\t\t\targs.rmtblkno = be32_to_cpu(name_rmt->valueblk);\n\t\t\t\targs.rmtblkcnt = xfs_attr3_rmt_blocks(\n\t\t\t\t\t\t\targs.dp->i_mount, valuelen);\n\t\t\t\tretval = xfs_attr_rmtval_get(&args);\n\t\t\t\tif (retval)\n\t\t\t\t\treturn retval;\n\t\t\t\tretval = context->put_listent(context,\n\t\t\t\t\t\tentry->flags,\n\t\t\t\t\t\tname_rmt->name,\n\t\t\t\t\t\t(int)name_rmt->namelen,\n\t\t\t\t\t\tvaluelen,\n\t\t\t\t\t\targs.value);\n\t\t\t\tkmem_free(args.value);\n\t\t\t} else {\n\t\t\t\tretval = context->put_listent(context,\n\t\t\t\t\t\tentry->flags,\n\t\t\t\t\t\tname_rmt->name,\n\t\t\t\t\t\t(int)name_rmt->namelen,\n\t\t\t\t\t\tvaluelen,\n\t\t\t\t\t\tNULL);\n\t\t\t}\n\t\t\tif (retval)\n\t\t\t\treturn retval;\n\t\t}\n\t\tif (context->seen_enough)\n\t\t\tbreak;\n\t\tcursor->offset++;\n\t}\n\ttrace_xfs_attr_list_leaf_end(context);\n\treturn retval;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-241', 'CWE-19'], 'message': 'xfs: remote attribute overwrite causes transaction overrun\n\nCommit e461fcb (\"xfs: remote attribute lookups require the value\nlength\") passes the remote attribute length in the xfs_da_args\nstructure on lookup so that CRC calculations and validity checking\ncan be performed correctly by related code. This, unfortunately has\nthe side effect of changing the args->valuelen parameter in cases\nwhere it shouldn't.\n\nThat is, when we replace a remote attribute, the incoming\nreplacement stores the value and length in args->value and\nargs->valuelen, but then the lookup which finds the existing remote\nattribute overwrites args->valuelen with the length of the remote\nattribute being replaced. Hence when we go to create the new\nattribute, we create it of the size of the existing remote\nattribute, not the size it is supposed to be. When the new attribute\nis much smaller than the old attribute, this results in a\ntransaction overrun and an ASSERT() failure on a debug kernel:\n\nXFS: Assertion failed: tp->t_blk_res_used <= tp->t_blk_res, file: fs/xfs/xfs_trans.c, line: 331\n\nFix this by keeping the remote attribute value length separate to\nthe attribute value length in the xfs_da_args structure. The enables\nus to pass the length of the remote attribute to be removed without\noverwriting the new attribute's length.\n\nAlso, ensure that when we save remote block contexts for a later\nrename we zero the original state variables so that we don't confuse\nthe state of the attribute to be removes with the state of the new\nattribute that we just added. [Spotted by Brain Foster.]\n\nSigned-off-by: Dave Chinner \nReviewed-by: Brian Foster \nSigned-off-by: Dave Chinner '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadHDRImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n char\n format[MaxTextExtent],\n keyword[MaxTextExtent],\n tag[MaxTextExtent],\n value[MaxTextExtent];\n\n double\n gamma;\n\n Image\n *image;\n\n int\n c;\n\n MagickBooleanType\n status,\n value_expected;\n\n register Quantum\n *q;\n\n register ssize_t\n i,\n x;\n\n register unsigned char\n *p;\n\n ssize_t\n count,\n y;\n\n unsigned char\n *end,\n pixel[4],\n *pixels;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickSignature);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Decode image header.\n */\n image->columns=0;\n image->rows=0;\n *format='\\0';\n c=ReadBlobByte(image);\n if (c == EOF)\n {\n image=DestroyImage(image);\n return((Image *) NULL);\n }\n while (isgraph(c) && (image->columns == 0) && (image->rows == 0))\n {\n if (c == (int) '#')\n {\n char\n *comment;\n\n register char\n *p;\n\n size_t\n length;\n\n /*\n Read comment-- any text between # and end-of-line.\n */\n length=MaxTextExtent;\n comment=AcquireString((char *) NULL);\n for (p=comment; comment != (char *) NULL; p++)\n {\n c=ReadBlobByte(image);\n if ((c == EOF) || (c == (int) '\\n'))\n break;\n if ((size_t) (p-comment+1) >= length)\n {\n *p='\\0';\n length<<=1;\n comment=(char *) ResizeQuantumMemory(comment,length+\n MaxTextExtent,sizeof(*comment));\n if (comment == (char *) NULL)\n break;\n p=comment+strlen(comment);\n }\n *p=(char) c;\n }\n if (comment == (char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n *p='\\0';\n (void) SetImageProperty(image,\"comment\",comment,exception);\n comment=DestroyString(comment);\n c=ReadBlobByte(image);\n }\n else\n if (isalnum(c) == MagickFalse)\n c=ReadBlobByte(image);\n else\n {\n register char\n *p;\n\n /*\n Determine a keyword and its value.\n */\n p=keyword;\n do\n {\n if ((size_t) (p-keyword) < (MaxTextExtent-1))\n *p++=c;\n c=ReadBlobByte(image);\n } while (isalnum(c) || (c == '_'));\n *p='\\0';\n value_expected=MagickFalse;\n while ((isspace((int) ((unsigned char) c)) != 0) || (c == '='))\n {\n if (c == '=')\n value_expected=MagickTrue;\n c=ReadBlobByte(image);\n }\n if (LocaleCompare(keyword,\"Y\") == 0)\n value_expected=MagickTrue;\n if (value_expected == MagickFalse)\n continue;\n p=value;\n while ((c != '\\n') && (c != '\\0'))\n {\n if ((size_t) (p-value) < (MaxTextExtent-1))\n *p++=c;\n c=ReadBlobByte(image);\n }\n *p='\\0';\n /*\n Assign a value to the specified keyword.\n */\n switch (*keyword)\n {\n case 'F':\n case 'f':\n {\n if (LocaleCompare(keyword,\"format\") == 0)\n {\n (void) CopyMagickString(format,value,MaxTextExtent);\n break;\n }\n (void) FormatLocaleString(tag,MaxTextExtent,\"hdr:%s\",keyword);\n (void) SetImageProperty(image,tag,value,exception);\n break;\n }\n case 'G':\n case 'g':\n {\n if (LocaleCompare(keyword,\"gamma\") == 0)\n {\n image->gamma=StringToDouble(value,(char **) NULL);\n break;\n }\n (void) FormatLocaleString(tag,MaxTextExtent,\"hdr:%s\",keyword);\n (void) SetImageProperty(image,tag,value,exception);\n break;\n }\n case 'P':\n case 'p':\n {\n if (LocaleCompare(keyword,\"primaries\") == 0)\n {\n float\n chromaticity[6],\n white_point[2];\n\n (void) sscanf(value,\"%g %g %g %g %g %g %g %g\",\n &chromaticity[0],&chromaticity[1],&chromaticity[2],\n &chromaticity[3],&chromaticity[4],&chromaticity[5],\n &white_point[0],&white_point[1]);\n image->chromaticity.red_primary.x=chromaticity[0];\n image->chromaticity.red_primary.y=chromaticity[1];\n image->chromaticity.green_primary.x=chromaticity[2];\n image->chromaticity.green_primary.y=chromaticity[3];\n image->chromaticity.blue_primary.x=chromaticity[4];\n image->chromaticity.blue_primary.y=chromaticity[5];\n image->chromaticity.white_point.x=white_point[0],\n image->chromaticity.white_point.y=white_point[1];\n break;\n }\n (void) FormatLocaleString(tag,MaxTextExtent,\"hdr:%s\",keyword);\n (void) SetImageProperty(image,tag,value,exception);\n break;\n }\n case 'Y':\n case 'y':\n {\n char\n target[] = \"Y\";\n\n if (strcmp(keyword,target) == 0)\n {\n int\n height,\n width;\n\n (void) sscanf(value,\"%d +X %d\",&height,&width);\n image->columns=(size_t) width;\n image->rows=(size_t) height;\n break;\n }\n (void) FormatLocaleString(tag,MaxTextExtent,\"hdr:%s\",keyword);\n (void) SetImageProperty(image,tag,value,exception);\n break;\n }\n default:\n {\n (void) FormatLocaleString(tag,MaxTextExtent,\"hdr:%s\",keyword);\n (void) SetImageProperty(image,tag,value,exception);\n break;\n }\n }\n }\n if ((image->columns == 0) && (image->rows == 0))\n while (isspace((int) ((unsigned char) c)) != 0)\n c=ReadBlobByte(image);\n }\n if ((LocaleCompare(format,\"32-bit_rle_rgbe\") != 0) &&\n (LocaleCompare(format,\"32-bit_rle_xyze\") != 0))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if ((image->columns == 0) || (image->rows == 0))\n ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\");\n (void) SetImageColorspace(image,RGBColorspace,exception);\n if (LocaleCompare(format,\"32-bit_rle_xyze\") == 0)\n (void) SetImageColorspace(image,XYZColorspace,exception);\n image->compression=(image->columns < 8) || (image->columns > 0x7ffff) ?\n NoCompression : RLECompression;\n if (image_info->ping != MagickFalse)\n {\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n }\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n /*\n Read RGBE (red+green+blue+exponent) pixels.\n */\n pixels=(unsigned char *) AcquireQuantumMemory(image->columns,4*\n sizeof(*pixels));\n if (pixels == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n if (image->compression != RLECompression)\n {\n count=ReadBlob(image,4*image->columns*sizeof(*pixels),pixels);\n if (count != (ssize_t) (4*image->columns*sizeof(*pixels)))\n break;\n }\n else\n {\n count=ReadBlob(image,4*sizeof(*pixel),pixel);\n if (count != 4)\n break;\n if ((size_t) ((((size_t) pixel[2]) << 8) | pixel[3]) != image->columns)\n {\n (void) memcpy(pixels,pixel,4*sizeof(*pixel));\n count=ReadBlob(image,4*(image->columns-1)*sizeof(*pixels),pixels+4);\n image->compression=NoCompression;\n }\n else\n {\n p=pixels;\n for (i=0; i < 4; i++)\n {\n end=&pixels[(i+1)*image->columns];\n while (p < end)\n {\n count=ReadBlob(image,2*sizeof(*pixel),pixel);\n if (count < 1)\n break;\n if (pixel[0] > 128)\n {\n count=(ssize_t) pixel[0]-128;\n if ((count == 0) || (count > (ssize_t) (end-p)))\n break;\n while (count-- > 0)\n *p++=pixel[1];\n }\n else\n {\n count=(ssize_t) pixel[0];\n if ((count == 0) || (count > (ssize_t) (end-p)))\n break;\n *p++=pixel[1];\n if (--count > 0)\n {\n count=ReadBlob(image,(size_t) count*sizeof(*p),p);\n if (count < 1)\n break;\n p+=count;\n }\n }\n }\n }\n }\n }\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n i=0;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (image->compression == RLECompression)\n {\n pixel[0]=pixels[x];\n pixel[1]=pixels[x+image->columns];\n pixel[2]=pixels[x+2*image->columns];\n pixel[3]=pixels[x+3*image->columns];\n }\n else\n {\n pixel[0]=pixels[i++];\n pixel[1]=pixels[i++];\n pixel[2]=pixels[i++];\n pixel[3]=pixels[i++];\n }\n SetPixelRed(image,0,q);\n SetPixelGreen(image,0,q);\n SetPixelBlue(image,0,q);\n if (pixel[3] != 0)\n {\n gamma=pow(2.0,pixel[3]-(128.0+8.0));\n SetPixelRed(image,ClampToQuantum(QuantumRange*gamma*pixel[0]),q);\n SetPixelGreen(image,ClampToQuantum(QuantumRange*gamma*pixel[1]),q);\n SetPixelBlue(image,ClampToQuantum(QuantumRange*gamma*pixel[2]),q);\n }\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n if (EOFBlob(image) != MagickFalse)\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-703', 'CWE-835'], 'message': 'Fixed infinite loop and added checks for the sscanf result.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline int file_list_cpu(struct file *file)\n{\n#ifdef CONFIG_SMP\n\treturn file->f_sb_list_cpu;\n#else\n\treturn smp_processor_id();\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-17'], 'message': 'get rid of s_files and files_lock\n\nThe only thing we need it for is alt-sysrq-r (emergency remount r/o)\nand these days we can do just as well without going through the\nlist of files.\n\nSigned-off-by: Al Viro '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void file_sb_list_del(struct file *file)\n{\n\tif (!list_empty(&file->f_u.fu_list)) {\n\t\tlg_local_lock_cpu(&files_lglock, file_list_cpu(file));\n\t\tlist_del_init(&file->f_u.fu_list);\n\t\tlg_local_unlock_cpu(&files_lglock, file_list_cpu(file));\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-17'], 'message': 'get rid of s_files and files_lock\n\nThe only thing we need it for is alt-sysrq-r (emergency remount r/o)\nand these days we can do just as well without going through the\nlist of files.\n\nSigned-off-by: Al Viro '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: pipe_iov_copy_from_user(void *to, struct iovec *iov, unsigned long len,\n\t\t\tint atomic)\n{\n\tunsigned long copy;\n\n\twhile (len > 0) {\n\t\twhile (!iov->iov_len)\n\t\t\tiov++;\n\t\tcopy = min_t(unsigned long, len, iov->iov_len);\n\n\t\tif (atomic) {\n\t\t\tif (__copy_from_user_inatomic(to, iov->iov_base, copy))\n\t\t\t\treturn -EFAULT;\n\t\t} else {\n\t\t\tif (copy_from_user(to, iov->iov_base, copy))\n\t\t\t\treturn -EFAULT;\n\t\t}\n\t\tto += copy;\n\t\tlen -= copy;\n\t\tiov->iov_base += copy;\n\t\tiov->iov_len -= copy;\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-17'], 'message': 'new helper: copy_page_from_iter()\n\nparallel to copy_page_to_iter(). pipe_write() switched to it (and became\n->write_iter()).\n\nSigned-off-by: Al Viro '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline int xsave_state_booting(struct xsave_struct *fx, u64 mask)\n{\n\tu32 lmask = mask;\n\tu32 hmask = mask >> 32;\n\tint err = 0;\n\n\tWARN_ON(system_state != SYSTEM_BOOTING);\n\n\tif (boot_cpu_has(X86_FEATURE_XSAVES))\n\t\tasm volatile(\"1:\"XSAVES\"\\n\\t\"\n\t\t\t\"2:\\n\\t\"\n\t\t\t: : \"D\" (fx), \"m\" (*fx), \"a\" (lmask), \"d\" (hmask)\n\t\t\t: \"memory\");\n\telse\n\t\tasm volatile(\"1:\"XSAVE\"\\n\\t\"\n\t\t\t\"2:\\n\\t\"\n\t\t\t: : \"D\" (fx), \"m\" (*fx), \"a\" (lmask), \"d\" (hmask)\n\t\t\t: \"memory\");\n\n\tasm volatile(xstate_fault\n\t\t : \"0\" (0)\n\t\t : \"memory\");\n\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'x86/fpu/xsaves: Fix improper uses of __ex_table\n\nCommit:\n\n f31a9f7c7169 (\"x86/xsaves: Use xsaves/xrstors to save and restore xsave area\")\n\nintroduced alternative instructions for XSAVES/XRSTORS and commit:\n\n adb9d526e982 (\"x86/xsaves: Add xsaves and xrstors support for booting time\")\n\nadded support for the XSAVES/XRSTORS instructions at boot time.\n\nUnfortunately both failed to properly protect them against faulting:\n\nThe 'xstate_fault' macro will use the closest label named '1'\nbackward and that ends up in the .altinstr_replacement section\nrather than in .text. This means that the kernel will never find\nin the __ex_table the .text address where this instruction might\nfault, leading to serious problems if userspace manages to\ntrigger the fault.\n\nSigned-off-by: Quentin Casasnovas \nSigned-off-by: Jamie Iles \n[ Improved the changelog, fixed some whitespace noise. ]\nAcked-by: Borislav Petkov \nAcked-by: Linus Torvalds \nCc: \nCc: Allan Xavier \nCc: H. Peter Anvin \nCc: Thomas Gleixner \nFixes: adb9d526e982 (\"x86/xsaves: Add xsaves and xrstors support for booting time\")\nFixes: f31a9f7c7169 (\"x86/xsaves: Use xsaves/xrstors to save and restore xsave area\")\nSigned-off-by: Ingo Molnar '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static encodePtr get_array_type(xmlNodePtr node, zval *array, smart_str *type TSRMLS_DC)\n{\n\tHashTable *ht;\n\tint i, count, cur_type, prev_type, different;\n\tzval **tmp;\n\tchar *prev_stype = NULL, *cur_stype = NULL, *prev_ns = NULL, *cur_ns = NULL;\n\n\tif (!array || Z_TYPE_P(array) != IS_ARRAY) {\n\t\tsmart_str_appendl(type, \"xsd:anyType\", sizeof(\"xsd:anyType\")-1);\n\t\treturn get_conversion(XSD_ANYTYPE);\n\t}\n\n\tdifferent = FALSE;\n\tcur_type = prev_type = 0;\n\tht = HASH_OF(array);\n\tcount = zend_hash_num_elements(ht);\n\n\tzend_hash_internal_pointer_reset(ht);\n\tfor (i = 0;i < count;i++) {\n\t\tzend_hash_get_current_data(ht, (void **)&tmp);\n\n\t\tif (Z_TYPE_PP(tmp) == IS_OBJECT &&\n\t\t Z_OBJCE_PP(tmp) == soap_var_class_entry) {\n\t\t\tzval **ztype;\n\n\t\t\tif (zend_hash_find(Z_OBJPROP_PP(tmp), \"enc_type\", sizeof(\"enc_type\"), (void **)&ztype) == FAILURE) {\n\t\t\t\tsoap_error0(E_ERROR, \"Encoding: SoapVar has no 'enc_type' property\");\n\t\t\t}\n\t\t\tcur_type = Z_LVAL_PP(ztype);\n\n\t\t\tif (zend_hash_find(Z_OBJPROP_PP(tmp), \"enc_stype\", sizeof(\"enc_stype\"), (void **)&ztype) == SUCCESS) {\n\t\t\t\tcur_stype = Z_STRVAL_PP(ztype);\n\t\t\t} else {\n\t\t\t\tcur_stype = NULL;\n\t\t\t}\n\n\t\t\tif (zend_hash_find(Z_OBJPROP_PP(tmp), \"enc_ns\", sizeof(\"enc_ns\"), (void **)&ztype) == SUCCESS) {\n\t\t\t\tcur_ns = Z_STRVAL_PP(ztype);\n\t\t\t} else {\n\t\t\t\tcur_ns = NULL;\n\t\t\t}\n\n\t\t} else if (Z_TYPE_PP(tmp) == IS_ARRAY && is_map(*tmp)) {\n\t\t\tcur_type = APACHE_MAP;\n\t\t\tcur_stype = NULL;\n\t\t\tcur_ns = NULL;\n\t\t} else {\n\t\t\tcur_type = Z_TYPE_PP(tmp);\n\t\t\tcur_stype = NULL;\n\t\t\tcur_ns = NULL;\n\t\t}\n\n\t\tif (i > 0) {\n\t\t\tif ((cur_type != prev_type) ||\n\t\t\t (cur_stype != NULL && prev_stype != NULL && strcmp(cur_stype,prev_stype) != 0) ||\n\t\t\t (cur_stype == NULL && cur_stype != prev_stype) ||\n\t\t\t (cur_ns != NULL && prev_ns != NULL && strcmp(cur_ns,prev_ns) != 0) ||\n\t\t\t (cur_ns == NULL && cur_ns != prev_ns)) {\n\t\t\t\tdifferent = TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tprev_type = cur_type;\n\t\tprev_stype = cur_stype;\n\t\tprev_ns = cur_ns;\n\t\tzend_hash_move_forward(ht);\n\t}\n\n\tif (different || count == 0) {\n\t\tsmart_str_appendl(type, \"xsd:anyType\", sizeof(\"xsd:anyType\")-1);\n\t\treturn get_conversion(XSD_ANYTYPE);\n\t} else {\n\t\tencodePtr enc;\n\n\t\tif (cur_stype != NULL) {\n\t\t\tsmart_str array_type = {0};\n\n\t\t\tif (cur_ns) {\n\t\t\t\txmlNsPtr ns = encode_add_ns(node, cur_ns);\n\n\t\t\t\tsmart_str_appends(type, (char*)ns->prefix);\n\t\t\t\tsmart_str_appendc(type, ':');\n\t\t\t\tsmart_str_appends(&array_type, cur_ns);\n\t\t\t\tsmart_str_appendc(&array_type, ':');\n\t\t\t}\n\t\t\tsmart_str_appends(type, cur_stype);\n\t\t\tsmart_str_0(type);\n\t\t\tsmart_str_appends(&array_type, cur_stype);\n\t\t\tsmart_str_0(&array_type);\n\n\t\t\tenc = get_encoder_ex(SOAP_GLOBAL(sdl), array_type.c, array_type.len);\n\t\t\tsmart_str_free(&array_type);\n\t\t\treturn enc;\n\t\t} else {\n\t\t\tenc = get_conversion(cur_type);\n\t\t\tget_type_str(node, enc->details.ns, enc->details.type_str, type);\n\t\t\treturn enc;\n\t\t}\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-19'], 'message': 'Added type checks'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int handle_gid_request(enum request_types request_type, gid_t gid,\n const char *domain_name, struct berval **berval)\n{\n int ret;\n struct group grp;\n struct group *grp_result = NULL;\n char *sid_str = NULL;\n enum sss_id_type id_type;\n size_t buf_len;\n char *buf = NULL;\n struct sss_nss_kv *kv_list = NULL;\n\n ret = get_buffer(&buf_len, &buf);\n if (ret != LDAP_SUCCESS) {\n return ret;\n }\n\n if (request_type == REQ_SIMPLE) {\n ret = sss_nss_getsidbyid(gid, &sid_str, &id_type);\n if (ret != 0 || id_type != SSS_ID_TYPE_GID) {\n if (ret == ENOENT) {\n ret = LDAP_NO_SUCH_OBJECT;\n } else {\n ret = LDAP_OPERATIONS_ERROR;\n }\n goto done;\n }\n\n ret = pack_ber_sid(sid_str, berval);\n } else {\n ret = getgrgid_r(gid, &grp, buf, buf_len, &grp_result);\n if (ret != 0) {\n ret = LDAP_NO_SUCH_OBJECT;\n goto done;\n }\n if (grp_result == NULL) {\n ret = LDAP_NO_SUCH_OBJECT;\n goto done;\n }\n\n if (request_type == REQ_FULL_WITH_GROUPS) {\n ret = sss_nss_getorigbyname(grp.gr_name, &kv_list, &id_type);\n if (ret != 0 || !(id_type == SSS_ID_TYPE_GID\n || id_type == SSS_ID_TYPE_BOTH)) {\n if (ret == ENOENT) {\n ret = LDAP_NO_SUCH_OBJECT;\n } else {\n ret = LDAP_OPERATIONS_ERROR;\n }\n goto done;\n }\n }\n\n ret = pack_ber_group((request_type == REQ_FULL ? RESP_GROUP\n : RESP_GROUP_MEMBERS),\n domain_name, grp.gr_name, grp.gr_gid,\n grp.gr_mem, kv_list, berval);\n }\n\ndone:\n sss_nss_free_kv(kv_list);\n free(sid_str);\n free(buf);\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-19'], 'message': 'extdom: handle ERANGE return code for getXXYYY_r() calls\n\nThe getXXYYY_r() calls require a buffer to store the variable data of\nthe passwd and group structs. If the provided buffer is too small ERANGE\nis returned and the caller can try with a larger buffer again.\n\nCmocka/cwrap based unit-tests for get*_r_wrapper() are added.\n\nResolves https://fedorahosted.org/freeipa/ticket/4908\n\nReviewed-By: Alexander Bokovoy '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: SYSCALL_DEFINE6(recvfrom, int, fd, void __user *, ubuf, size_t, size,\n\t\tunsigned int, flags, struct sockaddr __user *, addr,\n\t\tint __user *, addr_len)\n{\n\tstruct socket *sock;\n\tstruct iovec iov;\n\tstruct msghdr msg;\n\tstruct sockaddr_storage address;\n\tint err, err2;\n\tint fput_needed;\n\n\tif (size > INT_MAX)\n\t\tsize = INT_MAX;\n\tsock = sockfd_lookup_light(fd, &err, &fput_needed);\n\tif (!sock)\n\t\tgoto out;\n\n\tmsg.msg_control = NULL;\n\tmsg.msg_controllen = 0;\n\tiov.iov_len = size;\n\tiov.iov_base = ubuf;\n\tiov_iter_init(&msg.msg_iter, READ, &iov, 1, size);\n\t/* Save some cycles and don't copy the address if not needed */\n\tmsg.msg_name = addr ? (struct sockaddr *)&address : NULL;\n\t/* We assume all kernel code knows the size of sockaddr_storage */\n\tmsg.msg_namelen = 0;\n\tif (sock->file->f_flags & O_NONBLOCK)\n\t\tflags |= MSG_DONTWAIT;\n\terr = sock_recvmsg(sock, &msg, size, flags);\n\n\tif (err >= 0 && addr != NULL) {\n\t\terr2 = move_addr_to_user(&address,\n\t\t\t\t\t msg.msg_namelen, addr, addr_len);\n\t\tif (err2 < 0)\n\t\t\terr = err2;\n\t}\n\n\tfput_light(sock->file, fput_needed);\nout:\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'net: validate the range we feed to iov_iter_init() in sys_sendto/sys_recvfrom\n\nCc: stable@vger.kernel.org # v3.19\nSigned-off-by: Al Viro \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: xmlNewTextReader(xmlParserInputBufferPtr input, const char *URI) {\n xmlTextReaderPtr ret;\n\n if (input == NULL)\n\treturn(NULL);\n ret = xmlMalloc(sizeof(xmlTextReader));\n if (ret == NULL) {\n xmlGenericError(xmlGenericErrorContext,\n\t\t\"xmlNewTextReader : malloc failed\\n\");\n\treturn(NULL);\n }\n memset(ret, 0, sizeof(xmlTextReader));\n ret->doc = NULL;\n ret->entTab = NULL;\n ret->entMax = 0;\n ret->entNr = 0;\n ret->input = input;\n ret->buffer = xmlBufCreateSize(100);\n if (ret->buffer == NULL) {\n xmlFree(ret);\n xmlGenericError(xmlGenericErrorContext,\n\t\t\"xmlNewTextReader : malloc failed\\n\");\n\treturn(NULL);\n }\n ret->sax = (xmlSAXHandler *) xmlMalloc(sizeof(xmlSAXHandler));\n if (ret->sax == NULL) {\n\txmlBufFree(ret->buffer);\n\txmlFree(ret);\n xmlGenericError(xmlGenericErrorContext,\n\t\t\"xmlNewTextReader : malloc failed\\n\");\n\treturn(NULL);\n }\n xmlSAXVersion(ret->sax, 2);\n ret->startElement = ret->sax->startElement;\n ret->sax->startElement = xmlTextReaderStartElement;\n ret->endElement = ret->sax->endElement;\n ret->sax->endElement = xmlTextReaderEndElement;\n#ifdef LIBXML_SAX1_ENABLED\n if (ret->sax->initialized == XML_SAX2_MAGIC) {\n#endif /* LIBXML_SAX1_ENABLED */\n\tret->startElementNs = ret->sax->startElementNs;\n\tret->sax->startElementNs = xmlTextReaderStartElementNs;\n\tret->endElementNs = ret->sax->endElementNs;\n\tret->sax->endElementNs = xmlTextReaderEndElementNs;\n#ifdef LIBXML_SAX1_ENABLED\n } else {\n\tret->startElementNs = NULL;\n\tret->endElementNs = NULL;\n }\n#endif /* LIBXML_SAX1_ENABLED */\n ret->characters = ret->sax->characters;\n ret->sax->characters = xmlTextReaderCharacters;\n ret->sax->ignorableWhitespace = xmlTextReaderCharacters;\n ret->cdataBlock = ret->sax->cdataBlock;\n ret->sax->cdataBlock = xmlTextReaderCDataBlock;\n\n ret->mode = XML_TEXTREADER_MODE_INITIAL;\n ret->node = NULL;\n ret->curnode = NULL;\n if (xmlBufUse(ret->input->buffer) < 4) {\n\txmlParserInputBufferRead(input, 4);\n }\n if (xmlBufUse(ret->input->buffer) >= 4) {\n\tret->ctxt = xmlCreatePushParserCtxt(ret->sax, NULL,\n\t\t\t (const char *) xmlBufContent(ret->input->buffer),\n 4, URI);\n\tret->base = 0;\n\tret->cur = 4;\n } else {\n\tret->ctxt = xmlCreatePushParserCtxt(ret->sax, NULL, NULL, 0, URI);\n\tret->base = 0;\n\tret->cur = 0;\n }\n\n if (ret->ctxt == NULL) {\n xmlGenericError(xmlGenericErrorContext,\n\t\t\"xmlNewTextReader : malloc failed\\n\");\n\txmlBufFree(ret->buffer);\n\txmlFree(ret->sax);\n\txmlFree(ret);\n\treturn(NULL);\n }\n ret->ctxt->parseMode = XML_PARSE_READER;\n ret->ctxt->_private = ret;\n ret->ctxt->linenumbers = 1;\n ret->ctxt->dictNames = 1;\n ret->allocs = XML_TEXTREADER_CTXT;\n /*\n * use the parser dictionnary to allocate all elements and attributes names\n */\n ret->ctxt->docdict = 1;\n ret->dict = ret->ctxt->dict;\n#ifdef LIBXML_XINCLUDE_ENABLED\n ret->xinclude = 0;\n#endif\n#ifdef LIBXML_PATTERN_ENABLED\n ret->patternMax = 0;\n ret->patternTab = NULL;\n#endif\n return(ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-1819 Enforce the reader to run in constant memory\n\nOne of the operation on the reader could resolve entities\nleading to the classic expansion issue. Make sure the\nbuffer used for xmlreader operation is bounded.\nIntroduce a new allocation type for the buffers for this effect.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int SavePackageDescriptionToDebugDump(const char *dump_dir_name)\n{\n struct dump_dir *dd = dd_opendir(dump_dir_name, /*flags:*/ 0);\n if (!dd)\n return 1;\n\n char *analyzer = dd_load_text(dd, FILENAME_ANALYZER);\n if (!strcmp(analyzer, \"Kerneloops\"))\n {\n dd_save_text(dd, FILENAME_PACKAGE, \"kernel\");\n dd_save_text(dd, FILENAME_COMPONENT, \"kernel\");\n dd_close(dd);\n free(analyzer);\n return 0;\n }\n free(analyzer);\n\n char *cmdline = NULL;\n char *executable = NULL;\n char *rootdir = NULL;\n char *package_short_name = NULL;\n struct pkg_envra *pkg_name = NULL;\n char *component = NULL;\n int error = 1;\n /* note: \"goto ret\" statements below free all the above variables,\n * but they don't dd_close(dd) */\n\n cmdline = dd_load_text_ext(dd, FILENAME_CMDLINE, DD_FAIL_QUIETLY_ENOENT);\n executable = dd_load_text(dd, FILENAME_EXECUTABLE);\n rootdir = dd_load_text_ext(dd, FILENAME_ROOTDIR,\n DD_FAIL_QUIETLY_ENOENT | DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE);\n\n /* Close dd while we query package database. It can take some time,\n * don't want to keep dd locked longer than necessary */\n dd_close(dd);\n\n if (is_path_blacklisted(executable))\n {\n log(\"Blacklisted executable '%s'\", executable);\n goto ret; /* return 1 (failure) */\n }\n\n pkg_name = rpm_get_package_nvr(executable, rootdir);\n if (!pkg_name)\n {\n if (settings_bProcessUnpackaged)\n {\n log_info(\"Crash in unpackaged executable '%s', \"\n \"proceeding without packaging information\", executable);\n goto ret0; /* no error */\n }\n log(\"Executable '%s' doesn't belong to any package\"\n\t\t\" and ProcessUnpackaged is set to 'no'\",\n\t\texecutable\n );\n goto ret; /* return 1 (failure) */\n }\n\n /* Check well-known interpreter names */\n const char *basename = strrchr(executable, '/');\n if (basename)\n basename++;\n else\n basename = executable;\n\n /* if basename is known interpreter, we want to blame the running script\n * not the interpreter\n */\n if (g_list_find_custom(settings_Interpreters, basename, (GCompareFunc)g_strcmp0))\n {\n struct pkg_envra *script_pkg = get_script_name(cmdline, &executable);\n /* executable may have changed, check it again */\n if (is_path_blacklisted(executable))\n {\n log(\"Blacklisted executable '%s'\", executable);\n goto ret; /* return 1 (failure) */\n }\n if (!script_pkg)\n {\n /* Script name is not absolute, or it doesn't\n * belong to any installed package.\n */\n if (!settings_bProcessUnpackaged)\n {\n log(\"Interpreter crashed, but no packaged script detected: '%s'\", cmdline);\n goto ret; /* return 1 (failure) */\n }\n\n /* Unpackaged script, but the settings says we want to keep it.\n * BZ plugin wont allow to report this anyway, because component\n * is missing, so there is no reason to mark it as not_reportable.\n * Someone might want to use abrt to report it using ftp.\n */\n goto ret0;\n }\n\n free_pkg_envra(pkg_name);\n pkg_name = script_pkg;\n }\n\n package_short_name = xasprintf(\"%s\", pkg_name->p_name);\n log_info(\"Package:'%s' short:'%s'\", pkg_name->p_nvr, package_short_name);\n\n\n if (g_list_find_custom(settings_setBlackListedPkgs, package_short_name, (GCompareFunc)g_strcmp0))\n {\n log(\"Blacklisted package '%s'\", package_short_name);\n goto ret; /* return 1 (failure) */\n }\n\n if (settings_bOpenGPGCheck)\n {\n if (!rpm_chk_fingerprint(package_short_name))\n {\n log(\"Package '%s' isn't signed with proper key\", package_short_name);\n goto ret; /* return 1 (failure) */\n }\n /* We used to also check the integrity of the executable here:\n * if (!CheckHash(package_short_name.c_str(), executable)) BOOM();\n * Checking the MD5 sum requires to run prelink to \"un-prelink\" the\n * binaries - this is considered potential security risk so we don't\n * do it now, until we find some non-intrusive way.\n */\n }\n\n component = rpm_get_component(executable, rootdir);\n\n dd = dd_opendir(dump_dir_name, /*flags:*/ 0);\n if (!dd)\n goto ret; /* return 1 (failure) */\n\n if (pkg_name)\n {\n dd_save_text(dd, FILENAME_PACKAGE, pkg_name->p_nvr);\n dd_save_text(dd, FILENAME_PKG_EPOCH, pkg_name->p_epoch);\n dd_save_text(dd, FILENAME_PKG_NAME, pkg_name->p_name);\n dd_save_text(dd, FILENAME_PKG_VERSION, pkg_name->p_version);\n dd_save_text(dd, FILENAME_PKG_RELEASE, pkg_name->p_release);\n dd_save_text(dd, FILENAME_PKG_ARCH, pkg_name->p_arch);\n }\n\n if (component)\n dd_save_text(dd, FILENAME_COMPONENT, component);\n\n dd_close(dd);\n\n ret0:\n error = 0;\n ret:\n free(cmdline);\n free(executable);\n free(rootdir);\n free(package_short_name);\n free_pkg_envra(pkg_name);\n free(component);\n\n return error;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59'], 'message': 'a-a-save-package-data: turn off reading data from root directories\n\nMaking copies of files from arbitrary root directories is not secure.\n\nRelated: #1211835\n\nSigned-off-by: Jakub Filak '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int open_user_core(uid_t uid, uid_t fsuid, pid_t pid, char **percent_values)\n{\n errno = 0;\n if (user_pwd == NULL\n || chdir(user_pwd) != 0\n ) {\n perror_msg(\"Can't cd to '%s'\", user_pwd);\n return -1;\n }\n\n struct passwd* pw = getpwuid(uid);\n gid_t gid = pw ? pw->pw_gid : uid;\n //log(\"setting uid: %i gid: %i\", uid, gid);\n xsetegid(gid);\n xseteuid(fsuid);\n\n if (strcmp(core_basename, \"core\") == 0)\n {\n /* Mimic \"core.PID\" if requested */\n char buf[] = \"0\\n\";\n int fd = open(\"/proc/sys/kernel/core_uses_pid\", O_RDONLY);\n if (fd >= 0)\n {\n IGNORE_RESULT(read(fd, buf, sizeof(buf)));\n close(fd);\n }\n if (strcmp(buf, \"1\\n\") == 0)\n {\n core_basename = xasprintf(\"%s.%lu\", core_basename, (long)pid);\n }\n }\n else\n {\n /* Expand old core pattern, put expanded name in core_basename */\n core_basename = xstrdup(core_basename);\n unsigned idx = 0;\n while (1)\n {\n char c = core_basename[idx];\n if (!c)\n break;\n idx++;\n if (c != '%')\n continue;\n\n /* We just copied %, look at following char and expand %c */\n c = core_basename[idx];\n unsigned specifier_num = strchrnul(percent_specifiers, c) - percent_specifiers;\n if (percent_specifiers[specifier_num] != '\\0') /* valid %c (might be %% too) */\n {\n const char *val = \"%\";\n if (specifier_num > 0) /* not %% */\n val = percent_values[specifier_num - 1];\n //log(\"c:'%c'\", c);\n //log(\"val:'%s'\", val);\n\n /* Replace %c at core_basename[idx] by its value */\n idx--;\n char *old = core_basename;\n core_basename = xasprintf(\"%.*s%s%s\", idx, core_basename, val, core_basename + idx + 2);\n //log(\"pos:'%*s|'\", idx, \"\");\n //log(\"new:'%s'\", core_basename);\n //log(\"old:'%s'\", old);\n free(old);\n idx += strlen(val);\n }\n /* else: invalid %c, % is already copied verbatim,\n * next loop iteration will copy c */\n }\n }\n\n full_core_basename = core_basename;\n if (core_basename[0] != '/')\n {\n if (g_need_nonrelative)\n {\n error_msg(\"Current suid_dumpable policy prevents from saving core dumps according to relative core_pattern\");\n return -1;\n }\n core_basename = concat_path_file(user_pwd, core_basename);\n }\n\n /* Open (create) compat core file.\n * man core:\n * There are various circumstances in which a core dump file\n * is not produced:\n *\n * [skipped obvious ones]\n * The process does not have permission to write the core file.\n * ...if a file with the same name exists and is not writable\n * or is not a regular file (e.g., it is a directory or a symbolic link).\n *\n * A file with the same name already exists, but there is more\n * than one hard link to that file.\n *\n * The file system where the core dump file would be created is full;\n * or has run out of inodes; or is mounted read-only;\n * or the user has reached their quota for the file system.\n *\n * The RLIMIT_CORE or RLIMIT_FSIZE resource limits for the process\n * are set to zero.\n * [we check RLIMIT_CORE, but how can we check RLIMIT_FSIZE?]\n *\n * The binary being executed by the process does not have\n * read permission enabled. [how we can check it here?]\n *\n * The process is executing a set-user-ID (set-group-ID) program\n * that is owned by a user (group) other than the real\n * user (group) ID of the process. [TODO?]\n * (However, see the description of the prctl(2) PR_SET_DUMPABLE operation,\n * and the description of the /proc/sys/fs/suid_dumpable file in proc(5).)\n */\n struct stat sb;\n errno = 0;\n /* Do not O_TRUNC: if later checks fail, we do not want to have file already modified here */\n int user_core_fd = open(core_basename, O_WRONLY | O_CREAT | O_NOFOLLOW | g_user_core_flags, 0600); /* kernel makes 0600 too */\n xsetegid(0);\n xseteuid(0);\n if (user_core_fd < 0\n || fstat(user_core_fd, &sb) != 0\n || !S_ISREG(sb.st_mode)\n || sb.st_nlink != 1\n || sb.st_uid != fsuid\n ) {\n if (user_core_fd < 0)\n perror_msg(\"Can't open '%s'\", full_core_basename);\n else\n perror_msg(\"'%s' is not a regular file with link count 1 owned by UID(%d)\", full_core_basename, fsuid);\n return -1;\n }\n if (ftruncate(user_core_fd, 0) != 0) {\n /* perror first, otherwise unlink may trash errno */\n perror_msg(\"Can't truncate '%s' to size 0\", full_core_basename);\n unlink(core_basename);\n return -1;\n }\n\n return user_core_fd;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'ccpp: do not use value of /proc/PID/cwd for chdir\n\nAvoid symlink resolutions.\n\nThis issue was discovered by Florian Weimer of Red Hat Product Security.\n\nSigned-off-by: Jakub Filak '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static unsigned create_oops_dump_dirs(GList *oops_list, unsigned oops_cnt)\n{\n unsigned countdown = MAX_DUMPED_DD_COUNT; /* do not report hundreds of oopses */\n\n log_notice(\"Saving %u oopses as problem dirs\", oops_cnt >= countdown ? countdown : oops_cnt);\n\n char *cmdline_str = xmalloc_fopen_fgetline_fclose(\"/proc/cmdline\");\n char *fips_enabled = xmalloc_fopen_fgetline_fclose(\"/proc/sys/crypto/fips_enabled\");\n char *proc_modules = xmalloc_open_read_close(\"/proc/modules\", /*maxsize:*/ NULL);\n char *suspend_stats = xmalloc_open_read_close(\"/sys/kernel/debug/suspend_stats\", /*maxsize:*/ NULL);\n\n time_t t = time(NULL);\n const char *iso_date = iso_date_string(&t);\n /* dump should be readable by all if we're run with -x */\n uid_t my_euid = (uid_t)-1L;\n mode_t mode = DEFAULT_DUMP_DIR_MODE | S_IROTH;\n /* and readable only for the owner otherwise */\n if (!world_readable_dump)\n {\n mode = DEFAULT_DUMP_DIR_MODE;\n my_euid = geteuid();\n }\n\n pid_t my_pid = getpid();\n unsigned idx = 0;\n unsigned errors = 0;\n while (idx < oops_cnt)\n {\n char base[sizeof(\"oops-YYYY-MM-DD-hh:mm:ss-%lu-%lu\") + 2 * sizeof(long)*3];\n sprintf(base, \"oops-%s-%lu-%lu\", iso_date, (long)my_pid, (long)idx);\n char *path = concat_path_file(debug_dumps_dir, base);\n\n struct dump_dir *dd = dd_create(path, /*uid:*/ my_euid, mode);\n if (dd)\n {\n dd_create_basic_files(dd, /*uid:*/ my_euid, NULL);\n save_oops_data_in_dump_dir(dd, (char*)g_list_nth_data(oops_list, idx++), proc_modules);\n dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION);\n dd_save_text(dd, FILENAME_ANALYZER, \"Kerneloops\");\n dd_save_text(dd, FILENAME_TYPE, \"Kerneloops\");\n if (cmdline_str)\n dd_save_text(dd, FILENAME_CMDLINE, cmdline_str);\n if (proc_modules)\n dd_save_text(dd, \"proc_modules\", proc_modules);\n if (fips_enabled && strcmp(fips_enabled, \"0\") != 0)\n dd_save_text(dd, \"fips_enabled\", fips_enabled);\n if (suspend_stats)\n dd_save_text(dd, \"suspend_stats\", suspend_stats);\n dd_close(dd);\n notify_new_path(path);\n }\n else\n errors++;\n\n free(path);\n\n if (--countdown == 0)\n break;\n\n if (dd && throttle_dd_creation)\n sleep(1);\n }\n\n free(cmdline_str);\n free(proc_modules);\n free(fips_enabled);\n free(suspend_stats);\n\n return errors;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'make the dump directories owned by root by default\n\nIt was discovered that the abrt event scripts create a user-readable\ncopy of a sosreport file in abrt problem directories, and include\nexcerpts of /var/log/messages selected by the user-controlled process\nname, leading to an information disclosure.\n\nThis issue was discovered by Florian Weimer of Red Hat Product Security.\n\nRelated: #1212868\n\nSigned-off-by: Jakub Filak '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: CURLcode Curl_http_done(struct connectdata *conn,\n CURLcode status, bool premature)\n{\n struct SessionHandle *data = conn->data;\n struct HTTP *http =data->req.protop;\n\n Curl_unencode_cleanup(conn);\n\n#ifdef USE_SPNEGO\n if(data->state.proxyneg.state == GSS_AUTHSENT ||\n data->state.negotiate.state == GSS_AUTHSENT)\n Curl_cleanup_negotiate(data);\n#endif\n\n /* set the proper values (possibly modified on POST) */\n conn->fread_func = data->set.fread_func; /* restore */\n conn->fread_in = data->set.in; /* restore */\n conn->seek_func = data->set.seek_func; /* restore */\n conn->seek_client = data->set.seek_client; /* restore */\n\n if(http == NULL)\n return CURLE_OK;\n\n if(http->send_buffer) {\n Curl_send_buffer *buff = http->send_buffer;\n\n free(buff->buffer);\n free(buff);\n http->send_buffer = NULL; /* clear the pointer */\n }\n\n if(HTTPREQ_POST_FORM == data->set.httpreq) {\n data->req.bytecount = http->readbytecount + http->writebytecount;\n\n Curl_formclean(&http->sendit); /* Now free that whole lot */\n if(http->form.fp) {\n /* a file being uploaded was left opened, close it! */\n fclose(http->form.fp);\n http->form.fp = NULL;\n }\n }\n else if(HTTPREQ_PUT == data->set.httpreq)\n data->req.bytecount = http->readbytecount + http->writebytecount;\n\n if(status)\n return status;\n\n if(!premature && /* this check is pointless when DONE is called before the\n entire operation is complete */\n !conn->bits.retry &&\n !data->set.connect_only &&\n ((http->readbytecount +\n data->req.headerbytecount -\n data->req.deductheadercount)) <= 0) {\n /* If this connection isn't simply closed to be retried, AND nothing was\n read from the HTTP server (that counts), this can't be right so we\n return an error here */\n failf(data, \"Empty reply from server\");\n return CURLE_GOT_NOTHING;\n }\n\n return CURLE_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284'], 'message': 'http_done: close Negotiate connections when done\n\nWhen doing HTTP requests Negotiate authenticated, the entire connnection\nmay become authenticated and not just the specific HTTP request which is\notherwise how HTTP works, as Negotiate can basically use NTLM under the\nhood. curl was not adhering to this fact but would assume that such\nrequests would also be authenticated per request.\n\nCVE-2015-3148\n\nBug: http://curl.haxx.se/docs/adv_20150422B.html\nReported-by: Isaac Boukris'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: PHP_FUNCTION(imageloadfont)\n{\n\tchar *file;\n\tint file_name, hdr_size = sizeof(gdFont) - sizeof(char *);\n\tint ind, body_size, n = 0, b, i, body_size_check;\n\tgdFontPtr font;\n\tphp_stream *stream;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s\", &file, &file_name) == FAILURE) {\n\t\treturn;\n\t}\n\n\tstream = php_stream_open_wrapper(file, \"rb\", IGNORE_PATH | IGNORE_URL_WIN | REPORT_ERRORS, NULL);\n\tif (stream == NULL) {\n\t\tRETURN_FALSE;\n\t}\n\n\t/* Only supports a architecture-dependent binary dump format\n\t * at the moment.\n\t * The file format is like this on machines with 32-byte integers:\n\t *\n\t * byte 0-3: (int) number of characters in the font\n\t * byte 4-7: (int) value of first character in the font (often 32, space)\n\t * byte 8-11: (int) pixel width of each character\n\t * byte 12-15: (int) pixel height of each character\n\t * bytes 16-: (char) array with character data, one byte per pixel\n\t * in each character, for a total of\n\t * (nchars*width*height) bytes.\n\t */\n\tfont = (gdFontPtr) emalloc(sizeof(gdFont));\n\tb = 0;\n\twhile (b < hdr_size && (n = php_stream_read(stream, (char*)&font[b], hdr_size - b))) {\n\t\tb += n;\n\t}\n\n\tif (!n) {\n\t\tefree(font);\n\t\tif (php_stream_eof(stream)) {\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"End of file while reading header\");\n\t\t} else {\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Error while reading header\");\n\t\t}\n\t\tphp_stream_close(stream);\n\t\tRETURN_FALSE;\n\t}\n\ti = php_stream_tell(stream);\n\tphp_stream_seek(stream, 0, SEEK_END);\n\tbody_size_check = php_stream_tell(stream) - hdr_size;\n\tphp_stream_seek(stream, i, SEEK_SET);\n\n\tbody_size = font->w * font->h * font->nchars;\n\tif (body_size != body_size_check) {\n\t\tfont->w = FLIPWORD(font->w);\n\t\tfont->h = FLIPWORD(font->h);\n\t\tfont->nchars = FLIPWORD(font->nchars);\n\t\tbody_size = font->w * font->h * font->nchars;\n\t}\n\n\tif (overflow2(font->nchars, font->h) || overflow2(font->nchars * font->h, font->w )) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Error reading font, invalid font header\");\n\t\tefree(font);\n\t\tphp_stream_close(stream);\n\t\tRETURN_FALSE;\n\t}\n\n\tif (body_size != body_size_check) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Error reading font\");\n\t\tefree(font);\n\t\tphp_stream_close(stream);\n\t\tRETURN_FALSE;\n\t}\n\n\tfont->data = emalloc(body_size);\n\tb = 0;\n\twhile (b < body_size && (n = php_stream_read(stream, &font->data[b], body_size - b))) {\n\t\tb += n;\n\t}\n\n\tif (!n) {\n\t\tefree(font->data);\n\t\tefree(font);\n\t\tif (php_stream_eof(stream)) {\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"End of file while reading body\");\n\t\t} else {\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Error while reading body\");\n\t\t}\n\t\tphp_stream_close(stream);\n\t\tRETURN_FALSE;\n\t}\n\tphp_stream_close(stream);\n\n\t/* Adding 5 to the font index so we will never have font indices\n\t * that overlap with the old fonts (with indices 1-5). The first\n\t * list index given out is always 1.\n\t */\n\tind = 5 + zend_list_insert(font, le_gd_font TSRMLS_CC);\n\n\tRETURN_LONG(ind);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fixed bug #69353 (Missing null byte checks for paths in various PHP extensions)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int dd_delete_item(struct dump_dir *dd, const char *name)\n{\n if (!dd->locked)\n error_msg_and_die(\"dump_dir is not opened\"); /* bug */\n\n char *path = concat_path_file(dd->dd_dirname, name);\n int res = unlink(path);\n\n if (res < 0)\n {\n if (errno == ENOENT)\n errno = res = 0;\n else\n perror_msg(\"Can't delete file '%s'\", path);\n }\n\n free(path);\n return res;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-22'], 'message': 'dd: harden functions against directory traversal issues\n\nTest correctness of all accessed dump dir files in all dd* functions.\nBefore this commit, the callers were allowed to pass strings like\n\"../../etc/shadow\" in the filename argument of all dd* functions.\n\nRelated: #1214457\n\nSigned-off-by: Jakub Filak '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static bool allowed_problem_dir(const char *dir_name)\n{\n//HACK HACK HACK! Disabled for now until we fix clients (abrt-gui) to not pass /home/user/.cache/abrt/spool\n#if 0\n unsigned len = strlen(g_settings_dump_location);\n\n /* If doesn't start with \"g_settings_dump_location[/]\"... */\n if (strncmp(dir_name, g_settings_dump_location, len) != 0\n || (dir_name[len] != '/' && dir_name[len] != '\\0')\n /* or contains \"/.\" anywhere (-> might contain \"..\" component) */\n || strstr(dir_name + len, \"/.\")\n ) {\n return false;\n }\n#endif\n return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'dbus: process only valid sub-directories of the dump location\n\nMust have correct rights and must be a direct sub-directory of the dump\nlocation.\n\nThis issue was discovered by Florian Weimer of Red Hat Product Security.\n\nRelated: #1214451\n\nSigned-off-by: Jakub Filak '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void problem_data_load_from_dump_dir(problem_data_t *problem_data, struct dump_dir *dd, char **excluding)\n{\n char *short_name;\n char *full_name;\n\n dd_init_next_file(dd);\n while (dd_get_next_file(dd, &short_name, &full_name))\n {\n if (excluding && is_in_string_list(short_name, excluding))\n {\n //log(\"Excluded:'%s'\", short_name);\n goto next;\n }\n\n if (short_name[0] == '#'\n || (short_name[0] && short_name[strlen(short_name) - 1] == '~')\n ) {\n //log(\"Excluded (editor backup file):'%s'\", short_name);\n goto next;\n }\n\n ssize_t sz = 4*1024;\n char *text = is_text_file(full_name, &sz);\n if (!text || text == HUGE_TEXT)\n {\n int flag = !text ? CD_FLAG_BIN : (CD_FLAG_BIN+CD_FLAG_BIGTXT);\n problem_data_add(problem_data,\n short_name,\n full_name,\n flag + CD_FLAG_ISNOTEDITABLE\n );\n goto next;\n }\n\n char *content;\n if (sz < 4*1024) /* did is_text_file read entire file? */\n {\n /* yes */\n content = text;\n }\n else\n {\n /* no, need to read it all */\n free(text);\n content = dd_load_text(dd, short_name);\n }\n /* Strip '\\n' from one-line elements: */\n char *nl = strchr(content, '\\n');\n if (nl && nl[1] == '\\0')\n *nl = '\\0';\n\n /* Sanitize possibly corrupted utf8.\n * Of control chars, allow only tab and newline.\n */\n char *sanitized = sanitize_utf8(content,\n (SANITIZE_ALL & ~SANITIZE_LF & ~SANITIZE_TAB)\n );\n if (sanitized)\n {\n free(content);\n content = sanitized;\n }\n\n bool editable = is_editable_file(short_name);\n int flags = 0;\n if (editable)\n flags |= CD_FLAG_TXT | CD_FLAG_ISEDITABLE;\n else\n flags |= CD_FLAG_TXT | CD_FLAG_ISNOTEDITABLE;\n\n static const char *const list_files[] = {\n FILENAME_UID ,\n FILENAME_PACKAGE ,\n FILENAME_CMDLINE ,\n FILENAME_TIME ,\n FILENAME_COUNT ,\n FILENAME_REASON ,\n NULL\n };\n if (is_in_string_list(short_name, (char**)list_files))\n flags |= CD_FLAG_LIST;\n\n if (strcmp(short_name, FILENAME_TIME) == 0)\n flags |= CD_FLAG_UNIXTIME;\n\n problem_data_add(problem_data,\n short_name,\n content,\n flags\n );\n free(content);\n next:\n free(short_name);\n free(full_name);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'lib: fix races in dump directory handling code\n\nFlorian Weimer :\n\n dd_opendir() should keep a file handle (opened with O_DIRECTORY) and\n use openat() and similar functions to access files in it.\n\n ...\n\n The file system manipulation functions should guard against hard\n links (check that link count is <= 1, just as in the user coredump\n code in abrt-hook-ccpp), possibly after opening the file\n with O_PATH first to avoid side effects on open/close.\n\nRelated: #1214745\n\nSigned-off-by: Jakub Filak '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: struct dump_dir *dd_opendir(const char *dir, int flags)\n{\n struct dump_dir *dd = dd_init();\n\n dir = dd->dd_dirname = rm_trailing_slashes(dir);\n\n struct stat stat_buf;\n if (stat(dir, &stat_buf) != 0)\n goto cant_access;\n /* & 0666 should remove the executable bit */\n dd->mode = (stat_buf.st_mode & 0666);\n\n errno = 0;\n if (dd_lock(dd, WAIT_FOR_OTHER_PROCESS_USLEEP, flags) < 0)\n {\n if ((flags & DD_OPEN_READONLY) && errno == EACCES)\n {\n /* Directory is not writable. If it seems to be readable,\n * return \"read only\" dd, not NULL */\n if (stat(dir, &stat_buf) == 0\n && S_ISDIR(stat_buf.st_mode)\n && access(dir, R_OK) == 0\n ) {\n if(dd_check(dd) != NULL)\n {\n dd_close(dd);\n dd = NULL;\n }\n return dd;\n }\n }\n if (errno == EISDIR)\n {\n /* EISDIR: dd_lock can lock the dir, but it sees no time file there,\n * even after it retried many times. It must be an ordinary directory!\n *\n * Without this check, e.g. abrt-action-print happily prints any current\n * directory when run without arguments, because its option -d DIR\n * defaults to \".\"!\n */\n error_msg(\"'%s' is not a problem directory\", dir);\n }\n else\n {\n cant_access:\n if (errno == ENOENT || errno == ENOTDIR)\n {\n if (!(flags & DD_FAIL_QUIETLY_ENOENT))\n error_msg(\"'%s' does not exist\", dir);\n }\n else\n {\n if (!(flags & DD_FAIL_QUIETLY_EACCES))\n perror_msg(\"Can't access '%s'\", dir);\n }\n }\n dd_close(dd);\n return NULL;\n }\n\n dd->dd_uid = (uid_t)-1L;\n dd->dd_gid = (gid_t)-1L;\n if (geteuid() == 0)\n {\n /* In case caller would want to create more files, he'll need uid:gid */\n struct stat stat_buf;\n if (stat(dir, &stat_buf) != 0 || !S_ISDIR(stat_buf.st_mode))\n {\n error_msg(\"Can't stat '%s', or it is not a directory\", dir);\n dd_close(dd);\n return NULL;\n }\n dd->dd_uid = stat_buf.st_uid;\n dd->dd_gid = stat_buf.st_gid;\n }\n\n return dd;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'lib: fix races in dump directory handling code\n\nFlorian Weimer :\n\n dd_opendir() should keep a file handle (opened with O_DIRECTORY) and\n use openat() and similar functions to access files in it.\n\n ...\n\n The file system manipulation functions should guard against hard\n links (check that link count is <= 1, just as in the user coredump\n code in abrt-hook-ccpp), possibly after opening the file\n with O_PATH first to avoid side effects on open/close.\n\nRelated: #1214745\n\nSigned-off-by: Jakub Filak '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void dd_sanitize_mode_and_owner(struct dump_dir *dd)\n{\n /* Don't sanitize if we aren't run under root:\n * we assume that during file creation (by whatever means,\n * even by \"hostname >file\" in abrt_event.conf)\n * normal umask-based mode setting takes care of correct mode,\n * and uid:gid is, of course, set to user's uid and gid.\n *\n * For root operating on /var/spool/abrt/USERS_PROBLEM, this isn't true:\n * \"hostname >file\", for example, would create file OWNED BY ROOT!\n * This routine resets mode and uid:gid for all such files.\n */\n if (dd->dd_uid == (uid_t)-1)\n return;\n\n if (!dd->locked)\n error_msg_and_die(\"dump_dir is not opened\"); /* bug */\n\n DIR *d = opendir(dd->dd_dirname);\n if (!d)\n return;\n\n struct dirent *dent;\n while ((dent = readdir(d)) != NULL)\n {\n if (dent->d_name[0] == '.') /* \".lock\", \".\", \"..\"? skip */\n continue;\n char *full_path = concat_path_file(dd->dd_dirname, dent->d_name);\n struct stat statbuf;\n if (lstat(full_path, &statbuf) == 0 && S_ISREG(statbuf.st_mode))\n {\n if ((statbuf.st_mode & 0777) != dd->mode)\n {\n /* We open the file only for fchmod()\n *\n * We use fchmod() because chmod() changes the permissions of\n * the file specified whose pathname is given in path, which\n * is dereferenced if it is a symbolic link.\n */\n int fd = open(full_path, O_RDONLY | O_NOFOLLOW, dd->mode);\n if (fd >= 0)\n {\n if (fchmod(fd, dd->mode) != 0)\n {\n perror_msg(\"Can't change '%s' mode to 0%o\", full_path,\n (unsigned)dd->mode);\n }\n close(fd);\n }\n else\n {\n perror_msg(\"Can't open regular file '%s'\", full_path);\n }\n }\n if (statbuf.st_uid != dd->dd_uid || statbuf.st_gid != dd->dd_gid)\n {\n if (lchown(full_path, dd->dd_uid, dd->dd_gid) != 0)\n {\n perror_msg(\"Can't change '%s' ownership to %lu:%lu\", full_path,\n (long)dd->dd_uid, (long)dd->dd_gid);\n }\n }\n }\n free(full_path);\n }\n closedir(d);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'lib: fix races in dump directory handling code\n\nFlorian Weimer :\n\n dd_opendir() should keep a file handle (opened with O_DIRECTORY) and\n use openat() and similar functions to access files in it.\n\n ...\n\n The file system manipulation functions should guard against hard\n links (check that link count is <= 1, just as in the user coredump\n code in abrt-hook-ccpp), possibly after opening the file\n with O_PATH first to avoid side effects on open/close.\n\nRelated: #1214745\n\nSigned-off-by: Jakub Filak '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int main(int argc,char *argv[])\n{\n int error= 0, ho_error;\n int first_command;\n my_bool can_handle_passwords;\n MYSQL mysql;\n char **commands, **save_argv;\n\n MY_INIT(argv[0]);\n mysql_init(&mysql);\n my_getopt_use_args_separator= TRUE;\n if (load_defaults(\"my\",load_default_groups,&argc,&argv))\n exit(1); \n my_getopt_use_args_separator= FALSE;\n\n save_argv = argv;\t\t\t\t/* Save for free_defaults */\n if ((ho_error=handle_options(&argc, &argv, my_long_options, get_one_option)))\n {\n free_defaults(save_argv);\n exit(ho_error);\n }\n if (debug_info_flag)\n my_end_arg= MY_CHECK_ERROR | MY_GIVE_INFO;\n if (debug_check_flag)\n my_end_arg= MY_CHECK_ERROR;\n\n if (argc == 0)\n {\n usage();\n exit(1);\n }\n commands = argv;\n if (tty_password)\n opt_password = get_tty_password(NullS);\n\n (void) signal(SIGINT,endprog);\t\t\t/* Here if abort */\n (void) signal(SIGTERM,endprog);\t\t/* Here if abort */\n\n if (opt_bind_addr)\n mysql_options(&mysql,MYSQL_OPT_BIND,opt_bind_addr);\n if (opt_compress)\n mysql_options(&mysql,MYSQL_OPT_COMPRESS,NullS);\n if (opt_connect_timeout)\n {\n uint tmp=opt_connect_timeout;\n mysql_options(&mysql,MYSQL_OPT_CONNECT_TIMEOUT, (char*) &tmp);\n }\n#ifdef HAVE_OPENSSL\n if (opt_use_ssl)\n {\n mysql_ssl_set(&mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,\n\t\t opt_ssl_capath, opt_ssl_cipher);\n mysql_options(&mysql, MYSQL_OPT_SSL_CRL, opt_ssl_crl);\n mysql_options(&mysql, MYSQL_OPT_SSL_CRLPATH, opt_ssl_crlpath);\n }\n mysql_options(&mysql,MYSQL_OPT_SSL_VERIFY_SERVER_CERT,\n (char*)&opt_ssl_verify_server_cert);\n#endif\n if (opt_protocol)\n mysql_options(&mysql,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol);\n#if defined (_WIN32) && !defined (EMBEDDED_LIBRARY)\n if (shared_memory_base_name)\n mysql_options(&mysql,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name);\n#endif\n mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, default_charset);\n error_flags= (myf)(opt_nobeep ? 0 : ME_BELL);\n\n if (opt_plugin_dir && *opt_plugin_dir)\n mysql_options(&mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir);\n\n if (opt_default_auth && *opt_default_auth)\n mysql_options(&mysql, MYSQL_DEFAULT_AUTH, opt_default_auth);\n\n mysql_options(&mysql, MYSQL_OPT_CONNECT_ATTR_RESET, 0);\n mysql_options4(&mysql, MYSQL_OPT_CONNECT_ATTR_ADD,\n \"program_name\", \"mysqladmin\");\n if (using_opt_enable_cleartext_plugin)\n mysql_options(&mysql, MYSQL_ENABLE_CLEARTEXT_PLUGIN, \n (char*) &opt_enable_cleartext_plugin);\n\n first_command= find_type(argv[0], &command_typelib, FIND_TYPE_BASIC);\n can_handle_passwords= \n (first_command == ADMIN_PASSWORD || first_command == ADMIN_OLD_PASSWORD) ?\n TRUE : FALSE;\n mysql_options(&mysql, MYSQL_OPT_CAN_HANDLE_EXPIRED_PASSWORDS,\n &can_handle_passwords);\n\n if (sql_connect(&mysql, option_wait))\n {\n /*\n We couldn't get an initial connection and will definitely exit.\n The following just determines the exit-code we'll give.\n */\n\n unsigned int err= mysql_errno(&mysql);\n if (err >= CR_MIN_ERROR && err <= CR_MAX_ERROR)\n error= 1;\n else\n {\n /* Return 0 if all commands are PING */\n for (; argc > 0; argv++, argc--)\n {\n if (find_type(argv[0], &command_typelib, FIND_TYPE_BASIC) !=\n ADMIN_PING)\n {\n error= 1;\n break;\n }\n }\n }\n }\n else\n {\n /*\n --count=0 aborts right here. Otherwise iff --sleep=t (\"interval\")\n is given a t!=0, we get an endless loop, or n iterations if --count=n\n was given an n!=0. If --sleep wasn't given, we get one iteration.\n\n To wit, --wait loops the connection-attempts, while --sleep loops\n the command execution (endlessly if no --count is given).\n */\n\n while (!interrupted && (!opt_count_iterations || nr_iterations))\n {\n new_line = 0;\n\n if ((error= execute_commands(&mysql,argc,commands)))\n {\n /*\n Unknown/malformed command always aborts and can't be --forced.\n If the user got confused about the syntax, proceeding would be\n dangerous ...\n */\n\tif (error > 0)\n\t break;\n\n /*\n Command was well-formed, but failed on the server. Might succeed\n on retry (if conditions on server change etc.), but needs --force\n to retry.\n */\n if (!option_force)\n break;\n } /* if((error= ... */\n\n if (interval) /* --sleep=interval given */\n {\n if (opt_count_iterations && --nr_iterations == 0)\n break;\n\n /*\n If connection was dropped (unintentionally, or due to SHUTDOWN),\n re-establish it if --wait (\"retry-connect\") was given and user\n didn't signal for us to die. Otherwise, signal failure.\n */\n\n\tif (mysql.net.vio == 0)\n\t{\n\t if (option_wait && !interrupted)\n\t {\n\t sleep(1);\n\t sql_connect(&mysql, option_wait);\n\t /*\n\t continue normally and decrease counters so that\n\t \"mysqladmin --count=1 --wait=1 shutdown\"\n\t cannot loop endlessly.\n\t */\n\t }\n\t else\n\t {\n\t /*\n\t connexion broke, and we have no order to re-establish it. fail.\n\t */\n\t if (!option_force)\n\t error= 1;\n\t break;\n\t }\n\t} /* lost connection */\n\n\tsleep(interval);\n\tif (new_line)\n\t puts(\"\");\n }\n else\n break; /* no --sleep, done looping */\n } /* command-loop */\n } /* got connection */\n\n mysql_close(&mysql);\n my_free(opt_password);\n my_free(user);\n#if defined (_WIN32) && !defined (EMBEDDED_LIBRARY)\n my_free(shared_memory_base_name);\n#endif\n free_defaults(save_argv);\n my_end(my_end_arg);\n exit(error ? 1 : 0);\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284', 'CWE-295'], 'message': 'WL#6791 : Redefine client --ssl option to imply enforced encryption\n\n# Changed the meaning of the --ssl=1 option of all client binaries\nto mean force ssl, not try ssl and fail over to eunecrypted\n# Added a new MYSQL_OPT_SSL_ENFORCE mysql_options()\noption to specify that an ssl connection is required.\n# Added a new macro SSL_SET_OPTIONS() to the client\nSSL handling headers that sets all the relevant SSL options at \nonce.\n# Revamped all of the current native clients to use the new macro\n# Removed some Windows line endings.\n# Added proper handling of the new option into the ssl helper\nheaders.\n# If SSL is mandatory assume that the media is secure enough \nfor the sha256 plugin to do unencrypted password exchange even\nbefore establishing a connection.\n# Set the default ssl cipher to DHE-RSA-AES256-SHA if none is \nspecified.\n# updated test cases that require a non-default cipher to spawn \na mysql command line tool binary since mysqltest has no support\nfor specifying ciphers.\n# updated the replication slave connection code to always enforce\nSSL if any of the SSL config options is present.\n# test cases added and updated.\n# added a mysql_get_option() API to return mysql_options() \nvalues. Used the new API inside the sha256 plugin.\n# Fixed compilation warnings because of unused variables.\n# Fixed test failures (mysql_ssl and bug13115401)\n# Fixed whitespace issues.\n# Fully implemented the mysql_get_option() function.\n# Added a test case for mysql_get_option()\n# fixed some trailing whitespace issues\n# fixed some uint/int warnings in mysql_client_test.c\n# removed shared memory option from non-windows get_options\n tests\n# moved MYSQL_OPT_LOCAL_INFILE to the uint options'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int run_tool(char *tool_path, DYNAMIC_STRING *ds_res, ...)\n{\n int ret;\n const char* arg;\n va_list args;\n DYNAMIC_STRING ds_cmdline;\n\n DBUG_ENTER(\"run_tool\");\n DBUG_PRINT(\"enter\", (\"tool_path: %s\", tool_path));\n\n if (init_dynamic_string(&ds_cmdline, IF_WIN(\"\\\"\", \"\"), FN_REFLEN, FN_REFLEN))\n die(\"Out of memory\");\n\n dynstr_append_os_quoted(&ds_cmdline, tool_path, NullS);\n dynstr_append(&ds_cmdline, \" \");\n\n va_start(args, ds_res);\n\n while ((arg= va_arg(args, char *)))\n {\n /* Options should be os quoted */\n if (strncmp(arg, \"--\", 2) == 0)\n dynstr_append_os_quoted(&ds_cmdline, arg, NullS);\n else\n dynstr_append(&ds_cmdline, arg);\n dynstr_append(&ds_cmdline, \" \");\n }\n\n va_end(args);\n\n#ifdef __WIN__\n dynstr_append(&ds_cmdline, \"\\\"\");\n#endif\n\n DBUG_PRINT(\"info\", (\"Running: %s\", ds_cmdline.str));\n ret= run_command(ds_cmdline.str, ds_res);\n DBUG_PRINT(\"exit\", (\"ret: %d\", ret));\n dynstr_free(&ds_cmdline);\n DBUG_RETURN(ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-295'], 'message': 'WL#9072: Backport WL#8785 to 5.5'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: _asn1_extract_der_octet (asn1_node node, const unsigned char *der,\n\t\t\t int der_len, unsigned flags)\n{\n int len2, len3;\n int counter, counter_end;\n int result;\n\n len2 = asn1_get_length_der (der, der_len, &len3);\n if (len2 < -1)\n return ASN1_DER_ERROR;\n\n counter = len3 + 1;\n\n if (len2 == -1)\n counter_end = der_len - 2;\n else\n counter_end = der_len;\n\n while (counter < counter_end)\n {\n len2 = asn1_get_length_der (der + counter, der_len, &len3);\n\n if (IS_ERR(len2, flags))\n\t{\n\t warn();\n\t return ASN1_DER_ERROR;\n\t}\n\n if (len2 >= 0)\n\t{\n\t DECR_LEN(der_len, len2+len3);\n\t _asn1_append_value (node, der + counter + len3, len2);\n\t}\n else\n\t{\t\t\t/* indefinite */\n\t DECR_LEN(der_len, len3);\n\t result =\n\t _asn1_extract_der_octet (node, der + counter + len3,\n\t\t\t\t der_len, flags);\n\t if (result != ASN1_SUCCESS)\n\t return result;\n\t len2 = 0;\n\t}\n\n DECR_LEN(der_len, 1);\n counter += len2 + len3 + 1;\n }\n\n return ASN1_SUCCESS;\n\ncleanup:\n return result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': '_asn1_extract_der_octet: prevent past of boundary access\n\nReported by Hanno B\u00f6ck.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline void perf_callchain_user_64(struct perf_callchain_entry *entry,\n\t\t\t\t\t struct pt_regs *regs)\n{\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'powerpc/perf: Cap 64bit userspace backtraces to PERF_MAX_STACK_DEPTH\n\nWe cap 32bit userspace backtraces to PERF_MAX_STACK_DEPTH\n(currently 127), but we forgot to do the same for 64bit backtraces.\n\nCc: stable@vger.kernel.org\nSigned-off-by: Anton Blanchard \nSigned-off-by: Michael Ellerman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: PHP_FUNCTION(chdir)\n{\n\tchar *str;\n\tint ret, str_len;\n\t\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"p\", &str, &str_len) == FAILURE) {\n\t\tRETURN_FALSE;\n\t}\n\n\tif (php_check_open_basedir(str TSRMLS_CC)) {\n\t\tRETURN_FALSE;\n\t}\n\tret = VCWD_CHDIR(str);\n\t\n\tif (ret != 0) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"%s (errno %d)\", strerror(errno), errno);\n\t\tRETURN_FALSE;\n\t}\n\n\tif (BG(CurrentStatFile) && !IS_ABSOLUTE_PATH(BG(CurrentStatFile), strlen(BG(CurrentStatFile)))) {\n\t\tefree(BG(CurrentStatFile));\n\t\tBG(CurrentStatFile) = NULL;\n\t}\n\tif (BG(CurrentLStatFile) && !IS_ABSOLUTE_PATH(BG(CurrentLStatFile), strlen(BG(CurrentLStatFile)))) {\n\t\tefree(BG(CurrentLStatFile));\n\t\tBG(CurrentLStatFile) = NULL;\n\t}\n\n\tRETURN_TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-19'], 'message': 'Fixed bug #69418 - more s->p fixes for filenames'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void pcntl_signal_handler(int signo)\n{\n\tstruct php_pcntl_pending_signal *psig;\n\tTSRMLS_FETCH();\n\t\n\tpsig = PCNTL_G(spares);\n\tif (!psig) {\n\t\t/* oops, too many signals for us to track, so we'll forget about this one */\n\t\treturn;\n\t}\n\tPCNTL_G(spares) = psig->next;\n\n\tpsig->signo = signo;\n\tpsig->next = NULL;\n\n\t/* the head check is important, as the tick handler cannot atomically clear both\n\t * the head and tail */\n\tif (PCNTL_G(head) && PCNTL_G(tail)) {\n\t\tPCNTL_G(tail)->next = psig;\n\t} else {\n\t\tPCNTL_G(head) = psig;\n\t}\n\tPCNTL_G(tail) = psig;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-19'], 'message': 'Fixed bug #69418 - more s->p fixes for filenames'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ftp_close(ftpbuf_t *ftp)\n{\n\tif (ftp == NULL) {\n\t\treturn NULL;\n\t}\n\tif (ftp->data) {\n\t\tdata_close(ftp, ftp->data);\n\t}\n\tif (ftp->stream && ftp->closestream) {\n\t\tTSRMLS_FETCH();\n\t\tphp_stream_close(ftp->stream);\n\t}\n\tif (ftp->fd != -1) {\n#if HAVE_OPENSSL_EXT\n\t\tif (ftp->ssl_active) {\n\t\t\tSSL_shutdown(ftp->ssl_handle);\n\t\t\tSSL_free(ftp->ssl_handle);\n\t\t}\n#endif\t\t\n\t\tclosesocket(ftp->fd);\n\t}\t\n\tftp_gc(ftp);\n\tefree(ftp);\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'Fix bug #69545 - avoid overflow when reading list'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ftp_alloc(ftpbuf_t *ftp, const long size, char **response)\n{\n\tchar buffer[64];\n\n\tif (ftp == NULL || size <= 0) {\n\t\treturn 0;\n\t}\n\n\tsnprintf(buffer, sizeof(buffer) - 1, \"%ld\", size);\n \n\tif (!ftp_putcmd(ftp, \"ALLO\", buffer)) {\n\t\treturn 0;\n\t}\n\n\tif (!ftp_getresp(ftp)) {\n\t\treturn 0;\n\t}\n\n\tif (response) {\n\t\t*response = estrdup(ftp->inbuf);\n\t}\n\n\tif (ftp->resp < 200 || ftp->resp >= 300) {\n\t\treturn 0;\n\t}\n\n\treturn 1;\t\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'Fix bug #69545 - avoid overflow when reading list'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int phar_parse_tarfile(php_stream* fp, char *fname, int fname_len, char *alias, int alias_len, phar_archive_data** pphar, int is_data, php_uint32 compression, char **error TSRMLS_DC) /* {{{ */\n{\n\tchar buf[512], *actual_alias = NULL, *p;\n\tphar_entry_info entry = {0};\n\tsize_t pos = 0, read, totalsize;\n\ttar_header *hdr;\n\tphp_uint32 sum1, sum2, size, old;\n\tphar_archive_data *myphar, **actual;\n\tint last_was_longlink = 0;\n\n\tif (error) {\n\t\t*error = NULL;\n\t}\n\n\tphp_stream_seek(fp, 0, SEEK_END);\n\ttotalsize = php_stream_tell(fp);\n\tphp_stream_seek(fp, 0, SEEK_SET);\n\tread = php_stream_read(fp, buf, sizeof(buf));\n\n\tif (read != sizeof(buf)) {\n\t\tif (error) {\n\t\t\tspprintf(error, 4096, \"phar error: \\\"%s\\\" is not a tar file or is truncated\", fname);\n\t\t}\n\t\tphp_stream_close(fp);\n\t\treturn FAILURE;\n\t}\n\n\thdr = (tar_header*)buf;\n\told = (memcmp(hdr->magic, \"ustar\", sizeof(\"ustar\")-1) != 0);\n\n\tmyphar = (phar_archive_data *) pecalloc(1, sizeof(phar_archive_data), PHAR_G(persist));\n\tmyphar->is_persistent = PHAR_G(persist);\n\t/* estimate number of entries, can't be certain with tar files */\n\tzend_hash_init(&myphar->manifest, 2 + (totalsize >> 12),\n\t\tzend_get_hash_value, destroy_phar_manifest_entry, (zend_bool)myphar->is_persistent);\n\tzend_hash_init(&myphar->mounted_dirs, 5,\n\t\tzend_get_hash_value, NULL, (zend_bool)myphar->is_persistent);\n\tzend_hash_init(&myphar->virtual_dirs, 4 + (totalsize >> 11),\n\t\tzend_get_hash_value, NULL, (zend_bool)myphar->is_persistent);\n\tmyphar->is_tar = 1;\n\t/* remember whether this entire phar was compressed with gz/bzip2 */\n\tmyphar->flags = compression;\n\n\tentry.is_tar = 1;\n\tentry.is_crc_checked = 1;\n\tentry.phar = myphar;\n\tpos += sizeof(buf);\n\n\tdo {\n\t\tphar_entry_info *newentry;\n\n\t\tpos = php_stream_tell(fp);\n\t\thdr = (tar_header*) buf;\n\t\tsum1 = phar_tar_number(hdr->checksum, sizeof(hdr->checksum));\n\t\tif (sum1 == 0 && phar_tar_checksum(buf, sizeof(buf)) == 0) {\n\t\t\tbreak;\n\t\t}\n\t\tmemset(hdr->checksum, ' ', sizeof(hdr->checksum));\n\t\tsum2 = phar_tar_checksum(buf, old?sizeof(old_tar_header):sizeof(tar_header));\n\n\t\tsize = entry.uncompressed_filesize = entry.compressed_filesize =\n\t\t\tphar_tar_number(hdr->size, sizeof(hdr->size));\n\n\t\tif (((!old && hdr->prefix[0] == 0) || old) && strlen(hdr->name) == sizeof(\".phar/signature.bin\")-1 && !strncmp(hdr->name, \".phar/signature.bin\", sizeof(\".phar/signature.bin\")-1)) {\n\t\t\toff_t curloc;\n\n\t\t\tif (size > 511) {\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 4096, \"phar error: tar-based phar \\\"%s\\\" has signature that is larger than 511 bytes, cannot process\", fname);\n\t\t\t\t}\nbail:\n\t\t\t\tphp_stream_close(fp);\n\t\t\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\t\t\tcurloc = php_stream_tell(fp);\n\t\t\tread = php_stream_read(fp, buf, size);\n\t\t\tif (read != size) {\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 4096, \"phar error: tar-based phar \\\"%s\\\" signature cannot be read\", fname);\n\t\t\t\t}\n\t\t\t\tgoto bail;\n\t\t\t}\n#ifdef WORDS_BIGENDIAN\n# define PHAR_GET_32(buffer) \\\n\t(((((unsigned char*)(buffer))[3]) << 24) \\\n\t\t| ((((unsigned char*)(buffer))[2]) << 16) \\\n\t\t| ((((unsigned char*)(buffer))[1]) << 8) \\\n\t\t| (((unsigned char*)(buffer))[0]))\n#else\n# define PHAR_GET_32(buffer) (php_uint32) *(buffer)\n#endif\n\t\t\tmyphar->sig_flags = PHAR_GET_32(buf);\n\t\t\tif (FAILURE == phar_verify_signature(fp, php_stream_tell(fp) - size - 512, myphar->sig_flags, buf + 8, size - 8, fname, &myphar->signature, &myphar->sig_len, error TSRMLS_CC)) {\n\t\t\t\tif (error) {\n\t\t\t\t\tchar *save = *error;\n\t\t\t\t\tspprintf(error, 4096, \"phar error: tar-based phar \\\"%s\\\" signature cannot be verified: %s\", fname, save);\n\t\t\t\t\tefree(save);\n\t\t\t\t}\n\t\t\t\tgoto bail;\n\t\t\t}\n\t\t\tphp_stream_seek(fp, curloc + 512, SEEK_SET);\n\t\t\t/* signature checked out, let's ensure this is the last file in the phar */\n\t\t\tif (((hdr->typeflag == '\\0') || (hdr->typeflag == TAR_FILE)) && size > 0) {\n\t\t\t\t/* this is not good enough - seek succeeds even on truncated tars */\n\t\t\t\tphp_stream_seek(fp, 512, SEEK_CUR);\n\t\t\t\tif ((uint)php_stream_tell(fp) > totalsize) {\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\tspprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (truncated)\", fname);\n\t\t\t\t\t}\n\t\t\t\t\tphp_stream_close(fp);\n\t\t\t\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\t\t\t\treturn FAILURE;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tread = php_stream_read(fp, buf, sizeof(buf));\n\n\t\t\tif (read != sizeof(buf)) {\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (truncated)\", fname);\n\t\t\t\t}\n\t\t\t\tphp_stream_close(fp);\n\t\t\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\n\t\t\thdr = (tar_header*) buf;\n\t\t\tsum1 = phar_tar_number(hdr->checksum, sizeof(hdr->checksum));\n\n\t\t\tif (sum1 == 0 && phar_tar_checksum(buf, sizeof(buf)) == 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (error) {\n\t\t\t\tspprintf(error, 4096, \"phar error: \\\"%s\\\" has entries after signature, invalid phar\", fname);\n\t\t\t}\n\n\t\t\tgoto bail;\n\t\t}\n\n\t\tif (!last_was_longlink && hdr->typeflag == 'L') {\n\t\t\tlast_was_longlink = 1;\n\t\t\t/* support the ././@LongLink system for storing long filenames */\n\t\t\tentry.filename_len = entry.uncompressed_filesize;\n\n\t\t\t/* Check for overflow - bug 61065 */\n\t\t\tif (entry.filename_len == UINT_MAX) {\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (invalid entry size)\", fname);\n\t\t\t\t}\n\t\t\t\tphp_stream_close(fp);\n\t\t\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\t\t\tentry.filename = pemalloc(entry.filename_len+1, myphar->is_persistent);\n\n\t\t\tread = php_stream_read(fp, entry.filename, entry.filename_len);\n\t\t\tif (read != entry.filename_len) {\n\t\t\t\tefree(entry.filename);\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (truncated)\", fname);\n\t\t\t\t}\n\t\t\t\tphp_stream_close(fp);\n\t\t\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\t\t\tentry.filename[entry.filename_len] = '\\0';\n\n\t\t\t/* skip blank stuff */\n\t\t\tsize = ((size+511)&~511) - size;\n\n\t\t\t/* this is not good enough - seek succeeds even on truncated tars */\n\t\t\tphp_stream_seek(fp, size, SEEK_CUR);\n\t\t\tif ((uint)php_stream_tell(fp) > totalsize) {\n\t\t\t\tefree(entry.filename);\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (truncated)\", fname);\n\t\t\t\t}\n\t\t\t\tphp_stream_close(fp);\n\t\t\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\n\t\t\tread = php_stream_read(fp, buf, sizeof(buf));\n\n\t\t\tif (read != sizeof(buf)) {\n\t\t\t\tefree(entry.filename);\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (truncated)\", fname);\n\t\t\t\t}\n\t\t\t\tphp_stream_close(fp);\n\t\t\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\t\t\tcontinue;\n\t\t} else if (!last_was_longlink && !old && hdr->prefix[0] != 0) {\n\t\t\tchar name[256];\n\t\t\tint i, j;\n\n\t\t\tfor (i = 0; i < 155; i++) {\n\t\t\t\tname[i] = hdr->prefix[i];\n\t\t\t\tif (name[i] == '\\0') {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tname[i++] = '/';\n\t\t\tfor (j = 0; j < 100; j++) {\n\t\t\t\tname[i+j] = hdr->name[j];\n\t\t\t\tif (name[i+j] == '\\0') {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tentry.filename_len = i+j;\n\n\t\t\tif (name[entry.filename_len - 1] == '/') {\n\t\t\t\t/* some tar programs store directories with trailing slash */\n\t\t\t\tentry.filename_len--;\n\t\t\t}\n\t\t\tentry.filename = pestrndup(name, entry.filename_len, myphar->is_persistent);\n\t\t} else if (!last_was_longlink) {\n\t\t\tint i;\n\n\t\t\t/* calculate strlen, which can be no longer than 100 */\n\t\t\tfor (i = 0; i < 100; i++) {\n\t\t\t\tif (hdr->name[i] == '\\0') {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tentry.filename_len = i;\n\t\t\tentry.filename = pestrndup(hdr->name, i, myphar->is_persistent);\n\n\t\t\tif (entry.filename[entry.filename_len - 1] == '/') {\n\t\t\t\t/* some tar programs store directories with trailing slash */\n\t\t\t\tentry.filename[entry.filename_len - 1] = '\\0';\n\t\t\t\tentry.filename_len--;\n\t\t\t}\n\t\t}\n\t\tlast_was_longlink = 0;\n\n\t\tphar_add_virtual_dirs(myphar, entry.filename, entry.filename_len TSRMLS_CC);\n\n\t\tif (sum1 != sum2) {\n\t\t\tif (error) {\n\t\t\t\tspprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (checksum mismatch of file \\\"%s\\\")\", fname, entry.filename);\n\t\t\t}\n\t\t\tpefree(entry.filename, myphar->is_persistent);\n\t\t\tphp_stream_close(fp);\n\t\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\t\treturn FAILURE;\n\t\t}\n\n\t\tentry.tar_type = ((old & (hdr->typeflag == '\\0')) ? TAR_FILE : hdr->typeflag);\n\t\tentry.offset = entry.offset_abs = pos; /* header_offset unused in tar */\n\t\tentry.fp_type = PHAR_FP;\n\t\tentry.flags = phar_tar_number(hdr->mode, sizeof(hdr->mode)) & PHAR_ENT_PERM_MASK;\n\t\tentry.timestamp = phar_tar_number(hdr->mtime, sizeof(hdr->mtime));\n\t\tentry.is_persistent = myphar->is_persistent;\n#ifndef S_ISDIR\n#define S_ISDIR(mode)\t(((mode)&S_IFMT) == S_IFDIR)\n#endif\n\t\tif (old && entry.tar_type == TAR_FILE && S_ISDIR(entry.flags)) {\n\t\t\tentry.tar_type = TAR_DIR;\n\t\t}\n\n\t\tif (entry.tar_type == TAR_DIR) {\n\t\t\tentry.is_dir = 1;\n\t\t} else {\n\t\t\tentry.is_dir = 0;\n\t\t}\n\n\t\tentry.link = NULL;\n\n\t\tif (entry.tar_type == TAR_LINK) {\n\t\t\tif (!zend_hash_exists(&myphar->manifest, hdr->linkname, strlen(hdr->linkname))) {\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file - hard link to non-existent file \\\"%s\\\"\", fname, hdr->linkname);\n\t\t\t\t}\n\t\t\t\tpefree(entry.filename, entry.is_persistent);\n\t\t\t\tphp_stream_close(fp);\n\t\t\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\t\t\tentry.link = estrdup(hdr->linkname);\n\t\t} else if (entry.tar_type == TAR_SYMLINK) {\n\t\t\tentry.link = estrdup(hdr->linkname);\n\t\t}\n\t\tphar_set_inode(&entry TSRMLS_CC);\n\t\tzend_hash_add(&myphar->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info), (void **) &newentry);\n\n\t\tif (entry.is_persistent) {\n\t\t\t++entry.manifest_pos;\n\t\t}\n\n\t\tif (entry.filename_len >= sizeof(\".phar/.metadata\")-1 && !memcmp(entry.filename, \".phar/.metadata\", sizeof(\".phar/.metadata\")-1)) {\n\t\t\tif (FAILURE == phar_tar_process_metadata(newentry, fp TSRMLS_CC)) {\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 4096, \"phar error: tar-based phar \\\"%s\\\" has invalid metadata in magic file \\\"%s\\\"\", fname, entry.filename);\n\t\t\t\t}\n\t\t\t\tphp_stream_close(fp);\n\t\t\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\t\t}\n\n\t\tif (!actual_alias && entry.filename_len == sizeof(\".phar/alias.txt\")-1 && !strncmp(entry.filename, \".phar/alias.txt\", sizeof(\".phar/alias.txt\")-1)) {\n\t\t\t/* found explicit alias */\n\t\t\tif (size > 511) {\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 4096, \"phar error: tar-based phar \\\"%s\\\" has alias that is larger than 511 bytes, cannot process\", fname);\n\t\t\t\t}\n\t\t\t\tphp_stream_close(fp);\n\t\t\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\n\t\t\tread = php_stream_read(fp, buf, size);\n\n\t\t\tif (read == size) {\n\t\t\t\tbuf[size] = '\\0';\n\t\t\t\tif (!phar_validate_alias(buf, size)) {\n\t\t\t\t\tif (size > 50) {\n\t\t\t\t\t\tbuf[50] = '.';\n\t\t\t\t\t\tbuf[51] = '.';\n\t\t\t\t\t\tbuf[52] = '.';\n\t\t\t\t\t\tbuf[53] = '\\0';\n\t\t\t\t\t}\n\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\tspprintf(error, 4096, \"phar error: invalid alias \\\"%s\\\" in tar-based phar \\\"%s\\\"\", buf, fname);\n\t\t\t\t\t}\n\n\t\t\t\t\tphp_stream_close(fp);\n\t\t\t\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\t\t\t\treturn FAILURE;\n\t\t\t\t}\n\n\t\t\t\tactual_alias = pestrndup(buf, size, myphar->is_persistent);\n\t\t\t\tmyphar->alias = actual_alias;\n\t\t\t\tmyphar->alias_len = size;\n\t\t\t\tphp_stream_seek(fp, pos, SEEK_SET);\n\t\t\t} else {\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 4096, \"phar error: Unable to read alias from tar-based phar \\\"%s\\\"\", fname);\n\t\t\t\t}\n\n\t\t\t\tphp_stream_close(fp);\n\t\t\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\t\t}\n\n\t\tsize = (size+511)&~511;\n\n\t\tif (((hdr->typeflag == '\\0') || (hdr->typeflag == TAR_FILE)) && size > 0) {\n\t\t\t/* this is not good enough - seek succeeds even on truncated tars */\n\t\t\tphp_stream_seek(fp, size, SEEK_CUR);\n\t\t\tif ((uint)php_stream_tell(fp) > totalsize) {\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (truncated)\", fname);\n\t\t\t\t}\n\t\t\t\tphp_stream_close(fp);\n\t\t\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\t\t}\n\n\t\tread = php_stream_read(fp, buf, sizeof(buf));\n\n\t\tif (read != sizeof(buf)) {\n\t\t\tif (error) {\n\t\t\t\tspprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (truncated)\", fname);\n\t\t\t}\n\t\t\tphp_stream_close(fp);\n\t\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\t\treturn FAILURE;\n\t\t}\n\t} while (read != 0);\n\n\tif (zend_hash_exists(&(myphar->manifest), \".phar/stub.php\", sizeof(\".phar/stub.php\")-1)) {\n\t\tmyphar->is_data = 0;\n\t} else {\n\t\tmyphar->is_data = 1;\n\t}\n\n\t/* ensure signature set */\n\tif (!myphar->is_data && PHAR_G(require_hash) && !myphar->signature) {\n\t\tphp_stream_close(fp);\n\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\tif (error) {\n\t\t\tspprintf(error, 0, \"tar-based phar \\\"%s\\\" does not have a signature\", fname);\n\t\t}\n\t\treturn FAILURE;\n\t}\n\n\tmyphar->fname = pestrndup(fname, fname_len, myphar->is_persistent);\n#ifdef PHP_WIN32\n\tphar_unixify_path_separators(myphar->fname, fname_len);\n#endif\n\tmyphar->fname_len = fname_len;\n\tmyphar->fp = fp;\n\tp = strrchr(myphar->fname, '/');\n\n\tif (p) {\n\t\tmyphar->ext = memchr(p, '.', (myphar->fname + fname_len) - p);\n\t\tif (myphar->ext == p) {\n\t\t\tmyphar->ext = memchr(p + 1, '.', (myphar->fname + fname_len) - p - 1);\n\t\t}\n\t\tif (myphar->ext) {\n\t\t\tmyphar->ext_len = (myphar->fname + fname_len) - myphar->ext;\n\t\t}\n\t}\n\n\tphar_request_initialize(TSRMLS_C);\n\n\tif (SUCCESS != zend_hash_add(&(PHAR_GLOBALS->phar_fname_map), myphar->fname, fname_len, (void*)&myphar, sizeof(phar_archive_data*), (void **)&actual)) {\n\t\tif (error) {\n\t\t\tspprintf(error, 4096, \"phar error: Unable to add tar-based phar \\\"%s\\\" to phar registry\", fname);\n\t\t}\n\t\tphp_stream_close(fp);\n\t\tphar_destroy_phar_data(myphar TSRMLS_CC);\n\t\treturn FAILURE;\n\t}\n\n\tmyphar = *actual;\n\n\tif (actual_alias) {\n\t\tphar_archive_data **fd_ptr;\n\n\t\tmyphar->is_temporary_alias = 0;\n\n\t\tif (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), actual_alias, myphar->alias_len, (void **)&fd_ptr)) {\n\t\t\tif (SUCCESS != phar_free_alias(*fd_ptr, actual_alias, myphar->alias_len TSRMLS_CC)) {\n\t\t\t\tif (error) {\n\t\t\t\t\tspprintf(error, 4096, \"phar error: Unable to add tar-based phar \\\"%s\\\", alias is already in use\", fname);\n\t\t\t\t}\n\t\t\t\tzend_hash_del(&(PHAR_GLOBALS->phar_fname_map), myphar->fname, fname_len);\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\t\t}\n\n\t\tzend_hash_add(&(PHAR_GLOBALS->phar_alias_map), actual_alias, myphar->alias_len, (void*)&myphar, sizeof(phar_archive_data*), NULL);\n\t} else {\n\t\tphar_archive_data **fd_ptr;\n\n\t\tif (alias_len) {\n\t\t\tif (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void **)&fd_ptr)) {\n\t\t\t\tif (SUCCESS != phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) {\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\tspprintf(error, 4096, \"phar error: Unable to add tar-based phar \\\"%s\\\", alias is already in use\", fname);\n\t\t\t\t\t}\n\t\t\t\t\tzend_hash_del(&(PHAR_GLOBALS->phar_fname_map), myphar->fname, fname_len);\n\t\t\t\t\treturn FAILURE;\n\t\t\t\t}\n\t\t\t}\n\t\t\tzend_hash_add(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void*)&myphar, sizeof(phar_archive_data*), NULL);\n\t\t\tmyphar->alias = pestrndup(alias, alias_len, myphar->is_persistent);\n\t\t\tmyphar->alias_len = alias_len;\n\t\t} else {\n\t\t\tmyphar->alias = pestrndup(myphar->fname, fname_len, myphar->is_persistent);\n\t\t\tmyphar->alias_len = fname_len;\n\t\t}\n\n\t\tmyphar->is_temporary_alias = 1;\n\t}\n\n\tif (pphar) {\n\t\t*pphar = myphar;\n\t}\n\n\treturn SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'Fix bug #69453 - don't try to cut empty string'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: tTcpIpPacketParsingResult ParaNdis_CheckSumVerify(\n tCompletePhysicalAddress *pDataPages,\n ULONG ulDataLength,\n ULONG ulStartOffset,\n ULONG flags,\n LPCSTR caller)\n{\n IPHeader *pIpHeader = (IPHeader *) RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset);\n\n tTcpIpPacketParsingResult res = QualifyIpPacket(pIpHeader, ulDataLength);\n if (res.ipStatus == ppresNotIP || res.ipCheckSum == ppresIPTooShort)\n return res;\n\n if (res.ipStatus == ppresIPV4)\n {\n if (flags & pcrIpChecksum)\n res = VerifyIpChecksum(&pIpHeader->v4, res, (flags & pcrFixIPChecksum) != 0);\n if(res.xxpStatus == ppresXxpKnown)\n {\n if (res.TcpUdp == ppresIsTCP) /* TCP */\n {\n if(flags & pcrTcpV4Checksum)\n {\n res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV4Checksum));\n }\n }\n else /* UDP */\n {\n if (flags & pcrUdpV4Checksum)\n {\n res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV4Checksum));\n }\n }\n }\n }\n else if (res.ipStatus == ppresIPV6)\n {\n if(res.xxpStatus == ppresXxpKnown)\n {\n if (res.TcpUdp == ppresIsTCP) /* TCP */\n {\n if(flags & pcrTcpV6Checksum)\n {\n res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV6Checksum));\n }\n }\n else /* UDP */\n {\n if (flags & pcrUdpV6Checksum)\n {\n res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV6Checksum));\n }\n }\n }\n }\n PrintOutParsingResult(res, 1, caller);\n return res;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'NetKVM: BZ#1169718: Checking the length only on read\n\nSigned-off-by: Joseph Hindin '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: QualifyIpPacket(IPHeader *pIpHeader, ULONG len)\n{\n tTcpIpPacketParsingResult res;\n UCHAR ver_len = pIpHeader->v4.ip_verlen;\n UCHAR ip_version = (ver_len & 0xF0) >> 4;\n USHORT ipHeaderSize = 0;\n USHORT fullLength = 0;\n res.value = 0;\n \n if (ip_version == 4)\n {\n ipHeaderSize = (ver_len & 0xF) << 2;\n fullLength = swap_short(pIpHeader->v4.ip_length);\n DPrintf(3, (\"ip_version %d, ipHeaderSize %d, protocol %d, iplen %d\\n\",\n ip_version, ipHeaderSize, pIpHeader->v4.ip_protocol, fullLength));\n res.ipStatus = (ipHeaderSize >= sizeof(IPv4Header)) ? ppresIPV4 : ppresNotIP;\n if (len < ipHeaderSize) res.ipCheckSum = ppresIPTooShort;\n if (fullLength) {}\n else\n {\n DPrintf(2, (\"ip v.%d, iplen %d\\n\", ip_version, fullLength));\n }\n }\n else if (ip_version == 6)\n {\n UCHAR nextHeader = pIpHeader->v6.ip6_next_header;\n BOOLEAN bParsingDone = FALSE;\n ipHeaderSize = sizeof(pIpHeader->v6);\n res.ipStatus = ppresIPV6;\n res.ipCheckSum = ppresCSOK;\n fullLength = swap_short(pIpHeader->v6.ip6_payload_len);\n fullLength += ipHeaderSize;\n while (nextHeader != 59)\n {\n IPv6ExtHeader *pExt;\n switch (nextHeader)\n {\n case PROTOCOL_TCP:\n bParsingDone = TRUE;\n res.xxpStatus = ppresXxpKnown;\n res.TcpUdp = ppresIsTCP;\n res.xxpFull = len >= fullLength ? 1 : 0;\n res = ProcessTCPHeader(res, pIpHeader, len, ipHeaderSize);\n break;\n case PROTOCOL_UDP:\n bParsingDone = TRUE;\n res.xxpStatus = ppresXxpKnown;\n res.TcpUdp = ppresIsUDP;\n res.xxpFull = len >= fullLength ? 1 : 0;\n res = ProcessUDPHeader(res, pIpHeader, len, ipHeaderSize);\n break;\n //existing extended headers\n case 0:\n case 60:\n case 43:\n case 44:\n case 51:\n case 50:\n case 135:\n if (len >= ((ULONG)ipHeaderSize + 8))\n {\n pExt = (IPv6ExtHeader *)((PUCHAR)pIpHeader + ipHeaderSize);\n nextHeader = pExt->ip6ext_next_header;\n ipHeaderSize += 8;\n ipHeaderSize += pExt->ip6ext_hdr_len * 8;\n }\n else\n {\n DPrintf(0, (\"[%s] ERROR: Break in the middle of ext. headers(len %d, hdr > %d)\\n\", __FUNCTION__, len, ipHeaderSize));\n res.ipStatus = ppresNotIP;\n bParsingDone = TRUE;\n }\n break;\n //any other protocol\n default:\n res.xxpStatus = ppresXxpOther;\n bParsingDone = TRUE;\n break;\n }\n if (bParsingDone)\n break;\n }\n if (ipHeaderSize <= MAX_SUPPORTED_IPV6_HEADERS)\n {\n DPrintf(3, (\"ip_version %d, ipHeaderSize %d, protocol %d, iplen %d\\n\",\n ip_version, ipHeaderSize, nextHeader, fullLength));\n res.ipHeaderSize = ipHeaderSize;\n }\n else\n {\n DPrintf(0, (\"[%s] ERROR: IP chain is too large (%d)\\n\", __FUNCTION__, ipHeaderSize));\n res.ipStatus = ppresNotIP;\n }\n }\n \n if (res.ipStatus == ppresIPV4)\n {\n res.ipHeaderSize = ipHeaderSize;\n res.xxpFull = len >= fullLength ? 1 : 0;\n // bit \"more fragments\" or fragment offset mean the packet is fragmented\n res.IsFragment = (pIpHeader->v4.ip_offset & ~0xC0) != 0;\n switch (pIpHeader->v4.ip_protocol)\n {\n case PROTOCOL_TCP:\n {\n res = ProcessTCPHeader(res, pIpHeader, len, ipHeaderSize);\n }\n break;\n case PROTOCOL_UDP:\n {\n res = ProcessUDPHeader(res, pIpHeader, len, ipHeaderSize);\n }\n break;\n default:\n res.xxpStatus = ppresXxpOther;\n break;\n }\n }\n return res;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'NetKVM: BZ#1169718: More rigoruous testing of incoming packet\n\nSigned-off-by: Joseph Hindin '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: PHP_FUNCTION(imagegrabwindow)\n{\n\tHWND window;\n\tlong client_area = 0;\n\tRECT rc = {0};\n\tRECT rc_win = {0};\n\tint Width, Height;\n\tHDC\t\thdc;\n\tHDC memDC;\n\tHBITMAP memBM;\n\tHBITMAP hOld;\n\tHINSTANCE handle;\n\tlong lwindow_handle;\n\ttypedef BOOL (WINAPI *tPrintWindow)(HWND, HDC,UINT);\n\ttPrintWindow pPrintWindow = 0;\n\tgdImagePtr im;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"l|l\", &lwindow_handle, &client_area) == FAILURE) {\n\t\tRETURN_FALSE;\n\t}\n\n\twindow = (HWND) lwindow_handle;\n\n\tif (!IsWindow(window)) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_NOTICE, \"Invalid window handle\");\n\t\tRETURN_FALSE;\n\t}\n\n\thdc\t\t= GetDC(0);\n\n\tif (client_area) {\n\t\tGetClientRect(window, &rc);\n\t\tWidth = rc.right;\n\t\tHeight = rc.bottom;\n\t} else {\n\t\tGetWindowRect(window, &rc);\n\t\tWidth\t= rc.right - rc.left;\n\t\tHeight\t= rc.bottom - rc.top;\n\t}\n\n\tWidth\t\t= (Width/4)*4;\n\n\tmemDC\t= CreateCompatibleDC(hdc);\n\tmemBM\t= CreateCompatibleBitmap(hdc, Width, Height);\n\thOld\t= (HBITMAP) SelectObject (memDC, memBM);\n\n\n\thandle = LoadLibrary(\"User32.dll\");\n\tif ( handle == 0 ) {\n\t\tgoto clean;\n\t}\n\tpPrintWindow = (tPrintWindow) GetProcAddress(handle, \"PrintWindow\"); \n\n\tif ( pPrintWindow ) {\n\t\tpPrintWindow(window, memDC, (UINT) client_area);\n\t} else {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Windows API too old\");\n\t\tgoto clean;\n\t}\n\n\tFreeLibrary(handle);\n\n\tim = gdImageCreateTrueColor(Width, Height);\n\tif (im) {\n\t\tint x,y;\n\t\tfor (y=0; y <= Height; y++) {\n\t\t\tfor (x=0; x <= Width; x++) {\n\t\t\t\tint c = GetPixel(memDC, x,y);\n\t\t\t\tgdImageSetPixel(im, x, y, gdTrueColor(GetRValue(c), GetGValue(c), GetBValue(c)));\n\t\t\t}\n\t\t}\n\t}\n\nclean:\n\tSelectObject(memDC,hOld);\n\tDeleteObject(memBM);\n\tDeleteDC(memDC);\n\tReleaseDC( 0, hdc );\n\n\tif (!im) {\n\t\tRETURN_FALSE;\n\t} else {\n\t\tZEND_REGISTER_RESOURCE(return_value, im, le_gd);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fix #69719 - more checks for nulls in paths'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: SSL_CTX *tls_init_ctx(fr_tls_server_conf_t *conf, int client)\n{\n\tSSL_CTX\t\t*ctx;\n\tX509_STORE\t*certstore;\n\tint\t\tverify_mode = SSL_VERIFY_NONE;\n\tint\t\tctx_options = 0;\n\tint\t\tctx_tls_versions = 0;\n\tint\t\ttype;\n\n\t/*\n\t *\tSHA256 is in all versions of OpenSSL, but isn't\n\t *\tinitialized by default. It's needed for WiMAX\n\t *\tcertificates.\n\t */\n#ifdef HAVE_OPENSSL_EVP_SHA256\n\tEVP_add_digest(EVP_sha256());\n#endif\n\n\tctx = SSL_CTX_new(SSLv23_method()); /* which is really \"all known SSL / TLS methods\". Idiots. */\n\tif (!ctx) {\n\t\tint err;\n\t\twhile ((err = ERR_get_error())) {\n\t\t\tERROR(LOG_PREFIX \": Failed creating SSL context: %s\", ERR_error_string(err, NULL));\n\t\t\treturn NULL;\n\t\t}\n\t}\n\n\t/*\n\t * Save the config on the context so that callbacks which\n\t * only get SSL_CTX* e.g. session persistence, can get it\n\t */\n\tSSL_CTX_set_app_data(ctx, conf);\n\n\t/*\n\t * Identify the type of certificates that needs to be loaded\n\t */\n\tif (conf->file_type) {\n\t\ttype = SSL_FILETYPE_PEM;\n\t} else {\n\t\ttype = SSL_FILETYPE_ASN1;\n\t}\n\n\t/*\n\t * Set the password to load private key\n\t */\n\tif (conf->private_key_password) {\n#ifdef __APPLE__\n\t\t/*\n\t\t * We don't want to put the private key password in eap.conf, so check\n\t\t * for our special string which indicates we should get the password\n\t\t * programmatically.\n\t\t */\n\t\tchar const* special_string = \"Apple:UseCertAdmin\";\n\t\tif (strncmp(conf->private_key_password, special_string, strlen(special_string)) == 0) {\n\t\t\tchar cmd[256];\n\t\t\tchar *password;\n\t\t\tlong const max_password_len = 128;\n\t\t\tsnprintf(cmd, sizeof(cmd) - 1, \"/usr/sbin/certadmin --get-private-key-passphrase \\\"%s\\\"\",\n\t\t\t\t conf->private_key_file);\n\n\t\t\tDEBUG2(LOG_PREFIX \": Getting private key passphrase using command \\\"%s\\\"\", cmd);\n\n\t\t\tFILE* cmd_pipe = popen(cmd, \"r\");\n\t\t\tif (!cmd_pipe) {\n\t\t\t\tERROR(LOG_PREFIX \": %s command failed: Unable to get private_key_password\", cmd);\n\t\t\t\tERROR(LOG_PREFIX \": Error reading private_key_file %s\", conf->private_key_file);\n\t\t\t\treturn NULL;\n\t\t\t}\n\n\t\t\trad_const_free(conf->private_key_password);\n\t\t\tpassword = talloc_array(conf, char, max_password_len);\n\t\t\tif (!password) {\n\t\t\t\tERROR(LOG_PREFIX \": Can't allocate space for private_key_password\");\n\t\t\t\tERROR(LOG_PREFIX \": Error reading private_key_file %s\", conf->private_key_file);\n\t\t\t\tpclose(cmd_pipe);\n\t\t\t\treturn NULL;\n\t\t\t}\n\n\t\t\tfgets(password, max_password_len, cmd_pipe);\n\t\t\tpclose(cmd_pipe);\n\n\t\t\t/* Get rid of newline at end of password. */\n\t\t\tpassword[strlen(password) - 1] = '\\0';\n\n\t\t\tDEBUG3(LOG_PREFIX \": Password from command = \\\"%s\\\"\", password);\n\t\t\tconf->private_key_password = password;\n\t\t}\n#endif\n\n\t\t{\n\t\t\tchar *password;\n\n\t\t\tmemcpy(&password, &conf->private_key_password, sizeof(password));\n\t\t\tSSL_CTX_set_default_passwd_cb_userdata(ctx, password);\n\t\t\tSSL_CTX_set_default_passwd_cb(ctx, cbtls_password);\n\t\t}\n\t}\n\n#ifdef PSK_MAX_IDENTITY_LEN\n\tif (!client) {\n\t\t/*\n\t\t *\tNo dynamic query exists. There MUST be a\n\t\t *\tstatically configured identity and password.\n\t\t */\n\t\tif (conf->psk_query && !*conf->psk_query) {\n\t\t\tERROR(LOG_PREFIX \": Invalid PSK Configuration: psk_query cannot be empty\");\n\t\t\treturn NULL;\n\t\t}\n\n\t\t/*\n\t\t *\tSet the callback only if we can check things.\n\t\t */\n\t\tif (conf->psk_identity || conf->psk_query) {\n\t\t\tSSL_CTX_set_psk_server_callback(ctx, psk_server_callback);\n\t\t}\n\n\t} else if (conf->psk_query) {\n\t\tERROR(LOG_PREFIX \": Invalid PSK Configuration: psk_query cannot be used for outgoing connections\");\n\t\treturn NULL;\n\t}\n\n\t/*\n\t *\tNow check that if PSK is being used, the config is valid.\n\t */\n\tif ((conf->psk_identity && !conf->psk_password) ||\n\t (!conf->psk_identity && conf->psk_password) ||\n\t (conf->psk_identity && !*conf->psk_identity) ||\n\t (conf->psk_password && !*conf->psk_password)) {\n\t\tERROR(LOG_PREFIX \": Invalid PSK Configuration: psk_identity or psk_password are empty\");\n\t\treturn NULL;\n\t}\n\n\tif (conf->psk_identity) {\n\t\tsize_t psk_len, hex_len;\n\t\tuint8_t buffer[PSK_MAX_PSK_LEN];\n\n\t\tif (conf->certificate_file ||\n\t\t conf->private_key_password || conf->private_key_file ||\n\t\t conf->ca_file || conf->ca_path) {\n\t\t\tERROR(LOG_PREFIX \": When PSKs are used, No certificate configuration is permitted\");\n\t\t\treturn NULL;\n\t\t}\n\n\t\tif (client) {\n\t\t\tSSL_CTX_set_psk_client_callback(ctx,\n\t\t\t\t\t\t\tpsk_client_callback);\n\t\t}\n\n\t\tpsk_len = strlen(conf->psk_password);\n\t\tif (strlen(conf->psk_password) > (2 * PSK_MAX_PSK_LEN)) {\n\t\t\tERROR(LOG_PREFIX \": psk_hexphrase is too long (max %d)\", PSK_MAX_PSK_LEN);\n\t\t\treturn NULL;\n\t\t}\n\n\t\t/*\n\t\t *\tCheck the password now, so that we don't have\n\t\t *\terrors at run-time.\n\t\t */\n\t\thex_len = fr_hex2bin(buffer, sizeof(buffer), conf->psk_password, psk_len);\n\t\tif (psk_len != (2 * hex_len)) {\n\t\t\tERROR(LOG_PREFIX \": psk_hexphrase is not all hex\");\n\t\t\treturn NULL;\n\t\t}\n\n\t\tgoto post_ca;\n\t}\n#else\n\t(void) client;\t/* -Wunused */\n#endif\n\n\t/*\n\t *\tLoad our keys and certificates\n\t *\n\t *\tIf certificates are of type PEM then we can make use\n\t *\tof cert chain authentication using openssl api call\n\t *\tSSL_CTX_use_certificate_chain_file. Please see how\n\t *\tthe cert chain needs to be given in PEM from\n\t *\topenSSL.org\n\t */\n\tif (!conf->certificate_file) goto load_ca;\n\n\tif (type == SSL_FILETYPE_PEM) {\n\t\tif (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) {\n\t\t\tERROR(LOG_PREFIX \": Error reading certificate file %s:%s\", conf->certificate_file,\n\t\t\t ERR_error_string(ERR_get_error(), NULL));\n\t\t\treturn NULL;\n\t\t}\n\n\t} else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) {\n\t\tERROR(LOG_PREFIX \": Error reading certificate file %s:%s\",\n\t\t conf->certificate_file,\n\t\t ERR_error_string(ERR_get_error(), NULL));\n\t\treturn NULL;\n\t}\n\n\t/* Load the CAs we trust */\nload_ca:\n\tif (conf->ca_file || conf->ca_path) {\n\t\tif (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {\n\t\t\tERROR(LOG_PREFIX \": SSL error %s\", ERR_error_string(ERR_get_error(), NULL));\n\t\t\tERROR(LOG_PREFIX \": Error reading Trusted root CA list %s\",conf->ca_file );\n\t\t\treturn NULL;\n\t\t}\n\t}\n\tif (conf->ca_file && *conf->ca_file) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));\n\n\tif (conf->private_key_file) {\n\t\tif (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) {\n\t\t\tERROR(LOG_PREFIX \": Failed reading private key file %s:%s\",\n\t\t\t conf->private_key_file,\n\t\t\t ERR_error_string(ERR_get_error(), NULL));\n\t\t\treturn NULL;\n\t\t}\n\n\t\t/*\n\t\t * Check if the loaded private key is the right one\n\t\t */\n\t\tif (!SSL_CTX_check_private_key(ctx)) {\n\t\t\tERROR(LOG_PREFIX \": Private key does not match the certificate public key\");\n\t\t\treturn NULL;\n\t\t}\n\t}\n\n#ifdef PSK_MAX_IDENTITY_LEN\npost_ca:\n#endif\n\n\t/*\n\t *\tWe never want SSLv2 or SSLv3.\n\t */\n\tctx_options |= SSL_OP_NO_SSLv2;\n\tctx_options |= SSL_OP_NO_SSLv3;\n\n\t/*\n\t *\tAs of 3.0.5, we always allow TLSv1.1 and TLSv1.2.\n\t *\tThough they can be *globally* disabled if necessary.x\n\t */\n#ifdef SSL_OP_NO_TLSv1\n\tif (conf->disable_tlsv1) ctx_options |= SSL_OP_NO_TLSv1;\n\n\tctx_tls_versions |= SSL_OP_NO_TLSv1;\n#endif\n#ifdef SSL_OP_NO_TLSv1_1\n\tif (conf->disable_tlsv1_1) ctx_options |= SSL_OP_NO_TLSv1_1;\n\n\tctx_tls_versions |= SSL_OP_NO_TLSv1_1;\n#endif\n#ifdef SSL_OP_NO_TLSv1_2\n\tif (conf->disable_tlsv1_2) ctx_options |= SSL_OP_NO_TLSv1_2;\n\n\tctx_tls_versions |= SSL_OP_NO_TLSv1_2;\n#endif\n\n\tif ((ctx_options & ctx_tls_versions) == ctx_tls_versions) {\n\t\tERROR(LOG_PREFIX \": You have disabled all available TLS versions. EAP will not work\");\n\t\treturn NULL;\n\t}\n\n#ifdef SSL_OP_NO_TICKET\n\tctx_options |= SSL_OP_NO_TICKET;\n#endif\n\n\t/*\n\t *\tSSL_OP_SINGLE_DH_USE must be used in order to prevent\n\t *\tsmall subgroup attacks and forward secrecy. Always\n\t *\tusing\n\t *\n\t *\tSSL_OP_SINGLE_DH_USE has an impact on the computer\n\t *\ttime needed during negotiation, but it is not very\n\t *\tlarge.\n\t */\n\tctx_options |= SSL_OP_SINGLE_DH_USE;\n\n\t/*\n\t *\tSSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues\n\t *\tin Windows Vista client.\n\t *\thttp://www.openssl.org/~bodo/tls-cbc.txt\n\t *\thttp://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html\n\t */\n\tctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;\n\n\tSSL_CTX_set_options(ctx, ctx_options);\n\n\t/*\n\t *\tTODO: Set the RSA & DH\n\t *\tSSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);\n\t *\tSSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);\n\t */\n\n\t/*\n\t *\tset the message callback to identify the type of\n\t *\tmessage. For every new session, there can be a\n\t *\tdifferent callback argument.\n\t *\n\t *\tSSL_CTX_set_msg_callback(ctx, cbtls_msg);\n\t */\n\n\t/*\n\t *\tSet eliptical curve crypto configuration.\n\t */\n#if OPENSSL_VERSION_NUMBER >= 0x0090800fL\n#ifndef OPENSSL_NO_ECDH\n\tif (set_ecdh_curve(ctx, conf->ecdh_curve) < 0) {\n\t\treturn NULL;\n\t}\n#endif\n#endif\n\n\t/* Set Info callback */\n\tSSL_CTX_set_info_callback(ctx, cbtls_info);\n\n\t/*\n\t *\tCallbacks, etc. for session resumption.\n\t */\n\tif (conf->session_cache_enable) {\n\t\t/*\n\t\t *\tCache sessions on disk if requested.\n\t\t */\n\t\tif (conf->session_cache_path) {\n\t\t\tSSL_CTX_sess_set_new_cb(ctx, cbtls_new_session);\n\t\t\tSSL_CTX_sess_set_get_cb(ctx, cbtls_get_session);\n\t\t\tSSL_CTX_sess_set_remove_cb(ctx, cbtls_remove_session);\n\t\t}\n\n\t\tSSL_CTX_set_quiet_shutdown(ctx, 1);\n\t\tif (fr_tls_ex_index_vps < 0)\n\t\t\tfr_tls_ex_index_vps = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_vps);\n\t}\n\n\t/*\n\t *\tCheck the certificates for revocation.\n\t */\n#ifdef X509_V_FLAG_CRL_CHECK\n\tif (conf->check_crl) {\n\t\tcertstore = SSL_CTX_get_cert_store(ctx);\n\t\tif (certstore == NULL) {\n\t\t\tERROR(LOG_PREFIX \": SSL error %s\", ERR_error_string(ERR_get_error(), NULL));\n\t\t\tERROR(LOG_PREFIX \": Error reading Certificate Store\");\n\t \t\treturn NULL;\n\t\t}\n\t\tX509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);\n\t}\n#endif\n\n\t/*\n\t *\tSet verify modes\n\t *\tAlways verify the peer certificate\n\t */\n\tverify_mode |= SSL_VERIFY_PEER;\n\tverify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;\n\tverify_mode |= SSL_VERIFY_CLIENT_ONCE;\n\tSSL_CTX_set_verify(ctx, verify_mode, cbtls_verify);\n\n\tif (conf->verify_depth) {\n\t\tSSL_CTX_set_verify_depth(ctx, conf->verify_depth);\n\t}\n\n\t/* Load randomness */\n\tif (conf->random_file) {\n\t\tif (!(RAND_load_file(conf->random_file, 1024*10))) {\n\t\t\tERROR(LOG_PREFIX \": SSL error %s\", ERR_error_string(ERR_get_error(), NULL));\n\t\t\tERROR(LOG_PREFIX \": Error loading randomness\");\n\t\t\treturn NULL;\n\t\t}\n\t}\n\n\t/*\n\t * Set the cipher list if we were told to\n\t */\n\tif (conf->cipher_list) {\n\t\tif (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) {\n\t\t\tERROR(LOG_PREFIX \": Error setting cipher list\");\n\t\t\treturn NULL;\n\t\t}\n\t}\n\n\t/*\n\t *\tSetup session caching\n\t */\n\tif (conf->session_cache_enable) {\n\t\t/*\n\t\t *\tCreate a unique context Id per EAP-TLS configuration.\n\t\t */\n\t\tif (conf->session_id_name) {\n\t\t\tsnprintf(conf->session_context_id, sizeof(conf->session_context_id),\n\t\t\t\t \"FR eap %s\", conf->session_id_name);\n\t\t} else {\n\t\t\tsnprintf(conf->session_context_id, sizeof(conf->session_context_id),\n\t\t\t\t \"FR eap %p\", conf);\n\t\t}\n\n\t\t/*\n\t\t *\tCache it, and DON'T auto-clear it.\n\t\t */\n\t\tSSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_AUTO_CLEAR);\n\n\t\tSSL_CTX_set_session_id_context(ctx,\n\t\t\t\t\t (unsigned char *) conf->session_context_id,\n\t\t\t\t\t (unsigned int) strlen(conf->session_context_id));\n\n\t\t/*\n\t\t *\tOur timeout is in hours, this is in seconds.\n\t\t */\n\t\tSSL_CTX_set_timeout(ctx, conf->session_timeout * 3600);\n\n\t\t/*\n\t\t *\tSet the maximum number of entries in the\n\t\t *\tsession cache.\n\t\t */\n\t\tSSL_CTX_sess_set_cache_size(ctx, conf->session_cache_size);\n\n\t} else {\n\t\tSSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);\n\t}\n\n\treturn ctx;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-295'], 'message': 'Set X509_V_FLAG_CRL_CHECK_ALL'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int attach_child_main(void* data)\n{\n\tstruct attach_clone_payload* payload = (struct attach_clone_payload*)data;\n\tint ipc_socket = payload->ipc_socket;\n\tlxc_attach_options_t* options = payload->options;\n\tstruct lxc_proc_context_info* init_ctx = payload->init_ctx;\n#if HAVE_SYS_PERSONALITY_H\n\tlong new_personality;\n#endif\n\tint ret;\n\tint status;\n\tint expected;\n\tlong flags;\n\tint fd;\n\tuid_t new_uid;\n\tgid_t new_gid;\n\n\t/* wait for the initial thread to signal us that it's ready\n\t * for us to start initializing\n\t */\n\texpected = 0;\n\tstatus = -1;\n\tret = lxc_read_nointr_expect(ipc_socket, &status, sizeof(status), &expected);\n\tif (ret <= 0) {\n\t\tERROR(\"error using IPC to receive notification from initial process (0)\");\n\t\tshutdown(ipc_socket, SHUT_RDWR);\n\t\trexit(-1);\n\t}\n\n\t/* A description of the purpose of this functionality is\n\t * provided in the lxc-attach(1) manual page. We have to\n\t * remount here and not in the parent process, otherwise\n\t * /proc may not properly reflect the new pid namespace.\n\t */\n\tif (!(options->namespaces & CLONE_NEWNS) && (options->attach_flags & LXC_ATTACH_REMOUNT_PROC_SYS)) {\n\t\tret = lxc_attach_remount_sys_proc();\n\t\tif (ret < 0) {\n\t\t\tshutdown(ipc_socket, SHUT_RDWR);\n\t\t\trexit(-1);\n\t\t}\n\t}\n\n\t/* now perform additional attachments*/\n#if HAVE_SYS_PERSONALITY_H\n\tif (options->personality < 0)\n\t\tnew_personality = init_ctx->personality;\n\telse\n\t\tnew_personality = options->personality;\n\n\tif (options->attach_flags & LXC_ATTACH_SET_PERSONALITY) {\n\t\tret = personality(new_personality);\n\t\tif (ret < 0) {\n\t\t\tSYSERROR(\"could not ensure correct architecture\");\n\t\t\tshutdown(ipc_socket, SHUT_RDWR);\n\t\t\trexit(-1);\n\t\t}\n\t}\n#endif\n\n\tif (options->attach_flags & LXC_ATTACH_DROP_CAPABILITIES) {\n\t\tret = lxc_attach_drop_privs(init_ctx);\n\t\tif (ret < 0) {\n\t\t\tERROR(\"could not drop privileges\");\n\t\t\tshutdown(ipc_socket, SHUT_RDWR);\n\t\t\trexit(-1);\n\t\t}\n\t}\n\n\t/* always set the environment (specify (LXC_ATTACH_KEEP_ENV, NULL, NULL) if you want this to be a no-op) */\n\tret = lxc_attach_set_environment(options->env_policy, options->extra_env_vars, options->extra_keep_env);\n\tif (ret < 0) {\n\t\tERROR(\"could not set initial environment for attached process\");\n\t\tshutdown(ipc_socket, SHUT_RDWR);\n\t\trexit(-1);\n\t}\n\n\t/* set user / group id */\n\tnew_uid = 0;\n\tnew_gid = 0;\n\t/* ignore errors, we will fall back to root in that case\n\t * (/proc was not mounted etc.)\n\t */\n\tif (options->namespaces & CLONE_NEWUSER)\n\t\tlxc_attach_get_init_uidgid(&new_uid, &new_gid);\n\n\tif (options->uid != (uid_t)-1)\n\t\tnew_uid = options->uid;\n\tif (options->gid != (gid_t)-1)\n\t\tnew_gid = options->gid;\n\n\t/* try to set the uid/gid combination */\n\tif ((new_gid != 0 || options->namespaces & CLONE_NEWUSER)) {\n\t\tif (setgid(new_gid) || setgroups(0, NULL)) {\n\t\t\tSYSERROR(\"switching to container gid\");\n\t\t\tshutdown(ipc_socket, SHUT_RDWR);\n\t\t\trexit(-1);\n\t\t}\n\t}\n\tif ((new_uid != 0 || options->namespaces & CLONE_NEWUSER) && setuid(new_uid)) {\n\t\tSYSERROR(\"switching to container uid\");\n\t\tshutdown(ipc_socket, SHUT_RDWR);\n\t\trexit(-1);\n\t}\n\n\t/* tell initial process it may now put us into the cgroups */\n\tstatus = 1;\n\tret = lxc_write_nointr(ipc_socket, &status, sizeof(status));\n\tif (ret != sizeof(status)) {\n\t\tERROR(\"error using IPC to notify initial process for initialization (1)\");\n\t\tshutdown(ipc_socket, SHUT_RDWR);\n\t\trexit(-1);\n\t}\n\n\t/* wait for the initial thread to signal us that it has done\n\t * everything for us when it comes to cgroups etc.\n\t */\n\texpected = 2;\n\tstatus = -1;\n\tret = lxc_read_nointr_expect(ipc_socket, &status, sizeof(status), &expected);\n\tif (ret <= 0) {\n\t\tERROR(\"error using IPC to receive final notification from initial process (2)\");\n\t\tshutdown(ipc_socket, SHUT_RDWR);\n\t\trexit(-1);\n\t}\n\n\tshutdown(ipc_socket, SHUT_RDWR);\n\tclose(ipc_socket);\n\n\t/* set new apparmor profile/selinux context */\n\tif ((options->namespaces & CLONE_NEWNS) && (options->attach_flags & LXC_ATTACH_LSM)) {\n\t\tint on_exec;\n\n\t\ton_exec = options->attach_flags & LXC_ATTACH_LSM_EXEC ? 1 : 0;\n\t\tret = lsm_process_label_set(init_ctx->lsm_label, 0, on_exec);\n\t\tif (ret < 0) {\n\t\t\trexit(-1);\n\t\t}\n\t}\n\n\tif (init_ctx->container && init_ctx->container->lxc_conf &&\n\t\t\tlxc_seccomp_load(init_ctx->container->lxc_conf) != 0) {\n\t\tERROR(\"Loading seccomp policy\");\n\t\trexit(-1);\n\t}\n\n\tlxc_proc_put_context_info(init_ctx);\n\n\t/* The following is done after the communication socket is\n\t * shut down. That way, all errors that might (though\n\t * unlikely) occur up until this point will have their messages\n\t * printed to the original stderr (if logging is so configured)\n\t * and not the fd the user supplied, if any.\n\t */\n\n\t/* fd handling for stdin, stdout and stderr;\n\t * ignore errors here, user may want to make sure\n\t * the fds are closed, for example */\n\tif (options->stdin_fd >= 0 && options->stdin_fd != 0)\n\t\tdup2(options->stdin_fd, 0);\n\tif (options->stdout_fd >= 0 && options->stdout_fd != 1)\n\t\tdup2(options->stdout_fd, 1);\n\tif (options->stderr_fd >= 0 && options->stderr_fd != 2)\n\t\tdup2(options->stderr_fd, 2);\n\n\t/* close the old fds */\n\tif (options->stdin_fd > 2)\n\t\tclose(options->stdin_fd);\n\tif (options->stdout_fd > 2)\n\t\tclose(options->stdout_fd);\n\tif (options->stderr_fd > 2)\n\t\tclose(options->stderr_fd);\n\n\t/* try to remove CLOEXEC flag from stdin/stdout/stderr,\n\t * but also here, ignore errors */\n\tfor (fd = 0; fd <= 2; fd++) {\n\t\tflags = fcntl(fd, F_GETFL);\n\t\tif (flags < 0)\n\t\t\tcontinue;\n\t\tif (flags & FD_CLOEXEC) {\n\t\t\tif (fcntl(fd, F_SETFL, flags & ~FD_CLOEXEC) < 0) {\n\t\t\t\tSYSERROR(\"Unable to clear CLOEXEC from fd\");\n\t\t\t}\n\t\t}\n\t}\n\n\t/* we're done, so we can now do whatever the user intended us to do */\n\trexit(payload->exec_function(payload->exec_payload));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-17'], 'message': 'CVE-2015-1334: Don't use the container's /proc during attach\n\nA user could otherwise over-mount /proc and prevent the apparmor profile\nor selinux label from being written which combined with a modified\n/bin/sh or other commonly used binary would lead to unconfined code\nexecution.\n\nReported-by: Roman Fiedler\nSigned-off-by: St\u00e9phane Graber '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static struct file *path_openat(int dfd, struct filename *pathname,\n\t\tstruct nameidata *nd, const struct open_flags *op, int flags)\n{\n\tstruct file *file;\n\tstruct path path;\n\tint opened = 0;\n\tint error;\n\n\tfile = get_empty_filp();\n\tif (IS_ERR(file))\n\t\treturn file;\n\n\tfile->f_flags = op->open_flag;\n\n\tif (unlikely(file->f_flags & __O_TMPFILE)) {\n\t\terror = do_tmpfile(dfd, pathname, nd, flags, op, file, &opened);\n\t\tgoto out;\n\t}\n\n\terror = path_init(dfd, pathname, flags, nd);\n\tif (unlikely(error))\n\t\tgoto out;\n\n\terror = do_last(nd, &path, file, op, &opened, pathname);\n\twhile (unlikely(error > 0)) { /* trailing symlink */\n\t\tstruct path link = path;\n\t\tvoid *cookie;\n\t\tif (!(nd->flags & LOOKUP_FOLLOW)) {\n\t\t\tpath_put_conditional(&path, nd);\n\t\t\tpath_put(&nd->path);\n\t\t\terror = -ELOOP;\n\t\t\tbreak;\n\t\t}\n\t\terror = may_follow_link(&link, nd);\n\t\tif (unlikely(error))\n\t\t\tbreak;\n\t\tnd->flags |= LOOKUP_PARENT;\n\t\tnd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL);\n\t\terror = follow_link(&link, nd, &cookie);\n\t\tif (unlikely(error))\n\t\t\tbreak;\n\t\terror = do_last(nd, &path, file, op, &opened, pathname);\n\t\tput_link(nd, &link, cookie);\n\t}\nout:\n\tpath_cleanup(nd);\n\tif (!(opened & FILE_OPENED)) {\n\t\tBUG_ON(!error);\n\t\tput_filp(file);\n\t}\n\tif (unlikely(error)) {\n\t\tif (error == -EOPENSTALE) {\n\t\t\tif (flags & LOOKUP_RCU)\n\t\t\t\terror = -ECHILD;\n\t\t\telse\n\t\t\t\terror = -ESTALE;\n\t\t}\n\t\tfile = ERR_PTR(error);\n\t}\n\treturn file;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'path_openat(): fix double fput()\n\npath_openat() jumps to the wrong place after do_tmpfile() - it has\nalready done path_cleanup() (as part of path_lookupat() called by\ndo_tmpfile()), so doing that again can lead to double fput().\n\nCc: stable@vger.kernel.org\t# v3.11+\nSigned-off-by: Al Viro '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: Panic(const char *fmtstr, ...)\n{\n /* Ignored */\n sLog(log_warning, \"Panic callback invoked. \\n\");\n exit(1);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'randomly generate tmp directory name'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int jas_stream_read(jas_stream_t *stream, void *buf, int cnt)\n{\n\tint n;\n\tint c;\n\tchar *bufptr;\n\n\tbufptr = buf;\n\n\tn = 0;\n\twhile (n < cnt) {\n\t\tif ((c = jas_stream_getc(stream)) == EOF) {\n\t\t\treturn n;\n\t\t}\n\t\t*bufptr++ = c;\n\t\t++n;\n\t}\n\n\treturn n;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415', 'CWE-190', 'CWE-369'], 'message': 'Made some changes to the I/O stream library for memory streams.\nThere were a number of potential problems due to the possibility\nof integer overflow.\nChanged some integral types to the larger types size_t or ssize_t.\nFor example, the function mem_resize now takes the buffer size parameter\nas a size_t.\nAdded a new function jas_stream_memopen2, which takes a\nbuffer size specified as a size_t instead of an int.\nThis can be used in jas_image_cmpt_create to avoid potential\noverflow problems.\n\nAdded a new function jas_deprecated to warn about reliance on\ndeprecated library behavior.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void vnc_colordepth(VncState *vs)\n{\n if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {\n /* Sending a WMVi message to notify the client*/\n vnc_lock_output(vs);\n vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);\n vnc_write_u8(vs, 0);\n vnc_write_u16(vs, 1); /* number of rects */\n vnc_framebuffer_update(vs, 0, 0,\n surface_width(vs->vd->ds),\n surface_height(vs->vd->ds),\n VNC_ENCODING_WMVi);\n pixel_format_message(vs);\n vnc_unlock_output(vs);\n vnc_flush(vs);\n } else {\n set_pixel_conversion(vs);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'ui/vnc: fix potential memory corruption issues\n\nthis patch makes the VNC server work correctly if the\nserver surface and the guest surface have different sizes.\n\nBasically the server surface is adjusted to not exceed VNC_MAX_WIDTH\nx VNC_MAX_HEIGHT and additionally the width is rounded up to multiple of\nVNC_DIRTY_PIXELS_PER_BIT.\n\nIf we have a resolution whose width is not dividable by VNC_DIRTY_PIXELS_PER_BIT\nwe now get a small black bar on the right of the screen.\n\nIf the surface is too big to fit the limits only the upper left area is shown.\n\nOn top of that this fixes 2 memory corruption issues:\n\nThe first was actually discovered during playing\naround with a Windows 7 vServer. During resolution\nchange in Windows 7 it happens sometimes that Windows\nchanges to an intermediate resolution where\nserver_stride % cmp_bytes != 0 (in vnc_refresh_server_surface).\nThis happens only if width % VNC_DIRTY_PIXELS_PER_BIT != 0.\n\nThe second is a theoretical issue, but is maybe exploitable\nby the guest. If for some reason the guest surface size is bigger\nthan VNC_MAX_WIDTH x VNC_MAX_HEIGHT we end up in severe corruption since\nthis limit is nowhere enforced.\n\nSigned-off-by: Peter Lieven \nSigned-off-by: Gerd Hoffmann '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: SPL_METHOD(SplObjectStorage, next)\n{\n\tspl_SplObjectStorage *intern = (spl_SplObjectStorage*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\t\n\tif (zend_parse_parameters_none() == FAILURE) {\n\t\treturn;\n\t}\n\t\n\tzend_hash_move_forward_ex(&intern->storage, &intern->pos);\n\tintern->index++;\n} /* }}} */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Fix bug #70168 - Use After Free Vulnerability in unserialize() with SplObjectStorage'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: SPL_METHOD(SplObjectStorage, current)\n{\n\tspl_SplObjectStorageElement *element;\n\tspl_SplObjectStorage *intern = (spl_SplObjectStorage*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\t\n\tif (zend_parse_parameters_none() == FAILURE) {\n\t\treturn;\n\t}\n\t\n\tif (zend_hash_get_current_data_ex(&intern->storage, (void**)&element, &intern->pos) == FAILURE) {\n\t\treturn;\n\t}\n\tRETVAL_ZVAL(element->obj, 1, 0);\n} /* }}} */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Fix bug #70168 - Use After Free Vulnerability in unserialize() with SplObjectStorage'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: SPL_METHOD(SplDoublyLinkedList, push)\n{\n\tzval *value;\n\tspl_dllist_object *intern;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"z\", &value) == FAILURE) {\n\t\treturn;\n\t}\n\n\tSEPARATE_ARG_IF_REF(value);\n\n\tintern = (spl_dllist_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\tspl_ptr_llist_push(intern->llist, value TSRMLS_CC);\n\n\tRETURN_TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Fixed bug #70169 (Use After Free Vulnerability in unserialize() with SplDoublyLinkedList)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static FILE * pw_tmpfile(int lockfd)\n{\n\tFILE *fd;\n\tchar *tmpname = NULL;\n\tchar *dir = \"/etc\";\n\n\tif ((fd = xfmkstemp(&tmpname, dir)) == NULL) {\n\t\tulckpwdf();\n\t\terr(EXIT_FAILURE, _(\"can't open temporary file\"));\n\t}\n\n\tcopyfile(lockfd, fileno(fd));\n\ttmp_file = tmpname;\n\treturn fd;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'chsh, chfn, vipw: fix filenames collision\n\nThe utils when compiled WITHOUT libuser then mkostemp()ing\n\"/etc/%s.XXXXXX\" where the filename prefix is argv[0] basename.\n\nAn attacker could repeatedly execute the util with modified argv[0]\nand after many many attempts mkostemp() may generate suffix which\nmakes sense. The result maybe temporary file with name like rc.status\nld.so.preload or krb5.keytab, etc.\n\nNote that distros usually use libuser based ch{sh,fn} or stuff from\nshadow-utils.\n\nIt's probably very minor security bug.\n\nAddresses: CVE-2015-5224\nSigned-off-by: Karel Zak '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static ZIPARCHIVE_METHOD(getStatusString)\n{\n\tstruct zip *intern;\n\tzval *this = getThis();\n\tint zep, syp, len;\n\tchar error_string[128];\n\n\tif (!this) {\n\t\tRETURN_FALSE;\n\t}\n\n\tZIP_FROM_OBJECT(intern, this);\n\n\tzip_error_get(intern, &zep, &syp);\n\n\tlen = zip_error_to_str(error_string, 128, zep, syp);\n\tRETVAL_STRINGL(error_string, len, 1); \n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-22'], 'message': 'Fixed bug #70350: ZipArchive::extractTo allows for directory traversal when creating directories'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: make_weights (PixopsFilter *filter,\n\t PixopsInterpType interp_type,\t \n\t double scale_x,\n\t double scale_y)\n{\n switch (interp_type)\n {\n case PIXOPS_INTERP_NEAREST:\n g_assert_not_reached ();\n break;\n\n case PIXOPS_INTERP_TILES:\n tile_make_weights (&filter->x, scale_x);\n tile_make_weights (&filter->y, scale_y);\n break;\n \n case PIXOPS_INTERP_BILINEAR:\n bilinear_magnify_make_weights (&filter->x, scale_x);\n bilinear_magnify_make_weights (&filter->y, scale_y);\n break;\n \n case PIXOPS_INTERP_HYPER:\n bilinear_box_make_weights (&filter->x, scale_x);\n bilinear_box_make_weights (&filter->y, scale_y);\n break;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'pixops: Fail make_weights functions on OOM\n\nThe weights could grow very large under certain circumstances, in\nparticular in security-relevant conditions, including the testsuite.\nBy allowing the weight allocation to fail, this can be worked around.\n\nhttps://bugzilla.gnome.org/show_bug.cgi?id=754387'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static gboolean fill_in_context(TGAContext *ctx, GError **err)\n{\n\tgboolean alpha;\n\tguint w, h;\n\n\tg_return_val_if_fail(ctx != NULL, FALSE);\n\n\tctx->run_length_encoded =\n\t\t((ctx->hdr->type == TGA_TYPE_RLE_PSEUDOCOLOR)\n\t\t || (ctx->hdr->type == TGA_TYPE_RLE_TRUECOLOR)\n\t\t || (ctx->hdr->type == TGA_TYPE_RLE_GRAYSCALE));\n\n\tif (ctx->hdr->has_cmap)\n\t\tctx->cmap_size = ((ctx->hdr->cmap_bpp + 7) >> 3) *\n\t\t\tLE16(ctx->hdr->cmap_n_colors);\n\n\talpha = ((ctx->hdr->bpp == 16) || \n\t\t (ctx->hdr->bpp == 32) ||\n\t\t (ctx->hdr->has_cmap && (ctx->hdr->cmap_bpp == 32)));\n\n\tw = LE16(ctx->hdr->width);\n\th = LE16(ctx->hdr->height);\n\n\tif (ctx->sfunc) {\n\t\tgint wi = w;\n\t\tgint hi = h;\n\t\t\n\t\t(*ctx->sfunc) (&wi, &hi, ctx->udata);\n\t\t\n\t\tif (wi == 0 || hi == 0) \n\t\t\treturn FALSE;\n\t}\n\n\tctx->pbuf = get_contiguous_pixbuf (w, h, alpha);\n\n\tif (!ctx->pbuf) {\n\t\tg_set_error_literal(err, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,\n _(\"Cannot allocate new pixbuf\"));\n\t\treturn FALSE;\n\t}\n\n\tctx->pbuf_bytes = ctx->pbuf->rowstride * ctx->pbuf->height;\n\tif ((ctx->hdr->flags & TGA_ORIGIN_UPPER) || ctx->run_length_encoded)\n\t\tctx->pptr = ctx->pbuf->pixels;\n\telse\n\t\tctx->pptr = ctx->pbuf->pixels + (ctx->pbuf->height - 1)*ctx->pbuf->rowstride;\n\n\tif (ctx->hdr->type == TGA_TYPE_PSEUDOCOLOR)\n\t ctx->rowstride = ctx->pbuf->width;\n\telse if (ctx->hdr->type == TGA_TYPE_GRAYSCALE)\n\t ctx->rowstride = (alpha ? ctx->pbuf->width * 2 : ctx->pbuf->width);\n\telse if (ctx->hdr->type == TGA_TYPE_TRUECOLOR)\n\t\tctx->rowstride = ctx->pbuf->rowstride;\n\n\tctx->completed_lines = 0;\n\treturn TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'io-tga: Colormaps are always present, so always parse them.\n\nWe might end up with a colormap with 0 entries, but whatever, it's a\ncolormap.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ext4_ext_handle_uninitialized_extents(handle_t *handle, struct inode *inode,\n\t\t\text4_lblk_t iblock, unsigned int max_blocks,\n\t\t\tstruct ext4_ext_path *path, int flags,\n\t\t\tunsigned int allocated, struct buffer_head *bh_result,\n\t\t\text4_fsblk_t newblock)\n{\n\tint ret = 0;\n\tint err = 0;\n\text4_io_end_t *io = EXT4_I(inode)->cur_aio_dio;\n\n\text_debug(\"ext4_ext_handle_uninitialized_extents: inode %lu, logical\"\n\t\t \"block %llu, max_blocks %u, flags %d, allocated %u\",\n\t\t inode->i_ino, (unsigned long long)iblock, max_blocks,\n\t\t flags, allocated);\n\text4_ext_show_leaf(inode, path);\n\n\t/* get_block() before submit the IO, split the extent */\n\tif (flags == EXT4_GET_BLOCKS_PRE_IO) {\n\t\tret = ext4_split_unwritten_extents(handle,\n\t\t\t\t\t\tinode, path, iblock,\n\t\t\t\t\t\tmax_blocks, flags);\n\t\t/*\n\t\t * Flag the inode(non aio case) or end_io struct (aio case)\n\t\t * that this IO needs to convertion to written when IO is\n\t\t * completed\n\t\t */\n\t\tif (io)\n\t\t\tio->flag = EXT4_IO_UNWRITTEN;\n\t\telse\n\t\t\text4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);\n\t\tgoto out;\n\t}\n\t/* IO end_io complete, convert the filled extent to written */\n\tif (flags == EXT4_GET_BLOCKS_CONVERT) {\n\t\tret = ext4_convert_unwritten_extents_endio(handle, inode,\n\t\t\t\t\t\t\tpath);\n\t\tif (ret >= 0)\n\t\t\text4_update_inode_fsync_trans(handle, inode, 1);\n\t\tgoto out2;\n\t}\n\t/* buffered IO case */\n\t/*\n\t * repeat fallocate creation request\n\t * we already have an unwritten extent\n\t */\n\tif (flags & EXT4_GET_BLOCKS_UNINIT_EXT)\n\t\tgoto map_out;\n\n\t/* buffered READ or buffered write_begin() lookup */\n\tif ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {\n\t\t/*\n\t\t * We have blocks reserved already. We\n\t\t * return allocated blocks so that delalloc\n\t\t * won't do block reservation for us. But\n\t\t * the buffer head will be unmapped so that\n\t\t * a read from the block returns 0s.\n\t\t */\n\t\tset_buffer_unwritten(bh_result);\n\t\tgoto out1;\n\t}\n\n\t/* buffered write, writepage time, convert*/\n\tret = ext4_ext_convert_to_initialized(handle, inode,\n\t\t\t\t\t\tpath, iblock,\n\t\t\t\t\t\tmax_blocks);\n\tif (ret >= 0)\n\t\text4_update_inode_fsync_trans(handle, inode, 1);\nout:\n\tif (ret <= 0) {\n\t\terr = ret;\n\t\tgoto out2;\n\t} else\n\t\tallocated = ret;\n\tset_buffer_new(bh_result);\n\t/*\n\t * if we allocated more blocks than requested\n\t * we need to make sure we unmap the extra block\n\t * allocated. The actual needed block will get\n\t * unmapped later when we find the buffer_head marked\n\t * new.\n\t */\n\tif (allocated > max_blocks) {\n\t\tunmap_underlying_metadata_blocks(inode->i_sb->s_bdev,\n\t\t\t\t\tnewblock + max_blocks,\n\t\t\t\t\tallocated - max_blocks);\n\t\tallocated = max_blocks;\n\t}\n\n\t/*\n\t * If we have done fallocate with the offset that is already\n\t * delayed allocated, we would have block reservation\n\t * and quota reservation done in the delayed write path.\n\t * But fallocate would have already updated quota and block\n\t * count for this offset. So cancel these reservation\n\t */\n\tif (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)\n\t\text4_da_update_reserve_space(inode, allocated, 0);\n\nmap_out:\n\tset_buffer_mapped(bh_result);\nout1:\n\tif (allocated > max_blocks)\n\t\tallocated = max_blocks;\n\text4_ext_show_leaf(inode, path);\n\tbh_result->b_bdev = inode->i_sb->s_bdev;\n\tbh_result->b_blocknr = newblock;\nout2:\n\tif (path) {\n\t\text4_ext_drop_refs(path);\n\t\tkfree(path);\n\t}\n\treturn err ? err : allocated;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'ext4: use ext4_get_block_write in buffer write\n\nAllocate uninitialized extent before ext4 buffer write and\nconvert the extent to initialized after io completes.\nThe purpose is to make sure an extent can only be marked\ninitialized after it has been written with new data so\nwe can safely drop the i_mutex lock in ext4 DIO read without\nexposing stale data. This helps to improve multi-thread DIO\nread performance on high-speed disks.\n\nSkip the nobh and data=journal mount cases to make things simple for now.\n\nSigned-off-by: Jiaying Zhang \nSigned-off-by: \"Theodore Ts'o\" '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static ext4_io_end_t *ext4_init_io_end (struct inode *inode)\n{\n\text4_io_end_t *io = NULL;\n\n\tio = kmalloc(sizeof(*io), GFP_NOFS);\n\n\tif (io) {\n\t\tigrab(inode);\n\t\tio->inode = inode;\n\t\tio->flag = 0;\n\t\tio->offset = 0;\n\t\tio->size = 0;\n\t\tio->error = 0;\n\t\tINIT_WORK(&io->work, ext4_end_io_work);\n\t\tINIT_LIST_HEAD(&io->list);\n\t}\n\n\treturn io;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'ext4: use ext4_get_block_write in buffer write\n\nAllocate uninitialized extent before ext4 buffer write and\nconvert the extent to initialized after io completes.\nThe purpose is to make sure an extent can only be marked\ninitialized after it has been written with new data so\nwe can safely drop the i_mutex lock in ext4 DIO read without\nexposing stale data. This helps to improve multi-thread DIO\nread performance on high-speed disks.\n\nSkip the nobh and data=journal mount cases to make things simple for now.\n\nSigned-off-by: Jiaying Zhang \nSigned-off-by: \"Theodore Ts'o\" '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void lxc_execute_bind_init(struct lxc_conf *conf)\n{\n\tint ret;\n\tchar path[PATH_MAX], destpath[PATH_MAX], *p;\n\n\t/* If init exists in the container, don't bind mount a static one */\n\tp = choose_init(conf->rootfs.mount);\n\tif (p) {\n\t\tfree(p);\n\t\treturn;\n\t}\n\n\tret = snprintf(path, PATH_MAX, SBINDIR \"/init.lxc.static\");\n\tif (ret < 0 || ret >= PATH_MAX) {\n\t\tWARN(\"Path name too long searching for lxc.init.static\");\n\t\treturn;\n\t}\n\n\tif (!file_exists(path)) {\n\t\tINFO(\"%s does not exist on host\", path);\n\t\treturn;\n\t}\n\n\tret = snprintf(destpath, PATH_MAX, \"%s%s\", conf->rootfs.mount, \"/init.lxc.static\");\n\tif (ret < 0 || ret >= PATH_MAX) {\n\t\tWARN(\"Path name too long for container's lxc.init.static\");\n\t\treturn;\n\t}\n\n\tif (!file_exists(destpath)) {\n\t\tFILE * pathfile = fopen(destpath, \"wb\");\n\t\tif (!pathfile) {\n\t\t\tSYSERROR(\"Failed to create mount target '%s'\", destpath);\n\t\t\treturn;\n\t\t}\n\t\tfclose(pathfile);\n\t}\n\n\tret = mount(path, destpath, \"none\", MS_BIND, NULL);\n\tif (ret < 0)\n\t\tSYSERROR(\"Failed to bind lxc.init.static into container\");\n\tINFO(\"lxc.init.static bound into container at %s\", path);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'CVE-2015-1335: Protect container mounts against symlinks\n\nWhen a container starts up, lxc sets up the container's inital fstree\nby doing a bunch of mounting, guided by the container configuration\nfile. The container config is owned by the admin or user on the host,\nso we do not try to guard against bad entries. However, since the\nmount target is in the container, it's possible that the container admin\ncould divert the mount with symbolic links. This could bypass proper\ncontainer startup (i.e. confinement of a root-owned container by the\nrestrictive apparmor policy, by diverting the required write to\n/proc/self/attr/current), or bypass the (path-based) apparmor policy\nby diverting, say, /proc to /mnt in the container.\n\nTo prevent this,\n\n1. do not allow mounts to paths containing symbolic links\n\n2. do not allow bind mounts from relative paths containing symbolic\nlinks.\n\nDetails:\n\nDefine safe_mount which ensures that the container has not inserted any\nsymbolic links into any mount targets for mounts to be done during\ncontainer setup.\n\nThe host's mount path may contain symbolic links. As it is under the\ncontrol of the administrator, that's ok. So safe_mount begins the check\nfor symbolic links after the rootfs->mount, by opening that directory.\n\nIt opens each directory along the path using openat() relative to the\nparent directory using O_NOFOLLOW. When the target is reached, it\nmounts onto /proc/self/fd/.\n\nUse safe_mount() in mount_entry(), when mounting container proc,\nand when needed. In particular, safe_mount() need not be used in\nany case where:\n\n1. the mount is done in the container's namespace\n2. the mount is for the container's rootfs\n3. the mount is relative to a tmpfs or proc/sysfs which we have\n just safe_mount()ed ourselves\n\nSince we were using proc/net as a temporary placeholder for /proc/sys/net\nduring container startup, and proc/net is a symbolic link, use proc/tty\ninstead.\n\nUpdate the lxc.container.conf manpage with details about the new\nrestrictions.\n\nFinally, add a testcase to test some symbolic link possibilities.\n\nReported-by: Roman Fiedler\nSigned-off-by: Serge Hallyn \nAcked-by: St\u00e9phane Graber '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int usbvision_probe(struct usb_interface *intf,\n\t\t\t const struct usb_device_id *devid)\n{\n\tstruct usb_device *dev = usb_get_dev(interface_to_usbdev(intf));\n\tstruct usb_interface *uif;\n\t__u8 ifnum = intf->altsetting->desc.bInterfaceNumber;\n\tconst struct usb_host_interface *interface;\n\tstruct usb_usbvision *usbvision = NULL;\n\tconst struct usb_endpoint_descriptor *endpoint;\n\tint model, i, ret;\n\n\tPDEBUG(DBG_PROBE, \"VID=%#04x, PID=%#04x, ifnum=%u\",\n\t\t\t\tdev->descriptor.idVendor,\n\t\t\t\tdev->descriptor.idProduct, ifnum);\n\n\tmodel = devid->driver_info;\n\tif (model < 0 || model >= usbvision_device_data_size) {\n\t\tPDEBUG(DBG_PROBE, \"model out of bounds %d\", model);\n\t\tret = -ENODEV;\n\t\tgoto err_usb;\n\t}\n\tprintk(KERN_INFO \"%s: %s found\\n\", __func__,\n\t\t\t\tusbvision_device_data[model].model_string);\n\n\t/*\n\t * this is a security check.\n\t * an exploit using an incorrect bInterfaceNumber is known\n\t */\n\tif (ifnum >= USB_MAXINTERFACES || !dev->actconfig->interface[ifnum])\n\t\treturn -ENODEV;\n\n\tif (usbvision_device_data[model].interface >= 0)\n\t\tinterface = &dev->actconfig->interface[usbvision_device_data[model].interface]->altsetting[0];\n\telse\n\t\tinterface = &dev->actconfig->interface[ifnum]->altsetting[0];\n\tendpoint = &interface->endpoint[1].desc;\n\tif (!usb_endpoint_xfer_isoc(endpoint)) {\n\t\tdev_err(&intf->dev, \"%s: interface %d. has non-ISO endpoint!\\n\",\n\t\t __func__, ifnum);\n\t\tdev_err(&intf->dev, \"%s: Endpoint attributes %d\",\n\t\t __func__, endpoint->bmAttributes);\n\t\tret = -ENODEV;\n\t\tgoto err_usb;\n\t}\n\tif (usb_endpoint_dir_out(endpoint)) {\n\t\tdev_err(&intf->dev, \"%s: interface %d. has ISO OUT endpoint!\\n\",\n\t\t __func__, ifnum);\n\t\tret = -ENODEV;\n\t\tgoto err_usb;\n\t}\n\n\tusbvision = usbvision_alloc(dev, intf);\n\tif (usbvision == NULL) {\n\t\tdev_err(&intf->dev, \"%s: couldn't allocate USBVision struct\\n\", __func__);\n\t\tret = -ENOMEM;\n\t\tgoto err_usb;\n\t}\n\n\tif (dev->descriptor.bNumConfigurations > 1)\n\t\tusbvision->bridge_type = BRIDGE_NT1004;\n\telse if (model == DAZZLE_DVC_90_REV_1_SECAM)\n\t\tusbvision->bridge_type = BRIDGE_NT1005;\n\telse\n\t\tusbvision->bridge_type = BRIDGE_NT1003;\n\tPDEBUG(DBG_PROBE, \"bridge_type %d\", usbvision->bridge_type);\n\n\t/* compute alternate max packet sizes */\n\tuif = dev->actconfig->interface[0];\n\n\tusbvision->num_alt = uif->num_altsetting;\n\tPDEBUG(DBG_PROBE, \"Alternate settings: %i\", usbvision->num_alt);\n\tusbvision->alt_max_pkt_size = kmalloc(32 * usbvision->num_alt, GFP_KERNEL);\n\tif (usbvision->alt_max_pkt_size == NULL) {\n\t\tdev_err(&intf->dev, \"usbvision: out of memory!\\n\");\n\t\tret = -ENOMEM;\n\t\tgoto err_pkt;\n\t}\n\n\tfor (i = 0; i < usbvision->num_alt; i++) {\n\t\tu16 tmp = le16_to_cpu(uif->altsetting[i].endpoint[1].desc.\n\t\t\t\t wMaxPacketSize);\n\t\tusbvision->alt_max_pkt_size[i] =\n\t\t\t(tmp & 0x07ff) * (((tmp & 0x1800) >> 11) + 1);\n\t\tPDEBUG(DBG_PROBE, \"Alternate setting %i, max size= %i\", i,\n\t\t usbvision->alt_max_pkt_size[i]);\n\t}\n\n\n\tusbvision->nr = usbvision_nr++;\n\n\tspin_lock_init(&usbvision->queue_lock);\n\tinit_waitqueue_head(&usbvision->wait_frame);\n\tinit_waitqueue_head(&usbvision->wait_stream);\n\n\tusbvision->have_tuner = usbvision_device_data[model].tuner;\n\tif (usbvision->have_tuner)\n\t\tusbvision->tuner_type = usbvision_device_data[model].tuner_type;\n\n\tusbvision->dev_model = model;\n\tusbvision->remove_pending = 0;\n\tusbvision->iface = ifnum;\n\tusbvision->iface_alt = 0;\n\tusbvision->video_endp = endpoint->bEndpointAddress;\n\tusbvision->isoc_packet_size = 0;\n\tusbvision->usb_bandwidth = 0;\n\tusbvision->user = 0;\n\tusbvision->streaming = stream_off;\n\tusbvision_configure_video(usbvision);\n\tusbvision_register_video(usbvision);\n\n\tusbvision_create_sysfs(&usbvision->vdev);\n\n\tPDEBUG(DBG_PROBE, \"success\");\n\treturn 0;\n\nerr_pkt:\n\tusbvision_release(usbvision);\nerr_usb:\n\tusb_put_dev(dev);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-17'], 'message': '[media] usbvision: fix crash on detecting device with invalid configuration\n\nThe usbvision driver crashes when a specially crafted usb device with invalid\nnumber of interfaces or endpoints is detected. This fix adds checks that the\ndevice has proper configuration expected by the driver.\n\nReported-by: Ralf Spenneberg \nSigned-off-by: Vladis Dronov \nSigned-off-by: Mauro Carvalho Chehab '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: crypto_recv(\n\tstruct peer *peer,\t/* peer structure pointer */\n\tstruct recvbuf *rbufp\t/* packet buffer pointer */\n\t)\n{\n\tconst EVP_MD *dp;\t/* message digest algorithm */\n\tu_int32\t*pkt;\t\t/* receive packet pointer */\n\tstruct autokey *ap, *bp; /* autokey pointer */\n\tstruct exten *ep, *fp;\t/* extension pointers */\n\tstruct cert_info *xinfo; /* certificate info pointer */\n\tint\thas_mac;\t/* length of MAC field */\n\tint\tauthlen;\t/* offset of MAC field */\n\tassocid_t associd;\t/* association ID */\n\ttstamp_t fstamp = 0;\t/* filestamp */\n\tu_int\tlen;\t\t/* extension field length */\n\tu_int\tcode;\t\t/* extension field opcode */\n\tu_int\tvallen = 0;\t/* value length */\n\tX509\t*cert;\t\t/* X509 certificate */\n\tchar\tstatstr[NTP_MAXSTRLEN]; /* statistics for filegen */\n\tkeyid_t\tcookie;\t\t/* crumbles */\n\tint\thismode;\t/* packet mode */\n\tint\trval = XEVNT_OK;\n\tconst u_char *puch;\n\tu_int32 temp32;\n\n\t/*\n\t * Initialize. Note that the packet has already been checked for\n\t * valid format and extension field lengths. First extract the\n\t * field length, command code and association ID in host byte\n\t * order. These are used with all commands and modes. Then check\n\t * the version number, which must be 2, and length, which must\n\t * be at least 8 for requests and VALUE_LEN (24) for responses.\n\t * Packets that fail either test sink without a trace. The\n\t * association ID is saved only if nonzero.\n\t */\n\tauthlen = LEN_PKT_NOMAC;\n\thismode = (int)PKT_MODE((&rbufp->recv_pkt)->li_vn_mode);\n\twhile ((has_mac = rbufp->recv_length - authlen) > (int)MAX_MAC_LEN) {\n\t\tpkt = (u_int32 *)&rbufp->recv_pkt + authlen / 4;\n\t\tep = (struct exten *)pkt;\n\t\tcode = ntohl(ep->opcode) & 0xffff0000;\n\t\tlen = ntohl(ep->opcode) & 0x0000ffff;\n\t\t// HMS: Why pkt[1] instead of ep->associd ?\n\t\tassocid = (associd_t)ntohl(pkt[1]);\n\t\trval = XEVNT_OK;\n\t\tDPRINTF(1, (\"crypto_recv: flags 0x%x ext offset %d len %u code 0x%x associd %d\\n\",\n\t\t\t peer->crypto, authlen, len, code >> 16,\n\t\t\t associd));\n\n\t\t/*\n\t\t * Check version number and field length. If bad,\n\t\t * quietly ignore the packet.\n\t\t */\n\t\tif (((code >> 24) & 0x3f) != CRYPTO_VN || len < 8) {\n\t\t\tsys_badlength++;\n\t\t\tcode |= CRYPTO_ERROR;\n\t\t}\n\n\t\tif (len >= VALUE_LEN) {\n\t\t\tfstamp = ntohl(ep->fstamp);\n\t\t\tvallen = ntohl(ep->vallen);\n\t\t\t/*\n\t\t\t * Bug 2761: I hope this isn't too early...\n\t\t\t */\n\t\t\tif ( vallen == 0\n\t\t\t || len - VALUE_LEN < vallen)\n\t\t\t\treturn XEVNT_LEN;\n\t\t}\n\t\tswitch (code) {\n\n\t\t/*\n\t\t * Install status word, host name, signature scheme and\n\t\t * association ID. In OpenSSL the signature algorithm is\n\t\t * bound to the digest algorithm, so the NID completely\n\t\t * defines the signature scheme. Note the request and\n\t\t * response are identical, but neither is validated by\n\t\t * signature. The request is processed here only in\n\t\t * symmetric modes. The server name field might be\n\t\t * useful to implement access controls in future.\n\t\t */\n\t\tcase CRYPTO_ASSOC:\n\n\t\t\t/*\n\t\t\t * If our state machine is running when this\n\t\t\t * message arrives, the other fellow might have\n\t\t\t * restarted. However, this could be an\n\t\t\t * intruder, so just clamp the poll interval and\n\t\t\t * find out for ourselves. Otherwise, pass the\n\t\t\t * extension field to the transmit side.\n\t\t\t */\n\t\t\tif (peer->crypto & CRYPTO_FLAG_CERT) {\n\t\t\t\trval = XEVNT_ERR;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (peer->cmmd) {\n\t\t\t\tif (peer->assoc != associd) {\n\t\t\t\t\trval = XEVNT_ERR;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfp = emalloc(len);\n\t\t\tmemcpy(fp, ep, len);\n\t\t\tfp->associd = htonl(peer->associd);\n\t\t\tpeer->cmmd = fp;\n\t\t\t/* fall through */\n\n\t\tcase CRYPTO_ASSOC | CRYPTO_RESP:\n\n\t\t\t/*\n\t\t\t * Discard the message if it has already been\n\t\t\t * stored or the message has been amputated.\n\t\t\t */\n\t\t\tif (peer->crypto) {\n\t\t\t\tif (peer->assoc != associd)\n\t\t\t\t\trval = XEVNT_ERR;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tINSIST(len >= VALUE_LEN);\n\t\t\tif (vallen == 0 || vallen > MAXHOSTNAME ||\n\t\t\t len - VALUE_LEN < vallen) {\n\t\t\t\trval = XEVNT_LEN;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tDPRINTF(1, (\"crypto_recv: ident host 0x%x %d server 0x%x %d\\n\",\n\t\t\t\t crypto_flags, peer->associd, fstamp,\n\t\t\t\t peer->assoc));\n\t\t\ttemp32 = crypto_flags & CRYPTO_FLAG_MASK;\n\n\t\t\t/*\n\t\t\t * If the client scheme is PC, the server scheme\n\t\t\t * must be PC. The public key and identity are\n\t\t\t * presumed valid, so we skip the certificate\n\t\t\t * and identity exchanges and move immediately\n\t\t\t * to the cookie exchange which confirms the\n\t\t\t * server signature.\n\t\t\t */\n\t\t\tif (crypto_flags & CRYPTO_FLAG_PRIV) {\n\t\t\t\tif (!(fstamp & CRYPTO_FLAG_PRIV)) {\n\t\t\t\t\trval = XEVNT_KEY;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tfstamp |= CRYPTO_FLAG_CERT |\n\t\t\t\t CRYPTO_FLAG_VRFY | CRYPTO_FLAG_SIGN;\n\n\t\t\t/*\n\t\t\t * It is an error if either peer supports\n\t\t\t * identity, but the other does not.\n\t\t\t */\n\t\t\t} else if (hismode == MODE_ACTIVE || hismode ==\n\t\t\t MODE_PASSIVE) {\n\t\t\t\tif ((temp32 && !(fstamp &\n\t\t\t\t CRYPTO_FLAG_MASK)) ||\n\t\t\t\t (!temp32 && (fstamp &\n\t\t\t\t CRYPTO_FLAG_MASK))) {\n\t\t\t\t\trval = XEVNT_KEY;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Discard the message if the signature digest\n\t\t\t * NID is not supported.\n\t\t\t */\n\t\t\ttemp32 = (fstamp >> 16) & 0xffff;\n\t\t\tdp =\n\t\t\t (const EVP_MD *)EVP_get_digestbynid(temp32);\n\t\t\tif (dp == NULL) {\n\t\t\t\trval = XEVNT_MD;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Save status word, host name and message\n\t\t\t * digest/signature type. If this is from a\n\t\t\t * broadcast and the association ID has changed,\n\t\t\t * request the autokey values.\n\t\t\t */\n\t\t\tpeer->assoc = associd;\n\t\t\tif (hismode == MODE_SERVER)\n\t\t\t\tfstamp |= CRYPTO_FLAG_AUTO;\n\t\t\tif (!(fstamp & CRYPTO_FLAG_TAI))\n\t\t\t\tfstamp |= CRYPTO_FLAG_LEAP;\n\t\t\tRAND_bytes((u_char *)&peer->hcookie, 4);\n\t\t\tpeer->crypto = fstamp;\n\t\t\tpeer->digest = dp;\n\t\t\tif (peer->subject != NULL)\n\t\t\t\tfree(peer->subject);\n\t\t\tpeer->subject = emalloc(vallen + 1);\n\t\t\tmemcpy(peer->subject, ep->pkt, vallen);\n\t\t\tpeer->subject[vallen] = '\\0';\n\t\t\tif (peer->issuer != NULL)\n\t\t\t\tfree(peer->issuer);\n\t\t\tpeer->issuer = estrdup(peer->subject);\n\t\t\tsnprintf(statstr, sizeof(statstr),\n\t\t\t \"assoc %d %d host %s %s\", peer->associd,\n\t\t\t peer->assoc, peer->subject,\n\t\t\t OBJ_nid2ln(temp32));\n\t\t\trecord_crypto_stats(&peer->srcadr, statstr);\n\t\t\tDPRINTF(1, (\"crypto_recv: %s\\n\", statstr));\n\t\t\tbreak;\n\n\t\t/*\n\t\t * Decode X509 certificate in ASN.1 format and extract\n\t\t * the data containing, among other things, subject\n\t\t * name and public key. In the default identification\n\t\t * scheme, the certificate trail is followed to a self\n\t\t * signed trusted certificate.\n\t\t */\n\t\tcase CRYPTO_CERT | CRYPTO_RESP:\n\n\t\t\t/*\n\t\t\t * Discard the message if empty or invalid.\n\t\t\t */\n\t\t\tif (len < VALUE_LEN)\n\t\t\t\tbreak;\n\n\t\t\tif ((rval = crypto_verify(ep, NULL, peer)) !=\n\t\t\t XEVNT_OK)\n\t\t\t\tbreak;\n\n\t\t\t/*\n\t\t\t * Scan the certificate list to delete old\n\t\t\t * versions and link the newest version first on\n\t\t\t * the list. Then, verify the signature. If the\n\t\t\t * certificate is bad or missing, just ignore\n\t\t\t * it.\n\t\t\t */\n\t\t\tif ((xinfo = cert_install(ep, peer)) == NULL) {\n\t\t\t\trval = XEVNT_CRT;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif ((rval = cert_hike(peer, xinfo)) != XEVNT_OK)\n\t\t\t\tbreak;\n\n\t\t\t/*\n\t\t\t * We plug in the public key and lifetime from\n\t\t\t * the first certificate received. However, note\n\t\t\t * that this certificate might not be signed by\n\t\t\t * the server, so we can't check the\n\t\t\t * signature/digest NID.\n\t\t\t */\n\t\t\tif (peer->pkey == NULL) {\n\t\t\t\tpuch = xinfo->cert.ptr;\n\t\t\t\tcert = d2i_X509(NULL, &puch,\n\t\t\t\t ntohl(xinfo->cert.vallen));\n\t\t\t\tpeer->pkey = X509_get_pubkey(cert);\n\t\t\t\tX509_free(cert);\n\t\t\t}\n\t\t\tpeer->flash &= ~TEST8;\n\t\t\ttemp32 = xinfo->nid;\n\t\t\tsnprintf(statstr, sizeof(statstr),\n\t\t\t \"cert %s %s 0x%x %s (%u) fs %u\",\n\t\t\t xinfo->subject, xinfo->issuer, xinfo->flags,\n\t\t\t OBJ_nid2ln(temp32), temp32,\n\t\t\t ntohl(ep->fstamp));\n\t\t\trecord_crypto_stats(&peer->srcadr, statstr);\n\t\t\tDPRINTF(1, (\"crypto_recv: %s\\n\", statstr));\n\t\t\tbreak;\n\n\t\t/*\n\t\t * Schnorr (IFF) identity scheme. This scheme is\n\t\t * designed for use with shared secret server group keys\n\t\t * and where the certificate may be generated by a third\n\t\t * party. The client sends a challenge to the server,\n\t\t * which performs a calculation and returns the result.\n\t\t * A positive result is possible only if both client and\n\t\t * server contain the same secret group key.\n\t\t */\n\t\tcase CRYPTO_IFF | CRYPTO_RESP:\n\n\t\t\t/*\n\t\t\t * Discard the message if invalid.\n\t\t\t */\n\t\t\tif ((rval = crypto_verify(ep, NULL, peer)) !=\n\t\t\t XEVNT_OK)\n\t\t\t\tbreak;\n\n\t\t\t/*\n\t\t\t * If the challenge matches the response, the\n\t\t\t * server public key, signature and identity are\n\t\t\t * all verified at the same time. The server is\n\t\t\t * declared trusted, so we skip further\n\t\t\t * certificate exchanges and move immediately to\n\t\t\t * the cookie exchange.\n\t\t\t */\n\t\t\tif ((rval = crypto_iff(ep, peer)) != XEVNT_OK)\n\t\t\t\tbreak;\n\n\t\t\tpeer->crypto |= CRYPTO_FLAG_VRFY;\n\t\t\tpeer->flash &= ~TEST8;\n\t\t\tsnprintf(statstr, sizeof(statstr), \"iff %s fs %u\",\n\t\t\t peer->issuer, ntohl(ep->fstamp));\n\t\t\trecord_crypto_stats(&peer->srcadr, statstr);\n\t\t\tDPRINTF(1, (\"crypto_recv: %s\\n\", statstr));\n\t\t\tbreak;\n\n\t\t/*\n\t\t * Guillou-Quisquater (GQ) identity scheme. This scheme\n\t\t * is designed for use with public certificates carrying\n\t\t * the GQ public key in an extension field. The client\n\t\t * sends a challenge to the server, which performs a\n\t\t * calculation and returns the result. A positive result\n\t\t * is possible only if both client and server contain\n\t\t * the same group key and the server has the matching GQ\n\t\t * private key.\n\t\t */\n\t\tcase CRYPTO_GQ | CRYPTO_RESP:\n\n\t\t\t/*\n\t\t\t * Discard the message if invalid\n\t\t\t */\n\t\t\tif ((rval = crypto_verify(ep, NULL, peer)) !=\n\t\t\t XEVNT_OK)\n\t\t\t\tbreak;\n\n\t\t\t/*\n\t\t\t * If the challenge matches the response, the\n\t\t\t * server public key, signature and identity are\n\t\t\t * all verified at the same time. The server is\n\t\t\t * declared trusted, so we skip further\n\t\t\t * certificate exchanges and move immediately to\n\t\t\t * the cookie exchange.\n\t\t\t */\n\t\t\tif ((rval = crypto_gq(ep, peer)) != XEVNT_OK)\n\t\t\t\tbreak;\n\n\t\t\tpeer->crypto |= CRYPTO_FLAG_VRFY;\n\t\t\tpeer->flash &= ~TEST8;\n\t\t\tsnprintf(statstr, sizeof(statstr), \"gq %s fs %u\",\n\t\t\t peer->issuer, ntohl(ep->fstamp));\n\t\t\trecord_crypto_stats(&peer->srcadr, statstr);\n\t\t\tDPRINTF(1, (\"crypto_recv: %s\\n\", statstr));\n\t\t\tbreak;\n\n\t\t/*\n\t\t * Mu-Varadharajan (MV) identity scheme. This scheme is\n\t\t * designed for use with three levels of trust, trusted\n\t\t * host, server and client. The trusted host key is\n\t\t * opaque to servers and clients; the server keys are\n\t\t * opaque to clients and each client key is different.\n\t\t * Client keys can be revoked without requiring new key\n\t\t * generations.\n\t\t */\n\t\tcase CRYPTO_MV | CRYPTO_RESP:\n\n\t\t\t/*\n\t\t\t * Discard the message if invalid.\n\t\t\t */\n\t\t\tif ((rval = crypto_verify(ep, NULL, peer)) !=\n\t\t\t XEVNT_OK)\n\t\t\t\tbreak;\n\n\t\t\t/*\n\t\t\t * If the challenge matches the response, the\n\t\t\t * server public key, signature and identity are\n\t\t\t * all verified at the same time. The server is\n\t\t\t * declared trusted, so we skip further\n\t\t\t * certificate exchanges and move immediately to\n\t\t\t * the cookie exchange.\n\t\t\t */\n\t\t\tif ((rval = crypto_mv(ep, peer)) != XEVNT_OK)\n\t\t\t\tbreak;\n\n\t\t\tpeer->crypto |= CRYPTO_FLAG_VRFY;\n\t\t\tpeer->flash &= ~TEST8;\n\t\t\tsnprintf(statstr, sizeof(statstr), \"mv %s fs %u\",\n\t\t\t peer->issuer, ntohl(ep->fstamp));\n\t\t\trecord_crypto_stats(&peer->srcadr, statstr);\n\t\t\tDPRINTF(1, (\"crypto_recv: %s\\n\", statstr));\n\t\t\tbreak;\n\n\n\t\t/*\n\t\t * Cookie response in client and symmetric modes. If the\n\t\t * cookie bit is set, the working cookie is the EXOR of\n\t\t * the current and new values.\n\t\t */\n\t\tcase CRYPTO_COOK | CRYPTO_RESP:\n\n\t\t\t/*\n\t\t\t * Discard the message if invalid or signature\n\t\t\t * not verified with respect to the cookie\n\t\t\t * values.\n\t\t\t */\n\t\t\tif ((rval = crypto_verify(ep, &peer->cookval,\n\t\t\t peer)) != XEVNT_OK)\n\t\t\t\tbreak;\n\n\t\t\t/*\n\t\t\t * Decrypt the cookie, hunting all the time for\n\t\t\t * errors.\n\t\t\t */\n\t\t\tif (vallen == (u_int)EVP_PKEY_size(host_pkey)) {\n\t\t\t\tu_int32 *cookiebuf = malloc(\n\t\t\t\t RSA_size(host_pkey->pkey.rsa));\n\t\t\t\tif (!cookiebuf) {\n\t\t\t\t\trval = XEVNT_CKY;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (RSA_private_decrypt(vallen,\n\t\t\t\t (u_char *)ep->pkt,\n\t\t\t\t (u_char *)cookiebuf,\n\t\t\t\t host_pkey->pkey.rsa,\n\t\t\t\t RSA_PKCS1_OAEP_PADDING) != 4) {\n\t\t\t\t\trval = XEVNT_CKY;\n\t\t\t\t\tfree(cookiebuf);\n\t\t\t\t\tbreak;\n\t\t\t\t} else {\n\t\t\t\t\tcookie = ntohl(*cookiebuf);\n\t\t\t\t\tfree(cookiebuf);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trval = XEVNT_CKY;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Install cookie values and light the cookie\n\t\t\t * bit. If this is not broadcast client mode, we\n\t\t\t * are done here.\n\t\t\t */\n\t\t\tkey_expire(peer);\n\t\t\tif (hismode == MODE_ACTIVE || hismode ==\n\t\t\t MODE_PASSIVE)\n\t\t\t\tpeer->pcookie = peer->hcookie ^ cookie;\n\t\t\telse\n\t\t\t\tpeer->pcookie = cookie;\n\t\t\tpeer->crypto |= CRYPTO_FLAG_COOK;\n\t\t\tpeer->flash &= ~TEST8;\n\t\t\tsnprintf(statstr, sizeof(statstr),\n\t\t\t \"cook %x ts %u fs %u\", peer->pcookie,\n\t\t\t ntohl(ep->tstamp), ntohl(ep->fstamp));\n\t\t\trecord_crypto_stats(&peer->srcadr, statstr);\n\t\t\tDPRINTF(1, (\"crypto_recv: %s\\n\", statstr));\n\t\t\tbreak;\n\n\t\t/*\n\t\t * Install autokey values in broadcast client and\n\t\t * symmetric modes. We have to do this every time the\n\t\t * sever/peer cookie changes or a new keylist is\n\t\t * rolled. Ordinarily, this is automatic as this message\n\t\t * is piggybacked on the first NTP packet sent upon\n\t\t * either of these events. Note that a broadcast client\n\t\t * or symmetric peer can receive this response without a\n\t\t * matching request.\n\t\t */\n\t\tcase CRYPTO_AUTO | CRYPTO_RESP:\n\n\t\t\t/*\n\t\t\t * Discard the message if invalid or signature\n\t\t\t * not verified with respect to the receive\n\t\t\t * autokey values.\n\t\t\t */\n\t\t\tif ((rval = crypto_verify(ep, &peer->recval,\n\t\t\t peer)) != XEVNT_OK) \n\t\t\t\tbreak;\n\n\t\t\t/*\n\t\t\t * Discard the message if a broadcast client and\n\t\t\t * the association ID does not match. This might\n\t\t\t * happen if a broacast server restarts the\n\t\t\t * protocol. A protocol restart will occur at\n\t\t\t * the next ASSOC message.\n\t\t\t */\n\t\t\tif ((peer->cast_flags & MDF_BCLNT) &&\n\t\t\t peer->assoc != associd)\n\t\t\t\tbreak;\n\n\t\t\t/*\n\t\t\t * Install autokey values and light the\n\t\t\t * autokey bit. This is not hard.\n\t\t\t */\n\t\t\tif (ep->tstamp == 0)\n\t\t\t\tbreak;\n\n\t\t\tif (peer->recval.ptr == NULL)\n\t\t\t\tpeer->recval.ptr =\n\t\t\t\t emalloc(sizeof(struct autokey));\n\t\t\tbp = (struct autokey *)peer->recval.ptr;\n\t\t\tpeer->recval.tstamp = ep->tstamp;\n\t\t\tpeer->recval.fstamp = ep->fstamp;\n\t\t\tap = (struct autokey *)ep->pkt;\n\t\t\tbp->seq = ntohl(ap->seq);\n\t\t\tbp->key = ntohl(ap->key);\n\t\t\tpeer->pkeyid = bp->key;\n\t\t\tpeer->crypto |= CRYPTO_FLAG_AUTO;\n\t\t\tpeer->flash &= ~TEST8;\n\t\t\tsnprintf(statstr, sizeof(statstr), \n\t\t\t \"auto seq %d key %x ts %u fs %u\", bp->seq,\n\t\t\t bp->key, ntohl(ep->tstamp),\n\t\t\t ntohl(ep->fstamp));\n\t\t\trecord_crypto_stats(&peer->srcadr, statstr);\n\t\t\tDPRINTF(1, (\"crypto_recv: %s\\n\", statstr));\n\t\t\tbreak;\n\t\n\t\t/*\n\t\t * X509 certificate sign response. Validate the\n\t\t * certificate signed by the server and install. Later\n\t\t * this can be provided to clients of this server in\n\t\t * lieu of the self signed certificate in order to\n\t\t * validate the public key.\n\t\t */\n\t\tcase CRYPTO_SIGN | CRYPTO_RESP:\n\n\t\t\t/*\n\t\t\t * Discard the message if invalid.\n\t\t\t */\n\t\t\tif ((rval = crypto_verify(ep, NULL, peer)) !=\n\t\t\t XEVNT_OK)\n\t\t\t\tbreak;\n\n\t\t\t/*\n\t\t\t * Scan the certificate list to delete old\n\t\t\t * versions and link the newest version first on\n\t\t\t * the list.\n\t\t\t */\n\t\t\tif ((xinfo = cert_install(ep, peer)) == NULL) {\n\t\t\t\trval = XEVNT_CRT;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tpeer->crypto |= CRYPTO_FLAG_SIGN;\n\t\t\tpeer->flash &= ~TEST8;\n\t\t\ttemp32 = xinfo->nid;\n\t\t\tsnprintf(statstr, sizeof(statstr),\n\t\t\t \"sign %s %s 0x%x %s (%u) fs %u\",\n\t\t\t xinfo->subject, xinfo->issuer, xinfo->flags,\n\t\t\t OBJ_nid2ln(temp32), temp32,\n\t\t\t ntohl(ep->fstamp));\n\t\t\trecord_crypto_stats(&peer->srcadr, statstr);\n\t\t\tDPRINTF(1, (\"crypto_recv: %s\\n\", statstr));\n\t\t\tbreak;\n\n\t\t/*\n\t\t * Install leapseconds values. While the leapsecond\n\t\t * values epoch, TAI offset and values expiration epoch\n\t\t * are retained, only the current TAI offset is provided\n\t\t * via the kernel to other applications.\n\t\t */\n\t\tcase CRYPTO_LEAP | CRYPTO_RESP:\n\t\t\t/*\n\t\t\t * Discard the message if invalid. We can't\n\t\t\t * compare the value timestamps here, as they\n\t\t\t * can be updated by different servers.\n\t\t\t */\n\t\t\trval = crypto_verify(ep, NULL, peer);\n\t\t\tif ((rval != XEVNT_OK ) ||\n\t\t\t (vallen != 3*sizeof(uint32_t)) )\n\t\t\t\tbreak;\n\n\t\t\t/* Check if we can update the basic TAI offset\n\t\t\t * for our current leap frame. This is a hack\n\t\t\t * and ignores the time stamps in the autokey\n\t\t\t * message.\n\t\t\t */\n\t\t\tif (sys_leap != LEAP_NOTINSYNC)\n\t\t\t\tleapsec_autokey_tai(ntohl(ep->pkt[0]),\n\t\t\t\t\t\t rbufp->recv_time.l_ui, NULL);\n\t\t\ttai_leap.tstamp = ep->tstamp;\n\t\t\ttai_leap.fstamp = ep->fstamp;\n\t\t\tcrypto_update();\n\t\t\tmprintf_event(EVNT_TAI, peer,\n\t\t\t\t \"%d seconds\", ntohl(ep->pkt[0]));\n\t\t\tpeer->crypto |= CRYPTO_FLAG_LEAP;\n\t\t\tpeer->flash &= ~TEST8;\n\t\t\tsnprintf(statstr, sizeof(statstr),\n\t\t\t\t \"leap TAI offset %d at %u expire %u fs %u\",\n\t\t\t\t ntohl(ep->pkt[0]), ntohl(ep->pkt[1]),\n\t\t\t\t ntohl(ep->pkt[2]), ntohl(ep->fstamp));\n\t\t\trecord_crypto_stats(&peer->srcadr, statstr);\n\t\t\tDPRINTF(1, (\"crypto_recv: %s\\n\", statstr));\n\t\t\tbreak;\n\n\t\t/*\n\t\t * We come here in symmetric modes for miscellaneous\n\t\t * commands that have value fields but are processed on\n\t\t * the transmit side. All we need do here is check for\n\t\t * valid field length. Note that ASSOC is handled\n\t\t * separately.\n\t\t */\n\t\tcase CRYPTO_CERT:\n\t\tcase CRYPTO_IFF:\n\t\tcase CRYPTO_GQ:\n\t\tcase CRYPTO_MV:\n\t\tcase CRYPTO_COOK:\n\t\tcase CRYPTO_SIGN:\n\t\t\tif (len < VALUE_LEN) {\n\t\t\t\trval = XEVNT_LEN;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t/* fall through */\n\n\t\t/*\n\t\t * We come here in symmetric modes for requests\n\t\t * requiring a response (above plus AUTO and LEAP) and\n\t\t * for responses. If a request, save the extension field\n\t\t * for later; invalid requests will be caught on the\n\t\t * transmit side. If an error or invalid response,\n\t\t * declare a protocol error.\n\t\t */\n\t\tdefault:\n\t\t\tif (code & (CRYPTO_RESP | CRYPTO_ERROR)) {\n\t\t\t\trval = XEVNT_ERR;\n\t\t\t} else if (peer->cmmd == NULL) {\n\t\t\t\tfp = emalloc(len);\n\t\t\t\tmemcpy(fp, ep, len);\n\t\t\t\tpeer->cmmd = fp;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * The first error found terminates the extension field\n\t\t * scan and we return the laundry to the caller.\n\t\t */\n\t\tif (rval != XEVNT_OK) {\n\t\t\tsnprintf(statstr, sizeof(statstr),\n\t\t\t \"%04x %d %02x %s\", htonl(ep->opcode),\n\t\t\t associd, rval, eventstr(rval));\n\t\t\trecord_crypto_stats(&peer->srcadr, statstr);\n\t\t\tDPRINTF(1, (\"crypto_recv: %s\\n\", statstr));\n\t\t\treturn (rval);\n\t\t}\n\t\tauthlen += (len + 3) / 4 * 4;\n\t}\n\treturn (rval);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'CVE-2014-9297'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: auth_delkeys(void)\n{\n\tsymkey *\tsk;\n\n\tITER_DLIST_BEGIN(key_listhead, sk, llink, symkey)\n\t\tif (sk->keyid > NTP_MAXKEY) {\t/* autokey */\n\t\t\tcontinue;\n\t\t}\n\n\t\t/*\n\t\t * Don't lose info as to which keys are trusted.\n\t\t */\n\t\tif (KEY_TRUSTED & sk->flags) {\n\t\t\tif (sk->secret != NULL) {\n\t\t\t\tmemset(sk->secret, '\\0', sk->secretsize);\n\t\t\t\tfree(sk->secret);\n\t\t\t}\n\t\t\tsk->secretsize = 0;\n\t\t\tsk->lifetime = 0;\n\t\t} else {\n\t\t\tfreesymkey(sk, &key_hash[KEYHASH(sk->keyid)]);\n\t\t}\n\tITER_DLIST_END()\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': '[TALOS-CAN-0054] memory corruption in password store'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: iakerb_gss_accept_sec_context(OM_uint32 *minor_status,\n gss_ctx_id_t *context_handle,\n gss_cred_id_t verifier_cred_handle,\n gss_buffer_t input_token,\n gss_channel_bindings_t input_chan_bindings,\n gss_name_t *src_name,\n gss_OID *mech_type,\n gss_buffer_t output_token,\n OM_uint32 *ret_flags,\n OM_uint32 *time_rec,\n gss_cred_id_t *delegated_cred_handle)\n{\n OM_uint32 major_status = GSS_S_FAILURE;\n OM_uint32 code;\n iakerb_ctx_id_t ctx;\n int initialContextToken = (*context_handle == GSS_C_NO_CONTEXT);\n\n if (initialContextToken) {\n code = iakerb_alloc_context(&ctx);\n if (code != 0)\n goto cleanup;\n\n } else\n ctx = (iakerb_ctx_id_t)*context_handle;\n\n if (iakerb_is_iakerb_token(input_token)) {\n if (ctx->gssc != GSS_C_NO_CONTEXT) {\n /* We shouldn't get an IAKERB token now. */\n code = G_WRONG_TOKID;\n major_status = GSS_S_DEFECTIVE_TOKEN;\n goto cleanup;\n }\n code = iakerb_acceptor_step(ctx, initialContextToken,\n input_token, output_token);\n if (code == (OM_uint32)KRB5_BAD_MSIZE)\n major_status = GSS_S_DEFECTIVE_TOKEN;\n if (code != 0)\n goto cleanup;\n if (initialContextToken) {\n *context_handle = (gss_ctx_id_t)ctx;\n ctx = NULL;\n }\n if (src_name != NULL)\n *src_name = GSS_C_NO_NAME;\n if (mech_type != NULL)\n *mech_type = (gss_OID)gss_mech_iakerb;\n if (ret_flags != NULL)\n *ret_flags = 0;\n if (time_rec != NULL)\n *time_rec = 0;\n if (delegated_cred_handle != NULL)\n *delegated_cred_handle = GSS_C_NO_CREDENTIAL;\n major_status = GSS_S_CONTINUE_NEEDED;\n } else {\n krb5_gss_ctx_ext_rec exts;\n\n iakerb_make_exts(ctx, &exts);\n\n major_status = krb5_gss_accept_sec_context_ext(&code,\n &ctx->gssc,\n verifier_cred_handle,\n input_token,\n input_chan_bindings,\n src_name,\n NULL,\n output_token,\n ret_flags,\n time_rec,\n delegated_cred_handle,\n &exts);\n if (major_status == GSS_S_COMPLETE) {\n *context_handle = ctx->gssc;\n ctx->gssc = NULL;\n iakerb_release_context(ctx);\n }\n if (mech_type != NULL)\n *mech_type = (gss_OID)gss_mech_krb5;\n }\n\ncleanup:\n if (initialContextToken && GSS_ERROR(major_status)) {\n iakerb_release_context(ctx);\n *context_handle = GSS_C_NO_CONTEXT;\n }\n\n *minor_status = code;\n return major_status;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-18'], 'message': 'Fix IAKERB context aliasing bugs [CVE-2015-2696]\n\nThe IAKERB mechanism currently replaces its context handle with the\nkrb5 mechanism handle upon establishment, under the assumption that\nmost GSS functions are only called after context establishment. This\nassumption is incorrect, and can lead to aliasing violations for some\nprograms. Maintain the IAKERB context structure after context\nestablishment and add new IAKERB entry points to refer to it with that\ntype. Add initiate and established flags to the IAKERB context\nstructure for use in gss_inquire_context() prior to context\nestablishment.\n\nCVE-2015-2696:\n\nIn MIT krb5 1.9 and later, applications which call\ngss_inquire_context() on a partially-established IAKERB context can\ncause the GSS-API library to read from a pointer using the wrong type,\ngenerally causing a process crash. Java server applications using the\nnative JGSS provider are vulnerable to this bug. A carefully crafted\nIAKERB packet might allow the gss_inquire_context() call to succeed\nwith attacker-determined results, but applications should not make\naccess control decisions based on gss_inquire_context() results prior\nto context establishment.\n\n CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C\n\n[ghudson@mit.edu: several bugfixes, style changes, and edge-case\nbehavior changes; commit message and CVE description]\n\nticket: 8244\ntarget_version: 1.14\ntags: pullup'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: spnego_gss_complete_auth_token(\n\t\tOM_uint32 *minor_status,\n\t\tconst gss_ctx_id_t context_handle,\n\t\tgss_buffer_t input_message_buffer)\n{\n\tOM_uint32 ret;\n\tret = gss_complete_auth_token(minor_status,\n\t\t\t\t context_handle,\n\t\t\t\t input_message_buffer);\n\treturn (ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-18', 'CWE-763'], 'message': 'Fix SPNEGO context aliasing bugs [CVE-2015-2695]\n\nThe SPNEGO mechanism currently replaces its context handle with the\nmechanism context handle upon establishment, under the assumption that\nmost GSS functions are only called after context establishment. This\nassumption is incorrect, and can lead to aliasing violations for some\nprograms. Maintain the SPNEGO context structure after context\nestablishment and refer to it in all GSS methods. Add initiate and\nopened flags to the SPNEGO context structure for use in\ngss_inquire_context() prior to context establishment.\n\nCVE-2015-2695:\n\nIn MIT krb5 1.5 and later, applications which call\ngss_inquire_context() on a partially-established SPNEGO context can\ncause the GSS-API library to read from a pointer using the wrong type,\ngenerally causing a process crash. This bug may go unnoticed, because\nthe most common SPNEGO authentication scenario establishes the context\nafter just one call to gss_accept_sec_context(). Java server\napplications using the native JGSS provider are vulnerable to this\nbug. A carefully crafted SPNEGO packet might allow the\ngss_inquire_context() call to succeed with attacker-determined\nresults, but applications should not make access control decisions\nbased on gss_inquire_context() results prior to context establishment.\n\n CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C\n\n[ghudson@mit.edu: several bugfixes, style changes, and edge-case\nbehavior changes; commit message and CVE description]\n\nticket: 8244\ntarget_version: 1.14\ntags: pullup'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: spnego_gss_init_sec_context(\n\t\t\tOM_uint32 *minor_status,\n\t\t\tgss_cred_id_t claimant_cred_handle,\n\t\t\tgss_ctx_id_t *context_handle,\n\t\t\tgss_name_t target_name,\n\t\t\tgss_OID mech_type,\n\t\t\tOM_uint32 req_flags,\n\t\t\tOM_uint32 time_req,\n\t\t\tgss_channel_bindings_t input_chan_bindings,\n\t\t\tgss_buffer_t input_token,\n\t\t\tgss_OID *actual_mech,\n\t\t\tgss_buffer_t output_token,\n\t\t\tOM_uint32 *ret_flags,\n\t\t\tOM_uint32 *time_rec)\n{\n\tsend_token_flag send_token = NO_TOKEN_SEND;\n\tOM_uint32 tmpmin, ret, negState;\n\tgss_buffer_t mechtok_in, mechListMIC_in, mechListMIC_out;\n\tgss_buffer_desc mechtok_out = GSS_C_EMPTY_BUFFER;\n\tspnego_gss_cred_id_t spcred = NULL;\n\tspnego_gss_ctx_id_t spnego_ctx = NULL;\n\n\tdsyslog(\"Entering init_sec_context\\n\");\n\n\tmechtok_in = mechListMIC_out = mechListMIC_in = GSS_C_NO_BUFFER;\n\tnegState = REJECT;\n\n\t/*\n\t * This function works in three steps:\n\t *\n\t * 1. Perform mechanism negotiation.\n\t * 2. Invoke the negotiated or optimistic mech's gss_init_sec_context\n\t * function and examine the results.\n\t * 3. Process or generate MICs if necessary.\n\t *\n\t * The three steps share responsibility for determining when the\n\t * exchange is complete. If the selected mech completed in a previous\n\t * call and no MIC exchange is expected, then step 1 will decide. If\n\t * the selected mech completes in this call and no MIC exchange is\n\t * expected, then step 2 will decide. If a MIC exchange is expected,\n\t * then step 3 will decide. If an error occurs in any step, the\n\t * exchange will be aborted, possibly with an error token.\n\t *\n\t * negState determines the state of the negotiation, and is\n\t * communicated to the acceptor if a continuing token is sent.\n\t * send_token is used to indicate what type of token, if any, should be\n\t * generated.\n\t */\n\n\t/* Validate arguments. */\n\tif (minor_status != NULL)\n\t\t*minor_status = 0;\n\tif (output_token != GSS_C_NO_BUFFER) {\n\t\toutput_token->length = 0;\n\t\toutput_token->value = NULL;\n\t}\n\tif (minor_status == NULL ||\n\t output_token == GSS_C_NO_BUFFER ||\n\t context_handle == NULL)\n\t\treturn GSS_S_CALL_INACCESSIBLE_WRITE;\n\n\tif (actual_mech != NULL)\n\t\t*actual_mech = GSS_C_NO_OID;\n\n\t/* Step 1: perform mechanism negotiation. */\n\tspcred = (spnego_gss_cred_id_t)claimant_cred_handle;\n\tif (*context_handle == GSS_C_NO_CONTEXT) {\n\t\tret = init_ctx_new(minor_status, spcred,\n\t\t\t\t context_handle, &send_token);\n\t\tif (ret != GSS_S_CONTINUE_NEEDED) {\n\t\t\tgoto cleanup;\n\t\t}\n\t} else {\n\t\tret = init_ctx_cont(minor_status, context_handle,\n\t\t\t\t input_token, &mechtok_in,\n\t\t\t\t &mechListMIC_in, &negState, &send_token);\n\t\tif (HARD_ERROR(ret)) {\n\t\t\tgoto cleanup;\n\t\t}\n\t}\n\n\t/* Step 2: invoke the selected or optimistic mechanism's\n\t * gss_init_sec_context function, if it didn't complete previously. */\n\tspnego_ctx = (spnego_gss_ctx_id_t)*context_handle;\n\tif (!spnego_ctx->mech_complete) {\n\t\tret = init_ctx_call_init(\n\t\t\tminor_status, spnego_ctx, spcred,\n\t\t\ttarget_name, req_flags,\n\t\t\ttime_req, mechtok_in,\n\t\t\tactual_mech, &mechtok_out,\n\t\t\tret_flags, time_rec,\n\t\t\t&negState, &send_token);\n\n\t\t/* Give the mechanism a chance to force a mechlistMIC. */\n\t\tif (!HARD_ERROR(ret) && mech_requires_mechlistMIC(spnego_ctx))\n\t\t\tspnego_ctx->mic_reqd = 1;\n\t}\n\n\t/* Step 3: process or generate the MIC, if the negotiated mech is\n\t * complete and supports MICs. */\n\tif (!HARD_ERROR(ret) && spnego_ctx->mech_complete &&\n\t (spnego_ctx->ctx_flags & GSS_C_INTEG_FLAG)) {\n\n\t\tret = handle_mic(minor_status,\n\t\t\t\t mechListMIC_in,\n\t\t\t\t (mechtok_out.length != 0),\n\t\t\t\t spnego_ctx, &mechListMIC_out,\n\t\t\t\t &negState, &send_token);\n\t}\ncleanup:\n\tif (send_token == INIT_TOKEN_SEND) {\n\t\tif (make_spnego_tokenInit_msg(spnego_ctx,\n\t\t\t\t\t 0,\n\t\t\t\t\t mechListMIC_out,\n\t\t\t\t\t req_flags,\n\t\t\t\t\t &mechtok_out, send_token,\n\t\t\t\t\t output_token) < 0) {\n\t\t\tret = GSS_S_FAILURE;\n\t\t}\n\t} else if (send_token != NO_TOKEN_SEND) {\n\t\tif (make_spnego_tokenTarg_msg(negState, GSS_C_NO_OID,\n\t\t\t\t\t &mechtok_out, mechListMIC_out,\n\t\t\t\t\t send_token,\n\t\t\t\t\t output_token) < 0) {\n\t\t\tret = GSS_S_FAILURE;\n\t\t}\n\t}\n\tgss_release_buffer(&tmpmin, &mechtok_out);\n\tif (ret == GSS_S_COMPLETE) {\n\t\t/*\n\t\t * Now, switch the output context to refer to the\n\t\t * negotiated mechanism's context.\n\t\t */\n\t\t*context_handle = (gss_ctx_id_t)spnego_ctx->ctx_handle;\n\t\tif (actual_mech != NULL)\n\t\t\t*actual_mech = spnego_ctx->actual_mech;\n\t\tif (ret_flags != NULL)\n\t\t\t*ret_flags = spnego_ctx->ctx_flags;\n\t\trelease_spnego_ctx(&spnego_ctx);\n\t} else if (ret != GSS_S_CONTINUE_NEEDED) {\n\t\tif (spnego_ctx != NULL) {\n\t\t\tgss_delete_sec_context(&tmpmin,\n\t\t\t\t\t &spnego_ctx->ctx_handle,\n\t\t\t\t\t GSS_C_NO_BUFFER);\n\t\t\trelease_spnego_ctx(&spnego_ctx);\n\t\t}\n\t\t*context_handle = GSS_C_NO_CONTEXT;\n\t}\n\tif (mechtok_in != GSS_C_NO_BUFFER) {\n\t\tgss_release_buffer(&tmpmin, mechtok_in);\n\t\tfree(mechtok_in);\n\t}\n\tif (mechListMIC_in != GSS_C_NO_BUFFER) {\n\t\tgss_release_buffer(&tmpmin, mechListMIC_in);\n\t\tfree(mechListMIC_in);\n\t}\n\tif (mechListMIC_out != GSS_C_NO_BUFFER) {\n\t\tgss_release_buffer(&tmpmin, mechListMIC_out);\n\t\tfree(mechListMIC_out);\n\t}\n\treturn ret;\n} /* init_sec_context */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-18', 'CWE-763'], 'message': 'Fix SPNEGO context aliasing bugs [CVE-2015-2695]\n\nThe SPNEGO mechanism currently replaces its context handle with the\nmechanism context handle upon establishment, under the assumption that\nmost GSS functions are only called after context establishment. This\nassumption is incorrect, and can lead to aliasing violations for some\nprograms. Maintain the SPNEGO context structure after context\nestablishment and refer to it in all GSS methods. Add initiate and\nopened flags to the SPNEGO context structure for use in\ngss_inquire_context() prior to context establishment.\n\nCVE-2015-2695:\n\nIn MIT krb5 1.5 and later, applications which call\ngss_inquire_context() on a partially-established SPNEGO context can\ncause the GSS-API library to read from a pointer using the wrong type,\ngenerally causing a process crash. This bug may go unnoticed, because\nthe most common SPNEGO authentication scenario establishes the context\nafter just one call to gss_accept_sec_context(). Java server\napplications using the native JGSS provider are vulnerable to this\nbug. A carefully crafted SPNEGO packet might allow the\ngss_inquire_context() call to succeed with attacker-determined\nresults, but applications should not make access control decisions\nbased on gss_inquire_context() results prior to context establishment.\n\n CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C\n\n[ghudson@mit.edu: several bugfixes, style changes, and edge-case\nbehavior changes; commit message and CVE description]\n\nticket: 8244\ntarget_version: 1.14\ntags: pullup'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: spnego_gss_get_mic(\n\t\tOM_uint32 *minor_status,\n\t\tconst gss_ctx_id_t context_handle,\n\t\tgss_qop_t qop_req,\n\t\tconst gss_buffer_t message_buffer,\n\t\tgss_buffer_t message_token)\n{\n\tOM_uint32 ret;\n\tret = gss_get_mic(minor_status,\n\t\t context_handle,\n\t\t qop_req,\n\t\t message_buffer,\n\t\t message_token);\n\treturn (ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-18', 'CWE-763'], 'message': 'Fix SPNEGO context aliasing bugs [CVE-2015-2695]\n\nThe SPNEGO mechanism currently replaces its context handle with the\nmechanism context handle upon establishment, under the assumption that\nmost GSS functions are only called after context establishment. This\nassumption is incorrect, and can lead to aliasing violations for some\nprograms. Maintain the SPNEGO context structure after context\nestablishment and refer to it in all GSS methods. Add initiate and\nopened flags to the SPNEGO context structure for use in\ngss_inquire_context() prior to context establishment.\n\nCVE-2015-2695:\n\nIn MIT krb5 1.5 and later, applications which call\ngss_inquire_context() on a partially-established SPNEGO context can\ncause the GSS-API library to read from a pointer using the wrong type,\ngenerally causing a process crash. This bug may go unnoticed, because\nthe most common SPNEGO authentication scenario establishes the context\nafter just one call to gss_accept_sec_context(). Java server\napplications using the native JGSS provider are vulnerable to this\nbug. A carefully crafted SPNEGO packet might allow the\ngss_inquire_context() call to succeed with attacker-determined\nresults, but applications should not make access control decisions\nbased on gss_inquire_context() results prior to context establishment.\n\n CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C\n\n[ghudson@mit.edu: several bugfixes, style changes, and edge-case\nbehavior changes; commit message and CVE description]\n\nticket: 8244\ntarget_version: 1.14\ntags: pullup'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: xz_decomp(xz_statep state)\n{\n int ret;\n unsigned had;\n unsigned long crc, len;\n lzma_stream *strm = &(state->strm);\n\n lzma_action action = LZMA_RUN;\n\n /* fill output buffer up to end of deflate stream */\n had = strm->avail_out;\n do {\n /* get more input for inflate() */\n if (strm->avail_in == 0 && xz_avail(state) == -1)\n return -1;\n if (strm->avail_in == 0) {\n xz_error(state, LZMA_DATA_ERROR, \"unexpected end of file\");\n return -1;\n }\n if (state->eof)\n action = LZMA_FINISH;\n\n /* decompress and handle errors */\n#ifdef HAVE_ZLIB_H\n if (state->how == GZIP) {\n state->zstrm.avail_in = (uInt) state->strm.avail_in;\n state->zstrm.next_in = (Bytef *) state->strm.next_in;\n state->zstrm.avail_out = (uInt) state->strm.avail_out;\n state->zstrm.next_out = (Bytef *) state->strm.next_out;\n ret = inflate(&state->zstrm, Z_NO_FLUSH);\n if (ret == Z_STREAM_ERROR || ret == Z_NEED_DICT) {\n xz_error(state, Z_STREAM_ERROR,\n \"internal error: inflate stream corrupt\");\n return -1;\n }\n if (ret == Z_MEM_ERROR)\n ret = LZMA_MEM_ERROR;\n if (ret == Z_DATA_ERROR)\n ret = LZMA_DATA_ERROR;\n if (ret == Z_STREAM_END)\n ret = LZMA_STREAM_END;\n state->strm.avail_in = state->zstrm.avail_in;\n state->strm.next_in = state->zstrm.next_in;\n state->strm.avail_out = state->zstrm.avail_out;\n state->strm.next_out = state->zstrm.next_out;\n } else /* state->how == LZMA */\n#endif\n ret = lzma_code(strm, action);\n if (ret == LZMA_MEM_ERROR) {\n xz_error(state, LZMA_MEM_ERROR, \"out of memory\");\n return -1;\n }\n if (ret == LZMA_DATA_ERROR) {\n xz_error(state, LZMA_DATA_ERROR, \"compressed data error\");\n return -1;\n }\n } while (strm->avail_out && ret != LZMA_STREAM_END);\n\n /* update available output and crc check value */\n state->have = had - strm->avail_out;\n state->next = strm->next_out - state->have;\n#ifdef HAVE_ZLIB_H\n state->zstrm.adler =\n crc32(state->zstrm.adler, state->next, state->have);\n#endif\n\n if (ret == LZMA_STREAM_END) {\n#ifdef HAVE_ZLIB_H\n if (state->how == GZIP) {\n if (gz_next4(state, &crc) == -1 || gz_next4(state, &len) == -1) {\n xz_error(state, LZMA_DATA_ERROR, \"unexpected end of file\");\n return -1;\n }\n if (crc != state->zstrm.adler) {\n xz_error(state, LZMA_DATA_ERROR, \"incorrect data check\");\n return -1;\n }\n if (len != (state->zstrm.total_out & 0xffffffffL)) {\n xz_error(state, LZMA_DATA_ERROR, \"incorrect length check\");\n return -1;\n }\n state->strm.avail_in = 0;\n state->strm.next_in = NULL;\n state->strm.avail_out = 0;\n state->strm.next_out = NULL;\n } else\n#endif\n if (strm->avail_in != 0 || !state->eof) {\n xz_error(state, LZMA_DATA_ERROR, \"trailing garbage\");\n return -1;\n }\n state->how = LOOK; /* ready for next stream, once have is 0 (leave\n * state->direct unchanged to remember how) */\n }\n\n /* good decompression */\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-8035 Fix XZ compression support loop\n\nFor https://bugzilla.gnome.org/show_bug.cgi?id=757466\nDoS when parsing specially crafted XML document if XZ support\nis compiled in (which wasn't the case for 2.9.2 and master since\nNov 2013, fixed in next commit !)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: _PUBLIC_ codepoint_t next_codepoint_handle_ext(\n\t\t\tstruct smb_iconv_handle *ic,\n\t\t\tconst char *str, charset_t src_charset,\n\t\t\tsize_t *bytes_consumed)\n{\n\t/* it cannot occupy more than 4 bytes in UTF16 format */\n\tuint8_t buf[4];\n\tsmb_iconv_t descriptor;\n\tsize_t ilen_orig;\n\tsize_t ilen;\n\tsize_t olen;\n\tchar *outbuf;\n\n\tif ((str[0] & 0x80) == 0) {\n\t\t*bytes_consumed = 1;\n\t\treturn (codepoint_t)str[0];\n\t}\n\n\t/*\n\t * we assume that no multi-byte character can take more than 5 bytes.\n\t * This is OK as we only support codepoints up to 1M (U+100000)\n\t */\n\tilen_orig = strnlen(str, 5);\n\tilen = ilen_orig;\n\n\tdescriptor = get_conv_handle(ic, src_charset, CH_UTF16);\n\tif (descriptor == (smb_iconv_t)-1) {\n\t\t*bytes_consumed = 1;\n\t\treturn INVALID_CODEPOINT;\n\t}\n\n\t/*\n\t * this looks a little strange, but it is needed to cope with\n\t * codepoints above 64k (U+1000) which are encoded as per RFC2781.\n\t */\n\tolen = 2;\n\toutbuf = (char *)buf;\n\tsmb_iconv(descriptor, &str, &ilen, &outbuf, &olen);\n\tif (olen == 2) {\n\t\tolen = 4;\n\t\toutbuf = (char *)buf;\n\t\tsmb_iconv(descriptor, &str, &ilen, &outbuf, &olen);\n\t\tif (olen == 4) {\n\t\t\t/* we didn't convert any bytes */\n\t\t\t*bytes_consumed = 1;\n\t\t\treturn INVALID_CODEPOINT;\n\t\t}\n\t\tolen = 4 - olen;\n\t} else {\n\t\tolen = 2 - olen;\n\t}\n\n\t*bytes_consumed = ilen_orig - ilen;\n\n\tif (olen == 2) {\n\t\treturn (codepoint_t)SVAL(buf, 0);\n\t}\n\tif (olen == 4) {\n\t\t/* decode a 4 byte UTF16 character manually */\n\t\treturn (codepoint_t)0x10000 +\n\t\t\t(buf[2] | ((buf[3] & 0x3)<<8) |\n\t\t\t (buf[0]<<10) | ((buf[1] & 0x3)<<18));\n\t}\n\n\t/* no other length is valid */\n\treturn INVALID_CODEPOINT;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'CVE-2015-5330: Fix handling of unicode near string endings\n\nUntil now next_codepoint_ext() and next_codepoint_handle_ext() were\nusing strnlen(str, 5) to determine how much string they should try to\ndecode. This ended up looking past the end of the string when it was not\nnull terminated and the final character looked like a multi-byte encoding.\nThe fix is to let the caller say how long the string can be.\n\nBug: https://bugzilla.samba.org/show_bug.cgi?id=11599\n\nSigned-off-by: Douglas Bagnall \nPair-programmed-with: Andrew Bartlett \nReviewed-by: Ralph Boehme '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: png_handle_PLTE(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)\n{\n png_color palette[PNG_MAX_PALETTE_LENGTH];\n int num, i;\n#ifdef PNG_POINTER_INDEXING_SUPPORTED\n png_colorp pal_ptr;\n#endif\n\n png_debug(1, \"in png_handle_PLTE\");\n\n if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)\n png_chunk_error(png_ptr, \"missing IHDR\");\n\n /* Moved to before the 'after IDAT' check below because otherwise duplicate\n * PLTE chunks are potentially ignored (the spec says there shall not be more\n * than one PLTE, the error is not treated as benign, so this check trumps\n * the requirement that PLTE appears before IDAT.)\n */\n else if ((png_ptr->mode & PNG_HAVE_PLTE) != 0)\n png_chunk_error(png_ptr, \"duplicate\");\n\n else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)\n {\n /* This is benign because the non-benign error happened before, when an\n * IDAT was encountered in a color-mapped image with no PLTE.\n */\n png_crc_finish(png_ptr, length);\n png_chunk_benign_error(png_ptr, \"out of place\");\n return;\n }\n\n png_ptr->mode |= PNG_HAVE_PLTE;\n\n if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0)\n {\n png_crc_finish(png_ptr, length);\n png_chunk_benign_error(png_ptr, \"ignored in grayscale PNG\");\n return;\n }\n\n#ifndef PNG_READ_OPT_PLTE_SUPPORTED\n if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)\n {\n png_crc_finish(png_ptr, length);\n return;\n }\n#endif\n\n if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)\n {\n png_crc_finish(png_ptr, length);\n\n if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)\n png_chunk_benign_error(png_ptr, \"invalid\");\n\n else\n png_chunk_error(png_ptr, \"invalid\");\n\n return;\n }\n\n /* The cast is safe because 'length' is less than 3*PNG_MAX_PALETTE_LENGTH */\n num = (int)length / 3;\n\n#ifdef PNG_POINTER_INDEXING_SUPPORTED\n for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)\n {\n png_byte buf[3];\n\n png_crc_read(png_ptr, buf, 3);\n pal_ptr->red = buf[0];\n pal_ptr->green = buf[1];\n pal_ptr->blue = buf[2];\n }\n#else\n for (i = 0; i < num; i++)\n {\n png_byte buf[3];\n\n png_crc_read(png_ptr, buf, 3);\n /* Don't depend upon png_color being any order */\n palette[i].red = buf[0];\n palette[i].green = buf[1];\n palette[i].blue = buf[2];\n }\n#endif\n\n /* If we actually need the PLTE chunk (ie for a paletted image), we do\n * whatever the normal CRC configuration tells us. However, if we\n * have an RGB image, the PLTE can be considered ancillary, so\n * we will act as though it is.\n */\n#ifndef PNG_READ_OPT_PLTE_SUPPORTED\n if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)\n#endif\n {\n png_crc_finish(png_ptr, 0);\n }\n\n#ifndef PNG_READ_OPT_PLTE_SUPPORTED\n else if (png_crc_error(png_ptr) != 0) /* Only if we have a CRC error */\n {\n /* If we don't want to use the data from an ancillary chunk,\n * we have two options: an error abort, or a warning and we\n * ignore the data in this chunk (which should be OK, since\n * it's considered ancillary for a RGB or RGBA image).\n *\n * IMPLEMENTATION NOTE: this is only here because png_crc_finish uses the\n * chunk type to determine whether to check the ancillary or the critical\n * flags.\n */\n if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE) == 0)\n {\n if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) != 0)\n return;\n\n else\n png_chunk_error(png_ptr, \"CRC error\");\n }\n\n /* Otherwise, we (optionally) emit a warning and use the chunk. */\n else if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) == 0)\n png_chunk_warning(png_ptr, \"CRC error\");\n }\n#endif\n\n /* TODO: png_set_PLTE has the side effect of setting png_ptr->palette to its\n * own copy of the palette. This has the side effect that when png_start_row\n * is called (this happens after any call to png_read_update_info) the\n * info_ptr palette gets changed. This is extremely unexpected and\n * confusing.\n *\n * Fix this by not sharing the palette in this way.\n *\n * Starting with libpng-1.6.19, png_set_PLTE() also issues a png_error() when\n * it attempts to set a palette length that is too large for the bit depth.\n */\n png_set_PLTE(png_ptr, info_ptr, palette, num);\n\n /* The three chunks, bKGD, hIST and tRNS *must* appear after PLTE and before\n * IDAT. Prior to 1.6.0 this was not checked; instead the code merely\n * checked the apparent validity of a tRNS chunk inserted before PLTE on a\n * palette PNG. 1.6.0 attempts to rigorously follow the standard and\n * therefore does a benign error if the erroneous condition is detected *and*\n * cancels the tRNS if the benign error returns. The alternative is to\n * amend the standard since it would be rather hypocritical of the standards\n * maintainers to ignore it.\n */\n#ifdef PNG_READ_tRNS_SUPPORTED\n if (png_ptr->num_trans > 0 ||\n (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS) != 0))\n {\n /* Cancel this because otherwise it would be used if the transforms\n * require it. Don't cancel the 'valid' flag because this would prevent\n * detection of duplicate chunks.\n */\n png_ptr->num_trans = 0;\n\n if (info_ptr != NULL)\n info_ptr->num_trans = 0;\n\n png_chunk_benign_error(png_ptr, \"tRNS must be after\");\n }\n#endif\n\n#ifdef PNG_READ_hIST_SUPPORTED\n if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST) != 0)\n png_chunk_benign_error(png_ptr, \"hIST must be after\");\n#endif\n\n#ifdef PNG_READ_bKGD_SUPPORTED\n if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD) != 0)\n png_chunk_benign_error(png_ptr, \"bKGD must be after\");\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': '[libpng16] Silently truncate over-length PLTE chunk while reading.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: xmlParseEncodingDecl(xmlParserCtxtPtr ctxt) {\n xmlChar *encoding = NULL;\n\n SKIP_BLANKS;\n if (CMP8(CUR_PTR, 'e', 'n', 'c', 'o', 'd', 'i', 'n', 'g')) {\n\tSKIP(8);\n\tSKIP_BLANKS;\n\tif (RAW != '=') {\n\t xmlFatalErr(ctxt, XML_ERR_EQUAL_REQUIRED, NULL);\n\t return(NULL);\n }\n\tNEXT;\n\tSKIP_BLANKS;\n\tif (RAW == '\"') {\n\t NEXT;\n\t encoding = xmlParseEncName(ctxt);\n\t if (RAW != '\"') {\n\t\txmlFatalErr(ctxt, XML_ERR_STRING_NOT_CLOSED, NULL);\n\t } else\n\t NEXT;\n\t} else if (RAW == '\\''){\n\t NEXT;\n\t encoding = xmlParseEncName(ctxt);\n\t if (RAW != '\\'') {\n\t\txmlFatalErr(ctxt, XML_ERR_STRING_NOT_CLOSED, NULL);\n\t } else\n\t NEXT;\n\t} else {\n\t xmlFatalErr(ctxt, XML_ERR_STRING_NOT_STARTED, NULL);\n\t}\n\n /*\n * Non standard parsing, allowing the user to ignore encoding\n */\n if (ctxt->options & XML_PARSE_IGNORE_ENC) {\n\t xmlFree((xmlChar *) encoding);\n return(NULL);\n\t}\n\n\t/*\n\t * UTF-16 encoding stwich has already taken place at this stage,\n\t * more over the little-endian/big-endian selection is already done\n\t */\n if ((encoding != NULL) &&\n\t ((!xmlStrcasecmp(encoding, BAD_CAST \"UTF-16\")) ||\n\t (!xmlStrcasecmp(encoding, BAD_CAST \"UTF16\")))) {\n\t /*\n\t * If no encoding was passed to the parser, that we are\n\t * using UTF-16 and no decoder is present i.e. the\n\t * document is apparently UTF-8 compatible, then raise an\n\t * encoding mismatch fatal error\n\t */\n\t if ((ctxt->encoding == NULL) &&\n\t (ctxt->input->buf != NULL) &&\n\t (ctxt->input->buf->encoder == NULL)) {\n\t\txmlFatalErrMsg(ctxt, XML_ERR_INVALID_ENCODING,\n\t\t \"Document labelled UTF-16 but has UTF-8 content\\n\");\n\t }\n\t if (ctxt->encoding != NULL)\n\t\txmlFree((xmlChar *) ctxt->encoding);\n\t ctxt->encoding = encoding;\n\t}\n\t/*\n\t * UTF-8 encoding is handled natively\n\t */\n else if ((encoding != NULL) &&\n\t ((!xmlStrcasecmp(encoding, BAD_CAST \"UTF-8\")) ||\n\t (!xmlStrcasecmp(encoding, BAD_CAST \"UTF8\")))) {\n\t if (ctxt->encoding != NULL)\n\t\txmlFree((xmlChar *) ctxt->encoding);\n\t ctxt->encoding = encoding;\n\t}\n\telse if (encoding != NULL) {\n\t xmlCharEncodingHandlerPtr handler;\n\n\t if (ctxt->input->encoding != NULL)\n\t\txmlFree((xmlChar *) ctxt->input->encoding);\n\t ctxt->input->encoding = encoding;\n\n handler = xmlFindCharEncodingHandler((const char *) encoding);\n\t if (handler != NULL) {\n\t\txmlSwitchToEncoding(ctxt, handler);\n\t } else {\n\t\txmlFatalErrMsgStr(ctxt, XML_ERR_UNSUPPORTED_ENCODING,\n\t\t\t\"Unsupported encoding %s\\n\", encoding);\n\t\treturn(NULL);\n\t }\n\t}\n }\n return(encoding);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Do not process encoding values if the declaration if broken\n\nFor https://bugzilla.gnome.org/show_bug.cgi?id=751603\n\nIf the string is not properly terminated do not try to convert\nto the given encoding.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int btrfs_clone(struct inode *src, struct inode *inode,\n\t\t const u64 off, const u64 olen, const u64 olen_aligned,\n\t\t const u64 destoff, int no_time_update)\n{\n\tstruct btrfs_root *root = BTRFS_I(inode)->root;\n\tstruct btrfs_path *path = NULL;\n\tstruct extent_buffer *leaf;\n\tstruct btrfs_trans_handle *trans;\n\tchar *buf = NULL;\n\tstruct btrfs_key key;\n\tu32 nritems;\n\tint slot;\n\tint ret;\n\tint no_quota;\n\tconst u64 len = olen_aligned;\n\tu64 last_disko = 0;\n\tu64 last_dest_end = destoff;\n\n\tret = -ENOMEM;\n\tbuf = vmalloc(root->nodesize);\n\tif (!buf)\n\t\treturn ret;\n\n\tpath = btrfs_alloc_path();\n\tif (!path) {\n\t\tvfree(buf);\n\t\treturn ret;\n\t}\n\n\tpath->reada = 2;\n\t/* clone data */\n\tkey.objectid = btrfs_ino(src);\n\tkey.type = BTRFS_EXTENT_DATA_KEY;\n\tkey.offset = off;\n\n\twhile (1) {\n\t\tu64 next_key_min_offset = key.offset + 1;\n\n\t\t/*\n\t\t * note the key will change type as we walk through the\n\t\t * tree.\n\t\t */\n\t\tpath->leave_spinning = 1;\n\t\tret = btrfs_search_slot(NULL, BTRFS_I(src)->root, &key, path,\n\t\t\t\t0, 0);\n\t\tif (ret < 0)\n\t\t\tgoto out;\n\t\t/*\n\t\t * First search, if no extent item that starts at offset off was\n\t\t * found but the previous item is an extent item, it's possible\n\t\t * it might overlap our target range, therefore process it.\n\t\t */\n\t\tif (key.offset == off && ret > 0 && path->slots[0] > 0) {\n\t\t\tbtrfs_item_key_to_cpu(path->nodes[0], &key,\n\t\t\t\t\t path->slots[0] - 1);\n\t\t\tif (key.type == BTRFS_EXTENT_DATA_KEY)\n\t\t\t\tpath->slots[0]--;\n\t\t}\n\n\t\tnritems = btrfs_header_nritems(path->nodes[0]);\nprocess_slot:\n\t\tno_quota = 1;\n\t\tif (path->slots[0] >= nritems) {\n\t\t\tret = btrfs_next_leaf(BTRFS_I(src)->root, path);\n\t\t\tif (ret < 0)\n\t\t\t\tgoto out;\n\t\t\tif (ret > 0)\n\t\t\t\tbreak;\n\t\t\tnritems = btrfs_header_nritems(path->nodes[0]);\n\t\t}\n\t\tleaf = path->nodes[0];\n\t\tslot = path->slots[0];\n\n\t\tbtrfs_item_key_to_cpu(leaf, &key, slot);\n\t\tif (key.type > BTRFS_EXTENT_DATA_KEY ||\n\t\t key.objectid != btrfs_ino(src))\n\t\t\tbreak;\n\n\t\tif (key.type == BTRFS_EXTENT_DATA_KEY) {\n\t\t\tstruct btrfs_file_extent_item *extent;\n\t\t\tint type;\n\t\t\tu32 size;\n\t\t\tstruct btrfs_key new_key;\n\t\t\tu64 disko = 0, diskl = 0;\n\t\t\tu64 datao = 0, datal = 0;\n\t\t\tu8 comp;\n\t\t\tu64 drop_start;\n\n\t\t\textent = btrfs_item_ptr(leaf, slot,\n\t\t\t\t\t\tstruct btrfs_file_extent_item);\n\t\t\tcomp = btrfs_file_extent_compression(leaf, extent);\n\t\t\ttype = btrfs_file_extent_type(leaf, extent);\n\t\t\tif (type == BTRFS_FILE_EXTENT_REG ||\n\t\t\t type == BTRFS_FILE_EXTENT_PREALLOC) {\n\t\t\t\tdisko = btrfs_file_extent_disk_bytenr(leaf,\n\t\t\t\t\t\t\t\t extent);\n\t\t\t\tdiskl = btrfs_file_extent_disk_num_bytes(leaf,\n\t\t\t\t\t\t\t\t extent);\n\t\t\t\tdatao = btrfs_file_extent_offset(leaf, extent);\n\t\t\t\tdatal = btrfs_file_extent_num_bytes(leaf,\n\t\t\t\t\t\t\t\t extent);\n\t\t\t} else if (type == BTRFS_FILE_EXTENT_INLINE) {\n\t\t\t\t/* take upper bound, may be compressed */\n\t\t\t\tdatal = btrfs_file_extent_ram_bytes(leaf,\n\t\t\t\t\t\t\t\t extent);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * The first search might have left us at an extent\n\t\t\t * item that ends before our target range's start, can\n\t\t\t * happen if we have holes and NO_HOLES feature enabled.\n\t\t\t */\n\t\t\tif (key.offset + datal <= off) {\n\t\t\t\tpath->slots[0]++;\n\t\t\t\tgoto process_slot;\n\t\t\t} else if (key.offset >= off + len) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tnext_key_min_offset = key.offset + datal;\n\t\t\tsize = btrfs_item_size_nr(leaf, slot);\n\t\t\tread_extent_buffer(leaf, buf,\n\t\t\t\t\t btrfs_item_ptr_offset(leaf, slot),\n\t\t\t\t\t size);\n\n\t\t\tbtrfs_release_path(path);\n\t\t\tpath->leave_spinning = 0;\n\n\t\t\tmemcpy(&new_key, &key, sizeof(new_key));\n\t\t\tnew_key.objectid = btrfs_ino(inode);\n\t\t\tif (off <= key.offset)\n\t\t\t\tnew_key.offset = key.offset + destoff - off;\n\t\t\telse\n\t\t\t\tnew_key.offset = destoff;\n\n\t\t\t/*\n\t\t\t * Deal with a hole that doesn't have an extent item\n\t\t\t * that represents it (NO_HOLES feature enabled).\n\t\t\t * This hole is either in the middle of the cloning\n\t\t\t * range or at the beginning (fully overlaps it or\n\t\t\t * partially overlaps it).\n\t\t\t */\n\t\t\tif (new_key.offset != last_dest_end)\n\t\t\t\tdrop_start = last_dest_end;\n\t\t\telse\n\t\t\t\tdrop_start = new_key.offset;\n\n\t\t\t/*\n\t\t\t * 1 - adjusting old extent (we may have to split it)\n\t\t\t * 1 - add new extent\n\t\t\t * 1 - inode update\n\t\t\t */\n\t\t\ttrans = btrfs_start_transaction(root, 3);\n\t\t\tif (IS_ERR(trans)) {\n\t\t\t\tret = PTR_ERR(trans);\n\t\t\t\tgoto out;\n\t\t\t}\n\n\t\t\tif (type == BTRFS_FILE_EXTENT_REG ||\n\t\t\t type == BTRFS_FILE_EXTENT_PREALLOC) {\n\t\t\t\t/*\n\t\t\t\t * a | --- range to clone ---| b\n\t\t\t\t * | ------------- extent ------------- |\n\t\t\t\t */\n\n\t\t\t\t/* subtract range b */\n\t\t\t\tif (key.offset + datal > off + len)\n\t\t\t\t\tdatal = off + len - key.offset;\n\n\t\t\t\t/* subtract range a */\n\t\t\t\tif (off > key.offset) {\n\t\t\t\t\tdatao += off - key.offset;\n\t\t\t\t\tdatal -= off - key.offset;\n\t\t\t\t}\n\n\t\t\t\tret = btrfs_drop_extents(trans, root, inode,\n\t\t\t\t\t\t\t drop_start,\n\t\t\t\t\t\t\t new_key.offset + datal,\n\t\t\t\t\t\t\t 1);\n\t\t\t\tif (ret) {\n\t\t\t\t\tif (ret != -EOPNOTSUPP)\n\t\t\t\t\t\tbtrfs_abort_transaction(trans,\n\t\t\t\t\t\t\t\troot, ret);\n\t\t\t\t\tbtrfs_end_transaction(trans, root);\n\t\t\t\t\tgoto out;\n\t\t\t\t}\n\n\t\t\t\tret = btrfs_insert_empty_item(trans, root, path,\n\t\t\t\t\t\t\t &new_key, size);\n\t\t\t\tif (ret) {\n\t\t\t\t\tbtrfs_abort_transaction(trans, root,\n\t\t\t\t\t\t\t\tret);\n\t\t\t\t\tbtrfs_end_transaction(trans, root);\n\t\t\t\t\tgoto out;\n\t\t\t\t}\n\n\t\t\t\tleaf = path->nodes[0];\n\t\t\t\tslot = path->slots[0];\n\t\t\t\twrite_extent_buffer(leaf, buf,\n\t\t\t\t\t btrfs_item_ptr_offset(leaf, slot),\n\t\t\t\t\t size);\n\n\t\t\t\textent = btrfs_item_ptr(leaf, slot,\n\t\t\t\t\t\tstruct btrfs_file_extent_item);\n\n\t\t\t\t/* disko == 0 means it's a hole */\n\t\t\t\tif (!disko)\n\t\t\t\t\tdatao = 0;\n\n\t\t\t\tbtrfs_set_file_extent_offset(leaf, extent,\n\t\t\t\t\t\t\t datao);\n\t\t\t\tbtrfs_set_file_extent_num_bytes(leaf, extent,\n\t\t\t\t\t\t\t\tdatal);\n\n\t\t\t\t/*\n\t\t\t\t * We need to look up the roots that point at\n\t\t\t\t * this bytenr and see if the new root does. If\n\t\t\t\t * it does not we need to make sure we update\n\t\t\t\t * quotas appropriately.\n\t\t\t\t */\n\t\t\t\tif (disko && root != BTRFS_I(src)->root &&\n\t\t\t\t disko != last_disko) {\n\t\t\t\t\tno_quota = check_ref(trans, root,\n\t\t\t\t\t\t\t disko);\n\t\t\t\t\tif (no_quota < 0) {\n\t\t\t\t\t\tbtrfs_abort_transaction(trans,\n\t\t\t\t\t\t\t\t\troot,\n\t\t\t\t\t\t\t\t\tret);\n\t\t\t\t\t\tbtrfs_end_transaction(trans,\n\t\t\t\t\t\t\t\t root);\n\t\t\t\t\t\tret = no_quota;\n\t\t\t\t\t\tgoto out;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (disko) {\n\t\t\t\t\tinode_add_bytes(inode, datal);\n\t\t\t\t\tret = btrfs_inc_extent_ref(trans, root,\n\t\t\t\t\t\t\tdisko, diskl, 0,\n\t\t\t\t\t\t\troot->root_key.objectid,\n\t\t\t\t\t\t\tbtrfs_ino(inode),\n\t\t\t\t\t\t\tnew_key.offset - datao,\n\t\t\t\t\t\t\tno_quota);\n\t\t\t\t\tif (ret) {\n\t\t\t\t\t\tbtrfs_abort_transaction(trans,\n\t\t\t\t\t\t\t\t\troot,\n\t\t\t\t\t\t\t\t\tret);\n\t\t\t\t\t\tbtrfs_end_transaction(trans,\n\t\t\t\t\t\t\t\t root);\n\t\t\t\t\t\tgoto out;\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (type == BTRFS_FILE_EXTENT_INLINE) {\n\t\t\t\tu64 skip = 0;\n\t\t\t\tu64 trim = 0;\n\t\t\t\tu64 aligned_end = 0;\n\n\t\t\t\t/*\n\t\t\t\t * Don't copy an inline extent into an offset\n\t\t\t\t * greater than zero. Having an inline extent\n\t\t\t\t * at such an offset results in chaos as btrfs\n\t\t\t\t * isn't prepared for such cases. Just skip\n\t\t\t\t * this case for the same reasons as commented\n\t\t\t\t * at btrfs_ioctl_clone().\n\t\t\t\t */\n\t\t\t\tif (last_dest_end > 0) {\n\t\t\t\t\tret = -EOPNOTSUPP;\n\t\t\t\t\tbtrfs_end_transaction(trans, root);\n\t\t\t\t\tgoto out;\n\t\t\t\t}\n\n\t\t\t\tif (off > key.offset) {\n\t\t\t\t\tskip = off - key.offset;\n\t\t\t\t\tnew_key.offset += skip;\n\t\t\t\t}\n\n\t\t\t\tif (key.offset + datal > off + len)\n\t\t\t\t\ttrim = key.offset + datal - (off + len);\n\n\t\t\t\tif (comp && (skip || trim)) {\n\t\t\t\t\tret = -EINVAL;\n\t\t\t\t\tbtrfs_end_transaction(trans, root);\n\t\t\t\t\tgoto out;\n\t\t\t\t}\n\t\t\t\tsize -= skip + trim;\n\t\t\t\tdatal -= skip + trim;\n\n\t\t\t\taligned_end = ALIGN(new_key.offset + datal,\n\t\t\t\t\t\t root->sectorsize);\n\t\t\t\tret = btrfs_drop_extents(trans, root, inode,\n\t\t\t\t\t\t\t drop_start,\n\t\t\t\t\t\t\t aligned_end,\n\t\t\t\t\t\t\t 1);\n\t\t\t\tif (ret) {\n\t\t\t\t\tif (ret != -EOPNOTSUPP)\n\t\t\t\t\t\tbtrfs_abort_transaction(trans,\n\t\t\t\t\t\t\troot, ret);\n\t\t\t\t\tbtrfs_end_transaction(trans, root);\n\t\t\t\t\tgoto out;\n\t\t\t\t}\n\n\t\t\t\tret = btrfs_insert_empty_item(trans, root, path,\n\t\t\t\t\t\t\t &new_key, size);\n\t\t\t\tif (ret) {\n\t\t\t\t\tbtrfs_abort_transaction(trans, root,\n\t\t\t\t\t\t\t\tret);\n\t\t\t\t\tbtrfs_end_transaction(trans, root);\n\t\t\t\t\tgoto out;\n\t\t\t\t}\n\n\t\t\t\tif (skip) {\n\t\t\t\t\tu32 start =\n\t\t\t\t\t btrfs_file_extent_calc_inline_size(0);\n\t\t\t\t\tmemmove(buf+start, buf+start+skip,\n\t\t\t\t\t\tdatal);\n\t\t\t\t}\n\n\t\t\t\tleaf = path->nodes[0];\n\t\t\t\tslot = path->slots[0];\n\t\t\t\twrite_extent_buffer(leaf, buf,\n\t\t\t\t\t btrfs_item_ptr_offset(leaf, slot),\n\t\t\t\t\t size);\n\t\t\t\tinode_add_bytes(inode, datal);\n\t\t\t}\n\n\t\t\t/* If we have an implicit hole (NO_HOLES feature). */\n\t\t\tif (drop_start < new_key.offset)\n\t\t\t\tclone_update_extent_map(inode, trans,\n\t\t\t\t\t\tNULL, drop_start,\n\t\t\t\t\t\tnew_key.offset - drop_start);\n\n\t\t\tclone_update_extent_map(inode, trans, path, 0, 0);\n\n\t\t\tbtrfs_mark_buffer_dirty(leaf);\n\t\t\tbtrfs_release_path(path);\n\n\t\t\tlast_dest_end = ALIGN(new_key.offset + datal,\n\t\t\t\t\t root->sectorsize);\n\t\t\tret = clone_finish_inode_update(trans, inode,\n\t\t\t\t\t\t\tlast_dest_end,\n\t\t\t\t\t\t\tdestoff, olen,\n\t\t\t\t\t\t\tno_time_update);\n\t\t\tif (ret)\n\t\t\t\tgoto out;\n\t\t\tif (new_key.offset + datal >= destoff + len)\n\t\t\t\tbreak;\n\t\t}\n\t\tbtrfs_release_path(path);\n\t\tkey.offset = next_key_min_offset;\n\t}\n\tret = 0;\n\n\tif (last_dest_end < destoff + len) {\n\t\t/*\n\t\t * We have an implicit hole (NO_HOLES feature is enabled) that\n\t\t * fully or partially overlaps our cloning range at its end.\n\t\t */\n\t\tbtrfs_release_path(path);\n\n\t\t/*\n\t\t * 1 - remove extent(s)\n\t\t * 1 - inode update\n\t\t */\n\t\ttrans = btrfs_start_transaction(root, 2);\n\t\tif (IS_ERR(trans)) {\n\t\t\tret = PTR_ERR(trans);\n\t\t\tgoto out;\n\t\t}\n\t\tret = btrfs_drop_extents(trans, root, inode,\n\t\t\t\t\t last_dest_end, destoff + len, 1);\n\t\tif (ret) {\n\t\t\tif (ret != -EOPNOTSUPP)\n\t\t\t\tbtrfs_abort_transaction(trans, root, ret);\n\t\t\tbtrfs_end_transaction(trans, root);\n\t\t\tgoto out;\n\t\t}\n\t\tclone_update_extent_map(inode, trans, NULL, last_dest_end,\n\t\t\t\t\tdestoff + len - last_dest_end);\n\t\tret = clone_finish_inode_update(trans, inode, destoff + len,\n\t\t\t\t\t\tdestoff, olen, no_time_update);\n\t}\n\nout:\n\tbtrfs_free_path(path);\n\tvfree(buf);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Btrfs: fix file corruption and data loss after cloning inline extents\n\nCurrently the clone ioctl allows to clone an inline extent from one file\nto another that already has other (non-inlined) extents. This is a problem\nbecause btrfs is not designed to deal with files having inline and regular\nextents, if a file has an inline extent then it must be the only extent\nin the file and must start at file offset 0. Having a file with an inline\nextent followed by regular extents results in EIO errors when doing reads\nor writes against the first 4K of the file.\n\nAlso, the clone ioctl allows one to lose data if the source file consists\nof a single inline extent, with a size of N bytes, and the destination\nfile consists of a single inline extent with a size of M bytes, where we\nhave M > N. In this case the clone operation removes the inline extent\nfrom the destination file and then copies the inline extent from the\nsource file into the destination file - we lose the M - N bytes from the\ndestination file, a read operation will get the value 0x00 for any bytes\nin the the range [N, M] (the destination inode's i_size remained as M,\nthat's why we can read past N bytes).\n\nSo fix this by not allowing such destructive operations to happen and\nreturn errno EOPNOTSUPP to user space.\n\nCurrently the fstest btrfs/035 tests the data loss case but it totally\nignores this - i.e. expects the operation to succeed and does not check\nthe we got data loss.\n\nThe following test case for fstests exercises all these cases that result\nin file corruption and data loss:\n\n seq=`basename $0`\n seqres=$RESULT_DIR/$seq\n echo \"QA output created by $seq\"\n tmp=/tmp/$$\n status=1\t# failure is the default!\n trap \"_cleanup; exit \\$status\" 0 1 2 3 15\n\n _cleanup()\n {\n rm -f $tmp.*\n }\n\n # get standard environment, filters and checks\n . ./common/rc\n . ./common/filter\n\n # real QA test starts here\n _need_to_be_root\n _supported_fs btrfs\n _supported_os Linux\n _require_scratch\n _require_cloner\n _require_btrfs_fs_feature \"no_holes\"\n _require_btrfs_mkfs_feature \"no-holes\"\n\n rm -f $seqres.full\n\n test_cloning_inline_extents()\n {\n local mkfs_opts=$1\n local mount_opts=$2\n\n _scratch_mkfs $mkfs_opts >>$seqres.full 2>&1\n _scratch_mount $mount_opts\n\n # File bar, the source for all the following clone operations, consists\n # of a single inline extent (50 bytes).\n $XFS_IO_PROG -f -c \"pwrite -S 0xbb 0 50\" $SCRATCH_MNT/bar \\\n | _filter_xfs_io\n\n # Test cloning into a file with an extent (non-inlined) where the\n # destination offset overlaps that extent. It should not be possible to\n # clone the inline extent from file bar into this file.\n $XFS_IO_PROG -f -c \"pwrite -S 0xaa 0K 16K\" $SCRATCH_MNT/foo \\\n | _filter_xfs_io\n $CLONER_PROG -s 0 -d 0 -l 0 $SCRATCH_MNT/bar $SCRATCH_MNT/foo\n\n # Doing IO against any range in the first 4K of the file should work.\n # Due to a past clone ioctl bug which allowed cloning the inline extent,\n # these operations resulted in EIO errors.\n echo \"File foo data after clone operation:\"\n # All bytes should have the value 0xaa (clone operation failed and did\n # not modify our file).\n od -t x1 $SCRATCH_MNT/foo\n $XFS_IO_PROG -c \"pwrite -S 0xcc 0 100\" $SCRATCH_MNT/foo | _filter_xfs_io\n\n # Test cloning the inline extent against a file which has a hole in its\n # first 4K followed by a non-inlined extent. It should not be possible\n # as well to clone the inline extent from file bar into this file.\n $XFS_IO_PROG -f -c \"pwrite -S 0xdd 4K 12K\" $SCRATCH_MNT/foo2 \\\n | _filter_xfs_io\n $CLONER_PROG -s 0 -d 0 -l 0 $SCRATCH_MNT/bar $SCRATCH_MNT/foo2\n\n # Doing IO against any range in the first 4K of the file should work.\n # Due to a past clone ioctl bug which allowed cloning the inline extent,\n # these operations resulted in EIO errors.\n echo \"File foo2 data after clone operation:\"\n # All bytes should have the value 0x00 (clone operation failed and did\n # not modify our file).\n od -t x1 $SCRATCH_MNT/foo2\n $XFS_IO_PROG -c \"pwrite -S 0xee 0 90\" $SCRATCH_MNT/foo2 | _filter_xfs_io\n\n # Test cloning the inline extent against a file which has a size of zero\n # but has a prealloc extent. It should not be possible as well to clone\n # the inline extent from file bar into this file.\n $XFS_IO_PROG -f -c \"falloc -k 0 1M\" $SCRATCH_MNT/foo3 | _filter_xfs_io\n $CLONER_PROG -s 0 -d 0 -l 0 $SCRATCH_MNT/bar $SCRATCH_MNT/foo3\n\n # Doing IO against any range in the first 4K of the file should work.\n # Due to a past clone ioctl bug which allowed cloning the inline extent,\n # these operations resulted in EIO errors.\n echo \"First 50 bytes of foo3 after clone operation:\"\n # Should not be able to read any bytes, file has 0 bytes i_size (the\n # clone operation failed and did not modify our file).\n od -t x1 $SCRATCH_MNT/foo3\n $XFS_IO_PROG -c \"pwrite -S 0xff 0 90\" $SCRATCH_MNT/foo3 | _filter_xfs_io\n\n # Test cloning the inline extent against a file which consists of a\n # single inline extent that has a size not greater than the size of\n # bar's inline extent (40 < 50).\n # It should be possible to do the extent cloning from bar to this file.\n $XFS_IO_PROG -f -c \"pwrite -S 0x01 0 40\" $SCRATCH_MNT/foo4 \\\n | _filter_xfs_io\n $CLONER_PROG -s 0 -d 0 -l 0 $SCRATCH_MNT/bar $SCRATCH_MNT/foo4\n\n # Doing IO against any range in the first 4K of the file should work.\n echo \"File foo4 data after clone operation:\"\n # Must match file bar's content.\n od -t x1 $SCRATCH_MNT/foo4\n $XFS_IO_PROG -c \"pwrite -S 0x02 0 90\" $SCRATCH_MNT/foo4 | _filter_xfs_io\n\n # Test cloning the inline extent against a file which consists of a\n # single inline extent that has a size greater than the size of bar's\n # inline extent (60 > 50).\n # It should not be possible to clone the inline extent from file bar\n # into this file.\n $XFS_IO_PROG -f -c \"pwrite -S 0x03 0 60\" $SCRATCH_MNT/foo5 \\\n | _filter_xfs_io\n $CLONER_PROG -s 0 -d 0 -l 0 $SCRATCH_MNT/bar $SCRATCH_MNT/foo5\n\n # Reading the file should not fail.\n echo \"File foo5 data after clone operation:\"\n # Must have a size of 60 bytes, with all bytes having a value of 0x03\n # (the clone operation failed and did not modify our file).\n od -t x1 $SCRATCH_MNT/foo5\n\n # Test cloning the inline extent against a file which has no extents but\n # has a size greater than bar's inline extent (16K > 50).\n # It should not be possible to clone the inline extent from file bar\n # into this file.\n $XFS_IO_PROG -f -c \"truncate 16K\" $SCRATCH_MNT/foo6 | _filter_xfs_io\n $CLONER_PROG -s 0 -d 0 -l 0 $SCRATCH_MNT/bar $SCRATCH_MNT/foo6\n\n # Reading the file should not fail.\n echo \"File foo6 data after clone operation:\"\n # Must have a size of 16K, with all bytes having a value of 0x00 (the\n # clone operation failed and did not modify our file).\n od -t x1 $SCRATCH_MNT/foo6\n\n # Test cloning the inline extent against a file which has no extents but\n # has a size not greater than bar's inline extent (30 < 50).\n # It should be possible to clone the inline extent from file bar into\n # this file.\n $XFS_IO_PROG -f -c \"truncate 30\" $SCRATCH_MNT/foo7 | _filter_xfs_io\n $CLONER_PROG -s 0 -d 0 -l 0 $SCRATCH_MNT/bar $SCRATCH_MNT/foo7\n\n # Reading the file should not fail.\n echo \"File foo7 data after clone operation:\"\n # Must have a size of 50 bytes, with all bytes having a value of 0xbb.\n od -t x1 $SCRATCH_MNT/foo7\n\n # Test cloning the inline extent against a file which has a size not\n # greater than the size of bar's inline extent (20 < 50) but has\n # a prealloc extent that goes beyond the file's size. It should not be\n # possible to clone the inline extent from bar into this file.\n $XFS_IO_PROG -f -c \"falloc -k 0 1M\" \\\n -c \"pwrite -S 0x88 0 20\" \\\n $SCRATCH_MNT/foo8 | _filter_xfs_io\n $CLONER_PROG -s 0 -d 0 -l 0 $SCRATCH_MNT/bar $SCRATCH_MNT/foo8\n\n echo \"File foo8 data after clone operation:\"\n # Must have a size of 20 bytes, with all bytes having a value of 0x88\n # (the clone operation did not modify our file).\n od -t x1 $SCRATCH_MNT/foo8\n\n _scratch_unmount\n }\n\n echo -e \"\\nTesting without compression and without the no-holes feature...\\n\"\n test_cloning_inline_extents\n\n echo -e \"\\nTesting with compression and without the no-holes feature...\\n\"\n test_cloning_inline_extents \"\" \"-o compress\"\n\n echo -e \"\\nTesting without compression and with the no-holes feature...\\n\"\n test_cloning_inline_extents \"-O no-holes\" \"\"\n\n echo -e \"\\nTesting with compression and with the no-holes feature...\\n\"\n test_cloning_inline_extents \"-O no-holes\" \"-o compress\"\n\n status=0\n exit\n\nCc: stable@vger.kernel.org\nSigned-off-by: Filipe Manana '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static bool decode_openldap_dereference(void *mem_ctx, DATA_BLOB in, void *_out)\n{\n\tvoid **out = (void **)_out;\n\tstruct asn1_data *data = asn1_init(mem_ctx);\n\tstruct dsdb_openldap_dereference_result_control *control;\n\tstruct dsdb_openldap_dereference_result **r = NULL;\n\tint i = 0;\n\tif (!data) return false;\n\n\tcontrol = talloc(mem_ctx, struct dsdb_openldap_dereference_result_control);\n\tif (!control) return false;\n\n\tif (!asn1_load(data, in)) {\n\t\treturn false;\n\t}\n\n\tcontrol = talloc(mem_ctx, struct dsdb_openldap_dereference_result_control);\n\tif (!control) {\n\t\treturn false;\n\t}\n\n\tif (!asn1_start_tag(data, ASN1_SEQUENCE(0))) {\n\t\treturn false;\n\t}\n\n\twhile (asn1_tag_remaining(data) > 0) {\t\t\t\t\t\n\t\tr = talloc_realloc(control, r, struct dsdb_openldap_dereference_result *, i + 2);\n\t\tif (!r) {\n\t\t\treturn false;\n\t\t}\n\t\tr[i] = talloc_zero(r, struct dsdb_openldap_dereference_result);\n\t\tif (!r[i]) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (!asn1_start_tag(data, ASN1_SEQUENCE(0))) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tasn1_read_OctetString_talloc(r[i], data, &r[i]->source_attribute);\n\t\tasn1_read_OctetString_talloc(r[i], data, &r[i]->dereferenced_dn);\n\t\tif (asn1_peek_tag(data, ASN1_CONTEXT(0))) {\n\t\t\tif (!asn1_start_tag(data, ASN1_CONTEXT(0))) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\tldap_decode_attribs_bare(r, data, &r[i]->attributes,\n\t\t\t\t\t\t &r[i]->num_attributes);\n\t\t\t\n\t\t\tif (!asn1_end_tag(data)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tif (!asn1_end_tag(data)) {\n\t\t\treturn false;\n\t\t}\n\t\ti++;\n\t\tr[i] = NULL;\n\t}\n\n\tif (!asn1_end_tag(data)) {\n\t\treturn false;\n\t}\n\n\tcontrol->attributes = r;\n\t*out = control;\n\n\treturn true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-7540: s4: libcli: ldap message - Ensure all asn1_XX returns are checked.\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=9187\n\nSigned-off-by: Jeremy Allison \nReviewed-by: Ronnie Sahlberg \n\nAutobuild-User(master): Jeremy Allison \nAutobuild-Date(master): Fri Sep 26 03:15:00 CEST 2014 on sn-devel-104\n\n(cherry picked from commit 69a7e3cfdc8dbba9c8dcfdfae82d2894c7247e15)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool asn1_check_BOOLEAN(struct asn1_data *data, bool v)\n{\n\tuint8_t b = 0;\n\n\tasn1_read_uint8(data, &b);\n\tif (b != ASN1_BOOLEAN) {\n\t\tdata->has_error = true;\n\t\treturn false;\n\t}\n\tasn1_read_uint8(data, &b);\n\tif (b != v) {\n\t\tdata->has_error = true;\n\t\treturn false;\n\t}\n\treturn !data->has_error;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-7540: lib: util: Check *every* asn1 return call and early return.\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=9187\n\nSigned-off-by: Jeremy Allison \nReviewed-by: Volker Lendecke \n\nAutobuild-User(master): Jeremy Allison \nAutobuild-Date(master): Fri Sep 19 01:29:00 CEST 2014 on sn-devel-104\n\n(cherry picked from commit b9d3fd4cc551df78a7b066ee8ce43bbaa3ff994a)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool asn1_read_BOOLEAN(struct asn1_data *data, bool *v)\n{\n\tuint8_t tmp = 0;\n\tasn1_start_tag(data, ASN1_BOOLEAN);\n\tasn1_read_uint8(data, &tmp);\n\tif (tmp == 0xFF) {\n\t\t*v = true;\n\t} else {\n\t\t*v = false;\n\t}\n\tasn1_end_tag(data);\n\treturn !data->has_error;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-7540: lib: util: Check *every* asn1 return call and early return.\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=9187\n\nSigned-off-by: Jeremy Allison \nReviewed-by: Volker Lendecke \n\nAutobuild-User(master): Jeremy Allison \nAutobuild-Date(master): Fri Sep 19 01:29:00 CEST 2014 on sn-devel-104\n\n(cherry picked from commit b9d3fd4cc551df78a7b066ee8ce43bbaa3ff994a)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: NTSTATUS smb2cli_session_encryption_on(struct smbXcli_session *session)\n{\n\tif (session->smb2->should_encrypt) {\n\t\treturn NT_STATUS_OK;\n\t}\n\n\tif (session->conn->protocol < PROTOCOL_SMB2_24) {\n\t\treturn NT_STATUS_NOT_SUPPORTED;\n\t}\n\n\tif (session->conn->smb2.server.cipher == 0) {\n\t\treturn NT_STATUS_NOT_SUPPORTED;\n\t}\n\n\tif (session->smb2->signing_key.data == NULL) {\n\t\treturn NT_STATUS_NOT_SUPPORTED;\n\t}\n\tsession->smb2->should_encrypt = true;\n\treturn NT_STATUS_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'CVE-2015-5296: libcli/smb: make sure we require signing when we demand encryption on a session\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=11536\n\nSigned-off-by: Stefan Metzmacher \nReviewed-by: Jeremy Allison '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int pptp_bind(struct socket *sock, struct sockaddr *uservaddr,\n\tint sockaddr_len)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct sockaddr_pppox *sp = (struct sockaddr_pppox *) uservaddr;\n\tstruct pppox_sock *po = pppox_sk(sk);\n\tstruct pptp_opt *opt = &po->proto.pptp;\n\tint error = 0;\n\n\tlock_sock(sk);\n\n\topt->src_addr = sp->sa_addr.pptp;\n\tif (add_chan(po))\n\t\terror = -EBUSY;\n\n\trelease_sock(sk);\n\treturn error;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'pptp: verify sockaddr_len in pptp_bind() and pptp_connect()\n\nReported-by: Dmitry Vyukov \nSigned-off-by: Cong Wang \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int client_run(int f_in, int f_out, pid_t pid, int argc, char *argv[])\n{\n\tstruct file_list *flist = NULL;\n\tint exit_code = 0, exit_code2 = 0;\n\tchar *local_name = NULL;\n\n\tcleanup_child_pid = pid;\n\tif (!read_batch) {\n\t\tset_nonblocking(f_in);\n\t\tset_nonblocking(f_out);\n\t}\n\n\tio_set_sock_fds(f_in, f_out);\n\tsetup_protocol(f_out,f_in);\n\n\t/* We set our stderr file handle to blocking because ssh might have\n\t * set it to non-blocking. This can be particularly troublesome if\n\t * stderr is a clone of stdout, because ssh would have set our stdout\n\t * to non-blocking at the same time (which can easily cause us to lose\n\t * output from our print statements). This kluge shouldn't cause ssh\n\t * any problems for how we use it. Note also that we delayed setting\n\t * this until after the above protocol setup so that we know for sure\n\t * that ssh is done twiddling its file descriptors. */\n\tset_blocking(STDERR_FILENO);\n\n\tif (am_sender) {\n\t\tkeep_dirlinks = 0; /* Must be disabled on the sender. */\n\n\t\tif (always_checksum\n\t\t && (log_format_has(stdout_format, 'C')\n\t\t || log_format_has(logfile_format, 'C')))\n\t\t\tsender_keeps_checksum = 1;\n\n\t\tif (protocol_version >= 30)\n\t\t\tio_start_multiplex_out(f_out);\n\t\telse\n\t\t\tio_start_buffering_out(f_out);\n\t\tif (protocol_version >= 31 || (!filesfrom_host && protocol_version >= 23))\n\t\t\tio_start_multiplex_in(f_in);\n\t\telse\n\t\t\tio_start_buffering_in(f_in);\n\t\tsend_filter_list(f_out);\n\t\tif (filesfrom_host)\n\t\t\tfilesfrom_fd = f_in;\n\n\t\tif (write_batch && !am_server)\n\t\t\tstart_write_batch(f_out);\n\t\tflist = send_file_list(f_out, argc, argv);\n\t\tif (DEBUG_GTE(FLIST, 3))\n\t\t\trprintf(FINFO,\"file list sent\\n\");\n\n\t\tif (protocol_version < 31 && filesfrom_host && protocol_version >= 23)\n\t\t\tio_start_multiplex_in(f_in);\n\n\t\tio_flush(NORMAL_FLUSH);\n\t\tsend_files(f_in, f_out);\n\t\tio_flush(FULL_FLUSH);\n\t\thandle_stats(-1);\n\t\tif (protocol_version >= 24)\n\t\t\tread_final_goodbye(f_in, f_out);\n\t\tif (pid != -1) {\n\t\t\tif (DEBUG_GTE(EXIT, 2))\n\t\t\t\trprintf(FINFO,\"client_run waiting on %d\\n\", (int) pid);\n\t\t\tio_flush(FULL_FLUSH);\n\t\t\twait_process_with_flush(pid, &exit_code);\n\t\t}\n\t\toutput_summary();\n\t\tio_flush(FULL_FLUSH);\n\t\texit_cleanup(exit_code);\n\t}\n\n\tif (!read_batch) {\n\t\tif (protocol_version >= 23)\n\t\t\tio_start_multiplex_in(f_in);\n\t\tif (need_messages_from_generator)\n\t\t\tio_start_multiplex_out(f_out);\n\t\telse\n\t\t\tio_start_buffering_out(f_out);\n\t}\n\n\tsend_filter_list(read_batch ? -1 : f_out);\n\n\tif (filesfrom_fd >= 0) {\n\t\tstart_filesfrom_forwarding(filesfrom_fd);\n\t\tfilesfrom_fd = -1;\n\t}\n\n\tif (write_batch && !am_server)\n\t\tstart_write_batch(f_in);\n\tflist = recv_file_list(f_in);\n\tif (inc_recurse && file_total == 1)\n\t\trecv_additional_file_list(f_in);\n\n\tif (flist && flist->used > 0) {\n\t\tlocal_name = get_local_name(flist, argv[0]);\n\n\t\tcheck_alt_basis_dirs();\n\n\t\texit_code2 = do_recv(f_in, f_out, local_name);\n\t} else {\n\t\thandle_stats(-1);\n\t\toutput_summary();\n\t}\n\n\tif (pid != -1) {\n\t\tif (DEBUG_GTE(RECV, 1))\n\t\t\trprintf(FINFO,\"client_run2 waiting on %d\\n\", (int) pid);\n\t\tio_flush(FULL_FLUSH);\n\t\twait_process_with_flush(pid, &exit_code);\n\t}\n\n\treturn MAX(exit_code, exit_code2);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59'], 'message': 'Complain if an inc-recursive path is not right for its dir.\nThis ensures that a malicious sender can't use a just-sent\nsymlink as a trasnfer path.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int clie_5_attach(struct usb_serial *serial)\n{\n\tstruct usb_serial_port *port;\n\tunsigned int pipe;\n\tint j;\n\n\t/* TH55 registers 2 ports.\n\t Communication in from the UX50/TH55 uses bulk_in_endpointAddress\n\t from port 0. Communication out to the UX50/TH55 uses\n\t bulk_out_endpointAddress from port 1\n\n\t Lets do a quick and dirty mapping\n\t */\n\n\t/* some sanity check */\n\tif (serial->num_ports < 2)\n\t\treturn -1;\n\n\t/* port 0 now uses the modified endpoint Address */\n\tport = serial->port[0];\n\tport->bulk_out_endpointAddress =\n\t\t\t\tserial->port[1]->bulk_out_endpointAddress;\n\n\tpipe = usb_sndbulkpipe(serial->dev, port->bulk_out_endpointAddress);\n\tfor (j = 0; j < ARRAY_SIZE(port->write_urbs); ++j)\n\t\tport->write_urbs[j]->pipe = pipe;\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'USB: serial: visor: fix crash on detecting device without write_urbs\n\nThe visor driver crashes in clie_5_attach() when a specially crafted USB\ndevice without bulk-out endpoint is detected. This fix adds a check that\nthe device has proper configuration expected by the driver.\n\nReported-by: Ralf Spenneberg \nSigned-off-by: Vladis Dronov \nFixes: cfb8da8f69b8 (\"USB: visor: fix initialisation of UX50/TH55 devices\")\nCc: stable \nSigned-off-by: Johan Hovold '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: authusekey(\n\tkeyid_t keyno,\n\tint keytype,\n\tconst u_char *str\n\t)\n{\n\tsize_t\tlen;\n\n\tlen = strlen((const char *)str);\n\tif (0 == len)\n\t\treturn 0;\n\n\tMD5auth_setkey(keyno, keytype, str, len);\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-287'], 'message': '[Sec 2936] Skeleton Key: Any trusted key system can serve time. HStenn.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: save_config(\n\tstruct recvbuf *rbufp,\n\tint restrict_mask\n\t)\n{\n#ifdef SAVECONFIG\n\tstatic const char savedconfig_eq[] = \"savedconfig=\";\n\t\n\tchar filespec[128];\n\tchar filename[128];\n\tchar fullpath[512];\n\tchar savedconfig[sizeof(savedconfig_eq) + sizeof(filename)];\n\ttime_t now;\n\tint fd;\n\tFILE *fptr;\n\tint prc;\n\tsize_t reqlen;\n#endif\n\n\tif (RES_NOMODIFY & restrict_mask) {\n\t\tctl_printf(\"%s\", \"saveconfig prohibited by restrict ... nomodify\");\n\t\tctl_flushpkt(0);\n\t\tNLOG(NLOG_SYSINFO)\n\t\t\tmsyslog(LOG_NOTICE,\n\t\t\t\t\"saveconfig from %s rejected due to nomodify restriction\",\n\t\t\t\tstoa(&rbufp->recv_srcadr));\n\t\tsys_restricted++;\n\t\treturn;\n\t}\n\n#ifdef SAVECONFIG\n\tif (NULL == saveconfigdir) {\n\t\tctl_printf(\"%s\", \"saveconfig prohibited, no saveconfigdir configured\");\n\t\tctl_flushpkt(0);\n\t\tNLOG(NLOG_SYSINFO)\n\t\t\tmsyslog(LOG_NOTICE,\n\t\t\t\t\"saveconfig from %s rejected, no saveconfigdir\",\n\t\t\t\tstoa(&rbufp->recv_srcadr));\n\t\treturn;\n\t}\n\n\t/* The length checking stuff gets serious. Do not assume a NUL\n\t * byte can be found, but if so, use it to calculate the needed\n\t * buffer size. If the available buffer is too short, bail out;\n\t * likewise if there is no file spec. (The latter will not\n\t * happen when using NTPQ, but there are other ways to craft a\n\t * network packet!)\n\t */\n\treqlen = (size_t)(reqend - reqpt);\n\tif (0 != reqlen) {\n\t\tchar * nulpos = (char*)memchr(reqpt, 0, reqlen);\n\t\tif (NULL != nulpos)\n\t\t\treqlen = (size_t)(nulpos - reqpt);\n\t}\n\tif (0 == reqlen)\n\t\treturn;\n\tif (reqlen >= sizeof(filespec)) {\n\t\tctl_printf(\"saveconfig exceeded maximum raw name length (%u)\",\n\t\t\t (u_int)sizeof(filespec));\n\t\tctl_flushpkt(0);\n\t\tmsyslog(LOG_NOTICE,\n\t\t\t\"saveconfig exceeded maximum raw name length from %s\",\n\t\t\tstoa(&rbufp->recv_srcadr));\n\t\treturn;\n\t}\n\n\t/* copy data directly as we exactly know the size */\n\tmemcpy(filespec, reqpt, reqlen);\n\tfilespec[reqlen] = '\\0';\n\t\n\t/*\n\t * allow timestamping of the saved config filename with\n\t * strftime() format such as:\n\t * ntpq -c \"saveconfig ntp-%Y%m%d-%H%M%S.conf\"\n\t * XXX: Nice feature, but not too safe.\n\t * YYY: The check for permitted characters in file names should\n\t * weed out the worst. Let's hope 'strftime()' does not\n\t * develop pathological problems.\n\t */\n\ttime(&now);\n\tif (0 == strftime(filename, sizeof(filename), filespec,\n\t\t\t localtime(&now)))\n\t{\n\t\t/*\n\t\t * If we arrive here, 'strftime()' balked; most likely\n\t\t * the buffer was too short. (Or it encounterd an empty\n\t\t * format, or just a format that expands to an empty\n\t\t * string.) We try to use the original name, though this\n\t\t * is very likely to fail later if there are format\n\t\t * specs in the string. Note that truncation cannot\n\t\t * happen here as long as both buffers have the same\n\t\t * size!\n\t\t */\n\t\tstrlcpy(filename, filespec, sizeof(filename));\n\t}\n\n\t/*\n\t * Check the file name for sanity. This migth/will rule out file\n\t * names that would be legal but problematic, and it blocks\n\t * directory traversal.\n\t */\n\tif (!is_safe_filename(filename)) {\n\t\tctl_printf(\"saveconfig rejects unsafe file name '%s'\",\n\t\t\t filename);\n\t\tctl_flushpkt(0);\n\t\tmsyslog(LOG_NOTICE,\n\t\t\t\"saveconfig rejects unsafe file name from %s\",\n\t\t\tstoa(&rbufp->recv_srcadr));\n\t\treturn;\n\t}\n\n\t/* concatenation of directory and path can cause another\n\t * truncation...\n\t */\n\tprc = snprintf(fullpath, sizeof(fullpath), \"%s%s\",\n\t\t saveconfigdir, filename);\n\tif (prc < 0 || prc >= sizeof(fullpath)) {\n\t\tctl_printf(\"saveconfig exceeded maximum path length (%u)\",\n\t\t\t (u_int)sizeof(fullpath));\n\t\tctl_flushpkt(0);\n\t\tmsyslog(LOG_NOTICE,\n\t\t\t\"saveconfig exceeded maximum path length from %s\",\n\t\t\tstoa(&rbufp->recv_srcadr));\n\t\treturn;\n\t}\n\n\tfd = open(fullpath, O_CREAT | O_TRUNC | O_WRONLY,\n\t\t S_IRUSR | S_IWUSR);\n\tif (-1 == fd)\n\t\tfptr = NULL;\n\telse\n\t\tfptr = fdopen(fd, \"w\");\n\n\tif (NULL == fptr || -1 == dump_all_config_trees(fptr, 1)) {\n\t\tctl_printf(\"Unable to save configuration to file '%s'\",\n\t\t\t filename);\n\t\tmsyslog(LOG_ERR,\n\t\t\t\"saveconfig %s from %s failed\", filename,\n\t\t\tstoa(&rbufp->recv_srcadr));\n\t} else {\n\t\tctl_printf(\"Configuration saved to '%s'\", filename);\n\t\tmsyslog(LOG_NOTICE,\n\t\t\t\"Configuration saved to '%s' (requested by %s)\",\n\t\t\tfullpath, stoa(&rbufp->recv_srcadr));\n\t\t/*\n\t\t * save the output filename in system variable\n\t\t * savedconfig, retrieved with:\n\t\t * ntpq -c \"rv 0 savedconfig\"\n\t\t * Note: the way 'savedconfig' is defined makes overflow\n\t\t * checks unnecessary here.\n\t\t */\n\t\tsnprintf(savedconfig, sizeof(savedconfig), \"%s%s\",\n\t\t\t savedconfig_eq, filename);\n\t\tset_sys_var(savedconfig, strlen(savedconfig) + 1, RO);\n\t}\n\n\tif (NULL != fptr)\n\t\tfclose(fptr);\n#else\t/* !SAVECONFIG follows */\n\tctl_printf(\"%s\",\n\t\t \"saveconfig unavailable, configured with --disable-saveconfig\");\n#endif\t\n\tctl_flushpkt(0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-254'], 'message': '[Bug 2938] ntpq saveconfig command allows dangerous characters in filenames.\n - make sure the file does not exist (no overwrite allowed)\n - ensure text mode where applicable (windows)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: get_clock_info(\n\tsockaddr_u *srcadr,\n\tendpt *inter,\n\tstruct req_pkt *inpkt\n\t)\n{\n\tregister struct info_clock *ic;\n\tregister u_int32 *clkaddr;\n\tregister int items;\n\tstruct refclockstat clock_stat;\n\tsockaddr_u addr;\n\tl_fp ltmp;\n\n\tZERO_SOCK(&addr);\n\tAF(&addr) = AF_INET;\n#ifdef ISC_PLATFORM_HAVESALEN\n\taddr.sa.sa_len = SOCKLEN(&addr);\n#endif\n\tSET_PORT(&addr, NTP_PORT);\n\titems = INFO_NITEMS(inpkt->err_nitems);\n\tclkaddr = &inpkt->u.u32[0];\n\n\tic = (struct info_clock *)prepare_pkt(srcadr, inter, inpkt,\n\t\t\t\t\t sizeof(struct info_clock));\n\n\twhile (items-- > 0) {\n\t\tNSRCADR(&addr) = *clkaddr++;\n\t\tif (!ISREFCLOCKADR(&addr) || NULL ==\n\t\t findexistingpeer(&addr, NULL, NULL, -1, 0)) {\n\t\t\treq_ack(srcadr, inter, inpkt, INFO_ERR_NODATA);\n\t\t\treturn;\n\t\t}\n\n\t\tclock_stat.kv_list = (struct ctl_var *)0;\n\n\t\trefclock_control(&addr, NULL, &clock_stat);\n\n\t\tic->clockadr = NSRCADR(&addr);\n\t\tic->type = clock_stat.type;\n\t\tic->flags = clock_stat.flags;\n\t\tic->lastevent = clock_stat.lastevent;\n\t\tic->currentstatus = clock_stat.currentstatus;\n\t\tic->polls = htonl((u_int32)clock_stat.polls);\n\t\tic->noresponse = htonl((u_int32)clock_stat.noresponse);\n\t\tic->badformat = htonl((u_int32)clock_stat.badformat);\n\t\tic->baddata = htonl((u_int32)clock_stat.baddata);\n\t\tic->timestarted = htonl((u_int32)clock_stat.timereset);\n\t\tDTOLFP(clock_stat.fudgetime1, <mp);\n\t\tHTONL_FP(<mp, &ic->fudgetime1);\n\t\tDTOLFP(clock_stat.fudgetime2, <mp);\n\t\tHTONL_FP(<mp, &ic->fudgetime2);\n\t\tic->fudgeval1 = htonl((u_int32)clock_stat.fudgeval1);\n\t\tic->fudgeval2 = htonl(clock_stat.fudgeval2);\n\n\t\tfree_varlist(clock_stat.kv_list);\n\n\t\tic = (struct info_clock *)more_pkt();\n\t}\n\tflush_pkt();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': '[Bug 2939] reslist NULL pointer dereference\n[Bug 2940] Stack exhaustion in recursive traversal of restriction list\n -- these two where fixed together --'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: yytnamerr (char *yyres, const char *yystr)\n{\n if (*yystr == '\"')\n {\n YYSIZE_T yyn = 0;\n char const *yyp = yystr;\n\n for (;;)\n switch (*++yyp)\n {\n case '\\'':\n case ',':\n goto do_not_strip_quotes;\n\n case '\\\\':\n if (*++yyp != '\\\\')\n goto do_not_strip_quotes;\n /* Fall through. */\n default:\n if (yyres)\n yyres[yyn] = *yyp;\n yyn++;\n break;\n\n case '\"':\n if (yyres)\n yyres[yyn] = '\\0';\n return yyn;\n }\n do_not_strip_quotes: ;\n }\n\n if (! yyres)\n return yystrlen (yystr);\n\n return yystpcpy (yyres, yystr) - yyres;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-19'], 'message': '[Sec 2942]: Off-path DoS attack on auth broadcast mode. HStenn.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: list_dbs(MYSQL *mysql,const char *wild)\n{\n const char *header;\n uint length, counter = 0;\n ulong rowcount = 0L;\n char tables[NAME_LEN+1], rows[NAME_LEN+1];\n char query[255];\n MYSQL_FIELD *field;\n MYSQL_RES *result;\n MYSQL_ROW row= NULL, rrow;\n\n if (!(result=mysql_list_dbs(mysql,wild)))\n {\n fprintf(stderr,\"%s: Cannot list databases: %s\\n\",my_progname,\n\t mysql_error(mysql));\n return 1;\n }\n\n /*\n If a wildcard was used, but there was only one row and it's name is an\n exact match, we'll assume they really wanted to see the contents of that\n database. This is because it is fairly common for database names to\n contain the underscore (_), like INFORMATION_SCHEMA.\n */\n if (wild && mysql_num_rows(result) == 1)\n {\n row= mysql_fetch_row(result);\n if (!my_strcasecmp(&my_charset_latin1, row[0], wild))\n {\n mysql_free_result(result);\n if (opt_status)\n return list_table_status(mysql, wild, NULL);\n else\n return list_tables(mysql, wild, NULL);\n }\n }\n\n if (wild)\n printf(\"Wildcard: %s\\n\",wild);\n\n header=\"Databases\";\n length=(uint) strlen(header);\n field=mysql_fetch_field(result);\n if (length < field->max_length)\n length=field->max_length;\n\n if (!opt_verbose)\n print_header(header,length,NullS);\n else if (opt_verbose == 1)\n print_header(header,length,\"Tables\",6,NullS);\n else\n print_header(header,length,\"Tables\",6,\"Total Rows\",12,NullS);\n\n /* The first row may have already been read up above. */\n while (row || (row= mysql_fetch_row(result)))\n {\n counter++;\n\n if (opt_verbose)\n {\n if (!(mysql_select_db(mysql,row[0])))\n {\n\tMYSQL_RES *tresult = mysql_list_tables(mysql,(char*)NULL);\n\tif (mysql_affected_rows(mysql) > 0)\n\t{\n\t sprintf(tables,\"%6lu\",(ulong) mysql_affected_rows(mysql));\n\t rowcount = 0;\n\t if (opt_verbose > 1)\n\t {\n /* Print the count of tables and rows for each database */\n MYSQL_ROW trow;\n\t while ((trow = mysql_fetch_row(tresult)))\n\t {\n\t sprintf(query,\"SELECT COUNT(*) FROM `%s`\",trow[0]);\n\t if (!(mysql_query(mysql,query)))\n\t {\n\t\tMYSQL_RES *rresult;\n\t\tif ((rresult = mysql_store_result(mysql)))\n\t\t{\n\t\t rrow = mysql_fetch_row(rresult);\n\t\t rowcount += (ulong) strtoull(rrow[0], (char**) 0, 10);\n\t\t mysql_free_result(rresult);\n\t\t}\n\t }\n\t }\n\t sprintf(rows,\"%12lu\",rowcount);\n\t }\n\t}\n\telse\n\t{\n\t sprintf(tables,\"%6d\",0);\n\t sprintf(rows,\"%12d\",0);\n\t}\n\tmysql_free_result(tresult);\n }\n else\n {\n\tstrmov(tables,\"N/A\");\n\tstrmov(rows,\"N/A\");\n }\n }\n\n if (!opt_verbose)\n print_row(row[0],length,0);\n else if (opt_verbose == 1)\n print_row(row[0],length,tables,6,NullS);\n else\n print_row(row[0],length,tables,6,rows,12,NullS);\n\n row= NULL;\n }\n\n print_trailer(length,\n\t\t(opt_verbose > 0 ? 6 : 0),\n\t\t(opt_verbose > 1 ? 12 :0),\n\t\t0);\n\n if (counter && opt_verbose)\n printf(\"%u row%s in set.\\n\",counter,(counter > 1) ? \"s\" : \"\");\n mysql_free_result(result);\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Bug#21973610: BUFFER OVERFLOW ISSUES\n\nDescription : Incorrect usage of sprintf/strcpy caused\n possible buffer overflow issues at various\n places.\n\nSolution : - Fixed mysql_plugin and mysqlshow\n - Fixed regex library issues\n\nReviewed-By : Georgi Kodinov \nReviewed-By : Venkata S Murthy Sidagam '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int CertManager::Validate()\n{\n CertList::reverse_iterator last = peerList_.rbegin();\n size_t count = peerList_.size();\n\n while ( count > 1 ) {\n TaoCrypt::Source source((*last)->get_buffer(), (*last)->get_length());\n TaoCrypt::CertDecoder cert(source, true, &signers_, verifyNone_);\n\n if (int err = cert.GetError().What())\n return err;\n\n const TaoCrypt::PublicKey& key = cert.GetPublicKey();\n signers_.push_back(NEW_YS TaoCrypt::Signer(key.GetKey(), key.size(),\n cert.GetCommonName(), cert.GetHash()));\n ++last;\n --count;\n }\n\n if (count) {\n // peer's is at the front\n TaoCrypt::Source source((*last)->get_buffer(), (*last)->get_length());\n TaoCrypt::CertDecoder cert(source, true, &signers_, verifyNone_);\n\n int err = cert.GetError().What();\n if ( err && err != TaoCrypt::SIG_OTHER_E)\n return err;\n\n uint sz = cert.GetPublicKey().size();\n peerPublicKey_.allocate(sz);\n peerPublicKey_.assign(cert.GetPublicKey().GetKey(), sz);\n\n if (cert.GetKeyType() == TaoCrypt::RSAk)\n peerKeyType_ = rsa_sa_algo;\n else\n peerKeyType_ = dsa_sa_algo;\n\n size_t iSz = strlen(cert.GetIssuer()) + 1;\n size_t sSz = strlen(cert.GetCommonName()) + 1;\n int bSz = (int)strlen(cert.GetBeforeDate()) + 1;\n int aSz = (int)strlen(cert.GetAfterDate()) + 1;\n peerX509_ = NEW_YS X509(cert.GetIssuer(), iSz, cert.GetCommonName(),\n sSz, cert.GetBeforeDate(), bSz,\n cert.GetAfterDate(), aSz);\n\n if (err == TaoCrypt::SIG_OTHER_E && verifyCallback_) {\n X509_STORE_CTX store;\n store.error = err;\n store.error_depth = static_cast(count) - 1;\n store.current_cert = peerX509_;\n\n int ok = verifyCallback_(0, &store);\n if (ok) return 0;\n }\n\n if (err == TaoCrypt::SIG_OTHER_E) return err;\n }\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-254'], 'message': 'Bug #22738607: YASSL FUNCTION X509_NAME_GET_INDEX_BY_NID IS NOT WORKING AS EXPECTED.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void tcp_cwnd_reduction(struct sock *sk, const int prior_unsacked,\n\t\t\t int fast_rexmit, int flag)\n{\n\tstruct tcp_sock *tp = tcp_sk(sk);\n\tint sndcnt = 0;\n\tint delta = tp->snd_ssthresh - tcp_packets_in_flight(tp);\n\tint newly_acked_sacked = prior_unsacked -\n\t\t\t\t (tp->packets_out - tp->sacked_out);\n\n\ttp->prr_delivered += newly_acked_sacked;\n\tif (delta < 0) {\n\t\tu64 dividend = (u64)tp->snd_ssthresh * tp->prr_delivered +\n\t\t\t tp->prior_cwnd - 1;\n\t\tsndcnt = div_u64(dividend, tp->prior_cwnd) - tp->prr_out;\n\t} else if ((flag & FLAG_RETRANS_DATA_ACKED) &&\n\t\t !(flag & FLAG_LOST_RETRANS)) {\n\t\tsndcnt = min_t(int, delta,\n\t\t\t max_t(int, tp->prr_delivered - tp->prr_out,\n\t\t\t\t newly_acked_sacked) + 1);\n\t} else {\n\t\tsndcnt = min(delta, newly_acked_sacked);\n\t}\n\tsndcnt = max(sndcnt, (fast_rexmit ? 1 : 0));\n\ttp->snd_cwnd = tcp_packets_in_flight(tp) + sndcnt;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'tcp: fix zero cwnd in tcp_cwnd_reduction\n\nPatch 3759824da87b (\"tcp: PRR uses CRB mode by default and SS mode\nconditionally\") introduced a bug that cwnd may become 0 when both\ninflight and sndcnt are 0 (cwnd = inflight + sndcnt). This may lead\nto a div-by-zero if the connection starts another cwnd reduction\nphase by setting tp->prior_cwnd to the current cwnd (0) in\ntcp_init_cwnd_reduction().\n\nTo prevent this we skip PRR operation when nothing is acked or\nsacked. Then cwnd must be positive in all cases as long as ssthresh\nis positive:\n\n1) The proportional reduction mode\n inflight > ssthresh > 0\n\n2) The reduction bound mode\n a) inflight == ssthresh > 0\n\n b) inflight < ssthresh\n sndcnt > 0 since newly_acked_sacked > 0 and inflight < ssthresh\n\nTherefore in all cases inflight and sndcnt can not both be 0.\nWe check invalid tp->prior_cwnd to avoid potential div0 bugs.\n\nIn reality this bug is triggered only with a sequence of less common\nevents. For example, the connection is terminating an ECN-triggered\ncwnd reduction with an inflight 0, then it receives reordered/old\nACKs or DSACKs from prior transmission (which acks nothing). Or the\nconnection is in fast recovery stage that marks everything lost,\nbut fails to retransmit due to local issues, then receives data\npackets from other end which acks nothing.\n\nFixes: 3759824da87b (\"tcp: PRR uses CRB mode by default and SS mode conditionally\")\nReported-by: Oleksandr Natalenko \nSigned-off-by: Yuchung Cheng \nSigned-off-by: Neal Cardwell \nSigned-off-by: Eric Dumazet \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int jas_image_writecmpt(jas_image_t *image, int cmptno, jas_image_coord_t x, jas_image_coord_t y, jas_image_coord_t width,\n jas_image_coord_t height, jas_matrix_t *data)\n{\n\tjas_image_cmpt_t *cmpt;\n\tjas_image_coord_t i;\n\tjas_image_coord_t j;\n\tjas_seqent_t *d;\n\tjas_seqent_t *dr;\n\tint drs;\n\tjas_seqent_t v;\n\tint k;\n\tint c;\n\n\tif (cmptno < 0 || cmptno >= image->numcmpts_) {\n\t\treturn -1;\n\t}\n\n\tcmpt = image->cmpts_[cmptno];\n\tif (x >= cmpt->width_ || y >= cmpt->height_ ||\n\t x + width > cmpt->width_ ||\n\t y + height > cmpt->height_) {\n\t\treturn -1;\n\t}\n\n\tif (jas_matrix_numrows(data) != height || jas_matrix_numcols(data) != width) {\n\t\treturn -1;\n\t}\n\n\tdr = jas_matrix_getref(data, 0, 0);\n\tdrs = jas_matrix_rowstep(data);\n\tfor (i = 0; i < height; ++i, dr += drs) {\n\t\td = dr;\n\t\tif (jas_stream_seek(cmpt->stream_, (cmpt->width_ * (y + i) + x)\n\t\t * cmpt->cps_, SEEK_SET) < 0) {\n\t\t\treturn -1;\n\t\t}\n\t\tfor (j = width; j > 0; --j, ++d) {\n\t\t\tv = inttobits(*d, cmpt->prec_, cmpt->sgnd_);\n\t\t\tfor (k = cmpt->cps_; k > 0; --k) {\n\t\t\t\tc = (v >> (8 * (cmpt->cps_ - 1))) & 0xff;\n\t\t\t\tif (jas_stream_putc(cmpt->stream_,\n\t\t\t\t (unsigned char) c) == EOF) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\tv <<= 8;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Added fix for CVE-2016-2089.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: create_policy_2_svc(cpol_arg *arg, struct svc_req *rqstp)\n{\n static generic_ret ret;\n char *prime_arg;\n gss_buffer_desc client_name,\n service_name;\n OM_uint32 minor_stat;\n kadm5_server_handle_t handle;\n const char *errmsg = NULL;\n\n xdr_free(xdr_generic_ret, &ret);\n\n if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))\n goto exit_func;\n\n if ((ret.code = check_handle((void *)handle)))\n goto exit_func;\n\n ret.api_version = handle->api_version;\n\n if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {\n ret.code = KADM5_FAILURE;\n goto exit_func;\n }\n prime_arg = arg->rec.policy;\n\n if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context,\n rqst2name(rqstp),\n ACL_ADD, NULL, NULL)) {\n ret.code = KADM5_AUTH_ADD;\n log_unauth(\"kadm5_create_policy\", prime_arg,\n &client_name, &service_name, rqstp);\n\n } else {\n ret.code = kadm5_create_policy((void *)handle, &arg->rec,\n arg->mask);\n if( ret.code != 0 )\n errmsg = krb5_get_error_message(handle->context, ret.code);\n\n log_done(\"kadm5_create_policy\",\n ((prime_arg == NULL) ? \"(null)\" : prime_arg), errmsg,\n &client_name, &service_name, rqstp);\n\n if (errmsg != NULL)\n krb5_free_error_message(handle->context, errmsg);\n }\n gss_release_buffer(&minor_stat, &client_name);\n gss_release_buffer(&minor_stat, &service_name);\nexit_func:\n free_server_handle(handle);\n return &ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-772', 'CWE-401'], 'message': 'Fix leaks in kadmin server stubs [CVE-2015-8631]\n\nIn each kadmind server stub, initialize the client_name and\nserver_name variables, and release them in the cleanup handler. Many\nof the stubs will otherwise leak the client and server name if\nkrb5_unparse_name() fails. Also make sure to free the prime_arg\nvariables in rename_principal_2_svc(), or we can leak the first one if\nunparsing the second one fails. Discovered by Simo Sorce.\n\nCVE-2015-8631:\n\nIn all versions of MIT krb5, an authenticated attacker can cause\nkadmind to leak memory by supplying a null principal name in a request\nwhich uses one. Repeating these requests will eventually cause\nkadmind to exhaust all available memory.\n\n CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C\n\nticket: 8343 (new)\ntarget_version: 1.14-next\ntarget_version: 1.13-next\ntags: pullup'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: modify_policy_2_svc(mpol_arg *arg, struct svc_req *rqstp)\n{\n static generic_ret ret;\n char *prime_arg;\n gss_buffer_desc client_name,\n service_name;\n OM_uint32 minor_stat;\n kadm5_server_handle_t handle;\n const char *errmsg = NULL;\n\n xdr_free(xdr_generic_ret, &ret);\n\n if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))\n goto exit_func;\n\n if ((ret.code = check_handle((void *)handle)))\n goto exit_func;\n\n ret.api_version = handle->api_version;\n\n if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {\n ret.code = KADM5_FAILURE;\n goto exit_func;\n }\n prime_arg = arg->rec.policy;\n\n if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context,\n rqst2name(rqstp),\n ACL_MODIFY, NULL, NULL)) {\n log_unauth(\"kadm5_modify_policy\", prime_arg,\n &client_name, &service_name, rqstp);\n ret.code = KADM5_AUTH_MODIFY;\n } else {\n ret.code = kadm5_modify_policy((void *)handle, &arg->rec,\n arg->mask);\n if( ret.code != 0 )\n errmsg = krb5_get_error_message(handle->context, ret.code);\n\n log_done(\"kadm5_modify_policy\",\n ((prime_arg == NULL) ? \"(null)\" : prime_arg), errmsg,\n &client_name, &service_name, rqstp);\n\n if (errmsg != NULL)\n krb5_free_error_message(handle->context, errmsg);\n }\n gss_release_buffer(&minor_stat, &client_name);\n gss_release_buffer(&minor_stat, &service_name);\nexit_func:\n free_server_handle(handle);\n return &ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-772', 'CWE-401'], 'message': 'Fix leaks in kadmin server stubs [CVE-2015-8631]\n\nIn each kadmind server stub, initialize the client_name and\nserver_name variables, and release them in the cleanup handler. Many\nof the stubs will otherwise leak the client and server name if\nkrb5_unparse_name() fails. Also make sure to free the prime_arg\nvariables in rename_principal_2_svc(), or we can leak the first one if\nunparsing the second one fails. Discovered by Simo Sorce.\n\nCVE-2015-8631:\n\nIn all versions of MIT krb5, an authenticated attacker can cause\nkadmind to leak memory by supplying a null principal name in a request\nwhich uses one. Repeating these requests will eventually cause\nkadmind to exhaust all available memory.\n\n CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C\n\nticket: 8343 (new)\ntarget_version: 1.14-next\ntarget_version: 1.13-next\ntags: pullup'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void UTFstring::UpdateFromUTF8()\n{\n delete [] _Data;\n // find the size of the final UCS-2 string\n size_t i;\n for (_Length=0, i=0; i(UTF8string[i]);\n if (lead < 0x80)\n i++;\n else if ((lead >> 5) == 0x6)\n i += 2;\n else if ((lead >> 4) == 0xe)\n i += 3;\n else if ((lead >> 3) == 0x1e)\n i += 4;\n else\n // Invalid size?\n break;\n }\n _Data = new wchar_t[_Length+1];\n size_t j;\n for (j=0, i=0; i(UTF8string[i]);\n if (lead < 0x80) {\n _Data[j] = lead;\n i++;\n } else if ((lead >> 5) == 0x6) {\n _Data[j] = ((lead & 0x1F) << 6) + (UTF8string[i+1] & 0x3F);\n i += 2;\n } else if ((lead >> 4) == 0xe) {\n _Data[j] = ((lead & 0x0F) << 12) + ((UTF8string[i+1] & 0x3F) << 6) + (UTF8string[i+2] & 0x3F);\n i += 3;\n } else if ((lead >> 3) == 0x1e) {\n _Data[j] = ((lead & 0x07) << 18) + ((UTF8string[i+1] & 0x3F) << 12) + ((UTF8string[i+2] & 0x3F) << 6) + (UTF8string[i+3] & 0x3F);\n i += 4;\n } else\n // Invalid char?\n break;\n }\n _Data[j] = 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-703'], 'message': 'EbmlUnicodeString: don't read beyond end of string\n\nThe conversion from an UTF-8 encoded string into a wchar_t one was\nreading from beyond the end of the source buffer if the length indicated\nby a UTF-8 character's first byte exceeds the number of bytes actually\npresent afterwards.\n\nFixes the issue reported as Cisco TALOS-CAN-0036.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int php_stream_temp_set_option(php_stream *stream, int option, int value, void *ptrparam TSRMLS_DC) /* {{{ */\n{\n\tphp_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract;\n\t\n\tswitch(option) {\n\t\tcase PHP_STREAM_OPTION_META_DATA_API:\n\t\t\tif (ts->meta) {\n\t\t\t\tzend_hash_copy(Z_ARRVAL_P((zval*)ptrparam), Z_ARRVAL_P(ts->meta), (copy_ctor_func_t) zval_add_ref, NULL, sizeof(zval*));\n\t\t\t}\n\t\t\treturn PHP_STREAM_OPTION_RETURN_OK;\n\t\tdefault:\n\t\t\tif (ts->innerstream) {\n\t\t\t\treturn php_stream_set_option(ts->innerstream, option, value, ptrparam);\n\t\t\t}\n\t\t\treturn PHP_STREAM_OPTION_RETURN_NOTIMPL;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fixed bug #71323 - Output of stream_get_meta_data can be falsified by its input'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: PHP_FUNCTION(stream_set_chunk_size)\n{\n\tint\t\t\tret;\n\tlong\t\tcsize;\n\tzval\t\t*zstream;\n\tphp_stream\t*stream;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"rl\", &zstream, &csize) == FAILURE) {\n\t\tRETURN_FALSE;\n\t}\n\n\tif (csize <= 0) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"The chunk size must be a positive integer, given %ld\", csize);\n\t\tRETURN_FALSE;\n\t}\n\t/* stream.chunk_size is actually a size_t, but php_stream_set_option \n\t * can only use an int to accept the new value and return the old one.\n\t * In any case, values larger than INT_MAX for a chunk size make no sense.\n\t */\n\tif (csize > INT_MAX) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"The chunk size cannot be larger than %d\", INT_MAX);\n\t\tRETURN_FALSE;\n\t}\n\t\n\tphp_stream_from_zval(stream, &zstream);\n\n\tret = php_stream_set_option(stream, PHP_STREAM_OPTION_SET_CHUNK_SIZE, (int)csize, NULL);\n\t\n\tRETURN_LONG(ret > 0 ? (long)ret : (long)EOF);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fixed bug #71323 - Output of stream_get_meta_data can be falsified by its input'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline pgd_t *pgd_alloc(struct mm_struct *mm)\n{\n\tspin_lock_init(&mm->context.list_lock);\n\tINIT_LIST_HEAD(&mm->context.pgtable_list);\n\tINIT_LIST_HEAD(&mm->context.gmap_list);\n\treturn (pgd_t *) crst_table_alloc(mm);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 's390/mm: four page table levels vs. fork\n\nThe fork of a process with four page table levels is broken since\ngit commit 6252d702c5311ce9 \"[S390] dynamic page tables.\"\n\nAll new mm contexts are created with three page table levels and\nan asce limit of 4TB. If the parent has four levels dup_mmap will\nadd vmas to the new context which are outside of the asce limit.\nThe subsequent call to copy_page_range will walk the three level\npage table structure of the new process with non-zero pgd and pud\nindexes. This leads to memory clobbers as the pgd_index *and* the\npud_index is added to the mm->pgd pointer without a pgd_deref\nin between.\n\nThe init_new_context() function is selecting the number of page\ntable levels for a new context. The function is used by mm_init()\nwhich in turn is called by dup_mm() and mm_alloc(). These two are\nused by fork() and exec(). The init_new_context() function can\ndistinguish the two cases by looking at mm->context.asce_limit,\nfor fork() the mm struct has been copied and the number of page\ntable levels may not change. For exec() the mm_alloc() function\nset the new mm structure to zero, in this case a three-level page\ntable is created as the temporary stack space is located at\nSTACK_TOP_MAX = 4TB.\n\nThis fixes CVE-2016-2143.\n\nReported-by: Marcin Ko\u015bcielnicki \nReviewed-by: Heiko Carstens \nCc: stable@vger.kernel.org\nSigned-off-by: Martin Schwidefsky '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void queue_delete(struct snd_seq_queue *q)\n{\n\t/* stop and release the timer */\n\tsnd_seq_timer_stop(q->timer);\n\tsnd_seq_timer_close(q);\n\t/* wait until access free */\n\tsnd_use_lock_sync(&q->use_lock);\n\t/* release resources... */\n\tsnd_seq_prioq_delete(&q->tickq);\n\tsnd_seq_prioq_delete(&q->timeq);\n\tsnd_seq_timer_delete(&q->timer);\n\n\tkfree(q);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'ALSA: seq: Fix race at timer setup and close\n\nALSA sequencer code has an open race between the timer setup ioctl and\nthe close of the client. This was triggered by syzkaller fuzzer, and\na use-after-free was caught there as a result.\n\nThis patch papers over it by adding a proper queue->timer_mutex lock\naround the timer-related calls in the relevant code path.\n\nReported-by: Dmitry Vyukov \nTested-by: Dmitry Vyukov \nCc: \nSigned-off-by: Takashi Iwai '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int snd_hrtimer_start(struct snd_timer *t)\n{\n\tstruct snd_hrtimer *stime = t->private_data;\n\n\tatomic_set(&stime->running, 0);\n\thrtimer_cancel(&stime->hrt);\n\thrtimer_start(&stime->hrt, ns_to_ktime(t->sticks * resolution),\n\t\t HRTIMER_MODE_REL);\n\tatomic_set(&stime->running, 1);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'ALSA: hrtimer: Fix stall by hrtimer_cancel()\n\nhrtimer_cancel() waits for the completion from the callback, thus it\nmust not be called inside the callback itself. This was already a\nproblem in the past with ALSA hrtimer driver, and the early commit\n[fcfdebe70759: ALSA: hrtimer - Fix lock-up] tried to address it.\n\nHowever, the previous fix is still insufficient: it may still cause a\nlockup when the ALSA timer instance reprograms itself in its callback.\nThen it invokes the start function even in snd_timer_interrupt() that\nis called in hrtimer callback itself, results in a CPU stall. This is\nno hypothetical problem but actually triggered by syzkaller fuzzer.\n\nThis patch tries to fix the issue again. Now we call\nhrtimer_try_to_cancel() at both start and stop functions so that it\nwon't fall into a deadlock, yet giving some chance to cancel the queue\nif the functions have been called outside the callback. The proper\nhrtimer_cancel() is called in anyway at closing, so this should be\nenough.\n\nReported-and-tested-by: Dmitry Vyukov \nCc: \nSigned-off-by: Takashi Iwai '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: readconf_main(void)\n{\nint sep = 0;\nstruct stat statbuf;\nuschar *s, *filename;\nconst uschar *list = config_main_filelist;\n\n/* Loop through the possible file names */\n\nwhile((filename = string_nextinlist(&list, &sep, big_buffer, big_buffer_size))\n != NULL)\n {\n /* Cut out all the fancy processing unless specifically wanted */\n\n #if defined(CONFIGURE_FILE_USE_NODE) || defined(CONFIGURE_FILE_USE_EUID)\n uschar *suffix = filename + Ustrlen(filename);\n\n /* Try for the node-specific file if a node name exists */\n\n #ifdef CONFIGURE_FILE_USE_NODE\n struct utsname uts;\n if (uname(&uts) >= 0)\n {\n #ifdef CONFIGURE_FILE_USE_EUID\n sprintf(CS suffix, \".%ld.%.256s\", (long int)original_euid, uts.nodename);\n config_file = Ufopen(filename, \"rb\");\n if (config_file == NULL)\n #endif /* CONFIGURE_FILE_USE_EUID */\n {\n sprintf(CS suffix, \".%.256s\", uts.nodename);\n config_file = Ufopen(filename, \"rb\");\n }\n }\n #endif /* CONFIGURE_FILE_USE_NODE */\n\n /* Otherwise, try the generic name, possibly with the euid added */\n\n #ifdef CONFIGURE_FILE_USE_EUID\n if (config_file == NULL)\n {\n sprintf(CS suffix, \".%ld\", (long int)original_euid);\n config_file = Ufopen(filename, \"rb\");\n }\n #endif /* CONFIGURE_FILE_USE_EUID */\n\n /* Finally, try the unadorned name */\n\n if (config_file == NULL)\n {\n *suffix = 0;\n config_file = Ufopen(filename, \"rb\");\n }\n #else /* if neither defined */\n\n /* This is the common case when the fancy processing is not included. */\n\n config_file = Ufopen(filename, \"rb\");\n #endif\n\n /* If the file does not exist, continue to try any others. For any other\n error, break out (and die). */\n\n if (config_file != NULL || errno != ENOENT) break;\n }\n\n/* On success, save the name for verification; config_filename is used when\nlogging configuration errors (it changes for .included files) whereas\nconfig_main_filename is the name shown by -bP. Failure to open a configuration\nfile is a serious disaster. */\n\nif (config_file != NULL)\n {\n uschar *p;\n config_filename = config_main_filename = string_copy(filename);\n\n p = Ustrrchr(filename, '/');\n config_main_directory = p ? string_copyn(filename, p - filename) \n : string_copy(US\".\");\n }\nelse\n {\n if (filename == NULL)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"non-existent configuration file(s): \"\n \"%s\", config_main_filelist);\n else\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"%s\", string_open_failed(errno,\n \"configuration file %s\", filename));\n }\n\n/* Check the status of the file we have opened, if we have retained root\nprivileges and the file isn't /dev/null (which *should* be 0666). */\n\nif (trusted_config && Ustrcmp(filename, US\"/dev/null\"))\n {\n if (fstat(fileno(config_file), &statbuf) != 0)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to stat configuration file %s\",\n big_buffer);\n\n if ((statbuf.st_uid != root_uid /* owner not root */\n #ifdef CONFIGURE_OWNER\n && statbuf.st_uid != config_uid /* owner not the special one */\n #endif\n ) || /* or */\n (statbuf.st_gid != root_gid /* group not root & */\n #ifdef CONFIGURE_GROUP\n && statbuf.st_gid != config_gid /* group not the special one */\n #endif\n && (statbuf.st_mode & 020) != 0) || /* group writeable */\n /* or */\n ((statbuf.st_mode & 2) != 0)) /* world writeable */\n\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"Exim configuration file %s has the \"\n \"wrong owner, group, or mode\", big_buffer);\n }\n\n/* Process the main configuration settings. They all begin with a lower case\nletter. If we see something starting with an upper case letter, it is taken as\na macro definition. */\n\nwhile ((s = get_config_line()) != NULL)\n {\n if (isupper(s[0])) read_macro_assignment(s);\n\n else if (Ustrncmp(s, \"domainlist\", 10) == 0)\n read_named_list(&domainlist_anchor, &domainlist_count,\n MAX_NAMED_LIST, s+10, US\"domain list\");\n\n else if (Ustrncmp(s, \"hostlist\", 8) == 0)\n read_named_list(&hostlist_anchor, &hostlist_count,\n MAX_NAMED_LIST, s+8, US\"host list\");\n\n else if (Ustrncmp(s, US\"addresslist\", 11) == 0)\n read_named_list(&addresslist_anchor, &addresslist_count,\n MAX_NAMED_LIST, s+11, US\"address list\");\n\n else if (Ustrncmp(s, US\"localpartlist\", 13) == 0)\n read_named_list(&localpartlist_anchor, &localpartlist_count,\n MAX_NAMED_LIST, s+13, US\"local part list\");\n\n else\n (void) readconf_handle_option(s, optionlist_config, optionlist_config_size,\n NULL, US\"main option \\\"%s\\\" unknown\");\n }\n\n\n/* If local_sender_retain is set, local_from_check must be unset. */\n\nif (local_sender_retain && local_from_check)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"both local_from_check and \"\n \"local_sender_retain are set; this combination is not allowed\");\n\n/* If the timezone string is empty, set it to NULL, implying no TZ variable\nwanted. */\n\nif (timezone_string != NULL && *timezone_string == 0) timezone_string = NULL;\n\n/* The max retry interval must not be greater than 24 hours. */\n\nif (retry_interval_max > 24*60*60) retry_interval_max = 24*60*60;\n\n/* remote_max_parallel must be > 0 */\n\nif (remote_max_parallel <= 0) remote_max_parallel = 1;\n\n/* Save the configured setting of freeze_tell, so we can re-instate it at the\nstart of a new SMTP message. */\n\nfreeze_tell_config = freeze_tell;\n\n/* The primary host name may be required for expansion of spool_directory\nand log_file_path, so make sure it is set asap. It is obtained from uname(),\nbut if that yields an unqualified value, make a FQDN by using gethostbyname to\ncanonize it. Some people like upper case letters in their host names, so we\ndon't force the case. */\n\nif (primary_hostname == NULL)\n {\n const uschar *hostname;\n struct utsname uts;\n if (uname(&uts) < 0)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"uname() failed to yield host name\");\n hostname = US uts.nodename;\n\n if (Ustrchr(hostname, '.') == NULL)\n {\n int af = AF_INET;\n struct hostent *hostdata;\n\n #if HAVE_IPV6\n if (!disable_ipv6 && (dns_ipv4_lookup == NULL ||\n match_isinlist(hostname, CUSS &dns_ipv4_lookup, 0, NULL, NULL,\n\t MCL_DOMAIN, TRUE, NULL) != OK))\n af = AF_INET6;\n #else\n af = AF_INET;\n #endif\n\n for (;;)\n {\n #if HAVE_IPV6\n #if HAVE_GETIPNODEBYNAME\n int error_num;\n hostdata = getipnodebyname(CS hostname, af, 0, &error_num);\n #else\n hostdata = gethostbyname2(CS hostname, af);\n #endif\n #else\n hostdata = gethostbyname(CS hostname);\n #endif\n\n if (hostdata != NULL)\n {\n hostname = US hostdata->h_name;\n break;\n }\n\n if (af == AF_INET) break;\n af = AF_INET;\n }\n }\n\n primary_hostname = string_copy(hostname);\n }\n\n/* Set up default value for smtp_active_hostname */\n\nsmtp_active_hostname = primary_hostname;\n\n/* If spool_directory wasn't set in the build-time configuration, it must have\ngot set above. Of course, writing to the log may not work if log_file_path is\nnot set, but it will at least get to syslog or somewhere, with any luck. */\n\nif (*spool_directory == 0)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"spool_directory undefined: cannot \"\n \"proceed\");\n\n/* Expand the spool directory name; it may, for example, contain the primary\nhost name. Same comment about failure. */\n\ns = expand_string(spool_directory);\nif (s == NULL)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to expand spool_directory \"\n \"\\\"%s\\\": %s\", spool_directory, expand_string_message);\nspool_directory = s;\n\n/* Expand log_file_path, which must contain \"%s\" in any component that isn't\nthe null string or \"syslog\". It is also allowed to contain one instance of %D\nor %M. However, it must NOT contain % followed by anything else. */\n\nif (*log_file_path != 0)\n {\n const uschar *ss, *sss;\n int sep = ':'; /* Fixed for log file path */\n s = expand_string(log_file_path);\n if (s == NULL)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to expand log_file_path \"\n \"\\\"%s\\\": %s\", log_file_path, expand_string_message);\n\n ss = s;\n while ((sss = string_nextinlist(&ss,&sep,big_buffer,big_buffer_size)) != NULL)\n {\n uschar *t;\n if (sss[0] == 0 || Ustrcmp(sss, \"syslog\") == 0) continue;\n t = Ustrstr(sss, \"%s\");\n if (t == NULL)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"log_file_path \\\"%s\\\" does not \"\n \"contain \\\"%%s\\\"\", sss);\n *t = 'X';\n t = Ustrchr(sss, '%');\n if (t != NULL)\n {\n if ((t[1] != 'D' && t[1] != 'M') || Ustrchr(t+2, '%') != NULL)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"log_file_path \\\"%s\\\" contains \"\n \"unexpected \\\"%%\\\" character\", s);\n }\n }\n\n log_file_path = s;\n }\n\n/* Interpret syslog_facility into an integer argument for 'ident' param to\nopenlog(). Default is LOG_MAIL set in globals.c. Allow the user to omit the\nleading \"log_\". */\n\nif (syslog_facility_str != NULL)\n {\n int i;\n uschar *s = syslog_facility_str;\n\n if ((Ustrlen(syslog_facility_str) >= 4) &&\n (strncmpic(syslog_facility_str, US\"log_\", 4) == 0))\n s += 4;\n\n for (i = 0; i < syslog_list_size; i++)\n {\n if (strcmpic(s, syslog_list[i].name) == 0)\n {\n syslog_facility = syslog_list[i].value;\n break;\n }\n }\n\n if (i >= syslog_list_size)\n {\n log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n \"failed to interpret syslog_facility \\\"%s\\\"\", syslog_facility_str);\n }\n }\n\n/* Expand pid_file_path */\n\nif (*pid_file_path != 0)\n {\n s = expand_string(pid_file_path);\n if (s == NULL)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to expand pid_file_path \"\n \"\\\"%s\\\": %s\", pid_file_path, expand_string_message);\n pid_file_path = s;\n }\n\n/* Set default value of process_log_path */\n\nif (process_log_path == NULL || *process_log_path =='\\0')\n process_log_path = string_sprintf(\"%s/exim-process.info\", spool_directory);\n\n/* Compile the regex for matching a UUCP-style \"From_\" line in an incoming\nmessage. */\n\nregex_From = regex_must_compile(uucp_from_pattern, FALSE, TRUE);\n\n/* Unpick the SMTP rate limiting options, if set */\n\nif (smtp_ratelimit_mail != NULL)\n {\n unpick_ratelimit(smtp_ratelimit_mail, &smtp_rlm_threshold,\n &smtp_rlm_base, &smtp_rlm_factor, &smtp_rlm_limit);\n }\n\nif (smtp_ratelimit_rcpt != NULL)\n {\n unpick_ratelimit(smtp_ratelimit_rcpt, &smtp_rlr_threshold,\n &smtp_rlr_base, &smtp_rlr_factor, &smtp_rlr_limit);\n }\n\n/* The qualify domains default to the primary host name */\n\nif (qualify_domain_sender == NULL)\n qualify_domain_sender = primary_hostname;\nif (qualify_domain_recipient == NULL)\n qualify_domain_recipient = qualify_domain_sender;\n\n/* Setting system_filter_user in the configuration sets the gid as well if a\nname is given, but a numerical value does not. */\n\nif (system_filter_uid_set && !system_filter_gid_set)\n {\n struct passwd *pw = getpwuid(system_filter_uid);\n if (pw == NULL)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"Failed to look up uid %ld\",\n (long int)system_filter_uid);\n system_filter_gid = pw->pw_gid;\n system_filter_gid_set = TRUE;\n }\n\n/* If the errors_reply_to field is set, check that it is syntactically valid\nand ensure it contains a domain. */\n\nif (errors_reply_to != NULL)\n {\n uschar *errmess;\n int start, end, domain;\n uschar *recipient = parse_extract_address(errors_reply_to, &errmess,\n &start, &end, &domain, FALSE);\n\n if (recipient == NULL)\n log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n \"error in errors_reply_to (%s): %s\", errors_reply_to, errmess);\n\n if (domain == 0)\n log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n \"errors_reply_to (%s) does not contain a domain\", errors_reply_to);\n }\n\n/* If smtp_accept_queue or smtp_accept_max_per_host is set, then\nsmtp_accept_max must also be set. */\n\nif (smtp_accept_max == 0 &&\n (smtp_accept_queue > 0 || smtp_accept_max_per_host != NULL))\n log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n \"smtp_accept_max must be set if smtp_accept_queue or \"\n \"smtp_accept_max_per_host is set\");\n\n/* Set up the host number if anything is specified. It is an expanded string\nso that it can be computed from the host name, for example. We do this last\nso as to ensure that everything else is set up before the expansion. */\n\nif (host_number_string != NULL)\n {\n long int n;\n uschar *end;\n uschar *s = expand_string(host_number_string);\n if (s == NULL)\n log_write(0, LOG_MAIN|LOG_PANIC_DIE,\n \"failed to expand localhost_number \\\"%s\\\": %s\",\n host_number_string, expand_string_message);\n n = Ustrtol(s, &end, 0);\n while (isspace(*end)) end++;\n if (*end != 0)\n log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n \"localhost_number value is not a number: %s\", s);\n if (n > LOCALHOST_MAX)\n log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n \"localhost_number is greater than the maximum allowed value (%d)\",\n LOCALHOST_MAX);\n host_number = n;\n }\n\n#ifdef SUPPORT_TLS\n/* If tls_verify_hosts is set, tls_verify_certificates must also be set */\n\nif ((tls_verify_hosts != NULL || tls_try_verify_hosts != NULL) &&\n tls_verify_certificates == NULL)\n log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n \"tls_%sverify_hosts is set, but tls_verify_certificates is not set\",\n (tls_verify_hosts != NULL)? \"\" : \"try_\");\n\n/* This also checks that the library linkage is working and we can call\nroutines in it, so call even if tls_require_ciphers is unset */\nif (!tls_dropprivs_validate_require_cipher())\n exit(1);\n\n/* Magic number: at time of writing, 1024 has been the long-standing value\nused by so many clients, and what Exim used to use always, that it makes\nsense to just min-clamp this max-clamp at that. */\nif (tls_dh_max_bits < 1024)\n log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n \"tls_dh_max_bits is too small, must be at least 1024 for interop\");\n\n/* If openssl_options is set, validate it */\nif (openssl_options != NULL)\n {\n# ifdef USE_GNUTLS\n log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n \"openssl_options is set but we're using GnuTLS\");\n# else\n long dummy;\n if (!(tls_openssl_options_parse(openssl_options, &dummy)))\n log_write(0, LOG_PANIC_DIE|LOG_CONFIG,\n \"openssl_options parse error: %s\", openssl_options);\n# endif\n }\n\nif (gnutls_require_kx || gnutls_require_mac || gnutls_require_proto)\n log_write(0, LOG_MAIN, \"WARNING: main options\"\n \" gnutls_require_kx, gnutls_require_mac and gnutls_require_protocols\"\n \" are obsolete\\n\");\n#endif\t/*SUPPORT_TLS*/\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'Fix CVE-2016-1531\n\nAdd keep_environment, add_environment.\nChange the working directory to \"/\" during the early startup\nphase.\n\n(cherry picked from commit bc3c7bb7d4aba3e563434e5627fe1f2176aa18c0)\n (cherry picked from commit 2b92b67bfc33efe05e6ff2ea3852731ac2273832)\n (cherry picked from commit 14b82c8b736c8ed24eda144f57703cb9feac6323)\n (cherry picked from commit 9ca92d0c6e9c6f161bd8111366c6952d3a9315e2)\n (cherry picked from commit 0020c6d9ecfd98ed7b2b337ed4f898fdc409784b)\n (cherry picked from commit e8f96966360ea8867ad6a8b5affda6c37fa4958c)\n (cherry picked from commit ef6fb807c1e1a665f444f644c60c77269f7c5209)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void rng_random_request_entropy(RngBackend *b, size_t size,\n EntropyReceiveFunc *receive_entropy,\n void *opaque)\n{\n RndRandom *s = RNG_RANDOM(b);\n\n if (s->receive_func) {\n s->receive_func(s->opaque, NULL, 0);\n }\n\n s->receive_func = receive_entropy;\n s->opaque = opaque;\n s->size = size;\n\n qemu_set_fd_handler(s->fd, entropy_available, NULL, s);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'rng: add request queue support to rng-random\n\nRequests are now created in the RngBackend parent class and the\ncode path is shared by both rng-egd and rng-random.\n\nThis commit fixes the rng-random implementation which processed\nonly one request at a time and simply discarded all but the most\nrecent one. In the guest this manifested as delayed completion\nof reads from virtio-rng, i.e. a read was completed only after\nanother read was issued.\n\nBy switching rng-random to use the same request queue as rng-egd,\nthe unsafe stack-based allocation of the entropy buffer is\neliminated and replaced with g_malloc.\n\nSigned-off-by: Ladi Prosek \nReviewed-by: Amit Shah \nMessage-Id: <1456994238-9585-5-git-send-email-lprosek@redhat.com>\nSigned-off-by: Amit Shah '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static NOINLINE char *xmalloc_optname_optval(uint8_t *option, const struct dhcp_optflag *optflag, const char *opt_name)\n{\n\tunsigned upper_length;\n\tint len, type, optlen;\n\tchar *dest, *ret;\n\n\t/* option points to OPT_DATA, need to go back to get OPT_LEN */\n\tlen = option[-OPT_DATA + OPT_LEN];\n\n\ttype = optflag->flags & OPTION_TYPE_MASK;\n\toptlen = dhcp_option_lengths[type];\n\tupper_length = len_of_option_as_string[type]\n\t\t* ((unsigned)(len + optlen - 1) / (unsigned)optlen);\n\n\tdest = ret = xmalloc(upper_length + strlen(opt_name) + 2);\n\tdest += sprintf(ret, \"%s=\", opt_name);\n\n\twhile (len >= optlen) {\n\t\tswitch (type) {\n\t\tcase OPTION_IP:\n\t\tcase OPTION_IP_PAIR:\n\t\t\tdest += sprint_nip(dest, \"\", option);\n\t\t\tif (type == OPTION_IP)\n\t\t\t\tbreak;\n\t\t\tdest += sprint_nip(dest, \"/\", option + 4);\n\t\t\tbreak;\n//\t\tcase OPTION_BOOLEAN:\n//\t\t\tdest += sprintf(dest, *option ? \"yes\" : \"no\");\n//\t\t\tbreak;\n\t\tcase OPTION_U8:\n\t\t\tdest += sprintf(dest, \"%u\", *option);\n\t\t\tbreak;\n//\t\tcase OPTION_S16:\n\t\tcase OPTION_U16: {\n\t\t\tuint16_t val_u16;\n\t\t\tmove_from_unaligned16(val_u16, option);\n\t\t\tdest += sprintf(dest, \"%u\", ntohs(val_u16));\n\t\t\tbreak;\n\t\t}\n\t\tcase OPTION_S32:\n\t\tcase OPTION_U32: {\n\t\t\tuint32_t val_u32;\n\t\t\tmove_from_unaligned32(val_u32, option);\n\t\t\tdest += sprintf(dest, type == OPTION_U32 ? \"%lu\" : \"%ld\", (unsigned long) ntohl(val_u32));\n\t\t\tbreak;\n\t\t}\n\t\t/* Note: options which use 'return' instead of 'break'\n\t\t * (for example, OPTION_STRING) skip the code which handles\n\t\t * the case of list of options.\n\t\t */\n\t\tcase OPTION_STRING:\n\t\tcase OPTION_STRING_HOST:\n\t\t\tmemcpy(dest, option, len);\n\t\t\tdest[len] = '\\0';\n\t\t\tif (type == OPTION_STRING_HOST && !good_hostname(dest))\n\t\t\t\tsafe_strncpy(dest, \"bad\", len);\n\t\t\treturn ret;\n\t\tcase OPTION_STATIC_ROUTES: {\n\t\t\t/* Option binary format:\n\t\t\t * mask [one byte, 0..32]\n\t\t\t * ip [big endian, 0..4 bytes depending on mask]\n\t\t\t * router [big endian, 4 bytes]\n\t\t\t * may be repeated\n\t\t\t *\n\t\t\t * We convert it to a string \"IP/MASK ROUTER IP2/MASK2 ROUTER2\"\n\t\t\t */\n\t\t\tconst char *pfx = \"\";\n\n\t\t\twhile (len >= 1 + 4) { /* mask + 0-byte ip + router */\n\t\t\t\tuint32_t nip;\n\t\t\t\tuint8_t *p;\n\t\t\t\tunsigned mask;\n\t\t\t\tint bytes;\n\n\t\t\t\tmask = *option++;\n\t\t\t\tif (mask > 32)\n\t\t\t\t\tbreak;\n\t\t\t\tlen--;\n\n\t\t\t\tnip = 0;\n\t\t\t\tp = (void*) &nip;\n\t\t\t\tbytes = (mask + 7) / 8; /* 0 -> 0, 1..8 -> 1, 9..16 -> 2 etc */\n\t\t\t\twhile (--bytes >= 0) {\n\t\t\t\t\t*p++ = *option++;\n\t\t\t\t\tlen--;\n\t\t\t\t}\n\t\t\t\tif (len < 4)\n\t\t\t\t\tbreak;\n\n\t\t\t\t/* print ip/mask */\n\t\t\t\tdest += sprint_nip(dest, pfx, (void*) &nip);\n\t\t\t\tpfx = \" \";\n\t\t\t\tdest += sprintf(dest, \"/%u \", mask);\n\t\t\t\t/* print router */\n\t\t\t\tdest += sprint_nip(dest, \"\", option);\n\t\t\t\toption += 4;\n\t\t\t\tlen -= 4;\n\t\t\t}\n\n\t\t\treturn ret;\n\t\t}\n\t\tcase OPTION_6RD:\n\t\t\t/* Option binary format (see RFC 5969):\n\t\t\t * 0 1 2 3\n\t\t\t * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n\t\t\t * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t\t\t * | OPTION_6RD | option-length | IPv4MaskLen | 6rdPrefixLen |\n\t\t\t * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t\t\t * | 6rdPrefix |\n\t\t\t * ... (16 octets) ...\n\t\t\t * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t\t\t * ... 6rdBRIPv4Address(es) ...\n\t\t\t * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t\t\t * We convert it to a string\n\t\t\t * \"IPv4MaskLen 6rdPrefixLen 6rdPrefix 6rdBRIPv4Address...\"\n\t\t\t *\n\t\t\t * Sanity check: ensure that our length is at least 22 bytes, that\n\t\t\t * IPv4MaskLen <= 32,\n\t\t\t * 6rdPrefixLen <= 128,\n\t\t\t * 6rdPrefixLen + (32 - IPv4MaskLen) <= 128\n\t\t\t * (2nd condition need no check - it follows from 1st and 3rd).\n\t\t\t * Else, return envvar with empty value (\"optname=\")\n\t\t\t */\n\t\t\tif (len >= (1 + 1 + 16 + 4)\n\t\t\t && option[0] <= 32\n\t\t\t && (option[1] + 32 - option[0]) <= 128\n\t\t\t) {\n\t\t\t\t/* IPv4MaskLen */\n\t\t\t\tdest += sprintf(dest, \"%u \", *option++);\n\t\t\t\t/* 6rdPrefixLen */\n\t\t\t\tdest += sprintf(dest, \"%u \", *option++);\n\t\t\t\t/* 6rdPrefix */\n\t\t\t\tdest += sprint_nip6(dest, /* \"\", */ option);\n\t\t\t\toption += 16;\n\t\t\t\tlen -= 1 + 1 + 16 + 4;\n\t\t\t\t/* \"+ 4\" above corresponds to the length of IPv4 addr\n\t\t\t\t * we consume in the loop below */\n\t\t\t\twhile (1) {\n\t\t\t\t\t/* 6rdBRIPv4Address(es) */\n\t\t\t\t\tdest += sprint_nip(dest, \" \", option);\n\t\t\t\t\toption += 4;\n\t\t\t\t\tlen -= 4; /* do we have yet another 4+ bytes? */\n\t\t\t\t\tif (len < 0)\n\t\t\t\t\t\tbreak; /* no */\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn ret;\n#if ENABLE_FEATURE_UDHCP_RFC3397\n\t\tcase OPTION_DNS_STRING:\n\t\t\t/* unpack option into dest; use ret for prefix (i.e., \"optname=\") */\n\t\t\tdest = dname_dec(option, len, ret);\n\t\t\tif (dest) {\n\t\t\t\tfree(ret);\n\t\t\t\treturn dest;\n\t\t\t}\n\t\t\t/* error. return \"optname=\" string */\n\t\t\treturn ret;\n\t\tcase OPTION_SIP_SERVERS:\n\t\t\t/* Option binary format:\n\t\t\t * type: byte\n\t\t\t * type=0: domain names, dns-compressed\n\t\t\t * type=1: IP addrs\n\t\t\t */\n\t\t\toption++;\n\t\t\tlen--;\n\t\t\tif (option[-1] == 0) {\n\t\t\t\tdest = dname_dec(option, len, ret);\n\t\t\t\tif (dest) {\n\t\t\t\t\tfree(ret);\n\t\t\t\t\treturn dest;\n\t\t\t\t}\n\t\t\t} else\n\t\t\tif (option[-1] == 1) {\n\t\t\t\tconst char *pfx = \"\";\n\t\t\t\twhile (1) {\n\t\t\t\t\tlen -= 4;\n\t\t\t\t\tif (len < 0)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdest += sprint_nip(dest, pfx, option);\n\t\t\t\t\tpfx = \" \";\n\t\t\t\t\toption += 4;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn ret;\n#endif\n\t\t} /* switch */\n\n\t\t/* If we are here, try to format any remaining data\n\t\t * in the option as another, similarly-formatted option\n\t\t */\n\t\toption += optlen;\n\t\tlen -= optlen;\n// TODO: it can be a list only if (optflag->flags & OPTION_LIST).\n// Should we bail out/warn if we see multi-ip option which is\n// not allowed to be such (for example, DHCP_BROADCAST)? -\n\t\tif (len < optlen /* || !(optflag->flags & OPTION_LIST) */)\n\t\t\tbreak;\n\t\t*dest++ = ' ';\n\t\t*dest = '\\0';\n\t} /* while */\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'udhcpc: fix OPTION_6RD parsing (could overflow its malloced buffer)\n\nSigned-off-by: Denys Vlasenko '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int pagemap_open(struct inode *inode, struct file *file)\n{\n\tpr_warn_once(\"Bits 55-60 of /proc/PID/pagemap entries are about \"\n\t\t\t\"to stop being page-shift some time soon. See the \"\n\t\t\t\"linux/Documentation/vm/pagemap.txt for details.\\n\");\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'pagemap: do not leak physical addresses to non-privileged userspace\n\nAs pointed by recent post[1] on exploiting DRAM physical imperfection,\n/proc/PID/pagemap exposes sensitive information which can be used to do\nattacks.\n\nThis disallows anybody without CAP_SYS_ADMIN to read the pagemap.\n\n[1] http://googleprojectzero.blogspot.com/2015/03/exploiting-dram-rowhammer-bug-to-gain.html\n\n[ Eventually we might want to do anything more finegrained, but for now\n this is the simple model. - Linus ]\n\nSigned-off-by: Kirill A. Shutemov \nAcked-by: Konstantin Khlebnikov \nAcked-by: Andy Lutomirski \nCc: Pavel Emelyanov \nCc: Andrew Morton \nCc: Mark Seaborn \nCc: stable@vger.kernel.org\nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: process_db_args(krb5_context context, char **db_args, xargs_t *xargs,\n OPERATION optype)\n{\n int i=0;\n krb5_error_code st=0;\n char *arg=NULL, *arg_val=NULL;\n char **dptr=NULL;\n unsigned int arg_val_len=0;\n\n if (db_args) {\n for (i=0; db_args[i]; ++i) {\n arg = strtok_r(db_args[i], \"=\", &arg_val);\n if (strcmp(arg, TKTPOLICY_ARG) == 0) {\n dptr = &xargs->tktpolicydn;\n } else {\n if (strcmp(arg, USERDN_ARG) == 0) {\n if (optype == MODIFY_PRINCIPAL ||\n xargs->dn != NULL || xargs->containerdn != NULL ||\n xargs->linkdn != NULL) {\n st = EINVAL;\n k5_setmsg(context, st, _(\"%s option not supported\"),\n arg);\n goto cleanup;\n }\n dptr = &xargs->dn;\n } else if (strcmp(arg, CONTAINERDN_ARG) == 0) {\n if (optype == MODIFY_PRINCIPAL ||\n xargs->dn != NULL || xargs->containerdn != NULL) {\n st = EINVAL;\n k5_setmsg(context, st, _(\"%s option not supported\"),\n arg);\n goto cleanup;\n }\n dptr = &xargs->containerdn;\n } else if (strcmp(arg, LINKDN_ARG) == 0) {\n if (xargs->dn != NULL || xargs->linkdn != NULL) {\n st = EINVAL;\n k5_setmsg(context, st, _(\"%s option not supported\"),\n arg);\n goto cleanup;\n }\n dptr = &xargs->linkdn;\n } else {\n st = EINVAL;\n k5_setmsg(context, st, _(\"unknown option: %s\"), arg);\n goto cleanup;\n }\n\n xargs->dn_from_kbd = TRUE;\n if (arg_val == NULL || strlen(arg_val) == 0) {\n st = EINVAL;\n k5_setmsg(context, st, _(\"%s option value missing\"), arg);\n goto cleanup;\n }\n }\n\n if (arg_val == NULL) {\n st = EINVAL;\n k5_setmsg(context, st, _(\"%s option value missing\"), arg);\n goto cleanup;\n }\n arg_val_len = strlen(arg_val) + 1;\n\n if (strcmp(arg, TKTPOLICY_ARG) == 0) {\n if ((st = krb5_ldap_name_to_policydn (context,\n arg_val,\n dptr)) != 0)\n goto cleanup;\n } else {\n *dptr = k5memdup(arg_val, arg_val_len, &st);\n if (*dptr == NULL)\n goto cleanup;\n }\n }\n }\n\ncleanup:\n return st;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'Fix LDAP null deref on empty arg [CVE-2016-3119]\n\nIn the LDAP KDB module's process_db_args(), strtok_r() may return NULL\nif there is an empty string in the db_args array. Check for this case\nand avoid dereferencing a null pointer.\n\nCVE-2016-3119:\n\nIn MIT krb5 1.6 and later, an authenticated attacker with permission\nto modify a principal entry can cause kadmind to dereference a null\npointer by supplying an empty DB argument to the modify_principal\ncommand, if kadmind is configured to use the LDAP KDB module.\n\n CVSSv2 Vector: AV:N/AC:H/Au:S/C:N/I:N/A:C/E:H/RL:OF/RC:ND\n\nticket: 8383 (new)\ntarget_version: 1.14-next\ntarget_version: 1.13-next\ntags: pullup'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: mbfl_strpos(\n mbfl_string *haystack,\n mbfl_string *needle,\n int offset,\n int reverse)\n{\n\tint result;\n\tmbfl_string _haystack_u8, _needle_u8;\n\tconst mbfl_string *haystack_u8, *needle_u8 = NULL;\n\tconst unsigned char *u8_tbl;\n\n\tif (haystack == NULL || haystack->val == NULL || needle == NULL || needle->val == NULL) {\n\t\treturn -8;\n\t}\n\n\t{\n\t\tconst mbfl_encoding *u8_enc;\n\t\tu8_enc = mbfl_no2encoding(mbfl_no_encoding_utf8);\n\t\tif (u8_enc == NULL || u8_enc->mblen_table == NULL) {\n\t\t\treturn -8;\n\t\t}\n\t\tu8_tbl = u8_enc->mblen_table;\n\t}\n\n\tif (haystack->no_encoding != mbfl_no_encoding_utf8) {\n\t\tmbfl_string_init(&_haystack_u8);\n\t\thaystack_u8 = mbfl_convert_encoding(haystack, &_haystack_u8, mbfl_no_encoding_utf8);\n\t\tif (haystack_u8 == NULL) {\n\t\t\tresult = -4;\n\t\t\tgoto out;\n\t\t}\n\t} else {\n\t\thaystack_u8 = haystack;\n\t}\n\n\tif (needle->no_encoding != mbfl_no_encoding_utf8) {\n\t\tmbfl_string_init(&_needle_u8);\n\t\tneedle_u8 = mbfl_convert_encoding(needle, &_needle_u8, mbfl_no_encoding_utf8);\n\t\tif (needle_u8 == NULL) {\n\t\t\tresult = -4;\n\t\t\tgoto out;\n\t\t}\n\t} else {\n\t\tneedle_u8 = needle;\n\t}\n\n\tif (needle_u8->len < 1) {\n\t\tresult = -8;\n\t\tgoto out;\n\t}\n\n\tresult = -1;\n\tif (haystack_u8->len < needle_u8->len) {\n\t\tgoto out;\n\t}\n\n\tif (!reverse) {\n\t\tunsigned int jtbl[1 << (sizeof(unsigned char) * 8)];\n\t\tunsigned int needle_u8_len = needle_u8->len;\n\t\tunsigned int i;\n\t\tconst unsigned char *p, *q, *e;\n\t\tconst unsigned char *haystack_u8_val = haystack_u8->val,\n\t\t *needle_u8_val = needle_u8->val;\n\t\tfor (i = 0; i < sizeof(jtbl) / sizeof(*jtbl); ++i) {\n\t\t\tjtbl[i] = needle_u8_len + 1;\n\t\t}\n\t\tfor (i = 0; i < needle_u8_len - 1; ++i) {\n\t\t\tjtbl[needle_u8_val[i]] = needle_u8_len - i;\n\t\t}\n\t\te = haystack_u8_val + haystack_u8->len;\n\t\tp = haystack_u8_val;\n\t\twhile (--offset >= 0) {\n\t\t\tif (p >= e) {\n\t\t\t\tresult = -16;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tp += u8_tbl[*p];\n\t\t}\n\t\tp += needle_u8_len;\n\t\tif (p > e) {\n\t\t\tgoto out;\n\t\t}\n\t\twhile (p <= e) {\n\t\t\tconst unsigned char *pv = p;\n\t\t\tq = needle_u8_val + needle_u8_len;\n\t\t\tfor (;;) {\n\t\t\t\tif (q == needle_u8_val) {\n\t\t\t\t\tresult = 0;\n\t\t\t\t\twhile (p > haystack_u8_val) {\n\t\t\t\t\t\tunsigned char c = *--p;\n\t\t\t\t\t\tif (c < 0x80) {\n\t\t\t\t\t\t\t++result;\n\t\t\t\t\t\t} else if ((c & 0xc0) != 0x80) {\n\t\t\t\t\t\t\t++result;\n\t\t\t\t\t\t}\t\n\t\t\t\t\t}\n\t\t\t\t\tgoto out;\n\t\t\t\t}\n\t\t\t\tif (*--q != *--p) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tp += jtbl[*p];\n\t\t\tif (p <= pv) {\n\t\t\t\tp = pv + 1;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tunsigned int jtbl[1 << (sizeof(unsigned char) * 8)];\n\t\tunsigned int needle_u8_len = needle_u8->len, needle_len = 0;\n\t\tunsigned int i;\n\t\tconst unsigned char *p, *e, *q, *qe;\n\t\tconst unsigned char *haystack_u8_val = haystack_u8->val,\n\t\t *needle_u8_val = needle_u8->val;\n\t\tfor (i = 0; i < sizeof(jtbl) / sizeof(*jtbl); ++i) {\n\t\t\tjtbl[i] = needle_u8_len;\n\t\t}\n\t\tfor (i = needle_u8_len - 1; i > 0; --i) {\n\t\t\tunsigned char c = needle_u8_val[i];\n\t\t\tjtbl[c] = i;\n\t\t\tif (c < 0x80) {\n\t\t\t\t++needle_len;\n\t\t\t} else if ((c & 0xc0) != 0x80) {\n\t\t\t\t++needle_len;\n\t\t\t}\n\t\t}\n\t\t{\n\t\t\tunsigned char c = needle_u8_val[0];\n\t\t\tif (c < 0x80) {\n\t\t\t\t++needle_len;\n\t\t\t} else if ((c & 0xc0) != 0x80) {\n\t\t\t\t++needle_len;\n\t\t\t}\n\t\t}\n\t\te = haystack_u8_val;\n\t\tp = e + haystack_u8->len;\n\t\tqe = needle_u8_val + needle_u8_len;\n\t\tif (offset < 0) {\n\t\t\tif (-offset > needle_len) {\n\t\t\t\toffset += needle_len; \n\t\t\t\twhile (offset < 0) {\n\t\t\t\t\tunsigned char c;\n\t\t\t\t\tif (p <= e) {\n\t\t\t\t\t\tresult = -16;\n\t\t\t\t\t\tgoto out;\n\t\t\t\t\t}\n\t\t\t\t\tc = *(--p);\n\t\t\t\t\tif (c < 0x80) {\n\t\t\t\t\t\t++offset;\n\t\t\t\t\t} else if ((c & 0xc0) != 0x80) {\n\t\t\t\t\t\t++offset;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tconst unsigned char *ee = haystack_u8_val + haystack_u8->len;\n\t\t\twhile (--offset >= 0) {\n\t\t\t\tif (e >= ee) {\n\t\t\t\t\tresult = -16;\n\t\t\t\t\tgoto out;\n\t\t\t\t}\n\t\t\t\te += u8_tbl[*e];\n\t\t\t}\n\t\t}\n\t\tif (p < e + needle_u8_len) {\n\t\t\tgoto out;\n\t\t}\n\t\tp -= needle_u8_len;\n\t\twhile (p >= e) {\n\t\t\tconst unsigned char *pv = p;\n\t\t\tq = needle_u8_val;\n\t\t\tfor (;;) {\n\t\t\t\tif (q == qe) {\n\t\t\t\t\tresult = 0;\n\t\t\t\t\tp -= needle_u8_len;\n\t\t\t\t\twhile (p > haystack_u8_val) {\n\t\t\t\t\t\tunsigned char c = *--p;\n\t\t\t\t\t\tif (c < 0x80) {\n\t\t\t\t\t\t\t++result;\n\t\t\t\t\t\t} else if ((c & 0xc0) != 0x80) {\n\t\t\t\t\t\t\t++result;\n\t\t\t\t\t\t}\t\n\t\t\t\t\t}\n\t\t\t\t\tgoto out;\n\t\t\t\t}\n\t\t\t\tif (*q != *p) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t++p, ++q;\n\t\t\t}\n\t\t\tp -= jtbl[*p];\n\t\t\tif (p >= pv) {\n\t\t\t\tp = pv - 1;\n\t\t\t}\n\t\t}\n\t}\nout:\n\tif (haystack_u8 == &_haystack_u8) {\n\t\tmbfl_string_clear(&_haystack_u8);\n\t}\n\tif (needle_u8 == &_needle_u8) {\n\t\tmbfl_string_clear(&_needle_u8);\n\t}\n\treturn result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fixed bug #71906: AddressSanitizer: negative-size-param (-1) in mbfl_strcut'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: PHP_METHOD(Phar, createDefaultStub)\n{\n\tchar *index = NULL, *webindex = NULL, *error;\n\tzend_string *stub;\n\tsize_t index_len = 0, webindex_len = 0;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS(), \"|ss\", &index, &index_len, &webindex, &webindex_len) == FAILURE) {\n\t\treturn;\n\t}\n\n\tstub = phar_create_default_stub(index, webindex, &error);\n\n\tif (error) {\n\t\tzend_throw_exception_ex(phar_ce_PharException, 0, \"%s\", error);\n\t\tefree(error);\n\t\treturn;\n\t}\n\tRETURN_NEW_STR(stub);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #71860: Require valid paths for phar filenames'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: PHP_METHOD(Phar, isValidPharFilename)\n{\n\tchar *fname;\n\tconst char *ext_str;\n\tsize_t fname_len;\n\tint ext_len, is_executable;\n\tzend_bool executable = 1;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS(), \"s|b\", &fname, &fname_len, &executable) == FAILURE) {\n\t\treturn;\n\t}\n\n\tis_executable = executable;\n\tRETVAL_BOOL(phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, is_executable, 2, 1) == SUCCESS);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #71860: Require valid paths for phar filenames'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ext4_insert_range(struct inode *inode, loff_t offset, loff_t len)\n{\n\tstruct super_block *sb = inode->i_sb;\n\thandle_t *handle;\n\tstruct ext4_ext_path *path;\n\tstruct ext4_extent *extent;\n\text4_lblk_t offset_lblk, len_lblk, ee_start_lblk = 0;\n\tunsigned int credits, ee_len;\n\tint ret = 0, depth, split_flag = 0;\n\tloff_t ioffset;\n\n\t/*\n\t * We need to test this early because xfstests assumes that an\n\t * insert range of (0, 1) will return EOPNOTSUPP if the file\n\t * system does not support insert range.\n\t */\n\tif (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))\n\t\treturn -EOPNOTSUPP;\n\n\t/* Insert range works only on fs block size aligned offsets. */\n\tif (offset & (EXT4_CLUSTER_SIZE(sb) - 1) ||\n\t\t\tlen & (EXT4_CLUSTER_SIZE(sb) - 1))\n\t\treturn -EINVAL;\n\n\tif (!S_ISREG(inode->i_mode))\n\t\treturn -EOPNOTSUPP;\n\n\ttrace_ext4_insert_range(inode, offset, len);\n\n\toffset_lblk = offset >> EXT4_BLOCK_SIZE_BITS(sb);\n\tlen_lblk = len >> EXT4_BLOCK_SIZE_BITS(sb);\n\n\t/* Call ext4_force_commit to flush all data in case of data=journal */\n\tif (ext4_should_journal_data(inode)) {\n\t\tret = ext4_force_commit(inode->i_sb);\n\t\tif (ret)\n\t\t\treturn ret;\n\t}\n\n\t/*\n\t * Need to round down to align start offset to page size boundary\n\t * for page size > block size.\n\t */\n\tioffset = round_down(offset, PAGE_SIZE);\n\n\t/* Write out all dirty pages */\n\tret = filemap_write_and_wait_range(inode->i_mapping, ioffset,\n\t\t\tLLONG_MAX);\n\tif (ret)\n\t\treturn ret;\n\n\t/* Take mutex lock */\n\tmutex_lock(&inode->i_mutex);\n\n\t/* Currently just for extent based files */\n\tif (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {\n\t\tret = -EOPNOTSUPP;\n\t\tgoto out_mutex;\n\t}\n\n\t/* Check for wrap through zero */\n\tif (inode->i_size + len > inode->i_sb->s_maxbytes) {\n\t\tret = -EFBIG;\n\t\tgoto out_mutex;\n\t}\n\n\t/* Offset should be less than i_size */\n\tif (offset >= i_size_read(inode)) {\n\t\tret = -EINVAL;\n\t\tgoto out_mutex;\n\t}\n\n\ttruncate_pagecache(inode, ioffset);\n\n\t/* Wait for existing dio to complete */\n\text4_inode_block_unlocked_dio(inode);\n\tinode_dio_wait(inode);\n\n\tcredits = ext4_writepage_trans_blocks(inode);\n\thandle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);\n\tif (IS_ERR(handle)) {\n\t\tret = PTR_ERR(handle);\n\t\tgoto out_dio;\n\t}\n\n\t/* Expand file to avoid data loss if there is error while shifting */\n\tinode->i_size += len;\n\tEXT4_I(inode)->i_disksize += len;\n\tinode->i_mtime = inode->i_ctime = ext4_current_time(inode);\n\tret = ext4_mark_inode_dirty(handle, inode);\n\tif (ret)\n\t\tgoto out_stop;\n\n\tdown_write(&EXT4_I(inode)->i_data_sem);\n\text4_discard_preallocations(inode);\n\n\tpath = ext4_find_extent(inode, offset_lblk, NULL, 0);\n\tif (IS_ERR(path)) {\n\t\tup_write(&EXT4_I(inode)->i_data_sem);\n\t\tgoto out_stop;\n\t}\n\n\tdepth = ext_depth(inode);\n\textent = path[depth].p_ext;\n\tif (extent) {\n\t\tee_start_lblk = le32_to_cpu(extent->ee_block);\n\t\tee_len = ext4_ext_get_actual_len(extent);\n\n\t\t/*\n\t\t * If offset_lblk is not the starting block of extent, split\n\t\t * the extent @offset_lblk\n\t\t */\n\t\tif ((offset_lblk > ee_start_lblk) &&\n\t\t\t\t(offset_lblk < (ee_start_lblk + ee_len))) {\n\t\t\tif (ext4_ext_is_unwritten(extent))\n\t\t\t\tsplit_flag = EXT4_EXT_MARK_UNWRIT1 |\n\t\t\t\t\tEXT4_EXT_MARK_UNWRIT2;\n\t\t\tret = ext4_split_extent_at(handle, inode, &path,\n\t\t\t\t\toffset_lblk, split_flag,\n\t\t\t\t\tEXT4_EX_NOCACHE |\n\t\t\t\t\tEXT4_GET_BLOCKS_PRE_IO |\n\t\t\t\t\tEXT4_GET_BLOCKS_METADATA_NOFAIL);\n\t\t}\n\n\t\text4_ext_drop_refs(path);\n\t\tkfree(path);\n\t\tif (ret < 0) {\n\t\t\tup_write(&EXT4_I(inode)->i_data_sem);\n\t\t\tgoto out_stop;\n\t\t}\n\t}\n\n\tret = ext4_es_remove_extent(inode, offset_lblk,\n\t\t\tEXT_MAX_BLOCKS - offset_lblk);\n\tif (ret) {\n\t\tup_write(&EXT4_I(inode)->i_data_sem);\n\t\tgoto out_stop;\n\t}\n\n\t/*\n\t * if offset_lblk lies in a hole which is at start of file, use\n\t * ee_start_lblk to shift extents\n\t */\n\tret = ext4_ext_shift_extents(inode, handle,\n\t\tee_start_lblk > offset_lblk ? ee_start_lblk : offset_lblk,\n\t\tlen_lblk, SHIFT_RIGHT);\n\n\tup_write(&EXT4_I(inode)->i_data_sem);\n\tif (IS_SYNC(inode))\n\t\text4_handle_sync(handle);\n\nout_stop:\n\text4_journal_stop(handle);\nout_dio:\n\text4_inode_resume_unlocked_dio(inode);\nout_mutex:\n\tmutex_unlock(&inode->i_mutex);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'ext4: fix races between page faults and hole punching\n\nCurrently, page faults and hole punching are completely unsynchronized.\nThis can result in page fault faulting in a page into a range that we\nare punching after truncate_pagecache_range() has been called and thus\nwe can end up with a page mapped to disk blocks that will be shortly\nfreed. Filesystem corruption will shortly follow. Note that the same\nrace is avoided for truncate by checking page fault offset against\ni_size but there isn't similar mechanism available for punching holes.\n\nFix the problem by creating new rw semaphore i_mmap_sem in inode and\ngrab it for writing over truncate, hole punching, and other functions\nremoving blocks from extent tree and for read over page faults. We\ncannot easily use i_data_sem for this since that ranks below transaction\nstart and we need something ranking above it so that it can be held over\nthe whole truncate / hole punching operation. Also remove various\nworkarounds we had in the code to reduce race window when page fault\ncould have created pages with stale mapping information.\n\nSigned-off-by: Jan Kara \nSigned-off-by: Theodore Ts'o '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ext4_collapse_range(struct inode *inode, loff_t offset, loff_t len)\n{\n\tstruct super_block *sb = inode->i_sb;\n\text4_lblk_t punch_start, punch_stop;\n\thandle_t *handle;\n\tunsigned int credits;\n\tloff_t new_size, ioffset;\n\tint ret;\n\n\t/*\n\t * We need to test this early because xfstests assumes that a\n\t * collapse range of (0, 1) will return EOPNOTSUPP if the file\n\t * system does not support collapse range.\n\t */\n\tif (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))\n\t\treturn -EOPNOTSUPP;\n\n\t/* Collapse range works only on fs block size aligned offsets. */\n\tif (offset & (EXT4_CLUSTER_SIZE(sb) - 1) ||\n\t len & (EXT4_CLUSTER_SIZE(sb) - 1))\n\t\treturn -EINVAL;\n\n\tif (!S_ISREG(inode->i_mode))\n\t\treturn -EINVAL;\n\n\ttrace_ext4_collapse_range(inode, offset, len);\n\n\tpunch_start = offset >> EXT4_BLOCK_SIZE_BITS(sb);\n\tpunch_stop = (offset + len) >> EXT4_BLOCK_SIZE_BITS(sb);\n\n\t/* Call ext4_force_commit to flush all data in case of data=journal. */\n\tif (ext4_should_journal_data(inode)) {\n\t\tret = ext4_force_commit(inode->i_sb);\n\t\tif (ret)\n\t\t\treturn ret;\n\t}\n\n\t/*\n\t * Need to round down offset to be aligned with page size boundary\n\t * for page size > block size.\n\t */\n\tioffset = round_down(offset, PAGE_SIZE);\n\n\t/* Write out all dirty pages */\n\tret = filemap_write_and_wait_range(inode->i_mapping, ioffset,\n\t\t\t\t\t LLONG_MAX);\n\tif (ret)\n\t\treturn ret;\n\n\t/* Take mutex lock */\n\tmutex_lock(&inode->i_mutex);\n\n\t/*\n\t * There is no need to overlap collapse range with EOF, in which case\n\t * it is effectively a truncate operation\n\t */\n\tif (offset + len >= i_size_read(inode)) {\n\t\tret = -EINVAL;\n\t\tgoto out_mutex;\n\t}\n\n\t/* Currently just for extent based files */\n\tif (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {\n\t\tret = -EOPNOTSUPP;\n\t\tgoto out_mutex;\n\t}\n\n\t/* Wait for existing dio to complete */\n\text4_inode_block_unlocked_dio(inode);\n\tinode_dio_wait(inode);\n\n\t/*\n\t * Prevent page faults from reinstantiating pages we have released from\n\t * page cache.\n\t */\n\tdown_write(&EXT4_I(inode)->i_mmap_sem);\n\ttruncate_pagecache(inode, ioffset);\n\n\tcredits = ext4_writepage_trans_blocks(inode);\n\thandle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);\n\tif (IS_ERR(handle)) {\n\t\tret = PTR_ERR(handle);\n\t\tgoto out_mmap;\n\t}\n\n\tdown_write(&EXT4_I(inode)->i_data_sem);\n\text4_discard_preallocations(inode);\n\n\tret = ext4_es_remove_extent(inode, punch_start,\n\t\t\t\t EXT_MAX_BLOCKS - punch_start);\n\tif (ret) {\n\t\tup_write(&EXT4_I(inode)->i_data_sem);\n\t\tgoto out_stop;\n\t}\n\n\tret = ext4_ext_remove_space(inode, punch_start, punch_stop - 1);\n\tif (ret) {\n\t\tup_write(&EXT4_I(inode)->i_data_sem);\n\t\tgoto out_stop;\n\t}\n\text4_discard_preallocations(inode);\n\n\tret = ext4_ext_shift_extents(inode, handle, punch_stop,\n\t\t\t\t punch_stop - punch_start, SHIFT_LEFT);\n\tif (ret) {\n\t\tup_write(&EXT4_I(inode)->i_data_sem);\n\t\tgoto out_stop;\n\t}\n\n\tnew_size = i_size_read(inode) - len;\n\ti_size_write(inode, new_size);\n\tEXT4_I(inode)->i_disksize = new_size;\n\n\tup_write(&EXT4_I(inode)->i_data_sem);\n\tif (IS_SYNC(inode))\n\t\text4_handle_sync(handle);\n\tinode->i_mtime = inode->i_ctime = ext4_current_time(inode);\n\text4_mark_inode_dirty(handle, inode);\n\nout_stop:\n\text4_journal_stop(handle);\nout_mmap:\n\tup_write(&EXT4_I(inode)->i_mmap_sem);\n\text4_inode_resume_unlocked_dio(inode);\nout_mutex:\n\tmutex_unlock(&inode->i_mutex);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'ext4: fix races between buffered IO and collapse / insert range\n\nCurrent code implementing FALLOC_FL_COLLAPSE_RANGE and\nFALLOC_FL_INSERT_RANGE is prone to races with buffered writes and page\nfaults. If buffered write or write via mmap manages to squeeze between\nfilemap_write_and_wait_range() and truncate_pagecache() in the fallocate\nimplementations, the written data is simply discarded by\ntruncate_pagecache() although it should have been shifted.\n\nFix the problem by moving filemap_write_and_wait_range() call inside\ni_mutex and i_mmap_sem. That way we are protected against races with\nboth buffered writes and page faults.\n\nSigned-off-by: Jan Kara \nSigned-off-by: Theodore Ts'o '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: srtp_protect_aead (srtp_ctx_t *ctx, srtp_stream_ctx_t *stream, \n\t void *rtp_hdr, unsigned int *pkt_octet_len)\n{\n srtp_hdr_t *hdr = (srtp_hdr_t*)rtp_hdr;\n uint32_t *enc_start; /* pointer to start of encrypted portion */\n int enc_octet_len = 0; /* number of octets in encrypted portion */\n xtd_seq_num_t est; /* estimated xtd_seq_num_t of *hdr */\n int delta; /* delta of local pkt idx and that in hdr */\n err_status_t status;\n int tag_len;\n v128_t iv;\n unsigned int aad_len;\n\n debug_print(mod_srtp, \"function srtp_protect_aead\", NULL);\n\n /*\n * update the key usage limit, and check it to make sure that we\n * didn't just hit either the soft limit or the hard limit, and call\n * the event handler if we hit either.\n */\n switch (key_limit_update(stream->limit)) {\n case key_event_normal:\n break;\n case key_event_hard_limit:\n srtp_handle_event(ctx, stream, event_key_hard_limit);\n return err_status_key_expired;\n case key_event_soft_limit:\n default:\n srtp_handle_event(ctx, stream, event_key_soft_limit);\n break;\n }\n\n /* get tag length from stream */\n tag_len = auth_get_tag_length(stream->rtp_auth);\n\n /*\n * find starting point for encryption and length of data to be\n * encrypted - the encrypted portion starts after the rtp header\n * extension, if present; otherwise, it starts after the last csrc,\n * if any are present\n */\n enc_start = (uint32_t*)hdr + uint32s_in_rtp_header + hdr->cc;\n if (hdr->x == 1) {\n srtp_hdr_xtnd_t *xtn_hdr = (srtp_hdr_xtnd_t*)enc_start;\n enc_start += (ntohs(xtn_hdr->length) + 1);\n }\n if (!((uint8_t*)enc_start < (uint8_t*)hdr + *pkt_octet_len))\n return err_status_parse_err;\n enc_octet_len = (int)(*pkt_octet_len -\n ((uint8_t*)enc_start - (uint8_t*)hdr));\n if (enc_octet_len < 0) return err_status_parse_err;\n\n /*\n * estimate the packet index using the start of the replay window\n * and the sequence number from the header\n */\n delta = rdbx_estimate_index(&stream->rtp_rdbx, &est, ntohs(hdr->seq));\n status = rdbx_check(&stream->rtp_rdbx, delta);\n if (status) {\n\tif (status != err_status_replay_fail || !stream->allow_repeat_tx) {\n\t return status; /* we've been asked to reuse an index */\n\t}\n } else {\n\trdbx_add_index(&stream->rtp_rdbx, delta);\n }\n\n#ifdef NO_64BIT_MATH\n debug_print2(mod_srtp, \"estimated packet index: %08x%08x\",\n high32(est), low32(est));\n#else\n debug_print(mod_srtp, \"estimated packet index: %016llx\", est);\n#endif\n\n /*\n * AEAD uses a new IV formation method\n */\n srtp_calc_aead_iv(stream, &iv, &est, hdr);\n status = cipher_set_iv(stream->rtp_cipher, &iv, direction_encrypt);\n if (status) {\n return err_status_cipher_fail;\n }\n\n /* shift est, put into network byte order */\n#ifdef NO_64BIT_MATH\n est = be64_to_cpu(make64((high32(est) << 16) |\n (low32(est) >> 16),\n low32(est) << 16));\n#else\n est = be64_to_cpu(est << 16);\n#endif\n\n /*\n * Set the AAD over the RTP header \n */\n aad_len = (uint8_t *)enc_start - (uint8_t *)hdr;\n status = cipher_set_aad(stream->rtp_cipher, (uint8_t*)hdr, aad_len);\n if (status) {\n return ( err_status_cipher_fail);\n }\n\n /* Encrypt the payload */\n status = cipher_encrypt(stream->rtp_cipher,\n (uint8_t*)enc_start, (unsigned int *)&enc_octet_len);\n if (status) {\n return err_status_cipher_fail;\n }\n /*\n * If we're doing GCM, we need to get the tag\n * and append that to the output\n */\n status = cipher_get_tag(stream->rtp_cipher, \n (uint8_t*)enc_start+enc_octet_len, &tag_len);\n if (status) {\n\treturn ( err_status_cipher_fail);\n }\n\n /* increase the packet length by the length of the auth tag */\n *pkt_octet_len += tag_len;\n\n return err_status_ok;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Allow zero payload packets to pass bounds check.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void tm_reclaim_thread(struct thread_struct *thr,\n\t\t\t struct thread_info *ti, uint8_t cause)\n{\n\tunsigned long msr_diff = 0;\n\n\t/*\n\t * If FP/VSX registers have been already saved to the\n\t * thread_struct, move them to the transact_fp array.\n\t * We clear the TIF_RESTORE_TM bit since after the reclaim\n\t * the thread will no longer be transactional.\n\t */\n\tif (test_ti_thread_flag(ti, TIF_RESTORE_TM)) {\n\t\tmsr_diff = thr->ckpt_regs.msr & ~thr->regs->msr;\n\t\tif (msr_diff & MSR_FP)\n\t\t\tmemcpy(&thr->transact_fp, &thr->fp_state,\n\t\t\t sizeof(struct thread_fp_state));\n\t\tif (msr_diff & MSR_VEC)\n\t\t\tmemcpy(&thr->transact_vr, &thr->vr_state,\n\t\t\t sizeof(struct thread_vr_state));\n\t\tclear_ti_thread_flag(ti, TIF_RESTORE_TM);\n\t\tmsr_diff &= MSR_FP | MSR_VEC | MSR_VSX | MSR_FE0 | MSR_FE1;\n\t}\n\n\ttm_reclaim(thr, thr->regs->msr, cause);\n\n\t/* Having done the reclaim, we now have the checkpointed\n\t * FP/VSX values in the registers. These might be valid\n\t * even if we have previously called enable_kernel_fp() or\n\t * flush_fp_to_thread(), so update thr->regs->msr to\n\t * indicate their current validity.\n\t */\n\tthr->regs->msr |= msr_diff;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284'], 'message': 'powerpc/tm: Check for already reclaimed tasks\n\nCurrently we can hit a scenario where we'll tm_reclaim() twice. This\nresults in a TM bad thing exception because the second reclaim occurs\nwhen not in suspend mode.\n\nThe scenario in which this can happen is the following. We attempt to\ndeliver a signal to userspace. To do this we need obtain the stack\npointer to write the signal context. To get this stack pointer we\nmust tm_reclaim() in case we need to use the checkpointed stack\npointer (see get_tm_stackpointer()). Normally we'd then return\ndirectly to userspace to deliver the signal without going through\n__switch_to().\n\nUnfortunatley, if at this point we get an error (such as a bad\nuserspace stack pointer), we need to exit the process. The exit will\nresult in a __switch_to(). __switch_to() will attempt to save the\nprocess state which results in another tm_reclaim(). This\ntm_reclaim() now causes a TM Bad Thing exception as this state has\nalready been saved and the processor is no longer in TM suspend mode.\nWhee!\n\nThis patch checks the state of the MSR to ensure we are TM suspended\nbefore we attempt the tm_reclaim(). If we've already saved the state\naway, we should no longer be in TM suspend mode. This has the\nadditional advantage of checking for a potential TM Bad Thing\nexception.\n\nFound using syscall fuzzer.\n\nFixes: fb09692e71f1 (\"powerpc: Add reclaim and recheckpoint functions for context switching transactional memory processes\")\nCc: stable@vger.kernel.org # v3.9+\nSigned-off-by: Michael Neuling \nSigned-off-by: Michael Ellerman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void tokenadd(struct jv_parser* p, char c) {\n assert(p->tokenpos <= p->tokenlen);\n if (p->tokenpos == p->tokenlen) {\n p->tokenlen = p->tokenlen*2 + 256;\n p->tokenbuf = jv_mem_realloc(p->tokenbuf, p->tokenlen);\n }\n assert(p->tokenpos < p->tokenlen);\n p->tokenbuf[p->tokenpos++] = c;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Heap buffer overflow in tokenadd() (fix #105)\n\nThis was an off-by one: the NUL terminator byte was not allocated on\nresize. This was triggered by JSON-encoded numbers longer than 256\nbytes.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: SecureVector EME_PKCS1v15::unpad(const byte in[], size_t inlen,\n size_t key_len) const\n {\n if(inlen != key_len / 8 || inlen < 10 || in[0] != 0x02)\n throw Decoding_Error(\"PKCS1::unpad\");\n\n size_t seperator = 0;\n for(size_t j = 0; j != inlen; ++j)\n if(in[j] == 0)\n {\n seperator = j;\n break;\n }\n if(seperator < 9)\n throw Decoding_Error(\"PKCS1::unpad\");\n\n return SecureVector(in + seperator + 1, inlen - seperator - 1);\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Fixes for CVE-2015-7827 and CVE-2016-2849'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: PHP_FUNCTION(bcmul)\n{\n\tchar *left, *right;\n\tint left_len, right_len;\n\tlong scale_param = 0;\n\tbc_num first, second, result;\n\tint scale = BCG(bc_precision), argc = ZEND_NUM_ARGS();\n\n\tif (zend_parse_parameters(argc TSRMLS_CC, \"ss|l\", &left, &left_len, &right, &right_len, &scale_param) == FAILURE) {\n\t\treturn;\n\t}\n\t\n\tif (argc == 3) {\n\t\tscale = (int) ((int)scale_param < 0) ? 0 : scale_param;\n\t}\n\t\n\tbc_init_num(&first TSRMLS_CC);\n\tbc_init_num(&second TSRMLS_CC);\n\tbc_init_num(&result TSRMLS_CC);\n\tphp_str2num(&first, left TSRMLS_CC);\n\tphp_str2num(&second, right TSRMLS_CC);\n\tbc_multiply (first, second, &result, scale TSRMLS_CC);\n\n\tif (result->n_scale > scale) {\n\t\tresult->n_scale = scale;\n\t}\n\n\tZ_STRVAL_P(return_value) = bc_num2str(result);\n\tZ_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value));\n\tZ_TYPE_P(return_value) = IS_STRING;\n\tbc_free_num(&first);\n\tbc_free_num(&second);\n\tbc_free_num(&result);\n\treturn;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #72093: bcpowmod accepts negative scale and corrupts _one_ definition\n\nWe can not modify result since it can be copy of _zero_ or _one_, etc. and\n\"copy\" in bcmath is just bumping the refcount.\n\nConflicts:\n\tmain/php_version.h'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void php_xml_parser_create_impl(INTERNAL_FUNCTION_PARAMETERS, int ns_support) /* {{{ */\n{\n\txml_parser *parser;\n\tint auto_detect = 0;\n\n\tchar *encoding_param = NULL;\n\tint encoding_param_len = 0;\n\n\tchar *ns_param = NULL;\n\tint ns_param_len = 0;\n\t\n\tXML_Char *encoding;\n\t\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (ns_support ? \"|ss\": \"|s\"), &encoding_param, &encoding_param_len, &ns_param, &ns_param_len) == FAILURE) {\n\t\tRETURN_FALSE;\n\t}\n\n\tif (encoding_param != NULL) {\n\t\t/* The supported encoding types are hardcoded here because\n\t\t * we are limited to the encodings supported by expat/xmltok.\n\t\t */\n\t\tif (encoding_param_len == 0) {\n\t\t\tencoding = XML(default_encoding);\n\t\t\tauto_detect = 1;\n\t\t} else if (strcasecmp(encoding_param, \"ISO-8859-1\") == 0) {\n\t\t\tencoding = \"ISO-8859-1\";\n\t\t} else if (strcasecmp(encoding_param, \"UTF-8\") == 0) {\n\t\t\tencoding = \"UTF-8\";\n\t\t} else if (strcasecmp(encoding_param, \"US-ASCII\") == 0) {\n\t\t\tencoding = \"US-ASCII\";\n\t\t} else {\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"unsupported source encoding \\\"%s\\\"\", encoding_param);\n\t\t\tRETURN_FALSE;\n\t\t}\n\t} else {\n\t\tencoding = XML(default_encoding);\n\t}\n\n\tif (ns_support && ns_param == NULL){\n\t\tns_param = \":\";\n\t}\n\n\tparser = ecalloc(1, sizeof(xml_parser));\n\tparser->parser = XML_ParserCreate_MM((auto_detect ? NULL : encoding),\n &php_xml_mem_hdlrs, ns_param);\n\n\tparser->target_encoding = encoding;\n\tparser->case_folding = 1;\n\tparser->object = NULL;\n\tparser->isparsing = 0;\n\n\tXML_SetUserData(parser->parser, parser);\n\n\tZEND_REGISTER_RESOURCE(return_value, parser,le_xml_parser);\n\tparser->index = Z_LVAL_P(return_value);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix bug #72099: xml_parse_into_struct segmentation fault'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int propagate_mnt(struct mount *dest_mnt, struct mountpoint *dest_mp,\n\t\t struct mount *source_mnt, struct hlist_head *tree_list)\n{\n\tstruct mount *m, *n;\n\tint ret = 0;\n\n\t/*\n\t * we don't want to bother passing tons of arguments to\n\t * propagate_one(); everything is serialized by namespace_sem,\n\t * so globals will do just fine.\n\t */\n\tuser_ns = current->nsproxy->mnt_ns->user_ns;\n\tlast_dest = dest_mnt;\n\tlast_source = source_mnt;\n\tmp = dest_mp;\n\tlist = tree_list;\n\tdest_master = dest_mnt->mnt_master;\n\n\t/* all peers of dest_mnt, except dest_mnt itself */\n\tfor (n = next_peer(dest_mnt); n != dest_mnt; n = next_peer(n)) {\n\t\tret = propagate_one(n);\n\t\tif (ret)\n\t\t\tgoto out;\n\t}\n\n\t/* all slave groups */\n\tfor (m = next_group(dest_mnt, dest_mnt); m;\n\t\t\tm = next_group(m, dest_mnt)) {\n\t\t/* everything in that slave group */\n\t\tn = m;\n\t\tdo {\n\t\t\tret = propagate_one(n);\n\t\t\tif (ret)\n\t\t\t\tgoto out;\n\t\t\tn = next_peer(n);\n\t\t} while (n != m);\n\t}\nout:\n\tread_seqlock_excl(&mount_lock);\n\thlist_for_each_entry(n, tree_list, mnt_hash) {\n\t\tm = n->mnt_parent;\n\t\tif (m->mnt_master != dest_mnt->mnt_master)\n\t\t\tCLEAR_MNT_MARK(m->mnt_master);\n\t}\n\tread_sequnlock_excl(&mount_lock);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'propogate_mnt: Handle the first propogated copy being a slave\n\nWhen the first propgated copy was a slave the following oops would result:\n> BUG: unable to handle kernel NULL pointer dereference at 0000000000000010\n> IP: [] propagate_one+0xbe/0x1c0\n> PGD bacd4067 PUD bac66067 PMD 0\n> Oops: 0000 [#1] SMP\n> Modules linked in:\n> CPU: 1 PID: 824 Comm: mount Not tainted 4.6.0-rc5userns+ #1523\n> Hardware name: Bochs Bochs, BIOS Bochs 01/01/2007\n> task: ffff8800bb0a8000 ti: ffff8800bac3c000 task.ti: ffff8800bac3c000\n> RIP: 0010:[] [] propagate_one+0xbe/0x1c0\n> RSP: 0018:ffff8800bac3fd38 EFLAGS: 00010283\n> RAX: 0000000000000000 RBX: ffff8800bb77ec00 RCX: 0000000000000010\n> RDX: 0000000000000000 RSI: ffff8800bb58c000 RDI: ffff8800bb58c480\n> RBP: ffff8800bac3fd48 R08: 0000000000000001 R09: 0000000000000000\n> R10: 0000000000001ca1 R11: 0000000000001c9d R12: 0000000000000000\n> R13: ffff8800ba713800 R14: ffff8800bac3fda0 R15: ffff8800bb77ec00\n> FS: 00007f3c0cd9b7e0(0000) GS:ffff8800bfb00000(0000) knlGS:0000000000000000\n> CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033\n> CR2: 0000000000000010 CR3: 00000000bb79d000 CR4: 00000000000006e0\n> Stack:\n> ffff8800bb77ec00 0000000000000000 ffff8800bac3fd88 ffffffff811fbf85\n> ffff8800bac3fd98 ffff8800bb77f080 ffff8800ba713800 ffff8800bb262b40\n> 0000000000000000 0000000000000000 ffff8800bac3fdd8 ffffffff811f1da0\n> Call Trace:\n> [] propagate_mnt+0x105/0x140\n> [] attach_recursive_mnt+0x120/0x1e0\n> [] graft_tree+0x63/0x70\n> [] do_add_mount+0x9b/0x100\n> [] do_mount+0x2aa/0xdf0\n> [] ? strndup_user+0x4e/0x70\n> [] SyS_mount+0x75/0xc0\n> [] do_syscall_64+0x4b/0xa0\n> [] entry_SYSCALL64_slow_path+0x25/0x25\n> Code: 00 00 75 ec 48 89 0d 02 22 22 01 8b 89 10 01 00 00 48 89 05 fd 21 22 01 39 8e 10 01 00 00 0f 84 e0 00 00 00 48 8b 80 d8 00 00 00 <48> 8b 50 10 48 89 05 df 21 22 01 48 89 15 d0 21 22 01 8b 53 30\n> RIP [] propagate_one+0xbe/0x1c0\n> RSP \n> CR2: 0000000000000010\n> ---[ end trace 2725ecd95164f217 ]---\n\nThis oops happens with the namespace_sem held and can be triggered by\nnon-root users. An all around not pleasant experience.\n\nTo avoid this scenario when finding the appropriate source mount to\ncopy stop the walk up the mnt_master chain when the first source mount\nis encountered.\n\nFurther rewrite the walk up the last_source mnt_master chain so that\nit is clear what is going on.\n\nThe reason why the first source mount is special is that it it's\nmnt_parent is not a mount in the dest_mnt propagation tree, and as\nsuch termination conditions based up on the dest_mnt mount propgation\ntree do not make sense.\n\nTo avoid other kinds of confusion last_dest is not changed when\ncomputing last_source. last_dest is only used once in propagate_one\nand that is above the point of the code being modified, so changing\nthe global variable is meaningless and confusing.\n\nCc: stable@vger.kernel.org\nfixes: f2ebb3a921c1ca1e2ddd9242e95a1989a50c4c68 (\"smarter propagate_mnt()\")\nReported-by: Tycho Andersen \nReviewed-by: Seth Forshee \nTested-by: Seth Forshee \nSigned-off-by: \"Eric W. Biederman\" '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void bpf_map_inc(struct bpf_map *map, bool uref)\n{\n\tatomic_inc(&map->refcnt);\n\tif (uref)\n\t\tatomic_inc(&map->usercnt);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'bpf: fix refcnt overflow\n\nOn a system with >32Gbyte of phyiscal memory and infinite RLIMIT_MEMLOCK,\nthe malicious application may overflow 32-bit bpf program refcnt.\nIt's also possible to overflow map refcnt on 1Tb system.\nImpose 32k hard limit which means that the same bpf program or\nmap cannot be shared by more than 32k processes.\n\nFixes: 1be7f75d1668 (\"bpf: enable non-root eBPF programs\")\nReported-by: Jann Horn \nSigned-off-by: Alexei Starovoitov \nAcked-by: Daniel Borkmann \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: mbed_connect_step1(struct connectdata *conn,\n int sockindex)\n{\n struct SessionHandle *data = conn->data;\n struct ssl_connect_data* connssl = &conn->ssl[sockindex];\n\n bool sni = TRUE; /* default is SNI enabled */\n int ret = -1;\n#ifdef ENABLE_IPV6\n struct in6_addr addr;\n#else\n struct in_addr addr;\n#endif\n void *old_session = NULL;\n char errorbuf[128];\n errorbuf[0]=0;\n\n /* mbedTLS only supports SSLv3 and TLSv1 */\n if(data->set.ssl.version == CURL_SSLVERSION_SSLv2) {\n failf(data, \"mbedTLS does not support SSLv2\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n else if(data->set.ssl.version == CURL_SSLVERSION_SSLv3)\n sni = FALSE; /* SSLv3 has no SNI */\n\n#ifdef THREADING_SUPPORT\n entropy_init_mutex(&entropy);\n mbedtls_ctr_drbg_init(&connssl->ctr_drbg);\n\n ret = mbedtls_ctr_drbg_seed(&connssl->ctr_drbg, entropy_func_mutex,\n &entropy, NULL, 0);\n if(ret) {\n#ifdef MBEDTLS_ERROR_C\n mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));\n#endif /* MBEDTLS_ERROR_C */\n failf(data, \"Failed - mbedTLS: ctr_drbg_init returned (-0x%04X) %s\\n\",\n -ret, errorbuf);\n }\n#else\n mbedtls_entropy_init(&connssl->entropy);\n mbedtls_ctr_drbg_init(&connssl->ctr_drbg);\n\n ret = mbedtls_ctr_drbg_seed(&connssl->ctr_drbg, mbedtls_entropy_func,\n &connssl->entropy, NULL, 0);\n if(ret) {\n#ifdef MBEDTLS_ERROR_C\n mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));\n#endif /* MBEDTLS_ERROR_C */\n failf(data, \"Failed - mbedTLS: ctr_drbg_init returned (-0x%04X) %s\\n\",\n -ret, errorbuf);\n }\n#endif /* THREADING_SUPPORT */\n\n /* Load the trusted CA */\n mbedtls_x509_crt_init(&connssl->cacert);\n\n if(data->set.str[STRING_SSL_CAFILE]) {\n ret = mbedtls_x509_crt_parse_file(&connssl->cacert,\n data->set.str[STRING_SSL_CAFILE]);\n\n if(ret<0) {\n#ifdef MBEDTLS_ERROR_C\n mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));\n#endif /* MBEDTLS_ERROR_C */\n failf(data, \"Error reading ca cert file %s - mbedTLS: (-0x%04X) %s\",\n data->set.str[STRING_SSL_CAFILE], -ret, errorbuf);\n\n if(data->set.ssl.verifypeer)\n return CURLE_SSL_CACERT_BADFILE;\n }\n }\n\n if(data->set.str[STRING_SSL_CAPATH]) {\n ret = mbedtls_x509_crt_parse_path(&connssl->cacert,\n data->set.str[STRING_SSL_CAPATH]);\n\n if(ret<0) {\n#ifdef MBEDTLS_ERROR_C\n mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));\n#endif /* MBEDTLS_ERROR_C */\n failf(data, \"Error reading ca cert path %s - mbedTLS: (-0x%04X) %s\",\n data->set.str[STRING_SSL_CAPATH], -ret, errorbuf);\n\n if(data->set.ssl.verifypeer)\n return CURLE_SSL_CACERT_BADFILE;\n }\n }\n\n /* Load the client certificate */\n mbedtls_x509_crt_init(&connssl->clicert);\n\n if(data->set.str[STRING_CERT]) {\n ret = mbedtls_x509_crt_parse_file(&connssl->clicert,\n data->set.str[STRING_CERT]);\n\n if(ret) {\n#ifdef MBEDTLS_ERROR_C\n mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));\n#endif /* MBEDTLS_ERROR_C */\n failf(data, \"Error reading client cert file %s - mbedTLS: (-0x%04X) %s\",\n data->set.str[STRING_CERT], -ret, errorbuf);\n\n return CURLE_SSL_CERTPROBLEM;\n }\n }\n\n /* Load the client private key */\n mbedtls_pk_init(&connssl->pk);\n\n if(data->set.str[STRING_KEY]) {\n ret = mbedtls_pk_parse_keyfile(&connssl->pk, data->set.str[STRING_KEY],\n data->set.str[STRING_KEY_PASSWD]);\n if(ret == 0 && !mbedtls_pk_can_do(&connssl->pk, MBEDTLS_PK_RSA))\n ret = MBEDTLS_ERR_PK_TYPE_MISMATCH;\n\n if(ret) {\n#ifdef MBEDTLS_ERROR_C\n mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));\n#endif /* MBEDTLS_ERROR_C */\n failf(data, \"Error reading private key %s - mbedTLS: (-0x%04X) %s\",\n data->set.str[STRING_KEY], -ret, errorbuf);\n\n return CURLE_SSL_CERTPROBLEM;\n }\n }\n\n /* Load the CRL */\n mbedtls_x509_crl_init(&connssl->crl);\n\n if(data->set.str[STRING_SSL_CRLFILE]) {\n ret = mbedtls_x509_crl_parse_file(&connssl->crl,\n data->set.str[STRING_SSL_CRLFILE]);\n\n if(ret) {\n#ifdef MBEDTLS_ERROR_C\n mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));\n#endif /* MBEDTLS_ERROR_C */\n failf(data, \"Error reading CRL file %s - mbedTLS: (-0x%04X) %s\",\n data->set.str[STRING_SSL_CRLFILE], -ret, errorbuf);\n\n return CURLE_SSL_CRL_BADFILE;\n }\n }\n\n infof(data, \"mbedTLS: Connecting to %s:%d\\n\",\n conn->host.name, conn->remote_port);\n\n mbedtls_ssl_config_init(&connssl->config);\n\n mbedtls_ssl_init(&connssl->ssl);\n if(mbedtls_ssl_setup(&connssl->ssl, &connssl->config)) {\n failf(data, \"mbedTLS: ssl_init failed\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n ret = mbedtls_ssl_config_defaults(&connssl->config,\n MBEDTLS_SSL_IS_CLIENT,\n MBEDTLS_SSL_TRANSPORT_STREAM,\n MBEDTLS_SSL_PRESET_DEFAULT);\n if(ret) {\n failf(data, \"mbedTLS: ssl_config failed\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n\n /* new profile with RSA min key len = 1024 ... */\n mbedtls_ssl_conf_cert_profile(&connssl->config,\n &mbedtls_x509_crt_profile_fr);\n\n switch(data->set.ssl.version) {\n case CURL_SSLVERSION_DEFAULT:\n case CURL_SSLVERSION_TLSv1:\n mbedtls_ssl_conf_min_version(&connssl->config, MBEDTLS_SSL_MAJOR_VERSION_3,\n MBEDTLS_SSL_MINOR_VERSION_1);\n infof(data, \"mbedTLS: Set min SSL version to TLS 1.0\\n\");\n break;\n case CURL_SSLVERSION_SSLv3:\n mbedtls_ssl_conf_min_version(&connssl->config, MBEDTLS_SSL_MAJOR_VERSION_3,\n MBEDTLS_SSL_MINOR_VERSION_0);\n mbedtls_ssl_conf_max_version(&connssl->config, MBEDTLS_SSL_MAJOR_VERSION_3,\n MBEDTLS_SSL_MINOR_VERSION_0);\n infof(data, \"mbedTLS: Set SSL version to SSLv3\\n\");\n break;\n case CURL_SSLVERSION_TLSv1_0:\n mbedtls_ssl_conf_min_version(&connssl->config, MBEDTLS_SSL_MAJOR_VERSION_3,\n MBEDTLS_SSL_MINOR_VERSION_1);\n mbedtls_ssl_conf_max_version(&connssl->config, MBEDTLS_SSL_MAJOR_VERSION_3,\n MBEDTLS_SSL_MINOR_VERSION_1);\n infof(data, \"mbedTLS: Set SSL version to TLS 1.0\\n\");\n break;\n case CURL_SSLVERSION_TLSv1_1:\n mbedtls_ssl_conf_min_version(&connssl->config, MBEDTLS_SSL_MAJOR_VERSION_3,\n MBEDTLS_SSL_MINOR_VERSION_2);\n mbedtls_ssl_conf_max_version(&connssl->config, MBEDTLS_SSL_MAJOR_VERSION_3,\n MBEDTLS_SSL_MINOR_VERSION_2);\n infof(data, \"mbedTLS: Set SSL version to TLS 1.1\\n\");\n break;\n case CURL_SSLVERSION_TLSv1_2:\n mbedtls_ssl_conf_min_version(&connssl->config, MBEDTLS_SSL_MAJOR_VERSION_3,\n MBEDTLS_SSL_MINOR_VERSION_3);\n mbedtls_ssl_conf_max_version(&connssl->config, MBEDTLS_SSL_MAJOR_VERSION_3,\n MBEDTLS_SSL_MINOR_VERSION_3);\n infof(data, \"mbedTLS: Set SSL version to TLS 1.2\\n\");\n break;\n default:\n failf(data, \"mbedTLS: Unsupported SSL protocol version\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n\n mbedtls_ssl_conf_authmode(&connssl->config, MBEDTLS_SSL_VERIFY_OPTIONAL);\n\n mbedtls_ssl_conf_rng(&connssl->config, mbedtls_ctr_drbg_random,\n &connssl->ctr_drbg);\n mbedtls_ssl_set_bio(&connssl->ssl, &conn->sock[sockindex],\n mbedtls_net_send,\n mbedtls_net_recv,\n NULL /* rev_timeout() */);\n\n mbedtls_ssl_conf_ciphersuites(&connssl->config,\n mbedtls_ssl_list_ciphersuites());\n if(!Curl_ssl_getsessionid(conn, &old_session, NULL)) {\n ret = mbedtls_ssl_set_session(&connssl->ssl, old_session);\n if(ret) {\n failf(data, \"mbedtls_ssl_set_session returned -0x%x\", -ret);\n return CURLE_SSL_CONNECT_ERROR;\n }\n infof(data, \"mbedTLS re-using session\\n\");\n }\n\n mbedtls_ssl_conf_ca_chain(&connssl->config,\n &connssl->cacert,\n &connssl->crl);\n\n if(data->set.str[STRING_KEY]) {\n mbedtls_ssl_conf_own_cert(&connssl->config,\n &connssl->clicert, &connssl->pk);\n }\n if(!Curl_inet_pton(AF_INET, conn->host.name, &addr) &&\n#ifdef ENABLE_IPV6\n !Curl_inet_pton(AF_INET6, conn->host.name, &addr) &&\n#endif\n sni && mbedtls_ssl_set_hostname(&connssl->ssl, conn->host.name)) {\n infof(data, \"WARNING: failed to configure \"\n \"server name indication (SNI) TLS extension\\n\");\n }\n\n#ifdef HAS_ALPN\n if(conn->bits.tls_enable_alpn) {\n const char **p = &connssl->protocols[0];\n#ifdef USE_NGHTTP2\n if(data->set.httpversion >= CURL_HTTP_VERSION_2)\n *p++ = NGHTTP2_PROTO_VERSION_ID;\n#endif\n *p++ = ALPN_HTTP_1_1;\n *p = NULL;\n /* this function doesn't clone the protocols array, which is why we need\n to keep it around */\n if(mbedtls_ssl_conf_alpn_protocols(&connssl->config,\n &connssl->protocols[0])) {\n failf(data, \"Failed setting ALPN protocols\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n for(p = &connssl->protocols[0]; *p; ++p)\n infof(data, \"ALPN, offering %s\\n\", *p);\n }\n#endif\n\n#ifdef MBEDTLS_DEBUG\n mbedtls_ssl_conf_dbg(&connssl->config, mbedtls_debug, data);\n#endif\n\n connssl->connecting_state = ssl_connect_2;\n\n return CURLE_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'mbedtls/polarssl: set \"hostname\" unconditionally\n\n...as otherwise the TLS libs will skip the CN/SAN check and just allow\nconnection to any server. curl previously skipped this function when SNI\nwasn't used or when connecting to an IP address specified host.\n\nCVE-2016-3739\n\nBug: https://curl.haxx.se/docs/adv_20160518A.html\nReported-by: Moti Avrahami'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: xmlZMemBuffGetContent( xmlZMemBuffPtr buff, char ** data_ref ) {\n\n int\t\tzlgth = -1;\n int\t\tz_err;\n\n if ( ( buff == NULL ) || ( data_ref == NULL ) )\n\treturn ( -1 );\n\n /* Need to loop until compression output buffers are flushed */\n\n do\n {\n\tz_err = deflate( &buff->zctrl, Z_FINISH );\n\tif ( z_err == Z_OK ) {\n\t /* In this case Z_OK means more buffer space needed */\n\n\t if ( xmlZMemBuffExtend( buff, buff->size ) == -1 )\n\t\treturn ( -1 );\n\t}\n }\n while ( z_err == Z_OK );\n\n /* If the compression state is not Z_STREAM_END, some error occurred */\n\n if ( z_err == Z_STREAM_END ) {\n\n\t/* Need to append the gzip data trailer */\n\n\tif ( buff->zctrl.avail_out < ( 2 * sizeof( unsigned long ) ) ) {\n\t if ( xmlZMemBuffExtend(buff, (2 * sizeof(unsigned long))) == -1 )\n\t\treturn ( -1 );\n\t}\n\n\t/*\n\t** For whatever reason, the CRC and length data are pushed out\n\t** in reverse byte order. So a memcpy can't be used here.\n\t*/\n\n\tappend_reverse_ulong( buff, buff->crc );\n\tappend_reverse_ulong( buff, buff->zctrl.total_in );\n\n\tzlgth = buff->zctrl.next_out - buff->zbuff;\n\t*data_ref = (char *)buff->zbuff;\n }\n\n else {\n\txmlChar msg[500];\n\txmlStrPrintf(msg, 500,\n\t\t (const xmlChar *) \"xmlZMemBuffGetContent: %s - %d\\n\",\n\t\t \"Error flushing zlib buffers. Error code\", z_err );\n\txmlIOErr(XML_IO_WRITE, (const char *) msg);\n }\n\n return ( zlgth );\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-134'], 'message': 'Fix some format string warnings with possible format string vulnerability\n\nFor https://bugzilla.gnome.org/show_bug.cgi?id=761029\n\nDecorate every method in libxml2 with the appropriate\nLIBXML_ATTR_FORMAT(fmt,args) macro and add some cleanups\nfollowing the reports.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int main(int argc ATTRIBUTE_UNUSED, char **argv ATTRIBUTE_UNUSED) {\n printf(\"%s : Module support not compiled in\\n\", argv[0]);\n return(0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-134'], 'message': 'Fix some format string warnings with possible format string vulnerability\n\nFor https://bugzilla.gnome.org/show_bug.cgi?id=761029\n\nDecorate every method in libxml2 with the appropriate\nLIBXML_ATTR_FORMAT(fmt,args) macro and add some cleanups\nfollowing the reports.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: xmlParseNCNameComplex(xmlParserCtxtPtr ctxt) {\n int len = 0, l;\n int c;\n int count = 0;\n const xmlChar *end; /* needed because CUR_CHAR() can move cur on \\r\\n */\n\n#ifdef DEBUG\n nbParseNCNameComplex++;\n#endif\n\n /*\n * Handler for more complex cases\n */\n GROW;\n end = ctxt->input->cur;\n c = CUR_CHAR(l);\n if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */\n\t(!xmlIsNameStartChar(ctxt, c) || (c == ':'))) {\n\treturn(NULL);\n }\n\n while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */\n\t (xmlIsNameChar(ctxt, c) && (c != ':'))) {\n\tif (count++ > XML_PARSER_CHUNK_SIZE) {\n if ((len > XML_MAX_NAME_LENGTH) &&\n ((ctxt->options & XML_PARSE_HUGE) == 0)) {\n xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, \"NCName\");\n return(NULL);\n }\n\t count = 0;\n\t GROW;\n if (ctxt->instate == XML_PARSER_EOF)\n return(NULL);\n\t}\n\tlen += l;\n\tNEXTL(l);\n\tend = ctxt->input->cur;\n\tc = CUR_CHAR(l);\n\tif (c == 0) {\n\t count = 0;\n\t /*\n\t * when shrinking to extend the buffer we really need to preserve\n\t * the part of the name we already parsed. Hence rolling back\n\t * by current lenght.\n\t */\n\t ctxt->input->cur -= l;\n\t GROW;\n\t ctxt->input->cur += l;\n if (ctxt->instate == XML_PARSER_EOF)\n return(NULL);\n\t end = ctxt->input->cur;\n\t c = CUR_CHAR(l);\n\t}\n }\n if ((len > XML_MAX_NAME_LENGTH) &&\n ((ctxt->options & XML_PARSE_HUGE) == 0)) {\n xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, \"NCName\");\n return(NULL);\n }\n return(xmlDictLookup(ctxt->dict, end - len, len));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Bug 759398: Heap use-after-free in xmlDictComputeFastKey \n\n* parser.c:\n(xmlParseNCNameComplex): Store start position instead of a\npointer to the name since the underlying buffer may change,\nresulting in a stale pointer being used.\n* result/errors/759398.xml: Added.\n* result/errors/759398.xml.err: Added.\n* result/errors/759398.xml.str: Added.\n* test/errors/759398.xml: Added test case.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: gdImagePtr gdImageScaleTwoPass(const gdImagePtr src, const unsigned int src_width, const unsigned int src_height, const unsigned int new_width, const unsigned int new_height)\n{\n\tgdImagePtr tmp_im;\n\tgdImagePtr dst;\n\n\t/* Convert to truecolor if it isn't; this code requires it. */\n\tif (!src->trueColor) {\n\t\tgdImagePaletteToTrueColor(src);\n\t}\n\n\ttmp_im = gdImageCreateTrueColor(new_width, src_height);\n\tif (tmp_im == NULL) {\n\t\treturn NULL;\n\t}\n\tgdImageSetInterpolationMethod(tmp_im, src->interpolation_id);\n\t_gdScaleHoriz(src, src_width, src_height, tmp_im, new_width, src_height);\n\n\tdst = gdImageCreateTrueColor(new_width, new_height);\n\tif (dst == NULL) {\n\t\tgdFree(tmp_im);\n\t\treturn NULL;\n\t}\n\tgdImageSetInterpolationMethod(dst, src->interpolation_id);\n\t_gdScaleVert(tmp_im, new_width, src_height, dst, new_width, new_height);\n\tgdFree(tmp_im);\n\n\treturn dst;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'Fix #70064: imagescale(..., IMG_BICUBIC) leaks memory\n\nA temporary image (tmp_im) is created with gdImageTrueColor() and freed with\ngdFree() instead of gdImageDestroy(). Let's fix that.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static char* getPreferredTag(const char* gf_tag)\n{ \n\tchar* result = NULL;\n\tint grOffset = 0;\n\n\tgrOffset = findOffset( LOC_GRANDFATHERED ,gf_tag);\n\tif(grOffset < 0) {\n\t\treturn NULL;\n\t}\n\tif( grOffset < LOC_PREFERRED_GRANDFATHERED_LEN ){\n\t\t/* return preferred tag */\n\t\tresult = estrdup( LOC_PREFERRED_GRANDFATHERED[grOffset] );\n\t} else {\n\t\t/* Return correct grandfathered language tag */\n\t\tresult = estrdup( LOC_GRANDFATHERED[grOffset] );\n\t}\n\treturn result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #72241: get_icu_value_internal out-of-bounds read'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: PHP_NAMED_FUNCTION(zif_locale_set_default)\n{\n\tchar* locale_name = NULL;\n\tint len=0;\t\n\n\tif(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, \"s\",\n\t\t&locale_name ,&len ) == FAILURE)\n\t{\n\t\tintl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,\n\t\t\t \t\"locale_set_default: unable to parse input params\", 0 TSRMLS_CC );\n\n\t\tRETURN_FALSE;\n\t}\n\n\tif(len == 0) {\n\t\tlocale_name = (char *)uloc_getDefault() ;\n\t\tlen = strlen(locale_name);\n\t}\n\n\tzend_alter_ini_entry(LOCALE_INI_NAME, sizeof(LOCALE_INI_NAME), locale_name, len, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);\t\n\n\tRETURN_TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #72241: get_icu_value_internal out-of-bounds read'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: PHP_FUNCTION(locale_get_display_region) \n{\n get_icu_disp_value_src_php( LOC_REGION_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #72241: get_icu_value_internal out-of-bounds read'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int gdTransformAffineGetImage(gdImagePtr *dst,\n\t\t const gdImagePtr src,\n\t\t gdRectPtr src_area,\n\t\t const double affine[6])\n{\n\tint res;\n\tdouble m[6];\n\tgdRect bbox;\n\tgdRect area_full;\n\n\tif (src_area == NULL) {\n\t\tarea_full.x = 0;\n\t\tarea_full.y = 0;\n\t\tarea_full.width = gdImageSX(src);\n\t\tarea_full.height = gdImageSY(src);\n\t\tsrc_area = &area_full;\n\t}\n\n\tgdTransformAffineBoundingBox(src_area, affine, &bbox);\n\n\t*dst = gdImageCreateTrueColor(bbox.width, bbox.height);\n\tif (*dst == NULL) {\n\t\treturn GD_FALSE;\n\t}\n\t(*dst)->saveAlphaFlag = 1;\n\n\tif (!src->trueColor) {\n\t\tgdImagePaletteToTrueColor(src);\n\t}\n\t\n\t/* Translate to dst origin (0,0) */\n\tgdAffineTranslate(m, -bbox.x, -bbox.y);\n\tgdAffineConcat(m, affine, m);\n\n\tgdImageAlphaBlending(*dst, 0);\n\n\tres = gdTransformAffineCopy(*dst,\n\t\t 0,0,\n\t\t src,\n\t\t src_area,\n\t\t m);\n\n\tif (res != GD_TRUE) {\n\t\tgdImageDestroy(*dst);\n\t\tdst = NULL;\n\t\treturn GD_FALSE;\n\t} else {\n\t\treturn GD_TRUE;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed bug #72227: imagescale out-of-bounds read\n\nPorted from https://github.com/libgd/libgd/commit/4f65a3e4eedaffa1efcf9ee1eb08f0b504fbc31a'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: PHPAPI char *php_unescape_html_entities(unsigned char *old, size_t oldlen, size_t *newlen, int all, int flags, char *hint_charset TSRMLS_DC)\n{\n\tsize_t retlen;\n\tchar *ret;\n\tenum entity_charset charset;\n\tconst entity_ht *inverse_map = NULL;\n\tsize_t new_size = TRAVERSE_FOR_ENTITIES_EXPAND_SIZE(oldlen);\n\n\tif (all) {\n\t\tcharset = determine_charset(hint_charset TSRMLS_CC);\n\t} else {\n\t\tcharset = cs_8859_1; /* charset shouldn't matter, use ISO-8859-1 for performance */\n\t}\n\n\t/* don't use LIMIT_ALL! */\n\n\tif (oldlen > new_size) {\n\t\t/* overflow, refuse to do anything */\n\t\tret = estrndup((char*)old, oldlen);\n\t\tretlen = oldlen;\n\t\tgoto empty_source;\n\t}\n\tret = emalloc(new_size);\n\t*ret = '\\0';\n\tretlen = oldlen;\n\tif (retlen == 0) {\n\t\tgoto empty_source;\n\t}\n\t\n\tinverse_map = unescape_inverse_map(all, flags);\n\t\n\t/* replace numeric entities */\n\ttraverse_for_entities(old, oldlen, ret, &retlen, all, flags, inverse_map, charset);\n\nempty_source:\t\n\t*newlen = retlen;\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72135 - don't create strings with lengths outside int range'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: BGD_DECLARE(void) gdImageXbmCtx(gdImagePtr image, char* file_name, int fg, gdIOCtx * out)\n{\n\tint x, y, c, b, sx, sy, p;\n\tchar *name, *f;\n\tsize_t i, l;\n\n\tname = file_name;\n\tif ((f = strrchr(name, '/')) != NULL) name = f+1;\n\tif ((f = strrchr(name, '\\\\')) != NULL) name = f+1;\n\tname = strdup(name);\n\tif ((f = strrchr(name, '.')) != NULL && !strcasecmp(f, \".XBM\")) *f = '\\0';\n\tif ((l = strlen(name)) == 0) {\n\t\tfree(name);\n\t\tname = strdup(\"image\");\n\t} else {\n\t\tfor (i=0; i \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'xbm: avoid stack overflow (read) with large names #211\n\nWe use the name passed in to printf into a local stack buffer which is\nlimited to 4000 bytes. So given a large enough value, lots of stack\ndata is leaked. Rewrite the code to do simple memory copies with most\nof the strings to avoid that issue, and only use stack buffer for small\nnumbers of constant size.\n\nThis closes #211.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: MagickExport MagickBooleanType DrawClipPath(Image *image,\n const DrawInfo *draw_info,const char *name,ExceptionInfo *exception)\n{\n char\n filename[MagickPathExtent];\n\n Image\n *clip_mask;\n\n const char\n *value;\n\n DrawInfo\n *clone_info;\n\n MagickStatusType\n status;\n\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(draw_info != (const DrawInfo *) NULL);\n (void) FormatLocaleString(filename,MagickPathExtent,\"%s\",name);\n value=GetImageArtifact(image,filename);\n if (value == (const char *) NULL)\n return(MagickFalse);\n clip_mask=CloneImage(image,image->columns,image->rows,MagickTrue,exception);\n if (clip_mask == (Image *) NULL)\n return(MagickFalse);\n (void) QueryColorCompliance(\"#0000\",AllCompliance,\n &clip_mask->background_color,exception);\n clip_mask->background_color.alpha=(Quantum) TransparentAlpha;\n (void) SetImageBackgroundColor(clip_mask,exception);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\"\\nbegin clip-path %s\",\n draw_info->clip_mask);\n clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);\n (void) CloneString(&clone_info->primitive,value);\n (void) QueryColorCompliance(\"#ffffff\",AllCompliance,&clone_info->fill,\n exception);\n clone_info->clip_mask=(char *) NULL;\n status=NegateImage(clip_mask,MagickFalse,exception);\n (void) SetImageMask(image,ReadPixelMask,clip_mask,exception);\n clip_mask=DestroyImage(clip_mask);\n status&=DrawImage(image,clone_info,exception);\n clone_info=DestroyDrawInfo(clone_info);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\"end clip-path\");\n return(status != 0 ? MagickTrue : MagickFalse);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-119'], 'message': 'Prevent buffer overflow in magick/draw.c'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static INT AirPDcapScanForKeys(\n PAIRPDCAP_CONTEXT ctx,\n const guint8 *data,\n const guint mac_header_len,\n const guint tot_len,\n AIRPDCAP_SEC_ASSOCIATION_ID id\n)\n{\n const UCHAR *addr;\n guint bodyLength;\n PAIRPDCAP_SEC_ASSOCIATION sta_sa;\n PAIRPDCAP_SEC_ASSOCIATION sa;\n guint offset = 0;\n const guint8 dot1x_header[] = {\n 0xAA, /* DSAP=SNAP */\n 0xAA, /* SSAP=SNAP */\n 0x03, /* Control field=Unnumbered frame */\n 0x00, 0x00, 0x00, /* Org. code=encaps. Ethernet */\n 0x88, 0x8E /* Type: 802.1X authentication */\n };\n const guint8 bt_dot1x_header[] = {\n 0xAA, /* DSAP=SNAP */\n 0xAA, /* SSAP=SNAP */\n 0x03, /* Control field=Unnumbered frame */\n 0x00, 0x19, 0x58, /* Org. code=Bluetooth SIG */\n 0x00, 0x03 /* Type: Bluetooth Security */\n };\n const guint8 tdls_header[] = {\n 0xAA, /* DSAP=SNAP */\n 0xAA, /* SSAP=SNAP */\n 0x03, /* Control field=Unnumbered frame */\n 0x00, 0x00, 0x00, /* Org. code=encaps. Ethernet */\n 0x89, 0x0D, /* Type: 802.11 - Fast Roaming Remote Request */\n 0x02, /* Payload Type: TDLS */\n 0X0C /* Action Category: TDLS */\n };\n\n const EAPOL_RSN_KEY *pEAPKey;\n#ifdef _DEBUG\n#define MSGBUF_LEN 255\n CHAR msgbuf[MSGBUF_LEN];\n#endif\n AIRPDCAP_DEBUG_TRACE_START(\"AirPDcapScanForKeys\");\n\n /* cache offset in the packet data */\n offset = mac_header_len;\n\n /* check if the packet has an LLC header and the packet is 802.1X authentication (IEEE 802.1X-2004, pg. 24) */\n if (memcmp(data+offset, dot1x_header, 8) == 0 || memcmp(data+offset, bt_dot1x_header, 8) == 0) {\n\n AIRPDCAP_DEBUG_PRINT_LINE(\"AirPDcapScanForKeys\", \"Authentication: EAPOL packet\", AIRPDCAP_DEBUG_LEVEL_3);\n\n /* skip LLC header */\n offset+=8;\n\n /* check if the packet is a EAPOL-Key (0x03) (IEEE 802.1X-2004, pg. 25) */\n if (data[offset+1]!=3) {\n AIRPDCAP_DEBUG_PRINT_LINE(\"AirPDcapScanForKeys\", \"Not EAPOL-Key\", AIRPDCAP_DEBUG_LEVEL_3);\n return AIRPDCAP_RET_NO_VALID_HANDSHAKE;\n }\n\n /* get and check the body length (IEEE 802.1X-2004, pg. 25) */\n bodyLength=pntoh16(data+offset+2);\n if ((tot_len-offset-4) < bodyLength) { /* Only check if frame is long enough for eapol header, ignore tailing garbage, see bug 9065 */\n AIRPDCAP_DEBUG_PRINT_LINE(\"AirPDcapScanForKeys\", \"EAPOL body too short\", AIRPDCAP_DEBUG_LEVEL_3);\n return AIRPDCAP_RET_NO_VALID_HANDSHAKE;\n }\n\n /* skip EAPOL MPDU and go to the first byte of the body */\n offset+=4;\n\n pEAPKey = (const EAPOL_RSN_KEY *) (data+offset);\n\n /* check if the key descriptor type is valid (IEEE 802.1X-2004, pg. 27) */\n if (/*pEAPKey->type!=0x1 &&*/ /* RC4 Key Descriptor Type (deprecated) */\n pEAPKey->type != AIRPDCAP_RSN_WPA2_KEY_DESCRIPTOR && /* IEEE 802.11 Key Descriptor Type (WPA2) */\n pEAPKey->type != AIRPDCAP_RSN_WPA_KEY_DESCRIPTOR) /* 254 = RSN_KEY_DESCRIPTOR - WPA, */\n {\n AIRPDCAP_DEBUG_PRINT_LINE(\"AirPDcapScanForKeys\", \"Not valid key descriptor type\", AIRPDCAP_DEBUG_LEVEL_3);\n return AIRPDCAP_RET_NO_VALID_HANDSHAKE;\n }\n\n /* start with descriptor body */\n offset+=1;\n\n /* search for a cached Security Association for current BSSID and AP */\n sa = AirPDcapGetSaPtr(ctx, &id);\n if (sa == NULL){\n AIRPDCAP_DEBUG_PRINT_LINE(\"AirPDcapScanForKeys\", \"No SA for BSSID found\", AIRPDCAP_DEBUG_LEVEL_3);\n return AIRPDCAP_RET_REQ_DATA;\n }\n\n /* It could be a Pairwise Key exchange, check */\n if (AirPDcapRsna4WHandshake(ctx, data, sa, offset, tot_len) == AIRPDCAP_RET_SUCCESS_HANDSHAKE)\n return AIRPDCAP_RET_SUCCESS_HANDSHAKE;\n\n if (mac_header_len + GROUP_KEY_PAYLOAD_LEN_MIN > tot_len) {\n AIRPDCAP_DEBUG_PRINT_LINE(\"AirPDcapScanForKeys\", \"Message too short for Group Key\", AIRPDCAP_DEBUG_LEVEL_3);\n return AIRPDCAP_RET_NO_VALID_HANDSHAKE;\n }\n\n /* Verify the bitfields: Key = 0(groupwise) Mic = 1 Ack = 1 Secure = 1 */\n if (AIRPDCAP_EAP_KEY(data[offset+1])!=0 ||\n AIRPDCAP_EAP_ACK(data[offset+1])!=1 ||\n AIRPDCAP_EAP_MIC(data[offset]) != 1 ||\n AIRPDCAP_EAP_SEC(data[offset]) != 1){\n\n AIRPDCAP_DEBUG_PRINT_LINE(\"AirPDcapScanForKeys\", \"Key bitfields not correct for Group Key\", AIRPDCAP_DEBUG_LEVEL_3);\n return AIRPDCAP_RET_NO_VALID_HANDSHAKE;\n }\n\n /* force STA address to be the broadcast MAC so we create an SA for the groupkey */\n memcpy(id.sta, broadcast_mac, AIRPDCAP_MAC_LEN);\n\n /* get the Security Association structure for the broadcast MAC and AP */\n sa = AirPDcapGetSaPtr(ctx, &id);\n if (sa == NULL){\n return AIRPDCAP_RET_REQ_DATA;\n }\n\n /* Get the SA for the STA, since we need its pairwise key to decrpyt the group key */\n\n /* get STA address */\n if ( (addr=AirPDcapGetStaAddress((const AIRPDCAP_MAC_FRAME_ADDR4 *)(data))) != NULL) {\n memcpy(id.sta, addr, AIRPDCAP_MAC_LEN);\n#ifdef _DEBUG\n g_snprintf(msgbuf, MSGBUF_LEN, \"ST_MAC: %2X.%2X.%2X.%2X.%2X.%2X\\t\", id.sta[0],id.sta[1],id.sta[2],id.sta[3],id.sta[4],id.sta[5]);\n#endif\n AIRPDCAP_DEBUG_PRINT_LINE(\"AirPDcapScanForKeys\", msgbuf, AIRPDCAP_DEBUG_LEVEL_3);\n } else {\n AIRPDCAP_DEBUG_PRINT_LINE(\"AirPDcapScanForKeys\", \"SA not found\", AIRPDCAP_DEBUG_LEVEL_5);\n return AIRPDCAP_RET_REQ_DATA;\n }\n\n sta_sa = AirPDcapGetSaPtr(ctx, &id);\n if (sta_sa == NULL){\n return AIRPDCAP_RET_REQ_DATA;\n }\n\n /* Try to extract the group key and install it in the SA */\n return (AirPDcapDecryptWPABroadcastKey(pEAPKey, sta_sa->wpa.ptk+16, sa, tot_len-offset+1));\n\n } else if (memcmp(data+offset, tdls_header, 10) == 0) {\n const guint8 *initiator, *responder;\n guint8 action;\n guint status, offset_rsne = 0, offset_fte = 0, offset_link = 0, offset_timeout = 0;\n AIRPDCAP_DEBUG_PRINT_LINE(\"AirPDcapScanForKeys\", \"Authentication: TDLS Action Frame\", AIRPDCAP_DEBUG_LEVEL_3);\n\n /* skip LLC header */\n offset+=10;\n\n /* check if the packet is a TDLS response or confirm */\n action = data[offset];\n if (action!=1 && action!=2) {\n AIRPDCAP_DEBUG_PRINT_LINE(\"AirPDcapScanForKeys\", \"Not Response nor confirm\", AIRPDCAP_DEBUG_LEVEL_3);\n return AIRPDCAP_RET_NO_VALID_HANDSHAKE;\n }\n\n /* check status */\n offset++;\n status=pntoh16(data+offset);\n if (status!=0) {\n AIRPDCAP_DEBUG_PRINT_LINE(\"AirPDcapScanForKeys\", \"TDLS setup not successfull\", AIRPDCAP_DEBUG_LEVEL_3);\n return AIRPDCAP_RET_NO_VALID_HANDSHAKE;\n }\n\n /* skip Token + capabilities */\n offset+=5;\n\n /* search for RSN, Fast BSS Transition, Link Identifier and Timeout Interval IEs */\n\n while(offset < (tot_len - 2)) {\n if (data[offset] == 48) {\n offset_rsne = offset;\n } else if (data[offset] == 55) {\n offset_fte = offset;\n } else if (data[offset] == 56) {\n offset_timeout = offset;\n } else if (data[offset] == 101) {\n offset_link = offset;\n }\n\n if (tot_len < offset + data[offset + 1] + 2) {\n return AIRPDCAP_RET_NO_VALID_HANDSHAKE;\n }\n offset += data[offset + 1] + 2;\n }\n\n if (offset_rsne == 0 || offset_fte == 0 ||\n offset_timeout == 0 || offset_link == 0)\n {\n AIRPDCAP_DEBUG_PRINT_LINE(\"AirPDcapScanForKeys\", \"Cannot Find all necessary IEs\", AIRPDCAP_DEBUG_LEVEL_3);\n return AIRPDCAP_RET_NO_VALID_HANDSHAKE;\n }\n\n AIRPDCAP_DEBUG_PRINT_LINE(\"AirPDcapScanForKeys\", \"Found RSNE/Fast BSS/Timeout Interval/Link IEs\", AIRPDCAP_DEBUG_LEVEL_3);\n\n /* Will create a Security Association between 2 STA. Need to get both MAC address */\n initiator = &data[offset_link + 8];\n responder = &data[offset_link + 14];\n\n if (memcmp(initiator, responder, AIRPDCAP_MAC_LEN) < 0) {\n memcpy(id.sta, initiator, AIRPDCAP_MAC_LEN);\n memcpy(id.bssid, responder, AIRPDCAP_MAC_LEN);\n } else {\n memcpy(id.sta, responder, AIRPDCAP_MAC_LEN);\n memcpy(id.bssid, initiator, AIRPDCAP_MAC_LEN);\n }\n\n sa = AirPDcapGetSaPtr(ctx, &id);\n if (sa == NULL){\n return AIRPDCAP_RET_REQ_DATA;\n }\n\n if (sa->validKey) {\n if (memcmp(sa->wpa.nonce, data + offset_fte + 52, AIRPDCAP_WPA_NONCE_LEN) == 0) {\n /* Already have valid key for this SA, no need to redo key derivation */\n return AIRPDCAP_RET_SUCCESS_HANDSHAKE;\n } else {\n /* We are opening a new session with the same two STA, save previous sa */\n AIRPDCAP_SEC_ASSOCIATION *tmp_sa = g_new(AIRPDCAP_SEC_ASSOCIATION, 1);\n memcpy(tmp_sa, sa, sizeof(AIRPDCAP_SEC_ASSOCIATION));\n sa->next=tmp_sa;\n sa->validKey = FALSE;\n }\n }\n\n if (AirPDcapTDLSDeriveKey(sa, data, offset_rsne, offset_fte, offset_timeout, offset_link, action)\n == AIRPDCAP_RET_SUCCESS) {\n AIRPDCAP_DEBUG_TRACE_END(\"AirPDcapScanForKeys\");\n return AIRPDCAP_RET_SUCCESS_HANDSHAKE;\n }\n } else {\n AIRPDCAP_DEBUG_PRINT_LINE(\"AirPDcapScanForKeys\", \"Skipping: not an EAPOL packet\", AIRPDCAP_DEBUG_LEVEL_3);\n }\n\n AIRPDCAP_DEBUG_TRACE_END(\"AirPDcapScanForKeys\");\n return AIRPDCAP_RET_NO_VALID_HANDSHAKE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Make sure EAPOL body is big enough for a EAPOL_RSN_KEY.\n\nA pointer to a EAPOL_RSN_KEY is set on the packet presuming the\nwhole EAPOL_RSN_KEY is there. That's not always the case for\nfuzzed/malicious captures.\n\nBug: 11585\nChange-Id: Ib94b8aceef444c7820e43b969596efdb8dbecccd\nReviewed-on: https://code.wireshark.org/review/15540\nReviewed-by: Michael Mann \nPetri-Dish: Michael Mann \nTested-by: Petri Dish Buildbot \nReviewed-by: Anders Broman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: cosine_seek_read(wtap *wth, gint64 seek_off, struct wtap_pkthdr *phdr,\n\tBuffer *buf, int *err, gchar **err_info)\n{\n\tint\tpkt_len;\n\tchar\tline[COSINE_LINE_LENGTH];\n\n\tif (file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1)\n\t\treturn FALSE;\n\n\tif (file_gets(line, COSINE_LINE_LENGTH, wth->random_fh) == NULL) {\n\t\t*err = file_error(wth->random_fh, err_info);\n\t\tif (*err == 0) {\n\t\t\t*err = WTAP_ERR_SHORT_READ;\n\t\t}\n\t\treturn FALSE;\n\t}\n\n\t/* Parse the header */\n\tpkt_len = parse_cosine_rec_hdr(phdr, line, err, err_info);\n\tif (pkt_len == -1)\n\t\treturn FALSE;\n\n\t/* Convert the ASCII hex dump to binary data */\n\treturn parse_cosine_hex_dump(wth->random_fh, phdr, pkt_len, buf, err,\n\t err_info);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix packet length handling.\n\nTreat the packet length as unsigned - it shouldn't be negative in the\nfile. If it is, that'll probably cause the sscanf to fail, so we'll\nreport the file as bad.\n\nCheck it against WTAP_MAX_PACKET_SIZE to make sure we don't try to\nallocate a huge amount of memory, just as we do in other file readers.\n\nUse the now-validated packet size as the length in\nws_buffer_assure_space(), so we are certain to have enough space, and\ndon't allocate too much space.\n\nMerge the header and packet data parsing routines while we're at it.\n\nBug: 12395\nChange-Id: Ia70f33b71ff28451190fcf144c333fd1362646b2\nReviewed-on: https://code.wireshark.org/review/15172\nReviewed-by: Guy Harris '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: dissect_rpcap_packet (tvbuff_t *tvb, packet_info *pinfo, proto_tree *top_tree,\n proto_tree *parent_tree, gint offset, proto_item *top_item)\n{\n proto_tree *tree;\n proto_item *ti;\n nstime_t ts;\n tvbuff_t *new_tvb;\n guint caplen, len, frame_no;\n gint reported_length_remaining;\n\n ti = proto_tree_add_item (parent_tree, hf_packet, tvb, offset, 20, ENC_NA);\n tree = proto_item_add_subtree (ti, ett_packet);\n\n ts.secs = tvb_get_ntohl (tvb, offset);\n ts.nsecs = tvb_get_ntohl (tvb, offset + 4) * 1000;\n proto_tree_add_time(tree, hf_timestamp, tvb, offset, 8, &ts);\n offset += 8;\n\n caplen = tvb_get_ntohl (tvb, offset);\n ti = proto_tree_add_item (tree, hf_caplen, tvb, offset, 4, ENC_BIG_ENDIAN);\n offset += 4;\n\n len = tvb_get_ntohl (tvb, offset);\n proto_tree_add_item (tree, hf_len, tvb, offset, 4, ENC_BIG_ENDIAN);\n offset += 4;\n\n frame_no = tvb_get_ntohl (tvb, offset);\n proto_tree_add_item (tree, hf_npkt, tvb, offset, 4, ENC_BIG_ENDIAN);\n offset += 4;\n\n proto_item_append_text (ti, \", Frame %u\", frame_no);\n proto_item_append_text (top_item, \" Frame %u\", frame_no);\n\n /*\n * reported_length_remaining should not be -1, as offset is at\n * most right past the end of the available data in the packet.\n */\n reported_length_remaining = tvb_reported_length_remaining (tvb, offset);\n if (caplen > (guint)reported_length_remaining) {\n expert_add_info(pinfo, ti, &ei_caplen_too_big);\n return;\n }\n\n new_tvb = tvb_new_subset (tvb, offset, caplen, len);\n if (decode_content && linktype != WTAP_ENCAP_UNKNOWN) {\n dissector_try_uint(wtap_encap_dissector_table, linktype, new_tvb, pinfo, top_tree);\n\n if (!info_added) {\n /* Only indicate when not added before */\n /* Indicate RPCAP in the protocol column */\n col_prepend_fence_fstr(pinfo->cinfo, COL_PROTOCOL, \"R|\");\n\n /* Indicate RPCAP in the info column */\n col_prepend_fence_fstr (pinfo->cinfo, COL_INFO, \"Remote | \");\n info_added = TRUE;\n register_frame_end_routine(pinfo, rpcap_frame_end);\n }\n } else {\n if (linktype == WTAP_ENCAP_UNKNOWN) {\n proto_item_append_text (ti, \", Unknown link-layer type\");\n }\n call_dissector (data_handle, new_tvb, pinfo, top_tree);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'The WTAP_ENCAP_ETHERNET dissector needs to be passed a struct eth_phdr.\n\nWe now require that. Make it so.\n\nBug: 12440\nChange-Id: Iffee520976b013800699bde3c6092a3e86be0d76\nReviewed-on: https://code.wireshark.org/review/15424\nReviewed-by: Guy Harris '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int phar_extract_file(zend_bool overwrite, phar_entry_info *entry, char *dest, int dest_len, char **error TSRMLS_DC) /* {{{ */\n{\n\tphp_stream_statbuf ssb;\n\tint len;\n\tphp_stream *fp;\n\tchar *fullpath;\n\tconst char *slash;\n\tmode_t mode;\n\tcwd_state new_state;\n\tchar *filename;\n\tsize_t filename_len;\n\n\tif (entry->is_mounted) {\n\t\t/* silently ignore mounted entries */\n\t\treturn SUCCESS;\n\t}\n\n\tif (entry->filename_len >= sizeof(\".phar\")-1 && !memcmp(entry->filename, \".phar\", sizeof(\".phar\")-1)) {\n\t\treturn SUCCESS;\n\t}\n\t/* strip .. from path and restrict it to be under dest directory */\n\tnew_state.cwd = (char*)malloc(2);\n\tnew_state.cwd[0] = DEFAULT_SLASH;\n\tnew_state.cwd[1] = '\\0';\n\tnew_state.cwd_length = 1;\n\tif (virtual_file_ex(&new_state, entry->filename, NULL, CWD_EXPAND TSRMLS_CC) != 0 ||\n\t\t\tnew_state.cwd_length <= 1) {\n\t\tif (EINVAL == errno && entry->filename_len > 50) {\n\t\t\tchar *tmp = estrndup(entry->filename, 50);\n\t\t\tspprintf(error, 4096, \"Cannot extract \\\"%s...\\\" to \\\"%s...\\\", extracted filename is too long for filesystem\", tmp, dest);\n\t\t\tefree(tmp);\n\t\t} else {\n\t\t\tspprintf(error, 4096, \"Cannot extract \\\"%s\\\", internal error\", entry->filename);\n\t\t}\n\t\tfree(new_state.cwd);\n\t\treturn FAILURE;\n\t}\n\tfilename = new_state.cwd + 1;\n\tfilename_len = new_state.cwd_length - 1;\n#ifdef PHP_WIN32\n\t/* unixify the path back, otherwise non zip formats might be broken */\n\t{\n\t\tint cnt = filename_len;\n\n\t\tdo {\n\t\t\tif ('\\\\' == filename[cnt]) {\n\t\t\t\tfilename[cnt] = '/';\n\t\t\t}\n\t\t} while (cnt-- >= 0);\n\t}\n#endif\n\n\tlen = spprintf(&fullpath, 0, \"%s/%s\", dest, filename);\n\n\tif (len >= MAXPATHLEN) {\n\t\tchar *tmp;\n\t\t/* truncate for error message */\n\t\tfullpath[50] = '\\0';\n\t\tif (entry->filename_len > 50) {\n\t\t\ttmp = estrndup(entry->filename, 50);\n\t\t\tspprintf(error, 4096, \"Cannot extract \\\"%s...\\\" to \\\"%s...\\\", extracted filename is too long for filesystem\", tmp, fullpath);\n\t\t\tefree(tmp);\n\t\t} else {\n\t\t\tspprintf(error, 4096, \"Cannot extract \\\"%s\\\" to \\\"%s...\\\", extracted filename is too long for filesystem\", entry->filename, fullpath);\n\t\t}\n\t\tefree(fullpath);\n\t\tfree(new_state.cwd);\n\t\treturn FAILURE;\n\t}\n\n\tif (!len) {\n\t\tspprintf(error, 4096, \"Cannot extract \\\"%s\\\", internal error\", entry->filename);\n\t\tefree(fullpath);\n\t\tfree(new_state.cwd);\n\t\treturn FAILURE;\n\t}\n\n\tif (PHAR_OPENBASEDIR_CHECKPATH(fullpath)) {\n\t\tspprintf(error, 4096, \"Cannot extract \\\"%s\\\" to \\\"%s\\\", openbasedir/safe mode restrictions in effect\", entry->filename, fullpath);\n\t\tefree(fullpath);\n\t\tfree(new_state.cwd);\n\t\treturn FAILURE;\n\t}\n\n\t/* let see if the path already exists */\n\tif (!overwrite && SUCCESS == php_stream_stat_path(fullpath, &ssb)) {\n\t\tspprintf(error, 4096, \"Cannot extract \\\"%s\\\" to \\\"%s\\\", path already exists\", entry->filename, fullpath);\n\t\tefree(fullpath);\n\t\tfree(new_state.cwd);\n\t\treturn FAILURE;\n\t}\n\n\t/* perform dirname */\n\tslash = zend_memrchr(filename, '/', filename_len);\n\n\tif (slash) {\n\t\tfullpath[dest_len + (slash - filename) + 1] = '\\0';\n\t} else {\n\t\tfullpath[dest_len] = '\\0';\n\t}\n\n\tif (FAILURE == php_stream_stat_path(fullpath, &ssb)) {\n\t\tif (entry->is_dir) {\n\t\t\tif (!php_stream_mkdir(fullpath, entry->flags & PHAR_ENT_PERM_MASK, PHP_STREAM_MKDIR_RECURSIVE, NULL)) {\n\t\t\t\tspprintf(error, 4096, \"Cannot extract \\\"%s\\\", could not create directory \\\"%s\\\"\", entry->filename, fullpath);\n\t\t\t\tefree(fullpath);\n\t\t\t\tfree(new_state.cwd);\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\t\t} else {\n\t\t\tif (!php_stream_mkdir(fullpath, 0777, PHP_STREAM_MKDIR_RECURSIVE, NULL)) {\n\t\t\t\tspprintf(error, 4096, \"Cannot extract \\\"%s\\\", could not create directory \\\"%s\\\"\", entry->filename, fullpath);\n\t\t\t\tefree(fullpath);\n\t\t\t\tfree(new_state.cwd);\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (slash) {\n\t\tfullpath[dest_len + (slash - filename) + 1] = '/';\n\t} else {\n\t\tfullpath[dest_len] = '/';\n\t}\n\n\tfilename = NULL;\n\tfree(new_state.cwd);\n\t/* it is a standalone directory, job done */\n\tif (entry->is_dir) {\n\t\tefree(fullpath);\n\t\treturn SUCCESS;\n\t}\n\n#if PHP_API_VERSION < 20100412\n\tfp = php_stream_open_wrapper(fullpath, \"w+b\", REPORT_ERRORS|ENFORCE_SAFE_MODE, NULL);\n#else\n\tfp = php_stream_open_wrapper(fullpath, \"w+b\", REPORT_ERRORS, NULL);\n#endif\n\n\tif (!fp) {\n\t\tspprintf(error, 4096, \"Cannot extract \\\"%s\\\", could not open for writing \\\"%s\\\"\", entry->filename, fullpath);\n\t\tefree(fullpath);\n\t\treturn FAILURE;\n\t}\n\n\tif (!phar_get_efp(entry, 0 TSRMLS_CC)) {\n\t\tif (FAILURE == phar_open_entry_fp(entry, error, 1 TSRMLS_CC)) {\n\t\t\tif (error) {\n\t\t\t\tspprintf(error, 4096, \"Cannot extract \\\"%s\\\" to \\\"%s\\\", unable to open internal file pointer: %s\", entry->filename, fullpath, *error);\n\t\t\t} else {\n\t\t\t\tspprintf(error, 4096, \"Cannot extract \\\"%s\\\" to \\\"%s\\\", unable to open internal file pointer\", entry->filename, fullpath);\n\t\t\t}\n\t\t\tefree(fullpath);\n\t\t\tphp_stream_close(fp);\n\t\t\treturn FAILURE;\n\t\t}\n\t}\n\n\tif (FAILURE == phar_seek_efp(entry, 0, SEEK_SET, 0, 0 TSRMLS_CC)) {\n\t\tspprintf(error, 4096, \"Cannot extract \\\"%s\\\" to \\\"%s\\\", unable to seek internal file pointer\", entry->filename, fullpath);\n\t\tefree(fullpath);\n\t\tphp_stream_close(fp);\n\t\treturn FAILURE;\n\t}\n\n\tif (SUCCESS != php_stream_copy_to_stream_ex(phar_get_efp(entry, 0 TSRMLS_CC), fp, entry->uncompressed_filesize, NULL)) {\n\t\tspprintf(error, 4096, \"Cannot extract \\\"%s\\\" to \\\"%s\\\", copying contents failed\", entry->filename, fullpath);\n\t\tefree(fullpath);\n\t\tphp_stream_close(fp);\n\t\treturn FAILURE;\n\t}\n\n\tphp_stream_close(fp);\n\tmode = (mode_t) entry->flags & PHAR_ENT_PERM_MASK;\n\n\tif (FAILURE == VCWD_CHMOD(fullpath, mode)) {\n\t\tspprintf(error, 4096, \"Cannot extract \\\"%s\\\" to \\\"%s\\\", setting file permissions failed\", entry->filename, fullpath);\n\t\tefree(fullpath);\n\t\treturn FAILURE;\n\t}\n\n\tefree(fullpath);\n\treturn SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'virtual_file_ex uses emalloc in 5.6+'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: xcf_load_layer_props (XcfInfo *info,\n GimpImage *image,\n GimpLayer **layer,\n GList **item_path,\n gboolean *apply_mask,\n gboolean *edit_mask,\n gboolean *show_mask,\n guint32 *text_layer_flags,\n guint32 *group_layer_flags)\n{\n PropType prop_type;\n guint32 prop_size;\n\n while (TRUE)\n {\n if (! xcf_load_prop (info, &prop_type, &prop_size))\n return FALSE;\n\n switch (prop_type)\n {\n case PROP_END:\n return TRUE;\n\n case PROP_ACTIVE_LAYER:\n info->active_layer = *layer;\n break;\n\n case PROP_FLOATING_SELECTION:\n info->floating_sel = *layer;\n info->cp +=\n xcf_read_int32 (info->fp,\n (guint32 *) &info->floating_sel_offset, 1);\n break;\n\n case PROP_OPACITY:\n {\n guint32 opacity;\n\n info->cp += xcf_read_int32 (info->fp, &opacity, 1);\n gimp_layer_set_opacity (*layer, (gdouble) opacity / 255.0, FALSE);\n }\n break;\n\n case PROP_VISIBLE:\n {\n gboolean visible;\n\n info->cp += xcf_read_int32 (info->fp, (guint32 *) &visible, 1);\n gimp_item_set_visible (GIMP_ITEM (*layer), visible, FALSE);\n }\n break;\n\n case PROP_LINKED:\n {\n gboolean linked;\n\n info->cp += xcf_read_int32 (info->fp, (guint32 *) &linked, 1);\n gimp_item_set_linked (GIMP_ITEM (*layer), linked, FALSE);\n }\n break;\n\n case PROP_LOCK_CONTENT:\n {\n gboolean lock_content;\n\n info->cp += xcf_read_int32 (info->fp, (guint32 *) &lock_content, 1);\n\n if (gimp_item_can_lock_content (GIMP_ITEM (*layer)))\n gimp_item_set_lock_content (GIMP_ITEM (*layer),\n lock_content, FALSE);\n }\n break;\n\n case PROP_LOCK_ALPHA:\n {\n gboolean lock_alpha;\n\n info->cp += xcf_read_int32 (info->fp, (guint32 *) &lock_alpha, 1);\n\n if (gimp_layer_can_lock_alpha (*layer))\n gimp_layer_set_lock_alpha (*layer, lock_alpha, FALSE);\n }\n break;\n\n case PROP_APPLY_MASK:\n info->cp += xcf_read_int32 (info->fp, (guint32 *) apply_mask, 1);\n break;\n\n case PROP_EDIT_MASK:\n info->cp += xcf_read_int32 (info->fp, (guint32 *) edit_mask, 1);\n break;\n\n case PROP_SHOW_MASK:\n info->cp += xcf_read_int32 (info->fp, (guint32 *) show_mask, 1);\n break;\n\n case PROP_OFFSETS:\n {\n guint32 offset_x;\n guint32 offset_y;\n\n info->cp += xcf_read_int32 (info->fp, &offset_x, 1);\n info->cp += xcf_read_int32 (info->fp, &offset_y, 1);\n\n gimp_item_set_offset (GIMP_ITEM (*layer), offset_x, offset_y);\n }\n break;\n\n case PROP_MODE:\n {\n guint32 mode;\n\n info->cp += xcf_read_int32 (info->fp, &mode, 1);\n gimp_layer_set_mode (*layer, (GimpLayerModeEffects) mode, FALSE);\n }\n break;\n\n case PROP_TATTOO:\n {\n GimpTattoo tattoo;\n\n info->cp += xcf_read_int32 (info->fp, (guint32 *) &tattoo, 1);\n gimp_item_set_tattoo (GIMP_ITEM (*layer), tattoo);\n }\n break;\n\n case PROP_PARASITES:\n {\n glong base = info->cp;\n\n while (info->cp - base < prop_size)\n {\n GimpParasite *p = xcf_load_parasite (info);\n\n if (! p)\n return FALSE;\n\n gimp_item_parasite_attach (GIMP_ITEM (*layer), p, FALSE);\n gimp_parasite_free (p);\n }\n\n if (info->cp - base != prop_size)\n gimp_message_literal (info->gimp, G_OBJECT (info->progress),\n\t\t\t\t GIMP_MESSAGE_WARNING,\n\t\t\t\t \"Error while loading a layer's parasites\");\n }\n break;\n\n case PROP_TEXT_LAYER_FLAGS:\n info->cp += xcf_read_int32 (info->fp, text_layer_flags, 1);\n break;\n\n case PROP_GROUP_ITEM:\n {\n GimpLayer *group;\n\n group = gimp_group_layer_new (image);\n\n gimp_object_set_name (GIMP_OBJECT (group),\n gimp_object_get_name (*layer));\n\n GIMP_DRAWABLE (group)->private->type =\n gimp_drawable_type (GIMP_DRAWABLE (*layer));\n\n g_object_ref_sink (*layer);\n g_object_unref (*layer);\n *layer = group;\n }\n break;\n\n case PROP_ITEM_PATH:\n {\n glong base = info->cp;\n GList *path = NULL;\n\n while (info->cp - base < prop_size)\n {\n guint32 index;\n\n if (xcf_read_int32 (info->fp, &index, 1) != 4)\n {\n g_list_free (path);\n return FALSE;\n }\n\n info->cp += 4;\n path = g_list_append (path, GUINT_TO_POINTER (index));\n }\n\n *item_path = path;\n }\n break;\n\n case PROP_GROUP_ITEM_FLAGS:\n info->cp += xcf_read_int32 (info->fp, group_layer_flags, 1);\n break;\n\n default:\n#ifdef GIMP_UNSTABLE\n g_printerr (\"unexpected/unknown layer property: %d (skipping)\\n\",\n prop_type);\n#endif\n if (! xcf_skip_unknown_prop (info, prop_size))\n return FALSE;\n break;\n }\n }\n\n return FALSE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Bug 767873 - (CVE-2016-4994) Multiple Use-After-Free when parsing...\n\n...XCF channel and layer properties\n\nThe properties PROP_ACTIVE_LAYER, PROP_FLOATING_SELECTION,\nPROP_ACTIVE_CHANNEL saves the current object pointer the @info\nstructure. Others like PROP_SELECTION (for channel) and\nPROP_GROUP_ITEM (for layer) will delete the current object and create\na new object, leaving the pointers in @info invalid (dangling).\n\nTherefore, if a property from the first type will come before the\nsecond, the result will be an UaF in the last lines of xcf_load_image\n(when it actually using the pointers from @info).\n\nI wasn't able to exploit this bug because that\ng_object_instance->c_class gets cleared by the last g_object_unref and\nGIMP_IS_{LAYER,CHANNEL} detects that and return FALSE.\n\n(cherry picked from commit 6d804bf9ae77bc86a0a97f9b944a129844df9395)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: check_compat_entry_size_and_hooks(struct compat_arpt_entry *e,\n\t\t\t\t struct xt_table_info *newinfo,\n\t\t\t\t unsigned int *size,\n\t\t\t\t const unsigned char *base,\n\t\t\t\t const unsigned char *limit,\n\t\t\t\t const unsigned int *hook_entries,\n\t\t\t\t const unsigned int *underflows,\n\t\t\t\t const char *name)\n{\n\tstruct xt_entry_target *t;\n\tstruct xt_target *target;\n\tunsigned int entry_offset;\n\tint ret, off, h;\n\n\tduprintf(\"check_compat_entry_size_and_hooks %p\\n\", e);\n\tif ((unsigned long)e % __alignof__(struct compat_arpt_entry) != 0 ||\n\t (unsigned char *)e + sizeof(struct compat_arpt_entry) >= limit) {\n\t\tduprintf(\"Bad offset %p, limit = %p\\n\", e, limit);\n\t\treturn -EINVAL;\n\t}\n\n\tif (e->next_offset < sizeof(struct compat_arpt_entry) +\n\t\t\t sizeof(struct compat_xt_entry_target)) {\n\t\tduprintf(\"checking: element %p size %u\\n\",\n\t\t\t e, e->next_offset);\n\t\treturn -EINVAL;\n\t}\n\n\t/* For purposes of check_entry casting the compat entry is fine */\n\tret = check_entry((struct arpt_entry *)e);\n\tif (ret)\n\t\treturn ret;\n\n\toff = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry);\n\tentry_offset = (void *)e - (void *)base;\n\n\tt = compat_arpt_get_target(e);\n\ttarget = xt_request_find_target(NFPROTO_ARP, t->u.user.name,\n\t\t\t\t\tt->u.user.revision);\n\tif (IS_ERR(target)) {\n\t\tduprintf(\"check_compat_entry_size_and_hooks: `%s' not found\\n\",\n\t\t\t t->u.user.name);\n\t\tret = PTR_ERR(target);\n\t\tgoto out;\n\t}\n\tt->u.kernel.target = target;\n\n\toff += xt_compat_target_offset(target);\n\t*size += off;\n\tret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off);\n\tif (ret)\n\t\tgoto release_target;\n\n\t/* Check hooks & underflows */\n\tfor (h = 0; h < NF_ARP_NUMHOOKS; h++) {\n\t\tif ((unsigned char *)e - base == hook_entries[h])\n\t\t\tnewinfo->hook_entry[h] = hook_entries[h];\n\t\tif ((unsigned char *)e - base == underflows[h])\n\t\t\tnewinfo->underflow[h] = underflows[h];\n\t}\n\n\t/* Clear counters and comefrom */\n\tmemset(&e->counters, 0, sizeof(e->counters));\n\te->comefrom = 0;\n\treturn 0;\n\nrelease_target:\n\tmodule_put(t->u.kernel.target->me);\nout:\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'netfilter: x_tables: make sure e->next_offset covers remaining blob size\n\nOtherwise this function may read data beyond the ruleset blob.\n\nSigned-off-by: Florian Westphal \nSigned-off-by: Pablo Neira Ayuso '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void DecodeHeader(guchar *Data, gint Bytes,\n\t\t\t struct ico_progressive_state *State,\n\t\t\t GError **error)\n{\n/* For ICO's we have to be very clever. There are multiple images possible\n in an .ICO. As a simple heuristic, we select the image which occupies the \n largest number of bytes.\n */ \n\tstruct ico_direntry_data *entry;\n\tgint IconCount = 0; /* The number of icon-versions in the file */\n\tguchar *BIH; /* The DIB for the used icon */\n \tguchar *Ptr;\n \tgint I;\n\tguint16 imgtype; /* 1 = icon, 2 = cursor */\n\tGList *l;\n\n \t/* Step 1: The ICO header */\n\n\t/* First word should be 0 according to specs */\n\tif (((Data[1] << 8) + Data[0]) != 0) {\n\t\tg_set_error_literal (error,\n\t\t\t\t GDK_PIXBUF_ERROR,\n\t\t\t\t GDK_PIXBUF_ERROR_CORRUPT_IMAGE,\n\t\t\t\t _(\"Invalid header in icon\"));\n\t\treturn;\n\n\t}\n\n\timgtype = (Data[3] << 8) + Data[2];\n\n\tState->cursor = (imgtype == 2) ? TRUE : FALSE;\n\n\t/* If it is not a cursor make sure it is actually an icon */\n\tif (!State->cursor && imgtype != 1) {\n\t\tg_set_error_literal (error,\n\t\t\t\t GDK_PIXBUF_ERROR,\n\t\t\t\t GDK_PIXBUF_ERROR_CORRUPT_IMAGE,\n\t\t\t\t _(\"Invalid header in icon\"));\n\t\treturn;\n\t}\n\n\n \tIconCount = (Data[5] << 8) + (Data[4]);\n\t\n \tState->HeaderSize = 6 + IconCount*16;\n\n \tif (State->HeaderSize>State->BytesInHeaderBuf) {\n \t\tguchar *tmp=g_try_realloc(State->HeaderBuf,State->HeaderSize);\n\t\tif (!tmp) {\n\t\t\tg_set_error_literal (error,\n GDK_PIXBUF_ERROR,\n GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,\n _(\"Not enough memory to load icon\"));\n\t\t\treturn;\n\t\t}\n\t\tState->HeaderBuf = tmp;\n \t\tState->BytesInHeaderBuf = State->HeaderSize;\n \t}\n \tif (Bytes < State->HeaderSize) {\n\t\tg_set_error_literal (error,\n GDK_PIXBUF_ERROR,\n GDK_PIXBUF_ERROR_CORRUPT_IMAGE,\n _(\"Not enough bytes for header\"));\n \t\treturn;\n\t}\n\n\t/* Now iterate through the ICONDIRENTRY structures, and sort them by\n\t * which one we think is \"best\" (essentially the largest) */\n\tg_list_free_full (State->entries, g_free);\n\tState->entries = 0;\n\tPtr = Data + 6;\n\tfor (I=0;IImageScore = (Ptr[11] << 24) + (Ptr[10] << 16) + (Ptr[9] << 8) + (Ptr[8]);\n\t\tif (entry->ImageScore == 0)\n\t\t\tentry->ImageScore = 256;\n\t\tentry->x_hot = (Ptr[5] << 8) + Ptr[4];\n\t\tentry->y_hot = (Ptr[7] << 8) + Ptr[6];\n\t\tentry->DIBoffset = (Ptr[15]<<24)+(Ptr[14]<<16)+\n\t\t (Ptr[13]<<8) + (Ptr[12]);\n\t\tState->entries = g_list_insert_sorted (State->entries, entry, compare_direntry_scores);\n\t\tPtr += 16;\n\t} \n\n\t/* Now go through and find one we can parse */\n\tentry = NULL;\n\tfor (l = State->entries; l != NULL; l = g_list_next (l)) {\n\t\tentry = l->data;\n\n\t\tif (entry->DIBoffset < 0) {\n\t\t\tg_set_error_literal (error,\n\t\t\t GDK_PIXBUF_ERROR,\n\t\t\t GDK_PIXBUF_ERROR_CORRUPT_IMAGE,\n\t\t\t _(\"Invalid header in icon\"));\n\t\t\treturn;\n\t\t}\n\n\t\t/* We know how many bytes are in the \"header\" part. */\n\t\tState->HeaderSize = entry->DIBoffset + 40; /* 40 = sizeof(InfoHeader) */\n\n\t\tif (State->HeaderSize < 0) {\n\t\t\tg_set_error_literal (error,\n\t\t\t GDK_PIXBUF_ERROR,\n\t\t\t GDK_PIXBUF_ERROR_CORRUPT_IMAGE,\n\t\t\t _(\"Invalid header in icon\"));\n\t\t\treturn;\n\t\t}\n\n\t\tif (State->HeaderSize>State->BytesInHeaderBuf) {\n\t\t\tguchar *tmp=g_try_realloc(State->HeaderBuf,State->HeaderSize);\n\t\t\tif (!tmp) {\n\t\t\t\tg_set_error_literal (error,\n\t\t\t\t GDK_PIXBUF_ERROR,\n\t\t\t\t GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,\n\t\t\t\t _(\"Not enough memory to load icon\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tState->HeaderBuf = tmp;\n\t\t\tState->BytesInHeaderBuf = State->HeaderSize;\n\t\t}\n\t\tif (BytesHeaderSize)\n\t\t\treturn;\n\n\t\tBIH = Data+entry->DIBoffset;\n\n\t\t/* A compressed icon, try the next one */\n\t\tif ((BIH[16] != 0) || (BIH[17] != 0) || (BIH[18] != 0)\n\t\t || (BIH[19] != 0))\n\t\t\tcontinue;\n\n\t\t/* If we made it to here then we have selected a BIH structure\n\t\t * in a format that we can parse */\n\t\tbreak;\n\t}\n\n\t/* No valid icon found, because all are compressed? */\n\tif (l == NULL) {\n\t\tg_set_error_literal (error,\n\t\t GDK_PIXBUF_ERROR,\n\t\t GDK_PIXBUF_ERROR_CORRUPT_IMAGE,\n\t\t _(\"Compressed icons are not supported\"));\n\t\treturn;\n\t}\n\n\t/* This is the one we're going with */\n\tState->DIBoffset = entry->DIBoffset;\n\tState->x_hot = entry->x_hot;\n\tState->y_hot = entry->y_hot;\n\n#ifdef DUMPBIH\n\tDumpBIH(BIH);\n#endif\t\n\t/* Add the palette to the headersize */\n\t\t\n\tState->Header.width =\n\t (int)(BIH[7] << 24) + (BIH[6] << 16) + (BIH[5] << 8) + (BIH[4]);\n\tif (State->Header.width == 0)\n\t\tState->Header.width = 256;\n\n\tState->Header.height =\n\t (int)((BIH[11] << 24) + (BIH[10] << 16) + (BIH[9] << 8) + (BIH[8]))/2;\n\t /* /2 because the BIH height includes the transparency mask */\n\tif (State->Header.height == 0)\n\t\tState->Header.height = 256;\n\tState->Header.depth = (BIH[15] << 8) + (BIH[14]);\n\n\tState->Type = State->Header.depth;\t\n\tif (State->Lines>=State->Header.height)\n\t\tState->Type = 1; /* The transparency mask is 1 bpp */\n\t\n\t/* Determine the palette size. If the header indicates 0, it\n\t is actually the maximum for the bpp. You have to love the\n\t guys who made the spec. */\n\tI = (int)(BIH[35] << 24) + (BIH[34] << 16) + (BIH[33] << 8) + (BIH[32]);\n\tI = I*4;\n\tif ((I==0)&&(State->Type==1))\n\t\tI = 2*4;\n\tif ((I==0)&&(State->Type==4))\n\t\tI = 16*4;\n\tif ((I==0)&&(State->Type==8))\n\t\tI = 256*4;\n\t\n\tState->HeaderSize+=I;\n\t\n\tif (State->HeaderSize < 0) {\n\t\tg_set_error_literal (error,\n GDK_PIXBUF_ERROR,\n GDK_PIXBUF_ERROR_CORRUPT_IMAGE,\n _(\"Invalid header in icon\"));\n\t\treturn;\n\t}\n\n \tif (State->HeaderSize>State->BytesInHeaderBuf) {\n\t guchar *tmp=g_try_realloc(State->HeaderBuf,State->HeaderSize);\n\t\tif (!tmp) {\n\t\t\tg_set_error_literal (error,\n GDK_PIXBUF_ERROR,\n GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,\n _(\"Not enough memory to load icon\"));\n\t\t\treturn;\n\t\t}\n\t\tState->HeaderBuf = tmp;\n \t\tState->BytesInHeaderBuf = State->HeaderSize;\n \t}\n \tif (Bytes < State->HeaderSize) {\n\t\tg_set_error_literal (error,\n GDK_PIXBUF_ERROR,\n GDK_PIXBUF_ERROR_CORRUPT_IMAGE,\n _(\"Not enough bytes for header\"));\n \t\treturn;\n\t}\n\n\t/* Negative heights mean top-down pixel-order */\n\tif (State->Header.height < 0) {\n\t\tState->Header.height = -State->Header.height;\n\t\tState->Header.Negative = 1;\n\t}\n\tif (State->Header.width < 0) {\n\t\tState->Header.width = -State->Header.width;\n\t}\n\tg_assert (State->Header.width > 0);\n\tg_assert (State->Header.height > 0);\n\n if (State->Type == 32)\n State->LineWidth = State->Header.width * 4;\n else if (State->Type == 24)\n\t\tState->LineWidth = State->Header.width * 3;\n else if (State->Type == 16)\n State->LineWidth = State->Header.width * 2;\n else if (State->Type == 8)\n\t\tState->LineWidth = State->Header.width * 1;\n else if (State->Type == 4)\n\t\tState->LineWidth = (State->Header.width+1)/2;\n else if (State->Type == 1) {\n\t\tState->LineWidth = State->Header.width / 8;\n\t\tif ((State->Header.width & 7) != 0)\n\t\t\tState->LineWidth++;\n } else {\n g_set_error_literal (error,\n GDK_PIXBUF_ERROR,\n GDK_PIXBUF_ERROR_CORRUPT_IMAGE,\n _(\"Unsupported icon type\"));\n return;\n\t}\n\n\t/* Pad to a 32 bit boundary */\n\tif (((State->LineWidth % 4) > 0))\n\t\tState->LineWidth = (State->LineWidth / 4) * 4 + 4;\n\n\n\tif (State->LineBuf == NULL) {\n\t\tState->LineBuf = g_try_malloc(State->LineWidth);\n\t\tif (!State->LineBuf) {\n\t\t\tg_set_error_literal (error,\n GDK_PIXBUF_ERROR,\n GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,\n _(\"Not enough memory to load icon\"));\n\t\t\treturn;\n\t\t}\n\t}\n\n\tg_assert(State->LineBuf != NULL);\n\n\n\tif (State->pixbuf == NULL) {\n#if 1\n\t\tif (State->size_func) {\n\t\t\tgint width = State->Header.width;\n\t\t\tgint height = State->Header.height;\n\n\t\t\t(*State->size_func) (&width, &height, State->user_data);\n\t\t\tif (width == 0 || height == 0) {\n\t\t\t\tState->LineWidth = 0;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n#endif\n\n\t\tState->pixbuf =\n\t\t gdk_pixbuf_new(GDK_COLORSPACE_RGB, TRUE, 8,\n\t\t\t\t State->Header.width,\n\t\t\t\t State->Header.height);\n\t\tif (!State->pixbuf) {\n\t\t\tg_set_error_literal (error,\n GDK_PIXBUF_ERROR,\n GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,\n _(\"Not enough memory to load icon\"));\n\t\t\treturn;\n\t\t}\n\t\tif (State->cursor) {\n\t\t\tgchar hot[10];\n\t\t\tg_snprintf (hot, 10, \"%d\", State->x_hot);\n\t\t\tgdk_pixbuf_set_option (State->pixbuf, \"x_hot\", hot);\n\t\t\tg_snprintf (hot, 10, \"%d\", State->y_hot);\n\t\t\tgdk_pixbuf_set_option (State->pixbuf, \"y_hot\", hot);\n\t\t}\n\n\t\tif (State->prepared_func != NULL)\n\t\t\t/* Notify the client that we are ready to go */\n\t\t\t(*State->prepared_func) (State->pixbuf,\n NULL,\n\t\t\t\t\t\t State->user_data);\n\n\t}\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'ico: Be more careful when parsing headers\n\nThere is some redundancy between the ico directory and the\nbitmap image header. If the two disagree on the icon dimensions,\njust toss the image, instead of risking crashes or OOM later. Also\nadd some more debug spew that helped in tracking this down, and\nmake error messages more unique.\n\nThe commit also includes a test image that has an example of\nthis discrepancy and triggers the early exit.\n\nhttps://bugzilla.gnome.org/show_bug.cgi?id=769170'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline signed short ReadProfileShort(const EndianType endian,\n unsigned char *buffer)\n{\n union\n {\n unsigned int\n unsigned_value;\n\n signed int\n signed_value;\n } quantum;\n\n unsigned short\n value;\n\n if (endian == LSBEndian)\n {\n value=(unsigned short) ((buffer[1] << 8) | buffer[0]);\n quantum.unsigned_value=(value & 0xffff);\n return(quantum.signed_value);\n }\n value=(unsigned short) ((((unsigned char *) buffer)[0] << 8) |\n ((unsigned char *) buffer)[1]);\n quantum.unsigned_value=(value & 0xffff);\n return(quantum.signed_value);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190', 'CWE-125'], 'message': 'Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static __be32 nfsd3_proc_setacl(struct svc_rqst * rqstp,\n\t\tstruct nfsd3_setaclargs *argp,\n\t\tstruct nfsd3_attrstat *resp)\n{\n\tstruct inode *inode;\n\tsvc_fh *fh;\n\t__be32 nfserr = 0;\n\tint error;\n\n\tfh = fh_copy(&resp->fh, &argp->fh);\n\tnfserr = fh_verify(rqstp, &resp->fh, 0, NFSD_MAY_SATTR);\n\tif (nfserr)\n\t\tgoto out;\n\n\tinode = d_inode(fh->fh_dentry);\n\tif (!IS_POSIXACL(inode) || !inode->i_op->set_acl) {\n\t\terror = -EOPNOTSUPP;\n\t\tgoto out_errno;\n\t}\n\n\terror = fh_want_write(fh);\n\tif (error)\n\t\tgoto out_errno;\n\n\terror = inode->i_op->set_acl(inode, argp->acl_access, ACL_TYPE_ACCESS);\n\tif (error)\n\t\tgoto out_drop_write;\n\terror = inode->i_op->set_acl(inode, argp->acl_default,\n\t\t\t\t ACL_TYPE_DEFAULT);\n\nout_drop_write:\n\tfh_drop_write(fh);\nout_errno:\n\tnfserr = nfserrno(error);\nout:\n\t/* argp->acl_{access,default} may have been allocated in\n\t nfs3svc_decode_setaclargs. */\n\tposix_acl_release(argp->acl_access);\n\tposix_acl_release(argp->acl_default);\n\tRETURN_STATUS(nfserr);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284'], 'message': 'nfsd: check permissions when setting ACLs\n\nUse set_posix_acl, which includes proper permission checks, instead of\ncalling ->set_acl directly. Without this anyone may be able to grant\nthemselves permissions to a file by setting the ACL.\n\nLock the inode to make the new checks atomic with respect to set_acl.\n(Also, nfsd was the only caller of set_acl not locking the inode, so I\nsuspect this may fix other races.)\n\nThis also simplifies the code, and ensures our ACLs are checked by\nposix_acl_valid.\n\nThe permission checks and the inode locking were lost with commit\n4ac7249e, which changed nfsd to use the set_acl inode operation directly\ninstead of going through xattr handlers.\n\nReported-by: David Sinquin \n[agreunba@redhat.com: use set_posix_acl]\nFixes: 4ac7249e\nCc: Christoph Hellwig \nCc: Al Viro \nCc: stable@vger.kernel.org\nSigned-off-by: J. Bruce Fields '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void gdImageCopyMerge (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int w, int h, int pct)\n{\n\tint c, dc;\n\tint x, y;\n\tint tox, toy;\n\tint ncR, ncG, ncB;\n\ttoy = dstY;\n\t\n\tfor (y = srcY; y < (srcY + h); y++) {\n\t\ttox = dstX;\n\t\tfor (x = srcX; x < (srcX + w); x++) {\n\t\t\tint nc;\n\t\t\tc = gdImageGetPixel(src, x, y);\n\t\t\t/* Added 7/24/95: support transparent copies */\n\t\t\tif (gdImageGetTransparent(src) == c) {\n\t\t\t\ttox++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t/* If it's the same image, mapping is trivial */\n\t\t\tif (dst == src) {\n\t\t\t\tnc = c;\n\t\t\t} else {\n\t\t\t\tdc = gdImageGetPixel(dst, tox, toy);\n\n \t\t\t\tncR = (int)(gdImageRed (src, c) * (pct / 100.0) + gdImageRed (dst, dc) * ((100 - pct) / 100.0));\n \t\t\t\tncG = (int)(gdImageGreen (src, c) * (pct / 100.0) + gdImageGreen (dst, dc) * ((100 - pct) / 100.0));\n \t\t\t\tncB = (int)(gdImageBlue (src, c) * (pct / 100.0) + gdImageBlue (dst, dc) * ((100 - pct) / 100.0));\n\n\t\t\t\t/* Find a reasonable color */\n\t\t\t\tnc = gdImageColorResolve (dst, ncR, ncG, ncB);\n\t\t\t}\n\t\t\tgdImageSetPixel (dst, tox, toy, nc);\n\t\t\ttox++;\n\t\t}\n\t\ttoy++;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'iFixed bug #72446 - Integer Overflow in gdImagePaletteToTrueColor() resulting in heap overflow'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: \nstatic void php_mcrypt_module_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC) /* {{{ */\n{\n\tphp_mcrypt *pm = (php_mcrypt *) rsrc->ptr;\n\tif (pm) {\t\n\t\tmcrypt_generic_deinit(pm->td);\n\t\tmcrypt_module_close(pm->td);\n\t\tefree(pm);\n\t\tpm = NULL;\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72455: Heap Overflow due to integer overflows'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: Does a self test of the module \"module\" */\nPHP_FUNCTION(mcrypt_module_self_test)\n{\n\tMCRYPT_GET_MODE_DIR_ARGS(algorithms_dir);\n\t\n\tif (mcrypt_module_self_test(module, dir) == 0) {\n\t\tRETURN_TRUE;\n\t} else {\n\t\tRETURN_FALSE;\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72455: Heap Overflow due to integer overflows'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void _php_mb_regex_set_options(OnigOptionType options, OnigSyntaxType *syntax, OnigOptionType *prev_options, OnigSyntaxType **prev_syntax TSRMLS_DC) \n{\n\tif (prev_options != NULL) {\n\t\t*prev_options = MBREX(regex_default_options);\n\t}\n\tif (prev_syntax != NULL) {\n\t\t*prev_syntax = MBREX(regex_default_syntax);\n\t}\n\tMBREX(regex_default_options) = options;\n\tMBREX(regex_default_syntax) = syntax;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'Fix bug #72402: _php_mb_regex_ereg_replace_exec - double free'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: SPL_METHOD(SplFileObject, ftell)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\t\n\tlong ret = php_stream_tell(intern->u.file.stream);\n\n\tif (ret == -1) {\n\t\tRETURN_FALSE;\n\t} else {\n\t\tRETURN_LONG(ret);\n\t}\n} /* }}} */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72262 - do not overflow int'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: SPL_METHOD(SplFileObject, __construct)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\tzend_bool use_include_path = 0;\n\tchar *p1, *p2;\n\tchar *tmp_path;\n\tint tmp_path_len;\n\tzend_error_handling error_handling;\n\n\tzend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC);\n\n\tintern->u.file.open_mode = NULL;\n\tintern->u.file.open_mode_len = 0;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"p|sbr!\", \n\t\t\t&intern->file_name, &intern->file_name_len,\n\t\t\t&intern->u.file.open_mode, &intern->u.file.open_mode_len, \n\t\t\t&use_include_path, &intern->u.file.zcontext) == FAILURE) {\t\t\n\t\tintern->u.file.open_mode = NULL;\n\t\tintern->file_name = NULL;\n\t\tzend_restore_error_handling(&error_handling TSRMLS_CC);\n\t\treturn;\n\t}\n\t\n\tif (intern->u.file.open_mode == NULL) {\n\t\tintern->u.file.open_mode = \"r\";\n\t\tintern->u.file.open_mode_len = 1;\n\t}\n\n\tif (spl_filesystem_file_open(intern, use_include_path, 0 TSRMLS_CC) == SUCCESS) {\n\t\ttmp_path_len = strlen(intern->u.file.stream->orig_path);\n\n\t\tif (tmp_path_len > 1 && IS_SLASH_AT(intern->u.file.stream->orig_path, tmp_path_len-1)) {\n\t\t\ttmp_path_len--;\n\t\t}\n\n\t\ttmp_path = estrndup(intern->u.file.stream->orig_path, tmp_path_len);\n\n\t\tp1 = strrchr(tmp_path, '/');\n#if defined(PHP_WIN32) || defined(NETWARE)\n\t\tp2 = strrchr(tmp_path, '\\\\');\n#else\n\t\tp2 = 0;\n#endif\n\t\tif (p1 || p2) {\n\t\t\tintern->_path_len = (p1 > p2 ? p1 : p2) - tmp_path;\n\t\t} else {\n\t\t\tintern->_path_len = 0;\n\t\t}\n\n\t\tefree(tmp_path);\n\n\t\tintern->_path = estrndup(intern->u.file.stream->orig_path, intern->_path_len);\n\t}\n\n\tzend_restore_error_handling(&error_handling TSRMLS_CC);\n\n} /* }}} */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72262 - do not overflow int'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void spl_filesystem_dir_it_rewind(zend_object_iterator *iter TSRMLS_DC)\n{\n\tspl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter);\n\t\n\tobject->u.dir.index = 0;\n\tif (object->u.dir.dirp) {\n\t\tphp_stream_rewinddir(object->u.dir.dirp);\n\t}\n\tspl_filesystem_dir_read(object TSRMLS_CC);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72262 - do not overflow int'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static spl_filesystem_object * spl_filesystem_object_create_type(int ht, spl_filesystem_object *source, int type, zend_class_entry *ce, zval *return_value TSRMLS_DC) /* {{{ */\n{\n\tspl_filesystem_object *intern;\n\tzend_bool use_include_path = 0;\n\tzval *arg1, *arg2;\n\tzend_error_handling error_handling;\n\n\tzend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC);\n\n\tswitch (source->type) {\n\tcase SPL_FS_INFO:\n\tcase SPL_FS_FILE:\n\t\tbreak;\n\tcase SPL_FS_DIR:\n\t\tif (!source->u.dir.entry.d_name[0]) {\n\t\t\tzend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, \"Could not open file\");\n\t\t\tzend_restore_error_handling(&error_handling TSRMLS_CC);\n\t\t\treturn NULL;\n\t\t}\n\t}\n\n\tswitch (type) {\n\tcase SPL_FS_INFO:\n\t\tce = ce ? ce : source->info_class;\n\n\t\tzend_update_class_constants(ce TSRMLS_CC);\n\n\t\treturn_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC);\n\t\tZ_TYPE_P(return_value) = IS_OBJECT;\n\n\t\tspl_filesystem_object_get_file_name(source TSRMLS_CC);\n\t\tif (ce->constructor->common.scope != spl_ce_SplFileInfo) {\n\t\t\tMAKE_STD_ZVAL(arg1);\n\t\t\tZVAL_STRINGL(arg1, source->file_name, source->file_name_len, 1);\n\t\t\tzend_call_method_with_1_params(&return_value, ce, &ce->constructor, \"__construct\", NULL, arg1);\n\t\t\tzval_ptr_dtor(&arg1);\n\t\t} else {\n\t\t\tintern->file_name = estrndup(source->file_name, source->file_name_len);\n\t\t\tintern->file_name_len = source->file_name_len;\n\t\t\tintern->_path = spl_filesystem_object_get_path(source, &intern->_path_len TSRMLS_CC);\n\t\t\tintern->_path = estrndup(intern->_path, intern->_path_len);\n\t\t}\n\t\tbreak;\n\tcase SPL_FS_FILE:\n\t\tce = ce ? ce : source->file_class;\n\n\t\tzend_update_class_constants(ce TSRMLS_CC);\n\n\t\treturn_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC);\n\t\tZ_TYPE_P(return_value) = IS_OBJECT;\n\t\n\t\tspl_filesystem_object_get_file_name(source TSRMLS_CC);\n\n\t\tif (ce->constructor->common.scope != spl_ce_SplFileObject) {\n\t\t\tMAKE_STD_ZVAL(arg1);\n\t\t\tMAKE_STD_ZVAL(arg2);\n\t\t\tZVAL_STRINGL(arg1, source->file_name, source->file_name_len, 1);\n\t\t\tZVAL_STRINGL(arg2, \"r\", 1, 1);\n\t\t\tzend_call_method_with_2_params(&return_value, ce, &ce->constructor, \"__construct\", NULL, arg1, arg2);\n\t\t\tzval_ptr_dtor(&arg1);\n\t\t\tzval_ptr_dtor(&arg2);\n\t\t} else {\n\t\t\tintern->file_name = source->file_name;\n\t\t\tintern->file_name_len = source->file_name_len;\n\t\t\tintern->_path = spl_filesystem_object_get_path(source, &intern->_path_len TSRMLS_CC);\n\t\t\tintern->_path = estrndup(intern->_path, intern->_path_len);\n\t\t\n\t\t\tintern->u.file.open_mode = \"r\";\n\t\t\tintern->u.file.open_mode_len = 1;\n\t\t\n\t\t\tif (ht && zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"|sbr\", \n\t\t\t\t\t&intern->u.file.open_mode, &intern->u.file.open_mode_len, \n\t\t\t\t\t&use_include_path, &intern->u.file.zcontext) == FAILURE) {\n\t\t\t\tzend_restore_error_handling(&error_handling TSRMLS_CC);\n\t\t\t\tintern->u.file.open_mode = NULL;\n\t\t\t\tintern->file_name = NULL;\n\t\t\t\tzval_dtor(return_value);\n\t\t\t\tZ_TYPE_P(return_value) = IS_NULL;\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\n\t\t\tif (spl_filesystem_file_open(intern, use_include_path, 0 TSRMLS_CC) == FAILURE) {\n\t\t\t\tzend_restore_error_handling(&error_handling TSRMLS_CC);\n\t\t\t\tzval_dtor(return_value);\n\t\t\t\tZ_TYPE_P(return_value) = IS_NULL;\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase SPL_FS_DIR:\t\n\t\tzend_restore_error_handling(&error_handling TSRMLS_CC);\n\t\tzend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, \"Operation not supported\");\n\t\treturn NULL;\n\t}\n\tzend_restore_error_handling(&error_handling TSRMLS_CC);\n\treturn NULL;\n} /* }}} */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72262 - do not overflow int'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: SPL_METHOD(SplFileObject, getCsvControl)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\tchar delimiter[2], enclosure[2];\n\n\tarray_init(return_value);\n\t\n\tdelimiter[0] = intern->u.file.delimiter;\n\tdelimiter[1] = '\\0';\n\tenclosure[0] = intern->u.file.enclosure;\n\tenclosure[1] = '\\0';\n\n\tadd_next_index_string(return_value, delimiter, 1);\n\tadd_next_index_string(return_value, enclosure, 1);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72262 - do not overflow int'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: SPL_METHOD(SplFileInfo, getPath)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\tchar *path;\n\tint path_len;\n\t\n\tif (zend_parse_parameters_none() == FAILURE) {\n\t\treturn;\n\t}\n\n \tpath = spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC);\n\tRETURN_STRINGL(path, path_len, 1);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72262 - do not overflow int'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: SPL_METHOD(RecursiveDirectoryIterator, getSubPathname)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\tchar *sub_name;\n\tint len;\n\tchar slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH;\n\t\n\tif (zend_parse_parameters_none() == FAILURE) {\n\t\treturn;\n\t}\n\n\tif (intern->u.dir.sub_path) {\n\t\tlen = spprintf(&sub_name, 0, \"%s%c%s\", intern->u.dir.sub_path, slash, intern->u.dir.entry.d_name);\n\t\tRETURN_STRINGL(sub_name, len, 0);\n\t} else {\n\t\tRETURN_STRING(intern->u.dir.entry.d_name, 1);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72262 - do not overflow int'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int sclp_ctl_ioctl_sccb(void __user *user_area)\n{\n\tstruct sclp_ctl_sccb ctl_sccb;\n\tstruct sccb_header *sccb;\n\tint rc;\n\n\tif (copy_from_user(&ctl_sccb, user_area, sizeof(ctl_sccb)))\n\t\treturn -EFAULT;\n\tif (!sclp_ctl_cmdw_supported(ctl_sccb.cmdw))\n\t\treturn -EOPNOTSUPP;\n\tsccb = (void *) get_zeroed_page(GFP_KERNEL | GFP_DMA);\n\tif (!sccb)\n\t\treturn -ENOMEM;\n\tif (copy_from_user(sccb, u64_to_uptr(ctl_sccb.sccb), sizeof(*sccb))) {\n\t\trc = -EFAULT;\n\t\tgoto out_free;\n\t}\n\tif (sccb->length > PAGE_SIZE || sccb->length < 8)\n\t\treturn -EINVAL;\n\tif (copy_from_user(sccb, u64_to_uptr(ctl_sccb.sccb), sccb->length)) {\n\t\trc = -EFAULT;\n\t\tgoto out_free;\n\t}\n\trc = sclp_sync_request(ctl_sccb.cmdw, sccb);\n\tif (rc)\n\t\tgoto out_free;\n\tif (copy_to_user(u64_to_uptr(ctl_sccb.sccb), sccb, sccb->length))\n\t\trc = -EFAULT;\nout_free:\n\tfree_page((unsigned long) sccb);\n\treturn rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 's390/sclp_ctl: fix potential information leak with /dev/sclp\n\nThe sclp_ctl_ioctl_sccb function uses two copy_from_user calls to\nretrieve the sclp request from user space. The first copy_from_user\nfetches the length of the request which is stored in the first two\nbytes of the request. The second copy_from_user gets the complete\nsclp request, but this copies the length field a second time.\nA malicious user may have changed the length in the meantime.\n\nReported-by: Pengfei Wang \nReviewed-by: Michael Holzheu \nSigned-off-by: Martin Schwidefsky '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: SAPI_API int sapi_add_header_ex(char *header_line, uint header_line_len, zend_bool duplicate, zend_bool replace TSRMLS_DC)\n{\n\tsapi_header_line ctr = {0};\n\tint r;\n\t\n\tctr.line = header_line;\n\tctr.line_len = header_line_len;\n\n\tr = sapi_header_op(replace ? SAPI_HEADER_REPLACE : SAPI_HEADER_ADD,\n\t\t\t&ctr TSRMLS_CC);\n\n\tif (!duplicate)\n\t\tefree(header_line);\n\n\treturn r;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-601'], 'message': 'Fix for HTTP_PROXY issue.\n\nThe following changes are made:\n- _SERVER/_ENV only has HTTP_PROXY if the local environment has it,\n and only one from the environment.\n- getenv('HTTP_PROXY') only returns one from the local environment\n- getenv has optional second parameter, telling it to only consider\n local environment'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: PHPAPI void php_register_variable_safe(char *var, char *strval, int str_len, zval *track_vars_array TSRMLS_DC)\n{\n\tzval new_entry;\n\tassert(strval != NULL);\n\t\n\t/* Prepare value */\n\tZ_STRLEN(new_entry) = str_len;\n\tZ_STRVAL(new_entry) = estrndup(strval, Z_STRLEN(new_entry));\n\tZ_TYPE(new_entry) = IS_STRING;\n\n\tphp_register_variable_ex(var, &new_entry, track_vars_array TSRMLS_CC);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-601'], 'message': 'Fix for HTTP_PROXY issue.\n\nThe following changes are made:\n- _SERVER/_ENV only has HTTP_PROXY if the local environment has it,\n and only one from the environment.\n- getenv('HTTP_PROXY') only returns one from the local environment\n- getenv has optional second parameter, telling it to only consider\n local environment'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int srpt_rx_mgmt_fn_tag(struct srpt_send_ioctx *ioctx, u64 tag)\n{\n\tstruct srpt_device *sdev;\n\tstruct srpt_rdma_ch *ch;\n\tstruct srpt_send_ioctx *target;\n\tint ret, i;\n\n\tret = -EINVAL;\n\tch = ioctx->ch;\n\tBUG_ON(!ch);\n\tBUG_ON(!ch->sport);\n\tsdev = ch->sport->sdev;\n\tBUG_ON(!sdev);\n\tspin_lock_irq(&sdev->spinlock);\n\tfor (i = 0; i < ch->rq_size; ++i) {\n\t\ttarget = ch->ioctx_ring[i];\n\t\tif (target->cmd.se_lun == ioctx->cmd.se_lun &&\n\t\t target->cmd.tag == tag &&\n\t\t srpt_get_cmd_state(target) != SRPT_STATE_DONE) {\n\t\t\tret = 0;\n\t\t\t/* now let the target core abort &target->cmd; */\n\t\t\tbreak;\n\t\t}\n\t}\n\tspin_unlock_irq(&sdev->spinlock);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-476'], 'message': 'IB/srpt: Simplify srpt_handle_tsk_mgmt()\n\nLet the target core check task existence instead of the SRP target\ndriver. Additionally, let the target core check the validity of the\ntask management request instead of the ib_srpt driver.\n\nThis patch fixes the following kernel crash:\n\nBUG: unable to handle kernel NULL pointer dereference at 0000000000000001\nIP: [] srpt_handle_new_iu+0x6d7/0x790 [ib_srpt]\nOops: 0002 [#1] SMP\nCall Trace:\n [] srpt_process_completion+0xde/0x570 [ib_srpt]\n [] srpt_compl_thread+0x13f/0x160 [ib_srpt]\n [] kthread+0xcf/0xe0\n [] ret_from_fork+0x7c/0xb0\n\nSigned-off-by: Bart Van Assche \nFixes: 3e4f574857ee (\"ib_srpt: Convert TMR path to target_submit_tmr\")\nTested-by: Alex Estrin \nReviewed-by: Christoph Hellwig \nCc: Nicholas Bellinger \nCc: Sagi Grimberg \nCc: stable \nSigned-off-by: Doug Ledford '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: PHP_BZ2_API php_stream *_php_stream_bz2open(php_stream_wrapper *wrapper,\n\t\t\t\t\t\t\t\t\t\t\tchar *path,\n\t\t\t\t\t\t\t\t\t\t\tchar *mode,\n\t\t\t\t\t\t\t\t\t\t\tint options,\n\t\t\t\t\t\t\t\t\t\t\tchar **opened_path,\n\t\t\t\t\t\t\t\t\t\t\tphp_stream_context *context STREAMS_DC TSRMLS_DC)\n{\n\tphp_stream *retstream = NULL, *stream = NULL;\n\tchar *path_copy = NULL;\n\tBZFILE *bz_file = NULL;\n\n\tif (strncasecmp(\"compress.bzip2://\", path, 17) == 0) {\n\t\tpath += 17;\n\t}\n\tif (mode[0] == '\\0' || (mode[0] != 'w' && mode[0] != 'r' && mode[1] != '\\0')) {\n\t\treturn NULL;\n\t}\n\n#ifdef VIRTUAL_DIR\n\tvirtual_filepath_ex(path, &path_copy, NULL TSRMLS_CC);\n#else\n\tpath_copy = path;\n#endif \n\n\tif (php_check_open_basedir(path_copy TSRMLS_CC)) {\n#ifdef VIRTUAL_DIR\n\t\tfree(path_copy);\n#endif\n\t\treturn NULL;\n\t}\n\t\n\t/* try and open it directly first */\n\tbz_file = BZ2_bzopen(path_copy, mode);\n\n\tif (opened_path && bz_file) {\n\t\t*opened_path = estrdup(path_copy);\n\t}\n#ifdef VIRTUAL_DIR\n\tfree(path_copy);\n#endif\n\tpath_copy = NULL;\n\t\n\tif (bz_file == NULL) {\n\t\t/* that didn't work, so try and get something from the network/wrapper */\n\t\tstream = php_stream_open_wrapper(path, mode, options | STREAM_WILL_CAST, opened_path);\n\t\n\t\tif (stream) {\n\t\t\tint fd;\n\t\t\tif (SUCCESS == php_stream_cast(stream, PHP_STREAM_AS_FD, (void **) &fd, REPORT_ERRORS)) {\n\t\t\t\tbz_file = BZ2_bzdopen(fd, mode);\n\t\t\t}\n\t\t}\n\n\t\t/* remove the file created by php_stream_open_wrapper(), it is not needed since BZ2 functions\n\t\t * failed.\n\t\t */\n\t\tif (opened_path && !bz_file && mode[0] == 'w') {\n\t\t\tVCWD_UNLINK(*opened_path);\n\t\t}\n\t}\n\t\n\tif (bz_file) {\n\t\tretstream = _php_stream_bz2open_from_BZFILE(bz_file, mode, stream STREAMS_REL_CC TSRMLS_CC);\n\t\tif (retstream) {\n\t\t\treturn retstream;\n\t\t}\n\n\t\tBZ2_bzclose(bz_file);\n\t}\n\n\tif (stream) {\n\t\tphp_stream_close(stream);\n\t}\n\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Partial fix for bug #72613 - do not treat negative returns from bz2 as size_t'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: xmlXPtrNewContext(xmlDocPtr doc, xmlNodePtr here, xmlNodePtr origin) {\n xmlXPathContextPtr ret;\n\n ret = xmlXPathNewContext(doc);\n if (ret == NULL)\n\treturn(ret);\n ret->xptr = 1;\n ret->here = here;\n ret->origin = origin;\n\n xmlXPathRegisterFunc(ret, (xmlChar *)\"range-to\",\n\t xmlXPtrRangeToFunction);\n xmlXPathRegisterFunc(ret, (xmlChar *)\"range\",\n\t xmlXPtrRangeFunction);\n xmlXPathRegisterFunc(ret, (xmlChar *)\"range-inside\",\n\t xmlXPtrRangeInsideFunction);\n xmlXPathRegisterFunc(ret, (xmlChar *)\"string-range\",\n\t xmlXPtrStringRangeFunction);\n xmlXPathRegisterFunc(ret, (xmlChar *)\"start-point\",\n\t xmlXPtrStartPointFunction);\n xmlXPathRegisterFunc(ret, (xmlChar *)\"end-point\",\n\t xmlXPtrEndPointFunction);\n xmlXPathRegisterFunc(ret, (xmlChar *)\"here\",\n\t xmlXPtrHereFunction);\n xmlXPathRegisterFunc(ret, (xmlChar *)\" origin\",\n\t xmlXPtrOriginFunction);\n\n return(ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Fix XPointer paths beginning with range-to\n\nThe old code would invoke the broken xmlXPtrRangeToFunction. range-to\nisn't really a function but a special kind of location step. Remove\nthis function and always handle range-to in the XPath code.\n\nThe old xmlXPtrRangeToFunction could also be abused to trigger a\nuse-after-free error with the potential for remote code execution.\n\nFound with afl-fuzz.\n\nFixes CVE-2016-5131.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline realpath_cache_bucket* realpath_cache_find(const char *path, int path_len, time_t t TSRMLS_DC) /* {{{ */\n{\n#ifdef PHP_WIN32\n\tunsigned long key = realpath_cache_key(path, path_len TSRMLS_CC);\n#else\n\tunsigned long key = realpath_cache_key(path, path_len);\n#endif\n\n\tunsigned long n = key % (sizeof(CWDG(realpath_cache)) / sizeof(CWDG(realpath_cache)[0]));\n\trealpath_cache_bucket **bucket = &CWDG(realpath_cache)[n];\n\n\twhile (*bucket != NULL) {\n\t\tif (CWDG(realpath_cache_ttl) && (*bucket)->expires < t) {\n\t\t\trealpath_cache_bucket *r = *bucket;\n\t\t\t*bucket = (*bucket)->next;\n\n\t\t\t/* if the pointers match then only subtract the length of the path */\t\t \n\t\t \tif(r->path == r->realpath) {\n\t\t\t\tCWDG(realpath_cache_size) -= sizeof(realpath_cache_bucket) + r->path_len + 1;\n\t\t\t} else {\n\t\t\t\tCWDG(realpath_cache_size) -= sizeof(realpath_cache_bucket) + r->path_len + 1 + r->realpath_len + 1;\n\t\t\t}\n\t\t\tfree(r);\n\t\t} else if (key == (*bucket)->key && path_len == (*bucket)->path_len &&\n\t\t\t\t\tmemcmp(path, (*bucket)->path, path_len) == 0) {\n\t\t\treturn *bucket;\n\t\t} else {\n\t\t\tbucket = &(*bucket)->next;\n\t\t}\n\t}\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix for bug #72513'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline LineContribType * _gdContributionsAlloc(unsigned int line_length, unsigned int windows_size)\n{\n\tunsigned int u = 0;\n\tLineContribType *res;\n\tint overflow_error = 0;\n\n\tres = (LineContribType *) gdMalloc(sizeof(LineContribType));\n\tif (!res) {\n\t\treturn NULL;\n\t}\n\tres->WindowSize = windows_size;\n\tres->LineLength = line_length;\n\tif (overflow2(line_length, sizeof(ContributionType))) {\n\t\tgdFree(res);\n\t\treturn NULL;\n\t}\n\tres->ContribRow = (ContributionType *) gdMalloc(line_length * sizeof(ContributionType));\n\tif (res->ContribRow == NULL) {\n\t\tgdFree(res);\n\t\treturn NULL;\n\t}\n\tfor (u = 0 ; u < line_length ; u++) {\n\t\tif (overflow2(windows_size, sizeof(double))) {\n\t\t\toverflow_error = 1;\n\t\t} else {\n\t\t\tres->ContribRow[u].Weights = (double *) gdMalloc(windows_size * sizeof(double));\n\t\t}\n\t\tif (overflow_error == 1 || res->ContribRow[u].Weights == NULL) {\n\t\t\tu--;\n\t\t\twhile (u >= 0) {\n\t\t\t\tgdFree(res->ContribRow[u].Weights);\n\t\t\t\tu--;\n\t\t\t}\n\t\t\treturn NULL;\n\t\t}\n\t}\n\treturn res;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'improve fix #72558, while (u>=0) with unsigned int will always be true'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: PHP_METHOD(snmp, __construct)\n{\n\tphp_snmp_object *snmp_object;\n\tzval *object = getThis();\n\tchar *a1, *a2;\n\tint a1_len, a2_len;\n\tlong timeout = SNMP_DEFAULT_TIMEOUT;\n\tlong retries = SNMP_DEFAULT_RETRIES;\n\tlong version = SNMP_DEFAULT_VERSION;\n\tint argc = ZEND_NUM_ARGS();\n\tzend_error_handling error_handling;\n\n\tsnmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC);\n\tzend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC);\n\t\n\tif (zend_parse_parameters(argc TSRMLS_CC, \"lss|ll\", &version, &a1, &a1_len, &a2, &a2_len, &timeout, &retries) == FAILURE) {\n\t\tzend_restore_error_handling(&error_handling TSRMLS_CC);\n\t\treturn;\n\t}\n\n\tzend_restore_error_handling(&error_handling TSRMLS_CC);\n\n\tswitch(version) {\n\t\tcase SNMP_VERSION_1:\n\t\tcase SNMP_VERSION_2c:\n\t\tcase SNMP_VERSION_3:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tzend_throw_exception(zend_exception_get_default(TSRMLS_C), \"Unknown SNMP protocol version\", 0 TSRMLS_CC);\n\t\t\treturn;\n\t}\n\n\t/* handle re-open of snmp session */\n\tif (snmp_object->session) {\n\t\tnetsnmp_session_free(&(snmp_object->session));\n\t}\n\t\n\tif (netsnmp_session_init(&(snmp_object->session), version, a1, a2, timeout, retries TSRMLS_CC)) {\n\t\treturn;\n\t}\n\tsnmp_object->max_oids = 0;\n\tsnmp_object->valueretrieval = SNMP_G(valueretrieval);\n\tsnmp_object->enum_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM);\n\tsnmp_object->oid_output_format = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT);\n\tsnmp_object->quick_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT);\n\tsnmp_object->oid_increasing_check = TRUE;\n\tsnmp_object->exceptions_enabled = 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Fixed bug #72479 - same as #72434'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: php_stream *php_stream_zip_open(char *filename, char *path, char *mode STREAMS_DC TSRMLS_DC)\n{\n\tstruct zip_file *zf = NULL;\n\tint err = 0;\n\n\tphp_stream *stream = NULL;\n\tstruct php_zip_stream_data_t *self;\n\tstruct zip *stream_za;\n\n\tif (strncmp(mode,\"r\", strlen(\"r\")) != 0) {\n\t\treturn NULL;\n\t}\n\n\tif (filename) {\n\t\tif (ZIP_OPENBASEDIR_CHECKPATH(filename)) {\n\t\t\treturn NULL;\n\t\t}\n\n\t\t/* duplicate to make the stream za independent (esp. for MSHUTDOWN) */\n\t\tstream_za = zip_open(filename, ZIP_CREATE, &err);\n\t\tif (!stream_za) {\n\t\t\treturn NULL;\n\t\t}\n\n\t\tzf = zip_fopen(stream_za, path, 0);\n\t\tif (zf) {\n\t\t\tself = emalloc(sizeof(*self));\n\n\t\t\tself->za = stream_za;\n\t\t\tself->zf = zf; \n\t\t\tself->stream = NULL;\n\t\t\tself->cursor = 0;\n\t\t\tstream = php_stream_alloc(&php_stream_zipio_ops, self, NULL, mode);\n\t\t\tstream->orig_path = estrdup(path);\n\t\t} else {\n\t\t\tzip_close(stream_za);\n\t\t}\n\t}\n\n\tif (!stream) {\n\t\treturn NULL;\n\t} else {\n\t\treturn stream;\n\t}\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix fir bug #72520'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int __init init_ext2_fs(void)\n{\n\tint err = init_ext2_xattr();\n\tif (err)\n\t\treturn err;\n\terr = init_inodecache();\n\tif (err)\n\t\tgoto out1;\n err = register_filesystem(&ext2_fs_type);\n\tif (err)\n\t\tgoto out;\n\treturn 0;\nout:\n\tdestroy_inodecache();\nout1:\n\texit_ext2_xattr();\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-241', 'CWE-19'], 'message': 'ext2: convert to mbcache2\n\nThe conversion is generally straightforward. We convert filesystem from\na global cache to per-fs one. Similarly to ext4 the tricky part is that\nxattr block corresponding to found mbcache entry can get freed before we\nget buffer lock for that block. So we have to check whether the entry is\nstill valid after getting the buffer lock.\n\nSigned-off-by: Jan Kara \nSigned-off-by: Theodore Ts'o '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ext2_xattr_cache_insert(struct buffer_head *bh)\n{\n\t__u32 hash = le32_to_cpu(HDR(bh)->h_hash);\n\tstruct mb_cache_entry *ce;\n\tint error;\n\n\tce = mb_cache_entry_alloc(ext2_xattr_cache, GFP_NOFS);\n\tif (!ce)\n\t\treturn -ENOMEM;\n\terror = mb_cache_entry_insert(ce, bh->b_bdev, bh->b_blocknr, hash);\n\tif (error) {\n\t\tmb_cache_entry_free(ce);\n\t\tif (error == -EBUSY) {\n\t\t\tea_bdebug(bh, \"already in cache (%d cache entries)\",\n\t\t\t\tatomic_read(&ext2_xattr_cache->c_entry_count));\n\t\t\terror = 0;\n\t\t}\n\t} else {\n\t\tea_bdebug(bh, \"inserting [%x] (%d cache entries)\", (int)hash,\n\t\t\t atomic_read(&ext2_xattr_cache->c_entry_count));\n\t\tmb_cache_entry_release(ce);\n\t}\n\treturn error;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-241', 'CWE-19'], 'message': 'ext2: convert to mbcache2\n\nThe conversion is generally straightforward. We convert filesystem from\na global cache to per-fs one. Similarly to ext4 the tricky part is that\nxattr block corresponding to found mbcache entry can get freed before we\nget buffer lock for that block. So we have to check whether the entry is\nstill valid after getting the buffer lock.\n\nSigned-off-by: Jan Kara \nSigned-off-by: Theodore Ts'o '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: rsa_compute_root(const struct rsa_private_key *key,\n\t\t mpz_t x, const mpz_t m)\n{\n mpz_t xp; /* modulo p */\n mpz_t xq; /* modulo q */\n\n mpz_init(xp); mpz_init(xq); \n\n /* Compute xq = m^d % q = (m%q)^b % q */\n mpz_fdiv_r(xq, m, key->q);\n mpz_powm(xq, xq, key->b, key->q);\n\n /* Compute xp = m^d % p = (m%p)^a % p */\n mpz_fdiv_r(xp, m, key->p);\n mpz_powm(xp, xp, key->a, key->p);\n\n /* Set xp' = (xp - xq) c % p. */\n mpz_sub(xp, xp, xq);\n mpz_mul(xp, xp, key->c);\n mpz_fdiv_r(xp, xp, key->p);\n\n /* Finally, compute x = xq + q xp'\n *\n * To prove that this works, note that\n *\n * xp = x + i p,\n * xq = x + j q,\n * c q = 1 + k p\n *\n * for some integers i, j and k. Now, for some integer l,\n *\n * xp' = (xp - xq) c + l p\n * = (x + i p - (x + j q)) c + l p\n * = (i p - j q) c + l p\n * = (i c + l) p - j (c q)\n * = (i c + l) p - j (1 + kp)\n * = (i c + l - j k) p - j\n *\n * which shows that xp' = -j (mod p). We get\n *\n * xq + q xp' = x + j q + (i c + l - j k) p q - j q\n * = x + (i c + l - j k) p q\n *\n * so that\n *\n * xq + q xp' = x (mod pq)\n *\n * We also get 0 <= xq + q xp' < p q, because\n *\n * 0 <= xq < q and 0 <= xp' < p.\n */\n mpz_mul(x, key->q, xp);\n mpz_add(x, x, xq);\n\n mpz_clear(xp); mpz_clear(xq);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-203'], 'message': 'Use mpz_powm_sec.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: MagickExport MagickBooleanType ContrastStretchImage(Image *image,\n const double black_point,const double white_point,ExceptionInfo *exception)\n{\n#define MaxRange(color) ((double) ScaleQuantumToMap((Quantum) (color)))\n#define ContrastStretchImageTag \"ContrastStretch/Image\"\n\n CacheView\n *image_view;\n\n double\n *black,\n *histogram,\n *stretch_map,\n *white;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n progress;\n\n register ssize_t\n i;\n\n ssize_t\n y;\n\n /*\n Allocate histogram and stretch map.\n */\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n if (SetImageGray(image,exception) != MagickFalse)\n (void) SetImageColorspace(image,GRAYColorspace,exception);\n black=(double *) AcquireQuantumMemory(GetPixelChannels(image),sizeof(*black));\n white=(double *) AcquireQuantumMemory(GetPixelChannels(image),sizeof(*white));\n histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)*\n sizeof(*histogram));\n stretch_map=(double *) AcquireQuantumMemory(MaxMap+1UL,\n GetPixelChannels(image)*sizeof(*stretch_map));\n if ((black == (double *) NULL) || (white == (double *) NULL) ||\n (histogram == (double *) NULL) || (stretch_map == (double *) NULL))\n {\n if (stretch_map != (double *) NULL)\n stretch_map=(double *) RelinquishMagickMemory(stretch_map);\n if (histogram != (double *) NULL)\n histogram=(double *) RelinquishMagickMemory(histogram);\n if (white != (double *) NULL)\n white=(double *) RelinquishMagickMemory(white);\n if (black != (double *) NULL)\n black=(double *) RelinquishMagickMemory(black);\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n }\n /*\n Form histogram.\n */\n status=MagickTrue;\n (void) ResetMagickMemory(histogram,0,(MaxMap+1)*GetPixelChannels(image)*\n sizeof(*histogram));\n image_view=AcquireVirtualCacheView(image,exception);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register const Quantum\n *magick_restrict p;\n\n register ssize_t\n x;\n\n if (status == MagickFalse)\n continue;\n p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n {\n status=MagickFalse;\n continue;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n double\n pixel;\n\n pixel=GetPixelIntensity(image,p);\n for (i=0; i < (ssize_t) GetPixelChannels(image); i++)\n {\n if (image->channel_mask != DefaultChannels)\n pixel=(double) p[i];\n histogram[GetPixelChannels(image)*ScaleQuantumToMap(\n ClampToQuantum(pixel))+i]++;\n }\n p+=GetPixelChannels(image);\n }\n }\n image_view=DestroyCacheView(image_view);\n /*\n Find the histogram boundaries by locating the black/white levels.\n */\n for (i=0; i < (ssize_t) GetPixelChannels(image); i++)\n {\n double\n intensity;\n\n register ssize_t\n j;\n\n black[i]=0.0;\n white[i]=MaxRange(QuantumRange);\n intensity=0.0;\n for (j=0; j <= (ssize_t) MaxMap; j++)\n {\n intensity+=histogram[GetPixelChannels(image)*j+i];\n if (intensity > black_point)\n break;\n }\n black[i]=(double) j;\n intensity=0.0;\n for (j=(ssize_t) MaxMap; j != 0; j--)\n {\n intensity+=histogram[GetPixelChannels(image)*j+i];\n if (intensity > ((double) image->columns*image->rows-white_point))\n break;\n }\n white[i]=(double) j;\n }\n histogram=(double *) RelinquishMagickMemory(histogram);\n /*\n Stretch the histogram to create the stretched image mapping.\n */\n (void) ResetMagickMemory(stretch_map,0,(MaxMap+1)*GetPixelChannels(image)*\n sizeof(*stretch_map));\n for (i=0; i < (ssize_t) GetPixelChannels(image); i++)\n {\n register ssize_t\n j;\n\n for (j=0; j <= (ssize_t) MaxMap; j++)\n {\n double\n gamma;\n\n gamma=PerceptibleReciprocal(white[i]-black[i]);\n if (j < (ssize_t) black[i])\n stretch_map[GetPixelChannels(image)*j+i]=0.0;\n else\n if (j > (ssize_t) white[i])\n stretch_map[GetPixelChannels(image)*j+i]=(double) QuantumRange;\n else\n stretch_map[GetPixelChannels(image)*j+i]=(double) ScaleMapToQuantum(\n (double) (MaxMap*gamma*(j-black[i])));\n }\n }\n if (image->storage_class == PseudoClass)\n {\n register ssize_t\n j;\n\n /*\n Stretch-contrast colormap.\n */\n for (j=0; j < (ssize_t) image->colors; j++)\n {\n if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)\n {\n i=GetPixelChannelOffset(image,RedPixelChannel);\n image->colormap[j].red=stretch_map[GetPixelChannels(image)*\n ScaleQuantumToMap(ClampToQuantum(image->colormap[j].red))+i];\n }\n if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)\n {\n i=GetPixelChannelOffset(image,GreenPixelChannel);\n image->colormap[j].green=stretch_map[GetPixelChannels(image)*\n ScaleQuantumToMap(ClampToQuantum(image->colormap[j].green))+i];\n }\n if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)\n {\n i=GetPixelChannelOffset(image,BluePixelChannel);\n image->colormap[j].blue=stretch_map[GetPixelChannels(image)*\n ScaleQuantumToMap(ClampToQuantum(image->colormap[j].blue))+i];\n }\n if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)\n {\n i=GetPixelChannelOffset(image,AlphaPixelChannel);\n image->colormap[j].alpha=stretch_map[GetPixelChannels(image)*\n ScaleQuantumToMap(ClampToQuantum(image->colormap[j].alpha))+i];\n }\n }\n }\n /*\n Stretch-contrast image.\n */\n status=MagickTrue;\n progress=0;\n image_view=AcquireAuthenticCacheView(image,exception);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static,4) shared(progress,status) \\\n magick_threads(image,image,image->rows,1)\n#endif\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;\n\n register ssize_t\n x;\n\n if (status == MagickFalse)\n continue;\n q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n {\n status=MagickFalse;\n continue;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n register ssize_t\n j;\n\n if (GetPixelReadMask(image,q) == 0)\n {\n q+=GetPixelChannels(image);\n continue;\n }\n for (j=0; j < (ssize_t) GetPixelChannels(image); j++)\n {\n PixelChannel channel=GetPixelChannelChannel(image,j);\n PixelTrait traits=GetPixelChannelTraits(image,channel);\n if ((traits & UpdatePixelTrait) == 0)\n continue;\n q[j]=ClampToQuantum(stretch_map[GetPixelChannels(image)*\n ScaleQuantumToMap(q[j])+j]);\n }\n q+=GetPixelChannels(image);\n }\n if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)\n status=MagickFalse;\n if (image->progress_monitor != (MagickProgressMonitor) NULL)\n {\n MagickBooleanType\n proceed;\n\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp critical (MagickCore_ContrastStretchImage)\n#endif\n proceed=SetImageProgress(image,ContrastStretchImageTag,progress++,\n image->rows);\n if (proceed == MagickFalse)\n status=MagickFalse;\n }\n }\n image_view=DestroyCacheView(image_view);\n stretch_map=(double *) RelinquishMagickMemory(stretch_map);\n white=(double *) RelinquishMagickMemory(white);\n black=(double *) RelinquishMagickMemory(black);\n return(status);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Evaluate lazy pixel cache morphology to prevent buffer overflow (bug report from Ibrahim M. El-Sayed)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int tcp_v6_connect(struct sock *sk, struct sockaddr *uaddr,\n\t\t\t int addr_len)\n{\n\tstruct sockaddr_in6 *usin = (struct sockaddr_in6 *) uaddr;\n\tstruct inet_sock *inet = inet_sk(sk);\n\tstruct inet_connection_sock *icsk = inet_csk(sk);\n\tstruct ipv6_pinfo *np = inet6_sk(sk);\n\tstruct tcp_sock *tp = tcp_sk(sk);\n\tstruct in6_addr *saddr = NULL, *final_p, final;\n\tstruct flowi6 fl6;\n\tstruct dst_entry *dst;\n\tint addr_type;\n\tint err;\n\n\tif (addr_len < SIN6_LEN_RFC2133)\n\t\treturn -EINVAL;\n\n\tif (usin->sin6_family != AF_INET6)\n\t\treturn -EAFNOSUPPORT;\n\n\tmemset(&fl6, 0, sizeof(fl6));\n\n\tif (np->sndflow) {\n\t\tfl6.flowlabel = usin->sin6_flowinfo&IPV6_FLOWINFO_MASK;\n\t\tIP6_ECN_flow_init(fl6.flowlabel);\n\t\tif (fl6.flowlabel&IPV6_FLOWLABEL_MASK) {\n\t\t\tstruct ip6_flowlabel *flowlabel;\n\t\t\tflowlabel = fl6_sock_lookup(sk, fl6.flowlabel);\n\t\t\tif (!flowlabel)\n\t\t\t\treturn -EINVAL;\n\t\t\tfl6_sock_release(flowlabel);\n\t\t}\n\t}\n\n\t/*\n\t *\tconnect() to INADDR_ANY means loopback (BSD'ism).\n\t */\n\n\tif (ipv6_addr_any(&usin->sin6_addr))\n\t\tusin->sin6_addr.s6_addr[15] = 0x1;\n\n\taddr_type = ipv6_addr_type(&usin->sin6_addr);\n\n\tif (addr_type & IPV6_ADDR_MULTICAST)\n\t\treturn -ENETUNREACH;\n\n\tif (addr_type&IPV6_ADDR_LINKLOCAL) {\n\t\tif (addr_len >= sizeof(struct sockaddr_in6) &&\n\t\t usin->sin6_scope_id) {\n\t\t\t/* If interface is set while binding, indices\n\t\t\t * must coincide.\n\t\t\t */\n\t\t\tif (sk->sk_bound_dev_if &&\n\t\t\t sk->sk_bound_dev_if != usin->sin6_scope_id)\n\t\t\t\treturn -EINVAL;\n\n\t\t\tsk->sk_bound_dev_if = usin->sin6_scope_id;\n\t\t}\n\n\t\t/* Connect to link-local address requires an interface */\n\t\tif (!sk->sk_bound_dev_if)\n\t\t\treturn -EINVAL;\n\t}\n\n\tif (tp->rx_opt.ts_recent_stamp &&\n\t !ipv6_addr_equal(&sk->sk_v6_daddr, &usin->sin6_addr)) {\n\t\ttp->rx_opt.ts_recent = 0;\n\t\ttp->rx_opt.ts_recent_stamp = 0;\n\t\ttp->write_seq = 0;\n\t}\n\n\tsk->sk_v6_daddr = usin->sin6_addr;\n\tnp->flow_label = fl6.flowlabel;\n\n\t/*\n\t *\tTCP over IPv4\n\t */\n\n\tif (addr_type == IPV6_ADDR_MAPPED) {\n\t\tu32 exthdrlen = icsk->icsk_ext_hdr_len;\n\t\tstruct sockaddr_in sin;\n\n\t\tSOCK_DEBUG(sk, \"connect: ipv4 mapped\\n\");\n\n\t\tif (__ipv6_only_sock(sk))\n\t\t\treturn -ENETUNREACH;\n\n\t\tsin.sin_family = AF_INET;\n\t\tsin.sin_port = usin->sin6_port;\n\t\tsin.sin_addr.s_addr = usin->sin6_addr.s6_addr32[3];\n\n\t\ticsk->icsk_af_ops = &ipv6_mapped;\n\t\tsk->sk_backlog_rcv = tcp_v4_do_rcv;\n#ifdef CONFIG_TCP_MD5SIG\n\t\ttp->af_specific = &tcp_sock_ipv6_mapped_specific;\n#endif\n\n\t\terr = tcp_v4_connect(sk, (struct sockaddr *)&sin, sizeof(sin));\n\n\t\tif (err) {\n\t\t\ticsk->icsk_ext_hdr_len = exthdrlen;\n\t\t\ticsk->icsk_af_ops = &ipv6_specific;\n\t\t\tsk->sk_backlog_rcv = tcp_v6_do_rcv;\n#ifdef CONFIG_TCP_MD5SIG\n\t\t\ttp->af_specific = &tcp_sock_ipv6_specific;\n#endif\n\t\t\tgoto failure;\n\t\t}\n\t\tnp->saddr = sk->sk_v6_rcv_saddr;\n\n\t\treturn err;\n\t}\n\n\tif (!ipv6_addr_any(&sk->sk_v6_rcv_saddr))\n\t\tsaddr = &sk->sk_v6_rcv_saddr;\n\n\tfl6.flowi6_proto = IPPROTO_TCP;\n\tfl6.daddr = sk->sk_v6_daddr;\n\tfl6.saddr = saddr ? *saddr : np->saddr;\n\tfl6.flowi6_oif = sk->sk_bound_dev_if;\n\tfl6.flowi6_mark = sk->sk_mark;\n\tfl6.fl6_dport = usin->sin6_port;\n\tfl6.fl6_sport = inet->inet_sport;\n\n\tfinal_p = fl6_update_dst(&fl6, np->opt, &final);\n\n\tsecurity_sk_classify_flow(sk, flowi6_to_flowi(&fl6));\n\n\tdst = ip6_dst_lookup_flow(sk, &fl6, final_p);\n\tif (IS_ERR(dst)) {\n\t\terr = PTR_ERR(dst);\n\t\tgoto failure;\n\t}\n\n\tif (!saddr) {\n\t\tsaddr = &fl6.saddr;\n\t\tsk->sk_v6_rcv_saddr = *saddr;\n\t}\n\n\t/* set the source address */\n\tnp->saddr = *saddr;\n\tinet->inet_rcv_saddr = LOOPBACK4_IPV6;\n\n\tsk->sk_gso_type = SKB_GSO_TCPV6;\n\t__ip6_dst_store(sk, dst, NULL, NULL);\n\n\tif (tcp_death_row.sysctl_tw_recycle &&\n\t !tp->rx_opt.ts_recent_stamp &&\n\t ipv6_addr_equal(&fl6.daddr, &sk->sk_v6_daddr))\n\t\ttcp_fetch_timewait_stamp(sk, dst);\n\n\ticsk->icsk_ext_hdr_len = 0;\n\tif (np->opt)\n\t\ticsk->icsk_ext_hdr_len = (np->opt->opt_flen +\n\t\t\t\t\t np->opt->opt_nflen);\n\n\ttp->rx_opt.mss_clamp = IPV6_MIN_MTU - sizeof(struct tcphdr) - sizeof(struct ipv6hdr);\n\n\tinet->inet_dport = usin->sin6_port;\n\n\ttcp_set_state(sk, TCP_SYN_SENT);\n\terr = inet6_hash_connect(&tcp_death_row, sk);\n\tif (err)\n\t\tgoto late_failure;\n\n\tsk_set_txhash(sk);\n\n\tif (!tp->write_seq && likely(!tp->repair))\n\t\ttp->write_seq = secure_tcpv6_sequence_number(np->saddr.s6_addr32,\n\t\t\t\t\t\t\t sk->sk_v6_daddr.s6_addr32,\n\t\t\t\t\t\t\t inet->inet_sport,\n\t\t\t\t\t\t\t inet->inet_dport);\n\n\terr = tcp_connect(sk);\n\tif (err)\n\t\tgoto late_failure;\n\n\treturn 0;\n\nlate_failure:\n\ttcp_set_state(sk, TCP_CLOSE);\n\t__sk_dst_reset(sk);\nfailure:\n\tinet->inet_dport = 0;\n\tsk->sk_route_caps = 0;\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-284', 'CWE-264'], 'message': 'ipv6: add complete rcu protection around np->opt\n\nThis patch addresses multiple problems :\n\nUDP/RAW sendmsg() need to get a stable struct ipv6_txoptions\nwhile socket is not locked : Other threads can change np->opt\nconcurrently. Dmitry posted a syzkaller\n(http://github.com/google/syzkaller) program desmonstrating\nuse-after-free.\n\nStarting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock()\nand dccp_v6_request_recv_sock() also need to use RCU protection\nto dereference np->opt once (before calling ipv6_dup_options())\n\nThis patch adds full RCU protection to np->opt\n\nReported-by: Dmitry Vyukov \nSigned-off-by: Eric Dumazet \nAcked-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int udpv6_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)\n{\n\tstruct ipv6_txoptions opt_space;\n\tstruct udp_sock *up = udp_sk(sk);\n\tstruct inet_sock *inet = inet_sk(sk);\n\tstruct ipv6_pinfo *np = inet6_sk(sk);\n\tDECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name);\n\tstruct in6_addr *daddr, *final_p, final;\n\tstruct ipv6_txoptions *opt = NULL;\n\tstruct ip6_flowlabel *flowlabel = NULL;\n\tstruct flowi6 fl6;\n\tstruct dst_entry *dst;\n\tint addr_len = msg->msg_namelen;\n\tint ulen = len;\n\tint hlimit = -1;\n\tint tclass = -1;\n\tint dontfrag = -1;\n\tint corkreq = up->corkflag || msg->msg_flags&MSG_MORE;\n\tint err;\n\tint connected = 0;\n\tint is_udplite = IS_UDPLITE(sk);\n\tint (*getfrag)(void *, char *, int, int, int, struct sk_buff *);\n\n\t/* destination address check */\n\tif (sin6) {\n\t\tif (addr_len < offsetof(struct sockaddr, sa_data))\n\t\t\treturn -EINVAL;\n\n\t\tswitch (sin6->sin6_family) {\n\t\tcase AF_INET6:\n\t\t\tif (addr_len < SIN6_LEN_RFC2133)\n\t\t\t\treturn -EINVAL;\n\t\t\tdaddr = &sin6->sin6_addr;\n\t\t\tbreak;\n\t\tcase AF_INET:\n\t\t\tgoto do_udp_sendmsg;\n\t\tcase AF_UNSPEC:\n\t\t\tmsg->msg_name = sin6 = NULL;\n\t\t\tmsg->msg_namelen = addr_len = 0;\n\t\t\tdaddr = NULL;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn -EINVAL;\n\t\t}\n\t} else if (!up->pending) {\n\t\tif (sk->sk_state != TCP_ESTABLISHED)\n\t\t\treturn -EDESTADDRREQ;\n\t\tdaddr = &sk->sk_v6_daddr;\n\t} else\n\t\tdaddr = NULL;\n\n\tif (daddr) {\n\t\tif (ipv6_addr_v4mapped(daddr)) {\n\t\t\tstruct sockaddr_in sin;\n\t\t\tsin.sin_family = AF_INET;\n\t\t\tsin.sin_port = sin6 ? sin6->sin6_port : inet->inet_dport;\n\t\t\tsin.sin_addr.s_addr = daddr->s6_addr32[3];\n\t\t\tmsg->msg_name = &sin;\n\t\t\tmsg->msg_namelen = sizeof(sin);\ndo_udp_sendmsg:\n\t\t\tif (__ipv6_only_sock(sk))\n\t\t\t\treturn -ENETUNREACH;\n\t\t\treturn udp_sendmsg(sk, msg, len);\n\t\t}\n\t}\n\n\tif (up->pending == AF_INET)\n\t\treturn udp_sendmsg(sk, msg, len);\n\n\t/* Rough check on arithmetic overflow,\n\t better check is made in ip6_append_data().\n\t */\n\tif (len > INT_MAX - sizeof(struct udphdr))\n\t\treturn -EMSGSIZE;\n\n\tgetfrag = is_udplite ? udplite_getfrag : ip_generic_getfrag;\n\tif (up->pending) {\n\t\t/*\n\t\t * There are pending frames.\n\t\t * The socket lock must be held while it's corked.\n\t\t */\n\t\tlock_sock(sk);\n\t\tif (likely(up->pending)) {\n\t\t\tif (unlikely(up->pending != AF_INET6)) {\n\t\t\t\trelease_sock(sk);\n\t\t\t\treturn -EAFNOSUPPORT;\n\t\t\t}\n\t\t\tdst = NULL;\n\t\t\tgoto do_append_data;\n\t\t}\n\t\trelease_sock(sk);\n\t}\n\tulen += sizeof(struct udphdr);\n\n\tmemset(&fl6, 0, sizeof(fl6));\n\n\tif (sin6) {\n\t\tif (sin6->sin6_port == 0)\n\t\t\treturn -EINVAL;\n\n\t\tfl6.fl6_dport = sin6->sin6_port;\n\t\tdaddr = &sin6->sin6_addr;\n\n\t\tif (np->sndflow) {\n\t\t\tfl6.flowlabel = sin6->sin6_flowinfo&IPV6_FLOWINFO_MASK;\n\t\t\tif (fl6.flowlabel&IPV6_FLOWLABEL_MASK) {\n\t\t\t\tflowlabel = fl6_sock_lookup(sk, fl6.flowlabel);\n\t\t\t\tif (!flowlabel)\n\t\t\t\t\treturn -EINVAL;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * Otherwise it will be difficult to maintain\n\t\t * sk->sk_dst_cache.\n\t\t */\n\t\tif (sk->sk_state == TCP_ESTABLISHED &&\n\t\t ipv6_addr_equal(daddr, &sk->sk_v6_daddr))\n\t\t\tdaddr = &sk->sk_v6_daddr;\n\n\t\tif (addr_len >= sizeof(struct sockaddr_in6) &&\n\t\t sin6->sin6_scope_id &&\n\t\t __ipv6_addr_needs_scope_id(__ipv6_addr_type(daddr)))\n\t\t\tfl6.flowi6_oif = sin6->sin6_scope_id;\n\t} else {\n\t\tif (sk->sk_state != TCP_ESTABLISHED)\n\t\t\treturn -EDESTADDRREQ;\n\n\t\tfl6.fl6_dport = inet->inet_dport;\n\t\tdaddr = &sk->sk_v6_daddr;\n\t\tfl6.flowlabel = np->flow_label;\n\t\tconnected = 1;\n\t}\n\n\tif (!fl6.flowi6_oif)\n\t\tfl6.flowi6_oif = sk->sk_bound_dev_if;\n\n\tif (!fl6.flowi6_oif)\n\t\tfl6.flowi6_oif = np->sticky_pktinfo.ipi6_ifindex;\n\n\tfl6.flowi6_mark = sk->sk_mark;\n\n\tif (msg->msg_controllen) {\n\t\topt = &opt_space;\n\t\tmemset(opt, 0, sizeof(struct ipv6_txoptions));\n\t\topt->tot_len = sizeof(*opt);\n\n\t\terr = ip6_datagram_send_ctl(sock_net(sk), sk, msg, &fl6, opt,\n\t\t\t\t\t &hlimit, &tclass, &dontfrag);\n\t\tif (err < 0) {\n\t\t\tfl6_sock_release(flowlabel);\n\t\t\treturn err;\n\t\t}\n\t\tif ((fl6.flowlabel&IPV6_FLOWLABEL_MASK) && !flowlabel) {\n\t\t\tflowlabel = fl6_sock_lookup(sk, fl6.flowlabel);\n\t\t\tif (!flowlabel)\n\t\t\t\treturn -EINVAL;\n\t\t}\n\t\tif (!(opt->opt_nflen|opt->opt_flen))\n\t\t\topt = NULL;\n\t\tconnected = 0;\n\t}\n\tif (!opt)\n\t\topt = np->opt;\n\tif (flowlabel)\n\t\topt = fl6_merge_options(&opt_space, flowlabel, opt);\n\topt = ipv6_fixup_options(&opt_space, opt);\n\n\tfl6.flowi6_proto = sk->sk_protocol;\n\tif (!ipv6_addr_any(daddr))\n\t\tfl6.daddr = *daddr;\n\telse\n\t\tfl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */\n\tif (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr))\n\t\tfl6.saddr = np->saddr;\n\tfl6.fl6_sport = inet->inet_sport;\n\n\tfinal_p = fl6_update_dst(&fl6, opt, &final);\n\tif (final_p)\n\t\tconnected = 0;\n\n\tif (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr)) {\n\t\tfl6.flowi6_oif = np->mcast_oif;\n\t\tconnected = 0;\n\t} else if (!fl6.flowi6_oif)\n\t\tfl6.flowi6_oif = np->ucast_oif;\n\n\tsecurity_sk_classify_flow(sk, flowi6_to_flowi(&fl6));\n\n\tdst = ip6_sk_dst_lookup_flow(sk, &fl6, final_p);\n\tif (IS_ERR(dst)) {\n\t\terr = PTR_ERR(dst);\n\t\tdst = NULL;\n\t\tgoto out;\n\t}\n\n\tif (hlimit < 0)\n\t\thlimit = ip6_sk_dst_hoplimit(np, &fl6, dst);\n\n\tif (tclass < 0)\n\t\ttclass = np->tclass;\n\n\tif (msg->msg_flags&MSG_CONFIRM)\n\t\tgoto do_confirm;\nback_from_confirm:\n\n\t/* Lockless fast path for the non-corking case */\n\tif (!corkreq) {\n\t\tstruct sk_buff *skb;\n\n\t\tskb = ip6_make_skb(sk, getfrag, msg, ulen,\n\t\t\t\t sizeof(struct udphdr), hlimit, tclass, opt,\n\t\t\t\t &fl6, (struct rt6_info *)dst,\n\t\t\t\t msg->msg_flags, dontfrag);\n\t\terr = PTR_ERR(skb);\n\t\tif (!IS_ERR_OR_NULL(skb))\n\t\t\terr = udp_v6_send_skb(skb, &fl6);\n\t\tgoto release_dst;\n\t}\n\n\tlock_sock(sk);\n\tif (unlikely(up->pending)) {\n\t\t/* The socket is already corked while preparing it. */\n\t\t/* ... which is an evident application bug. --ANK */\n\t\trelease_sock(sk);\n\n\t\tnet_dbg_ratelimited(\"udp cork app bug 2\\n\");\n\t\terr = -EINVAL;\n\t\tgoto out;\n\t}\n\n\tup->pending = AF_INET6;\n\ndo_append_data:\n\tif (dontfrag < 0)\n\t\tdontfrag = np->dontfrag;\n\tup->len += ulen;\n\terr = ip6_append_data(sk, getfrag, msg, ulen,\n\t\tsizeof(struct udphdr), hlimit, tclass, opt, &fl6,\n\t\t(struct rt6_info *)dst,\n\t\tcorkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags, dontfrag);\n\tif (err)\n\t\tudp_v6_flush_pending_frames(sk);\n\telse if (!corkreq)\n\t\terr = udp_v6_push_pending_frames(sk);\n\telse if (unlikely(skb_queue_empty(&sk->sk_write_queue)))\n\t\tup->pending = 0;\n\n\tif (err > 0)\n\t\terr = np->recverr ? net_xmit_errno(err) : 0;\n\trelease_sock(sk);\n\nrelease_dst:\n\tif (dst) {\n\t\tif (connected) {\n\t\t\tip6_dst_store(sk, dst,\n\t\t\t\t ipv6_addr_equal(&fl6.daddr, &sk->sk_v6_daddr) ?\n\t\t\t\t &sk->sk_v6_daddr : NULL,\n#ifdef CONFIG_IPV6_SUBTREES\n\t\t\t\t ipv6_addr_equal(&fl6.saddr, &np->saddr) ?\n\t\t\t\t &np->saddr :\n#endif\n\t\t\t\t NULL);\n\t\t} else {\n\t\t\tdst_release(dst);\n\t\t}\n\t\tdst = NULL;\n\t}\n\nout:\n\tdst_release(dst);\n\tfl6_sock_release(flowlabel);\n\tif (!err)\n\t\treturn len;\n\t/*\n\t * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space. Reporting\n\t * ENOBUFS might not be good (it's not tunable per se), but otherwise\n\t * we don't have a good statistic (IpOutDiscards but it can be too many\n\t * things). We could add another new stat but at least for now that\n\t * seems like overkill.\n\t */\n\tif (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {\n\t\tUDP6_INC_STATS_USER(sock_net(sk),\n\t\t\t\tUDP_MIB_SNDBUFERRORS, is_udplite);\n\t}\n\treturn err;\n\ndo_confirm:\n\tdst_confirm(dst);\n\tif (!(msg->msg_flags&MSG_PROBE) || len)\n\t\tgoto back_from_confirm;\n\terr = 0;\n\tgoto out;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-284', 'CWE-264'], 'message': 'ipv6: add complete rcu protection around np->opt\n\nThis patch addresses multiple problems :\n\nUDP/RAW sendmsg() need to get a stable struct ipv6_txoptions\nwhile socket is not locked : Other threads can change np->opt\nconcurrently. Dmitry posted a syzkaller\n(http://github.com/google/syzkaller) program desmonstrating\nuse-after-free.\n\nStarting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock()\nand dccp_v6_request_recv_sock() also need to use RCU protection\nto dereference np->opt once (before calling ipv6_dup_options())\n\nThis patch adds full RCU protection to np->opt\n\nReported-by: Dmitry Vyukov \nSigned-off-by: Eric Dumazet \nAcked-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void *Type_MLU_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)\n{\n cmsMLU* mlu;\n cmsUInt32Number Count, RecLen, NumOfWchar;\n cmsUInt32Number SizeOfHeader;\n cmsUInt32Number Len, Offset;\n cmsUInt32Number i;\n wchar_t* Block;\n cmsUInt32Number BeginOfThisString, EndOfThisString, LargestPosition;\n\n *nItems = 0;\n if (!_cmsReadUInt32Number(io, &Count)) return NULL;\n if (!_cmsReadUInt32Number(io, &RecLen)) return NULL;\n\n if (RecLen != 12) {\n\n cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, \"multiLocalizedUnicodeType of len != 12 is not supported.\");\n return NULL;\n }\n\n mlu = cmsMLUalloc(self ->ContextID, Count);\n if (mlu == NULL) return NULL;\n\n mlu ->UsedEntries = Count;\n\n SizeOfHeader = 12 * Count + sizeof(_cmsTagBase);\n LargestPosition = 0;\n\n for (i=0; i < Count; i++) {\n\n if (!_cmsReadUInt16Number(io, &mlu ->Entries[i].Language)) goto Error;\n if (!_cmsReadUInt16Number(io, &mlu ->Entries[i].Country)) goto Error;\n\n // Now deal with Len and offset.\n if (!_cmsReadUInt32Number(io, &Len)) goto Error;\n if (!_cmsReadUInt32Number(io, &Offset)) goto Error;\n\n // Check for overflow\n if (Offset < (SizeOfHeader + 8)) goto Error;\n if ((Offset + Len) > SizeOfTag + 8) goto Error;\n\n // True begin of the string\n BeginOfThisString = Offset - SizeOfHeader - 8;\n\n // Ajust to wchar_t elements\n mlu ->Entries[i].Len = (Len * sizeof(wchar_t)) / sizeof(cmsUInt16Number);\n mlu ->Entries[i].StrW = (BeginOfThisString * sizeof(wchar_t)) / sizeof(cmsUInt16Number);\n\n // To guess maximum size, add offset + len\n EndOfThisString = BeginOfThisString + Len;\n if (EndOfThisString > LargestPosition)\n LargestPosition = EndOfThisString;\n }\n\n // Now read the remaining of tag and fill all strings. Subtract the directory\n SizeOfTag = (LargestPosition * sizeof(wchar_t)) / sizeof(cmsUInt16Number);\n if (SizeOfTag == 0)\n {\n Block = NULL;\n NumOfWchar = 0;\n\n }\n else\n {\n Block = (wchar_t*) _cmsMalloc(self ->ContextID, SizeOfTag);\n if (Block == NULL) goto Error;\n NumOfWchar = SizeOfTag / sizeof(wchar_t);\n if (!_cmsReadWCharArray(io, NumOfWchar, Block)) goto Error;\n }\n\n mlu ->MemPool = Block;\n mlu ->PoolSize = SizeOfTag;\n mlu ->PoolUsed = SizeOfTag;\n\n *nItems = 1;\n return (void*) mlu;\n\nError:\n if (mlu) cmsMLUfree(mlu);\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Contributed fixes from Oracle\n\nTwo minor glitches'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int __btrfs_set_acl(struct btrfs_trans_handle *trans,\n\t\t\t struct inode *inode, struct posix_acl *acl, int type)\n{\n\tint ret, size = 0;\n\tconst char *name;\n\tchar *value = NULL;\n\n\tswitch (type) {\n\tcase ACL_TYPE_ACCESS:\n\t\tname = XATTR_NAME_POSIX_ACL_ACCESS;\n\t\tif (acl) {\n\t\t\tret = posix_acl_equiv_mode(acl, &inode->i_mode);\n\t\t\tif (ret < 0)\n\t\t\t\treturn ret;\n\t\t\tif (ret == 0)\n\t\t\t\tacl = NULL;\n\t\t}\n\t\tret = 0;\n\t\tbreak;\n\tcase ACL_TYPE_DEFAULT:\n\t\tif (!S_ISDIR(inode->i_mode))\n\t\t\treturn acl ? -EINVAL : 0;\n\t\tname = XATTR_NAME_POSIX_ACL_DEFAULT;\n\t\tbreak;\n\tdefault:\n\t\treturn -EINVAL;\n\t}\n\n\tif (acl) {\n\t\tsize = posix_acl_xattr_size(acl->a_count);\n\t\tvalue = kmalloc(size, GFP_KERNEL);\n\t\tif (!value) {\n\t\t\tret = -ENOMEM;\n\t\t\tgoto out;\n\t\t}\n\n\t\tret = posix_acl_to_xattr(&init_user_ns, acl, value, size);\n\t\tif (ret < 0)\n\t\t\tgoto out;\n\t}\n\n\tret = __btrfs_setxattr(trans, inode, name, value, size, 0);\nout:\n\tkfree(value);\n\n\tif (!ret)\n\t\tset_cached_acl(inode, type, acl);\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-862', 'CWE-285'], 'message': 'posix_acl: Clear SGID bit when setting file permissions\n\nWhen file permissions are modified via chmod(2) and the user is not in\nthe owning group or capable of CAP_FSETID, the setgid bit is cleared in\ninode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file\npermissions as well as the new ACL, but doesn't clear the setgid bit in\na similar way; this allows to bypass the check in chmod(2). Fix that.\n\nReferences: CVE-2016-7097\nReviewed-by: Christoph Hellwig \nReviewed-by: Jeff Layton \nSigned-off-by: Jan Kara \nSigned-off-by: Andreas Gruenbacher '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: eog_image_save_error_message_area_new (const gchar *caption,\n\t\t\t\t const GError *error)\n{\n\tGtkWidget *message_area;\n\tgchar *error_message = NULL;\n\tgchar *message_details = NULL;\n\tgchar *pango_escaped_caption = NULL;\n\n\tg_return_val_if_fail (caption != NULL, NULL);\n\tg_return_val_if_fail (error != NULL, NULL);\n\n\t/* Escape the caption string with respect to pango markup.\n\t This is necessary because otherwise characters like \"&\" will\n\t be interpreted as the beginning of a pango entity inside\n\t the message area GtkLabel. */\n\tpango_escaped_caption = g_markup_escape_text (caption, -1);\n\terror_message = g_strdup_printf (_(\"Could not save image '%s'.\"),\n\t\t\t\t\t pango_escaped_caption);\n\n\tmessage_details = g_strdup (error->message);\n\n\tmessage_area = create_error_message_area (error_message,\n\t\t\t\t\t\t message_details,\n\t\t\t\t\t\t EOG_ERROR_MESSAGE_AREA_CANCEL_BUTTON |\n\t\t\t\t\t\t EOG_ERROR_MESSAGE_AREA_SAVEAS_BUTTON);\n\n\tg_free (pango_escaped_caption);\n\tg_free (error_message);\n\tg_free (message_details);\n\n\treturn message_area;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'EogErrorMessageArea: Make sure error messages are valid UTF8\n\nGMarkup requires valid UTF8 input strings and would cause odd\nlooking messages if given invalid input. This could also trigger an\nout-of-bounds write in glib before 2.44.1. Reported by kaslovdmitri.\n\nhttps://bugzilla.gnome.org/show_bug.cgi?id=770143'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: opj_pi_iterator_t *opj_pi_create_decode(opj_image_t *p_image,\n\t\t\t\t\t\t\t\t\t\topj_cp_t *p_cp,\n\t\t\t\t\t\t\t\t\t\tOPJ_UINT32 p_tile_no)\n{\n\t/* loop */\n\tOPJ_UINT32 pino;\n\tOPJ_UINT32 compno, resno;\n\n\t/* to store w, h, dx and dy fro all components and resolutions */\n\tOPJ_UINT32 * l_tmp_data;\n\tOPJ_UINT32 ** l_tmp_ptr;\n\n\t/* encoding prameters to set */\n\tOPJ_UINT32 l_max_res;\n\tOPJ_UINT32 l_max_prec;\n\tOPJ_INT32 l_tx0,l_tx1,l_ty0,l_ty1;\n\tOPJ_UINT32 l_dx_min,l_dy_min;\n\tOPJ_UINT32 l_bound;\n\tOPJ_UINT32 l_step_p , l_step_c , l_step_r , l_step_l ;\n\tOPJ_UINT32 l_data_stride;\n\n\t/* pointers */\n\topj_pi_iterator_t *l_pi = 00;\n\topj_tcp_t *l_tcp = 00;\n\tconst opj_tccp_t *l_tccp = 00;\n\topj_pi_comp_t *l_current_comp = 00;\n\topj_image_comp_t * l_img_comp = 00;\n\topj_pi_iterator_t * l_current_pi = 00;\n\tOPJ_UINT32 * l_encoding_value_ptr = 00;\n\n\t/* preconditions in debug */\n\tassert(p_cp != 00);\n\tassert(p_image != 00);\n\tassert(p_tile_no < p_cp->tw * p_cp->th);\n\n\t/* initializations */\n\tl_tcp = &p_cp->tcps[p_tile_no];\n\tl_bound = l_tcp->numpocs+1;\n\n\tl_data_stride = 4 * OPJ_J2K_MAXRLVLS;\n\tl_tmp_data = (OPJ_UINT32*)opj_malloc(\n\t\tl_data_stride * p_image->numcomps * sizeof(OPJ_UINT32));\n\tif\n\t\t(! l_tmp_data)\n\t{\n\t\treturn 00;\n\t}\n\tl_tmp_ptr = (OPJ_UINT32**)opj_malloc(\n\t\tp_image->numcomps * sizeof(OPJ_UINT32 *));\n\tif\n\t\t(! l_tmp_ptr)\n\t{\n\t\topj_free(l_tmp_data);\n\t\treturn 00;\n\t}\n\n\t/* memory allocation for pi */\n\tl_pi = opj_pi_create(p_image, p_cp, p_tile_no);\n\tif (!l_pi) {\n\t\topj_free(l_tmp_data);\n\t\topj_free(l_tmp_ptr);\n\t\treturn 00;\n\t}\n\n\tl_encoding_value_ptr = l_tmp_data;\n\t/* update pointer array */\n\tfor\n\t\t(compno = 0; compno < p_image->numcomps; ++compno)\n\t{\n\t\tl_tmp_ptr[compno] = l_encoding_value_ptr;\n\t\tl_encoding_value_ptr += l_data_stride;\n\t}\n\t/* get encoding parameters */\n\topj_get_all_encoding_parameters(p_image,p_cp,p_tile_no,&l_tx0,&l_tx1,&l_ty0,&l_ty1,&l_dx_min,&l_dy_min,&l_max_prec,&l_max_res,l_tmp_ptr);\n\n\t/* step calculations */\n\tl_step_p = 1;\n\tl_step_c = l_max_prec * l_step_p;\n\tl_step_r = p_image->numcomps * l_step_c;\n\tl_step_l = l_max_res * l_step_r;\n\n\t/* set values for first packet iterator */\n\tl_current_pi = l_pi;\n\n\t/* memory allocation for include */\n\t/* prevent an integer overflow issue */\n\tl_current_pi->include = 00;\n\tif (l_step_l <= (SIZE_MAX / (l_tcp->numlayers + 1U)))\n\t{\n\t\tl_current_pi->include = (OPJ_INT16*) opj_calloc((l_tcp->numlayers +1) * l_step_l, sizeof(OPJ_INT16));\n\t}\n\n\tif\n\t\t(!l_current_pi->include)\n\t{\n\t\topj_free(l_tmp_data);\n\t\topj_free(l_tmp_ptr);\n\t\topj_pi_destroy(l_pi, l_bound);\n\t\treturn 00;\n\t}\n\n\t/* special treatment for the first packet iterator */\n\tl_current_comp = l_current_pi->comps;\n\tl_img_comp = p_image->comps;\n\tl_tccp = l_tcp->tccps;\n\n\tl_current_pi->tx0 = l_tx0;\n\tl_current_pi->ty0 = l_ty0;\n\tl_current_pi->tx1 = l_tx1;\n\tl_current_pi->ty1 = l_ty1;\n\n\t/*l_current_pi->dx = l_img_comp->dx;*/\n\t/*l_current_pi->dy = l_img_comp->dy;*/\n\n\tl_current_pi->step_p = l_step_p;\n\tl_current_pi->step_c = l_step_c;\n\tl_current_pi->step_r = l_step_r;\n\tl_current_pi->step_l = l_step_l;\n\n\t/* allocation for components and number of components has already been calculated by opj_pi_create */\n\tfor\n\t\t(compno = 0; compno < l_current_pi->numcomps; ++compno)\n\t{\n\t\topj_pi_resolution_t *l_res = l_current_comp->resolutions;\n\t\tl_encoding_value_ptr = l_tmp_ptr[compno];\n\n\t\tl_current_comp->dx = l_img_comp->dx;\n\t\tl_current_comp->dy = l_img_comp->dy;\n\t\t/* resolutions have already been initialized */\n\t\tfor\n\t\t\t(resno = 0; resno < l_current_comp->numresolutions; resno++)\n\t\t{\n\t\t\tl_res->pdx = *(l_encoding_value_ptr++);\n\t\t\tl_res->pdy = *(l_encoding_value_ptr++);\n\t\t\tl_res->pw = *(l_encoding_value_ptr++);\n\t\t\tl_res->ph = *(l_encoding_value_ptr++);\n\t\t\t++l_res;\n\t\t}\n\t\t++l_current_comp;\n\t\t++l_img_comp;\n\t\t++l_tccp;\n\t}\n\t++l_current_pi;\n\n\tfor (pino = 1 ; pinocomps;\n\t\tl_img_comp = p_image->comps;\n\t\tl_tccp = l_tcp->tccps;\n\n\t\tl_current_pi->tx0 = l_tx0;\n\t\tl_current_pi->ty0 = l_ty0;\n\t\tl_current_pi->tx1 = l_tx1;\n\t\tl_current_pi->ty1 = l_ty1;\n\t\t/*l_current_pi->dx = l_dx_min;*/\n\t\t/*l_current_pi->dy = l_dy_min;*/\n\t\tl_current_pi->step_p = l_step_p;\n\t\tl_current_pi->step_c = l_step_c;\n\t\tl_current_pi->step_r = l_step_r;\n\t\tl_current_pi->step_l = l_step_l;\n\n\t\t/* allocation for components and number of components has already been calculated by opj_pi_create */\n\t\tfor\n\t\t\t(compno = 0; compno < l_current_pi->numcomps; ++compno)\n\t\t{\n\t\t\topj_pi_resolution_t *l_res = l_current_comp->resolutions;\n\t\t\tl_encoding_value_ptr = l_tmp_ptr[compno];\n\n\t\t\tl_current_comp->dx = l_img_comp->dx;\n\t\t\tl_current_comp->dy = l_img_comp->dy;\n\t\t\t/* resolutions have already been initialized */\n\t\t\tfor\n\t\t\t\t(resno = 0; resno < l_current_comp->numresolutions; resno++)\n\t\t\t{\n\t\t\t\tl_res->pdx = *(l_encoding_value_ptr++);\n\t\t\t\tl_res->pdy = *(l_encoding_value_ptr++);\n\t\t\t\tl_res->pw = *(l_encoding_value_ptr++);\n\t\t\t\tl_res->ph = *(l_encoding_value_ptr++);\n\t\t\t\t++l_res;\n\t\t\t}\n\t\t\t++l_current_comp;\n\t\t\t++l_img_comp;\n\t\t\t++l_tccp;\n\t\t}\n\t\t/* special treatment*/\n\t\tl_current_pi->include = (l_current_pi-1)->include;\n\t\t++l_current_pi;\n\t}\n\topj_free(l_tmp_data);\n\tl_tmp_data = 00;\n\topj_free(l_tmp_ptr);\n\tl_tmp_ptr = 00;\n\tif\n\t\t(l_tcp->POC)\n\t{\n\t\topj_pi_update_decode_poc (l_pi,l_tcp,l_max_prec,l_max_res);\n\t}\n\telse\n\t{\n\t\topj_pi_update_decode_not_poc(l_pi,l_tcp,l_max_prec,l_max_res);\n\t}\n\treturn l_pi;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190', 'CWE-125', 'CWE-703', 'CWE-787'], 'message': 'Cast to size_t before multiplication\n\nNeed to cast to size_t before multiplication otherwise overflow check is useless.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: local int bits(struct state *s, int need)\n{\n\tboost::int32_t val; /* bit accumulator (can use up to 20 bits) */\n\n /* load at least need bits into val */\n val = s->bitbuf;\n while (s->bitcnt < need) {\n if (s->incnt == s->inlen) longjmp(s->env, 1); /* out of input */\n val |= (boost::int32_t)(s->in[s->incnt++]) << s->bitcnt; /* load eight bits */\n s->bitcnt += 8;\n }\n\n /* drop need bits and update buffer, always zero to seven bits left */\n s->bitbuf = (int)(val >> need);\n s->bitcnt -= need;\n\n /* return need bits, zeroing the bits above that */\n return (int)(val & ((1L << need) - 1));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'update puff.c for gzip inflation (#1022)\n\nupdate puff.c for gzip inflation'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static bool check_log_path(sys_var *self, THD *thd, set_var *var)\n{\n if (!var->value)\n return false; // DEFAULT is ok\n\n if (!var->save_result.string_value.str)\n return true;\n\n if (var->save_result.string_value.length > FN_REFLEN)\n { // path is too long\n my_error(ER_PATH_LENGTH, MYF(0), self->name.str);\n return true;\n }\n\n char path[FN_REFLEN];\n size_t path_length= unpack_filename(path, var->save_result.string_value.str);\n\n if (!path_length)\n return true;\n\n if (!is_filename_allowed(var->save_result.string_value.str, \n var->save_result.string_value.length))\n {\n my_error(ER_WRONG_VALUE_FOR_VAR, MYF(0), \n self->name.str, var->save_result.string_value.str);\n return true;\n }\n\n MY_STAT f_stat;\n\n if (my_stat(path, &f_stat, MYF(0)))\n {\n if (!MY_S_ISREG(f_stat.st_mode) || !(f_stat.st_mode & MY_S_IWRITE))\n return true; // not a regular writable file\n return false;\n }\n\n (void) dirname_part(path, var->save_result.string_value.str, &path_length);\n\n if (var->save_result.string_value.length - path_length >= FN_LEN)\n { // filename is too long\n my_error(ER_PATH_LENGTH, MYF(0), self->name.str);\n return true;\n }\n\n if (!path_length) // no path is good path (remember, relative to datadir)\n return false;\n\n if (my_access(path, (F_OK|W_OK)))\n return true; // directory is not writable\n\n return false;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'Bug#24388753: PRIVILEGE ESCALATION USING MYSQLD_SAFE\n\n[This is the 5.5/5.6 version of the bugfix].\n\nThe problem was that it was possible to write log files ending\nin .ini/.cnf that later could be parsed as an options file.\nThis made it possible for users to specify startup options\nwithout the permissions to do so.\n\nThis patch fixes the problem by disallowing general query log\nand slow query log to be written to files ending in .ini and .cnf.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n#define RMT_EQUAL_RGB 1\n#define RMT_NONE 0\n#define RMT_RAW 2\n#define RT_STANDARD 1\n#define RT_ENCODED 2\n#define RT_FORMAT_RGB 3\n\n typedef struct _SUNInfo\n {\n unsigned int\n magic,\n width,\n height,\n depth,\n length,\n type,\n maptype,\n maplength;\n } SUNInfo;\n\n Image\n *image;\n\n int\n bit;\n\n MagickBooleanType\n status;\n\n MagickSizeType\n number_pixels;\n\n register Quantum\n *q;\n\n register ssize_t\n i,\n x;\n\n register unsigned char\n *p;\n\n size_t\n bytes_per_line,\n extent,\n length;\n\n ssize_t\n count,\n y;\n\n SUNInfo\n sun_info;\n\n unsigned char\n *sun_data,\n *sun_pixels;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickSignature);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Read SUN raster header.\n */\n (void) ResetMagickMemory(&sun_info,0,sizeof(sun_info));\n sun_info.magic=ReadBlobMSBLong(image);\n do\n {\n /*\n Verify SUN identifier.\n */\n if (sun_info.magic != 0x59a66a95)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n sun_info.width=ReadBlobMSBLong(image);\n sun_info.height=ReadBlobMSBLong(image);\n sun_info.depth=ReadBlobMSBLong(image);\n sun_info.length=ReadBlobMSBLong(image);\n sun_info.type=ReadBlobMSBLong(image);\n sun_info.maptype=ReadBlobMSBLong(image);\n sun_info.maplength=ReadBlobMSBLong(image);\n extent=sun_info.height*sun_info.width;\n if ((sun_info.height != 0) && (sun_info.width != extent/sun_info.height))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if ((sun_info.type != RT_STANDARD) && (sun_info.type != RT_ENCODED) &&\n (sun_info.type != RT_FORMAT_RGB))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if ((sun_info.maptype == RMT_NONE) && (sun_info.maplength != 0))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if ((sun_info.depth == 0) || (sun_info.depth > 32))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if ((sun_info.maptype != RMT_NONE) && (sun_info.maptype != RMT_EQUAL_RGB) &&\n (sun_info.maptype != RMT_RAW))\n ThrowReaderException(CoderError,\"ColormapTypeNotSupported\");\n image->columns=sun_info.width;\n image->rows=sun_info.height;\n image->depth=sun_info.depth <= 8 ? sun_info.depth :\n MAGICKCORE_QUANTUM_DEPTH;\n if (sun_info.depth < 24)\n {\n size_t\n one;\n\n image->storage_class=PseudoClass;\n image->colors=sun_info.maplength;\n one=1;\n if (sun_info.maptype == RMT_NONE)\n image->colors=one << sun_info.depth;\n if (sun_info.maptype == RMT_EQUAL_RGB)\n image->colors=sun_info.maplength/3;\n }\n switch (sun_info.maptype)\n {\n case RMT_NONE:\n {\n if (sun_info.depth < 24)\n {\n /*\n Create linear color ramp.\n */\n if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n break;\n }\n case RMT_EQUAL_RGB:\n {\n unsigned char\n *sun_colormap;\n\n /*\n Read SUN raster colormap.\n */\n if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n sun_colormap=(unsigned char *) AcquireQuantumMemory(image->colors,\n sizeof(*sun_colormap));\n if (sun_colormap == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n count=ReadBlob(image,image->colors,sun_colormap);\n if (count != (ssize_t) image->colors)\n ThrowReaderException(CorruptImageError,\"UnexpectedEndOfFile\");\n for (i=0; i < (ssize_t) image->colors; i++)\n image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(\n sun_colormap[i]);\n count=ReadBlob(image,image->colors,sun_colormap);\n if (count != (ssize_t) image->colors)\n ThrowReaderException(CorruptImageError,\"UnexpectedEndOfFile\");\n for (i=0; i < (ssize_t) image->colors; i++)\n image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(\n sun_colormap[i]);\n count=ReadBlob(image,image->colors,sun_colormap);\n if (count != (ssize_t) image->colors)\n ThrowReaderException(CorruptImageError,\"UnexpectedEndOfFile\");\n for (i=0; i < (ssize_t) image->colors; i++)\n image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(\n sun_colormap[i]);\n sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap);\n break;\n }\n case RMT_RAW:\n {\n unsigned char\n *sun_colormap;\n\n /*\n Read SUN raster colormap.\n */\n sun_colormap=(unsigned char *) AcquireQuantumMemory(sun_info.maplength,\n sizeof(*sun_colormap));\n if (sun_colormap == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n count=ReadBlob(image,sun_info.maplength,sun_colormap);\n if (count != (ssize_t) sun_info.maplength)\n ThrowReaderException(CorruptImageError,\"UnexpectedEndOfFile\");\n sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap);\n break;\n }\n default:\n ThrowReaderException(CoderError,\"ColormapTypeNotSupported\");\n }\n image->alpha_trait=sun_info.depth == 32 ? BlendPixelTrait :\n UndefinedPixelTrait;\n image->columns=sun_info.width;\n image->rows=sun_info.height;\n if (image_info->ping != MagickFalse)\n {\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n }\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n if ((sun_info.length*sizeof(*sun_data))/sizeof(*sun_data) !=\n sun_info.length || !sun_info.length)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n number_pixels=(MagickSizeType) image->columns*image->rows;\n if ((sun_info.type != RT_ENCODED) && (sun_info.depth >= 8) &&\n ((number_pixels*((sun_info.depth+7)/8)) > sun_info.length))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n sun_data=(unsigned char *) AcquireQuantumMemory((size_t) sun_info.length,\n sizeof(*sun_data));\n if (sun_data == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n count=(ssize_t) ReadBlob(image,sun_info.length,sun_data);\n if (count != (ssize_t) sun_info.length)\n ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n sun_pixels=sun_data;\n bytes_per_line=0;\n if (sun_info.type == RT_ENCODED)\n {\n size_t\n height;\n\n /*\n Read run-length encoded raster pixels.\n */\n height=sun_info.height;\n bytes_per_line=sun_info.width*sun_info.depth;\n if ((height == 0) || (sun_info.width == 0) || (sun_info.depth == 0) ||\n ((bytes_per_line/sun_info.depth) != sun_info.width))\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n bytes_per_line+=15;\n bytes_per_line<<=1;\n if ((bytes_per_line >> 1) != (sun_info.width*sun_info.depth+15))\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n bytes_per_line>>=4;\n sun_pixels=(unsigned char *) AcquireQuantumMemory(height,\n bytes_per_line*sizeof(*sun_pixels));\n if (sun_pixels == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) DecodeImage(sun_data,sun_info.length,sun_pixels,bytes_per_line*\n height);\n sun_data=(unsigned char *) RelinquishMagickMemory(sun_data);\n }\n /*\n Convert SUN raster image to pixel packets.\n */\n p=sun_pixels;\n if (sun_info.depth == 1)\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < ((ssize_t) image->columns-7); x+=8)\n {\n for (bit=7; bit >= 0; bit--)\n {\n SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01),\n q);\n q+=GetPixelChannels(image);\n }\n p++;\n }\n if ((image->columns % 8) != 0)\n {\n for (bit=7; bit >= (int) (8-(image->columns % 8)); bit--)\n {\n SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 :\n 0x01),q);\n q+=GetPixelChannels(image);\n }\n p++;\n }\n if ((((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2) != 0)\n p++;\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n else\n if (image->storage_class == PseudoClass)\n {\n if (bytes_per_line == 0)\n bytes_per_line=image->columns;\n length=image->rows*(image->columns+image->columns % 2);\n if (((sun_info.type == RT_ENCODED) &&\n (length > (bytes_per_line*image->rows))) ||\n ((sun_info.type != RT_ENCODED) && (length > sun_info.length)))\n ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelIndex(image,*p++,q);\n q+=GetPixelChannels(image);\n }\n if ((image->columns % 2) != 0)\n p++;\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n }\n else\n {\n size_t\n bytes_per_pixel;\n\n bytes_per_pixel=3;\n if (image->alpha_trait != UndefinedPixelTrait)\n bytes_per_pixel++;\n if (bytes_per_line == 0)\n bytes_per_line=bytes_per_pixel*image->columns;\n length=image->rows*(bytes_per_line+image->columns % 2);\n if (((sun_info.type == RT_ENCODED) &&\n (length > (bytes_per_line*image->rows))) ||\n ((sun_info.type != RT_ENCODED) && (length > sun_info.length)))\n ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (image->alpha_trait != UndefinedPixelTrait)\n SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);\n if (sun_info.type == RT_STANDARD)\n {\n SetPixelBlue(image,ScaleCharToQuantum(*p++),q);\n SetPixelGreen(image,ScaleCharToQuantum(*p++),q);\n SetPixelRed(image,ScaleCharToQuantum(*p++),q);\n }\n else\n {\n SetPixelRed(image,ScaleCharToQuantum(*p++),q);\n SetPixelGreen(image,ScaleCharToQuantum(*p++),q);\n SetPixelBlue(image,ScaleCharToQuantum(*p++),q);\n }\n if (image->colors != 0)\n {\n SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t)\n GetPixelRed(image,q)].red),q);\n SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t)\n GetPixelGreen(image,q)].green),q);\n SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t)\n GetPixelBlue(image,q)].blue),q);\n }\n q+=GetPixelChannels(image);\n }\n if (((bytes_per_pixel*image->columns) % 2) != 0)\n p++;\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n }\n if (image->storage_class == PseudoClass)\n (void) SyncImage(image,exception);\n sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels);\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n /*\n Proceed to next image.\n */\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n sun_info.magic=ReadBlobMSBLong(image);\n if (sun_info.magic == 0x59a66a95)\n {\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image,exception);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n GetBlobSize(image));\n if (status == MagickFalse)\n break;\n }\n } while (sun_info.magic == 0x59a66a95);\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-125'], 'message': 'http://www.imagemagick.org/discourse-server/viewtopic.php?f=3&t=26838'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static MagickBooleanType ReadPSDChannelPixels(Image *image,\n const size_t channels,const size_t row,const ssize_t type,\n const unsigned char *pixels,ExceptionInfo *exception)\n{\n Quantum\n pixel;\n\n register const unsigned char\n *p;\n\n register Quantum\n *q;\n\n register ssize_t\n x;\n\n size_t\n packet_size;\n\n unsigned short\n nibble;\n\n p=pixels;\n q=GetAuthenticPixels(image,0,row,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n return MagickFalse;\n packet_size=GetPSDPacketSize(image);\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (packet_size == 1)\n pixel=ScaleCharToQuantum(*p++);\n else\n {\n p=PushShortPixel(MSBEndian,p,&nibble);\n pixel=ScaleShortToQuantum(nibble);\n }\n switch (type)\n {\n case -1:\n {\n SetPixelAlpha(image,pixel,q);\n break;\n }\n case -2:\n case 0:\n {\n SetPixelRed(image,pixel,q);\n if (channels == 1 || type == -2)\n SetPixelGray(image,pixel,q);\n if (image->storage_class == PseudoClass)\n {\n if (packet_size == 1)\n SetPixelIndex(image,ScaleQuantumToChar(pixel),q);\n else\n SetPixelIndex(image,ScaleQuantumToShort(pixel),q);\n SetPixelViaPixelInfo(image,image->colormap+(ssize_t)\n ConstrainColormapIndex(image,GetPixelIndex(image,q),exception),q);\n if (image->depth == 1)\n {\n ssize_t\n bit,\n number_bits;\n \n number_bits=image->columns-x;\n if (number_bits > 8)\n number_bits=8;\n for (bit=0; bit < number_bits; bit++)\n {\n SetPixelIndex(image,(((unsigned char) pixel) &\n (0x01 << (7-bit))) != 0 ? 0 : 255,q);\n SetPixelViaPixelInfo(image,image->colormap+(ssize_t)\n GetPixelIndex(image,q),q);\n q+=GetPixelChannels(image);\n x++;\n }\n x--;\n continue;\n }\n }\n break;\n }\n case 1:\n {\n if (image->storage_class == PseudoClass)\n SetPixelAlpha(image,pixel,q);\n else\n SetPixelGreen(image,pixel,q);\n break;\n }\n case 2:\n {\n if (image->storage_class == PseudoClass)\n SetPixelAlpha(image,pixel,q);\n else\n SetPixelBlue(image,pixel,q);\n break;\n }\n case 3:\n {\n if (image->colorspace == CMYKColorspace)\n SetPixelBlack(image,pixel,q);\n else\n if (image->alpha_trait != UndefinedPixelTrait)\n SetPixelAlpha(image,pixel,q);\n break;\n }\n case 4:\n {\n if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) &&\n (channels > 3))\n break;\n if (image->alpha_trait != UndefinedPixelTrait)\n SetPixelAlpha(image,pixel,q);\n break;\n }\n default:\n break;\n }\n q+=GetPixelChannels(image);\n }\n return(SyncAuthenticPixels(image,exception));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Added missing call to ConstrainColormapIndex.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: MagickExport MemoryInfo *AcquireVirtualMemory(const size_t count,\n const size_t quantum)\n{\n MemoryInfo\n *memory_info;\n\n size_t\n length;\n\n length=count*quantum;\n if ((count == 0) || (quantum != (length/count)))\n {\n errno=ENOMEM;\n return((MemoryInfo *) NULL);\n }\n memory_info=(MemoryInfo *) MagickAssumeAligned(AcquireAlignedMemory(1,\n sizeof(*memory_info)));\n if (memory_info == (MemoryInfo *) NULL)\n ThrowFatalException(ResourceLimitFatalError,\"MemoryAllocationFailed\");\n (void) ResetMagickMemory(memory_info,0,sizeof(*memory_info));\n memory_info->length=length;\n memory_info->signature=MagickCoreSignature;\n if (AcquireMagickResource(MemoryResource,length) != MagickFalse)\n {\n memory_info->blob=AcquireAlignedMemory(1,length);\n if (memory_info->blob != NULL)\n {\n memory_info->type=AlignedVirtualMemory;\n return(memory_info);\n }\n }\n RelinquishMagickResource(MemoryResource,length);\n if (AcquireMagickResource(MapResource,length) != MagickFalse)\n {\n /*\n Heap memory failed, try anonymous memory mapping.\n */\n memory_info->blob=MapBlob(-1,IOMode,0,length);\n if (memory_info->blob != NULL)\n {\n memory_info->type=MapVirtualMemory;\n return(memory_info);\n }\n if (AcquireMagickResource(DiskResource,length) != MagickFalse)\n {\n int\n file;\n\n /*\n Anonymous memory mapping failed, try file-backed memory mapping.\n If the MapResource request failed, there is no point in trying\n file-backed memory mapping.\n */\n file=AcquireUniqueFileResource(memory_info->filename);\n if (file != -1)\n {\n if ((lseek(file,length-1,SEEK_SET) == (length-1)) &&\n (write(file,\"\",1) == 1))\n {\n memory_info->blob=MapBlob(file,IOMode,0,length);\n if (memory_info->blob != NULL)\n {\n (void) close(file);\n memory_info->type=MapVirtualMemory;\n return(memory_info);\n }\n }\n /*\n File-backed memory mapping failed, delete the temporary file.\n */\n (void) close(file);\n (void) RelinquishUniqueFileResource(memory_info->filename);\n *memory_info->filename = '\\0';\n }\n }\n RelinquishMagickResource(DiskResource,length);\n }\n RelinquishMagickResource(MapResource,length);\n if (memory_info->blob == NULL)\n {\n memory_info->blob=AcquireMagickMemory(length);\n if (memory_info->blob != NULL)\n memory_info->type=UnalignedVirtualMemory;\n }\n if (memory_info->blob == NULL)\n memory_info=RelinquishVirtualMemory(memory_info);\n return(memory_info);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/82\nhttps://github.com/ImageMagick/ImageMagick/issues/81\nhttps://github.com/ImageMagick/ImageMagick/issues/80\nhttps://github.com/ImageMagick/ImageMagick/issues/77'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image,\n ExceptionInfo *exception)\n{\n const char\n *property;\n\n const StringInfo\n *icc_profile;\n\n Image\n *base_image,\n *next_image;\n\n MagickBooleanType\n status;\n\n PSDInfo\n psd_info;\n\n register ssize_t\n i;\n\n size_t\n channel_size,\n channelLength,\n layer_count,\n layer_info_size,\n length,\n num_channels,\n packet_size,\n rounded_layer_info_size;\n\n StringInfo\n *bim_profile;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);\n if (status == MagickFalse)\n return(status);\n packet_size=(size_t) (image->depth > 8 ? 6 : 3);\n if (image->alpha_trait != UndefinedPixelTrait)\n packet_size+=image->depth > 8 ? 2 : 1;\n psd_info.version=1;\n if ((LocaleCompare(image_info->magick,\"PSB\") == 0) ||\n (image->columns > 30000) || (image->rows > 30000))\n psd_info.version=2;\n (void) WriteBlob(image,4,(const unsigned char *) \"8BPS\");\n (void) WriteBlobMSBShort(image,psd_info.version); /* version */\n for (i=1; i <= 6; i++)\n (void) WriteBlobByte(image, 0); /* 6 bytes of reserved */\n if (SetImageGray(image,exception) != MagickFalse)\n num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL);\n else\n if ((image_info->type != TrueColorType) && (image_info->type !=\n TrueColorAlphaType) && (image->storage_class == PseudoClass))\n num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL);\n else\n {\n if (image->storage_class == PseudoClass)\n (void) SetImageStorageClass(image,DirectClass,exception);\n if (image->colorspace != CMYKColorspace)\n num_channels=(image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL);\n else\n num_channels=(image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL);\n }\n (void) WriteBlobMSBShort(image,(unsigned short) num_channels);\n (void) WriteBlobMSBLong(image,(unsigned int) image->rows);\n (void) WriteBlobMSBLong(image,(unsigned int) image->columns);\n if (IsImageGray(image) != MagickFalse)\n {\n MagickBooleanType\n monochrome;\n\n /*\n Write depth & mode.\n */\n monochrome=IsImageMonochrome(image) && (image->depth == 1) ?\n MagickTrue : MagickFalse;\n (void) WriteBlobMSBShort(image,(unsigned short)\n (monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8));\n (void) WriteBlobMSBShort(image,(unsigned short)\n (monochrome != MagickFalse ? BitmapMode : GrayscaleMode));\n }\n else\n {\n (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class ==\n PseudoClass ? 8 : image->depth > 8 ? 16 : 8));\n\n if (((image_info->colorspace != UndefinedColorspace) ||\n (image->colorspace != CMYKColorspace)) &&\n (image_info->colorspace != CMYKColorspace))\n {\n (void) TransformImageColorspace(image,sRGBColorspace,exception);\n (void) WriteBlobMSBShort(image,(unsigned short)\n (image->storage_class == PseudoClass ? IndexedMode : RGBMode));\n }\n else\n {\n if (image->colorspace != CMYKColorspace)\n (void) TransformImageColorspace(image,CMYKColorspace,exception);\n (void) WriteBlobMSBShort(image,CMYKMode);\n }\n }\n if ((IsImageGray(image) != MagickFalse) ||\n (image->storage_class == DirectClass) || (image->colors > 256))\n (void) WriteBlobMSBLong(image,0);\n else\n {\n /*\n Write PSD raster colormap.\n */\n (void) WriteBlobMSBLong(image,768);\n for (i=0; i < (ssize_t) image->colors; i++)\n (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].red));\n for ( ; i < 256; i++)\n (void) WriteBlobByte(image,0);\n for (i=0; i < (ssize_t) image->colors; i++)\n (void) WriteBlobByte(image,ScaleQuantumToChar(\n image->colormap[i].green));\n for ( ; i < 256; i++)\n (void) WriteBlobByte(image,0);\n for (i=0; i < (ssize_t) image->colors; i++)\n (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].blue));\n for ( ; i < 256; i++)\n (void) WriteBlobByte(image,0);\n }\n /*\n Image resource block.\n */\n length=28; /* 0x03EB */\n bim_profile=(StringInfo *) GetImageProfile(image,\"8bim\");\n icc_profile=GetImageProfile(image,\"icc\");\n if (bim_profile != (StringInfo *) NULL)\n {\n bim_profile=CloneStringInfo(bim_profile);\n if (icc_profile != (StringInfo *) NULL)\n RemoveICCProfileFromResourceBlock(bim_profile);\n RemoveResolutionFromResourceBlock(bim_profile);\n length+=PSDQuantum(GetStringInfoLength(bim_profile));\n }\n if (icc_profile != (const StringInfo *) NULL)\n length+=PSDQuantum(GetStringInfoLength(icc_profile))+12;\n (void) WriteBlobMSBLong(image,(unsigned int) length);\n WriteResolutionResourceBlock(image);\n if (bim_profile != (StringInfo *) NULL)\n {\n (void) WriteBlob(image,GetStringInfoLength(bim_profile),\n GetStringInfoDatum(bim_profile));\n bim_profile=DestroyStringInfo(bim_profile);\n }\n if (icc_profile != (StringInfo *) NULL)\n {\n (void) WriteBlob(image,4,(const unsigned char *) \"8BIM\");\n (void) WriteBlobMSBShort(image,0x0000040F);\n (void) WriteBlobMSBShort(image,0);\n (void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength(\n icc_profile));\n (void) WriteBlob(image,GetStringInfoLength(icc_profile),\n GetStringInfoDatum(icc_profile));\n if ((MagickOffsetType) GetStringInfoLength(icc_profile) !=\n PSDQuantum(GetStringInfoLength(icc_profile)))\n (void) WriteBlobByte(image,0);\n }\n layer_count=0;\n layer_info_size=2;\n base_image=GetNextImageInList(image);\n if ((image->alpha_trait != UndefinedPixelTrait) && (base_image == (Image *) NULL))\n base_image=image;\n next_image=base_image;\n while ( next_image != NULL )\n {\n packet_size=next_image->depth > 8 ? 2UL : 1UL;\n if (IsImageGray(next_image) != MagickFalse)\n num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL;\n else\n if (next_image->storage_class == PseudoClass)\n num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL;\n else\n if (next_image->colorspace != CMYKColorspace)\n num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL;\n else\n num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL;\n channelLength=(size_t) (next_image->columns*next_image->rows*packet_size+2);\n layer_info_size+=(size_t) (4*4+2+num_channels*6+(psd_info.version == 1 ? 8 :\n 16)+4*1+4+num_channels*channelLength);\n property=(const char *) GetImageProperty(next_image,\"label\",exception);\n if (property == (const char *) NULL)\n layer_info_size+=16;\n else\n {\n size_t\n layer_length;\n\n layer_length=strlen(property);\n layer_info_size+=8+layer_length+(4-(layer_length % 4));\n }\n layer_count++;\n next_image=GetNextImageInList(next_image);\n }\n if (layer_count == 0)\n (void) SetPSDSize(&psd_info,image,0);\n else\n {\n CompressionType\n compression;\n\n (void) SetPSDSize(&psd_info,image,layer_info_size+\n (psd_info.version == 1 ? 8 : 16));\n if ((layer_info_size/2) != ((layer_info_size+1)/2))\n rounded_layer_info_size=layer_info_size+1;\n else\n rounded_layer_info_size=layer_info_size;\n (void) SetPSDSize(&psd_info,image,rounded_layer_info_size);\n if (image->alpha_trait != UndefinedPixelTrait)\n (void) WriteBlobMSBShort(image,-(unsigned short) layer_count);\n else\n (void) WriteBlobMSBShort(image,(unsigned short) layer_count);\n layer_count=1;\n compression=base_image->compression;\n for (next_image=base_image; next_image != NULL; )\n {\n next_image->compression=NoCompression;\n (void) WriteBlobMSBLong(image,(unsigned int) next_image->page.y);\n (void) WriteBlobMSBLong(image,(unsigned int) next_image->page.x);\n (void) WriteBlobMSBLong(image,(unsigned int) (next_image->page.y+\n next_image->rows));\n (void) WriteBlobMSBLong(image,(unsigned int) (next_image->page.x+\n next_image->columns));\n packet_size=next_image->depth > 8 ? 2UL : 1UL;\n channel_size=(unsigned int) ((packet_size*next_image->rows*\n next_image->columns)+2);\n if ((IsImageGray(next_image) != MagickFalse) ||\n (next_image->storage_class == PseudoClass))\n {\n (void) WriteBlobMSBShort(image,(unsigned short)\n (next_image->alpha_trait != UndefinedPixelTrait ? 2 : 1));\n (void) WriteBlobMSBShort(image,0);\n (void) SetPSDSize(&psd_info,image,channel_size);\n if (next_image->alpha_trait != UndefinedPixelTrait)\n {\n (void) WriteBlobMSBShort(image,(unsigned short) -1);\n (void) SetPSDSize(&psd_info,image,channel_size);\n }\n }\n else\n if (next_image->colorspace != CMYKColorspace)\n {\n (void) WriteBlobMSBShort(image,(unsigned short)\n (next_image->alpha_trait != UndefinedPixelTrait ? 4 : 3));\n (void) WriteBlobMSBShort(image,0);\n (void) SetPSDSize(&psd_info,image,channel_size);\n (void) WriteBlobMSBShort(image,1);\n (void) SetPSDSize(&psd_info,image,channel_size);\n (void) WriteBlobMSBShort(image,2);\n (void) SetPSDSize(&psd_info,image,channel_size);\n if (next_image->alpha_trait != UndefinedPixelTrait)\n {\n (void) WriteBlobMSBShort(image,(unsigned short) -1);\n (void) SetPSDSize(&psd_info,image,channel_size);\n }\n }\n else\n {\n (void) WriteBlobMSBShort(image,(unsigned short)\n (next_image->alpha_trait ? 5 : 4));\n (void) WriteBlobMSBShort(image,0);\n (void) SetPSDSize(&psd_info,image,channel_size);\n (void) WriteBlobMSBShort(image,1);\n (void) SetPSDSize(&psd_info,image,channel_size);\n (void) WriteBlobMSBShort(image,2);\n (void) SetPSDSize(&psd_info,image,channel_size);\n (void) WriteBlobMSBShort(image,3);\n (void) SetPSDSize(&psd_info,image,channel_size);\n if (next_image->alpha_trait)\n {\n (void) WriteBlobMSBShort(image,(unsigned short) -1);\n (void) SetPSDSize(&psd_info,image,channel_size);\n }\n }\n (void) WriteBlob(image,4,(const unsigned char *) \"8BIM\");\n (void) WriteBlob(image,4,(const unsigned char *)\n CompositeOperatorToPSDBlendMode(next_image->compose));\n (void) WriteBlobByte(image,255); /* layer opacity */\n (void) WriteBlobByte(image,0);\n (void) WriteBlobByte(image,next_image->compose==NoCompositeOp ?\n 1 << 0x02 : 1); /* layer properties - visible, etc. */\n (void) WriteBlobByte(image,0);\n property=(const char *) GetImageProperty(next_image,\"label\",exception);\n if (property == (const char *) NULL)\n {\n char\n layer_name[MagickPathExtent];\n\n (void) WriteBlobMSBLong(image,16);\n (void) WriteBlobMSBLong(image,0);\n (void) WriteBlobMSBLong(image,0);\n (void) FormatLocaleString(layer_name,MagickPathExtent,\"L%04ld\",(long)\n layer_count++);\n WritePascalString(image,layer_name,4);\n }\n else\n {\n size_t\n label_length;\n\n label_length=strlen(property);\n (void) WriteBlobMSBLong(image,(unsigned int) (label_length+(4-\n (label_length % 4))+8));\n (void) WriteBlobMSBLong(image,0);\n (void) WriteBlobMSBLong(image,0);\n WritePascalString(image,property,4);\n }\n next_image=GetNextImageInList(next_image);\n }\n /*\n Now the image data!\n */\n next_image=base_image;\n while (next_image != NULL)\n {\n status=WriteImageChannels(&psd_info,image_info,image,next_image,\n MagickTrue,exception);\n next_image=GetNextImageInList(next_image);\n }\n (void) WriteBlobMSBLong(image,0); /* user mask data */\n base_image->compression=compression;\n }\n /*\n Write composite image.\n */\n if (status != MagickFalse)\n status=WriteImageChannels(&psd_info,image_info,image,image,MagickFalse,\n exception);\n (void) CloseBlob(image);\n return(status);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Added check for out of bounds read (https://github.com/ImageMagick/ImageMagick/issues/108).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int mi_repair_parallel(MI_CHECK *param, register MI_INFO *info,\n\t\t\tconst char * name, int rep_quick)\n{\n int got_error;\n uint i,key, total_key_length, istep;\n ulong rec_length;\n ha_rows start_records;\n my_off_t new_header_length,del;\n File new_file;\n MI_SORT_PARAM *sort_param=0;\n MYISAM_SHARE *share=info->s;\n ulong *rec_per_key_part;\n HA_KEYSEG *keyseg;\n char llbuff[22];\n IO_CACHE new_data_cache; /* For non-quick repair. */\n IO_CACHE_SHARE io_share;\n SORT_INFO sort_info;\n ulonglong UNINIT_VAR(key_map);\n pthread_attr_t thr_attr;\n ulong max_pack_reclength;\n int error;\n DBUG_ENTER(\"mi_repair_parallel\");\n\n start_records=info->state->records;\n got_error=1;\n new_file= -1;\n new_header_length=(param->testflag & T_UNPACK) ? 0 :\n share->pack.header_length;\n if (!(param->testflag & T_SILENT))\n {\n printf(\"- parallel recovering (with sort) MyISAM-table '%s'\\n\",name);\n printf(\"Data records: %s\\n\", llstr(start_records,llbuff));\n }\n param->testflag|=T_REP; /* for easy checking */\n\n if (info->s->options & (HA_OPTION_CHECKSUM | HA_OPTION_COMPRESS_RECORD))\n param->testflag|=T_CALC_CHECKSUM;\n\n /*\n Quick repair (not touching data file, rebuilding indexes):\n {\n Read cache is (MI_CHECK *param)->read_cache using info->dfile.\n }\n\n Non-quick repair (rebuilding data file and indexes):\n {\n Master thread:\n\n Read cache is (MI_CHECK *param)->read_cache using info->dfile.\n Write cache is (MI_INFO *info)->rec_cache using new_file.\n\n Slave threads:\n\n Read cache is new_data_cache synced to master rec_cache.\n\n The final assignment of the filedescriptor for rec_cache is done\n after the cache creation.\n\n Don't check file size on new_data_cache, as the resulting file size\n is not known yet.\n\n As rec_cache and new_data_cache are synced, write_buffer_length is\n used for the read cache 'new_data_cache'. Both start at the same\n position 'new_header_length'.\n }\n */\n DBUG_PRINT(\"info\", (\"is quick repair: %d\", rep_quick));\n bzero((char*)&sort_info,sizeof(sort_info));\n /* Initialize pthread structures before goto err. */\n mysql_mutex_init(mi_key_mutex_MI_SORT_INFO_mutex,\n &sort_info.mutex, MY_MUTEX_INIT_FAST);\n mysql_cond_init(mi_key_cond_MI_SORT_INFO_cond, &sort_info.cond, 0);\n mysql_mutex_init(mi_key_mutex_MI_CHECK_print_msg,\n ¶m->print_msg_mutex, MY_MUTEX_INIT_FAST);\n param->need_print_msg_lock= 1;\n\n if (!(sort_info.key_block=\n\talloc_key_blocks(param, (uint) param->sort_key_blocks,\n\t\t\t share->base.max_key_block_length)) ||\n init_io_cache(¶m->read_cache, info->dfile,\n (uint) param->read_buffer_length,\n READ_CACHE, share->pack.header_length, 1, MYF(MY_WME)) ||\n (!rep_quick &&\n (init_io_cache(&info->rec_cache, info->dfile,\n (uint) param->write_buffer_length,\n WRITE_CACHE, new_header_length, 1,\n MYF(MY_WME | MY_WAIT_IF_FULL) & param->myf_rw) ||\n init_io_cache(&new_data_cache, -1,\n (uint) param->write_buffer_length,\n READ_CACHE, new_header_length, 1,\n MYF(MY_WME | MY_DONT_CHECK_FILESIZE)))))\n goto err;\n sort_info.key_block_end=sort_info.key_block+param->sort_key_blocks;\n info->opt_flag|=WRITE_CACHE_USED;\n info->rec_cache.file=info->dfile; /* for sort_delete_record */\n\n if (!rep_quick)\n {\n /* Get real path for data file */\n if ((new_file= mysql_file_create(mi_key_file_datatmp,\n fn_format(param->temp_filename,\n share->data_file_name, \"\",\n DATA_TMP_EXT, 2+4),\n 0, param->tmpfile_createflag,\n MYF(0))) < 0)\n {\n mi_check_print_error(param,\"Can't create new tempfile: '%s'\",\n\t\t\t param->temp_filename);\n goto err;\n }\n if (new_header_length &&\n filecopy(param, new_file,info->dfile,0L,new_header_length,\n\t\t \"datafile-header\"))\n goto err;\n if (param->testflag & T_UNPACK)\n {\n share->options&= ~HA_OPTION_COMPRESS_RECORD;\n mi_int2store(share->state.header.options,share->options);\n }\n share->state.dellink= HA_OFFSET_ERROR;\n info->rec_cache.file=new_file;\n }\n\n info->update= (short) (HA_STATE_CHANGED | HA_STATE_ROW_CHANGED);\n\n /* Optionally drop indexes and optionally modify the key_map. */\n mi_drop_all_indexes(param, info, FALSE);\n key_map= share->state.key_map;\n if (param->testflag & T_CREATE_MISSING_KEYS)\n {\n /* Invert the copied key_map to recreate all disabled indexes. */\n key_map= ~key_map;\n }\n\n sort_info.info=info;\n sort_info.param = param;\n\n set_data_file_type(&sort_info, share);\n sort_info.dupp=0;\n sort_info.buff=0;\n param->read_cache.end_of_file=sort_info.filelength=\n mysql_file_seek(param->read_cache.file, 0L, MY_SEEK_END, MYF(0));\n\n if (share->data_file_type == DYNAMIC_RECORD)\n rec_length=max(share->base.min_pack_length+1,share->base.min_block_length);\n else if (share->data_file_type == COMPRESSED_RECORD)\n rec_length=share->base.min_block_length;\n else\n rec_length=share->base.pack_reclength;\n /*\n +1 below is required hack for parallel repair mode.\n The info->state->records value, that is compared later\n to sort_info.max_records and cannot exceed it, is\n increased in sort_key_write. In mi_repair_by_sort, sort_key_write\n is called after sort_key_read, where the comparison is performed,\n but in parallel mode master thread can call sort_key_write\n before some other repair thread calls sort_key_read.\n Furthermore I'm not even sure +1 would be enough.\n May be sort_info.max_records shold be always set to max value in\n parallel mode.\n */\n sort_info.max_records=\n ((param->testflag & T_CREATE_MISSING_KEYS) ? info->state->records + 1:\n (ha_rows) (sort_info.filelength/rec_length+1));\n\n del=info->state->del;\n param->glob_crc=0;\n /* for compressed tables */\n max_pack_reclength= share->base.pack_reclength;\n if (share->options & HA_OPTION_COMPRESS_RECORD)\n set_if_bigger(max_pack_reclength, share->max_pack_length);\n if (!(sort_param=(MI_SORT_PARAM *)\n my_malloc((uint) share->base.keys *\n\t\t (sizeof(MI_SORT_PARAM) + max_pack_reclength),\n\t\t MYF(MY_ZEROFILL))))\n {\n mi_check_print_error(param,\"Not enough memory for key!\");\n goto err;\n }\n total_key_length=0;\n rec_per_key_part= param->rec_per_key_part;\n info->state->records=info->state->del=share->state.split=0;\n info->state->empty=0;\n\n for (i=key=0, istep=1 ; key < share->base.keys ;\n rec_per_key_part+=sort_param[i].keyinfo->keysegs, i+=istep, key++)\n {\n sort_param[i].key=key;\n sort_param[i].keyinfo=share->keyinfo+key;\n sort_param[i].seg=sort_param[i].keyinfo->seg;\n /*\n Skip this index if it is marked disabled in the copied\n (and possibly inverted) key_map.\n */\n if (! mi_is_key_active(key_map, key))\n {\n /* Remember old statistics for key */\n memcpy((char*) rec_per_key_part,\n\t (char*) (share->state.rec_per_key_part+\n\t\t (uint) (rec_per_key_part - param->rec_per_key_part)),\n\t sort_param[i].keyinfo->keysegs*sizeof(*rec_per_key_part));\n istep=0;\n continue;\n }\n istep=1;\n if ((!(param->testflag & T_SILENT)))\n printf (\"- Fixing index %d\\n\",key+1);\n if (sort_param[i].keyinfo->flag & HA_FULLTEXT)\n {\n sort_param[i].key_read=sort_ft_key_read;\n sort_param[i].key_write=sort_ft_key_write;\n }\n else\n {\n sort_param[i].key_read=sort_key_read;\n sort_param[i].key_write=sort_key_write;\n }\n sort_param[i].key_cmp=sort_key_cmp;\n sort_param[i].lock_in_memory=lock_memory;\n sort_param[i].tmpdir=param->tmpdir;\n sort_param[i].sort_info=&sort_info;\n sort_param[i].master=0;\n sort_param[i].fix_datafile=0;\n sort_param[i].calc_checksum= 0;\n\n sort_param[i].filepos=new_header_length;\n sort_param[i].max_pos=sort_param[i].pos=share->pack.header_length;\n\n sort_param[i].record= (((uchar *)(sort_param+share->base.keys))+\n\t\t\t (max_pack_reclength * i));\n if (!mi_alloc_rec_buff(info, -1, &sort_param[i].rec_buff))\n {\n mi_check_print_error(param,\"Not enough memory!\");\n goto err;\n }\n\n sort_param[i].key_length=share->rec_reflength;\n for (keyseg=sort_param[i].seg; keyseg->type != HA_KEYTYPE_END;\n\t keyseg++)\n {\n sort_param[i].key_length+=keyseg->length;\n if (keyseg->flag & HA_SPACE_PACK)\n sort_param[i].key_length+=get_pack_length(keyseg->length);\n if (keyseg->flag & (HA_BLOB_PART | HA_VAR_LENGTH_PART))\n sort_param[i].key_length+=2 + test(keyseg->length >= 127);\n if (keyseg->flag & HA_NULL_PART)\n sort_param[i].key_length++;\n }\n total_key_length+=sort_param[i].key_length;\n\n if (sort_param[i].keyinfo->flag & HA_FULLTEXT)\n {\n uint ft_max_word_len_for_sort=FT_MAX_WORD_LEN_FOR_SORT*\n sort_param[i].keyinfo->seg->charset->mbmaxlen;\n sort_param[i].key_length+=ft_max_word_len_for_sort-HA_FT_MAXBYTELEN;\n init_alloc_root(&sort_param[i].wordroot, FTPARSER_MEMROOT_ALLOC_SIZE, 0);\n }\n }\n sort_info.total_keys=i;\n sort_param[0].master= 1;\n sort_param[0].fix_datafile= (my_bool)(! rep_quick);\n sort_param[0].calc_checksum= test(param->testflag & T_CALC_CHECKSUM);\n\n if (!ftparser_alloc_param(info))\n goto err;\n\n sort_info.got_error=0;\n mysql_mutex_lock(&sort_info.mutex);\n\n /*\n Initialize the I/O cache share for use with the read caches and, in\n case of non-quick repair, the write cache. When all threads join on\n the cache lock, the writer copies the write cache contents to the\n read caches.\n */\n if (i > 1)\n {\n if (rep_quick)\n init_io_cache_share(¶m->read_cache, &io_share, NULL, i);\n else\n init_io_cache_share(&new_data_cache, &io_share, &info->rec_cache, i);\n }\n else\n io_share.total_threads= 0; /* share not used */\n\n (void) pthread_attr_init(&thr_attr);\n (void) pthread_attr_setdetachstate(&thr_attr,PTHREAD_CREATE_DETACHED);\n\n for (i=0 ; i < sort_info.total_keys ; i++)\n {\n /*\n Copy the properly initialized IO_CACHE structure so that every\n thread has its own copy. In quick mode param->read_cache is shared\n for use by all threads. In non-quick mode all threads but the\n first copy the shared new_data_cache, which is synchronized to the\n write cache of the first thread. The first thread copies\n param->read_cache, which is not shared.\n */\n sort_param[i].read_cache= ((rep_quick || !i) ? param->read_cache :\n new_data_cache);\n DBUG_PRINT(\"io_cache_share\", (\"thread: %u read_cache: 0x%lx\",\n i, (long) &sort_param[i].read_cache));\n\n /*\n two approaches: the same amount of memory for each thread\n or the memory for the same number of keys for each thread...\n In the second one all the threads will fill their sort_buffers\n (and call write_keys) at the same time, putting more stress on i/o.\n */\n sort_param[i].sortbuff_size=\n#ifndef USING_SECOND_APPROACH\n param->sort_buffer_length/sort_info.total_keys;\n#else\n param->sort_buffer_length*sort_param[i].key_length/total_key_length;\n#endif\n if ((error= mysql_thread_create(mi_key_thread_find_all_keys,\n &sort_param[i].thr, &thr_attr,\n thr_find_all_keys,\n (void *) (sort_param+i))))\n {\n mi_check_print_error(param,\"Cannot start a repair thread (errno= %d)\",\n error);\n /* Cleanup: Detach from the share. Avoid others to be blocked. */\n if (io_share.total_threads)\n remove_io_thread(&sort_param[i].read_cache);\n DBUG_PRINT(\"error\", (\"Cannot start a repair thread\"));\n sort_info.got_error=1;\n }\n else\n sort_info.threads_running++;\n }\n (void) pthread_attr_destroy(&thr_attr);\n\n /* waiting for all threads to finish */\n while (sort_info.threads_running)\n mysql_cond_wait(&sort_info.cond, &sort_info.mutex);\n mysql_mutex_unlock(&sort_info.mutex);\n\n if ((got_error= thr_write_keys(sort_param)))\n {\n param->retry_repair=1;\n goto err;\n }\n got_error=1;\t\t\t\t/* Assume the following may go wrong */\n\n if (sort_param[0].fix_datafile)\n {\n /*\n Append some nuls to the end of a memory mapped file. Destroy the\n write cache. The master thread did already detach from the share\n by remove_io_thread() in sort.c:thr_find_all_keys().\n */\n if (write_data_suffix(&sort_info,1) || end_io_cache(&info->rec_cache))\n goto err;\n if (param->testflag & T_SAFE_REPAIR)\n {\n /* Don't repair if we loosed more than one row */\n if (info->state->records+1 < start_records)\n {\n info->state->records=start_records;\n goto err;\n }\n }\n share->state.state.data_file_length= info->state->data_file_length=\n sort_param->filepos;\n /* Only whole records */\n share->state.version=(ulong) time((time_t*) 0);\n\n /*\n Exchange the data file descriptor of the table, so that we use the\n new file from now on.\n */\n mysql_file_close(info->dfile, MYF(0));\n info->dfile=new_file;\n\n share->data_file_type=sort_info.new_data_file_type;\n share->pack.header_length=(ulong) new_header_length;\n }\n else\n info->state->data_file_length=sort_param->max_pos;\n\n if (rep_quick && del+sort_info.dupp != info->state->del)\n {\n mi_check_print_error(param,\"Couldn't fix table with quick recovery: Found wrong number of deleted records\");\n mi_check_print_error(param,\"Run recovery again without -q\");\n param->retry_repair=1;\n param->testflag|=T_RETRY_WITHOUT_QUICK;\n goto err;\n }\n\n if (rep_quick & T_FORCE_UNIQUENESS)\n {\n my_off_t skr=info->state->data_file_length+\n (share->options & HA_OPTION_COMPRESS_RECORD ?\n MEMMAP_EXTRA_MARGIN : 0);\n#ifdef USE_RELOC\n if (share->data_file_type == STATIC_RECORD &&\n\tskr < share->base.reloc*share->base.min_pack_length)\n skr=share->base.reloc*share->base.min_pack_length;\n#endif\n if (skr != sort_info.filelength)\n if (mysql_file_chsize(info->dfile, skr, 0, MYF(0)))\n\tmi_check_print_warning(param,\n\t\t\t \"Can't change size of datafile, error: %d\",\n\t\t\t my_errno);\n }\n if (param->testflag & T_CALC_CHECKSUM)\n info->state->checksum=param->glob_crc;\n\n if (mysql_file_chsize(share->kfile, info->state->key_file_length, 0, MYF(0)))\n mi_check_print_warning(param,\n\t\t\t \"Can't change size of indexfile, error: %d\", my_errno);\n\n if (!(param->testflag & T_SILENT))\n {\n if (start_records != info->state->records)\n printf(\"Data records: %s\\n\", llstr(info->state->records,llbuff));\n if (sort_info.dupp)\n mi_check_print_warning(param,\n\t\t\t \"%s records have been removed\",\n\t\t\t llstr(sort_info.dupp,llbuff));\n }\n got_error=0;\n\n if (&share->state.state != info->state)\n memcpy(&share->state.state, info->state, sizeof(*info->state));\n\nerr:\n got_error|= flush_blocks(param, share->key_cache, share->kfile);\n /*\n Destroy the write cache. The master thread did already detach from\n the share by remove_io_thread() or it was not yet started (if the\n error happend before creating the thread).\n */\n (void) end_io_cache(&info->rec_cache);\n /*\n Destroy the new data cache in case of non-quick repair. All slave\n threads did either detach from the share by remove_io_thread()\n already or they were not yet started (if the error happend before\n creating the threads).\n */\n if (!rep_quick)\n (void) end_io_cache(&new_data_cache);\n if (!got_error)\n {\n /* Replace the actual file with the temporary file */\n if (new_file >= 0)\n {\n mysql_file_close(new_file, MYF(0));\n info->dfile=new_file= -1;\n if (change_to_newfile(share->data_file_name, MI_NAME_DEXT, DATA_TMP_EXT,\n\t\t\t (param->testflag & T_BACKUP_DATA ?\n\t\t\t MYF(MY_REDEL_MAKE_BACKUP): MYF(0))) ||\n\t mi_open_datafile(info,share,name,-1))\n\tgot_error=1;\n }\n }\n if (got_error)\n {\n if (! param->error_printed)\n mi_check_print_error(param,\"%d when fixing table\",my_errno);\n if (new_file >= 0)\n {\n (void) mysql_file_close(new_file, MYF(0));\n (void) mysql_file_delete(mi_key_file_datatmp,\n param->temp_filename, MYF(MY_WME));\n if (info->dfile == new_file) /* Retry with key cache */\n if (unlikely(mi_open_datafile(info, share, name, -1)))\n param->retry_repair= 0; /* Safety */\n }\n mi_mark_crashed_on_repair(info);\n }\n else if (key_map == share->state.key_map)\n share->state.changed&= ~STATE_NOT_OPTIMIZED_KEYS;\n share->state.changed|=STATE_NOT_SORTED_PAGES;\n\n mysql_cond_destroy(&sort_info.cond);\n mysql_mutex_destroy(&sort_info.mutex);\n mysql_mutex_destroy(¶m->print_msg_mutex);\n param->need_print_msg_lock= 0;\n\n my_free(sort_info.ft_buf);\n my_free(sort_info.key_block);\n my_free(sort_param);\n my_free(sort_info.buff);\n (void) end_io_cache(¶m->read_cache);\n info->opt_flag&= ~(READ_CACHE_USED | WRITE_CACHE_USED);\n if (!got_error && (param->testflag & T_UNPACK))\n {\n share->state.header.options[0]&= (uchar) ~HA_OPTION_COMPRESS_RECORD;\n share->pack.header_length=0;\n }\n DBUG_RETURN(got_error);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'Bug#24388746: PRIVILEGE ESCALATION AND RACE CONDITION USING CREATE TABLE\n\nDuring REPAIR TABLE of a MyISAM table, a temporary data file (.TMD)\nis created. When repair finishes, this file is renamed to the original\n.MYD file. The problem was that during this rename, we copied the\nstats from the old file to the new file with chmod/chown. If a user\nmanaged to replace the temporary file before chmod/chown was executed,\nit was possible to get an arbitrary file with the privileges of the\nmysql user.\n\nThis patch fixes the problem by not copying stats from the old\nfile to the new file. This is not needed as the new file was\ncreated with the correct stats. This fix only changes server\nbehavior - external utilities such as myisamchk still does\nchmod/chown.\n\nNo test case provided since the problem involves synchronization\nwith file system operations.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int manager_dispatch_notify_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {\n\n _cleanup_fdset_free_ FDSet *fds = NULL;\n Manager *m = userdata;\n char buf[NOTIFY_BUFFER_MAX+1];\n struct iovec iovec = {\n .iov_base = buf,\n .iov_len = sizeof(buf)-1,\n };\n union {\n struct cmsghdr cmsghdr;\n uint8_t buf[CMSG_SPACE(sizeof(struct ucred)) +\n CMSG_SPACE(sizeof(int) * NOTIFY_FD_MAX)];\n } control = {};\n struct msghdr msghdr = {\n .msg_iov = &iovec,\n .msg_iovlen = 1,\n .msg_control = &control,\n .msg_controllen = sizeof(control),\n };\n\n struct cmsghdr *cmsg;\n struct ucred *ucred = NULL;\n bool found = false;\n Unit *u1, *u2, *u3;\n int r, *fd_array = NULL;\n unsigned n_fds = 0;\n ssize_t n;\n\n assert(m);\n assert(m->notify_fd == fd);\n\n if (revents != EPOLLIN) {\n log_warning(\"Got unexpected poll event for notify fd.\");\n return 0;\n }\n\n n = recvmsg(m->notify_fd, &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);\n if (n < 0) {\n if (!IN_SET(errno, EAGAIN, EINTR))\n log_error(\"Failed to receive notification message: %m\");\n\n /* It's not an option to return an error here since it\n * would disable the notification handler entirely. Services\n * wouldn't be able to send the WATCHDOG message for\n * example... */\n return 0;\n }\n if (n == 0) {\n log_debug(\"Got zero-length notification message. Ignoring.\");\n return 0;\n }\n\n CMSG_FOREACH(cmsg, &msghdr) {\n if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {\n\n fd_array = (int*) CMSG_DATA(cmsg);\n n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);\n\n } else if (cmsg->cmsg_level == SOL_SOCKET &&\n cmsg->cmsg_type == SCM_CREDENTIALS &&\n cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred))) {\n\n ucred = (struct ucred*) CMSG_DATA(cmsg);\n }\n }\n\n if (n_fds > 0) {\n assert(fd_array);\n\n r = fdset_new_array(&fds, fd_array, n_fds);\n if (r < 0) {\n close_many(fd_array, n_fds);\n log_oom();\n return 0;\n }\n }\n\n if (!ucred || ucred->pid <= 0) {\n log_warning(\"Received notify message without valid credentials. Ignoring.\");\n return 0;\n }\n\n if ((size_t) n >= sizeof(buf)) {\n log_warning(\"Received notify message exceeded maximum size. Ignoring.\");\n return 0;\n }\n\n buf[n] = 0;\n\n /* Notify every unit that might be interested, but try\n * to avoid notifying the same one multiple times. */\n u1 = manager_get_unit_by_pid_cgroup(m, ucred->pid);\n if (u1) {\n manager_invoke_notify_message(m, u1, ucred->pid, buf, n, fds);\n found = true;\n }\n\n u2 = hashmap_get(m->watch_pids1, PID_TO_PTR(ucred->pid));\n if (u2 && u2 != u1) {\n manager_invoke_notify_message(m, u2, ucred->pid, buf, n, fds);\n found = true;\n }\n\n u3 = hashmap_get(m->watch_pids2, PID_TO_PTR(ucred->pid));\n if (u3 && u3 != u2 && u3 != u1) {\n manager_invoke_notify_message(m, u3, ucred->pid, buf, n, fds);\n found = true;\n }\n\n if (!found)\n log_warning(\"Cannot find unit for notify message of PID \"PID_FMT\".\", ucred->pid);\n\n if (fdset_size(fds) > 0)\n log_warning(\"Got auxiliary fds with notification message, closing all.\");\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'pid1: process zero-length notification messages again\n\nThis undoes 531ac2b234. I acked that patch without looking at the code\ncarefully enough. There are two problems:\n- we want to process the fds anyway\n- in principle empty notification messages are valid, and we should\n process them as usual, including logging using log_unit_debug().'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: Init_ossl_cipher(void)\n{\n#if 0\n mOSSL = rb_define_module(\"OpenSSL\");\n eOSSLError = rb_define_class_under(mOSSL, \"OpenSSLError\", rb_eStandardError);\n#endif\n\n /* Document-class: OpenSSL::Cipher\n *\n * Provides symmetric algorithms for encryption and decryption. The\n * algorithms that are available depend on the particular version\n * of OpenSSL that is installed.\n *\n * === Listing all supported algorithms\n *\n * A list of supported algorithms can be obtained by\n *\n * puts OpenSSL::Cipher.ciphers\n *\n * === Instantiating a Cipher\n *\n * There are several ways to create a Cipher instance. Generally, a\n * Cipher algorithm is categorized by its name, the key length in bits\n * and the cipher mode to be used. The most generic way to create a\n * Cipher is the following\n *\n * cipher = OpenSSL::Cipher.new('--')\n *\n * That is, a string consisting of the hyphenated concatenation of the\n * individual components name, key length and mode. Either all uppercase\n * or all lowercase strings may be used, for example:\n *\n * cipher = OpenSSL::Cipher.new('AES-128-CBC')\n *\n * For each algorithm supported, there is a class defined under the\n * Cipher class that goes by the name of the cipher, e.g. to obtain an\n * instance of AES, you could also use\n *\n * # these are equivalent\n * cipher = OpenSSL::Cipher::AES.new(128, :CBC)\n * cipher = OpenSSL::Cipher::AES.new(128, 'CBC')\n * cipher = OpenSSL::Cipher::AES.new('128-CBC')\n *\n * Finally, due to its wide-spread use, there are also extra classes\n * defined for the different key sizes of AES\n *\n * cipher = OpenSSL::Cipher::AES128.new(:CBC)\n * cipher = OpenSSL::Cipher::AES192.new(:CBC)\n * cipher = OpenSSL::Cipher::AES256.new(:CBC)\n *\n * === Choosing either encryption or decryption mode\n *\n * Encryption and decryption are often very similar operations for\n * symmetric algorithms, this is reflected by not having to choose\n * different classes for either operation, both can be done using the\n * same class. Still, after obtaining a Cipher instance, we need to\n * tell the instance what it is that we intend to do with it, so we\n * need to call either\n *\n * cipher.encrypt\n *\n * or\n *\n * cipher.decrypt\n *\n * on the Cipher instance. This should be the first call after creating\n * the instance, otherwise configuration that has already been set could\n * get lost in the process.\n *\n * === Choosing a key\n *\n * Symmetric encryption requires a key that is the same for the encrypting\n * and for the decrypting party and after initial key establishment should\n * be kept as private information. There are a lot of ways to create\n * insecure keys, the most notable is to simply take a password as the key\n * without processing the password further. A simple and secure way to\n * create a key for a particular Cipher is\n *\n * cipher = OpenSSL::AES256.new(:CFB)\n * cipher.encrypt\n * key = cipher.random_key # also sets the generated key on the Cipher\n *\n * If you absolutely need to use passwords as encryption keys, you\n * should use Password-Based Key Derivation Function 2 (PBKDF2) by\n * generating the key with the help of the functionality provided by\n * OpenSSL::PKCS5.pbkdf2_hmac_sha1 or OpenSSL::PKCS5.pbkdf2_hmac.\n *\n * Although there is Cipher#pkcs5_keyivgen, its use is deprecated and\n * it should only be used in legacy applications because it does not use\n * the newer PKCS#5 v2 algorithms.\n *\n * === Choosing an IV\n *\n * The cipher modes CBC, CFB, OFB and CTR all need an \"initialization\n * vector\", or short, IV. ECB mode is the only mode that does not require\n * an IV, but there is almost no legitimate use case for this mode\n * because of the fact that it does not sufficiently hide plaintext\n * patterns. Therefore\n *\n * You should never use ECB mode unless you are absolutely sure that\n * you absolutely need it\n *\n * Because of this, you will end up with a mode that explicitly requires\n * an IV in any case. Note that for backwards compatibility reasons,\n * setting an IV is not explicitly mandated by the Cipher API. If not\n * set, OpenSSL itself defaults to an all-zeroes IV (\"\\\\0\", not the\n * character). Although the IV can be seen as public information, i.e.\n * it may be transmitted in public once generated, it should still stay\n * unpredictable to prevent certain kinds of attacks. Therefore, ideally\n *\n * Always create a secure random IV for every encryption of your\n * Cipher\n *\n * A new, random IV should be created for every encryption of data. Think\n * of the IV as a nonce (number used once) - it's public but random and\n * unpredictable. A secure random IV can be created as follows\n *\n * cipher = ...\n * cipher.encrypt\n * key = cipher.random_key\n * iv = cipher.random_iv # also sets the generated IV on the Cipher\n *\n * Although the key is generally a random value, too, it is a bad choice\n * as an IV. There are elaborate ways how an attacker can take advantage\n * of such an IV. As a general rule of thumb, exposing the key directly\n * or indirectly should be avoided at all cost and exceptions only be\n * made with good reason.\n *\n * === Calling Cipher#final\n *\n * ECB (which should not be used) and CBC are both block-based modes.\n * This means that unlike for the other streaming-based modes, they\n * operate on fixed-size blocks of data, and therefore they require a\n * \"finalization\" step to produce or correctly decrypt the last block of\n * data by appropriately handling some form of padding. Therefore it is\n * essential to add the output of OpenSSL::Cipher#final to your\n * encryption/decryption buffer or you will end up with decryption errors\n * or truncated data.\n *\n * Although this is not really necessary for streaming-mode ciphers, it is\n * still recommended to apply the same pattern of adding the output of\n * Cipher#final there as well - it also enables you to switch between\n * modes more easily in the future.\n *\n * === Encrypting and decrypting some data\n *\n * data = \"Very, very confidential data\"\n *\n * cipher = OpenSSL::Cipher::AES.new(128, :CBC)\n * cipher.encrypt\n * key = cipher.random_key\n * iv = cipher.random_iv\n *\n * encrypted = cipher.update(data) + cipher.final\n * ...\n * decipher = OpenSSL::Cipher::AES.new(128, :CBC)\n * decipher.decrypt\n * decipher.key = key\n * decipher.iv = iv\n *\n * plain = decipher.update(encrypted) + decipher.final\n *\n * puts data == plain #=> true\n *\n * === Authenticated Encryption and Associated Data (AEAD)\n *\n * If the OpenSSL version used supports it, an Authenticated Encryption\n * mode (such as GCM or CCM) should always be preferred over any\n * unauthenticated mode. Currently, OpenSSL supports AE only in combination\n * with Associated Data (AEAD) where additional associated data is included\n * in the encryption process to compute a tag at the end of the encryption.\n * This tag will also be used in the decryption process and by verifying\n * its validity, the authenticity of a given ciphertext is established.\n *\n * This is superior to unauthenticated modes in that it allows to detect\n * if somebody effectively changed the ciphertext after it had been\n * encrypted. This prevents malicious modifications of the ciphertext that\n * could otherwise be exploited to modify ciphertexts in ways beneficial to\n * potential attackers.\n *\n * An associated data is used where there is additional information, such as\n * headers or some metadata, that must be also authenticated but not\n * necessarily need to be encrypted. If no associated data is needed for\n * encryption and later decryption, the OpenSSL library still requires a\n * value to be set - \"\" may be used in case none is available.\n *\n * An example using the GCM (Galois/Counter Mode). You have 16 bytes +key+,\n * 12 bytes (96 bits) +nonce+ and the associated data +auth_data+. Be sure\n * not to reuse the +key+ and +nonce+ pair. Reusing an nonce ruins the\n * security gurantees of GCM mode.\n *\n * cipher = OpenSSL::Cipher::AES.new(128, :GCM).encrypt\n * cipher.key = key\n * cipher.iv = nonce\n * cipher.auth_data = auth_data\n *\n * encrypted = cipher.update(data) + cipher.final\n * tag = cipher.auth_tag # produces 16 bytes tag by default\n *\n * Now you are the receiver. You know the +key+ and have received +nonce+,\n * +auth_data+, +encrypted+ and +tag+ through an untrusted network. Note\n * that GCM accepts an arbitrary length tag between 1 and 16 bytes. You may\n * additionally need to check that the received tag has the correct length,\n * or you allow attackers to forge a valid single byte tag for the tampered\n * ciphertext with a probability of 1/256.\n *\n * raise \"tag is truncated!\" unless tag.bytesize == 16\n * decipher = OpenSSL::Cipher::AES.new(128, :GCM).decrypt\n * decipher.key = key\n * decipher.iv = nonce\n * decipher.auth_tag = tag\n * decipher.auth_data = auth_data\n *\n * decrypted = decipher.update(encrypted) + decipher.final\n *\n * puts data == decrypted #=> true\n */\n cCipher = rb_define_class_under(mOSSL, \"Cipher\", rb_cObject);\n eCipherError = rb_define_class_under(cCipher, \"CipherError\", eOSSLError);\n\n rb_define_alloc_func(cCipher, ossl_cipher_alloc);\n rb_define_copy_func(cCipher, ossl_cipher_copy);\n rb_define_module_function(cCipher, \"ciphers\", ossl_s_ciphers, 0);\n rb_define_method(cCipher, \"initialize\", ossl_cipher_initialize, 1);\n rb_define_method(cCipher, \"reset\", ossl_cipher_reset, 0);\n rb_define_method(cCipher, \"encrypt\", ossl_cipher_encrypt, -1);\n rb_define_method(cCipher, \"decrypt\", ossl_cipher_decrypt, -1);\n rb_define_method(cCipher, \"pkcs5_keyivgen\", ossl_cipher_pkcs5_keyivgen, -1);\n rb_define_method(cCipher, \"update\", ossl_cipher_update, -1);\n rb_define_method(cCipher, \"final\", ossl_cipher_final, 0);\n rb_define_method(cCipher, \"name\", ossl_cipher_name, 0);\n rb_define_method(cCipher, \"key=\", ossl_cipher_set_key, 1);\n rb_define_method(cCipher, \"auth_data=\", ossl_cipher_set_auth_data, 1);\n rb_define_method(cCipher, \"auth_tag=\", ossl_cipher_set_auth_tag, 1);\n rb_define_method(cCipher, \"auth_tag\", ossl_cipher_get_auth_tag, -1);\n rb_define_method(cCipher, \"auth_tag_len=\", ossl_cipher_set_auth_tag_len, 1);\n rb_define_method(cCipher, \"authenticated?\", ossl_cipher_is_authenticated, 0);\n rb_define_method(cCipher, \"key_len=\", ossl_cipher_set_key_length, 1);\n rb_define_method(cCipher, \"key_len\", ossl_cipher_key_length, 0);\n rb_define_method(cCipher, \"iv=\", ossl_cipher_set_iv, 1);\n rb_define_method(cCipher, \"iv_len=\", ossl_cipher_set_iv_length, 1);\n rb_define_method(cCipher, \"iv_len\", ossl_cipher_iv_length, 0);\n rb_define_method(cCipher, \"block_size\", ossl_cipher_block_size, 0);\n rb_define_method(cCipher, \"padding=\", ossl_cipher_set_padding, 1);\n\n id_auth_tag_len = rb_intern_const(\"auth_tag_len\");\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-326', 'CWE-310', 'CWE-703'], 'message': 'cipher: don't set dummy encryption key in Cipher#initialize\n\nRemove the encryption key initialization from Cipher#initialize. This\nis effectively a revert of r32723 (\"Avoid possible SEGV from AES\nencryption/decryption\", 2011-07-28).\n\nr32723, which added the key initialization, was a workaround for\nRuby Bug #2768. For some certain ciphers, calling EVP_CipherUpdate()\nbefore setting an encryption key caused segfault. It was not a problem\nuntil OpenSSL implemented GCM mode - the encryption key could be\noverridden by repeated calls of EVP_CipherInit_ex(). But, it is not the\ncase for AES-GCM ciphers. Setting a key, an IV, a key, in this order\ncauses the IV to be reset to an all-zero IV.\n\nThe problem of Bug #2768 persists on the current versions of OpenSSL.\nSo, make Cipher#update raise an exception if a key is not yet set by the\nuser. Since encrypting or decrypting without key does not make any\nsense, this should not break existing applications.\n\nUsers can still call Cipher#key= and Cipher#iv= multiple times with\ntheir own responsibility.\n\nReference: https://bugs.ruby-lang.org/issues/2768\nReference: https://bugs.ruby-lang.org/issues/8221\nReference: https://github.com/ruby/openssl/issues/49'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: brcmf_cfg80211_start_ap(struct wiphy *wiphy, struct net_device *ndev,\n\t\t\tstruct cfg80211_ap_settings *settings)\n{\n\ts32 ie_offset;\n\tstruct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);\n\tstruct brcmf_if *ifp = netdev_priv(ndev);\n\tconst struct brcmf_tlv *ssid_ie;\n\tconst struct brcmf_tlv *country_ie;\n\tstruct brcmf_ssid_le ssid_le;\n\ts32 err = -EPERM;\n\tconst struct brcmf_tlv *rsn_ie;\n\tconst struct brcmf_vs_tlv *wpa_ie;\n\tstruct brcmf_join_params join_params;\n\tenum nl80211_iftype dev_role;\n\tstruct brcmf_fil_bss_enable_le bss_enable;\n\tu16 chanspec = chandef_to_chanspec(&cfg->d11inf, &settings->chandef);\n\tbool mbss;\n\tint is_11d;\n\n\tbrcmf_dbg(TRACE, \"ctrlchn=%d, center=%d, bw=%d, beacon_interval=%d, dtim_period=%d,\\n\",\n\t\t settings->chandef.chan->hw_value,\n\t\t settings->chandef.center_freq1, settings->chandef.width,\n\t\t settings->beacon_interval, settings->dtim_period);\n\tbrcmf_dbg(TRACE, \"ssid=%s(%zu), auth_type=%d, inactivity_timeout=%d\\n\",\n\t\t settings->ssid, settings->ssid_len, settings->auth_type,\n\t\t settings->inactivity_timeout);\n\tdev_role = ifp->vif->wdev.iftype;\n\tmbss = ifp->vif->mbss;\n\n\t/* store current 11d setting */\n\tbrcmf_fil_cmd_int_get(ifp, BRCMF_C_GET_REGULATORY, &ifp->vif->is_11d);\n\tcountry_ie = brcmf_parse_tlvs((u8 *)settings->beacon.tail,\n\t\t\t\t settings->beacon.tail_len,\n\t\t\t\t WLAN_EID_COUNTRY);\n\tis_11d = country_ie ? 1 : 0;\n\n\tmemset(&ssid_le, 0, sizeof(ssid_le));\n\tif (settings->ssid == NULL || settings->ssid_len == 0) {\n\t\tie_offset = DOT11_MGMT_HDR_LEN + DOT11_BCN_PRB_FIXED_LEN;\n\t\tssid_ie = brcmf_parse_tlvs(\n\t\t\t\t(u8 *)&settings->beacon.head[ie_offset],\n\t\t\t\tsettings->beacon.head_len - ie_offset,\n\t\t\t\tWLAN_EID_SSID);\n\t\tif (!ssid_ie)\n\t\t\treturn -EINVAL;\n\n\t\tmemcpy(ssid_le.SSID, ssid_ie->data, ssid_ie->len);\n\t\tssid_le.SSID_len = cpu_to_le32(ssid_ie->len);\n\t\tbrcmf_dbg(TRACE, \"SSID is (%s) in Head\\n\", ssid_le.SSID);\n\t} else {\n\t\tmemcpy(ssid_le.SSID, settings->ssid, settings->ssid_len);\n\t\tssid_le.SSID_len = cpu_to_le32((u32)settings->ssid_len);\n\t}\n\n\tif (!mbss) {\n\t\tbrcmf_set_mpc(ifp, 0);\n\t\tbrcmf_configure_arp_nd_offload(ifp, false);\n\t}\n\n\t/* find the RSN_IE */\n\trsn_ie = brcmf_parse_tlvs((u8 *)settings->beacon.tail,\n\t\t\t\t settings->beacon.tail_len, WLAN_EID_RSN);\n\n\t/* find the WPA_IE */\n\twpa_ie = brcmf_find_wpaie((u8 *)settings->beacon.tail,\n\t\t\t\t settings->beacon.tail_len);\n\n\tif ((wpa_ie != NULL || rsn_ie != NULL)) {\n\t\tbrcmf_dbg(TRACE, \"WPA(2) IE is found\\n\");\n\t\tif (wpa_ie != NULL) {\n\t\t\t/* WPA IE */\n\t\t\terr = brcmf_configure_wpaie(ifp, wpa_ie, false);\n\t\t\tif (err < 0)\n\t\t\t\tgoto exit;\n\t\t} else {\n\t\t\tstruct brcmf_vs_tlv *tmp_ie;\n\n\t\t\ttmp_ie = (struct brcmf_vs_tlv *)rsn_ie;\n\n\t\t\t/* RSN IE */\n\t\t\terr = brcmf_configure_wpaie(ifp, tmp_ie, true);\n\t\t\tif (err < 0)\n\t\t\t\tgoto exit;\n\t\t}\n\t} else {\n\t\tbrcmf_dbg(TRACE, \"No WPA(2) IEs found\\n\");\n\t\tbrcmf_configure_opensecurity(ifp);\n\t}\n\n\tbrcmf_config_ap_mgmt_ie(ifp->vif, &settings->beacon);\n\n\t/* Parameters shared by all radio interfaces */\n\tif (!mbss) {\n\t\tif (is_11d != ifp->vif->is_11d) {\n\t\t\terr = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_REGULATORY,\n\t\t\t\t\t\t is_11d);\n\t\t\tif (err < 0) {\n\t\t\t\tbrcmf_err(\"Regulatory Set Error, %d\\n\", err);\n\t\t\t\tgoto exit;\n\t\t\t}\n\t\t}\n\t\tif (settings->beacon_interval) {\n\t\t\terr = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_BCNPRD,\n\t\t\t\t\t\t settings->beacon_interval);\n\t\t\tif (err < 0) {\n\t\t\t\tbrcmf_err(\"Beacon Interval Set Error, %d\\n\",\n\t\t\t\t\t err);\n\t\t\t\tgoto exit;\n\t\t\t}\n\t\t}\n\t\tif (settings->dtim_period) {\n\t\t\terr = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_DTIMPRD,\n\t\t\t\t\t\t settings->dtim_period);\n\t\t\tif (err < 0) {\n\t\t\t\tbrcmf_err(\"DTIM Interval Set Error, %d\\n\", err);\n\t\t\t\tgoto exit;\n\t\t\t}\n\t\t}\n\n\t\tif ((dev_role == NL80211_IFTYPE_AP) &&\n\t\t ((ifp->ifidx == 0) ||\n\t\t !brcmf_feat_is_enabled(ifp, BRCMF_FEAT_RSDB))) {\n\t\t\terr = brcmf_fil_cmd_int_set(ifp, BRCMF_C_DOWN, 1);\n\t\t\tif (err < 0) {\n\t\t\t\tbrcmf_err(\"BRCMF_C_DOWN error %d\\n\", err);\n\t\t\t\tgoto exit;\n\t\t\t}\n\t\t\tbrcmf_fil_iovar_int_set(ifp, \"apsta\", 0);\n\t\t}\n\n\t\terr = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_INFRA, 1);\n\t\tif (err < 0) {\n\t\t\tbrcmf_err(\"SET INFRA error %d\\n\", err);\n\t\t\tgoto exit;\n\t\t}\n\t} else if (WARN_ON(is_11d != ifp->vif->is_11d)) {\n\t\t/* Multiple-BSS should use same 11d configuration */\n\t\terr = -EINVAL;\n\t\tgoto exit;\n\t}\n\n\t/* Interface specific setup */\n\tif (dev_role == NL80211_IFTYPE_AP) {\n\t\tif ((brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MBSS)) && (!mbss))\n\t\t\tbrcmf_fil_iovar_int_set(ifp, \"mbss\", 1);\n\n\t\terr = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_AP, 1);\n\t\tif (err < 0) {\n\t\t\tbrcmf_err(\"setting AP mode failed %d\\n\", err);\n\t\t\tgoto exit;\n\t\t}\n\t\tif (!mbss) {\n\t\t\t/* Firmware 10.x requires setting channel after enabling\n\t\t\t * AP and before bringing interface up.\n\t\t\t */\n\t\t\terr = brcmf_fil_iovar_int_set(ifp, \"chanspec\", chanspec);\n\t\t\tif (err < 0) {\n\t\t\t\tbrcmf_err(\"Set Channel failed: chspec=%d, %d\\n\",\n\t\t\t\t\t chanspec, err);\n\t\t\t\tgoto exit;\n\t\t\t}\n\t\t}\n\t\terr = brcmf_fil_cmd_int_set(ifp, BRCMF_C_UP, 1);\n\t\tif (err < 0) {\n\t\t\tbrcmf_err(\"BRCMF_C_UP error (%d)\\n\", err);\n\t\t\tgoto exit;\n\t\t}\n\t\t/* On DOWN the firmware removes the WEP keys, reconfigure\n\t\t * them if they were set.\n\t\t */\n\t\tbrcmf_cfg80211_reconfigure_wep(ifp);\n\n\t\tmemset(&join_params, 0, sizeof(join_params));\n\t\t/* join parameters starts with ssid */\n\t\tmemcpy(&join_params.ssid_le, &ssid_le, sizeof(ssid_le));\n\t\t/* create softap */\n\t\terr = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SET_SSID,\n\t\t\t\t\t &join_params, sizeof(join_params));\n\t\tif (err < 0) {\n\t\t\tbrcmf_err(\"SET SSID error (%d)\\n\", err);\n\t\t\tgoto exit;\n\t\t}\n\n\t\tif (settings->hidden_ssid) {\n\t\t\terr = brcmf_fil_iovar_int_set(ifp, \"closednet\", 1);\n\t\t\tif (err) {\n\t\t\t\tbrcmf_err(\"closednet error (%d)\\n\", err);\n\t\t\t\tgoto exit;\n\t\t\t}\n\t\t}\n\n\t\tbrcmf_dbg(TRACE, \"AP mode configuration complete\\n\");\n\t} else if (dev_role == NL80211_IFTYPE_P2P_GO) {\n\t\terr = brcmf_fil_iovar_int_set(ifp, \"chanspec\", chanspec);\n\t\tif (err < 0) {\n\t\t\tbrcmf_err(\"Set Channel failed: chspec=%d, %d\\n\",\n\t\t\t\t chanspec, err);\n\t\t\tgoto exit;\n\t\t}\n\t\terr = brcmf_fil_bsscfg_data_set(ifp, \"ssid\", &ssid_le,\n\t\t\t\t\t\tsizeof(ssid_le));\n\t\tif (err < 0) {\n\t\t\tbrcmf_err(\"setting ssid failed %d\\n\", err);\n\t\t\tgoto exit;\n\t\t}\n\t\tbss_enable.bsscfgidx = cpu_to_le32(ifp->bsscfgidx);\n\t\tbss_enable.enable = cpu_to_le32(1);\n\t\terr = brcmf_fil_iovar_data_set(ifp, \"bss\", &bss_enable,\n\t\t\t\t\t sizeof(bss_enable));\n\t\tif (err < 0) {\n\t\t\tbrcmf_err(\"bss_enable config failed %d\\n\", err);\n\t\t\tgoto exit;\n\t\t}\n\n\t\tbrcmf_dbg(TRACE, \"GO mode configuration complete\\n\");\n\t} else {\n\t\tWARN_ON(1);\n\t}\n\n\tset_bit(BRCMF_VIF_STATUS_AP_CREATED, &ifp->vif->sme_state);\n\tbrcmf_net_setcarrier(ifp, true);\n\nexit:\n\tif ((err) && (!mbss)) {\n\t\tbrcmf_set_mpc(ifp, 1);\n\t\tbrcmf_configure_arp_nd_offload(ifp, true);\n\t}\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-703'], 'message': 'brcmfmac: avoid potential stack overflow in brcmf_cfg80211_start_ap()\n\nUser-space can choose to omit NL80211_ATTR_SSID and only provide raw\nIE TLV data. When doing so it can provide SSID IE with length exceeding\nthe allowed size. The driver further processes this IE copying it\ninto a local variable without checking the length. Hence stack can be\ncorrupted and used as exploit.\n\nCc: stable@vger.kernel.org # v4.7\nReported-by: Daxing Guo \nReviewed-by: Hante Meuleman \nReviewed-by: Pieter-Paul Giesberts \nReviewed-by: Franky Lin \nSigned-off-by: Arend van Spriel \nSigned-off-by: Kalle Valo '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: xfs_iflush_int(\n\tstruct xfs_inode\t*ip,\n\tstruct xfs_buf\t\t*bp)\n{\n\tstruct xfs_inode_log_item *iip = ip->i_itemp;\n\tstruct xfs_dinode\t*dip;\n\tstruct xfs_mount\t*mp = ip->i_mount;\n\n\tASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL|XFS_ILOCK_SHARED));\n\tASSERT(xfs_isiflocked(ip));\n\tASSERT(ip->i_d.di_format != XFS_DINODE_FMT_BTREE ||\n\t ip->i_d.di_nextents > XFS_IFORK_MAXEXT(ip, XFS_DATA_FORK));\n\tASSERT(iip != NULL && iip->ili_fields != 0);\n\tASSERT(ip->i_d.di_version > 1);\n\n\t/* set *dip = inode's place in the buffer */\n\tdip = xfs_buf_offset(bp, ip->i_imap.im_boffset);\n\n\tif (XFS_TEST_ERROR(dip->di_magic != cpu_to_be16(XFS_DINODE_MAGIC),\n\t\t\t mp, XFS_ERRTAG_IFLUSH_1, XFS_RANDOM_IFLUSH_1)) {\n\t\txfs_alert_tag(mp, XFS_PTAG_IFLUSH,\n\t\t\t\"%s: Bad inode %Lu magic number 0x%x, ptr 0x%p\",\n\t\t\t__func__, ip->i_ino, be16_to_cpu(dip->di_magic), dip);\n\t\tgoto corrupt_out;\n\t}\n\tif (XFS_TEST_ERROR(ip->i_d.di_magic != XFS_DINODE_MAGIC,\n\t\t\t\tmp, XFS_ERRTAG_IFLUSH_2, XFS_RANDOM_IFLUSH_2)) {\n\t\txfs_alert_tag(mp, XFS_PTAG_IFLUSH,\n\t\t\t\"%s: Bad inode %Lu, ptr 0x%p, magic number 0x%x\",\n\t\t\t__func__, ip->i_ino, ip, ip->i_d.di_magic);\n\t\tgoto corrupt_out;\n\t}\n\tif (S_ISREG(ip->i_d.di_mode)) {\n\t\tif (XFS_TEST_ERROR(\n\t\t (ip->i_d.di_format != XFS_DINODE_FMT_EXTENTS) &&\n\t\t (ip->i_d.di_format != XFS_DINODE_FMT_BTREE),\n\t\t mp, XFS_ERRTAG_IFLUSH_3, XFS_RANDOM_IFLUSH_3)) {\n\t\t\txfs_alert_tag(mp, XFS_PTAG_IFLUSH,\n\t\t\t\t\"%s: Bad regular inode %Lu, ptr 0x%p\",\n\t\t\t\t__func__, ip->i_ino, ip);\n\t\t\tgoto corrupt_out;\n\t\t}\n\t} else if (S_ISDIR(ip->i_d.di_mode)) {\n\t\tif (XFS_TEST_ERROR(\n\t\t (ip->i_d.di_format != XFS_DINODE_FMT_EXTENTS) &&\n\t\t (ip->i_d.di_format != XFS_DINODE_FMT_BTREE) &&\n\t\t (ip->i_d.di_format != XFS_DINODE_FMT_LOCAL),\n\t\t mp, XFS_ERRTAG_IFLUSH_4, XFS_RANDOM_IFLUSH_4)) {\n\t\t\txfs_alert_tag(mp, XFS_PTAG_IFLUSH,\n\t\t\t\t\"%s: Bad directory inode %Lu, ptr 0x%p\",\n\t\t\t\t__func__, ip->i_ino, ip);\n\t\t\tgoto corrupt_out;\n\t\t}\n\t}\n\tif (XFS_TEST_ERROR(ip->i_d.di_nextents + ip->i_d.di_anextents >\n\t\t\t\tip->i_d.di_nblocks, mp, XFS_ERRTAG_IFLUSH_5,\n\t\t\t\tXFS_RANDOM_IFLUSH_5)) {\n\t\txfs_alert_tag(mp, XFS_PTAG_IFLUSH,\n\t\t\t\"%s: detected corrupt incore inode %Lu, \"\n\t\t\t\"total extents = %d, nblocks = %Ld, ptr 0x%p\",\n\t\t\t__func__, ip->i_ino,\n\t\t\tip->i_d.di_nextents + ip->i_d.di_anextents,\n\t\t\tip->i_d.di_nblocks, ip);\n\t\tgoto corrupt_out;\n\t}\n\tif (XFS_TEST_ERROR(ip->i_d.di_forkoff > mp->m_sb.sb_inodesize,\n\t\t\t\tmp, XFS_ERRTAG_IFLUSH_6, XFS_RANDOM_IFLUSH_6)) {\n\t\txfs_alert_tag(mp, XFS_PTAG_IFLUSH,\n\t\t\t\"%s: bad inode %Lu, forkoff 0x%x, ptr 0x%p\",\n\t\t\t__func__, ip->i_ino, ip->i_d.di_forkoff, ip);\n\t\tgoto corrupt_out;\n\t}\n\n\t/*\n\t * Inode item log recovery for v2 inodes are dependent on the\n\t * di_flushiter count for correct sequencing. We bump the flush\n\t * iteration count so we can detect flushes which postdate a log record\n\t * during recovery. This is redundant as we now log every change and\n\t * hence this can't happen but we need to still do it to ensure\n\t * backwards compatibility with old kernels that predate logging all\n\t * inode changes.\n\t */\n\tif (ip->i_d.di_version < 3)\n\t\tip->i_d.di_flushiter++;\n\n\t/*\n\t * Copy the dirty parts of the inode into the on-disk\n\t * inode. We always copy out the core of the inode,\n\t * because if the inode is dirty at all the core must\n\t * be.\n\t */\n\txfs_dinode_to_disk(dip, &ip->i_d);\n\n\t/* Wrap, we never let the log put out DI_MAX_FLUSH */\n\tif (ip->i_d.di_flushiter == DI_MAX_FLUSH)\n\t\tip->i_d.di_flushiter = 0;\n\n\txfs_iflush_fork(ip, dip, iip, XFS_DATA_FORK);\n\tif (XFS_IFORK_Q(ip))\n\t\txfs_iflush_fork(ip, dip, iip, XFS_ATTR_FORK);\n\txfs_inobp_check(mp, bp);\n\n\t/*\n\t * We've recorded everything logged in the inode, so we'd like to clear\n\t * the ili_fields bits so we don't log and flush things unnecessarily.\n\t * However, we can't stop logging all this information until the data\n\t * we've copied into the disk buffer is written to disk. If we did we\n\t * might overwrite the copy of the inode in the log with all the data\n\t * after re-logging only part of it, and in the face of a crash we\n\t * wouldn't have all the data we need to recover.\n\t *\n\t * What we do is move the bits to the ili_last_fields field. When\n\t * logging the inode, these bits are moved back to the ili_fields field.\n\t * In the xfs_iflush_done() routine we clear ili_last_fields, since we\n\t * know that the information those bits represent is permanently on\n\t * disk. As long as the flush completes before the inode is logged\n\t * again, then both ili_fields and ili_last_fields will be cleared.\n\t *\n\t * We can play with the ili_fields bits here, because the inode lock\n\t * must be held exclusively in order to set bits there and the flush\n\t * lock protects the ili_last_fields bits. Set ili_logged so the flush\n\t * done routine can tell whether or not to look in the AIL. Also, store\n\t * the current LSN of the inode so that we can tell whether the item has\n\t * moved in the AIL from xfs_iflush_done(). In order to read the lsn we\n\t * need the AIL lock, because it is a 64 bit value that cannot be read\n\t * atomically.\n\t */\n\tiip->ili_last_fields = iip->ili_fields;\n\tiip->ili_fields = 0;\n\tiip->ili_logged = 1;\n\n\txfs_trans_ail_copy_lsn(mp->m_ail, &iip->ili_flush_lsn,\n\t\t\t\t&iip->ili_item.li_lsn);\n\n\t/*\n\t * Attach the function xfs_iflush_done to the inode's\n\t * buffer. This will remove the inode from the AIL\n\t * and unlock the inode's flush lock when the inode is\n\t * completely written to disk.\n\t */\n\txfs_buf_attach_iodone(bp, xfs_iflush_done, &iip->ili_item);\n\n\t/* update the lsn in the on disk inode if required */\n\tif (ip->i_d.di_version == 3)\n\t\tdip->di_lsn = cpu_to_be64(iip->ili_item.li_lsn);\n\n\t/* generate the checksum. */\n\txfs_dinode_calc_crc(mp, dip);\n\n\tASSERT(bp->b_fspriv != NULL);\n\tASSERT(bp->b_iodone != NULL);\n\treturn 0;\n\ncorrupt_out:\n\treturn -EFSCORRUPTED;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-19'], 'message': 'xfs: optimise away log forces on timestamp updates for fdatasync\n\nxfs: timestamp updates cause excessive fdatasync log traffic\n\nSage Weil reported that a ceph test workload was writing to the\nlog on every fdatasync during an overwrite workload. Event tracing\nshowed that the only metadata modification being made was the\ntimestamp updates during the write(2) syscall, but fdatasync(2)\nis supposed to ignore them. The key observation was that the\ntransactions in the log all looked like this:\n\nINODE: #regs: 4 ino: 0x8b flags: 0x45 dsize: 32\n\nAnd contained a flags field of 0x45 or 0x85, and had data and\nattribute forks following the inode core. This means that the\ntimestamp updates were triggering dirty relogging of previously\nlogged parts of the inode that hadn't yet been flushed back to\ndisk.\n\nThere are two parts to this problem. The first is that XFS relogs\ndirty regions in subsequent transactions, so it carries around the\nfields that have been dirtied since the last time the inode was\nwritten back to disk, not since the last time the inode was forced\ninto the log.\n\nThe second part is that on v5 filesystems, the inode change count\nupdate during inode dirtying also sets the XFS_ILOG_CORE flag, so\non v5 filesystems this makes a timestamp update dirty the entire\ninode.\n\nAs a result when fdatasync is run, it looks at the dirty fields in\nthe inode, and sees more than just the timestamp flag, even though\nthe only metadata change since the last fdatasync was just the\ntimestamps. Hence we force the log on every subsequent fdatasync\neven though it is not needed.\n\nTo fix this, add a new field to the inode log item that tracks\nchanges since the last time fsync/fdatasync forced the log to flush\nthe changes to the journal. This flag is updated when we dirty the\ninode, but we do it before updating the change count so it does not\ncarry the \"core dirty\" flag from timestamp updates. The fields are\nzeroed when the inode is marked clean (due to writeback/freeing) or\nwhen an fsync/datasync forces the log. Hence if we only dirty the\ntimestamps on the inode between fsync/fdatasync calls, the fdatasync\nwill not trigger another log force.\n\nOver 100 runs of the test program:\n\nExt4 baseline:\n\truntime: 1.63s +/- 0.24s\n\tavg lat: 1.59ms +/- 0.24ms\n\tiops: ~2000\n\nXFS, vanilla kernel:\n runtime: 2.45s +/- 0.18s\n\tavg lat: 2.39ms +/- 0.18ms\n\tlog forces: ~400/s\n\tiops: ~1000\n\nXFS, patched kernel:\n runtime: 1.49s +/- 0.26s\n\tavg lat: 1.46ms +/- 0.25ms\n\tlog forces: ~30/s\n\tiops: ~1500\n\nReported-by: Sage Weil \nSigned-off-by: Dave Chinner \nReviewed-by: Brian Foster \nSigned-off-by: Dave Chinner '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int bmp_getint32(jas_stream_t *in, int_fast32_t *val)\n{\n\tint n;\n\tuint_fast32_t v;\n\tint c;\n\tfor (n = 4, v = 0;;) {\n\t\tif ((c = jas_stream_getc(in)) == EOF) {\n\t\t\treturn -1;\n\t\t}\n\t\tv |= (c << 24);\n\t\tif (--n <= 0) {\n\t\t\tbreak;\n\t\t}\n\t\tv >>= 8;\n\t}\n\tif (val) {\n\t\t*val = v;\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-125'], 'message': 'Fixed a sanitizer failure in the BMP codec.\nAlso, added a --debug-level command line option to the imginfo command\nfor debugging purposes.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: chunk_new_with_alloc_size(size_t alloc)\n{\n chunk_t *ch;\n ch = tor_malloc(alloc);\n ch->next = NULL;\n ch->datalen = 0;\n#ifdef DEBUG_CHUNK_ALLOC\n ch->DBG_alloc = alloc;\n#endif\n ch->memlen = CHUNK_SIZE_WITH_ALLOC(alloc);\n total_bytes_allocated_in_chunks += alloc;\n ch->data = &ch->mem[0];\n return ch;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Add a one-word sentinel value of 0x0 at the end of each buf_t chunk\n\nThis helps protect against bugs where any part of a buf_t's memory\nis passed to a function that expects a NUL-terminated input.\n\nIt also closes TROVE-2016-10-001 (aka bug 20384).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n#define SkipLinesOp 0x01\n#define SetColorOp 0x02\n#define SkipPixelsOp 0x03\n#define ByteDataOp 0x05\n#define RunDataOp 0x06\n#define EOFOp 0x07\n\n char\n magick[12];\n\n Image\n *image;\n\n int\n opcode,\n operand,\n status;\n\n MagickStatusType\n flags;\n\n MagickSizeType\n number_pixels;\n\n MemoryInfo\n *pixel_info;\n\n Quantum\n index;\n\n register ssize_t\n x;\n\n register Quantum\n *q;\n\n register ssize_t\n i;\n\n register unsigned char\n *p;\n\n size_t\n bits_per_pixel,\n map_length,\n number_colormaps,\n number_planes,\n number_planes_filled,\n one,\n pixel_info_length;\n\n ssize_t\n count,\n offset,\n y;\n\n unsigned char\n background_color[256],\n *colormap,\n pixel,\n plane,\n *pixels;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n /*\n Determine if this a RLE file.\n */\n count=ReadBlob(image,2,(unsigned char *) magick);\n if ((count != 2) || (memcmp(magick,\"\\122\\314\",2) != 0))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n do\n {\n /*\n Read image header.\n */\n image->page.x=ReadBlobLSBShort(image);\n image->page.y=ReadBlobLSBShort(image);\n image->columns=ReadBlobLSBShort(image);\n image->rows=ReadBlobLSBShort(image);\n flags=(MagickStatusType) ReadBlobByte(image);\n image->alpha_trait=flags & 0x04 ? BlendPixelTrait : UndefinedPixelTrait;\n number_planes=(size_t) ReadBlobByte(image);\n bits_per_pixel=(size_t) ReadBlobByte(image);\n number_colormaps=(size_t) ReadBlobByte(image);\n map_length=(unsigned char) ReadBlobByte(image);\n if (map_length >= 64)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n one=1;\n map_length=one << map_length;\n if ((number_planes == 0) || (number_planes == 2) ||\n ((flags & 0x04) && (number_colormaps > 254)) || (bits_per_pixel != 8) ||\n (image->columns == 0))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (flags & 0x02)\n {\n /*\n No background color-- initialize to black.\n */\n for (i=0; i < (ssize_t) number_planes; i++)\n background_color[i]=0;\n (void) ReadBlobByte(image);\n }\n else\n {\n /*\n Initialize background color.\n */\n p=background_color;\n for (i=0; i < (ssize_t) number_planes; i++)\n *p++=(unsigned char) ReadBlobByte(image);\n }\n if ((number_planes & 0x01) == 0)\n (void) ReadBlobByte(image);\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n colormap=(unsigned char *) NULL;\n if (number_colormaps != 0)\n {\n /*\n Read image colormaps.\n */\n colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps,\n 3*map_length*sizeof(*colormap));\n if (colormap == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n p=colormap;\n for (i=0; i < (ssize_t) number_colormaps; i++)\n for (x=0; x < (ssize_t) map_length; x++)\n *p++=(unsigned char) ScaleShortToQuantum(ReadBlobLSBShort(image));\n }\n if ((flags & 0x08) != 0)\n {\n char\n *comment;\n\n size_t\n length;\n\n /*\n Read image comment.\n */\n length=ReadBlobLSBShort(image);\n if (length != 0)\n {\n comment=(char *) AcquireQuantumMemory(length,sizeof(*comment));\n if (comment == (char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n count=ReadBlob(image,length-1,(unsigned char *) comment);\n comment[length-1]='\\0';\n (void) SetImageProperty(image,\"comment\",comment,exception);\n comment=DestroyString(comment);\n if ((length & 0x01) == 0)\n (void) ReadBlobByte(image);\n }\n }\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n /*\n Allocate RLE pixels.\n */\n if (image->alpha_trait != UndefinedPixelTrait)\n number_planes++;\n number_pixels=(MagickSizeType) image->columns*image->rows;\n number_planes_filled=(number_planes % 2 == 0) ? number_planes :\n number_planes+1;\n if ((number_pixels*number_planes_filled) != (size_t) (number_pixels*\n number_planes_filled))\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixel_info=AcquireVirtualMemory(image->columns,image->rows*\n MagickMax(number_planes_filled,4)*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixel_info_length=image->columns*image->rows*\n MagickMax(number_planes_filled,4);\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n if ((flags & 0x01) && !(flags & 0x02))\n {\n ssize_t\n j;\n\n /*\n Set background color.\n */\n p=pixels;\n for (i=0; i < (ssize_t) number_pixels; i++)\n {\n if (image->alpha_trait == UndefinedPixelTrait)\n for (j=0; j < (ssize_t) number_planes; j++)\n *p++=background_color[j];\n else\n {\n for (j=0; j < (ssize_t) (number_planes-1); j++)\n *p++=background_color[j];\n *p++=0; /* initialize matte channel */\n }\n }\n }\n /*\n Read runlength-encoded image.\n */\n plane=0;\n x=0;\n y=0;\n opcode=ReadBlobByte(image);\n do\n {\n switch (opcode & 0x3f)\n {\n case SkipLinesOp:\n {\n operand=ReadBlobByte(image);\n if (opcode & 0x40)\n operand=ReadBlobLSBSignedShort(image);\n x=0;\n y+=operand;\n break;\n }\n case SetColorOp:\n {\n operand=ReadBlobByte(image);\n plane=(unsigned char) operand;\n if (plane == 255)\n plane=(unsigned char) (number_planes-1);\n x=0;\n break;\n }\n case SkipPixelsOp:\n {\n operand=ReadBlobByte(image);\n if (opcode & 0x40)\n operand=ReadBlobLSBSignedShort(image);\n x+=operand;\n break;\n }\n case ByteDataOp:\n {\n operand=ReadBlobByte(image);\n if (opcode & 0x40)\n operand=ReadBlobLSBSignedShort(image);\n offset=((image->rows-y-1)*image->columns*number_planes)+x*\n number_planes+plane;\n operand++;\n if ((offset < 0) ||\n (offset+((size_t) operand*number_planes) > pixel_info_length))\n {\n if (number_colormaps != 0)\n colormap=(unsigned char *) RelinquishMagickMemory(colormap);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n }\n p=pixels+offset;\n for (i=0; i < (ssize_t) operand; i++)\n {\n pixel=(unsigned char) ReadBlobByte(image);\n if ((y < (ssize_t) image->rows) &&\n ((x+i) < (ssize_t) image->columns))\n *p=pixel;\n p+=number_planes;\n }\n if (operand & 0x01)\n (void) ReadBlobByte(image);\n x+=operand;\n break;\n }\n case RunDataOp:\n {\n operand=ReadBlobByte(image);\n if (opcode & 0x40)\n operand=ReadBlobLSBSignedShort(image);\n pixel=(unsigned char) ReadBlobByte(image);\n (void) ReadBlobByte(image);\n offset=((image->rows-y-1)*image->columns*number_planes)+x*\n number_planes+plane;\n operand++;\n if ((offset < 0) ||\n (offset+((size_t) operand*number_planes) > pixel_info_length))\n {\n if (number_colormaps != 0)\n colormap=(unsigned char *) RelinquishMagickMemory(colormap);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n }\n p=pixels+offset;\n for (i=0; i < (ssize_t) operand; i++)\n {\n if ((y < (ssize_t) image->rows) &&\n ((x+i) < (ssize_t) image->columns))\n *p=pixel;\n p+=number_planes;\n }\n x+=operand;\n break;\n }\n default:\n break;\n }\n opcode=ReadBlobByte(image);\n } while (((opcode & 0x3f) != EOFOp) && (opcode != EOF));\n if (number_colormaps != 0)\n {\n MagickStatusType\n mask;\n\n /*\n Apply colormap affineation to image.\n */\n mask=(MagickStatusType) (map_length-1);\n p=pixels;\n x=(ssize_t) number_planes;\n if (number_colormaps == 1)\n for (i=0; i < (ssize_t) number_pixels; i++)\n {\n ValidateColormapValue(image,*p & mask,&index,exception);\n *p=colormap[(ssize_t) index];\n p++;\n }\n else\n if ((number_planes >= 3) && (number_colormaps >= 3))\n for (i=0; i < (ssize_t) number_pixels; i++)\n for (x=0; x < (ssize_t) number_planes; x++)\n {\n ValidateColormapValue(image,(size_t) (x*map_length+\n (*p & mask)),&index,exception);\n *p=colormap[(ssize_t) index];\n p++;\n }\n if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes))\n {\n colormap=(unsigned char *) RelinquishMagickMemory(colormap);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n }\n }\n /*\n Initialize image structure.\n */\n if (number_planes >= 3)\n {\n /*\n Convert raster image to DirectClass pixel packets.\n */\n p=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelRed(image,ScaleCharToQuantum(*p++),q);\n SetPixelGreen(image,ScaleCharToQuantum(*p++),q);\n SetPixelBlue(image,ScaleCharToQuantum(*p++),q);\n if (image->alpha_trait != UndefinedPixelTrait)\n SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n }\n else\n {\n /*\n Create colormap.\n */\n if (number_colormaps == 0)\n map_length=256;\n if (AcquireImageColormap(image,map_length,exception) == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n p=colormap;\n if (number_colormaps == 1)\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n /*\n Pseudocolor.\n */\n image->colormap[i].red=(MagickRealType)\n ScaleCharToQuantum((unsigned char) i);\n image->colormap[i].green=(MagickRealType)\n ScaleCharToQuantum((unsigned char) i);\n image->colormap[i].blue=(MagickRealType)\n ScaleCharToQuantum((unsigned char) i);\n }\n else\n if (number_colormaps > 1)\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n image->colormap[i].red=(MagickRealType)\n ScaleCharToQuantum(*p);\n image->colormap[i].green=(MagickRealType)\n ScaleCharToQuantum(*(p+map_length));\n image->colormap[i].blue=(MagickRealType)\n ScaleCharToQuantum(*(p+map_length*2));\n p++;\n }\n p=pixels;\n if (image->alpha_trait == UndefinedPixelTrait)\n {\n /*\n Convert raster image to PseudoClass pixel packets.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelIndex(image,*p++,q);\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n (void) SyncImage(image,exception);\n }\n else\n {\n /*\n Image has a matte channel-- promote to DirectClass.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n ValidateColormapValue(image,(ssize_t) *p++,&index,exception);\n SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t)\n index].red),q);\n ValidateColormapValue(image,(ssize_t) *p++,&index,exception);\n SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t)\n index].green),q);\n ValidateColormapValue(image,(ssize_t) *p++,&index,exception);\n SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t)\n index].blue),q);\n SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);\n q+=GetPixelChannels(image);\n }\n if (x < (ssize_t) image->columns)\n break;\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n image->colormap=(PixelInfo *) RelinquishMagickMemory(\n image->colormap);\n image->storage_class=DirectClass;\n image->colors=0;\n }\n }\n if (number_colormaps != 0)\n colormap=(unsigned char *) RelinquishMagickMemory(colormap);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n /*\n Proceed to next image.\n */\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n (void) ReadBlobByte(image);\n count=ReadBlob(image,2,(unsigned char *) magick);\n if ((count != 0) && (memcmp(magick,\"\\122\\314\",2) == 0))\n {\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image,exception);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n GetBlobSize(image));\n if (status == MagickFalse)\n break;\n }\n } while ((count != 0) && (memcmp(magick,\"\\122\\314\",2) == 0));\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/271'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void *jas_realloc(void *ptr, size_t size)\n{\n\tvoid *result;\n\tjas_mb_t *mb;\n\tjas_mb_t *old_mb;\n\tsize_t old_size;\n\tsize_t ext_size;\n\tsize_t mem;\n\n\tJAS_DBGLOG(100, (\"jas_realloc(%x, %zu)\\n\", ptr, size));\n\tif (!ptr) {\n\t\treturn jas_malloc(size);\n\t}\n\tif (ptr && !size) {\n\t\tjas_free(ptr);\n\t}\n\tif (!jas_safe_size_add(size, JAS_MB_SIZE, &ext_size)) {\n\t\tjas_eprintf(\"requested memory size is too large\\n\");\n\t\treturn 0;\n\t}\n\told_mb = jas_get_mb(ptr);\n\told_size = old_mb->size;\n\tJAS_DBGLOG(101, (\"jas_realloc: old_mb=%x; old_size=%zu\\n\", old_mb,\n\t old_size));\n\tif (size > old_size) {\n\t\tif (!jas_safe_size_add(jas_mem, ext_size, &mem) || mem > jas_max_mem) {\n\t\t\tjas_eprintf(\"maximum memory limit would be exceeded\\n\");\n\t\t\treturn 0;\n\t\t}\n\t} else {\n\t\tif (!jas_safe_size_sub(jas_mem, old_size - size, &jas_mem)) {\n\t\t\tjas_eprintf(\"heap corruption detected\\n\");\n\t\t\tabort();\n\t\t}\n\t}\n\tJAS_DBGLOG(100, (\"jas_realloc: realloc(%p, %zu)\\n\", old_mb, ext_size));\n\tif (!(mb = realloc(old_mb, ext_size))) {\n\t\tresult = 0;\n\t} else {\n\t\tresult = jas_mb_get_data(mb);\n\t\tmb->size = size;\n\t\tjas_mem = mem;\n\t}\n\tJAS_DBGLOG(100, (\"jas_realloc(%p, %zu) -> %p (%p)\\n\", ptr, size, result,\n\t mb));\n\tJAS_DBGLOG(102, (\"max_mem=%zu; mem=%zu\\n\", jas_max_mem, jas_mem));\n\treturn result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fixed an integer overflow problem.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int main(int argc, char **argv)\n{\n\tjas_image_t *image;\n\tcmdopts_t *cmdopts;\n\tjas_stream_t *in;\n\tjas_stream_t *out;\n\tjas_tmr_t dectmr;\n\tjas_tmr_t enctmr;\n\tdouble dectime;\n\tdouble enctime;\n\tint_fast16_t numcmpts;\n\tint i;\n\n\t/* Determine the base name of this command. */\n\tif ((cmdname = strrchr(argv[0], '/'))) {\n\t\t++cmdname;\n\t} else {\n\t\tcmdname = argv[0];\n\t}\n\n\tif (jas_init()) {\n\t\tabort();\n\t}\n\n\t/* Parse the command line options. */\n\tif (!(cmdopts = cmdopts_parse(argc, argv))) {\n\t\tfprintf(stderr, \"error: cannot parse command line\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tif (cmdopts->version) {\n\t\tprintf(\"%s\\n\", JAS_VERSION);\n\t\tfprintf(stderr, \"libjasper %s\\n\", jas_getversion());\n\t\texit(EXIT_SUCCESS);\n\t}\n\n\tjas_setdbglevel(cmdopts->debug);\n\n\tif (cmdopts->verbose) {\n\t\tcmdinfo();\n\t}\n\n\t/* Open the input image file. */\n\tif (cmdopts->infile) {\n\t\t/* The input image is to be read from a file. */\n\t\tif (!(in = jas_stream_fopen(cmdopts->infile, \"rb\"))) {\n\t\t\tfprintf(stderr, \"error: cannot open input image file %s\\n\",\n\t\t\t cmdopts->infile);\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t} else {\n\t\t/* The input image is to be read from standard input. */\n\t\tif (!(in = jas_stream_fdopen(0, \"rb\"))) {\n\t\t\tfprintf(stderr, \"error: cannot open standard input\\n\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t}\n\n\t/* Open the output image file. */\n\tif (cmdopts->outfile) {\n\t\t/* The output image is to be written to a file. */\n\t\tif (!(out = jas_stream_fopen(cmdopts->outfile, \"w+b\"))) {\n\t\t\tfprintf(stderr, \"error: cannot open output image file %s\\n\",\n\t\t\t cmdopts->outfile);\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t} else {\n\t\t/* The output image is to be written to standard output. */\n\t\tif (!(out = jas_stream_fdopen(1, \"w+b\"))) {\n\t\t\tfprintf(stderr, \"error: cannot open standard output\\n\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t}\n\n\tif (cmdopts->infmt < 0) {\n\t\tif ((cmdopts->infmt = jas_image_getfmt(in)) < 0) {\n\t\t\tfprintf(stderr, \"error: input image has unknown format\\n\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t}\n\n\t/* Get the input image data. */\n\tjas_tmr_start(&dectmr);\n\tif (!(image = jas_image_decode(in, cmdopts->infmt, cmdopts->inopts))) {\n\t\tfprintf(stderr, \"error: cannot load image data\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n\tjas_tmr_stop(&dectmr);\n\tdectime = jas_tmr_get(&dectmr);\n\n\t/* If requested, throw away all of the components except one.\n\t Why might this be desirable? It is a hack, really.\n\t None of the image formats other than the JPEG-2000 ones support\n\t images with two, four, five, or more components. This hack\n\t allows such images to be decoded with the non-JPEG-2000 decoders,\n\t one component at a time. */\n\tnumcmpts = jas_image_numcmpts(image);\n\tif (cmdopts->cmptno >= 0 && cmdopts->cmptno < numcmpts) {\n\t\tfor (i = numcmpts - 1; i >= 0; --i) {\n\t\t\tif (i != cmdopts->cmptno) {\n\t\t\t\tjas_image_delcmpt(image, i);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (cmdopts->srgb) {\n\t\tjas_image_t *newimage;\n\t\tjas_cmprof_t *outprof;\n\t\tjas_eprintf(\"forcing conversion to sRGB\\n\");\n\t\tif (!(outprof = jas_cmprof_createfromclrspc(JAS_CLRSPC_SRGB))) {\n\t\t\tjas_eprintf(\"cannot create sRGB profile\\n\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tif (!(newimage = jas_image_chclrspc(image, outprof, JAS_CMXFORM_INTENT_PER))) {\n\t\t\tjas_eprintf(\"cannot convert to sRGB\\n\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tjas_image_destroy(image);\n\t\tjas_cmprof_destroy(outprof);\n\t\timage = newimage;\n\t}\n\n\t/* Generate the output image data. */\n\tjas_tmr_start(&enctmr);\n\tif (jas_image_encode(image, out, cmdopts->outfmt, cmdopts->outopts)) {\n\t\tfprintf(stderr, \"error: cannot encode image\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n\tjas_stream_flush(out);\n\tjas_tmr_stop(&enctmr);\n\tenctime = jas_tmr_get(&enctmr);\n\n\tif (cmdopts->verbose) {\n\t\tfprintf(stderr, \"decoding time = %f\\n\", dectime);\n\t\tfprintf(stderr, \"encoding time = %f\\n\", enctime);\n\t}\n\n\t/* If this fails, we don't care. */\n\t(void) jas_stream_close(in);\n\n\t/* Close the output image stream. */\n\tif (jas_stream_close(out)) {\n\t\tfprintf(stderr, \"error: cannot close output image file\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tcmdopts_destroy(cmdopts);\n\tjas_image_destroy(image);\n\tjas_image_clearfmts();\n\n\t/* Success at last! :-) */\n\treturn EXIT_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'A new experimental memory allocator has been introduced. The allocator\nis experimental in the sense that its API is not considered stable and\nthe allocator may change or disappear entirely in future versions of\nthe code. This new allocator tracks how much memory is being used by\njas_malloc and friends. A maximum upper bound on the memory usage can be\nset via the experimental API provided and a default value can be set at\nbuild time as well. Such functionality may be useful in run-time\nenvironments where the user wants to be able to limit the amount of\nmemory used by JasPer. This allocator is not used by default.\nNote: This feature needs C11 functionality.\nNote: The memory allocator is not thread safe in its current form.\n\nA new --memory-limit CLI option has been added to the jasper, imginfo,\nimgcmp, and jiv programs. The option is only available when the code is\nbuilt with the new memory allocator.\n\nThe support for my old debug memory allocator from the 1990s has been\npurged from the code. The debug memory allocator is probably not\na very useful thing with the advent of GCC/Clang code sanitizers.\n\nThe safe size_t integer functions no longer set their result upon failure.\nA safe subtract operation was also added.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int dynamicGetbuf(gdIOCtxPtr ctx, void *buf, int len)\n{\n\tint rlen, remain;\n\tdpIOCtxPtr dctx;\n\tdynamicPtr *dp;\n\n\tdctx = (dpIOCtxPtr) ctx;\n\tdp = dctx->dp;\n\n\tremain = dp->logicalSize - dp->pos;\n\tif(remain >= len) {\n\t\trlen = len;\n\t} else {\n\t\tif(remain == 0) {\n\t\t\t/* 2.0.34: EOF is incorrect. We use 0 for\n\t\t\t * errors and EOF, just like fileGetbuf,\n\t\t\t * which is a simple fread() wrapper.\n\t\t\t * TBB. Original bug report: Daniel Cowgill. */\n\t\t\treturn 0; /* NOT EOF */\n\t\t}\n\n\t\trlen = remain;\n\t}\n\n\tmemcpy(buf, (void *) ((char *)dp->data + dp->pos), rlen);\n\tdp->pos += rlen;\n\n\treturn rlen;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Avoid potentially dangerous signed to unsigned conversion\n\nWe make sure to never pass a negative `rlen` as size to memcpy(). See\nalso .\n\nPatch provided by Emmanuel Law.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int ext4_fill_super(struct super_block *sb, void *data, int silent)\n{\n\tchar *orig_data = kstrdup(data, GFP_KERNEL);\n\tstruct buffer_head *bh;\n\tstruct ext4_super_block *es = NULL;\n\tstruct ext4_sb_info *sbi = kzalloc(sizeof(*sbi), GFP_KERNEL);\n\text4_fsblk_t block;\n\text4_fsblk_t sb_block = get_sb_block(&data);\n\text4_fsblk_t logical_sb_block;\n\tunsigned long offset = 0;\n\tunsigned long journal_devnum = 0;\n\tunsigned long def_mount_opts;\n\tstruct inode *root;\n\tconst char *descr;\n\tint ret = -ENOMEM;\n\tint blocksize, clustersize;\n\tunsigned int db_count;\n\tunsigned int i;\n\tint needs_recovery, has_huge_files, has_bigalloc;\n\t__u64 blocks_count;\n\tint err = 0;\n\tunsigned int journal_ioprio = DEFAULT_JOURNAL_IOPRIO;\n\text4_group_t first_not_zeroed;\n\n\tif ((data && !orig_data) || !sbi)\n\t\tgoto out_free_base;\n\n\tsbi->s_blockgroup_lock =\n\t\tkzalloc(sizeof(struct blockgroup_lock), GFP_KERNEL);\n\tif (!sbi->s_blockgroup_lock)\n\t\tgoto out_free_base;\n\n\tsb->s_fs_info = sbi;\n\tsbi->s_sb = sb;\n\tsbi->s_inode_readahead_blks = EXT4_DEF_INODE_READAHEAD_BLKS;\n\tsbi->s_sb_block = sb_block;\n\tif (sb->s_bdev->bd_part)\n\t\tsbi->s_sectors_written_start =\n\t\t\tpart_stat_read(sb->s_bdev->bd_part, sectors[1]);\n\n\t/* Cleanup superblock name */\n\tstrreplace(sb->s_id, '/', '!');\n\n\t/* -EINVAL is default */\n\tret = -EINVAL;\n\tblocksize = sb_min_blocksize(sb, EXT4_MIN_BLOCK_SIZE);\n\tif (!blocksize) {\n\t\text4_msg(sb, KERN_ERR, \"unable to set blocksize\");\n\t\tgoto out_fail;\n\t}\n\n\t/*\n\t * The ext4 superblock will not be buffer aligned for other than 1kB\n\t * block sizes. We need to calculate the offset from buffer start.\n\t */\n\tif (blocksize != EXT4_MIN_BLOCK_SIZE) {\n\t\tlogical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE;\n\t\toffset = do_div(logical_sb_block, blocksize);\n\t} else {\n\t\tlogical_sb_block = sb_block;\n\t}\n\n\tif (!(bh = sb_bread_unmovable(sb, logical_sb_block))) {\n\t\text4_msg(sb, KERN_ERR, \"unable to read superblock\");\n\t\tgoto out_fail;\n\t}\n\t/*\n\t * Note: s_es must be initialized as soon as possible because\n\t * some ext4 macro-instructions depend on its value\n\t */\n\tes = (struct ext4_super_block *) (bh->b_data + offset);\n\tsbi->s_es = es;\n\tsb->s_magic = le16_to_cpu(es->s_magic);\n\tif (sb->s_magic != EXT4_SUPER_MAGIC)\n\t\tgoto cantfind_ext4;\n\tsbi->s_kbytes_written = le64_to_cpu(es->s_kbytes_written);\n\n\t/* Warn if metadata_csum and gdt_csum are both set. */\n\tif (ext4_has_feature_metadata_csum(sb) &&\n\t ext4_has_feature_gdt_csum(sb))\n\t\text4_warning(sb, \"metadata_csum and uninit_bg are \"\n\t\t\t \"redundant flags; please run fsck.\");\n\n\t/* Check for a known checksum algorithm */\n\tif (!ext4_verify_csum_type(sb, es)) {\n\t\text4_msg(sb, KERN_ERR, \"VFS: Found ext4 filesystem with \"\n\t\t\t \"unknown checksum algorithm.\");\n\t\tsilent = 1;\n\t\tgoto cantfind_ext4;\n\t}\n\n\t/* Load the checksum driver */\n\tif (ext4_has_feature_metadata_csum(sb)) {\n\t\tsbi->s_chksum_driver = crypto_alloc_shash(\"crc32c\", 0, 0);\n\t\tif (IS_ERR(sbi->s_chksum_driver)) {\n\t\t\text4_msg(sb, KERN_ERR, \"Cannot load crc32c driver.\");\n\t\t\tret = PTR_ERR(sbi->s_chksum_driver);\n\t\t\tsbi->s_chksum_driver = NULL;\n\t\t\tgoto failed_mount;\n\t\t}\n\t}\n\n\t/* Check superblock checksum */\n\tif (!ext4_superblock_csum_verify(sb, es)) {\n\t\text4_msg(sb, KERN_ERR, \"VFS: Found ext4 filesystem with \"\n\t\t\t \"invalid superblock checksum. Run e2fsck?\");\n\t\tsilent = 1;\n\t\tret = -EFSBADCRC;\n\t\tgoto cantfind_ext4;\n\t}\n\n\t/* Precompute checksum seed for all metadata */\n\tif (ext4_has_feature_csum_seed(sb))\n\t\tsbi->s_csum_seed = le32_to_cpu(es->s_checksum_seed);\n\telse if (ext4_has_metadata_csum(sb))\n\t\tsbi->s_csum_seed = ext4_chksum(sbi, ~0, es->s_uuid,\n\t\t\t\t\t sizeof(es->s_uuid));\n\n\t/* Set defaults before we parse the mount options */\n\tdef_mount_opts = le32_to_cpu(es->s_default_mount_opts);\n\tset_opt(sb, INIT_INODE_TABLE);\n\tif (def_mount_opts & EXT4_DEFM_DEBUG)\n\t\tset_opt(sb, DEBUG);\n\tif (def_mount_opts & EXT4_DEFM_BSDGROUPS)\n\t\tset_opt(sb, GRPID);\n\tif (def_mount_opts & EXT4_DEFM_UID16)\n\t\tset_opt(sb, NO_UID32);\n\t/* xattr user namespace & acls are now defaulted on */\n\tset_opt(sb, XATTR_USER);\n#ifdef CONFIG_EXT4_FS_POSIX_ACL\n\tset_opt(sb, POSIX_ACL);\n#endif\n\t/* don't forget to enable journal_csum when metadata_csum is enabled. */\n\tif (ext4_has_metadata_csum(sb))\n\t\tset_opt(sb, JOURNAL_CHECKSUM);\n\n\tif ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_DATA)\n\t\tset_opt(sb, JOURNAL_DATA);\n\telse if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_ORDERED)\n\t\tset_opt(sb, ORDERED_DATA);\n\telse if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_WBACK)\n\t\tset_opt(sb, WRITEBACK_DATA);\n\n\tif (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_PANIC)\n\t\tset_opt(sb, ERRORS_PANIC);\n\telse if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_CONTINUE)\n\t\tset_opt(sb, ERRORS_CONT);\n\telse\n\t\tset_opt(sb, ERRORS_RO);\n\t/* block_validity enabled by default; disable with noblock_validity */\n\tset_opt(sb, BLOCK_VALIDITY);\n\tif (def_mount_opts & EXT4_DEFM_DISCARD)\n\t\tset_opt(sb, DISCARD);\n\n\tsbi->s_resuid = make_kuid(&init_user_ns, le16_to_cpu(es->s_def_resuid));\n\tsbi->s_resgid = make_kgid(&init_user_ns, le16_to_cpu(es->s_def_resgid));\n\tsbi->s_commit_interval = JBD2_DEFAULT_MAX_COMMIT_AGE * HZ;\n\tsbi->s_min_batch_time = EXT4_DEF_MIN_BATCH_TIME;\n\tsbi->s_max_batch_time = EXT4_DEF_MAX_BATCH_TIME;\n\n\tif ((def_mount_opts & EXT4_DEFM_NOBARRIER) == 0)\n\t\tset_opt(sb, BARRIER);\n\n\t/*\n\t * enable delayed allocation by default\n\t * Use -o nodelalloc to turn it off\n\t */\n\tif (!IS_EXT3_SB(sb) && !IS_EXT2_SB(sb) &&\n\t ((def_mount_opts & EXT4_DEFM_NODELALLOC) == 0))\n\t\tset_opt(sb, DELALLOC);\n\n\t/*\n\t * set default s_li_wait_mult for lazyinit, for the case there is\n\t * no mount option specified.\n\t */\n\tsbi->s_li_wait_mult = EXT4_DEF_LI_WAIT_MULT;\n\n\tif (sbi->s_es->s_mount_opts[0]) {\n\t\tchar *s_mount_opts = kstrndup(sbi->s_es->s_mount_opts,\n\t\t\t\t\t sizeof(sbi->s_es->s_mount_opts),\n\t\t\t\t\t GFP_KERNEL);\n\t\tif (!s_mount_opts)\n\t\t\tgoto failed_mount;\n\t\tif (!parse_options(s_mount_opts, sb, &journal_devnum,\n\t\t\t\t &journal_ioprio, 0)) {\n\t\t\text4_msg(sb, KERN_WARNING,\n\t\t\t\t \"failed to parse options in superblock: %s\",\n\t\t\t\t s_mount_opts);\n\t\t}\n\t\tkfree(s_mount_opts);\n\t}\n\tsbi->s_def_mount_opt = sbi->s_mount_opt;\n\tif (!parse_options((char *) data, sb, &journal_devnum,\n\t\t\t &journal_ioprio, 0))\n\t\tgoto failed_mount;\n\n\tif (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) {\n\t\tprintk_once(KERN_WARNING \"EXT4-fs: Warning: mounting \"\n\t\t\t \"with data=journal disables delayed \"\n\t\t\t \"allocation and O_DIRECT support!\\n\");\n\t\tif (test_opt2(sb, EXPLICIT_DELALLOC)) {\n\t\t\text4_msg(sb, KERN_ERR, \"can't mount with \"\n\t\t\t\t \"both data=journal and delalloc\");\n\t\t\tgoto failed_mount;\n\t\t}\n\t\tif (test_opt(sb, DIOREAD_NOLOCK)) {\n\t\t\text4_msg(sb, KERN_ERR, \"can't mount with \"\n\t\t\t\t \"both data=journal and dioread_nolock\");\n\t\t\tgoto failed_mount;\n\t\t}\n\t\tif (test_opt(sb, DAX)) {\n\t\t\text4_msg(sb, KERN_ERR, \"can't mount with \"\n\t\t\t\t \"both data=journal and dax\");\n\t\t\tgoto failed_mount;\n\t\t}\n\t\tif (test_opt(sb, DELALLOC))\n\t\t\tclear_opt(sb, DELALLOC);\n\t} else {\n\t\tsb->s_iflags |= SB_I_CGROUPWB;\n\t}\n\n\tsb->s_flags = (sb->s_flags & ~MS_POSIXACL) |\n\t\t(test_opt(sb, POSIX_ACL) ? MS_POSIXACL : 0);\n\n\tif (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV &&\n\t (ext4_has_compat_features(sb) ||\n\t ext4_has_ro_compat_features(sb) ||\n\t ext4_has_incompat_features(sb)))\n\t\text4_msg(sb, KERN_WARNING,\n\t\t \"feature flags set on rev 0 fs, \"\n\t\t \"running e2fsck is recommended\");\n\n\tif (es->s_creator_os == cpu_to_le32(EXT4_OS_HURD)) {\n\t\tset_opt2(sb, HURD_COMPAT);\n\t\tif (ext4_has_feature_64bit(sb)) {\n\t\t\text4_msg(sb, KERN_ERR,\n\t\t\t\t \"The Hurd can't support 64-bit file systems\");\n\t\t\tgoto failed_mount;\n\t\t}\n\t}\n\n\tif (IS_EXT2_SB(sb)) {\n\t\tif (ext2_feature_set_ok(sb))\n\t\t\text4_msg(sb, KERN_INFO, \"mounting ext2 file system \"\n\t\t\t\t \"using the ext4 subsystem\");\n\t\telse {\n\t\t\text4_msg(sb, KERN_ERR, \"couldn't mount as ext2 due \"\n\t\t\t\t \"to feature incompatibilities\");\n\t\t\tgoto failed_mount;\n\t\t}\n\t}\n\n\tif (IS_EXT3_SB(sb)) {\n\t\tif (ext3_feature_set_ok(sb))\n\t\t\text4_msg(sb, KERN_INFO, \"mounting ext3 file system \"\n\t\t\t\t \"using the ext4 subsystem\");\n\t\telse {\n\t\t\text4_msg(sb, KERN_ERR, \"couldn't mount as ext3 due \"\n\t\t\t\t \"to feature incompatibilities\");\n\t\t\tgoto failed_mount;\n\t\t}\n\t}\n\n\t/*\n\t * Check feature flags regardless of the revision level, since we\n\t * previously didn't change the revision level when setting the flags,\n\t * so there is a chance incompat flags are set on a rev 0 filesystem.\n\t */\n\tif (!ext4_feature_set_ok(sb, (sb->s_flags & MS_RDONLY)))\n\t\tgoto failed_mount;\n\n\tblocksize = BLOCK_SIZE << le32_to_cpu(es->s_log_block_size);\n\tif (blocksize < EXT4_MIN_BLOCK_SIZE ||\n\t blocksize > EXT4_MAX_BLOCK_SIZE) {\n\t\text4_msg(sb, KERN_ERR,\n\t\t \"Unsupported filesystem blocksize %d (%d log_block_size)\",\n\t\t\t blocksize, le32_to_cpu(es->s_log_block_size));\n\t\tgoto failed_mount;\n\t}\n\tif (le32_to_cpu(es->s_log_block_size) >\n\t (EXT4_MAX_BLOCK_LOG_SIZE - EXT4_MIN_BLOCK_LOG_SIZE)) {\n\t\text4_msg(sb, KERN_ERR,\n\t\t\t \"Invalid log block size: %u\",\n\t\t\t le32_to_cpu(es->s_log_block_size));\n\t\tgoto failed_mount;\n\t}\n\n\tif (le16_to_cpu(sbi->s_es->s_reserved_gdt_blocks) > (blocksize / 4)) {\n\t\text4_msg(sb, KERN_ERR,\n\t\t\t \"Number of reserved GDT blocks insanely large: %d\",\n\t\t\t le16_to_cpu(sbi->s_es->s_reserved_gdt_blocks));\n\t\tgoto failed_mount;\n\t}\n\n\tif (sbi->s_mount_opt & EXT4_MOUNT_DAX) {\n\t\terr = bdev_dax_supported(sb, blocksize);\n\t\tif (err)\n\t\t\tgoto failed_mount;\n\t}\n\n\tif (ext4_has_feature_encrypt(sb) && es->s_encryption_level) {\n\t\text4_msg(sb, KERN_ERR, \"Unsupported encryption level %d\",\n\t\t\t es->s_encryption_level);\n\t\tgoto failed_mount;\n\t}\n\n\tif (sb->s_blocksize != blocksize) {\n\t\t/* Validate the filesystem blocksize */\n\t\tif (!sb_set_blocksize(sb, blocksize)) {\n\t\t\text4_msg(sb, KERN_ERR, \"bad block size %d\",\n\t\t\t\t\tblocksize);\n\t\t\tgoto failed_mount;\n\t\t}\n\n\t\tbrelse(bh);\n\t\tlogical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE;\n\t\toffset = do_div(logical_sb_block, blocksize);\n\t\tbh = sb_bread_unmovable(sb, logical_sb_block);\n\t\tif (!bh) {\n\t\t\text4_msg(sb, KERN_ERR,\n\t\t\t \"Can't read superblock on 2nd try\");\n\t\t\tgoto failed_mount;\n\t\t}\n\t\tes = (struct ext4_super_block *)(bh->b_data + offset);\n\t\tsbi->s_es = es;\n\t\tif (es->s_magic != cpu_to_le16(EXT4_SUPER_MAGIC)) {\n\t\t\text4_msg(sb, KERN_ERR,\n\t\t\t \"Magic mismatch, very weird!\");\n\t\t\tgoto failed_mount;\n\t\t}\n\t}\n\n\thas_huge_files = ext4_has_feature_huge_file(sb);\n\tsbi->s_bitmap_maxbytes = ext4_max_bitmap_size(sb->s_blocksize_bits,\n\t\t\t\t\t\t has_huge_files);\n\tsb->s_maxbytes = ext4_max_size(sb->s_blocksize_bits, has_huge_files);\n\n\tif (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV) {\n\t\tsbi->s_inode_size = EXT4_GOOD_OLD_INODE_SIZE;\n\t\tsbi->s_first_ino = EXT4_GOOD_OLD_FIRST_INO;\n\t} else {\n\t\tsbi->s_inode_size = le16_to_cpu(es->s_inode_size);\n\t\tsbi->s_first_ino = le32_to_cpu(es->s_first_ino);\n\t\tif ((sbi->s_inode_size < EXT4_GOOD_OLD_INODE_SIZE) ||\n\t\t (!is_power_of_2(sbi->s_inode_size)) ||\n\t\t (sbi->s_inode_size > blocksize)) {\n\t\t\text4_msg(sb, KERN_ERR,\n\t\t\t \"unsupported inode size: %d\",\n\t\t\t sbi->s_inode_size);\n\t\t\tgoto failed_mount;\n\t\t}\n\t\tif (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE)\n\t\t\tsb->s_time_gran = 1 << (EXT4_EPOCH_BITS - 2);\n\t}\n\n\tsbi->s_desc_size = le16_to_cpu(es->s_desc_size);\n\tif (ext4_has_feature_64bit(sb)) {\n\t\tif (sbi->s_desc_size < EXT4_MIN_DESC_SIZE_64BIT ||\n\t\t sbi->s_desc_size > EXT4_MAX_DESC_SIZE ||\n\t\t !is_power_of_2(sbi->s_desc_size)) {\n\t\t\text4_msg(sb, KERN_ERR,\n\t\t\t \"unsupported descriptor size %lu\",\n\t\t\t sbi->s_desc_size);\n\t\t\tgoto failed_mount;\n\t\t}\n\t} else\n\t\tsbi->s_desc_size = EXT4_MIN_DESC_SIZE;\n\n\tsbi->s_blocks_per_group = le32_to_cpu(es->s_blocks_per_group);\n\tsbi->s_inodes_per_group = le32_to_cpu(es->s_inodes_per_group);\n\n\tsbi->s_inodes_per_block = blocksize / EXT4_INODE_SIZE(sb);\n\tif (sbi->s_inodes_per_block == 0)\n\t\tgoto cantfind_ext4;\n\tif (sbi->s_inodes_per_group < sbi->s_inodes_per_block ||\n\t sbi->s_inodes_per_group > blocksize * 8) {\n\t\text4_msg(sb, KERN_ERR, \"invalid inodes per group: %lu\\n\",\n\t\t\t sbi->s_blocks_per_group);\n\t\tgoto failed_mount;\n\t}\n\tsbi->s_itb_per_group = sbi->s_inodes_per_group /\n\t\t\t\t\tsbi->s_inodes_per_block;\n\tsbi->s_desc_per_block = blocksize / EXT4_DESC_SIZE(sb);\n\tsbi->s_sbh = bh;\n\tsbi->s_mount_state = le16_to_cpu(es->s_state);\n\tsbi->s_addr_per_block_bits = ilog2(EXT4_ADDR_PER_BLOCK(sb));\n\tsbi->s_desc_per_block_bits = ilog2(EXT4_DESC_PER_BLOCK(sb));\n\n\tfor (i = 0; i < 4; i++)\n\t\tsbi->s_hash_seed[i] = le32_to_cpu(es->s_hash_seed[i]);\n\tsbi->s_def_hash_version = es->s_def_hash_version;\n\tif (ext4_has_feature_dir_index(sb)) {\n\t\ti = le32_to_cpu(es->s_flags);\n\t\tif (i & EXT2_FLAGS_UNSIGNED_HASH)\n\t\t\tsbi->s_hash_unsigned = 3;\n\t\telse if ((i & EXT2_FLAGS_SIGNED_HASH) == 0) {\n#ifdef __CHAR_UNSIGNED__\n\t\t\tif (!(sb->s_flags & MS_RDONLY))\n\t\t\t\tes->s_flags |=\n\t\t\t\t\tcpu_to_le32(EXT2_FLAGS_UNSIGNED_HASH);\n\t\t\tsbi->s_hash_unsigned = 3;\n#else\n\t\t\tif (!(sb->s_flags & MS_RDONLY))\n\t\t\t\tes->s_flags |=\n\t\t\t\t\tcpu_to_le32(EXT2_FLAGS_SIGNED_HASH);\n#endif\n\t\t}\n\t}\n\n\t/* Handle clustersize */\n\tclustersize = BLOCK_SIZE << le32_to_cpu(es->s_log_cluster_size);\n\thas_bigalloc = ext4_has_feature_bigalloc(sb);\n\tif (has_bigalloc) {\n\t\tif (clustersize < blocksize) {\n\t\t\text4_msg(sb, KERN_ERR,\n\t\t\t\t \"cluster size (%d) smaller than \"\n\t\t\t\t \"block size (%d)\", clustersize, blocksize);\n\t\t\tgoto failed_mount;\n\t\t}\n\t\tif (le32_to_cpu(es->s_log_cluster_size) >\n\t\t (EXT4_MAX_CLUSTER_LOG_SIZE - EXT4_MIN_BLOCK_LOG_SIZE)) {\n\t\t\text4_msg(sb, KERN_ERR,\n\t\t\t\t \"Invalid log cluster size: %u\",\n\t\t\t\t le32_to_cpu(es->s_log_cluster_size));\n\t\t\tgoto failed_mount;\n\t\t}\n\t\tsbi->s_cluster_bits = le32_to_cpu(es->s_log_cluster_size) -\n\t\t\tle32_to_cpu(es->s_log_block_size);\n\t\tsbi->s_clusters_per_group =\n\t\t\tle32_to_cpu(es->s_clusters_per_group);\n\t\tif (sbi->s_clusters_per_group > blocksize * 8) {\n\t\t\text4_msg(sb, KERN_ERR,\n\t\t\t\t \"#clusters per group too big: %lu\",\n\t\t\t\t sbi->s_clusters_per_group);\n\t\t\tgoto failed_mount;\n\t\t}\n\t\tif (sbi->s_blocks_per_group !=\n\t\t (sbi->s_clusters_per_group * (clustersize / blocksize))) {\n\t\t\text4_msg(sb, KERN_ERR, \"blocks per group (%lu) and \"\n\t\t\t\t \"clusters per group (%lu) inconsistent\",\n\t\t\t\t sbi->s_blocks_per_group,\n\t\t\t\t sbi->s_clusters_per_group);\n\t\t\tgoto failed_mount;\n\t\t}\n\t} else {\n\t\tif (clustersize != blocksize) {\n\t\t\text4_warning(sb, \"fragment/cluster size (%d) != \"\n\t\t\t\t \"block size (%d)\", clustersize,\n\t\t\t\t blocksize);\n\t\t\tclustersize = blocksize;\n\t\t}\n\t\tif (sbi->s_blocks_per_group > blocksize * 8) {\n\t\t\text4_msg(sb, KERN_ERR,\n\t\t\t\t \"#blocks per group too big: %lu\",\n\t\t\t\t sbi->s_blocks_per_group);\n\t\t\tgoto failed_mount;\n\t\t}\n\t\tsbi->s_clusters_per_group = sbi->s_blocks_per_group;\n\t\tsbi->s_cluster_bits = 0;\n\t}\n\tsbi->s_cluster_ratio = clustersize / blocksize;\n\n\t/* Do we have standard group size of clustersize * 8 blocks ? */\n\tif (sbi->s_blocks_per_group == clustersize << 3)\n\t\tset_opt2(sb, STD_GROUP_SIZE);\n\n\t/*\n\t * Test whether we have more sectors than will fit in sector_t,\n\t * and whether the max offset is addressable by the page cache.\n\t */\n\terr = generic_check_addressable(sb->s_blocksize_bits,\n\t\t\t\t\text4_blocks_count(es));\n\tif (err) {\n\t\text4_msg(sb, KERN_ERR, \"filesystem\"\n\t\t\t \" too large to mount safely on this system\");\n\t\tif (sizeof(sector_t) < 8)\n\t\t\text4_msg(sb, KERN_WARNING, \"CONFIG_LBDAF not enabled\");\n\t\tgoto failed_mount;\n\t}\n\n\tif (EXT4_BLOCKS_PER_GROUP(sb) == 0)\n\t\tgoto cantfind_ext4;\n\n\t/* check blocks count against device size */\n\tblocks_count = sb->s_bdev->bd_inode->i_size >> sb->s_blocksize_bits;\n\tif (blocks_count && ext4_blocks_count(es) > blocks_count) {\n\t\text4_msg(sb, KERN_WARNING, \"bad geometry: block count %llu \"\n\t\t \"exceeds size of device (%llu blocks)\",\n\t\t ext4_blocks_count(es), blocks_count);\n\t\tgoto failed_mount;\n\t}\n\n\t/*\n\t * It makes no sense for the first data block to be beyond the end\n\t * of the filesystem.\n\t */\n\tif (le32_to_cpu(es->s_first_data_block) >= ext4_blocks_count(es)) {\n\t\text4_msg(sb, KERN_WARNING, \"bad geometry: first data \"\n\t\t\t \"block %u is beyond end of filesystem (%llu)\",\n\t\t\t le32_to_cpu(es->s_first_data_block),\n\t\t\t ext4_blocks_count(es));\n\t\tgoto failed_mount;\n\t}\n\tblocks_count = (ext4_blocks_count(es) -\n\t\t\tle32_to_cpu(es->s_first_data_block) +\n\t\t\tEXT4_BLOCKS_PER_GROUP(sb) - 1);\n\tdo_div(blocks_count, EXT4_BLOCKS_PER_GROUP(sb));\n\tif (blocks_count > ((uint64_t)1<<32) - EXT4_DESC_PER_BLOCK(sb)) {\n\t\text4_msg(sb, KERN_WARNING, \"groups count too large: %u \"\n\t\t \"(block count %llu, first data block %u, \"\n\t\t \"blocks per group %lu)\", sbi->s_groups_count,\n\t\t ext4_blocks_count(es),\n\t\t le32_to_cpu(es->s_first_data_block),\n\t\t EXT4_BLOCKS_PER_GROUP(sb));\n\t\tgoto failed_mount;\n\t}\n\tsbi->s_groups_count = blocks_count;\n\tsbi->s_blockfile_groups = min_t(ext4_group_t, sbi->s_groups_count,\n\t\t\t(EXT4_MAX_BLOCK_FILE_PHYS / EXT4_BLOCKS_PER_GROUP(sb)));\n\tdb_count = (sbi->s_groups_count + EXT4_DESC_PER_BLOCK(sb) - 1) /\n\t\t EXT4_DESC_PER_BLOCK(sb);\n\tsbi->s_group_desc = ext4_kvmalloc(db_count *\n\t\t\t\t\t sizeof(struct buffer_head *),\n\t\t\t\t\t GFP_KERNEL);\n\tif (sbi->s_group_desc == NULL) {\n\t\text4_msg(sb, KERN_ERR, \"not enough memory\");\n\t\tret = -ENOMEM;\n\t\tgoto failed_mount;\n\t}\n\n\tbgl_lock_init(sbi->s_blockgroup_lock);\n\n\tfor (i = 0; i < db_count; i++) {\n\t\tblock = descriptor_loc(sb, logical_sb_block, i);\n\t\tsbi->s_group_desc[i] = sb_bread_unmovable(sb, block);\n\t\tif (!sbi->s_group_desc[i]) {\n\t\t\text4_msg(sb, KERN_ERR,\n\t\t\t \"can't read group descriptor %d\", i);\n\t\t\tdb_count = i;\n\t\t\tgoto failed_mount2;\n\t\t}\n\t}\n\tif (!ext4_check_descriptors(sb, logical_sb_block, &first_not_zeroed)) {\n\t\text4_msg(sb, KERN_ERR, \"group descriptors corrupted!\");\n\t\tret = -EFSCORRUPTED;\n\t\tgoto failed_mount2;\n\t}\n\n\tsbi->s_gdb_count = db_count;\n\tget_random_bytes(&sbi->s_next_generation, sizeof(u32));\n\tspin_lock_init(&sbi->s_next_gen_lock);\n\n\tsetup_timer(&sbi->s_err_report, print_daily_error_info,\n\t\t(unsigned long) sb);\n\n\t/* Register extent status tree shrinker */\n\tif (ext4_es_register_shrinker(sbi))\n\t\tgoto failed_mount3;\n\n\tsbi->s_stripe = ext4_get_stripe_size(sbi);\n\tsbi->s_extent_max_zeroout_kb = 32;\n\n\t/*\n\t * set up enough so that it can read an inode\n\t */\n\tsb->s_op = &ext4_sops;\n\tsb->s_export_op = &ext4_export_ops;\n\tsb->s_xattr = ext4_xattr_handlers;\n\tsb->s_cop = &ext4_cryptops;\n#ifdef CONFIG_QUOTA\n\tsb->dq_op = &ext4_quota_operations;\n\tif (ext4_has_feature_quota(sb))\n\t\tsb->s_qcop = &dquot_quotactl_sysfile_ops;\n\telse\n\t\tsb->s_qcop = &ext4_qctl_operations;\n\tsb->s_quota_types = QTYPE_MASK_USR | QTYPE_MASK_GRP | QTYPE_MASK_PRJ;\n#endif\n\tmemcpy(sb->s_uuid, es->s_uuid, sizeof(es->s_uuid));\n\n\tINIT_LIST_HEAD(&sbi->s_orphan); /* unlinked but open files */\n\tmutex_init(&sbi->s_orphan_lock);\n\n\tsb->s_root = NULL;\n\n\tneeds_recovery = (es->s_last_orphan != 0 ||\n\t\t\t ext4_has_feature_journal_needs_recovery(sb));\n\n\tif (ext4_has_feature_mmp(sb) && !(sb->s_flags & MS_RDONLY))\n\t\tif (ext4_multi_mount_protect(sb, le64_to_cpu(es->s_mmp_block)))\n\t\t\tgoto failed_mount3a;\n\n\t/*\n\t * The first inode we look at is the journal inode. Don't try\n\t * root first: it may be modified in the journal!\n\t */\n\tif (!test_opt(sb, NOLOAD) && ext4_has_feature_journal(sb)) {\n\t\tif (ext4_load_journal(sb, es, journal_devnum))\n\t\t\tgoto failed_mount3a;\n\t} else if (test_opt(sb, NOLOAD) && !(sb->s_flags & MS_RDONLY) &&\n\t\t ext4_has_feature_journal_needs_recovery(sb)) {\n\t\text4_msg(sb, KERN_ERR, \"required journal recovery \"\n\t\t \"suppressed and not mounted read-only\");\n\t\tgoto failed_mount_wq;\n\t} else {\n\t\t/* Nojournal mode, all journal mount options are illegal */\n\t\tif (test_opt2(sb, EXPLICIT_JOURNAL_CHECKSUM)) {\n\t\t\text4_msg(sb, KERN_ERR, \"can't mount with \"\n\t\t\t\t \"journal_checksum, fs mounted w/o journal\");\n\t\t\tgoto failed_mount_wq;\n\t\t}\n\t\tif (test_opt(sb, JOURNAL_ASYNC_COMMIT)) {\n\t\t\text4_msg(sb, KERN_ERR, \"can't mount with \"\n\t\t\t\t \"journal_async_commit, fs mounted w/o journal\");\n\t\t\tgoto failed_mount_wq;\n\t\t}\n\t\tif (sbi->s_commit_interval != JBD2_DEFAULT_MAX_COMMIT_AGE*HZ) {\n\t\t\text4_msg(sb, KERN_ERR, \"can't mount with \"\n\t\t\t\t \"commit=%lu, fs mounted w/o journal\",\n\t\t\t\t sbi->s_commit_interval / HZ);\n\t\t\tgoto failed_mount_wq;\n\t\t}\n\t\tif (EXT4_MOUNT_DATA_FLAGS &\n\t\t (sbi->s_mount_opt ^ sbi->s_def_mount_opt)) {\n\t\t\text4_msg(sb, KERN_ERR, \"can't mount with \"\n\t\t\t\t \"data=, fs mounted w/o journal\");\n\t\t\tgoto failed_mount_wq;\n\t\t}\n\t\tsbi->s_def_mount_opt &= EXT4_MOUNT_JOURNAL_CHECKSUM;\n\t\tclear_opt(sb, JOURNAL_CHECKSUM);\n\t\tclear_opt(sb, DATA_FLAGS);\n\t\tsbi->s_journal = NULL;\n\t\tneeds_recovery = 0;\n\t\tgoto no_journal;\n\t}\n\n\tif (ext4_has_feature_64bit(sb) &&\n\t !jbd2_journal_set_features(EXT4_SB(sb)->s_journal, 0, 0,\n\t\t\t\t JBD2_FEATURE_INCOMPAT_64BIT)) {\n\t\text4_msg(sb, KERN_ERR, \"Failed to set 64-bit journal feature\");\n\t\tgoto failed_mount_wq;\n\t}\n\n\tif (!set_journal_csum_feature_set(sb)) {\n\t\text4_msg(sb, KERN_ERR, \"Failed to set journal checksum \"\n\t\t\t \"feature set\");\n\t\tgoto failed_mount_wq;\n\t}\n\n\t/* We have now updated the journal if required, so we can\n\t * validate the data journaling mode. */\n\tswitch (test_opt(sb, DATA_FLAGS)) {\n\tcase 0:\n\t\t/* No mode set, assume a default based on the journal\n\t\t * capabilities: ORDERED_DATA if the journal can\n\t\t * cope, else JOURNAL_DATA\n\t\t */\n\t\tif (jbd2_journal_check_available_features\n\t\t (sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE))\n\t\t\tset_opt(sb, ORDERED_DATA);\n\t\telse\n\t\t\tset_opt(sb, JOURNAL_DATA);\n\t\tbreak;\n\n\tcase EXT4_MOUNT_ORDERED_DATA:\n\tcase EXT4_MOUNT_WRITEBACK_DATA:\n\t\tif (!jbd2_journal_check_available_features\n\t\t (sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) {\n\t\t\text4_msg(sb, KERN_ERR, \"Journal does not support \"\n\t\t\t \"requested data journaling mode\");\n\t\t\tgoto failed_mount_wq;\n\t\t}\n\tdefault:\n\t\tbreak;\n\t}\n\tset_task_ioprio(sbi->s_journal->j_task, journal_ioprio);\n\n\tsbi->s_journal->j_commit_callback = ext4_journal_commit_callback;\n\nno_journal:\n\tsbi->s_mb_cache = ext4_xattr_create_cache();\n\tif (!sbi->s_mb_cache) {\n\t\text4_msg(sb, KERN_ERR, \"Failed to create an mb_cache\");\n\t\tgoto failed_mount_wq;\n\t}\n\n\tif ((DUMMY_ENCRYPTION_ENABLED(sbi) || ext4_has_feature_encrypt(sb)) &&\n\t (blocksize != PAGE_SIZE)) {\n\t\text4_msg(sb, KERN_ERR,\n\t\t\t \"Unsupported blocksize for fs encryption\");\n\t\tgoto failed_mount_wq;\n\t}\n\n\tif (DUMMY_ENCRYPTION_ENABLED(sbi) && !(sb->s_flags & MS_RDONLY) &&\n\t !ext4_has_feature_encrypt(sb)) {\n\t\text4_set_feature_encrypt(sb);\n\t\text4_commit_super(sb, 1);\n\t}\n\n\t/*\n\t * Get the # of file system overhead blocks from the\n\t * superblock if present.\n\t */\n\tif (es->s_overhead_clusters)\n\t\tsbi->s_overhead = le32_to_cpu(es->s_overhead_clusters);\n\telse {\n\t\terr = ext4_calculate_overhead(sb);\n\t\tif (err)\n\t\t\tgoto failed_mount_wq;\n\t}\n\n\t/*\n\t * The maximum number of concurrent works can be high and\n\t * concurrency isn't really necessary. Limit it to 1.\n\t */\n\tEXT4_SB(sb)->rsv_conversion_wq =\n\t\talloc_workqueue(\"ext4-rsv-conversion\", WQ_MEM_RECLAIM | WQ_UNBOUND, 1);\n\tif (!EXT4_SB(sb)->rsv_conversion_wq) {\n\t\tprintk(KERN_ERR \"EXT4-fs: failed to create workqueue\\n\");\n\t\tret = -ENOMEM;\n\t\tgoto failed_mount4;\n\t}\n\n\t/*\n\t * The jbd2_journal_load will have done any necessary log recovery,\n\t * so we can safely mount the rest of the filesystem now.\n\t */\n\n\troot = ext4_iget(sb, EXT4_ROOT_INO);\n\tif (IS_ERR(root)) {\n\t\text4_msg(sb, KERN_ERR, \"get root inode failed\");\n\t\tret = PTR_ERR(root);\n\t\troot = NULL;\n\t\tgoto failed_mount4;\n\t}\n\tif (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) {\n\t\text4_msg(sb, KERN_ERR, \"corrupt root inode, run e2fsck\");\n\t\tiput(root);\n\t\tgoto failed_mount4;\n\t}\n\tsb->s_root = d_make_root(root);\n\tif (!sb->s_root) {\n\t\text4_msg(sb, KERN_ERR, \"get root dentry failed\");\n\t\tret = -ENOMEM;\n\t\tgoto failed_mount4;\n\t}\n\n\tif (ext4_setup_super(sb, es, sb->s_flags & MS_RDONLY))\n\t\tsb->s_flags |= MS_RDONLY;\n\n\t/* determine the minimum size of new large inodes, if present */\n\tif (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE) {\n\t\tsbi->s_want_extra_isize = sizeof(struct ext4_inode) -\n\t\t\t\t\t\t EXT4_GOOD_OLD_INODE_SIZE;\n\t\tif (ext4_has_feature_extra_isize(sb)) {\n\t\t\tif (sbi->s_want_extra_isize <\n\t\t\t le16_to_cpu(es->s_want_extra_isize))\n\t\t\t\tsbi->s_want_extra_isize =\n\t\t\t\t\tle16_to_cpu(es->s_want_extra_isize);\n\t\t\tif (sbi->s_want_extra_isize <\n\t\t\t le16_to_cpu(es->s_min_extra_isize))\n\t\t\t\tsbi->s_want_extra_isize =\n\t\t\t\t\tle16_to_cpu(es->s_min_extra_isize);\n\t\t}\n\t}\n\t/* Check if enough inode space is available */\n\tif (EXT4_GOOD_OLD_INODE_SIZE + sbi->s_want_extra_isize >\n\t\t\t\t\t\t\tsbi->s_inode_size) {\n\t\tsbi->s_want_extra_isize = sizeof(struct ext4_inode) -\n\t\t\t\t\t\t EXT4_GOOD_OLD_INODE_SIZE;\n\t\text4_msg(sb, KERN_INFO, \"required extra inode space not\"\n\t\t\t \"available\");\n\t}\n\n\text4_set_resv_clusters(sb);\n\n\terr = ext4_setup_system_zone(sb);\n\tif (err) {\n\t\text4_msg(sb, KERN_ERR, \"failed to initialize system \"\n\t\t\t \"zone (%d)\", err);\n\t\tgoto failed_mount4a;\n\t}\n\n\text4_ext_init(sb);\n\terr = ext4_mb_init(sb);\n\tif (err) {\n\t\text4_msg(sb, KERN_ERR, \"failed to initialize mballoc (%d)\",\n\t\t\t err);\n\t\tgoto failed_mount5;\n\t}\n\n\tblock = ext4_count_free_clusters(sb);\n\text4_free_blocks_count_set(sbi->s_es, \n\t\t\t\t EXT4_C2B(sbi, block));\n\terr = percpu_counter_init(&sbi->s_freeclusters_counter, block,\n\t\t\t\t GFP_KERNEL);\n\tif (!err) {\n\t\tunsigned long freei = ext4_count_free_inodes(sb);\n\t\tsbi->s_es->s_free_inodes_count = cpu_to_le32(freei);\n\t\terr = percpu_counter_init(&sbi->s_freeinodes_counter, freei,\n\t\t\t\t\t GFP_KERNEL);\n\t}\n\tif (!err)\n\t\terr = percpu_counter_init(&sbi->s_dirs_counter,\n\t\t\t\t\t ext4_count_dirs(sb), GFP_KERNEL);\n\tif (!err)\n\t\terr = percpu_counter_init(&sbi->s_dirtyclusters_counter, 0,\n\t\t\t\t\t GFP_KERNEL);\n\tif (!err)\n\t\terr = percpu_init_rwsem(&sbi->s_journal_flag_rwsem);\n\n\tif (err) {\n\t\text4_msg(sb, KERN_ERR, \"insufficient memory\");\n\t\tgoto failed_mount6;\n\t}\n\n\tif (ext4_has_feature_flex_bg(sb))\n\t\tif (!ext4_fill_flex_info(sb)) {\n\t\t\text4_msg(sb, KERN_ERR,\n\t\t\t \"unable to initialize \"\n\t\t\t \"flex_bg meta info!\");\n\t\t\tgoto failed_mount6;\n\t\t}\n\n\terr = ext4_register_li_request(sb, first_not_zeroed);\n\tif (err)\n\t\tgoto failed_mount6;\n\n\terr = ext4_register_sysfs(sb);\n\tif (err)\n\t\tgoto failed_mount7;\n\n#ifdef CONFIG_QUOTA\n\t/* Enable quota usage during mount. */\n\tif (ext4_has_feature_quota(sb) && !(sb->s_flags & MS_RDONLY)) {\n\t\terr = ext4_enable_quotas(sb);\n\t\tif (err)\n\t\t\tgoto failed_mount8;\n\t}\n#endif /* CONFIG_QUOTA */\n\n\tEXT4_SB(sb)->s_mount_state |= EXT4_ORPHAN_FS;\n\text4_orphan_cleanup(sb, es);\n\tEXT4_SB(sb)->s_mount_state &= ~EXT4_ORPHAN_FS;\n\tif (needs_recovery) {\n\t\text4_msg(sb, KERN_INFO, \"recovery complete\");\n\t\text4_mark_recovery_complete(sb, es);\n\t}\n\tif (EXT4_SB(sb)->s_journal) {\n\t\tif (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)\n\t\t\tdescr = \" journalled data mode\";\n\t\telse if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA)\n\t\t\tdescr = \" ordered data mode\";\n\t\telse\n\t\t\tdescr = \" writeback data mode\";\n\t} else\n\t\tdescr = \"out journal\";\n\n\tif (test_opt(sb, DISCARD)) {\n\t\tstruct request_queue *q = bdev_get_queue(sb->s_bdev);\n\t\tif (!blk_queue_discard(q))\n\t\t\text4_msg(sb, KERN_WARNING,\n\t\t\t\t \"mounting with \\\"discard\\\" option, but \"\n\t\t\t\t \"the device does not support discard\");\n\t}\n\n\tif (___ratelimit(&ext4_mount_msg_ratelimit, \"EXT4-fs mount\"))\n\t\text4_msg(sb, KERN_INFO, \"mounted filesystem with%s. \"\n\t\t\t \"Opts: %.*s%s%s\", descr,\n\t\t\t (int) sizeof(sbi->s_es->s_mount_opts),\n\t\t\t sbi->s_es->s_mount_opts,\n\t\t\t *sbi->s_es->s_mount_opts ? \"; \" : \"\", orig_data);\n\n\tif (es->s_error_count)\n\t\tmod_timer(&sbi->s_err_report, jiffies + 300*HZ); /* 5 minutes */\n\n\t/* Enable message ratelimiting. Default is 10 messages per 5 secs. */\n\tratelimit_state_init(&sbi->s_err_ratelimit_state, 5 * HZ, 10);\n\tratelimit_state_init(&sbi->s_warning_ratelimit_state, 5 * HZ, 10);\n\tratelimit_state_init(&sbi->s_msg_ratelimit_state, 5 * HZ, 10);\n\n\tkfree(orig_data);\n#ifdef CONFIG_EXT4_FS_ENCRYPTION\n\tmemcpy(sbi->key_prefix, EXT4_KEY_DESC_PREFIX,\n\t\t\t\tEXT4_KEY_DESC_PREFIX_SIZE);\n\tsbi->key_prefix_size = EXT4_KEY_DESC_PREFIX_SIZE;\n#endif\n\treturn 0;\n\ncantfind_ext4:\n\tif (!silent)\n\t\text4_msg(sb, KERN_ERR, \"VFS: Can't find ext4 filesystem\");\n\tgoto failed_mount;\n\n#ifdef CONFIG_QUOTA\nfailed_mount8:\n\text4_unregister_sysfs(sb);\n#endif\nfailed_mount7:\n\text4_unregister_li_request(sb);\nfailed_mount6:\n\text4_mb_release(sb);\n\tif (sbi->s_flex_groups)\n\t\tkvfree(sbi->s_flex_groups);\n\tpercpu_counter_destroy(&sbi->s_freeclusters_counter);\n\tpercpu_counter_destroy(&sbi->s_freeinodes_counter);\n\tpercpu_counter_destroy(&sbi->s_dirs_counter);\n\tpercpu_counter_destroy(&sbi->s_dirtyclusters_counter);\nfailed_mount5:\n\text4_ext_release(sb);\n\text4_release_system_zone(sb);\nfailed_mount4a:\n\tdput(sb->s_root);\n\tsb->s_root = NULL;\nfailed_mount4:\n\text4_msg(sb, KERN_ERR, \"mount failed\");\n\tif (EXT4_SB(sb)->rsv_conversion_wq)\n\t\tdestroy_workqueue(EXT4_SB(sb)->rsv_conversion_wq);\nfailed_mount_wq:\n\tif (sbi->s_mb_cache) {\n\t\text4_xattr_destroy_cache(sbi->s_mb_cache);\n\t\tsbi->s_mb_cache = NULL;\n\t}\n\tif (sbi->s_journal) {\n\t\tjbd2_journal_destroy(sbi->s_journal);\n\t\tsbi->s_journal = NULL;\n\t}\nfailed_mount3a:\n\text4_es_unregister_shrinker(sbi);\nfailed_mount3:\n\tdel_timer_sync(&sbi->s_err_report);\n\tif (sbi->s_mmp_tsk)\n\t\tkthread_stop(sbi->s_mmp_tsk);\nfailed_mount2:\n\tfor (i = 0; i < db_count; i++)\n\t\tbrelse(sbi->s_group_desc[i]);\n\tkvfree(sbi->s_group_desc);\nfailed_mount:\n\tif (sbi->s_chksum_driver)\n\t\tcrypto_free_shash(sbi->s_chksum_driver);\n#ifdef CONFIG_QUOTA\n\tfor (i = 0; i < EXT4_MAXQUOTAS; i++)\n\t\tkfree(sbi->s_qf_names[i]);\n#endif\n\text4_blkdev_remove(sbi);\n\tbrelse(bh);\nout_fail:\n\tsb->s_fs_info = NULL;\n\tkfree(sbi->s_blockgroup_lock);\nout_free_base:\n\tkfree(sbi);\n\tkfree(orig_data);\n\treturn err ? err : ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'ext4: validate s_first_meta_bg at mount time\n\nRalf Spenneberg reported that he hit a kernel crash when mounting a\nmodified ext4 image. And it turns out that kernel crashed when\ncalculating fs overhead (ext4_calculate_overhead()), this is because\nthe image has very large s_first_meta_bg (debug code shows it's\n842150400), and ext4 overruns the memory in count_overhead() when\nsetting bitmap buffer, which is PAGE_SIZE.\n\next4_calculate_overhead():\n buf = get_zeroed_page(GFP_NOFS); <=== PAGE_SIZE buffer\n blks = count_overhead(sb, i, buf);\n\ncount_overhead():\n for (j = ext4_bg_num_gdb(sb, grp); j > 0; j--) { <=== j = 842150400\n ext4_set_bit(EXT4_B2C(sbi, s++), buf); <=== buffer overrun\n count++;\n }\n\nThis can be reproduced easily for me by this script:\n\n #!/bin/bash\n rm -f fs.img\n mkdir -p /mnt/ext4\n fallocate -l 16M fs.img\n mke2fs -t ext4 -O bigalloc,meta_bg,^resize_inode -F fs.img\n debugfs -w -R \"ssv first_meta_bg 842150400\" fs.img\n mount -o loop fs.img /mnt/ext4\n\nFix it by validating s_first_meta_bg first at mount time, and\nrefusing to mount if its value exceeds the largest possible meta_bg\nnumber.\n\nReported-by: Ralf Spenneberg \nSigned-off-by: Eryu Guan \nSigned-off-by: Theodore Ts'o \nReviewed-by: Andreas Dilger '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int jpc_dec_tiledecode(jpc_dec_t *dec, jpc_dec_tile_t *tile)\n{\n\tint i;\n\tint j;\n\tjpc_dec_tcomp_t *tcomp;\n\tjpc_dec_rlvl_t *rlvl;\n\tjpc_dec_band_t *band;\n\tint compno;\n\tint rlvlno;\n\tint bandno;\n\tint adjust;\n\tint v;\n\tjpc_dec_ccp_t *ccp;\n\tjpc_dec_cmpt_t *cmpt;\n\n\tif (jpc_dec_decodecblks(dec, tile)) {\n\t\tjas_eprintf(\"jpc_dec_decodecblks failed\\n\");\n\t\treturn -1;\n\t}\n\n\t/* Perform dequantization. */\n\tfor (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps;\n\t ++compno, ++tcomp) {\n\t\tccp = &tile->cp->ccps[compno];\n\t\tfor (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls;\n\t\t ++rlvlno, ++rlvl) {\n\t\t\tif (!rlvl->bands) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (bandno = 0, band = rlvl->bands;\n\t\t\t bandno < rlvl->numbands; ++bandno, ++band) {\n\t\t\t\tif (!band->data) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tjpc_undo_roi(band->data, band->roishift, ccp->roishift -\n\t\t\t\t band->roishift, band->numbps);\n\t\t\t\tif (tile->realmode) {\n\t\t\t\t\tjas_matrix_asl(band->data, JPC_FIX_FRACBITS);\n\t\t\t\t\tjpc_dequantize(band->data, band->absstepsize);\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\n\t/* Apply an inverse wavelet transform if necessary. */\n\tfor (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps;\n\t ++compno, ++tcomp) {\n\t\tccp = &tile->cp->ccps[compno];\n\t\tjpc_tsfb_synthesize(tcomp->tsfb, tcomp->data);\n\t}\n\n\n\t/* Apply an inverse intercomponent transform if necessary. */\n\tswitch (tile->cp->mctid) {\n\tcase JPC_MCT_RCT:\n\t\tif (dec->numcomps < 3) {\n\t\t\tjas_eprintf(\"RCT requires at least three components\\n\");\n\t\t\treturn -1;\n\t\t}\n\t\tjpc_irct(tile->tcomps[0].data, tile->tcomps[1].data,\n\t\t tile->tcomps[2].data);\n\t\tbreak;\n\tcase JPC_MCT_ICT:\n\t\tif (dec->numcomps < 3) {\n\t\t\tjas_eprintf(\"ICT requires at least three components\\n\");\n\t\t\treturn -1;\n\t\t}\n\t\tjpc_iict(tile->tcomps[0].data, tile->tcomps[1].data,\n\t\t tile->tcomps[2].data);\n\t\tbreak;\n\t}\n\n\t/* Perform rounding and convert to integer values. */\n\tif (tile->realmode) {\n\t\tfor (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps;\n\t\t ++compno, ++tcomp) {\n\t\t\tfor (i = 0; i < jas_matrix_numrows(tcomp->data); ++i) {\n\t\t\t\tfor (j = 0; j < jas_matrix_numcols(tcomp->data); ++j) {\n\t\t\t\t\tv = jas_matrix_get(tcomp->data, i, j);\n\t\t\t\t\tv = jpc_fix_round(v);\n\t\t\t\t\tjas_matrix_set(tcomp->data, i, j, jpc_fixtoint(v));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/* Perform level shift. */\n\tfor (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno <\n\t dec->numcomps; ++compno, ++tcomp, ++cmpt) {\n\t\tadjust = cmpt->sgnd ? 0 : (1 << (cmpt->prec - 1));\n\t\tfor (i = 0; i < jas_matrix_numrows(tcomp->data); ++i) {\n\t\t\tfor (j = 0; j < jas_matrix_numcols(tcomp->data); ++j) {\n\t\t\t\t*jas_matrix_getref(tcomp->data, i, j) += adjust;\n\t\t\t}\n\t\t}\n\t}\n\n\t/* Perform clipping. */\n\tfor (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno <\n\t dec->numcomps; ++compno, ++tcomp, ++cmpt) {\n\t\tjpc_fix_t mn;\n\t\tjpc_fix_t mx;\n\t\tmn = cmpt->sgnd ? (-(1 << (cmpt->prec - 1))) : (0);\n\t\tmx = cmpt->sgnd ? ((1 << (cmpt->prec - 1)) - 1) : ((1 <<\n\t\t cmpt->prec) - 1);\n\t\tjas_matrix_clip(tcomp->data, mn, mx);\n\t}\n\n\t/* XXX need to free tsfb struct */\n\n\t/* Write the data for each component of the image. */\n\tfor (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno <\n\t dec->numcomps; ++compno, ++tcomp, ++cmpt) {\n\t\tif (jas_image_writecmpt(dec->image, compno, tcomp->xstart -\n\t\t JPC_CEILDIV(dec->xstart, cmpt->hstep), tcomp->ystart -\n\t\t JPC_CEILDIV(dec->ystart, cmpt->vstep), jas_matrix_numcols(\n\t\t tcomp->data), jas_matrix_numrows(tcomp->data), tcomp->data)) {\n\t\t\tjas_eprintf(\"write component failed\\n\");\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'The component domains must be the same for the ICT/RCT in the JPC codec.\nThis was previously enforced with an assertion.\nNow, it is handled in a more graceful manner.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: jas_image_t *jpg_decode(jas_stream_t *in, char *optstr)\n{\n\tstruct jpeg_decompress_struct cinfo;\n\tstruct jpeg_error_mgr jerr;\n\tFILE *input_file;\n\tjpg_dest_t dest_mgr_buf;\n\tjpg_dest_t *dest_mgr = &dest_mgr_buf;\n\tJDIMENSION num_scanlines;\n\tjas_image_t *image;\n\tint ret;\n\tjpg_dec_importopts_t opts;\n\tsize_t size;\n\n\tif (jpg_dec_parseopts(optstr, &opts)) {\n\t\tgoto error;\n\t}\n\n\t// In theory, the two memset calls that follow are not needed.\n\t// They are only here to make the code more predictable in the event\n\t// that the JPEG library fails to initialize a member.\n\tmemset(&cinfo, 0, sizeof(struct jpeg_decompress_struct));\n\tmemset(dest_mgr, 0, sizeof(jpg_dest_t));\n\n\tdest_mgr->data = 0;\n\n\timage = 0;\n\tinput_file = 0;\n\tif (!(input_file = tmpfile())) {\n\t\tjas_eprintf(\"cannot make temporary file\\n\");\n\t\tgoto error;\n\t}\n\tif (jpg_copystreamtofile(input_file, in)) {\n\t\tjas_eprintf(\"cannot copy stream\\n\");\n\t\tgoto error;\n\t}\n\trewind(input_file);\n\n\t/* Allocate and initialize a JPEG decompression object. */\n\tJAS_DBGLOG(10, (\"jpeg_std_error(%p)\\n\", &jerr));\n\tcinfo.err = jpeg_std_error(&jerr);\n\tJAS_DBGLOG(10, (\"jpeg_create_decompress(%p)\\n\", &cinfo));\n\tjpeg_create_decompress(&cinfo);\n\n\t/* Specify the data source for decompression. */\n\tJAS_DBGLOG(10, (\"jpeg_stdio_src(%p, %p)\\n\", &cinfo, input_file));\n\tjpeg_stdio_src(&cinfo, input_file);\n\n\t/* Read the file header to obtain the image information. */\n\tJAS_DBGLOG(10, (\"jpeg_read_header(%p, TRUE)\\n\", &cinfo));\n\tret = jpeg_read_header(&cinfo, TRUE);\n\tJAS_DBGLOG(10, (\"jpeg_read_header return value %d\\n\", ret));\n\tif (ret != JPEG_HEADER_OK) {\n\t\tjas_eprintf(\"jpeg_read_header did not return JPEG_HEADER_OK\\n\");\n\t}\n\tJAS_DBGLOG(10, (\n\t \"header: image_width %d; image_height %d; num_components %d\\n\",\n\t cinfo.image_width, cinfo.image_height, cinfo.num_components)\n\t );\n\n\t/* Start the decompressor. */\n\tJAS_DBGLOG(10, (\"jpeg_start_decompress(%p)\\n\", &cinfo));\n\tret = jpeg_start_decompress(&cinfo);\n\tJAS_DBGLOG(10, (\"jpeg_start_decompress return value %d\\n\", ret));\n\tJAS_DBGLOG(10, (\n\t \"header: output_width %d; output_height %d; output_components %d\\n\",\n\t cinfo.output_width, cinfo.output_height, cinfo.output_components)\n\t );\n\n\tif (opts.max_size) {\n\t\tif (!jas_safe_size_mul(cinfo.output_width, cinfo.output_height,\n\t\t &size) ||\n\t\t !jas_safe_size_mul(size, cinfo.output_components, &size)) {\n\t\t\tgoto error;\n\t\t}\n\t\tif (size > opts.max_size) {\n\t\t\tjas_eprintf(\"image is too large\\n\");\n\t\t\tgoto error;\n\t\t}\n\t}\n\n\t/* Create an image object to hold the decoded data. */\n\tif (!(image = jpg_mkimage(&cinfo))) {\n\t\tjas_eprintf(\"jpg_mkimage failed\\n\");\n\t\tgoto error;\n\t}\n\n\t/* Initialize the data sink object. */\n\tdest_mgr->image = image;\n\tif (!(dest_mgr->data = jas_matrix_create(1, cinfo.output_width))) {\n\t\tjas_eprintf(\"jas_matrix_create failed\\n\");\n\t\tgoto error;\n\t}\n\tdest_mgr->start_output = jpg_start_output;\n\tdest_mgr->put_pixel_rows = jpg_put_pixel_rows;\n\tdest_mgr->finish_output = jpg_finish_output;\n dest_mgr->buffer = (*cinfo.mem->alloc_sarray)\n ((j_common_ptr) &cinfo, JPOOL_IMAGE,\n cinfo.output_width * cinfo.output_components, (JDIMENSION) 1);\n\tdest_mgr->buffer_height = 1;\n\tdest_mgr->error = 0;\n\n\t/* Process the compressed data. */\n\t(*dest_mgr->start_output)(&cinfo, dest_mgr);\n\twhile (cinfo.output_scanline < cinfo.output_height) {\n\t\tJAS_DBGLOG(10, (\"jpeg_read_scanlines(%p, %p, %lu)\\n\", &cinfo,\n\t\t dest_mgr->buffer, JAS_CAST(unsigned long, dest_mgr->buffer_height)));\n\t\tnum_scanlines = jpeg_read_scanlines(&cinfo, dest_mgr->buffer,\n\t\t dest_mgr->buffer_height);\n\t\tJAS_DBGLOG(10, (\"jpeg_read_scanlines return value %lu\\n\",\n\t\t JAS_CAST(unsigned long, num_scanlines)));\n\t\t(*dest_mgr->put_pixel_rows)(&cinfo, dest_mgr, num_scanlines);\n\t}\n\t(*dest_mgr->finish_output)(&cinfo, dest_mgr);\n\n\t/* Complete the decompression process. */\n\tJAS_DBGLOG(10, (\"jpeg_finish_decompress(%p)\\n\", &cinfo));\n\tjpeg_finish_decompress(&cinfo);\n\n\t/* Destroy the JPEG decompression object. */\n\tJAS_DBGLOG(10, (\"jpeg_destroy_decompress(%p)\\n\", &cinfo));\n\tjpeg_destroy_decompress(&cinfo);\n\n\tjas_matrix_destroy(dest_mgr->data);\n\n\tJAS_DBGLOG(10, (\"fclose(%p)\\n\", input_file));\n\tfclose(input_file);\n\tinput_file = 0;\n\n\tif (dest_mgr->error) {\n\t\tjas_eprintf(\"error during decoding\\n\");\n\t\tgoto error;\n\t}\n\n\treturn image;\n\nerror:\n\tif (dest_mgr->data) {\n\t\tjas_matrix_destroy(dest_mgr->data);\n\t}\n\tif (image) {\n\t\tjas_image_destroy(image);\n\t}\n\tif (input_file) {\n\t\tfclose(input_file);\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-190'], 'message': 'The generation of the configuration file jas_config.h has been completely\nreworked in order to avoid pollution of the global namespace.\n\nSome problematic types like uchar, ulong, and friends have been replaced\nwith names with a jas_ prefix.\n\nAn option max_samples has been added to the BMP and JPEG decoders to\nrestrict the maximum size of image that they can decode. This change\nwas made as a (possibly temporary) fix to address security concerns.\nA max_samples command-line option has also been added to imginfo.\n\nWhether an image component (for jas_image_t) is stored in memory or on\ndisk is now based on the component size (rather than the image size).\n\nSome debug log message were added.\n\nSome new integer overflow checks were added.\n\nSome new safe integer add/multiply functions were added.\n\nMore pre-C99 cruft was removed. JasPer has numerous \"hacks\" to\nhandle pre-C99 compilers. JasPer now assumes C99 support. So, this\npre-C99 cruft is unnecessary and can be removed.\n\nThe regression jasper-doublefree-mem_close.jpg has been re-enabled.\nTheoretically, it should work more predictably now.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int jas_matrix_resize(jas_matrix_t *matrix, int numrows, int numcols)\n{\n\tint size;\n\tint i;\n\n\tsize = numrows * numcols;\n\tif (size > matrix->datasize_ || numrows > matrix->maxrows_) {\n\t\treturn -1;\n\t}\n\n\tmatrix->numrows_ = numrows;\n\tmatrix->numcols_ = numcols;\n\n\tfor (i = 0; i < numrows; ++i) {\n\t\tmatrix->rows_[i] = &matrix->data_[numcols * i];\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-190'], 'message': 'The generation of the configuration file jas_config.h has been completely\nreworked in order to avoid pollution of the global namespace.\n\nSome problematic types like uchar, ulong, and friends have been replaced\nwith names with a jas_ prefix.\n\nAn option max_samples has been added to the BMP and JPEG decoders to\nrestrict the maximum size of image that they can decode. This change\nwas made as a (possibly temporary) fix to address security concerns.\nA max_samples command-line option has also been added to imginfo.\n\nWhether an image component (for jas_image_t) is stored in memory or on\ndisk is now based on the component size (rather than the image size).\n\nSome debug log message were added.\n\nSome new integer overflow checks were added.\n\nSome new safe integer add/multiply functions were added.\n\nMore pre-C99 cruft was removed. JasPer has numerous \"hacks\" to\nhandle pre-C99 compilers. JasPer now assumes C99 support. So, this\npre-C99 cruft is unnecessary and can be removed.\n\nThe regression jasper-doublefree-mem_close.jpg has been re-enabled.\nTheoretically, it should work more predictably now.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void jas_matrix_asl(jas_matrix_t *matrix, int n)\n{\n\tint i;\n\tint j;\n\tjas_seqent_t *rowstart;\n\tint rowstep;\n\tjas_seqent_t *data;\n\n\tif (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {\n\t\tassert(matrix->rows_);\n\t\trowstep = jas_matrix_rowstep(matrix);\n\t\tfor (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,\n\t\t rowstart += rowstep) {\n\t\t\tfor (j = matrix->numcols_, data = rowstart; j > 0; --j,\n\t\t\t ++data) {\n\t\t\t\t//*data <<= n;\n\t\t\t\t*data = jas_seqent_asl(*data, n);\n\t\t\t}\n\t\t}\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-190'], 'message': 'The generation of the configuration file jas_config.h has been completely\nreworked in order to avoid pollution of the global namespace.\n\nSome problematic types like uchar, ulong, and friends have been replaced\nwith names with a jas_ prefix.\n\nAn option max_samples has been added to the BMP and JPEG decoders to\nrestrict the maximum size of image that they can decode. This change\nwas made as a (possibly temporary) fix to address security concerns.\nA max_samples command-line option has also been added to imginfo.\n\nWhether an image component (for jas_image_t) is stored in memory or on\ndisk is now based on the component size (rather than the image size).\n\nSome debug log message were added.\n\nSome new integer overflow checks were added.\n\nSome new safe integer add/multiply functions were added.\n\nMore pre-C99 cruft was removed. JasPer has numerous \"hacks\" to\nhandle pre-C99 compilers. JasPer now assumes C99 support. So, this\npre-C99 cruft is unnecessary and can be removed.\n\nThe regression jasper-doublefree-mem_close.jpg has been re-enabled.\nTheoretically, it should work more predictably now.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int pnm_validate(jas_stream_t *in)\n{\n\tuchar buf[2];\n\tint i;\n\tint n;\n\n\tassert(JAS_STREAM_MAXPUTBACK >= 2);\n\n\t/* Read the first two characters that constitute the signature. */\n\tif ((n = jas_stream_read(in, buf, 2)) < 0) {\n\t\treturn -1;\n\t}\n\t/* Put these characters back to the stream. */\n\tfor (i = n - 1; i >= 0; --i) {\n\t\tif (jas_stream_ungetc(in, buf[i]) == EOF) {\n\t\t\treturn -1;\n\t\t}\n\t}\n\t/* Did we read enough data? */\n\tif (n < 2) {\n\t\treturn -1;\n\t}\n\t/* Is this the correct signature for a PNM file? */\n\tif (buf[0] == 'P' && isdigit(buf[1])) {\n\t\treturn 0;\n\t}\n\treturn -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-190'], 'message': 'The generation of the configuration file jas_config.h has been completely\nreworked in order to avoid pollution of the global namespace.\n\nSome problematic types like uchar, ulong, and friends have been replaced\nwith names with a jas_ prefix.\n\nAn option max_samples has been added to the BMP and JPEG decoders to\nrestrict the maximum size of image that they can decode. This change\nwas made as a (possibly temporary) fix to address security concerns.\nA max_samples command-line option has also been added to imginfo.\n\nWhether an image component (for jas_image_t) is stored in memory or on\ndisk is now based on the component size (rather than the image size).\n\nSome debug log message were added.\n\nSome new integer overflow checks were added.\n\nSome new safe integer add/multiply functions were added.\n\nMore pre-C99 cruft was removed. JasPer has numerous \"hacks\" to\nhandle pre-C99 compilers. JasPer now assumes C99 support. So, this\npre-C99 cruft is unnecessary and can be removed.\n\nThe regression jasper-doublefree-mem_close.jpg has been re-enabled.\nTheoretically, it should work more predictably now.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int pgx_validate(jas_stream_t *in)\n{\n\tuchar buf[PGX_MAGICLEN];\n\tuint_fast32_t magic;\n\tint i;\n\tint n;\n\n\tassert(JAS_STREAM_MAXPUTBACK >= PGX_MAGICLEN);\n\n\t/* Read the validation data (i.e., the data used for detecting\n\t the format). */\n\tif ((n = jas_stream_read(in, buf, PGX_MAGICLEN)) < 0) {\n\t\treturn -1;\n\t}\n\n\t/* Put the validation data back onto the stream, so that the\n\t stream position will not be changed. */\n\tfor (i = n - 1; i >= 0; --i) {\n\t\tif (jas_stream_ungetc(in, buf[i]) == EOF) {\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\t/* Did we read enough data? */\n\tif (n < PGX_MAGICLEN) {\n\t\treturn -1;\n\t}\n\n\t/* Compute the signature value. */\n\tmagic = (buf[0] << 8) | buf[1];\n\n\t/* Ensure that the signature is correct for this format. */\n\tif (magic != PGX_MAGIC) {\n\t\treturn -1;\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-190'], 'message': 'The generation of the configuration file jas_config.h has been completely\nreworked in order to avoid pollution of the global namespace.\n\nSome problematic types like uchar, ulong, and friends have been replaced\nwith names with a jas_ prefix.\n\nAn option max_samples has been added to the BMP and JPEG decoders to\nrestrict the maximum size of image that they can decode. This change\nwas made as a (possibly temporary) fix to address security concerns.\nA max_samples command-line option has also been added to imginfo.\n\nWhether an image component (for jas_image_t) is stored in memory or on\ndisk is now based on the component size (rather than the image size).\n\nSome debug log message were added.\n\nSome new integer overflow checks were added.\n\nSome new safe integer add/multiply functions were added.\n\nMore pre-C99 cruft was removed. JasPer has numerous \"hacks\" to\nhandle pre-C99 compilers. JasPer now assumes C99 support. So, this\npre-C99 cruft is unnecessary and can be removed.\n\nThe regression jasper-doublefree-mem_close.jpg has been re-enabled.\nTheoretically, it should work more predictably now.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: sctp_disposition_t sctp_sf_ootb(struct net *net,\n\t\t\t\tconst struct sctp_endpoint *ep,\n\t\t\t\tconst struct sctp_association *asoc,\n\t\t\t\tconst sctp_subtype_t type,\n\t\t\t\tvoid *arg,\n\t\t\t\tsctp_cmd_seq_t *commands)\n{\n\tstruct sctp_chunk *chunk = arg;\n\tstruct sk_buff *skb = chunk->skb;\n\tsctp_chunkhdr_t *ch;\n\tsctp_errhdr_t *err;\n\t__u8 *ch_end;\n\tint ootb_shut_ack = 0;\n\tint ootb_cookie_ack = 0;\n\n\tSCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES);\n\n\tch = (sctp_chunkhdr_t *) chunk->chunk_hdr;\n\tdo {\n\t\t/* Report violation if the chunk is less then minimal */\n\t\tif (ntohs(ch->length) < sizeof(sctp_chunkhdr_t))\n\t\t\treturn sctp_sf_violation_chunklen(net, ep, asoc, type, arg,\n\t\t\t\t\t\t commands);\n\n\t\t/* Now that we know we at least have a chunk header,\n\t\t * do things that are type appropriate.\n\t\t */\n\t\tif (SCTP_CID_SHUTDOWN_ACK == ch->type)\n\t\t\tootb_shut_ack = 1;\n\n\t\t/* RFC 2960, Section 3.3.7\n\t\t * Moreover, under any circumstances, an endpoint that\n\t\t * receives an ABORT MUST NOT respond to that ABORT by\n\t\t * sending an ABORT of its own.\n\t\t */\n\t\tif (SCTP_CID_ABORT == ch->type)\n\t\t\treturn sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);\n\n\t\t/* RFC 8.4, 7) If the packet contains a \"Stale cookie\" ERROR\n\t\t * or a COOKIE ACK the SCTP Packet should be silently\n\t\t * discarded.\n\t\t */\n\n\t\tif (SCTP_CID_COOKIE_ACK == ch->type)\n\t\t\tootb_cookie_ack = 1;\n\n\t\tif (SCTP_CID_ERROR == ch->type) {\n\t\t\tsctp_walk_errors(err, ch) {\n\t\t\t\tif (SCTP_ERROR_STALE_COOKIE == err->cause) {\n\t\t\t\t\tootb_cookie_ack = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/* Report violation if chunk len overflows */\n\t\tch_end = ((__u8 *)ch) + SCTP_PAD4(ntohs(ch->length));\n\t\tif (ch_end > skb_tail_pointer(skb))\n\t\t\treturn sctp_sf_violation_chunklen(net, ep, asoc, type, arg,\n\t\t\t\t\t\t commands);\n\n\t\tch = (sctp_chunkhdr_t *) ch_end;\n\t} while (ch_end < skb_tail_pointer(skb));\n\n\tif (ootb_shut_ack)\n\t\treturn sctp_sf_shut_8_4_5(net, ep, asoc, type, arg, commands);\n\telse if (ootb_cookie_ack)\n\t\treturn sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);\n\telse\n\t\treturn sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'sctp: validate chunk len before actually using it\n\nAndrey Konovalov reported that KASAN detected that SCTP was using a slab\nbeyond the boundaries. It was caused because when handling out of the\nblue packets in function sctp_sf_ootb() it was checking the chunk len\nonly after already processing the first chunk, validating only for the\n2nd and subsequent ones.\n\nThe fix is to just move the check upwards so it's also validated for the\n1st chunk.\n\nReported-by: Andrey Konovalov \nTested-by: Andrey Konovalov \nSigned-off-by: Marcelo Ricardo Leitner \nReviewed-by: Xin Long \nAcked-by: Neil Horman \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void jpc_qmfb_split_colgrp(jpc_fix_t *a, int numrows, int stride,\n int parity)\n{\n\n\tint bufsize = JPC_CEILDIVPOW2(numrows, 1);\n\tjpc_fix_t splitbuf[QMFB_SPLITBUFSIZE * JPC_QMFB_COLGRPSIZE];\n\tjpc_fix_t *buf = splitbuf;\n\tjpc_fix_t *srcptr;\n\tjpc_fix_t *dstptr;\n\tregister jpc_fix_t *srcptr2;\n\tregister jpc_fix_t *dstptr2;\n\tregister int n;\n\tregister int i;\n\tint m;\n\tint hstartcol;\n\n\t/* Get a buffer. */\n\tif (bufsize > QMFB_SPLITBUFSIZE) {\n\t\tif (!(buf = jas_alloc2(bufsize, sizeof(jpc_fix_t)))) {\n\t\t\t/* We have no choice but to commit suicide in this case. */\n\t\t\tabort();\n\t\t}\n\t}\n\n\tif (numrows >= 2) {\n\t\thstartcol = (numrows + 1 - parity) >> 1;\n\t\t// ORIGINAL (WRONG): m = (parity) ? hstartcol : (numrows - hstartcol);\n\t\tm = numrows - hstartcol;\n\n\t\t/* Save the samples destined for the highpass channel. */\n\t\tn = m;\n\t\tdstptr = buf;\n\t\tsrcptr = &a[(1 - parity) * stride];\n\t\twhile (n-- > 0) {\n\t\t\tdstptr2 = dstptr;\n\t\t\tsrcptr2 = srcptr;\n\t\t\tfor (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {\n\t\t\t\t*dstptr2 = *srcptr2;\n\t\t\t\t++dstptr2;\n\t\t\t\t++srcptr2;\n\t\t\t}\n\t\t\tdstptr += JPC_QMFB_COLGRPSIZE;\n\t\t\tsrcptr += stride << 1;\n\t\t}\n\t\t/* Copy the appropriate samples into the lowpass channel. */\n\t\tdstptr = &a[(1 - parity) * stride];\n\t\tsrcptr = &a[(2 - parity) * stride];\n\t\tn = numrows - m - (!parity);\n\t\twhile (n-- > 0) {\n\t\t\tdstptr2 = dstptr;\n\t\t\tsrcptr2 = srcptr;\n\t\t\tfor (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {\n\t\t\t\t*dstptr2 = *srcptr2;\n\t\t\t\t++dstptr2;\n\t\t\t\t++srcptr2;\n\t\t\t}\n\t\t\tdstptr += stride;\n\t\t\tsrcptr += stride << 1;\n\t\t}\n\t\t/* Copy the saved samples into the highpass channel. */\n\t\tdstptr = &a[hstartcol * stride];\n\t\tsrcptr = buf;\n\t\tn = m;\n\t\twhile (n-- > 0) {\n\t\t\tdstptr2 = dstptr;\n\t\t\tsrcptr2 = srcptr;\n\t\t\tfor (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {\n\t\t\t\t*dstptr2 = *srcptr2;\n\t\t\t\t++dstptr2;\n\t\t\t\t++srcptr2;\n\t\t\t}\n\t\t\tdstptr += stride;\n\t\t\tsrcptr += JPC_QMFB_COLGRPSIZE;\n\t\t}\n\t}\n\n\t/* If the split buffer was allocated on the heap, free this memory. */\n\tif (buf != splitbuf) {\n\t\tjas_free(buf);\n\t}\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fixed a buffer overrun problem in the QMFB code in the JPC codec\nthat was caused by a buffer being allocated with a size that was too small\nin some cases.\nAdded a new regression test case.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: do_file(char const *const fname)\n{\n\ttable_sort_t custom_sort;\n\tElf32_Ehdr *ehdr = mmap_file(fname);\n\n\tehdr_curr = ehdr;\n\tswitch (ehdr->e_ident[EI_DATA]) {\n\tdefault:\n\t\tfprintf(stderr, \"unrecognized ELF data encoding %d: %s\\n\",\n\t\t\tehdr->e_ident[EI_DATA], fname);\n\t\tfail_file();\n\t\tbreak;\n\tcase ELFDATA2LSB:\n\t\tr = rle;\n\t\tr2 = r2le;\n\t\tr8 = r8le;\n\t\tw = wle;\n\t\tw2 = w2le;\n\t\tw8 = w8le;\n\t\tbreak;\n\tcase ELFDATA2MSB:\n\t\tr = rbe;\n\t\tr2 = r2be;\n\t\tr8 = r8be;\n\t\tw = wbe;\n\t\tw2 = w2be;\n\t\tw8 = w8be;\n\t\tbreak;\n\t} /* end switch */\n\tif (memcmp(ELFMAG, ehdr->e_ident, SELFMAG) != 0\n\t|| r2(&ehdr->e_type) != ET_EXEC\n\t|| ehdr->e_ident[EI_VERSION] != EV_CURRENT) {\n\t\tfprintf(stderr, \"unrecognized ET_EXEC file %s\\n\", fname);\n\t\tfail_file();\n\t}\n\n\tcustom_sort = NULL;\n\tswitch (r2(&ehdr->e_machine)) {\n\tdefault:\n\t\tfprintf(stderr, \"unrecognized e_machine %d %s\\n\",\n\t\t\tr2(&ehdr->e_machine), fname);\n\t\tfail_file();\n\t\tbreak;\n\tcase EM_386:\n\tcase EM_X86_64:\n\tcase EM_S390:\n\t\tcustom_sort = sort_relative_table;\n\t\tbreak;\n\tcase EM_ARCOMPACT:\n\tcase EM_ARCV2:\n\tcase EM_ARM:\n\tcase EM_AARCH64:\n\tcase EM_MICROBLAZE:\n\tcase EM_MIPS:\n\tcase EM_XTENSA:\n\t\tbreak;\n\t} /* end switch */\n\n\tswitch (ehdr->e_ident[EI_CLASS]) {\n\tdefault:\n\t\tfprintf(stderr, \"unrecognized ELF class %d %s\\n\",\n\t\t\tehdr->e_ident[EI_CLASS], fname);\n\t\tfail_file();\n\t\tbreak;\n\tcase ELFCLASS32:\n\t\tif (r2(&ehdr->e_ehsize) != sizeof(Elf32_Ehdr)\n\t\t|| r2(&ehdr->e_shentsize) != sizeof(Elf32_Shdr)) {\n\t\t\tfprintf(stderr,\n\t\t\t\t\"unrecognized ET_EXEC file: %s\\n\", fname);\n\t\t\tfail_file();\n\t\t}\n\t\tdo32(ehdr, fname, custom_sort);\n\t\tbreak;\n\tcase ELFCLASS64: {\n\t\tElf64_Ehdr *const ghdr = (Elf64_Ehdr *)ehdr;\n\t\tif (r2(&ghdr->e_ehsize) != sizeof(Elf64_Ehdr)\n\t\t|| r2(&ghdr->e_shentsize) != sizeof(Elf64_Shdr)) {\n\t\t\tfprintf(stderr,\n\t\t\t\t\"unrecognized ET_EXEC file: %s\\n\", fname);\n\t\t\tfail_file();\n\t\t}\n\t\tdo64(ghdr, fname, custom_sort);\n\t\tbreak;\n\t}\n\t} /* end switch */\n\n\tcleanup();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'x86/mm: Expand the exception table logic to allow new handling options\n\nHuge amounts of help from Andy Lutomirski and Borislav Petkov to\nproduce this. Andy provided the inspiration to add classes to the\nexception table with a clever bit-squeezing trick, Boris pointed\nout how much cleaner it would all be if we just had a new field.\n\nLinus Torvalds blessed the expansion with:\n\n ' I'd rather not be clever in order to save just a tiny amount of space\n in the exception table, which isn't really criticial for anybody. '\n\nThe third field is another relative function pointer, this one to a\nhandler that executes the actions.\n\nWe start out with three handlers:\n\n 1: Legacy - just jumps the to fixup IP\n 2: Fault - provide the trap number in %ax to the fixup code\n 3: Cleaned up legacy for the uaccess error hack\n\nSigned-off-by: Tony Luck \nReviewed-by: Borislav Petkov \nCc: Linus Torvalds \nCc: Peter Zijlstra \nCc: Thomas Gleixner \nLink: http://lkml.kernel.org/r/f6af78fcbd348cf4939875cfda9c19689b5e50b8.1455732970.git.tony.luck@intel.com\nSigned-off-by: Ingo Molnar '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: renderTable(struct table *t, int max_width, struct html_feed_environ *h_env)\n{\n int i, j, w, r, h;\n Str renderbuf;\n short new_tabwidth[MAXCOL] = { 0 };\n#ifdef MATRIX\n int itr;\n VEC *newwidth;\n MAT *mat, *minv;\n PERM *pivot;\n#endif\t\t\t\t/* MATRIX */\n int width;\n int rulewidth;\n Str vrulea = NULL, vruleb = NULL, vrulec = NULL;\n#ifdef ID_EXT\n Str idtag;\n#endif\t\t\t\t/* ID_EXT */\n\n t->total_height = 0;\n if (t->maxcol < 0) {\n\tmake_caption(t, h_env);\n\treturn;\n }\n\n if (t->sloppy_width > max_width)\n\tmax_width = t->sloppy_width;\n\n rulewidth = table_rule_width(t);\n\n max_width -= table_border_width(t);\n\n if (rulewidth > 1)\n\tmax_width = floor_at_intervals(max_width, rulewidth);\n\n if (max_width < rulewidth)\n\tmax_width = rulewidth;\n\n check_maximum_width(t);\n\n#ifdef MATRIX\n if (t->maxcol == 0) {\n\tif (t->tabwidth[0] > max_width)\n\t t->tabwidth[0] = max_width;\n\tif (t->total_width > 0)\n\t t->tabwidth[0] = max_width;\n\telse if (t->fixed_width[0] > 0)\n\t t->tabwidth[0] = t->fixed_width[0];\n\tif (t->tabwidth[0] < t->minimum_width[0])\n\t t->tabwidth[0] = t->minimum_width[0];\n }\n else {\n\tset_table_matrix(t, max_width);\n\n\titr = 0;\n\tmat = m_get(t->maxcol + 1, t->maxcol + 1);\n\tpivot = px_get(t->maxcol + 1);\n\tnewwidth = v_get(t->maxcol + 1);\n\tminv = m_get(t->maxcol + 1, t->maxcol + 1);\n\tdo {\n\t m_copy(t->matrix, mat);\n\t LUfactor(mat, pivot);\n\t LUsolve(mat, pivot, t->vector, newwidth);\n\t LUinverse(mat, pivot, minv);\n#ifdef TABLE_DEBUG\n\t set_integered_width(t, newwidth->ve, new_tabwidth);\n\t fprintf(stderr, \"itr=%d\\n\", itr);\n\t fprintf(stderr, \"max_width=%d\\n\", max_width);\n\t fprintf(stderr, \"minimum : \");\n\t for (i = 0; i <= t->maxcol; i++)\n\t\tfprintf(stderr, \"%2d \", t->minimum_width[i]);\n\t fprintf(stderr, \"\\nfixed : \");\n\t for (i = 0; i <= t->maxcol; i++)\n\t\tfprintf(stderr, \"%2d \", t->fixed_width[i]);\n\t fprintf(stderr, \"\\ndecided : \");\n\t for (i = 0; i <= t->maxcol; i++)\n\t\tfprintf(stderr, \"%2d \", new_tabwidth[i]);\n\t fprintf(stderr, \"\\n\");\n#endif\t\t\t\t/* TABLE_DEBUG */\n\t itr++;\n\n\t} while (check_table_width(t, newwidth->ve, minv, itr));\n\tset_integered_width(t, newwidth->ve, new_tabwidth);\n\tcheck_minimum_width(t, new_tabwidth);\n\tv_free(newwidth);\n\tpx_free(pivot);\n\tm_free(mat);\n\tm_free(minv);\n\tm_free(t->matrix);\n\tv_free(t->vector);\n\tfor (i = 0; i <= t->maxcol; i++) {\n\t t->tabwidth[i] = new_tabwidth[i];\n\t}\n }\n#else\t\t\t\t/* not MATRIX */\n set_table_width(t, new_tabwidth, max_width);\n for (i = 0; i <= t->maxcol; i++) {\n\tt->tabwidth[i] = new_tabwidth[i];\n }\n#endif\t\t\t\t/* not MATRIX */\n\n check_minimum_width(t, t->tabwidth);\n for (i = 0; i <= t->maxcol; i++)\n\tt->tabwidth[i] = ceil_at_intervals(t->tabwidth[i], rulewidth);\n\n renderCoTable(t, h_env->limit);\n\n for (i = 0; i <= t->maxcol; i++) {\n\tfor (j = 0; j <= t->maxrow; j++) {\n\t check_row(t, j);\n\t if (t->tabattr[j][i] & HTT_Y)\n\t\tcontinue;\n\t do_refill(t, j, i, h_env->limit);\n\t}\n }\n\n check_minimum_width(t, t->tabwidth);\n t->total_width = 0;\n for (i = 0; i <= t->maxcol; i++) {\n\tt->tabwidth[i] = ceil_at_intervals(t->tabwidth[i], rulewidth);\n\tt->total_width += t->tabwidth[i];\n }\n\n t->total_width += table_border_width(t);\n\n check_table_height(t);\n\n for (i = 0; i <= t->maxcol; i++) {\n\tfor (j = 0; j <= t->maxrow; j++) {\n\t TextLineList *l;\n\t int k;\n\t if ((t->tabattr[j][i] & HTT_Y) ||\n\t\t(t->tabattr[j][i] & HTT_TOP) || (t->tabdata[j][i] == NULL))\n\t\tcontinue;\n\t h = t->tabheight[j];\n\t for (k = j + 1; k <= t->maxrow; k++) {\n\t\tif (!(t->tabattr[k][i] & HTT_Y))\n\t\t break;\n\t\th += t->tabheight[k];\n\t\tswitch (t->border_mode) {\n\t\tcase BORDER_THIN:\n\t\tcase BORDER_THICK:\n\t\tcase BORDER_NOWIN:\n\t\t h += 1;\n\t\t break;\n\t\t}\n\t }\n\t h -= t->tabdata[j][i]->nitem;\n\t if (t->tabattr[j][i] & HTT_MIDDLE)\n\t\th /= 2;\n\t if (h <= 0)\n\t\tcontinue;\n\t l = newTextLineList();\n\t for (k = 0; k < h; k++)\n\t\tpushTextLine(l, newTextLine(NULL, 0));\n\t t->tabdata[j][i] = appendGeneralList((GeneralList *)l,\n\t\t\t\t\t\t t->tabdata[j][i]);\n\t}\n }\n\n /* table output */\n width = t->total_width;\n\n make_caption(t, h_env);\n\n HTMLlineproc1(\"
\", h_env);\n#ifdef ID_EXT\n    if (t->id != NULL) {\n\tidtag = Sprintf(\"<_id id=\\\"%s\\\">\", html_quote((t->id)->ptr));\n\tHTMLlineproc1(idtag->ptr, h_env);\n    }\n#endif\t\t\t\t/* ID_EXT */\n    switch (t->border_mode) {\n    case BORDER_THIN:\n    case BORDER_THICK:\n\trenderbuf = Strnew();\n\tprint_sep(t, -1, T_TOP, t->maxcol, renderbuf);\n\tpush_render_image(renderbuf, width, t->total_width, h_env);\n\tt->total_height += 1;\n\tbreak;\n    }\n    vruleb = Strnew();\n    switch (t->border_mode) {\n    case BORDER_THIN:\n    case BORDER_THICK:\n\tvrulea = Strnew();\n\tvrulec = Strnew();\n\tpush_symbol(vrulea, TK_VERTICALBAR(t->border_mode), symbol_width, 1);\n\tfor (i = 0; i < t->cellpadding; i++) {\n\t    Strcat_char(vrulea, ' ');\n\t    Strcat_char(vruleb, ' ');\n\t    Strcat_char(vrulec, ' ');\n\t}\n\tpush_symbol(vrulec, TK_VERTICALBAR(t->border_mode), symbol_width, 1);\n    case BORDER_NOWIN:\n\tpush_symbol(vruleb, TK_VERTICALBAR(BORDER_THIN), symbol_width, 1);\n\tfor (i = 0; i < t->cellpadding; i++)\n\t    Strcat_char(vruleb, ' ');\n\tbreak;\n    case BORDER_NONE:\n\tfor (i = 0; i < t->cellspacing; i++)\n\t    Strcat_char(vruleb, ' ');\n    }\n\n    for (r = 0; r <= t->maxrow; r++) {\n\tfor (h = 0; h < t->tabheight[r]; h++) {\n\t    renderbuf = Strnew();\n\t    if (t->border_mode == BORDER_THIN\n\t\t|| t->border_mode == BORDER_THICK)\n\t\tStrcat(renderbuf, vrulea);\n#ifdef ID_EXT\n\t    if (t->tridvalue[r] != NULL && h == 0) {\n\t\tidtag = Sprintf(\"<_id id=\\\"%s\\\">\",\n\t\t\t\thtml_quote((t->tridvalue[r])->ptr));\n\t\tStrcat(renderbuf, idtag);\n\t    }\n#endif\t\t\t\t/* ID_EXT */\n\t    for (i = 0; i <= t->maxcol; i++) {\n\t\tcheck_row(t, r);\n#ifdef ID_EXT\n\t\tif (t->tabidvalue[r][i] != NULL && h == 0) {\n\t\t    idtag = Sprintf(\"<_id id=\\\"%s\\\">\",\n\t\t\t\t    html_quote((t->tabidvalue[r][i])->ptr));\n\t\t    Strcat(renderbuf, idtag);\n\t\t}\n#endif\t\t\t\t/* ID_EXT */\n\t\tif (!(t->tabattr[r][i] & HTT_X)) {\n\t\t    w = t->tabwidth[i];\n\t\t    for (j = i + 1;\n\t\t\t j <= t->maxcol && (t->tabattr[r][j] & HTT_X); j++)\n\t\t\tw += t->tabwidth[j] + t->cellspacing;\n\t\t    if (t->tabattr[r][i] & HTT_Y) {\n\t\t\tfor (j = r - 1; j >= 0 && t->tabattr[j]\n\t\t\t     && (t->tabattr[j][i] & HTT_Y); j--) ;\n\t\t\tprint_item(t, j, i, w, renderbuf);\n\t\t    }\n\t\t    else\n\t\t\tprint_item(t, r, i, w, renderbuf);\n\t\t}\n\t\tif (i < t->maxcol && !(t->tabattr[r][i + 1] & HTT_X))\n\t\t    Strcat(renderbuf, vruleb);\n\t    }\n\t    switch (t->border_mode) {\n\t    case BORDER_THIN:\n\t    case BORDER_THICK:\n\t\tStrcat(renderbuf, vrulec);\n\t\tt->total_height += 1;\n\t\tbreak;\n\t    }\n\t    push_render_image(renderbuf, width, t->total_width, h_env);\n\t}\n\tif (r < t->maxrow && t->border_mode != BORDER_NONE) {\n\t    renderbuf = Strnew();\n\t    print_sep(t, r, T_MIDDLE, t->maxcol, renderbuf);\n\t    push_render_image(renderbuf, width, t->total_width, h_env);\n\t}\n\tt->total_height += t->tabheight[r];\n    }\n    switch (t->border_mode) {\n    case BORDER_THIN:\n    case BORDER_THICK:\n\trenderbuf = Strnew();\n\tprint_sep(t, t->maxrow, T_BOTTOM, t->maxcol, renderbuf);\n\tpush_render_image(renderbuf, width, t->total_width, h_env);\n\tt->total_height += 1;\n\tbreak;\n    }\n    if (t->total_height == 0) {\n       renderbuf = Strnew_charp(\" \");\n\tt->total_height++;\n\tt->total_width = 1;\n\tpush_render_image(renderbuf, 1, t->total_width, h_env);\n    }\n    HTMLlineproc1(\"
\", h_env);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Truncate max_width for renderTable\n\nBug-Debian: https://github.com/tats/w3m/issues/25'
" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: GC_API GC_ATTR_MALLOC void * GC_CALL GC_debug_malloc_stubborn(size_t lb,\n GC_EXTRA_PARAMS)\n {\n void * result = GC_malloc_stubborn(lb + DEBUG_BYTES);\n\n if (result == 0) {\n GC_err_printf(\"GC_debug_malloc_stubborn(%lu)\"\n \" returning NULL (%s:%d)\\n\", (unsigned long)lb, s, i);\n return(0);\n }\n if (!GC_debugging_started) {\n GC_start_debugging();\n }\n ADD_CALL_CHAIN(result, ra);\n return (GC_store_debug_info(result, (word)lb, s, i));\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix malloc routines to prevent size value wrap-around\n\nSee issue #135 on Github.\n\n* allchblk.c (GC_allochblk, GC_allochblk_nth): Use\nOBJ_SZ_TO_BLOCKS_CHECKED instead of OBJ_SZ_TO_BLOCKS.\n* malloc.c (GC_alloc_large): Likewise.\n* alloc.c (GC_expand_hp_inner): Type of \"bytes\" local variable changed\nfrom word to size_t; cast ROUNDUP_PAGESIZE argument to size_t; prevent\noverflow when computing GC_heapsize+bytes > GC_max_heapsize.\n* dbg_mlc.c (GC_debug_malloc, GC_debug_malloc_ignore_off_page,\nGC_debug_malloc_atomic_ignore_off_page, GC_debug_generic_malloc,\nGC_debug_generic_malloc_inner,\nGC_debug_generic_malloc_inner_ignore_off_page,\nGC_debug_malloc_stubborn, GC_debug_malloc_atomic,\nGC_debug_malloc_uncollectable, GC_debug_malloc_atomic_uncollectable):\nUse SIZET_SAT_ADD (instead of \"+\" operator) to add extra bytes to lb\nvalue.\n* fnlz_mlc.c (GC_finalized_malloc): Likewise.\n* gcj_mlc.c (GC_debug_gcj_malloc): Likewise.\n* include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES,\nADD_SLOP, ROUNDUP_PAGESIZE): Likewise.\n* include/private/gcconfig.h (GET_MEM): Likewise.\n* mallocx.c (GC_malloc_many, GC_memalign): Likewise.\n* os_dep.c (GC_wince_get_mem, GC_win32_get_mem): Likewise.\n* typd_mlc.c (GC_malloc_explicitly_typed,\nGC_malloc_explicitly_typed_ignore_off_page,\nGC_calloc_explicitly_typed): Likewise.\n* headers.c (GC_scratch_alloc): Change type of bytes_to_get from word\nto size_t (because ROUNDUP_PAGESIZE_IF_MMAP result type changed).\n* include/private/gc_priv.h: Include limits.h (unless SIZE_MAX already\ndefined).\n* include/private/gc_priv.h (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Move from\nmalloc.c file.\n* include/private/gc_priv.h (SIZET_SAT_ADD): New macro (defined before\ninclude gcconfig.h).\n* include/private/gc_priv.h (EXTRA_BYTES, GC_page_size): Change type\nto size_t.\n* os_dep.c (GC_page_size): Likewise.\n* include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES,\nADD_SLOP, ROUNDUP_PAGESIZE): Add comment about the argument.\n* include/private/gcconfig.h (GET_MEM): Likewise.\n* include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES,\nADD_SLOP, OBJ_SZ_TO_BLOCKS, ROUNDUP_PAGESIZE,\nROUNDUP_PAGESIZE_IF_MMAP): Rename argument to \"lb\".\n* include/private/gc_priv.h (OBJ_SZ_TO_BLOCKS_CHECKED): New macro.\n* include/private/gcconfig.h (GC_win32_get_mem, GC_wince_get_mem,\nGC_unix_get_mem): Change argument type from word to int.\n* os_dep.c (GC_unix_mmap_get_mem, GC_unix_get_mem,\nGC_unix_sbrk_get_mem, GC_wince_get_mem, GC_win32_get_mem): Likewise.\n* malloc.c (GC_alloc_large_and_clear): Call OBJ_SZ_TO_BLOCKS only\nif no value wrap around is guaranteed.\n* malloc.c (GC_generic_malloc): Do not check for lb_rounded < lb case\n(because ROUNDED_UP_GRANULES and GRANULES_TO_BYTES guarantees no value\nwrap around).\n* mallocx.c (GC_generic_malloc_ignore_off_page): Likewise.\n* misc.c (GC_init_size_map): Change \"i\" local variable type from int\nto size_t.\n* os_dep.c (GC_write_fault_handler, catch_exception_raise): Likewise.\n* misc.c (GC_envfile_init): Cast len to size_t when passed to\nROUNDUP_PAGESIZE_IF_MMAP.\n* os_dep.c (GC_setpagesize): Cast GC_sysinfo.dwPageSize and\nGETPAGESIZE() to size_t (when setting GC_page_size).\n* os_dep.c (GC_unix_mmap_get_mem, GC_unmap_start, GC_remove_protection):\nExpand ROUNDUP_PAGESIZE macro but without value wrap-around checking\n(the argument is of word type).\n* os_dep.c (GC_unix_mmap_get_mem): Replace -GC_page_size with\n~GC_page_size+1 (because GC_page_size is unsigned); remove redundant\ncast to size_t.\n* os_dep.c (GC_unix_sbrk_get_mem): Add explicit cast of GC_page_size\nto SBRK_ARG_T.\n* os_dep.c (GC_wince_get_mem): Change type of res_bytes local variable\nto size_t.\n* typd_mlc.c: Do not include limits.h.\n* typd_mlc.c (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Remove (as defined in\ngc_priv.h now).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: STATIC void * GC_debug_generic_malloc(size_t lb, int knd, GC_EXTRA_PARAMS)\n{\n void * result = GC_generic_malloc(lb + DEBUG_BYTES, knd);\n\n if (NULL == result) {\n GC_err_printf(\n \"GC_debug_generic_malloc(%lu, %d) returning NULL (%s:%d)\\n\",\n (unsigned long)lb, knd, s, i);\n return NULL;\n }\n if (!GC_debugging_started) {\n GC_start_debugging();\n }\n ADD_CALL_CHAIN(result, ra);\n return GC_store_debug_info(result, (word)lb, s, i);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix malloc routines to prevent size value wrap-around\n\nSee issue #135 on Github.\n\n* allchblk.c (GC_allochblk, GC_allochblk_nth): Use\nOBJ_SZ_TO_BLOCKS_CHECKED instead of OBJ_SZ_TO_BLOCKS.\n* malloc.c (GC_alloc_large): Likewise.\n* alloc.c (GC_expand_hp_inner): Type of \"bytes\" local variable changed\nfrom word to size_t; cast ROUNDUP_PAGESIZE argument to size_t; prevent\noverflow when computing GC_heapsize+bytes > GC_max_heapsize.\n* dbg_mlc.c (GC_debug_malloc, GC_debug_malloc_ignore_off_page,\nGC_debug_malloc_atomic_ignore_off_page, GC_debug_generic_malloc,\nGC_debug_generic_malloc_inner,\nGC_debug_generic_malloc_inner_ignore_off_page,\nGC_debug_malloc_stubborn, GC_debug_malloc_atomic,\nGC_debug_malloc_uncollectable, GC_debug_malloc_atomic_uncollectable):\nUse SIZET_SAT_ADD (instead of \"+\" operator) to add extra bytes to lb\nvalue.\n* fnlz_mlc.c (GC_finalized_malloc): Likewise.\n* gcj_mlc.c (GC_debug_gcj_malloc): Likewise.\n* include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES,\nADD_SLOP, ROUNDUP_PAGESIZE): Likewise.\n* include/private/gcconfig.h (GET_MEM): Likewise.\n* mallocx.c (GC_malloc_many, GC_memalign): Likewise.\n* os_dep.c (GC_wince_get_mem, GC_win32_get_mem): Likewise.\n* typd_mlc.c (GC_malloc_explicitly_typed,\nGC_malloc_explicitly_typed_ignore_off_page,\nGC_calloc_explicitly_typed): Likewise.\n* headers.c (GC_scratch_alloc): Change type of bytes_to_get from word\nto size_t (because ROUNDUP_PAGESIZE_IF_MMAP result type changed).\n* include/private/gc_priv.h: Include limits.h (unless SIZE_MAX already\ndefined).\n* include/private/gc_priv.h (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Move from\nmalloc.c file.\n* include/private/gc_priv.h (SIZET_SAT_ADD): New macro (defined before\ninclude gcconfig.h).\n* include/private/gc_priv.h (EXTRA_BYTES, GC_page_size): Change type\nto size_t.\n* os_dep.c (GC_page_size): Likewise.\n* include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES,\nADD_SLOP, ROUNDUP_PAGESIZE): Add comment about the argument.\n* include/private/gcconfig.h (GET_MEM): Likewise.\n* include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES,\nADD_SLOP, OBJ_SZ_TO_BLOCKS, ROUNDUP_PAGESIZE,\nROUNDUP_PAGESIZE_IF_MMAP): Rename argument to \"lb\".\n* include/private/gc_priv.h (OBJ_SZ_TO_BLOCKS_CHECKED): New macro.\n* include/private/gcconfig.h (GC_win32_get_mem, GC_wince_get_mem,\nGC_unix_get_mem): Change argument type from word to int.\n* os_dep.c (GC_unix_mmap_get_mem, GC_unix_get_mem,\nGC_unix_sbrk_get_mem, GC_wince_get_mem, GC_win32_get_mem): Likewise.\n* malloc.c (GC_alloc_large_and_clear): Call OBJ_SZ_TO_BLOCKS only\nif no value wrap around is guaranteed.\n* malloc.c (GC_generic_malloc): Do not check for lb_rounded < lb case\n(because ROUNDED_UP_GRANULES and GRANULES_TO_BYTES guarantees no value\nwrap around).\n* mallocx.c (GC_generic_malloc_ignore_off_page): Likewise.\n* misc.c (GC_init_size_map): Change \"i\" local variable type from int\nto size_t.\n* os_dep.c (GC_write_fault_handler, catch_exception_raise): Likewise.\n* misc.c (GC_envfile_init): Cast len to size_t when passed to\nROUNDUP_PAGESIZE_IF_MMAP.\n* os_dep.c (GC_setpagesize): Cast GC_sysinfo.dwPageSize and\nGETPAGESIZE() to size_t (when setting GC_page_size).\n* os_dep.c (GC_unix_mmap_get_mem, GC_unmap_start, GC_remove_protection):\nExpand ROUNDUP_PAGESIZE macro but without value wrap-around checking\n(the argument is of word type).\n* os_dep.c (GC_unix_mmap_get_mem): Replace -GC_page_size with\n~GC_page_size+1 (because GC_page_size is unsigned); remove redundant\ncast to size_t.\n* os_dep.c (GC_unix_sbrk_get_mem): Add explicit cast of GC_page_size\nto SBRK_ARG_T.\n* os_dep.c (GC_wince_get_mem): Change type of res_bytes local variable\nto size_t.\n* typd_mlc.c: Do not include limits.h.\n* typd_mlc.c (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Remove (as defined in\ngc_priv.h now).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: GC_malloc_explicitly_typed_ignore_off_page(size_t lb, GC_descr d)\n{\n ptr_t op;\n size_t lg;\n DCL_LOCK_STATE;\n\n GC_ASSERT(GC_explicit_typing_initialized);\n lb += TYPD_EXTRA_BYTES;\n if (SMALL_OBJ(lb)) {\n GC_DBG_COLLECT_AT_MALLOC(lb);\n lg = GC_size_map[lb];\n LOCK();\n op = GC_eobjfreelist[lg];\n if (EXPECT(0 == op, FALSE)) {\n UNLOCK();\n op = (ptr_t)GENERAL_MALLOC_IOP(lb, GC_explicit_kind);\n if (0 == op) return 0;\n lg = GC_size_map[lb]; /* May have been uninitialized. */\n } else {\n GC_eobjfreelist[lg] = obj_link(op);\n obj_link(op) = 0;\n GC_bytes_allocd += GRANULES_TO_BYTES(lg);\n UNLOCK();\n }\n ((word *)op)[GRANULES_TO_WORDS(lg) - 1] = d;\n } else {\n op = (ptr_t)GENERAL_MALLOC_IOP(lb, GC_explicit_kind);\n if (op != NULL) {\n lg = BYTES_TO_GRANULES(GC_size(op));\n ((word *)op)[GRANULES_TO_WORDS(lg) - 1] = d;\n }\n }\n return((void *) op);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix malloc routines to prevent size value wrap-around\n\nSee issue #135 on Github.\n\n* allchblk.c (GC_allochblk, GC_allochblk_nth): Use\nOBJ_SZ_TO_BLOCKS_CHECKED instead of OBJ_SZ_TO_BLOCKS.\n* malloc.c (GC_alloc_large): Likewise.\n* alloc.c (GC_expand_hp_inner): Type of \"bytes\" local variable changed\nfrom word to size_t; cast ROUNDUP_PAGESIZE argument to size_t; prevent\noverflow when computing GC_heapsize+bytes > GC_max_heapsize.\n* dbg_mlc.c (GC_debug_malloc, GC_debug_malloc_ignore_off_page,\nGC_debug_malloc_atomic_ignore_off_page, GC_debug_generic_malloc,\nGC_debug_generic_malloc_inner,\nGC_debug_generic_malloc_inner_ignore_off_page,\nGC_debug_malloc_stubborn, GC_debug_malloc_atomic,\nGC_debug_malloc_uncollectable, GC_debug_malloc_atomic_uncollectable):\nUse SIZET_SAT_ADD (instead of \"+\" operator) to add extra bytes to lb\nvalue.\n* fnlz_mlc.c (GC_finalized_malloc): Likewise.\n* gcj_mlc.c (GC_debug_gcj_malloc): Likewise.\n* include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES,\nADD_SLOP, ROUNDUP_PAGESIZE): Likewise.\n* include/private/gcconfig.h (GET_MEM): Likewise.\n* mallocx.c (GC_malloc_many, GC_memalign): Likewise.\n* os_dep.c (GC_wince_get_mem, GC_win32_get_mem): Likewise.\n* typd_mlc.c (GC_malloc_explicitly_typed,\nGC_malloc_explicitly_typed_ignore_off_page,\nGC_calloc_explicitly_typed): Likewise.\n* headers.c (GC_scratch_alloc): Change type of bytes_to_get from word\nto size_t (because ROUNDUP_PAGESIZE_IF_MMAP result type changed).\n* include/private/gc_priv.h: Include limits.h (unless SIZE_MAX already\ndefined).\n* include/private/gc_priv.h (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Move from\nmalloc.c file.\n* include/private/gc_priv.h (SIZET_SAT_ADD): New macro (defined before\ninclude gcconfig.h).\n* include/private/gc_priv.h (EXTRA_BYTES, GC_page_size): Change type\nto size_t.\n* os_dep.c (GC_page_size): Likewise.\n* include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES,\nADD_SLOP, ROUNDUP_PAGESIZE): Add comment about the argument.\n* include/private/gcconfig.h (GET_MEM): Likewise.\n* include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES,\nADD_SLOP, OBJ_SZ_TO_BLOCKS, ROUNDUP_PAGESIZE,\nROUNDUP_PAGESIZE_IF_MMAP): Rename argument to \"lb\".\n* include/private/gc_priv.h (OBJ_SZ_TO_BLOCKS_CHECKED): New macro.\n* include/private/gcconfig.h (GC_win32_get_mem, GC_wince_get_mem,\nGC_unix_get_mem): Change argument type from word to int.\n* os_dep.c (GC_unix_mmap_get_mem, GC_unix_get_mem,\nGC_unix_sbrk_get_mem, GC_wince_get_mem, GC_win32_get_mem): Likewise.\n* malloc.c (GC_alloc_large_and_clear): Call OBJ_SZ_TO_BLOCKS only\nif no value wrap around is guaranteed.\n* malloc.c (GC_generic_malloc): Do not check for lb_rounded < lb case\n(because ROUNDED_UP_GRANULES and GRANULES_TO_BYTES guarantees no value\nwrap around).\n* mallocx.c (GC_generic_malloc_ignore_off_page): Likewise.\n* misc.c (GC_init_size_map): Change \"i\" local variable type from int\nto size_t.\n* os_dep.c (GC_write_fault_handler, catch_exception_raise): Likewise.\n* misc.c (GC_envfile_init): Cast len to size_t when passed to\nROUNDUP_PAGESIZE_IF_MMAP.\n* os_dep.c (GC_setpagesize): Cast GC_sysinfo.dwPageSize and\nGETPAGESIZE() to size_t (when setting GC_page_size).\n* os_dep.c (GC_unix_mmap_get_mem, GC_unmap_start, GC_remove_protection):\nExpand ROUNDUP_PAGESIZE macro but without value wrap-around checking\n(the argument is of word type).\n* os_dep.c (GC_unix_mmap_get_mem): Replace -GC_page_size with\n~GC_page_size+1 (because GC_page_size is unsigned); remove redundant\ncast to size_t.\n* os_dep.c (GC_unix_sbrk_get_mem): Add explicit cast of GC_page_size\nto SBRK_ARG_T.\n* os_dep.c (GC_wince_get_mem): Change type of res_bytes local variable\nto size_t.\n* typd_mlc.c: Do not include limits.h.\n* typd_mlc.c (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Remove (as defined in\ngc_priv.h now).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ptr_t GC_unix_get_mem(word bytes)\n {\n return GC_unix_mmap_get_mem(bytes);\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix malloc routines to prevent size value wrap-around\n\nSee issue #135 on Github.\n\n* allchblk.c (GC_allochblk, GC_allochblk_nth): Use\nOBJ_SZ_TO_BLOCKS_CHECKED instead of OBJ_SZ_TO_BLOCKS.\n* malloc.c (GC_alloc_large): Likewise.\n* alloc.c (GC_expand_hp_inner): Type of \"bytes\" local variable changed\nfrom word to size_t; cast ROUNDUP_PAGESIZE argument to size_t; prevent\noverflow when computing GC_heapsize+bytes > GC_max_heapsize.\n* dbg_mlc.c (GC_debug_malloc, GC_debug_malloc_ignore_off_page,\nGC_debug_malloc_atomic_ignore_off_page, GC_debug_generic_malloc,\nGC_debug_generic_malloc_inner,\nGC_debug_generic_malloc_inner_ignore_off_page,\nGC_debug_malloc_stubborn, GC_debug_malloc_atomic,\nGC_debug_malloc_uncollectable, GC_debug_malloc_atomic_uncollectable):\nUse SIZET_SAT_ADD (instead of \"+\" operator) to add extra bytes to lb\nvalue.\n* fnlz_mlc.c (GC_finalized_malloc): Likewise.\n* gcj_mlc.c (GC_debug_gcj_malloc): Likewise.\n* include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES,\nADD_SLOP, ROUNDUP_PAGESIZE): Likewise.\n* include/private/gcconfig.h (GET_MEM): Likewise.\n* mallocx.c (GC_malloc_many, GC_memalign): Likewise.\n* os_dep.c (GC_wince_get_mem, GC_win32_get_mem): Likewise.\n* typd_mlc.c (GC_malloc_explicitly_typed,\nGC_malloc_explicitly_typed_ignore_off_page,\nGC_calloc_explicitly_typed): Likewise.\n* headers.c (GC_scratch_alloc): Change type of bytes_to_get from word\nto size_t (because ROUNDUP_PAGESIZE_IF_MMAP result type changed).\n* include/private/gc_priv.h: Include limits.h (unless SIZE_MAX already\ndefined).\n* include/private/gc_priv.h (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Move from\nmalloc.c file.\n* include/private/gc_priv.h (SIZET_SAT_ADD): New macro (defined before\ninclude gcconfig.h).\n* include/private/gc_priv.h (EXTRA_BYTES, GC_page_size): Change type\nto size_t.\n* os_dep.c (GC_page_size): Likewise.\n* include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES,\nADD_SLOP, ROUNDUP_PAGESIZE): Add comment about the argument.\n* include/private/gcconfig.h (GET_MEM): Likewise.\n* include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES,\nADD_SLOP, OBJ_SZ_TO_BLOCKS, ROUNDUP_PAGESIZE,\nROUNDUP_PAGESIZE_IF_MMAP): Rename argument to \"lb\".\n* include/private/gc_priv.h (OBJ_SZ_TO_BLOCKS_CHECKED): New macro.\n* include/private/gcconfig.h (GC_win32_get_mem, GC_wince_get_mem,\nGC_unix_get_mem): Change argument type from word to int.\n* os_dep.c (GC_unix_mmap_get_mem, GC_unix_get_mem,\nGC_unix_sbrk_get_mem, GC_wince_get_mem, GC_win32_get_mem): Likewise.\n* malloc.c (GC_alloc_large_and_clear): Call OBJ_SZ_TO_BLOCKS only\nif no value wrap around is guaranteed.\n* malloc.c (GC_generic_malloc): Do not check for lb_rounded < lb case\n(because ROUNDED_UP_GRANULES and GRANULES_TO_BYTES guarantees no value\nwrap around).\n* mallocx.c (GC_generic_malloc_ignore_off_page): Likewise.\n* misc.c (GC_init_size_map): Change \"i\" local variable type from int\nto size_t.\n* os_dep.c (GC_write_fault_handler, catch_exception_raise): Likewise.\n* misc.c (GC_envfile_init): Cast len to size_t when passed to\nROUNDUP_PAGESIZE_IF_MMAP.\n* os_dep.c (GC_setpagesize): Cast GC_sysinfo.dwPageSize and\nGETPAGESIZE() to size_t (when setting GC_page_size).\n* os_dep.c (GC_unix_mmap_get_mem, GC_unmap_start, GC_remove_protection):\nExpand ROUNDUP_PAGESIZE macro but without value wrap-around checking\n(the argument is of word type).\n* os_dep.c (GC_unix_mmap_get_mem): Replace -GC_page_size with\n~GC_page_size+1 (because GC_page_size is unsigned); remove redundant\ncast to size_t.\n* os_dep.c (GC_unix_sbrk_get_mem): Add explicit cast of GC_page_size\nto SBRK_ARG_T.\n* os_dep.c (GC_wince_get_mem): Change type of res_bytes local variable\nto size_t.\n* typd_mlc.c: Do not include limits.h.\n* typd_mlc.c (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Remove (as defined in\ngc_priv.h now).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: process_button(struct parsed_tag *tag)\n{\n Str tmp = NULL;\n char *p, *q, *r, *qq = \"\";\n int qlen, v;\n\n if (cur_form_id < 0) {\n char *s = \"\";\n tmp = process_form(parse_tag(&s, TRUE));\n }\n if (tmp == NULL)\n tmp = Strnew();\n\n p = \"submit\";\n parsedtag_get_value(tag, ATTR_TYPE, &p);\n q = NULL;\n parsedtag_get_value(tag, ATTR_VALUE, &q);\n r = \"\";\n parsedtag_get_value(tag, ATTR_NAME, &r);\n\n v = formtype(p);\n if (v == FORM_UNKNOWN)\n return NULL;\n\n if (!q) {\n switch (v) {\n case FORM_INPUT_SUBMIT:\n case FORM_INPUT_BUTTON:\n q = \"SUBMIT\";\n break;\n case FORM_INPUT_RESET:\n q = \"RESET\";\n break;\n }\n }\n if (q) {\n qq = html_quote(q);\n qlen = strlen(q);\n }\n\n /* Strcat_charp(tmp, \"\"); */\n Strcat(tmp, Sprintf(\"\",\n cur_hseq++, cur_form_id, html_quote(p),\n html_quote(r), qq));\n return tmp;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Prevent segfault with incorrect button type\n\nBug-Debian: https://github.com/tats/w3m/issues/17'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: formUpdateBuffer(Anchor *a, Buffer *buf, FormItemList *form)\n{\n Buffer save;\n char *p;\n int spos, epos, rows, c_rows, pos, col = 0;\n Line *l;\n\n copyBuffer(&save, buf);\n gotoLine(buf, a->start.line);\n switch (form->type) {\n case FORM_TEXTAREA:\n case FORM_INPUT_TEXT:\n case FORM_INPUT_FILE:\n case FORM_INPUT_PASSWORD:\n case FORM_INPUT_CHECKBOX:\n case FORM_INPUT_RADIO:\n#ifdef MENU_SELECT\n case FORM_SELECT:\n#endif\t\t\t\t/* MENU_SELECT */\n\tspos = a->start.pos;\n\tepos = a->end.pos;\n\tbreak;\n default:\n\tspos = a->start.pos + 1;\n\tepos = a->end.pos - 1;\n }\n switch (form->type) {\n case FORM_INPUT_CHECKBOX:\n case FORM_INPUT_RADIO:\n\tif (spos >= buf->currentLine->len || spos < 0)\n\t break;\n\tif (form->checked)\n\t buf->currentLine->lineBuf[spos] = '*';\n\telse\n\t buf->currentLine->lineBuf[spos] = ' ';\n\tbreak;\n case FORM_INPUT_TEXT:\n case FORM_INPUT_FILE:\n case FORM_INPUT_PASSWORD:\n case FORM_TEXTAREA:\n#ifdef MENU_SELECT\n case FORM_SELECT:\n\tif (form->type == FORM_SELECT) {\n\t p = form->label->ptr;\n\t updateSelectOption(form, form->select_option);\n\t}\n\telse\n#endif\t\t\t\t/* MENU_SELECT */\n\t{\n\t if (!form->value)\n\t\tbreak;\n\t p = form->value->ptr;\n\t}\n\tl = buf->currentLine;\n\tif (!l)\n\t break;\n\tif (form->type == FORM_TEXTAREA) {\n\t int n = a->y - buf->currentLine->linenumber;\n\t if (n > 0)\n\t\tfor (; l && n; l = l->prev, n--) ;\n\t else if (n < 0)\n\t\tfor (; l && n; l = l->prev, n++) ;\n\t if (!l)\n\t\tbreak;\n\t}\n\trows = form->rows ? form->rows : 1;\n\tcol = COLPOS(l, a->start.pos);\n\tfor (c_rows = 0; c_rows < rows; c_rows++, l = l->next) {\n\t if (rows > 1) {\n\t\tpos = columnPos(l, col);\n\t\ta = retrieveAnchor(buf->formitem, l->linenumber, pos);\n\t\tif (a == NULL)\n\t\t break;\n\t\tspos = a->start.pos;\n\t\tepos = a->end.pos;\n\t }\n\t if (a->start.line != a->end.line || spos > epos || epos >= l->len || spos < 0 || epos < 0)\n\t\tbreak;\n\t pos = form_update_line(l, &p, spos, epos, COLPOS(l, epos) - col,\n\t\t\t\t rows > 1,\n\t\t\t\t form->type == FORM_INPUT_PASSWORD);\n\t if (pos != epos) {\n\t\tshiftAnchorPosition(buf->href, buf->hmarklist,\n\t\t\t\t a->start.line, spos, pos - epos);\n\t\tshiftAnchorPosition(buf->name, buf->hmarklist,\n\t\t\t\t a->start.line, spos, pos - epos);\n\t\tshiftAnchorPosition(buf->img, buf->hmarklist,\n\t\t\t\t a->start.line, spos, pos - epos);\n\t\tshiftAnchorPosition(buf->formitem, buf->hmarklist,\n\t\t\t\t a->start.line, spos, pos - epos);\n\t }\n\t}\n\tbreak;\n }\n copyBuffer(buf, &save);\n arrangeLine(buf);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Prevent dereference near-null pointer in formUpdateBuffer\n\nBug-Debian: https://github.com/tats/w3m/issues/35'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: wc_any_to_ucs(wc_wchar_t cc)\n{\n int f;\n wc_uint16 *map = NULL;\n wc_uint32 map_size = 0x80;\n wc_map *map2;\n\n f = WC_CCS_INDEX(cc.ccs);\n switch (WC_CCS_TYPE(cc.ccs)) {\n case WC_CCS_A_CS94:\n\tif (cc.ccs == WC_CCS_US_ASCII)\n\t return cc.code;\n\tif (f < WC_F_ISO_BASE || f > WC_F_CS94_END)\n\t return WC_C_UCS4_ERROR;\n\tmap = cs94_ucs_map[f - WC_F_ISO_BASE];\n\tcc.code &= 0x7f;\n\tbreak;\n case WC_CCS_A_CS94W:\n\tif (cc.ccs == WC_CCS_GB_2312 && WcOption.use_gb12345_map) {\n\t cc.ccs = WC_CCS_GB_12345;\n\t return wc_any_to_ucs(cc);\n\t} else if (cc.ccs == WC_CCS_JIS_X_0213_1) {\n\t map2 = wc_map_search((wc_uint16)(cc.code & 0x7f7f),\n\t\tjisx02131_ucs_p2_map, N_jisx02131_ucs_p2_map);\n\t if (map2)\n\t\treturn map2->code2 | WC_C_UCS4_PLANE2;\n\t} else if (cc.ccs == WC_CCS_JIS_X_0213_2) {\n\t map2 = wc_map_search((wc_uint16)(cc.code & 0x7f7f),\n\t\tjisx02132_ucs_p2_map, N_jisx02132_ucs_p2_map);\n\t if (map2)\n\t\treturn map2->code2 | WC_C_UCS4_PLANE2;\n\t}\n\tif (f < WC_F_ISO_BASE || f > WC_F_CS94W_END)\n\t return 0;\n\tmap = cs94w_ucs_map[f - WC_F_ISO_BASE];\n\tmap_size = cs94w_ucs_map_size[f - WC_F_ISO_BASE];\n\tcc.code = WC_CS94W_N(cc.code);\n\tbreak;\n case WC_CCS_A_CS96:\n\tif (f < WC_F_ISO_BASE || f > WC_F_CS96_END)\n\t return WC_C_UCS4_ERROR;\n\tmap = cs96_ucs_map[f - WC_F_ISO_BASE];\n\tcc.code &= 0x7f;\n\tbreak;\n case WC_CCS_A_CS96W:\n\tif (f < WC_F_ISO_BASE || f > WC_F_CS96W_END)\n\t return WC_C_UCS4_ERROR;\n\tmap = cs96w_ucs_map[f - WC_F_ISO_BASE];\n\tmap_size = cs96w_ucs_map_size[f - WC_F_ISO_BASE];\n\tcc.code = WC_CS96W_N(cc.code);\n\tbreak;\n case WC_CCS_A_CS942:\n\tif (f < WC_F_ISO_BASE || f > WC_F_CS942_END)\n\t return WC_C_UCS4_ERROR;\n\tmap = cs942_ucs_map[f - WC_F_ISO_BASE];\n\tcc.code &= 0x7f;\n\tbreak;\n case WC_CCS_A_PCS:\n\tif (f < WC_F_PCS_BASE || f > WC_F_PCS_END)\n\t return WC_C_UCS4_ERROR;\n\tswitch (cc.ccs) {\n\tcase WC_CCS_CP1258_2:\n\t map2 = wc_map_search((wc_uint16)cc.code,\n\t\tcp12582_ucs_map, N_cp12582_ucs_map);\n\t if (map2)\n\t\treturn map2->code2;\n\t return WC_C_UCS4_ERROR;\n\tcase WC_CCS_TCVN_5712_3:\n\t return wc_any_to_ucs(wc_tcvn57123_to_tcvn5712(cc));\n\tcase WC_CCS_GBK_80:\n\t return WC_C_UCS2_EURO;\n\t}\n\tmap = pcs_ucs_map[f - WC_F_PCS_BASE];\n\tcc.code &= 0x7f;\n\tbreak;\n case WC_CCS_A_PCSW:\n\tif (f < WC_F_PCS_BASE || f > WC_F_PCSW_END)\n\t return WC_C_UCS4_ERROR;\n\tmap = pcsw_ucs_map[f - WC_F_PCS_BASE];\n\tmap_size = pcsw_ucs_map_size[f - WC_F_PCS_BASE];\n\tswitch (cc.ccs) {\n\tcase WC_CCS_BIG5:\n\t cc.code = WC_BIG5_N(cc.code);\n\t break;\n\tcase WC_CCS_BIG5_2:\n\t cc.code = WC_CS94W_N(cc.code) + WC_C_BIG5_2_BASE;\n\t break;\n\tcase WC_CCS_HKSCS_1:\n\tcase WC_CCS_HKSCS_2:\n\t cc = wc_cs128w_to_hkscs(cc);\n\tcase WC_CCS_HKSCS:\n\t map2 = wc_map_search((wc_uint16)cc.code,\n\t\thkscs_ucs_p2_map, N_hkscs_ucs_p2_map);\n\t if (map2)\n\t\treturn map2->code2 | WC_C_UCS4_PLANE2;\n\t cc.code = wc_hkscs_to_N(cc.code);\n\t break;\n\tcase WC_CCS_JOHAB:\n\t return wc_any_to_ucs(wc_johab_to_cs128w(cc));\n\tcase WC_CCS_JOHAB_1:\n\t return WC_CS94x128_N(cc.code) + WC_C_UCS2_HANGUL;\n\tcase WC_CCS_JOHAB_2:\n\t cc.code = WC_CS128W_N(cc.code);\n\t cc.code = WC_N_JOHAB2(cc.code);\n\t map2 = wc_map_search((wc_uint16)cc.code,\n\t\tjohab2_ucs_map, N_johab2_ucs_map);\n\t if (map2)\n\t\treturn map2->code2;\n\t return WC_C_UCS4_ERROR;\n\tcase WC_CCS_JOHAB_3:\n\t if ((cc.code & 0x7f7f) < 0x2121)\n\t\treturn WC_C_UCS4_ERROR;\n\tcase WC_CCS_SJIS_EXT:\n\t return wc_any_to_ucs(wc_sjis_ext_to_cs94w(cc));\n\tcase WC_CCS_SJIS_EXT_1:\n\t cc.code = wc_sjis_ext1_to_N(cc.code);\n\t if (cc.code == WC_C_SJIS_ERROR)\n\t\treturn WC_C_UCS4_ERROR;\n\t break;\n\tcase WC_CCS_SJIS_EXT_2:\n\t cc.code = wc_sjis_ext2_to_N(cc.code);\n\t if (cc.code == WC_C_SJIS_ERROR)\n\t\treturn WC_C_UCS4_ERROR;\n\t break;\n\tcase WC_CCS_GBK_1:\n\tcase WC_CCS_GBK_2:\n\t cc = wc_cs128w_to_gbk(cc);\n\tcase WC_CCS_GBK:\n\t cc.code = wc_gbk_to_N(cc.code);\n\t break;\n\tcase WC_CCS_GBK_EXT:\n\tcase WC_CCS_GBK_EXT_1:\n\tcase WC_CCS_GBK_EXT_2:\n\t return wc_gb18030_to_ucs(cc);\n\tcase WC_CCS_UHC_1:\n\tcase WC_CCS_UHC_2:\n\t cc = wc_cs128w_to_uhc(cc);\n\tcase WC_CCS_UHC:\n\t if (cc.code > WC_C_UHC_END)\n\t\treturn WC_C_UCS4_ERROR;\n\t cc.code = wc_uhc_to_N(cc.code);\n\t break;\n\tdefault:\n\t cc.code = WC_CS94W_N(cc.code);\n\t break;\n\t}\n\tbreak;\n case WC_CCS_A_WCS16:\n\tswitch (WC_CCS_SET(cc.ccs)) {\n\tcase WC_CCS_UCS2:\n\t return cc.code;\n\t}\n\treturn WC_C_UCS4_ERROR;\n case WC_CCS_A_WCS32:\n\tswitch (WC_CCS_SET(cc.ccs)) {\n\tcase WC_CCS_UCS4:\n\t return cc.code;\n\tcase WC_CCS_UCS_TAG:\n\t return wc_ucs_tag_to_ucs(cc.code);\n\tcase WC_CCS_GB18030:\n\t return wc_gb18030_to_ucs(cc);\n\t}\n\treturn WC_C_UCS4_ERROR;\n case WC_CCS_A_UNKNOWN:\n\tif (cc.ccs == WC_CCS_C1)\n\t return (cc.code | 0x80);\n default:\n\treturn WC_C_UCS4_ERROR;\n }\n if (map == NULL)\n\treturn WC_C_UCS4_ERROR;\n if (map_size == 0 || cc.code > map_size - 1)\n\treturn WC_C_UCS4_ERROR;\n cc.code = map[cc.code];\n return cc.code ? cc.code : WC_C_UCS4_ERROR;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Prevent global-buffer-overflow in wc_any_to_ucs()\n\nBug-Debian: https://github.com/tats/w3m/issues/43'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: windows_icon_typefind (GstTypeFind * find, gpointer user_data)\n{\n const guint8 *data;\n gint64 datalen;\n guint16 type, nimages;\n gint32 size, offset;\n\n datalen = gst_type_find_get_length (find);\n if ((data = gst_type_find_peek (find, 0, 6)) == NULL)\n return;\n\n /* header - simple and not enough to rely on it alone */\n if (GST_READ_UINT16_LE (data) != 0)\n return;\n type = GST_READ_UINT16_LE (data + 2);\n if (type != 1 && type != 2)\n return;\n nimages = GST_READ_UINT16_LE (data + 4);\n if (nimages == 0) /* we can assume we can't have an empty image file ? */\n return;\n\n /* first image */\n if (data[6 + 3] != 0)\n return;\n if (type == 1) {\n guint16 planes = GST_READ_UINT16_LE (data + 6 + 4);\n if (planes > 1)\n return;\n }\n size = GST_READ_UINT32_LE (data + 6 + 8);\n offset = GST_READ_UINT32_LE (data + 6 + 12);\n if (offset < 0 || size <= 0 || size >= datalen || offset >= datalen\n || size + offset > datalen)\n return;\n\n gst_type_find_suggest_simple (find, GST_TYPE_FIND_NEARLY_CERTAIN,\n \"image/x-icon\", NULL);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'typefind: bounds check windows ico detection\n\nFixes out of bounds read\n\nhttps://bugzilla.gnome.org/show_bug.cgi?id=774902'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void qemu_chr_be_write_impl(CharDriverState *s, uint8_t *buf, int len)\n{\n if (s->chr_read) {\n s->chr_read(s->handler_opaque, buf, len);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'char: move front end handlers in CharBackend\n\nSince the hanlders are associated with a CharBackend, rather than the\nCharDriverState, it is more appropriate to store in CharBackend. This\navoids the handler copy dance in qemu_chr_fe_set_handlers() then\nmux_chr_update_read_handler(), by storing the CharBackend pointer\ndirectly.\n\nAlso a mux CharDriver should go through mux->backends[focused], since\nchr->be will stay NULL. Before that, it was possible to call\nchr->handler by mistake with surprising results, for ex through\nqemu_chr_be_can_write(), which would result in calling the last set\nhandler front end, not the one with focus.\n\nSigned-off-by: Marc-Andr\u00e9 Lureau \nMessage-Id: <20161022095318.17775-22-marcandre.lureau@redhat.com>\nSigned-off-by: Paolo Bonzini '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void pty_chr_update_read_handler(CharDriverState *chr,\n GMainContext *context,\n int tag)\n{\n qemu_mutex_lock(&chr->chr_write_lock);\n pty_chr_update_read_handler_locked(chr);\n qemu_mutex_unlock(&chr->chr_write_lock);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'char: move front end handlers in CharBackend\n\nSince the hanlders are associated with a CharBackend, rather than the\nCharDriverState, it is more appropriate to store in CharBackend. This\navoids the handler copy dance in qemu_chr_fe_set_handlers() then\nmux_chr_update_read_handler(), by storing the CharBackend pointer\ndirectly.\n\nAlso a mux CharDriver should go through mux->backends[focused], since\nchr->be will stay NULL. Before that, it was possible to call\nchr->handler by mistake with surprising results, for ex through\nqemu_chr_be_can_write(), which would result in calling the last set\nhandler front end, not the one with focus.\n\nSigned-off-by: Marc-Andr\u00e9 Lureau \nMessage-Id: <20161022095318.17775-22-marcandre.lureau@redhat.com>\nSigned-off-by: Paolo Bonzini '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int blk_rq_map_user_iov(struct request_queue *q, struct request *rq,\n\t\t\tstruct rq_map_data *map_data,\n\t\t\tconst struct iov_iter *iter, gfp_t gfp_mask)\n{\n\tbool copy = false;\n\tunsigned long align = q->dma_pad_mask | queue_dma_alignment(q);\n\tstruct bio *bio = NULL;\n\tstruct iov_iter i;\n\tint ret;\n\n\tif (map_data)\n\t\tcopy = true;\n\telse if (iov_iter_alignment(iter) & align)\n\t\tcopy = true;\n\telse if (queue_virt_boundary(q))\n\t\tcopy = queue_virt_boundary(q) & iov_iter_gap_alignment(iter);\n\n\ti = *iter;\n\tdo {\n\t\tret =__blk_rq_map_user_iov(rq, map_data, &i, gfp_mask, copy);\n\t\tif (ret)\n\t\t\tgoto unmap_rq;\n\t\tif (!bio)\n\t\t\tbio = rq->bio;\n\t} while (iov_iter_count(&i));\n\n\tif (!bio_flagged(bio, BIO_USER_MAPPED))\n\t\trq->cmd_flags |= REQ_COPY_USER;\n\treturn 0;\n\nunmap_rq:\n\t__blk_rq_unmap_user(bio);\n\trq->bio = NULL;\n\treturn -EINVAL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Don't feed anything but regular iovec's to blk_rq_map_user_iov\n\nIn theory we could map other things, but there's a reason that function\nis called \"user_iov\". Using anything else (like splice can do) just\nconfuses it.\n\nReported-and-tested-by: Johannes Thumshirn \nCc: Al Viro \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void perf_event_disable(struct perf_event *event)\n{\n\tstruct perf_event_context *ctx = event->ctx;\n\tstruct task_struct *task = ctx->task;\n\n\tif (!task) {\n\t\t/*\n\t\t * Disable the event on the cpu that it's on\n\t\t */\n\t\tcpu_function_call(event->cpu, __perf_event_disable, event);\n\t\treturn;\n\t}\n\nretry:\n\tif (!task_function_call(task, __perf_event_disable, event))\n\t\treturn;\n\n\traw_spin_lock_irq(&ctx->lock);\n\t/*\n\t * If the event is still active, we need to retry the cross-call.\n\t */\n\tif (event->state == PERF_EVENT_STATE_ACTIVE) {\n\t\traw_spin_unlock_irq(&ctx->lock);\n\t\t/*\n\t\t * Reload the task pointer, it might have been changed by\n\t\t * a concurrent perf_event_context_sched_out().\n\t\t */\n\t\ttask = ctx->task;\n\t\tgoto retry;\n\t}\n\n\t/*\n\t * Since we have the lock this context can't be scheduled\n\t * in, so we can change the state safely.\n\t */\n\tif (event->state == PERF_EVENT_STATE_INACTIVE) {\n\t\tupdate_group_times(event);\n\t\tevent->state = PERF_EVENT_STATE_OFF;\n\t}\n\traw_spin_unlock_irq(&ctx->lock);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'perf: Fix event->ctx locking\n\nThere have been a few reported issues wrt. the lack of locking around\nchanging event->ctx. This patch tries to address those.\n\nIt avoids the whole rwsem thing; and while it appears to work, please\ngive it some thought in review.\n\nWhat I did fail at is sensible runtime checks on the use of\nevent->ctx, the RCU use makes it very hard.\n\nSigned-off-by: Peter Zijlstra (Intel) \nCc: Paul E. McKenney \nCc: Jiri Olsa \nCc: Arnaldo Carvalho de Melo \nCc: Linus Torvalds \nLink: http://lkml.kernel.org/r/20150123125834.209535886@infradead.org\nSigned-off-by: Ingo Molnar '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int perf_event_task_enable(void)\n{\n\tstruct perf_event *event;\n\n\tmutex_lock(¤t->perf_event_mutex);\n\tlist_for_each_entry(event, ¤t->perf_event_list, owner_entry)\n\t\tperf_event_for_each_child(event, perf_event_enable);\n\tmutex_unlock(¤t->perf_event_mutex);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'perf: Fix event->ctx locking\n\nThere have been a few reported issues wrt. the lack of locking around\nchanging event->ctx. This patch tries to address those.\n\nIt avoids the whole rwsem thing; and while it appears to work, please\ngive it some thought in review.\n\nWhat I did fail at is sensible runtime checks on the use of\nevent->ctx, the RCU use makes it very hard.\n\nSigned-off-by: Peter Zijlstra (Intel) \nCc: Paul E. McKenney \nCc: Jiri Olsa \nCc: Arnaldo Carvalho de Melo \nCc: Linus Torvalds \nLink: http://lkml.kernel.org/r/20150123125834.209535886@infradead.org\nSigned-off-by: Ingo Molnar '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: */\nstatic void php_wddx_serialize_object(wddx_packet *packet, zval *obj)\n{\n/* OBJECTS_FIXME */\n\tzval **ent, *fname, **varname;\n\tzval *retval = NULL;\n\tconst char *key;\n\tulong idx;\n\tchar tmp_buf[WDDX_BUF_LEN];\n\tHashTable *objhash, *sleephash;\n\tTSRMLS_FETCH();\n\n\tMAKE_STD_ZVAL(fname);\n\tZVAL_STRING(fname, \"__sleep\", 1);\n\n\t/*\n\t * We try to call __sleep() method on object. It's supposed to return an\n\t * array of property names to be serialized.\n\t */\n\tif (call_user_function_ex(CG(function_table), &obj, fname, &retval, 0, 0, 1, NULL TSRMLS_CC) == SUCCESS) {\n\t\tif (retval && (sleephash = HASH_OF(retval))) {\n\t\t\tPHP_CLASS_ATTRIBUTES;\n\n\t\t\tPHP_SET_CLASS_ATTRIBUTES(obj);\n\n\t\t\tphp_wddx_add_chunk_static(packet, WDDX_STRUCT_S);\n\t\t\tsnprintf(tmp_buf, WDDX_BUF_LEN, WDDX_VAR_S, PHP_CLASS_NAME_VAR);\n\t\t\tphp_wddx_add_chunk(packet, tmp_buf);\n\t\t\tphp_wddx_add_chunk_static(packet, WDDX_STRING_S);\n\t\t\tphp_wddx_add_chunk_ex(packet, class_name, name_len);\n\t\t\tphp_wddx_add_chunk_static(packet, WDDX_STRING_E);\n\t\t\tphp_wddx_add_chunk_static(packet, WDDX_VAR_E);\n\n\t\t\tPHP_CLEANUP_CLASS_ATTRIBUTES();\n\n\t\t\tobjhash = HASH_OF(obj);\n\n\t\t\tfor (zend_hash_internal_pointer_reset(sleephash);\n\t\t\t\t zend_hash_get_current_data(sleephash, (void **)&varname) == SUCCESS;\n\t\t\t\t zend_hash_move_forward(sleephash)) {\n\t\t\t\tif (Z_TYPE_PP(varname) != IS_STRING) {\n\t\t\t\t\tphp_error_docref(NULL TSRMLS_CC, E_NOTICE, \"__sleep should return an array only containing the names of instance-variables to serialize.\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (zend_hash_find(objhash, Z_STRVAL_PP(varname), Z_STRLEN_PP(varname)+1, (void **)&ent) == SUCCESS) {\n\t\t\t\t\tphp_wddx_serialize_var(packet, *ent, Z_STRVAL_PP(varname), Z_STRLEN_PP(varname) TSRMLS_CC);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tphp_wddx_add_chunk_static(packet, WDDX_STRUCT_E);\n\t\t}\n\t} else {\n\t\tuint key_len;\n\n\t\tPHP_CLASS_ATTRIBUTES;\n\n\t\tPHP_SET_CLASS_ATTRIBUTES(obj);\n\n\t\tphp_wddx_add_chunk_static(packet, WDDX_STRUCT_S);\n\t\tsnprintf(tmp_buf, WDDX_BUF_LEN, WDDX_VAR_S, PHP_CLASS_NAME_VAR);\n\t\tphp_wddx_add_chunk(packet, tmp_buf);\n\t\tphp_wddx_add_chunk_static(packet, WDDX_STRING_S);\n\t\tphp_wddx_add_chunk_ex(packet, class_name, name_len);\n\t\tphp_wddx_add_chunk_static(packet, WDDX_STRING_E);\n\t\tphp_wddx_add_chunk_static(packet, WDDX_VAR_E);\n\n\t\tPHP_CLEANUP_CLASS_ATTRIBUTES();\n\n\t\tobjhash = HASH_OF(obj);\n\t\tfor (zend_hash_internal_pointer_reset(objhash);\n\t\t\t zend_hash_get_current_data(objhash, (void**)&ent) == SUCCESS;\n\t\t\t zend_hash_move_forward(objhash)) {\n\t\t\tif (*ent == obj) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (zend_hash_get_current_key_ex(objhash, &key, &key_len, &idx, 0, NULL) == HASH_KEY_IS_STRING) {\n\t\t\t\tconst char *class_name, *prop_name;\n\n\t\t\t\tzend_unmangle_property_name(key, key_len-1, &class_name, &prop_name);\n\t\t\t\tphp_wddx_serialize_var(packet, *ent, prop_name, strlen(prop_name)+1 TSRMLS_CC);\n\t\t\t} else {\n\t\t\t\tkey_len = slprintf(tmp_buf, sizeof(tmp_buf), \"%ld\", idx);\n\t\t\t\tphp_wddx_serialize_var(packet, *ent, tmp_buf, key_len TSRMLS_CC);\n\t\t\t}\n\t\t}\n\t\tphp_wddx_add_chunk_static(packet, WDDX_STRUCT_E);\n\t}\n\n\tzval_dtor(fname);\n\tFREE_ZVAL(fname);\n\n\tif (retval) {\n\t\tzval_ptr_dtor(&retval);\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fix bug #73331 - do not try to serialize/unserialize objects wddx can not handle\n\nProper soltion would be to call serialize/unserialize and deal with the result,\nbut this requires more work that should be done by wddx maintainer (not me).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int jpc_pi_nextrpcl(register jpc_pi_t *pi)\n{\n\tint rlvlno;\n\tjpc_pirlvl_t *pirlvl;\n\tjpc_pchg_t *pchg;\n\tint prchind;\n\tint prcvind;\n\tint *prclyrno;\n\tint compno;\n\tjpc_picomp_t *picomp;\n\tint xstep;\n\tint ystep;\n\tuint_fast32_t r;\n\tuint_fast32_t rpx;\n\tuint_fast32_t rpy;\n\tuint_fast32_t trx0;\n\tuint_fast32_t try0;\n\n\tpchg = pi->pchg;\n\tif (!pi->prgvolfirst) {\n\t\tgoto skip;\n\t} else {\n\t\tpi->xstep = 0;\n\t\tpi->ystep = 0;\n\t\tfor (compno = 0, picomp = pi->picomps; compno < pi->numcomps;\n\t\t ++compno, ++picomp) {\n\t\t\tfor (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno <\n\t\t\t picomp->numrlvls; ++rlvlno, ++pirlvl) {\n\t\t\t\txstep = picomp->hsamp * (1 << (pirlvl->prcwidthexpn +\n\t\t\t\t picomp->numrlvls - rlvlno - 1));\n\t\t\t\tystep = picomp->vsamp * (1 << (pirlvl->prcheightexpn +\n\t\t\t\t picomp->numrlvls - rlvlno - 1));\n\t\t\t\tpi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep);\n\t\t\t\tpi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep);\n\t\t\t}\n\t\t}\n\t\tpi->prgvolfirst = 0;\n\t}\n\n\tfor (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend &&\n\t pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) {\n\t\tfor (pi->y = pi->ystart; pi->y < pi->yend; pi->y +=\n\t\t pi->ystep - (pi->y % pi->ystep)) {\n\t\t\tfor (pi->x = pi->xstart; pi->x < pi->xend; pi->x +=\n\t\t\t pi->xstep - (pi->x % pi->xstep)) {\n\t\t\t\tfor (pi->compno = pchg->compnostart,\n\t\t\t\t pi->picomp = &pi->picomps[pi->compno];\n\t\t\t\t pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno <\n\t\t\t\t pi->numcomps; ++pi->compno, ++pi->picomp) {\n\t\t\t\t\tif (pi->rlvlno >= pi->picomp->numrlvls) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tpi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];\n\t\t\t\t\tif (pi->pirlvl->numprcs == 0) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tr = pi->picomp->numrlvls - 1 - pi->rlvlno;\n\t\t\t\t\trpx = r + pi->pirlvl->prcwidthexpn;\n\t\t\t\t\trpy = r + pi->pirlvl->prcheightexpn;\n\t\t\t\t\ttrx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);\n\t\t\t\t\ttry0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);\n\t\t\t\t\tif (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx)))\n\t\t\t\t\t || !(pi->x % (1 << rpx))) &&\n\t\t\t\t\t ((pi->y == pi->ystart && ((try0 << r) % (1 << rpy)))\n\t\t\t\t\t || !(pi->y % (1 << rpy)))) {\n\t\t\t\t\t\tprchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp\n\t\t\t\t\t\t << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0,\n\t\t\t\t\t\t pi->pirlvl->prcwidthexpn);\n\t\t\t\t\t\tprcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp\n\t\t\t\t\t\t << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0,\n\t\t\t\t\t\t pi->pirlvl->prcheightexpn);\n\t\t\t\t\t\tpi->prcno = prcvind * pi->pirlvl->numhprcs + prchind;\n\n\t\t\t\t\t\tassert(pi->prcno < pi->pirlvl->numprcs);\n\t\t\t\t\t\tfor (pi->lyrno = 0; pi->lyrno <\n\t\t\t\t\t\t pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) {\n\t\t\t\t\t\t\tprclyrno = &pi->pirlvl->prclyrnos[pi->prcno];\n\t\t\t\t\t\t\tif (pi->lyrno >= *prclyrno) {\n\t\t\t\t\t\t\t\t++(*prclyrno);\n\t\t\t\t\t\t\t\treturn 0;\n\t\t\t\t\t\t\t}\nskip:\n\t\t\t\t\t\t\t;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed numerous integer overflow problems in the code for packet iterators\nin the JPC decoder.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadTIFFImage(const ImageInfo *image_info,\n ExceptionInfo *exception)\n{\n const char\n *option;\n\n float\n *chromaticity,\n x_position,\n y_position,\n x_resolution,\n y_resolution;\n\n Image\n *image;\n\n int\n tiff_status;\n\n MagickBooleanType\n status;\n\n MagickSizeType\n number_pixels;\n\n QuantumInfo\n *quantum_info;\n\n QuantumType\n quantum_type;\n\n register ssize_t\n i;\n\n size_t\n pad;\n\n ssize_t\n y;\n\n TIFF\n *tiff;\n\n TIFFMethodType\n method;\n\n uint16\n compress_tag,\n bits_per_sample,\n endian,\n extra_samples,\n interlace,\n max_sample_value,\n min_sample_value,\n orientation,\n pages,\n photometric,\n *sample_info,\n sample_format,\n samples_per_pixel,\n units,\n value;\n\n uint32\n height,\n rows_per_strip,\n width;\n\n unsigned char\n *pixels;\n\n /*\n Open image.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n (void) SetMagickThreadValue(tiff_exception,exception);\n tiff=TIFFClientOpen(image->filename,\"rb\",(thandle_t) image,TIFFReadBlob,\n TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,\n TIFFUnmapBlob);\n if (tiff == (TIFF *) NULL)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n if (image_info->number_scenes != 0)\n {\n /*\n Generate blank images for subimage specification (e.g. image.tif[4].\n We need to check the number of directores because it is possible that\n the subimage(s) are stored in the photoshop profile.\n */\n if (image_info->scene < (size_t) TIFFNumberOfDirectories(tiff))\n {\n for (i=0; i < (ssize_t) image_info->scene; i++)\n {\n status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;\n if (status == MagickFalse)\n {\n TIFFClose(tiff);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n AcquireNextImage(image_info,image,exception);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n TIFFClose(tiff);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n }\n }\n }\n do\n {\nDisableMSCWarning(4127)\n if (0 && (image_info->verbose != MagickFalse))\n TIFFPrintDirectory(tiff,stdout,MagickFalse);\nRestoreMSCWarning\n if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) ||\n (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric) != 1))\n {\n TIFFClose(tiff);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n if (sample_format == SAMPLEFORMAT_IEEEFP)\n (void) SetImageProperty(image,\"quantum:format\",\"floating-point\",\n exception);\n switch (photometric)\n {\n case PHOTOMETRIC_MINISBLACK:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"min-is-black\",\n exception);\n break;\n }\n case PHOTOMETRIC_MINISWHITE:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"min-is-white\",\n exception);\n break;\n }\n case PHOTOMETRIC_PALETTE:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"palette\",exception);\n break;\n }\n case PHOTOMETRIC_RGB:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"RGB\",exception);\n break;\n }\n case PHOTOMETRIC_CIELAB:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"CIELAB\",exception);\n break;\n }\n case PHOTOMETRIC_LOGL:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"CIE Log2(L)\",\n exception);\n break;\n }\n case PHOTOMETRIC_LOGLUV:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"LOGLUV\",exception);\n break;\n }\n#if defined(PHOTOMETRIC_MASK)\n case PHOTOMETRIC_MASK:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"MASK\",exception);\n break;\n }\n#endif\n case PHOTOMETRIC_SEPARATED:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"separated\",exception);\n break;\n }\n case PHOTOMETRIC_YCBCR:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"YCBCR\",exception);\n break;\n }\n default:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"unknown\",exception);\n break;\n }\n }\n if (image->debug != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Geometry: %ux%u\",\n (unsigned int) width,(unsigned int) height);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Interlace: %u\",\n interlace);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"Bits per sample: %u\",bits_per_sample);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"Min sample value: %u\",min_sample_value);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"Max sample value: %u\",max_sample_value);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Photometric \"\n \"interpretation: %s\",GetImageProperty(image,\"tiff:photometric\",\n exception));\n }\n image->columns=(size_t) width;\n image->rows=(size_t) height;\n image->depth=(size_t) bits_per_sample;\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Image depth: %.20g\",\n (double) image->depth);\n image->endian=MSBEndian;\n if (endian == FILLORDER_LSB2MSB)\n image->endian=LSBEndian;\n#if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN)\n if (TIFFIsBigEndian(tiff) == 0)\n {\n (void) SetImageProperty(image,\"tiff:endian\",\"lsb\",exception);\n image->endian=LSBEndian;\n }\n else\n {\n (void) SetImageProperty(image,\"tiff:endian\",\"msb\",exception);\n image->endian=MSBEndian;\n }\n#endif\n if ((photometric == PHOTOMETRIC_MINISBLACK) ||\n (photometric == PHOTOMETRIC_MINISWHITE))\n SetImageColorspace(image,GRAYColorspace,exception);\n if (photometric == PHOTOMETRIC_SEPARATED)\n SetImageColorspace(image,CMYKColorspace,exception);\n if (photometric == PHOTOMETRIC_CIELAB)\n SetImageColorspace(image,LabColorspace,exception);\n TIFFGetProfiles(tiff,image,image_info->ping,exception);\n TIFFGetProperties(tiff,image,exception);\n option=GetImageOption(image_info,\"tiff:exif-properties\");\n if (IsStringFalse(option) == MagickFalse) /* enabled by default */\n TIFFGetEXIFProperties(tiff,image,exception);\n (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,\n &samples_per_pixel);\n if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution) == 1) &&\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution) == 1))\n {\n image->resolution.x=x_resolution;\n image->resolution.y=y_resolution;\n }\n if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units) == 1)\n {\n if (units == RESUNIT_INCH)\n image->units=PixelsPerInchResolution;\n if (units == RESUNIT_CENTIMETER)\n image->units=PixelsPerCentimeterResolution;\n }\n if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position) == 1) &&\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position) == 1))\n {\n image->page.x=(ssize_t) ceil(x_position*image->resolution.x-0.5);\n image->page.y=(ssize_t) ceil(y_position*image->resolution.y-0.5);\n }\n if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation) == 1)\n image->orientation=(OrientationType) orientation;\n if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1)\n {\n if (chromaticity != (float *) NULL)\n {\n image->chromaticity.white_point.x=chromaticity[0];\n image->chromaticity.white_point.y=chromaticity[1];\n }\n }\n if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1)\n {\n if (chromaticity != (float *) NULL)\n {\n image->chromaticity.red_primary.x=chromaticity[0];\n image->chromaticity.red_primary.y=chromaticity[1];\n image->chromaticity.green_primary.x=chromaticity[2];\n image->chromaticity.green_primary.y=chromaticity[3];\n image->chromaticity.blue_primary.x=chromaticity[4];\n image->chromaticity.blue_primary.y=chromaticity[5];\n }\n }\n#if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)\n if ((compress_tag != COMPRESSION_NONE) &&\n (TIFFIsCODECConfigured(compress_tag) == 0))\n {\n TIFFClose(tiff);\n ThrowReaderException(CoderError,\"CompressNotSupported\");\n }\n#endif\n switch (compress_tag)\n {\n case COMPRESSION_NONE: image->compression=NoCompression; break;\n case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break;\n case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break;\n case COMPRESSION_JPEG:\n {\n image->compression=JPEGCompression;\n#if defined(JPEG_SUPPORT)\n {\n char\n sampling_factor[MagickPathExtent];\n\n int\n tiff_status;\n\n uint16\n horizontal,\n vertical;\n\n tiff_status=TIFFGetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,&horizontal,\n &vertical);\n if (tiff_status == 1)\n {\n (void) FormatLocaleString(sampling_factor,MagickPathExtent,\n \"%dx%d\",horizontal,vertical);\n (void) SetImageProperty(image,\"jpeg:sampling-factor\",\n sampling_factor,exception);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"Sampling Factors: %s\",sampling_factor);\n }\n }\n#endif\n break;\n }\n case COMPRESSION_OJPEG: image->compression=JPEGCompression; break;\n#if defined(COMPRESSION_LZMA)\n case COMPRESSION_LZMA: image->compression=LZMACompression; break;\n#endif\n case COMPRESSION_LZW: image->compression=LZWCompression; break;\n case COMPRESSION_DEFLATE: image->compression=ZipCompression; break;\n case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break;\n default: image->compression=RLECompression; break;\n }\n quantum_info=(QuantumInfo *) NULL;\n if ((photometric == PHOTOMETRIC_PALETTE) &&\n (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize))\n {\n size_t\n colors;\n\n colors=(size_t) GetQuantumRange(bits_per_sample)+1;\n if (AcquireImageColormap(image,colors,exception) == MagickFalse)\n {\n TIFFClose(tiff);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n }\n value=(unsigned short) image->scene;\n if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages) == 1)\n image->scene=value;\n if (image->storage_class == PseudoClass)\n {\n int\n tiff_status;\n\n size_t\n range;\n\n uint16\n *blue_colormap,\n *green_colormap,\n *red_colormap;\n\n /*\n Initialize colormap.\n */\n tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap,\n &green_colormap,&blue_colormap);\n if (tiff_status == 1)\n {\n if ((red_colormap != (uint16 *) NULL) &&\n (green_colormap != (uint16 *) NULL) &&\n (blue_colormap != (uint16 *) NULL))\n {\n range=255; /* might be old style 8-bit colormap */\n for (i=0; i < (ssize_t) image->colors; i++)\n if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) ||\n (blue_colormap[i] >= 256))\n {\n range=65535;\n break;\n }\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n image->colormap[i].red=ClampToQuantum(((double)\n QuantumRange*red_colormap[i])/range);\n image->colormap[i].green=ClampToQuantum(((double)\n QuantumRange*green_colormap[i])/range);\n image->colormap[i].blue=ClampToQuantum(((double)\n QuantumRange*blue_colormap[i])/range);\n }\n }\n }\n }\n if (image_info->ping != MagickFalse)\n {\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n goto next_tiff_frame;\n }\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n /*\n Allocate memory for the image and pixel buffer.\n */\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n {\n TIFFClose(tiff);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n if (sample_format == SAMPLEFORMAT_UINT)\n status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat);\n if (sample_format == SAMPLEFORMAT_INT)\n status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat);\n if (sample_format == SAMPLEFORMAT_IEEEFP)\n status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);\n if (status == MagickFalse)\n {\n TIFFClose(tiff);\n quantum_info=DestroyQuantumInfo(quantum_info);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n status=MagickTrue;\n switch (photometric)\n {\n case PHOTOMETRIC_MINISBLACK:\n {\n quantum_info->min_is_white=MagickFalse;\n break;\n }\n case PHOTOMETRIC_MINISWHITE:\n {\n quantum_info->min_is_white=MagickTrue;\n break;\n }\n default:\n break;\n }\n tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples,\n &sample_info);\n if (tiff_status == 1)\n {\n (void) SetImageProperty(image,\"tiff:alpha\",\"unspecified\",exception);\n if (extra_samples == 0)\n {\n if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB))\n image->alpha_trait=BlendPixelTrait;\n }\n else\n for (i=0; i < extra_samples; i++)\n {\n image->alpha_trait=BlendPixelTrait;\n if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA)\n {\n SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha);\n (void) SetImageProperty(image,\"tiff:alpha\",\"associated\",\n exception);\n }\n else\n if (sample_info[i] == EXTRASAMPLE_UNASSALPHA)\n (void) SetImageProperty(image,\"tiff:alpha\",\"unassociated\",\n exception);\n }\n }\n method=ReadGenericMethod;\n if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1)\n {\n char\n value[MagickPathExtent];\n\n method=ReadStripMethod;\n (void) FormatLocaleString(value,MagickPathExtent,\"%u\",\n (unsigned int) rows_per_strip);\n (void) SetImageProperty(image,\"tiff:rows-per-strip\",value,exception);\n }\n if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_CONTIG))\n method=ReadRGBAMethod;\n if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_SEPARATE))\n method=ReadCMYKAMethod;\n if ((photometric != PHOTOMETRIC_RGB) &&\n (photometric != PHOTOMETRIC_CIELAB) &&\n (photometric != PHOTOMETRIC_SEPARATED))\n method=ReadGenericMethod;\n if (image->storage_class == PseudoClass)\n method=ReadSingleSampleMethod;\n if ((photometric == PHOTOMETRIC_MINISBLACK) ||\n (photometric == PHOTOMETRIC_MINISWHITE))\n method=ReadSingleSampleMethod;\n if ((photometric != PHOTOMETRIC_SEPARATED) &&\n (interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64))\n method=ReadGenericMethod;\n if (image->compression == JPEGCompression)\n method=GetJPEGMethod(image,tiff,photometric,bits_per_sample,\n samples_per_pixel);\n if (compress_tag == COMPRESSION_JBIG)\n method=ReadStripMethod;\n if (TIFFIsTiled(tiff) != MagickFalse)\n method=ReadTileMethod;\n quantum_info->endian=LSBEndian;\n quantum_type=RGBQuantum;\n pixels=(unsigned char *) GetQuantumPixels(quantum_info);\n switch (method)\n {\n case ReadSingleSampleMethod:\n {\n /*\n Convert TIFF image to PseudoClass MIFF image.\n */\n quantum_type=IndexQuantum;\n pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0);\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n if (image->storage_class != PseudoClass)\n {\n quantum_type=samples_per_pixel == 1 ? AlphaQuantum :\n GrayAlphaQuantum;\n pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0);\n }\n else\n {\n quantum_type=IndexAlphaQuantum;\n pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0);\n }\n }\n else\n if (image->storage_class != PseudoClass)\n {\n quantum_type=GrayQuantum;\n pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0);\n }\n status=SetQuantumPad(image,quantum_info,pad*pow(2,ceil(log(\n bits_per_sample)/log(2))));\n if (status == MagickFalse)\n {\n TIFFClose(tiff);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n pixels=(unsigned char *) GetQuantumPixels(quantum_info);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n int\n status;\n\n register Quantum\n *magick_restrict q;\n\n status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);\n if (status == -1)\n break;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case ReadRGBAMethod:\n {\n /*\n Convert TIFF image to DirectClass MIFF image.\n */\n pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0);\n quantum_type=RGBQuantum;\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n quantum_type=RGBAQuantum;\n pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);\n }\n if (image->colorspace == CMYKColorspace)\n {\n pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);\n quantum_type=CMYKQuantum;\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n quantum_type=CMYKAQuantum;\n pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0);\n }\n }\n status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));\n if (status == MagickFalse)\n {\n TIFFClose(tiff);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n pixels=(unsigned char *) GetQuantumPixels(quantum_info);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n int\n status;\n\n register Quantum\n *magick_restrict q;\n\n status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);\n if (status == -1)\n break;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case ReadCMYKAMethod:\n {\n /*\n Convert TIFF image to DirectClass MIFF image.\n */\n for (i=0; i < (ssize_t) samples_per_pixel; i++)\n {\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;\n\n int\n status;\n\n status=TIFFReadPixels(tiff,bits_per_sample,(tsample_t) i,y,(char *)\n pixels);\n if (status == -1)\n break;\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n if (image->colorspace != CMYKColorspace)\n switch (i)\n {\n case 0: quantum_type=RedQuantum; break;\n case 1: quantum_type=GreenQuantum; break;\n case 2: quantum_type=BlueQuantum; break;\n case 3: quantum_type=AlphaQuantum; break;\n default: quantum_type=UndefinedQuantum; break;\n }\n else\n switch (i)\n {\n case 0: quantum_type=CyanQuantum; break;\n case 1: quantum_type=MagentaQuantum; break;\n case 2: quantum_type=YellowQuantum; break;\n case 3: quantum_type=BlackQuantum; break;\n case 4: quantum_type=AlphaQuantum; break;\n default: quantum_type=UndefinedQuantum; break;\n }\n (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case ReadYCCKMethod:\n {\n pixels=(unsigned char *) GetQuantumPixels(quantum_info);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n int\n status;\n\n register Quantum\n *magick_restrict q;\n\n register ssize_t\n x;\n\n unsigned char\n *p;\n\n status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);\n if (status == -1)\n break;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n p=pixels;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelCyan(image,ScaleCharToQuantum(ClampYCC((double) *p+\n (1.402*(double) *(p+2))-179.456)),q);\n SetPixelMagenta(image,ScaleCharToQuantum(ClampYCC((double) *p-\n (0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+\n 135.45984)),q);\n SetPixelYellow(image,ScaleCharToQuantum(ClampYCC((double) *p+\n (1.772*(double) *(p+1))-226.816)),q);\n SetPixelBlack(image,ScaleCharToQuantum((unsigned char) *(p+3)),q);\n q+=GetPixelChannels(image);\n p+=4;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case ReadStripMethod:\n {\n register uint32\n *p;\n\n /*\n Convert stripped TIFF image to DirectClass MIFF image.\n */\n i=0;\n p=(uint32 *) NULL;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register ssize_t\n x;\n\n register Quantum\n *magick_restrict q;\n\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n if (i == 0)\n {\n if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) pixels) == 0)\n break;\n i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t)\n image->rows-y);\n }\n i--;\n p=((uint32 *) pixels)+image->columns*i;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelRed(image,ScaleCharToQuantum((unsigned char)\n (TIFFGetR(*p))),q);\n SetPixelGreen(image,ScaleCharToQuantum((unsigned char)\n (TIFFGetG(*p))),q);\n SetPixelBlue(image,ScaleCharToQuantum((unsigned char)\n (TIFFGetB(*p))),q);\n if (image->alpha_trait != UndefinedPixelTrait)\n SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)\n (TIFFGetA(*p))),q);\n p++;\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case ReadTileMethod:\n {\n register uint32\n *p;\n\n uint32\n *tile_pixels,\n columns,\n rows;\n\n /*\n Convert tiled TIFF image to DirectClass MIFF image.\n */\n if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) ||\n (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1))\n {\n TIFFClose(tiff);\n ThrowReaderException(CoderError,\"ImageIsNotTiled\");\n }\n (void) SetImageStorageClass(image,DirectClass,exception);\n number_pixels=(MagickSizeType) columns*rows;\n if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse)\n {\n TIFFClose(tiff);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n tile_pixels=(uint32 *) AcquireQuantumMemory(columns,rows*\n sizeof(*tile_pixels));\n if (tile_pixels == (uint32 *) NULL)\n {\n TIFFClose(tiff);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n for (y=0; y < (ssize_t) image->rows; y+=rows)\n {\n register ssize_t\n x;\n\n register Quantum\n *magick_restrict q,\n *magick_restrict tile;\n\n size_t\n columns_remaining,\n rows_remaining;\n\n rows_remaining=image->rows-y;\n if ((ssize_t) (y+rows) < (ssize_t) image->rows)\n rows_remaining=rows;\n tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining,\n exception);\n if (tile == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x+=columns)\n {\n size_t\n column,\n row;\n\n if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0)\n break;\n columns_remaining=image->columns-x;\n if ((ssize_t) (x+columns) < (ssize_t) image->columns)\n columns_remaining=columns;\n p=tile_pixels+(rows-rows_remaining)*columns;\n q=tile+GetPixelChannels(image)*(image->columns*(rows_remaining-1)+\n x);\n for (row=rows_remaining; row > 0; row--)\n {\n if (image->alpha_trait != UndefinedPixelTrait)\n for (column=columns_remaining; column > 0; column--)\n {\n SetPixelRed(image,ScaleCharToQuantum((unsigned char)\n TIFFGetR(*p)),q);\n SetPixelGreen(image,ScaleCharToQuantum((unsigned char)\n TIFFGetG(*p)),q);\n SetPixelBlue(image,ScaleCharToQuantum((unsigned char)\n TIFFGetB(*p)),q);\n SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)\n TIFFGetA(*p)),q);\n p++;\n q+=GetPixelChannels(image);\n }\n else\n for (column=columns_remaining; column > 0; column--)\n {\n SetPixelRed(image,ScaleCharToQuantum((unsigned char)\n TIFFGetR(*p)),q);\n SetPixelGreen(image,ScaleCharToQuantum((unsigned char)\n TIFFGetG(*p)),q);\n SetPixelBlue(image,ScaleCharToQuantum((unsigned char)\n TIFFGetB(*p)),q);\n p++;\n q+=GetPixelChannels(image);\n }\n p+=columns-columns_remaining;\n q-=GetPixelChannels(image)*(image->columns+columns_remaining);\n }\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels);\n break;\n }\n case ReadGenericMethod:\n default:\n {\n MemoryInfo\n *pixel_info;\n\n register uint32\n *p;\n\n uint32\n *pixels;\n\n /*\n Convert TIFF image to DirectClass MIFF image.\n */\n number_pixels=(MagickSizeType) image->columns*image->rows;\n if (HeapOverflowSanityCheck(image->rows,sizeof(*pixels)) != MagickFalse)\n {\n TIFFClose(tiff);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n pixel_info=AcquireVirtualMemory(image->columns,image->rows*\n sizeof(uint32));\n if (pixel_info == (MemoryInfo *) NULL)\n {\n TIFFClose(tiff);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info);\n (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32)\n image->rows,(uint32 *) pixels,0);\n /*\n Convert image to DirectClass pixel packets.\n */\n p=pixels+number_pixels-1;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register ssize_t\n x;\n\n register Quantum\n *magick_restrict q;\n\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n q+=GetPixelChannels(image)*(image->columns-1);\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelRed(image,ScaleCharToQuantum((unsigned char)\n TIFFGetR(*p)),q);\n SetPixelGreen(image,ScaleCharToQuantum((unsigned char)\n TIFFGetG(*p)),q);\n SetPixelBlue(image,ScaleCharToQuantum((unsigned char)\n TIFFGetB(*p)),q);\n if (image->alpha_trait != UndefinedPixelTrait)\n SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)\n TIFFGetA(*p)),q);\n p--;\n q-=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n pixel_info=RelinquishVirtualMemory(pixel_info);\n break;\n }\n }\n SetQuantumImageType(image,quantum_type);\n next_tiff_frame:\n if (quantum_info != (QuantumInfo *) NULL)\n quantum_info=DestroyQuantumInfo(quantum_info);\n if (photometric == PHOTOMETRIC_CIELAB)\n DecodeLabImage(image,exception);\n if ((photometric == PHOTOMETRIC_LOGL) ||\n (photometric == PHOTOMETRIC_MINISBLACK) ||\n (photometric == PHOTOMETRIC_MINISWHITE))\n {\n image->type=GrayscaleType;\n if (bits_per_sample == 1)\n image->type=BilevelType;\n }\n /*\n Proceed to next image.\n */\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;\n if (status != MagickFalse)\n {\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image,exception);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,image->scene-1,\n image->scene);\n if (status == MagickFalse)\n break;\n }\n } while (status != MagickFalse);\n TIFFClose(tiff);\n TIFFReadPhotoshopLayers(image,image_info,exception);\n if (image_info->number_scenes != 0)\n {\n if (image_info->scene >= GetImageListLength(image))\n {\n /* Subimage was not found in the Photoshop layer */\n image=DestroyImageList(image);\n return((Image *)NULL);\n }\n }\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix possible buffer overflow when writing compressed TIFFS'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadGROUP4Image(const ImageInfo *image_info,\n ExceptionInfo *exception)\n{\n char\n filename[MagickPathExtent];\n\n FILE\n *file;\n\n Image\n *image;\n\n ImageInfo\n *read_info;\n\n int\n c,\n unique_file;\n\n MagickBooleanType\n status;\n\n size_t\n length;\n\n ssize_t\n offset,\n strip_offset;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Write raw CCITT Group 4 wrapped as a TIFF image file.\n */\n file=(FILE *) NULL;\n unique_file=AcquireUniqueFileResource(filename);\n if (unique_file != -1)\n file=fdopen(unique_file,\"wb\");\n if ((unique_file == -1) || (file == (FILE *) NULL))\n ThrowImageException(FileOpenError,\"UnableToCreateTemporaryFile\");\n length=fwrite(\"\\111\\111\\052\\000\\010\\000\\000\\000\\016\\000\",1,10,file);\n length=fwrite(\"\\376\\000\\003\\000\\001\\000\\000\\000\\000\\000\\000\\000\",1,12,file);\n length=fwrite(\"\\000\\001\\004\\000\\001\\000\\000\\000\",1,8,file);\n length=WriteLSBLong(file,image->columns);\n length=fwrite(\"\\001\\001\\004\\000\\001\\000\\000\\000\",1,8,file);\n length=WriteLSBLong(file,image->rows);\n length=fwrite(\"\\002\\001\\003\\000\\001\\000\\000\\000\\001\\000\\000\\000\",1,12,file);\n length=fwrite(\"\\003\\001\\003\\000\\001\\000\\000\\000\\004\\000\\000\\000\",1,12,file);\n length=fwrite(\"\\006\\001\\003\\000\\001\\000\\000\\000\\000\\000\\000\\000\",1,12,file);\n length=fwrite(\"\\021\\001\\003\\000\\001\\000\\000\\000\",1,8,file);\n strip_offset=10+(12*14)+4+8;\n length=WriteLSBLong(file,(size_t) strip_offset);\n length=fwrite(\"\\022\\001\\003\\000\\001\\000\\000\\000\",1,8,file);\n length=WriteLSBLong(file,(size_t) image_info->orientation);\n length=fwrite(\"\\025\\001\\003\\000\\001\\000\\000\\000\\001\\000\\000\\000\",1,12,file);\n length=fwrite(\"\\026\\001\\004\\000\\001\\000\\000\\000\",1,8,file);\n length=WriteLSBLong(file,image->rows);\n length=fwrite(\"\\027\\001\\004\\000\\001\\000\\000\\000\\000\\000\\000\\000\",1,12,file);\n offset=(ssize_t) ftell(file)-4;\n length=fwrite(\"\\032\\001\\005\\000\\001\\000\\000\\000\",1,8,file);\n length=WriteLSBLong(file,(size_t) (strip_offset-8));\n length=fwrite(\"\\033\\001\\005\\000\\001\\000\\000\\000\",1,8,file);\n length=WriteLSBLong(file,(size_t) (strip_offset-8));\n length=fwrite(\"\\050\\001\\003\\000\\001\\000\\000\\000\\002\\000\\000\\000\",1,12,file);\n length=fwrite(\"\\000\\000\\000\\000\",1,4,file);\n length=WriteLSBLong(file,(long) image->resolution.x);\n length=WriteLSBLong(file,1);\n for (length=0; (c=ReadBlobByte(image)) != EOF; length++)\n (void) fputc(c,file);\n offset=(ssize_t) fseek(file,(ssize_t) offset,SEEK_SET);\n length=WriteLSBLong(file,(unsigned int) length);\n (void) fclose(file);\n (void) CloseBlob(image);\n image=DestroyImage(image);\n /*\n Read TIFF image.\n */\n read_info=CloneImageInfo((ImageInfo *) NULL);\n (void) FormatLocaleString(read_info->filename,MagickPathExtent,\"%s\",filename);\n image=ReadTIFFImage(read_info,exception);\n read_info=DestroyImageInfo(read_info);\n if (image != (Image *) NULL)\n {\n (void) CopyMagickString(image->filename,image_info->filename,\n MagickPathExtent);\n (void) CopyMagickString(image->magick_filename,image_info->filename,\n MagickPathExtent);\n (void) CopyMagickString(image->magick,\"GROUP4\",MagickPathExtent);\n }\n (void) RelinquishUniqueFileResource(filename);\n return(image);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-703', 'CWE-252'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/196'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)\n{\n\tstruct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);\n\tint err = 0;\n\n\tmutex_lock(&swhash->hlist_mutex);\n\n\tif (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {\n\t\tstruct swevent_hlist *hlist;\n\n\t\thlist = kzalloc(sizeof(*hlist), GFP_KERNEL);\n\t\tif (!hlist) {\n\t\t\terr = -ENOMEM;\n\t\t\tgoto exit;\n\t\t}\n\t\trcu_assign_pointer(swhash->swevent_hlist, hlist);\n\t}\n\tswhash->hlist_refcount++;\nexit:\n\tmutex_unlock(&swhash->hlist_mutex);\n\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-362'], 'message': 'perf: Fix race in swevent hash\n\nThere's a race on CPU unplug where we free the swevent hash array\nwhile it can still have events on. This will result in a\nuse-after-free which is BAD.\n\nSimply do not free the hash array on unplug. This leaves the thing\naround and no use-after-free takes place.\n\nWhen the last swevent dies, we do a for_each_possible_cpu() iteration\nanyway to clean these up, at which time we'll free it, so no leakage\nwill occur.\n\nReported-by: Sasha Levin \nTested-by: Sasha Levin \nSigned-off-by: Peter Zijlstra (Intel) \nCc: Arnaldo Carvalho de Melo \nCc: Frederic Weisbecker \nCc: Jiri Olsa \nCc: Linus Torvalds \nCc: Peter Zijlstra \nCc: Stephane Eranian \nCc: Thomas Gleixner \nCc: Vince Weaver \nSigned-off-by: Ingo Molnar '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int git_pkt_parse_line(\n\tgit_pkt **head, const char *line, const char **out, size_t bufflen)\n{\n\tint ret;\n\tint32_t len;\n\n\t/* Not even enough for the length */\n\tif (bufflen > 0 && bufflen < PKT_LEN_SIZE)\n\t\treturn GIT_EBUFS;\n\n\tlen = parse_len(line);\n\tif (len < 0) {\n\t\t/*\n\t\t * If we fail to parse the length, it might be because the\n\t\t * server is trying to send us the packfile already.\n\t\t */\n\t\tif (bufflen >= 4 && !git__prefixcmp(line, \"PACK\")) {\n\t\t\tgiterr_clear();\n\t\t\t*out = line;\n\t\t\treturn pack_pkt(head);\n\t\t}\n\n\t\treturn (int)len;\n\t}\n\n\t/*\n\t * If we were given a buffer length, then make sure there is\n\t * enough in the buffer to satisfy this line\n\t */\n\tif (bufflen > 0 && bufflen < (size_t)len)\n\t\treturn GIT_EBUFS;\n\n\t/*\n\t * The length has to be exactly 0 in case of a flush\n\t * packet or greater than PKT_LEN_SIZE, as the decoded\n\t * length includes its own encoded length of four bytes.\n\t */\n\tif (len != 0 && len < PKT_LEN_SIZE)\n\t\treturn GIT_ERROR;\n\n\tline += PKT_LEN_SIZE;\n\t/*\n\t * TODO: How do we deal with empty lines? Try again? with the next\n\t * line?\n\t */\n\tif (len == PKT_LEN_SIZE) {\n\t\t*head = NULL;\n\t\t*out = line;\n\t\treturn 0;\n\t}\n\n\tif (len == 0) { /* Flush pkt */\n\t\t*out = line;\n\t\treturn flush_pkt(head);\n\t}\n\n\tlen -= PKT_LEN_SIZE; /* the encoded length includes its own size */\n\n\tif (*line == GIT_SIDE_BAND_DATA)\n\t\tret = data_pkt(head, line, len);\n\telse if (*line == GIT_SIDE_BAND_PROGRESS)\n\t\tret = sideband_progress_pkt(head, line, len);\n\telse if (*line == GIT_SIDE_BAND_ERROR)\n\t\tret = sideband_error_pkt(head, line, len);\n\telse if (!git__prefixcmp(line, \"ACK\"))\n\t\tret = ack_pkt(head, line, len);\n\telse if (!git__prefixcmp(line, \"NAK\"))\n\t\tret = nak_pkt(head);\n\telse if (!git__prefixcmp(line, \"ERR \"))\n\t\tret = err_pkt(head, line, len);\n\telse if (*line == '#')\n\t\tret = comment_pkt(head, line, len);\n\telse if (!git__prefixcmp(line, \"ok\"))\n\t\tret = ok_pkt(head, line, len);\n\telse if (!git__prefixcmp(line, \"ng\"))\n\t\tret = ng_pkt(head, line, len);\n\telse if (!git__prefixcmp(line, \"unpack\"))\n\t\tret = unpack_pkt(head, line, len);\n\telse\n\t\tret = ref_pkt(head, line, len);\n\n\t*out = line + len;\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-119'], 'message': 'smart_pkt: treat empty packet lines as error\n\nThe Git protocol does not specify what should happen in the case\nof an empty packet line (that is a packet line \"0004\"). We\ncurrently indicate success, but do not return a packet in the\ncase where we hit an empty line. The smart protocol was not\nprepared to handle such packets in all cases, though, resulting\nin a `NULL` pointer dereference.\n\nFix the issue by returning an error instead. As such kind of\npackets is not even specified by upstream, this is the right\nthing to do.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: extract_group_icon_cursor_resource(WinLibrary *fi, WinResource *wr, char *lang,\n int *ressize, bool is_icon)\n{\n\tWin32CursorIconDir *icondir;\n\tWin32CursorIconFileDir *fileicondir;\n\tchar *memory;\n\tint c, size, offset, skipped;\n\n\t/* get resource data and size */\n\ticondir = (Win32CursorIconDir *) get_resource_entry(fi, wr, &size);\n\tif (icondir == NULL) {\n\t\t/* get_resource_entry will print error */\n\t\treturn NULL;\n\t}\n\n\t/* calculate total size of output file */\n\tRETURN_IF_BAD_POINTER(NULL, icondir->count);\n\tskipped = 0;\n\tfor (c = 0 ; c < icondir->count ; c++) {\n\t\tint level;\n\t \tint iconsize;\n\t\tchar name[14];\n\t\tWinResource *fwr;\n\n\t\tRETURN_IF_BAD_POINTER(NULL, icondir->entries[c]);\n\t\t/*printf(\"%d. bytes_in_res=%d width=%d height=%d planes=%d bit_count=%d\\n\", c,\n\t\t\ticondir->entries[c].bytes_in_res,\n\t\t\t(is_icon ? icondir->entries[c].res_info.icon.width : icondir->entries[c].res_info.cursor.width),\n\t\t\t(is_icon ? icondir->entries[c].res_info.icon.height : icondir->entries[c].res_info.cursor.height),\n\t\t\ticondir->entries[c].plane_count,\n\t\t\ticondir->entries[c].bit_count);*/\n\n\t\t/* find the corresponding icon resource */\n\t\tsnprintf(name, sizeof(name)/sizeof(char), \"-%d\", icondir->entries[c].res_id);\n\t\tfwr = find_resource(fi, (is_icon ? \"-3\" : \"-1\"), name, lang, &level);\n\t\tif (fwr == NULL) {\n\t\t\twarn(_(\"%s: could not find `%s' in `%s' resource.\"),\n\t\t\t \tfi->name, &name[1], (is_icon ? \"group_icon\" : \"group_cursor\"));\n\t\t\treturn NULL;\n\t\t}\n\n\t\tif (get_resource_entry(fi, fwr, &iconsize) != NULL) {\n\t\t if (iconsize == 0) {\n\t\t\twarn(_(\"%s: icon resource `%s' is empty, skipping\"), fi->name, name);\n\t\t\tskipped++;\n\t\t\tcontinue;\n\t\t }\n\t\t if (iconsize != icondir->entries[c].bytes_in_res) {\n\t\t\twarn(_(\"%s: mismatch of size in icon resource `%s' and group (%d vs %d)\"), fi->name, name, iconsize, icondir->entries[c].bytes_in_res);\n\t\t }\n\t\t size += iconsize < icondir->entries[c].bytes_in_res ? icondir->entries[c].bytes_in_res : iconsize;\n\n\t\t /* cursor resources have two additional WORDs that contain\n\t\t * hotspot info */\n\t\t if (!is_icon)\n\t\t\tsize -= sizeof(uint16_t)*2;\n\t\t}\n\t}\n\toffset = sizeof(Win32CursorIconFileDir) + (icondir->count-skipped) * sizeof(Win32CursorIconFileDirEntry);\n\tsize += offset;\n\t*ressize = size;\n\n\t/* allocate that much memory */\n\tmemory = xmalloc(size);\n\tfileicondir = (Win32CursorIconFileDir *) memory;\n\n\t/* transfer Win32CursorIconDir structure members */\n\tfileicondir->reserved = icondir->reserved;\n\tfileicondir->type = icondir->type;\n\tfileicondir->count = icondir->count - skipped;\n\n\t/* transfer each cursor/icon: Win32CursorIconDirEntry and data */\n\tskipped = 0;\n\tfor (c = 0 ; c < icondir->count ; c++) {\n\t\tint level;\n\t\tchar name[14];\n\t\tWinResource *fwr;\n\t\tchar *data;\n\t\n\t\t/* find the corresponding icon resource */\n\t\tsnprintf(name, sizeof(name)/sizeof(char), \"-%d\", icondir->entries[c].res_id);\n\t\tfwr = find_resource(fi, (is_icon ? \"-3\" : \"-1\"), name, lang, &level);\n\t\tif (fwr == NULL) {\n\t\t\twarn(_(\"%s: could not find `%s' in `%s' resource.\"),\n\t\t\t \tfi->name, &name[1], (is_icon ? \"group_icon\" : \"group_cursor\"));\n\t\t\treturn NULL;\n\t\t}\n\n\t\t/* get data and size of that resource */\n\t\tdata = get_resource_entry(fi, fwr, &size);\n\t\tif (data == NULL) {\n\t\t\t/* get_resource_entry has printed error */\n\t\t\treturn NULL;\n\t\t}\n \t \tif (size == 0) {\n\t\t skipped++;\n\t\t continue;\n\t\t}\n\n\t\t/* copy ICONDIRENTRY (not including last dwImageOffset) */\n\t\tmemcpy(&fileicondir->entries[c-skipped], &icondir->entries[c],\n\t\t\tsizeof(Win32CursorIconFileDirEntry)-sizeof(uint32_t));\n\n\t\t/* special treatment for cursors */\n\t\tif (!is_icon) {\n\t\t\tfileicondir->entries[c-skipped].width = icondir->entries[c].res_info.cursor.width;\n\t\t\tfileicondir->entries[c-skipped].height = icondir->entries[c].res_info.cursor.height / 2;\n\t\t\tfileicondir->entries[c-skipped].color_count = 0;\n\t\t\tfileicondir->entries[c-skipped].reserved = 0;\n\t\t}\n\n\t\t/* set image offset and increase it */\n\t\tfileicondir->entries[c-skipped].dib_offset = offset;\n\n\t\t/* transfer resource into file memory */\n\t\tif (size > icondir->entries[c].bytes_in_res)\n\t\t\tsize = icondir->entries[c].bytes_in_res;\n\t\tif (is_icon) {\n\t\t\tmemcpy(&memory[offset], data, size);\n\t\t} else {\n\t\t\tfileicondir->entries[c-skipped].hotspot_x = ((uint16_t *) data)[0];\n\t\t\tfileicondir->entries[c-skipped].hotspot_y = ((uint16_t *) data)[1];\n\t\t\tmemcpy(&memory[offset], data+sizeof(uint16_t)*2,\n\t\t\t\t size-sizeof(uint16_t)*2);\n\t\t\toffset -= sizeof(uint16_t)*2;\n\t\t}\n\n\t\t/* increase the offset pointer */\n\t\toffset += icondir->entries[c].bytes_in_res;\n\t}\n\n\treturn (void *) memory;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'wrestool: Fix an index, additional check'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ModuleExport MagickBooleanType ReadPSDLayers(Image *image,\n const ImageInfo *image_info,const PSDInfo *psd_info,\n const MagickBooleanType skip_layers,ExceptionInfo *exception)\n{\n char\n type[4];\n\n LayerInfo\n *layer_info;\n\n MagickSizeType\n size;\n\n MagickBooleanType\n status;\n\n register ssize_t\n i;\n\n ssize_t\n count,\n j,\n number_layers;\n\n size=GetPSDSize(psd_info,image);\n if (size == 0)\n {\n /*\n Skip layers & masks.\n */\n (void) ReadBlobLong(image);\n count=ReadBlob(image,4,(unsigned char *) type);\n ReversePSDString(image,type,4);\n status=MagickFalse;\n if ((count == 0) || (LocaleNCompare(type,\"8BIM\",4) != 0))\n return(MagickTrue);\n else\n {\n count=ReadBlob(image,4,(unsigned char *) type);\n ReversePSDString(image,type,4);\n if ((count != 0) && (LocaleNCompare(type,\"Lr16\",4) == 0))\n size=GetPSDSize(psd_info,image);\n else\n return(MagickTrue);\n }\n }\n status=MagickTrue;\n if (size != 0)\n {\n layer_info=(LayerInfo *) NULL;\n number_layers=(short) ReadBlobShort(image);\n\n if (number_layers < 0)\n {\n /*\n The first alpha channel in the merged result contains the\n transparency data for the merged result.\n */\n number_layers=MagickAbsoluteValue(number_layers);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" negative layer count corrected for\");\n image->alpha_trait=BlendPixelTrait;\n }\n\n /*\n We only need to know if the image has an alpha channel\n */\n if (skip_layers != MagickFalse)\n return(MagickTrue);\n\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image contains %.20g layers\",(double) number_layers);\n\n if (number_layers == 0)\n ThrowBinaryException(CorruptImageError,\"InvalidNumberOfLayers\",\n image->filename);\n\n layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers,\n sizeof(*layer_info));\n if (layer_info == (LayerInfo *) NULL)\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" allocation of LayerInfo failed\");\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n }\n (void) ResetMagickMemory(layer_info,0,(size_t) number_layers*\n sizeof(*layer_info));\n\n for (i=0; i < number_layers; i++)\n {\n ssize_t\n x,\n y;\n\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" reading layer #%.20g\",(double) i+1);\n layer_info[i].page.y=ReadBlobSignedLong(image);\n layer_info[i].page.x=ReadBlobSignedLong(image);\n y=ReadBlobSignedLong(image);\n x=ReadBlobSignedLong(image);\n layer_info[i].page.width=(size_t) (x-layer_info[i].page.x);\n layer_info[i].page.height=(size_t) (y-layer_info[i].page.y);\n layer_info[i].channels=ReadBlobShort(image);\n if (layer_info[i].channels > MaxPSDChannels)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\"MaximumChannelsExceeded\",\n image->filename);\n }\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g\",\n (double) layer_info[i].page.x,(double) layer_info[i].page.y,\n (double) layer_info[i].page.height,(double)\n layer_info[i].page.width,(double) layer_info[i].channels);\n for (j=0; j < (ssize_t) layer_info[i].channels; j++)\n {\n layer_info[i].channel_info[j].type=(short) ReadBlobShort(image);\n layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info,\n image);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" channel[%.20g]: type=%.20g, size=%.20g\",(double) j,\n (double) layer_info[i].channel_info[j].type,\n (double) layer_info[i].channel_info[j].size);\n }\n count=ReadBlob(image,4,(unsigned char *) type);\n ReversePSDString(image,type,4);\n if ((count == 0) || (LocaleNCompare(type,\"8BIM\",4) != 0))\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer type was %.4s instead of 8BIM\", type);\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\"ImproperImageHeader\",\n image->filename);\n }\n count=ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey);\n ReversePSDString(image,layer_info[i].blendkey,4);\n layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char)\n ReadBlobByte(image));\n layer_info[i].clipping=(unsigned char) ReadBlobByte(image);\n layer_info[i].flags=(unsigned char) ReadBlobByte(image);\n layer_info[i].visible=!(layer_info[i].flags & 0x02);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s\",\n layer_info[i].blendkey,(double) layer_info[i].opacity,\n layer_info[i].clipping ? \"true\" : \"false\",layer_info[i].flags,\n layer_info[i].visible ? \"true\" : \"false\");\n (void) ReadBlobByte(image); /* filler */\n\n size=ReadBlobLong(image);\n if (size != 0)\n {\n MagickSizeType\n combined_length,\n length;\n\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer contains additional info\");\n length=ReadBlobLong(image);\n combined_length=length+4;\n if (length != 0)\n {\n /*\n Layer mask info.\n */\n layer_info[i].mask.page.y=ReadBlobSignedLong(image);\n layer_info[i].mask.page.x=ReadBlobSignedLong(image);\n layer_info[i].mask.page.height=(size_t) (ReadBlobLong(image)-\n layer_info[i].mask.page.y);\n layer_info[i].mask.page.width=(size_t) (ReadBlobLong(image)-\n layer_info[i].mask.page.x);\n layer_info[i].mask.background=(unsigned char) ReadBlobByte(\n image);\n layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image);\n if (!(layer_info[i].mask.flags & 0x01))\n {\n layer_info[i].mask.page.y=layer_info[i].mask.page.y-\n layer_info[i].page.y;\n layer_info[i].mask.page.x=layer_info[i].mask.page.x-\n layer_info[i].page.x;\n }\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g\",\n (double) layer_info[i].mask.page.x,(double) \n layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width,\n (double) layer_info[i].mask.page.height,(double)\n ((MagickOffsetType) length)-18);\n /*\n Skip over the rest of the layer mask information.\n */\n if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n }\n }\n length=ReadBlobLong(image);\n combined_length+=length+4;\n if (length != 0)\n {\n /*\n Layer blending ranges info.\n */\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer blending ranges: length=%.20g\",(double)\n ((MagickOffsetType) length));\n /*\n We read it, but don't use it...\n */\n for (j=0; j < (ssize_t) length; j+=8)\n {\n size_t blend_source=ReadBlobLong(image);\n size_t blend_dest=ReadBlobLong(image);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" source(%x), dest(%x)\",(unsigned int)\n blend_source,(unsigned int) blend_dest);\n }\n }\n /*\n Layer name.\n */\n length=(MagickSizeType) (unsigned char) ReadBlobByte(image);\n combined_length+=length+1;\n if (length > 0)\n (void) ReadBlob(image,(size_t) length++,layer_info[i].name);\n layer_info[i].name[length]='\\0';\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer name: %s\",layer_info[i].name);\n if ((length % 4) != 0)\n {\n length=4-(length % 4);\n combined_length+=length;\n /* Skip over the padding of the layer name */\n if (DiscardBlobBytes(image,length) == MagickFalse)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n }\n }\n length=(MagickSizeType) size-combined_length;\n if (length > 0)\n {\n unsigned char\n *info;\n\n layer_info[i].info=AcquireStringInfo((const size_t) length);\n info=GetStringInfoDatum(layer_info[i].info);\n (void) ReadBlob(image,(const size_t) length,info);\n }\n }\n }\n\n for (i=0; i < number_layers; i++)\n {\n if ((layer_info[i].page.width == 0) ||\n (layer_info[i].page.height == 0))\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer data is empty\");\n if (layer_info[i].info != (StringInfo *) NULL)\n layer_info[i].info=DestroyStringInfo(layer_info[i].info);\n continue;\n }\n\n /*\n Allocate layered image.\n */\n layer_info[i].image=CloneImage(image,layer_info[i].page.width,\n layer_info[i].page.height,MagickFalse,exception);\n if (layer_info[i].image == (Image *) NULL)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" allocation of image for layer %.20g failed\",(double) i);\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n }\n\n if (layer_info[i].info != (StringInfo *) NULL)\n {\n (void) SetImageProfile(layer_info[i].image,\"psd:additional-info\",\n layer_info[i].info,exception);\n layer_info[i].info=DestroyStringInfo(layer_info[i].info);\n }\n }\n\n if (image_info->ping == MagickFalse)\n {\n for (i=0; i < number_layers; i++)\n {\n if (layer_info[i].image == (Image *) NULL)\n {\n for (j=0; j < layer_info[i].channels; j++)\n {\n if (DiscardBlobBytes(image,(MagickSizeType)\n layer_info[i].channel_info[j].size) == MagickFalse)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n }\n }\n continue;\n }\n\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" reading data for layer %.20g\",(double) i);\n\n status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i],\n exception);\n if (status == MagickFalse)\n break;\n\n status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType)\n number_layers);\n if (status == MagickFalse)\n break;\n }\n }\n\n if (status != MagickFalse)\n {\n for (i=0; i < number_layers; i++)\n {\n if (layer_info[i].image == (Image *) NULL)\n {\n for (j=i; j < number_layers - 1; j++)\n layer_info[j] = layer_info[j+1];\n number_layers--;\n i--;\n }\n }\n\n if (number_layers > 0)\n {\n for (i=0; i < number_layers; i++)\n {\n if (i > 0)\n layer_info[i].image->previous=layer_info[i-1].image;\n if (i < (number_layers-1))\n layer_info[i].image->next=layer_info[i+1].image;\n layer_info[i].image->page=layer_info[i].page;\n }\n image->next=layer_info[0].image;\n layer_info[0].image->previous=image;\n }\n layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info);\n }\n else\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n }\n\n return(status);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/350'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) {\n _cleanup_close_ int fd;\n int r;\n\n assert(path);\n\n if (parents)\n mkdir_parents(path, 0755);\n\n fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode > 0 ? mode : 0644);\n if (fd < 0)\n return -errno;\n\n if (mode != MODE_INVALID) {\n r = fchmod(fd, mode);\n if (r < 0)\n return -errno;\n }\n\n if (uid != UID_INVALID || gid != GID_INVALID) {\n r = fchown(fd, uid, gid);\n if (r < 0)\n return -errno;\n }\n\n if (stamp != USEC_INFINITY) {\n struct timespec ts[2];\n\n timespec_store(&ts[0], stamp);\n ts[1] = ts[0];\n r = futimens(fd, ts);\n } else\n r = futimens(fd, NULL);\n if (r < 0)\n return -errno;\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'basic: fix touch() creating files with 07777 mode\n\nmode_t is unsigned, so MODE_INVALID < 0 can never be true.\n\nThis fixes a possible DoS where any user could fill /run by writing to\na world-writable /run/systemd/show-status.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int atusb_get_and_show_revision(struct atusb *atusb)\n{\n\tstruct usb_device *usb_dev = atusb->usb_dev;\n\tunsigned char buffer[3];\n\tint ret;\n\n\t/* Get a couple of the ATMega Firmware values */\n\tret = atusb_control_msg(atusb, usb_rcvctrlpipe(usb_dev, 0),\n\t\t\t\tATUSB_ID, ATUSB_REQ_FROM_DEV, 0, 0,\n\t\t\t\tbuffer, 3, 1000);\n\tif (ret >= 0) {\n\t\tatusb->fw_ver_maj = buffer[0];\n\t\tatusb->fw_ver_min = buffer[1];\n\t\tatusb->fw_hw_type = buffer[2];\n\n\t\tdev_info(&usb_dev->dev,\n\t\t\t \"Firmware: major: %u, minor: %u, hardware type: %u\\n\",\n\t\t\t atusb->fw_ver_maj, atusb->fw_ver_min, atusb->fw_hw_type);\n\t}\n\tif (atusb->fw_ver_maj == 0 && atusb->fw_ver_min < 2) {\n\t\tdev_info(&usb_dev->dev,\n\t\t\t \"Firmware version (%u.%u) predates our first public release.\",\n\t\t\t atusb->fw_ver_maj, atusb->fw_ver_min);\n\t\tdev_info(&usb_dev->dev, \"Please update to version 0.2 or newer\");\n\t}\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-119'], 'message': 'ieee802154: atusb: do not use the stack for buffers to make them DMA able\n\nFrom 4.9 we should really avoid using the stack here as this will not be DMA\nable on various platforms. This changes the buffers already being present in\ntime of 4.9 being released. This should go into stable as well.\n\nReported-by: Dan Carpenter \nCc: stable@vger.kernel.org\nSigned-off-by: Stefan Schmidt \nSigned-off-by: Marcel Holtmann '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int read_new_config_info (WavpackContext *wpc, WavpackMetadata *wpmd)\n{\n int bytecnt = wpmd->byte_length;\n unsigned char *byteptr = wpmd->data;\n\n wpc->version_five = 1; // just having this block signals version 5.0\n\n wpc->file_format = wpc->config.qmode = wpc->channel_layout = 0;\n\n if (wpc->channel_reordering) {\n free (wpc->channel_reordering);\n wpc->channel_reordering = NULL;\n }\n\n // if there's any data, the first two bytes are file_format and qmode flags\n\n if (bytecnt) {\n wpc->file_format = *byteptr++;\n wpc->config.qmode = (wpc->config.qmode & ~0xff) | *byteptr++;\n bytecnt -= 2;\n\n // another byte indicates a channel layout\n\n if (bytecnt) {\n int nchans, i;\n\n wpc->channel_layout = (int32_t) *byteptr++ << 16;\n bytecnt--;\n\n // another byte means we have a channel count for the layout and maybe a reordering\n\n if (bytecnt) {\n wpc->channel_layout += nchans = *byteptr++;\n bytecnt--;\n\n // any more means there's a reordering string\n\n if (bytecnt) {\n if (bytecnt > nchans)\n return FALSE;\n\n wpc->channel_reordering = malloc (nchans);\n\n // note that redundant reordering info is not stored, so we fill in the rest\n\n if (wpc->channel_reordering) {\n for (i = 0; i < nchans; ++i)\n if (bytecnt) {\n wpc->channel_reordering [i] = *byteptr++;\n bytecnt--;\n }\n else\n wpc->channel_reordering [i] = i;\n }\n }\n }\n else\n wpc->channel_layout += wpc->config.num_channels;\n }\n }\n\n return TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'fixes for 4 fuzz failures posted to SourceForge mailing list'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int megasas_handle_dcmd(MegasasState *s, MegasasCmd *cmd)\n{\n int opcode, len;\n int retval = 0;\n const struct dcmd_cmd_tbl_t *cmdptr = dcmd_cmd_tbl;\n\n opcode = le32_to_cpu(cmd->frame->dcmd.opcode);\n trace_megasas_handle_dcmd(cmd->index, opcode);\n len = megasas_map_dcmd(s, cmd);\n if (len < 0) {\n return MFI_STAT_MEMORY_NOT_AVAILABLE;\n }\n while (cmdptr->opcode != -1 && cmdptr->opcode != opcode) {\n cmdptr++;\n }\n if (cmdptr->opcode == -1) {\n trace_megasas_dcmd_unhandled(cmd->index, opcode, len);\n retval = megasas_dcmd_dummy(s, cmd);\n } else {\n trace_megasas_dcmd_enter(cmd->index, cmdptr->desc, len);\n retval = cmdptr->func(s, cmd);\n }\n if (retval != MFI_STAT_INVALID_STATUS) {\n megasas_finish_dcmd(cmd, len);\n }\n return retval;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'megasas: fix guest-triggered memory leak\n\nIf the guest sets the sglist size to a value >=2GB, megasas_handle_dcmd\nwill return MFI_STAT_MEMORY_NOT_AVAILABLE without freeing the memory.\nAvoid this by returning only the status from map_dcmd, and loading\ncmd->iov_size in the caller.\n\nReported-by: Li Qiang \nSigned-off-by: Paolo Bonzini '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: qtdemux_tag_add_str_full (GstQTDemux * qtdemux, GstTagList * taglist,\n const char *tag, const char *dummy, GNode * node)\n{\n const gchar *env_vars[] = { \"GST_QT_TAG_ENCODING\", \"GST_TAG_ENCODING\", NULL };\n GNode *data;\n char *s;\n int len;\n guint32 type;\n int offset;\n gboolean ret = TRUE;\n const gchar *charset = NULL;\n\n data = qtdemux_tree_get_child_by_type (node, FOURCC_data);\n if (data) {\n len = QT_UINT32 (data->data);\n type = QT_UINT32 ((guint8 *) data->data + 8);\n if (type == 0x00000001 && len > 16) {\n s = gst_tag_freeform_string_to_utf8 ((char *) data->data + 16, len - 16,\n env_vars);\n if (s) {\n GST_DEBUG_OBJECT (qtdemux, \"adding tag %s\", GST_STR_NULL (s));\n gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE, tag, s, NULL);\n g_free (s);\n } else {\n GST_DEBUG_OBJECT (qtdemux, \"failed to convert %s tag to UTF-8\", tag);\n }\n }\n } else {\n len = QT_UINT32 (node->data);\n type = QT_UINT32 ((guint8 *) node->data + 4);\n if ((type >> 24) == 0xa9) {\n gint str_len;\n gint lang_code;\n\n /* Type starts with the (C) symbol, so the next data is a list\n * of (string size(16), language code(16), string) */\n\n str_len = QT_UINT16 ((guint8 *) node->data + 8);\n lang_code = QT_UINT16 ((guint8 *) node->data + 10);\n\n /* the string + fourcc + size + 2 16bit fields,\n * means that there are more tags in this atom */\n if (len > str_len + 8 + 4) {\n /* TODO how to represent the same tag in different languages? */\n GST_WARNING_OBJECT (qtdemux, \"Ignoring metadata entry with multiple \"\n \"text alternatives, reading only first one\");\n }\n\n offset = 12;\n len = str_len + 8 + 4; /* remove trailing strings that we don't use */\n GST_DEBUG_OBJECT (qtdemux, \"found international text tag\");\n\n if (lang_code < 0x800) { /* MAC encoded string */\n charset = \"mac\";\n }\n } else if (len > 14 && qtdemux_is_string_tag_3gp (qtdemux,\n QT_FOURCC ((guint8 *) node->data + 4))) {\n guint32 type = QT_UINT32 ((guint8 *) node->data + 8);\n\n /* we go for 3GP style encoding if major brands claims so,\n * or if no hope for data be ok UTF-8, and compatible 3GP brand present */\n if (qtdemux_is_brand_3gp (qtdemux, TRUE) ||\n (qtdemux_is_brand_3gp (qtdemux, FALSE) &&\n ((type & 0x00FFFFFF) == 0x0) && (type >> 24 <= 0xF))) {\n offset = 14;\n /* 16-bit Language code is ignored here as well */\n GST_DEBUG_OBJECT (qtdemux, \"found 3gpp text tag\");\n } else {\n goto normal;\n }\n } else {\n normal:\n offset = 8;\n GST_DEBUG_OBJECT (qtdemux, \"found normal text tag\");\n ret = FALSE; /* may have to fallback */\n }\n if (charset) {\n GError *err = NULL;\n\n s = g_convert ((gchar *) node->data + offset, len - offset, \"utf8\",\n charset, NULL, NULL, &err);\n if (err) {\n GST_DEBUG_OBJECT (qtdemux, \"Failed to convert string from charset %s:\"\n \" %s(%d): %s\", charset, g_quark_to_string (err->domain), err->code,\n err->message);\n g_error_free (err);\n }\n } else {\n s = gst_tag_freeform_string_to_utf8 ((char *) node->data + offset,\n len - offset, env_vars);\n }\n if (s) {\n GST_DEBUG_OBJECT (qtdemux, \"adding tag %s\", GST_STR_NULL (s));\n gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE, tag, s, NULL);\n g_free (s);\n ret = TRUE;\n } else {\n GST_DEBUG_OBJECT (qtdemux, \"failed to convert %s tag to UTF-8\", tag);\n }\n }\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'qtdemux: Fix out of bounds read in tag parsing code\n\nWe can't simply assume that the length of the tag value as given\ninside the stream is correct but should also check against the amount of\ndata we have actually available.\n\nhttps://bugzilla.gnome.org/show_bug.cgi?id=775451'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: directory_exists (dirname)\n const char *dirname;\n{\n char *new_dirname;\n int dirlen, r;\n struct stat sb;\n\n /* First, dequote the directory name */\n new_dirname = bash_dequote_filename ((char *)dirname, rl_completion_quote_character);\n dirlen = STRLEN (new_dirname);\n if (new_dirname[dirlen - 1] == '/')\n new_dirname[dirlen - 1] = '\\0';\n#if defined (HAVE_LSTAT)\n r = lstat (new_dirname, &sb) == 0;\n#else\n r = stat (new_dirname, &sb) == 0;\n#endif\n free (new_dirname);\n return (r);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Bash-4.4 patch 7'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline void timer_stats_timer_clear_start_info(struct timer_list *timer)\n{\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'time: Remove CONFIG_TIMER_STATS\n\nCurrently CONFIG_TIMER_STATS exposes process information across namespaces:\n\nkernel/time/timer_list.c print_timer():\n\n SEQ_printf(m, \", %s/%d\", tmp, timer->start_pid);\n\n/proc/timer_list:\n\n #11: <0000000000000000>, hrtimer_wakeup, S:01, do_nanosleep, cron/2570\n\nGiven that the tracer can give the same information, this patch entirely\nremoves CONFIG_TIMER_STATS.\n\nSuggested-by: Thomas Gleixner \nSigned-off-by: Kees Cook \nAcked-by: John Stultz \nCc: Nicolas Pitre \nCc: linux-doc@vger.kernel.org\nCc: Lai Jiangshan \nCc: Shuah Khan \nCc: Xing Gao \nCc: Jonathan Corbet \nCc: Jessica Frazelle \nCc: kernel-hardening@lists.openwall.com\nCc: Nicolas Iooss \nCc: \"Paul E. McKenney\" \nCc: Petr Mladek \nCc: Richard Cochran \nCc: Tejun Heo \nCc: Michal Marek \nCc: Josh Poimboeuf \nCc: Dmitry Vyukov \nCc: Oleg Nesterov \nCc: \"Eric W. Biederman\" \nCc: Olof Johansson \nCc: Andrew Morton \nCc: linux-api@vger.kernel.org\nCc: Arjan van de Ven \nLink: http://lkml.kernel.org/r/20170208192659.GA32582@beast\nSigned-off-by: Thomas Gleixner '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void __hrtimer_init(struct hrtimer *timer, clockid_t clock_id,\n\t\t\t enum hrtimer_mode mode)\n{\n\tstruct hrtimer_cpu_base *cpu_base;\n\tint base;\n\n\tmemset(timer, 0, sizeof(struct hrtimer));\n\n\tcpu_base = raw_cpu_ptr(&hrtimer_bases);\n\n\tif (clock_id == CLOCK_REALTIME && mode != HRTIMER_MODE_ABS)\n\t\tclock_id = CLOCK_MONOTONIC;\n\n\tbase = hrtimer_clockid_to_base(clock_id);\n\ttimer->base = &cpu_base->clock_base[base];\n\ttimerqueue_init(&timer->node);\n\n#ifdef CONFIG_TIMER_STATS\n\ttimer->start_site = NULL;\n\ttimer->start_pid = -1;\n\tmemset(timer->start_comm, 0, TASK_COMM_LEN);\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'time: Remove CONFIG_TIMER_STATS\n\nCurrently CONFIG_TIMER_STATS exposes process information across namespaces:\n\nkernel/time/timer_list.c print_timer():\n\n SEQ_printf(m, \", %s/%d\", tmp, timer->start_pid);\n\n/proc/timer_list:\n\n #11: <0000000000000000>, hrtimer_wakeup, S:01, do_nanosleep, cron/2570\n\nGiven that the tracer can give the same information, this patch entirely\nremoves CONFIG_TIMER_STATS.\n\nSuggested-by: Thomas Gleixner \nSigned-off-by: Kees Cook \nAcked-by: John Stultz \nCc: Nicolas Pitre \nCc: linux-doc@vger.kernel.org\nCc: Lai Jiangshan \nCc: Shuah Khan \nCc: Xing Gao \nCc: Jonathan Corbet \nCc: Jessica Frazelle \nCc: kernel-hardening@lists.openwall.com\nCc: Nicolas Iooss \nCc: \"Paul E. McKenney\" \nCc: Petr Mladek \nCc: Richard Cochran \nCc: Tejun Heo \nCc: Michal Marek \nCc: Josh Poimboeuf \nCc: Dmitry Vyukov \nCc: Oleg Nesterov \nCc: \"Eric W. Biederman\" \nCc: Olof Johansson \nCc: Andrew Morton \nCc: linux-api@vger.kernel.org\nCc: Arjan van de Ven \nLink: http://lkml.kernel.org/r/20170208192659.GA32582@beast\nSigned-off-by: Thomas Gleixner '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,\n\t\t\t\tstruct delayed_work *dwork, unsigned long delay)\n{\n\tstruct timer_list *timer = &dwork->timer;\n\tstruct work_struct *work = &dwork->work;\n\n\tWARN_ON_ONCE(timer->function != delayed_work_timer_fn ||\n\t\t timer->data != (unsigned long)dwork);\n\tWARN_ON_ONCE(timer_pending(timer));\n\tWARN_ON_ONCE(!list_empty(&work->entry));\n\n\t/*\n\t * If @delay is 0, queue @dwork->work immediately. This is for\n\t * both optimization and correctness. The earliest @timer can\n\t * expire is on the closest next tick and delayed_work users depend\n\t * on that there's no such delay when @delay is 0.\n\t */\n\tif (!delay) {\n\t\t__queue_work(cpu, wq, &dwork->work);\n\t\treturn;\n\t}\n\n\ttimer_stats_timer_set_start_info(&dwork->timer);\n\n\tdwork->wq = wq;\n\tdwork->cpu = cpu;\n\ttimer->expires = jiffies + delay;\n\n\tif (unlikely(cpu != WORK_CPU_UNBOUND))\n\t\tadd_timer_on(timer, cpu);\n\telse\n\t\tadd_timer(timer);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'time: Remove CONFIG_TIMER_STATS\n\nCurrently CONFIG_TIMER_STATS exposes process information across namespaces:\n\nkernel/time/timer_list.c print_timer():\n\n SEQ_printf(m, \", %s/%d\", tmp, timer->start_pid);\n\n/proc/timer_list:\n\n #11: <0000000000000000>, hrtimer_wakeup, S:01, do_nanosleep, cron/2570\n\nGiven that the tracer can give the same information, this patch entirely\nremoves CONFIG_TIMER_STATS.\n\nSuggested-by: Thomas Gleixner \nSigned-off-by: Kees Cook \nAcked-by: John Stultz \nCc: Nicolas Pitre \nCc: linux-doc@vger.kernel.org\nCc: Lai Jiangshan \nCc: Shuah Khan \nCc: Xing Gao \nCc: Jonathan Corbet \nCc: Jessica Frazelle \nCc: kernel-hardening@lists.openwall.com\nCc: Nicolas Iooss \nCc: \"Paul E. McKenney\" \nCc: Petr Mladek \nCc: Richard Cochran \nCc: Tejun Heo \nCc: Michal Marek \nCc: Josh Poimboeuf \nCc: Dmitry Vyukov \nCc: Oleg Nesterov \nCc: \"Eric W. Biederman\" \nCc: Olof Johansson \nCc: Andrew Morton \nCc: linux-api@vger.kernel.org\nCc: Arjan van de Ven \nLink: http://lkml.kernel.org/r/20170208192659.GA32582@beast\nSigned-off-by: Thomas Gleixner '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline void timer_stats_timer_set_start_info(struct timer_list *timer)\n{\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'time: Remove CONFIG_TIMER_STATS\n\nCurrently CONFIG_TIMER_STATS exposes process information across namespaces:\n\nkernel/time/timer_list.c print_timer():\n\n SEQ_printf(m, \", %s/%d\", tmp, timer->start_pid);\n\n/proc/timer_list:\n\n #11: <0000000000000000>, hrtimer_wakeup, S:01, do_nanosleep, cron/2570\n\nGiven that the tracer can give the same information, this patch entirely\nremoves CONFIG_TIMER_STATS.\n\nSuggested-by: Thomas Gleixner \nSigned-off-by: Kees Cook \nAcked-by: John Stultz \nCc: Nicolas Pitre \nCc: linux-doc@vger.kernel.org\nCc: Lai Jiangshan \nCc: Shuah Khan \nCc: Xing Gao \nCc: Jonathan Corbet \nCc: Jessica Frazelle \nCc: kernel-hardening@lists.openwall.com\nCc: Nicolas Iooss \nCc: \"Paul E. McKenney\" \nCc: Petr Mladek \nCc: Richard Cochran \nCc: Tejun Heo \nCc: Michal Marek \nCc: Josh Poimboeuf \nCc: Dmitry Vyukov \nCc: Oleg Nesterov \nCc: \"Eric W. Biederman\" \nCc: Olof Johansson \nCc: Andrew Morton \nCc: linux-api@vger.kernel.org\nCc: Arjan van de Ven \nLink: http://lkml.kernel.org/r/20170208192659.GA32582@beast\nSigned-off-by: Thomas Gleixner '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int oidc_handle_existing_session(request_rec *r, oidc_cfg *cfg,\n\t\toidc_session_t *session) {\n\n\toidc_debug(r, \"enter\");\n\n\t/* get the header name in which the remote user name needs to be passed */\n\tchar *authn_header = oidc_cfg_dir_authn_header(r);\n\tint pass_headers = oidc_cfg_dir_pass_info_in_headers(r);\n\tint pass_envvars = oidc_cfg_dir_pass_info_in_envvars(r);\n\n\t/* verify current cookie domain against issued cookie domain */\n\tif (oidc_check_cookie_domain(r, cfg, session) == FALSE)\n\t\treturn HTTP_UNAUTHORIZED;\n\n\t/* check if the maximum session duration was exceeded */\n\tint rc = oidc_check_max_session_duration(r, cfg, session);\n\tif (rc != OK)\n\t\treturn rc;\n\n\t/* if needed, refresh claims from the user info endpoint */\n\tapr_byte_t needs_save = oidc_refresh_claims_from_userinfo_endpoint(r, cfg,\n\t\t\tsession);\n\n\t/*\n\t * we're going to pass the information that we have to the application,\n\t * but first we need to scrub the headers that we're going to use for security reasons\n\t */\n\tif (cfg->scrub_request_headers != 0) {\n\n\t\t/* scrub all headers starting with OIDC_ first */\n\t\toidc_scrub_request_headers(r, OIDC_DEFAULT_HEADER_PREFIX,\n\t\t\t\toidc_cfg_dir_authn_header(r));\n\n\t\t/*\n\t\t * then see if the claim headers need to be removed on top of that\n\t\t * (i.e. the prefix does not start with the default OIDC_)\n\t\t */\n\t\tif ((strstr(cfg->claim_prefix, OIDC_DEFAULT_HEADER_PREFIX)\n\t\t\t\t!= cfg->claim_prefix)) {\n\t\t\toidc_scrub_request_headers(r, cfg->claim_prefix, NULL);\n\t\t}\n\t}\n\n\t/* set the user authentication HTTP header if set and required */\n\tif ((r->user != NULL) && (authn_header != NULL))\n\t\toidc_util_set_header(r, authn_header, r->user);\n\n\tconst char *s_claims = NULL;\n\tconst char *s_id_token = NULL;\n\n\t/* copy id_token and claims from session to request state and obtain their values */\n\toidc_copy_tokens_to_request_state(r, session, &s_id_token, &s_claims);\n\n\t/* set the claims in the app headers */\n\tif (oidc_set_app_claims(r, cfg, session, s_claims) == FALSE)\n\t\treturn HTTP_INTERNAL_SERVER_ERROR;\n\n\tif ((cfg->pass_idtoken_as & OIDC_PASS_IDTOKEN_AS_CLAIMS)) {\n\t\t/* set the id_token in the app headers */\n\t\tif (oidc_set_app_claims(r, cfg, session, s_id_token) == FALSE)\n\t\t\treturn HTTP_INTERNAL_SERVER_ERROR;\n\t}\n\n\tif ((cfg->pass_idtoken_as & OIDC_PASS_IDTOKEN_AS_PAYLOAD)) {\n\t\t/* pass the id_token JSON object to the app in a header or environment variable */\n\t\toidc_util_set_app_info(r, \"id_token_payload\", s_id_token,\n\t\t\t\tOIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);\n\t}\n\n\tif ((cfg->pass_idtoken_as & OIDC_PASS_IDTOKEN_AS_SERIALIZED)) {\n\t\tif (cfg->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {\n\t\t\tconst char *s_id_token = NULL;\n\t\t\t/* get the compact serialized JWT from the session */\n\t\t\toidc_session_get(r, session, OIDC_IDTOKEN_SESSION_KEY, &s_id_token);\n\t\t\t/* pass the compact serialized JWT to the app in a header or environment variable */\n\t\t\toidc_util_set_app_info(r, \"id_token\", s_id_token,\n\t\t\t\t\tOIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);\n\t\t} else {\n\t\t\toidc_error(r,\n\t\t\t\t\t\"session type \\\"client-cookie\\\" does not allow storing/passing the id_token; use \\\"OIDCSessionType server-cache\\\" for that\");\n\t\t}\n\t}\n\n\t/* set the refresh_token in the app headers/variables, if enabled for this location/directory */\n\tconst char *refresh_token = NULL;\n\toidc_session_get(r, session, OIDC_REFRESHTOKEN_SESSION_KEY, &refresh_token);\n\tif ((oidc_cfg_dir_pass_refresh_token(r) != 0) && (refresh_token != NULL)) {\n\t\t/* pass it to the app in a header or environment variable */\n\t\toidc_util_set_app_info(r, \"refresh_token\", refresh_token,\n\t\t\t\tOIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);\n\t}\n\n\t/* set the access_token in the app headers/variables */\n\tconst char *access_token = NULL;\n\toidc_session_get(r, session, OIDC_ACCESSTOKEN_SESSION_KEY, &access_token);\n\tif (access_token != NULL) {\n\t\t/* pass it to the app in a header or environment variable */\n\t\toidc_util_set_app_info(r, \"access_token\", access_token,\n\t\t\t\tOIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);\n\t}\n\n\t/* set the expiry timestamp in the app headers/variables */\n\tconst char *access_token_expires = NULL;\n\toidc_session_get(r, session, OIDC_ACCESSTOKEN_EXPIRES_SESSION_KEY,\n\t\t\t&access_token_expires);\n\tif (access_token_expires != NULL) {\n\t\t/* pass it to the app in a header or environment variable */\n\t\toidc_util_set_app_info(r, \"access_token_expires\", access_token_expires,\n\t\t\t\tOIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);\n\t}\n\n\t/*\n\t * reset the session inactivity timer\n\t * but only do this once per 10% of the inactivity timeout interval (with a max to 60 seconds)\n\t * for performance reasons\n\t *\n\t * now there's a small chance that the session ends 10% (or a minute) earlier than configured/expected\n\t * cq. when there's a request after a recent save (so no update) and then no activity happens until\n\t * a request comes in just before the session should expire\n\t * (\"recent\" and \"just before\" refer to 10%-with-a-max-of-60-seconds of the inactivity interval after\n\t * the start/last-update and before the expiry of the session respectively)\n\t *\n\t * this is be deemed acceptable here because of performance gain\n\t */\n\tapr_time_t interval = apr_time_from_sec(cfg->session_inactivity_timeout);\n\tapr_time_t now = apr_time_now();\n\tapr_time_t slack = interval / 10;\n\tif (slack > apr_time_from_sec(60))\n\t\tslack = apr_time_from_sec(60);\n\tif (session->expiry - now < interval - slack) {\n\t\tsession->expiry = now + interval;\n\t\tneeds_save = TRUE;\n\t}\n\n\t/* check if something was updated in the session and we need to save it again */\n\tif (needs_save)\n\t\tif (oidc_session_save(r, session) == FALSE)\n\t\t\treturn HTTP_INTERNAL_SERVER_ERROR;\n\n\t/* return \"user authenticated\" status */\n\treturn OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-287'], 'message': 'security fix: scrub headers on `OIDCUnAuthAction pass`; closes #222\n\nOn accessing paths protected with `OIDCUnAuthAction pass` no headers\nwould be scrubbed when a user is not authenticated so malicious\nsoftware/users could set OIDC_CLAIM_ and OIDCAuthNHeader headers that\napplications would interpret as set by mod_auth_openidc. Thanks\n@wouterhund.\n\nSigned-off-by: Hans Zandbelt '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: tight_detect_smooth_image24(VncState *vs, int w, int h)\n{\n int off;\n int x, y, d, dx;\n unsigned int c;\n unsigned int stats[256];\n int pixels = 0;\n int pix, left[3];\n unsigned int errors;\n unsigned char *buf = vs->tight.tight.buffer;\n\n /*\n * If client is big-endian, color samples begin from the second\n * byte (offset 1) of a 32-bit pixel value.\n */\n off = !!(vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG);\n\n memset(stats, 0, sizeof (stats));\n\n for (y = 0, x = 0; y < h && x < w;) {\n for (d = 0; d < h - y && d < w - x - VNC_TIGHT_DETECT_SUBROW_WIDTH;\n d++) {\n for (c = 0; c < 3; c++) {\n left[c] = buf[((y+d)*w+x+d)*4+off+c] & 0xFF;\n }\n for (dx = 1; dx <= VNC_TIGHT_DETECT_SUBROW_WIDTH; dx++) {\n for (c = 0; c < 3; c++) {\n pix = buf[((y+d)*w+x+d+dx)*4+off+c] & 0xFF;\n stats[abs(pix - left[c])]++;\n left[c] = pix;\n }\n pixels++;\n }\n }\n if (w > h) {\n x += h;\n y = 0;\n } else {\n x = 0;\n y += w;\n }\n }\n\n /* 95% smooth or more ... */\n if (stats[0] * 33 / pixels >= 95) {\n return 0;\n }\n\n errors = 0;\n for (c = 1; c < 8; c++) {\n errors += stats[c] * (c * c);\n if (stats[c] == 0 || stats[c] > stats[c-1] * 2) {\n return 0;\n }\n }\n for (; c < 256; c++) {\n errors += stats[c] * (c * c);\n }\n errors /= (pixels * 3 - stats[0]);\n\n return errors;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'pixman/vnc: use pixman images in vnc.\n\nThe vnc code uses *three* DisplaySurfaces:\n\nFirst is the surface of the actual QemuConsole, usually the guest\nscreen, but could also be a text console (monitor/serial reachable via\nCtrl-Alt- keys). This is left as-is.\n\nSecond is the current server's view of the screen content. The vnc code\nuses this to figure which parts of the guest screen did _really_ change\nto reduce the amount of updates sent to the vnc clients. It is also\nused as data source when sending out the updates to the clients. This\nsurface gets replaced by a pixman image. The format changes too,\ninstead of using the guest screen format we'll use fixed 32bit rgb\nframebuffer and convert the pixels on the fly when comparing and\nupdating the server framebuffer.\n\nThird surface carries the format expected by the vnc client. That isn't\nused to store image data. This surface is switched to PixelFormat and a\nboolean for bigendian byte order.\n\nSigned-off-by: Gerd Hoffmann '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int send_mono_rect(VncState *vs, int x, int y,\n int w, int h, uint32_t bg, uint32_t fg)\n{\n ssize_t bytes;\n int stream = 1;\n int level = tight_conf[vs->tight.compression].mono_zlib_level;\n\n#ifdef CONFIG_VNC_PNG\n if (tight_can_send_png_rect(vs, w, h)) {\n int ret;\n int bpp = vs->clientds.pf.bytes_per_pixel * 8;\n VncPalette *palette = palette_new(2, bpp);\n\n palette_put(palette, bg);\n palette_put(palette, fg);\n ret = send_png_rect(vs, x, y, w, h, palette);\n palette_destroy(palette);\n return ret;\n }\n#endif\n\n bytes = ((w + 7) / 8) * h;\n\n vnc_write_u8(vs, (stream | VNC_TIGHT_EXPLICIT_FILTER) << 4);\n vnc_write_u8(vs, VNC_TIGHT_FILTER_PALETTE);\n vnc_write_u8(vs, 1);\n\n switch(vs->clientds.pf.bytes_per_pixel) {\n case 4:\n {\n uint32_t buf[2] = {bg, fg};\n size_t ret = sizeof (buf);\n\n if (vs->tight.pixel24) {\n tight_pack24(vs, (unsigned char*)buf, 2, &ret);\n }\n vnc_write(vs, buf, ret);\n\n tight_encode_mono_rect32(vs->tight.tight.buffer, w, h, bg, fg);\n break;\n }\n case 2:\n vnc_write(vs, &bg, 2);\n vnc_write(vs, &fg, 2);\n tight_encode_mono_rect16(vs->tight.tight.buffer, w, h, bg, fg);\n break;\n default:\n vnc_write_u8(vs, bg);\n vnc_write_u8(vs, fg);\n tight_encode_mono_rect8(vs->tight.tight.buffer, w, h, bg, fg);\n break;\n }\n vs->tight.tight.offset = bytes;\n\n bytes = tight_compress_data(vs, stream, bytes, level, Z_DEFAULT_STRATEGY);\n return (bytes >= 0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'pixman/vnc: use pixman images in vnc.\n\nThe vnc code uses *three* DisplaySurfaces:\n\nFirst is the surface of the actual QemuConsole, usually the guest\nscreen, but could also be a text console (monitor/serial reachable via\nCtrl-Alt- keys). This is left as-is.\n\nSecond is the current server's view of the screen content. The vnc code\nuses this to figure which parts of the guest screen did _really_ change\nto reduce the amount of updates sent to the vnc clients. It is also\nused as data source when sending out the updates to the clients. This\nsurface gets replaced by a pixman image. The format changes too,\ninstead of using the guest screen format we'll use fixed 32bit rgb\nframebuffer and convert the pixels on the fly when comparing and\nupdating the server framebuffer.\n\nThird surface carries the format expected by the vnc client. That isn't\nused to store image data. This surface is switched to PixelFormat and a\nboolean for bigendian byte order.\n\nSigned-off-by: Gerd Hoffmann '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int tight_send_framebuffer_update(VncState *vs, int x, int y,\n int w, int h)\n{\n int max_rows;\n\n if (vs->clientds.pf.bytes_per_pixel == 4 && vs->clientds.pf.rmax == 0xFF &&\n vs->clientds.pf.bmax == 0xFF && vs->clientds.pf.gmax == 0xFF) {\n vs->tight.pixel24 = true;\n } else {\n vs->tight.pixel24 = false;\n }\n\n#ifdef CONFIG_VNC_JPEG\n if (vs->tight.quality != (uint8_t)-1) {\n double freq = vnc_update_freq(vs, x, y, w, h);\n\n if (freq > tight_jpeg_conf[vs->tight.quality].jpeg_freq_threshold) {\n return send_rect_simple(vs, x, y, w, h, false);\n }\n }\n#endif\n\n if (w * h < VNC_TIGHT_MIN_SPLIT_RECT_SIZE) {\n return send_rect_simple(vs, x, y, w, h, true);\n }\n\n /* Calculate maximum number of rows in one non-solid rectangle. */\n\n max_rows = tight_conf[vs->tight.compression].max_rect_size;\n max_rows /= MIN(tight_conf[vs->tight.compression].max_rect_width, w);\n\n return find_large_solid_color_rect(vs, x, y, w, h, max_rows);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'pixman/vnc: use pixman images in vnc.\n\nThe vnc code uses *three* DisplaySurfaces:\n\nFirst is the surface of the actual QemuConsole, usually the guest\nscreen, but could also be a text console (monitor/serial reachable via\nCtrl-Alt- keys). This is left as-is.\n\nSecond is the current server's view of the screen content. The vnc code\nuses this to figure which parts of the guest screen did _really_ change\nto reduce the amount of updates sent to the vnc clients. It is also\nused as data source when sending out the updates to the clients. This\nsurface gets replaced by a pixman image. The format changes too,\ninstead of using the guest screen format we'll use fixed 32bit rgb\nframebuffer and convert the pixels on the fly when comparing and\nupdating the server framebuffer.\n\nThird surface carries the format expected by the vnc client. That isn't\nused to store image data. This surface is switched to PixelFormat and a\nboolean for bigendian byte order.\n\nSigned-off-by: Gerd Hoffmann '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int fb_copy_cmap(const struct fb_cmap *from, struct fb_cmap *to)\n{\n\tint tooff = 0, fromoff = 0;\n\tint size;\n\n\tif (to->start > from->start)\n\t\tfromoff = to->start - from->start;\n\telse\n\t\ttooff = from->start - to->start;\n\tsize = to->len - tooff;\n\tif (size > (int) (from->len - fromoff))\n\t\tsize = from->len - fromoff;\n\tif (size <= 0)\n\t\treturn -EINVAL;\n\tsize *= sizeof(u16);\n\n\tmemcpy(to->red+tooff, from->red+fromoff, size);\n\tmemcpy(to->green+tooff, from->green+fromoff, size);\n\tmemcpy(to->blue+tooff, from->blue+fromoff, size);\n\tif (from->transp && to->transp)\n\t\tmemcpy(to->transp+tooff, from->transp+fromoff, size);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'fbdev: color map copying bounds checking\n\nCopying color maps to userspace doesn't check the value of to->start,\nwhich will cause kernel heap buffer OOB read due to signedness wraps.\n\nCVE-2016-8405\n\nLink: http://lkml.kernel.org/r/20170105224249.GA50925@beast\nFixes: 1da177e4c3f4 (\"Linux-2.6.12-rc2\")\nSigned-off-by: Kees Cook \nReported-by: Peter Pi (@heisecode) of Trend Micro\nCc: Min Chong \nCc: Dan Carpenter \nCc: Tomi Valkeinen \nCc: Bartlomiej Zolnierkiewicz \nCc: \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static struct n_hdlc *n_hdlc_alloc(void)\n{\n\tstruct n_hdlc_buf *buf;\n\tint i;\n\tstruct n_hdlc *n_hdlc = kzalloc(sizeof(*n_hdlc), GFP_KERNEL);\n\n\tif (!n_hdlc)\n\t\treturn NULL;\n\n\tspin_lock_init(&n_hdlc->rx_free_buf_list.spinlock);\n\tspin_lock_init(&n_hdlc->tx_free_buf_list.spinlock);\n\tspin_lock_init(&n_hdlc->rx_buf_list.spinlock);\n\tspin_lock_init(&n_hdlc->tx_buf_list.spinlock);\n\t\n\t/* allocate free rx buffer list */\n\tfor(i=0;irx_free_buf_list,buf);\n\t\telse if (debuglevel >= DEBUG_LEVEL_INFO)\t\n\t\t\tprintk(\"%s(%d)n_hdlc_alloc(), kalloc() failed for rx buffer %d\\n\",__FILE__,__LINE__, i);\n\t}\n\t\n\t/* allocate free tx buffer list */\n\tfor(i=0;itx_free_buf_list,buf);\n\t\telse if (debuglevel >= DEBUG_LEVEL_INFO)\t\n\t\t\tprintk(\"%s(%d)n_hdlc_alloc(), kalloc() failed for tx buffer %d\\n\",__FILE__,__LINE__, i);\n\t}\n\t\n\t/* Initialize the control block */\n\tn_hdlc->magic = HDLC_MAGIC;\n\tn_hdlc->flags = 0;\n\t\n\treturn n_hdlc;\n\t\n}\t/* end of n_hdlc_alloc() */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'tty: n_hdlc: get rid of racy n_hdlc.tbuf\n\nCurrently N_HDLC line discipline uses a self-made singly linked list for\ndata buffers and has n_hdlc.tbuf pointer for buffer retransmitting after\nan error.\n\nThe commit be10eb7589337e5defbe214dae038a53dd21add8\n(\"tty: n_hdlc add buffer flushing\") introduced racy access to n_hdlc.tbuf.\nAfter tx error concurrent flush_tx_queue() and n_hdlc_send_frames() can put\none data buffer to tx_free_buf_list twice. That causes double free in\nn_hdlc_release().\n\nLet's use standard kernel linked list and get rid of n_hdlc.tbuf:\nin case of tx error put current data buffer after the head of tx_buf_list.\n\nSigned-off-by: Alexander Popov \nCc: stable \nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int user_match(const struct key *key, const struct key_match_data *match_data)\n{\n\treturn strcmp(key->description, match_data->raw_data) == 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'KEYS: Remove key_type::match in favour of overriding default by match_preparse\n\nA previous patch added a ->match_preparse() method to the key type. This is\nallowed to override the function called by the iteration algorithm.\nTherefore, we can just set a default that simply checks for an exact match of\nthe key description with the original criterion data and allow match_preparse\nto override it as needed.\n\nThe key_type::match op is then redundant and can be removed, as can the\nuser_match() function.\n\nSigned-off-by: David Howells \nAcked-by: Vivek Goyal '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int hashbin_delete( hashbin_t* hashbin, FREE_FUNC free_func)\n{\n\tirda_queue_t* queue;\n\tunsigned long flags = 0;\n\tint i;\n\n\tIRDA_ASSERT(hashbin != NULL, return -1;);\n\tIRDA_ASSERT(hashbin->magic == HB_MAGIC, return -1;);\n\n\t/* Synchronize */\n\tif ( hashbin->hb_type & HB_LOCK ) {\n\t\tspin_lock_irqsave_nested(&hashbin->hb_spinlock, flags,\n\t\t\t\t\t hashbin_lock_depth++);\n\t}\n\n\t/*\n\t * Free the entries in the hashbin, TODO: use hashbin_clear when\n\t * it has been shown to work\n\t */\n\tfor (i = 0; i < HASHBIN_SIZE; i ++ ) {\n\t\tqueue = dequeue_first((irda_queue_t**) &hashbin->hb_queue[i]);\n\t\twhile (queue ) {\n\t\t\tif (free_func)\n\t\t\t\t(*free_func)(queue);\n\t\t\tqueue = dequeue_first(\n\t\t\t\t(irda_queue_t**) &hashbin->hb_queue[i]);\n\t\t}\n\t}\n\n\t/* Cleanup local data */\n\thashbin->hb_current = NULL;\n\thashbin->magic = ~HB_MAGIC;\n\n\t/* Release lock */\n\tif ( hashbin->hb_type & HB_LOCK) {\n\t\tspin_unlock_irqrestore(&hashbin->hb_spinlock, flags);\n#ifdef CONFIG_LOCKDEP\n\t\thashbin_lock_depth--;\n#endif\n\t}\n\n\t/*\n\t * Free the hashbin structure\n\t */\n\tkfree(hashbin);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'irda: Fix lockdep annotations in hashbin_delete().\n\nA nested lock depth was added to the hasbin_delete() code but it\ndoesn't actually work some well and results in tons of lockdep splats.\n\nFix the code instead to properly drop the lock around the operation\nand just keep peeking the head of the hashbin queue.\n\nReported-by: Dmitry Vyukov \nTested-by: Dmitry Vyukov \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void PeerListWidget::updatePeer(const QString &ip, BitTorrent::TorrentHandle *const torrent, const BitTorrent::PeerInfo &peer)\n{\n QStandardItem *item = m_peerItems.value(ip);\n int row = item->row();\n if (m_resolveCountries) {\n const QIcon ico = GuiIconProvider::instance()->getFlagIcon(peer.country());\n if (!ico.isNull()) {\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::COUNTRY), ico, Qt::DecorationRole);\n const QString countryName = Net::GeoIPManager::CountryName(peer.country());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::COUNTRY), countryName, Qt::ToolTipRole);\n m_missingFlags.remove(ip);\n }\n }\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::CONNECTION), peer.connectionType());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::PORT), peer.address().port);\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::FLAGS), peer.flags());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::FLAGS), peer.flagsDescription(), Qt::ToolTipRole);\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::CLIENT), peer.client());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::PROGRESS), peer.progress());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWN_SPEED), peer.payloadDownSpeed());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::UP_SPEED), peer.payloadUpSpeed());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::TOT_DOWN), peer.totalDownload());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::TOT_UP), peer.totalUpload());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::RELEVANCE), peer.relevance());\n QStringList downloadingFiles(torrent->info().filesForPiece(peer.downloadingPieceIndex()));\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWNLOADING_PIECE), downloadingFiles.join(QLatin1String(\";\")));\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWNLOADING_PIECE), downloadingFiles.join(QLatin1String(\"\\n\")), Qt::ToolTipRole);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-79'], 'message': 'Add Utils::String::toHtmlEscaped'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: am_cache_entry_t *am_cache_new(server_rec *s, const char *key)\n{\n am_cache_entry_t *t;\n am_mod_cfg_rec *mod_cfg;\n void *table;\n apr_time_t current_time;\n int i;\n apr_time_t age;\n int rv;\n char buffer[512];\n\n /* Check if we have a valid session key. We abort if we don't. */\n if(key == NULL || strlen(key) != AM_ID_LENGTH) {\n return NULL;\n }\n\n\n mod_cfg = am_get_mod_cfg(s);\n\n\n /* Lock the table. */\n if((rv = apr_global_mutex_lock(mod_cfg->lock)) != APR_SUCCESS) {\n ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,\n \"apr_global_mutex_lock() failed [%d]: %s\",\n rv, apr_strerror(rv, buffer, sizeof(buffer)));\n return NULL;\n }\n\n table = apr_shm_baseaddr_get(mod_cfg->cache);\n\n /* Get current time. If we find a entry with expires <= the current\n * time, then we can use it.\n */\n current_time = apr_time_now();\n\n /* We will use 't' to remember the best/oldest entry. We\n * initalize it to the first entry in the table to simplify the\n * following code (saves test for t == NULL).\n */\n t = am_cache_entry_ptr(mod_cfg, table, 0);\n\n /* Iterate over the session table. Update 't' to match the \"best\"\n * entry (the least recently used). 't' will point a free entry\n * if we find one. Otherwise, 't' will point to the least recently\n * used entry.\n */\n for(i = 0; i < mod_cfg->init_cache_size; i++) {\n am_cache_entry_t *e = am_cache_entry_ptr(mod_cfg, table, i);\n if (e->key[0] == '\\0') {\n /* This entry is free. Update 't' to this entry\n * and exit loop.\n */\n t = e;\n break;\n }\n\n if (e->expires <= current_time) {\n /* This entry is expired, and is therefore free.\n * Update 't' and exit loop.\n */\n t = e;\n break;\n }\n\n if (e->access < t->access) {\n /* This entry is older than 't' - update 't'. */\n t = e;\n }\n }\n\n\n if(t->key[0] != '\\0' && t->expires > current_time) {\n /* We dropped a LRU entry. Calculate the age in seconds. */\n age = (current_time - t->access) / 1000000;\n\n if(age < 3600) {\n ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s,\n \"Dropping LRU entry entry with age = %\" APR_TIME_T_FMT\n \"s, which is less than one hour. It may be a good\"\n \" idea to increase MellonCacheSize.\",\n age);\n }\n }\n\n /* Now 't' points to the entry we are going to use. We initialize\n * it and returns it.\n */\n\n strcpy(t->key, key);\n\n /* Far far into the future. */\n t->expires = 0x7fffffffffffffffLL;\n\n t->logged_in = 0;\n t->size = 0;\n\n am_cache_storage_null(&t->user);\n am_cache_storage_null(&t->lasso_identity);\n am_cache_storage_null(&t->lasso_session);\n am_cache_storage_null(&t->lasso_saml_response);\n am_cache_entry_env_null(t);\n\n t->pool_size = am_cache_entry_pool_size(mod_cfg);\n t->pool[0] = '\\0';\n t->pool_used = 1;\n\n return t;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-79'], 'message': 'Fix Cross-Site Session Transfer vulnerability\n\nmod_auth_mellon did not verify that the site the session was created\nfor was the same site as the site the user accessed. This allows an\nattacker with access to one web site on a server to use the same\nsession to get access to a different site running on the same server.\n\nThis patch fixes this vulnerability by storing the cookie parameters\nused when creating the session in the session, and verifying those\nparameters when the session is loaded.\n\nThanks to Fran\u00e7ois Kooman for reporting this vulnerability.\n\nThis vulnerability has been assigned CVE-2017-6807.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: sig_handler handle_kill_signal(int sig)\n{\n char kill_buffer[40];\n MYSQL *kill_mysql= NULL;\n const char *reason = sig == SIGINT ? \"Ctrl-C\" : \"Terminal close\";\n\n /* terminate if no query being executed, or we already tried interrupting */\n /* terminate if no query being executed, or we already tried interrupting */\n if (!executing_query || (interrupted_query == 2))\n {\n tee_fprintf(stdout, \"%s -- exit!\\n\", reason);\n goto err;\n }\n\n kill_mysql= mysql_init(kill_mysql);\n mysql_options(kill_mysql, MYSQL_OPT_CONNECT_ATTR_RESET, 0);\n mysql_options4(kill_mysql, MYSQL_OPT_CONNECT_ATTR_ADD,\n \"program_name\", \"mysql\");\n if (!mysql_connect_ssl_check(kill_mysql, current_host, current_user,\n opt_password, \"\", opt_mysql_port,\n opt_mysql_unix_port, 0, opt_ssl_required))\n {\n tee_fprintf(stdout, \"%s -- sorry, cannot connect to server to kill query, giving up ...\\n\", reason);\n goto err;\n }\n\n interrupted_query++;\n\n /* mysqld < 5 does not understand KILL QUERY, skip to KILL CONNECTION */\n if ((interrupted_query == 1) && (mysql_get_server_version(&mysql) < 50000))\n interrupted_query= 2;\n\n /* kill_buffer is always big enough because max length of %lu is 15 */\n sprintf(kill_buffer, \"KILL %s%lu\",\n (interrupted_query == 1) ? \"QUERY \" : \"\",\n mysql_thread_id(&mysql));\n tee_fprintf(stdout, \"%s -- sending \\\"%s\\\" to server ...\\n\", \n reason, kill_buffer);\n mysql_real_query(kill_mysql, kill_buffer, (uint) strlen(kill_buffer));\n mysql_close(kill_mysql);\n tee_fprintf(stdout, \"%s -- query aborted.\\n\", reason);\n\n return;\n\nerr:\n#ifdef _WIN32\n /*\n When SIGINT is raised on Windows, the OS creates a new thread to handle the\n interrupt. Once that thread completes, the main thread continues running \n only to find that it's resources have already been free'd when the sigint \n handler called mysql_end(). \n */\n mysql_thread_end();\n return;\n#else\n mysql_end(sig);\n#endif \n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-319'], 'message': 'BUG#25575605: SETTING --SSL-MODE=REQUIRED SENDS CREDENTIALS BEFORE VERIFYING SSL CONNECTION\n\nMYSQL_OPT_SSL_MODE option introduced.\nIt is set in case of --ssl-mode=REQUIRED and permits only SSL connection.\n\n(cherry picked from commit f91b941842d240b8a62645e507f5554e8be76aec)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: sql_real_connect(char *host,char *database,char *user,char *password,\n\t\t uint silent)\n{\n if (connected)\n {\n connected= 0;\n mysql_close(&mysql);\n }\n mysql_init(&mysql);\n if (opt_init_command)\n mysql_options(&mysql, MYSQL_INIT_COMMAND, opt_init_command);\n if (opt_connect_timeout)\n {\n uint timeout=opt_connect_timeout;\n mysql_options(&mysql,MYSQL_OPT_CONNECT_TIMEOUT,\n\t\t (char*) &timeout);\n }\n if (opt_compress)\n mysql_options(&mysql,MYSQL_OPT_COMPRESS,NullS);\n if (opt_secure_auth)\n mysql_options(&mysql, MYSQL_SECURE_AUTH, (char *) &opt_secure_auth);\n if (using_opt_local_infile)\n mysql_options(&mysql,MYSQL_OPT_LOCAL_INFILE, (char*) &opt_local_infile);\n#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)\n if (opt_use_ssl)\n mysql_ssl_set(&mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,\n\t\t opt_ssl_capath, opt_ssl_cipher);\n mysql_options(&mysql,MYSQL_OPT_SSL_VERIFY_SERVER_CERT,\n (char*)&opt_ssl_verify_server_cert);\n#endif\n if (opt_protocol)\n mysql_options(&mysql,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol);\n#ifdef HAVE_SMEM\n if (shared_memory_base_name)\n mysql_options(&mysql,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name);\n#endif\n if (safe_updates)\n {\n char init_command[100];\n sprintf(init_command,\n\t \"SET SQL_SAFE_UPDATES=1,SQL_SELECT_LIMIT=%lu,MAX_JOIN_SIZE=%lu\",\n\t select_limit,max_join_size);\n mysql_options(&mysql, MYSQL_INIT_COMMAND, init_command);\n }\n\n mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, default_charset);\n \n if (opt_plugin_dir && *opt_plugin_dir)\n mysql_options(&mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir);\n\n if (opt_default_auth && *opt_default_auth)\n mysql_options(&mysql, MYSQL_DEFAULT_AUTH, opt_default_auth);\n\n if (using_opt_enable_cleartext_plugin)\n mysql_options(&mysql, MYSQL_ENABLE_CLEARTEXT_PLUGIN, \n (char*) &opt_enable_cleartext_plugin);\n\n if (!mysql_connect_ssl_check(&mysql, host, user, password,\n database, opt_mysql_port, opt_mysql_unix_port,\n connect_flag | CLIENT_MULTI_STATEMENTS,\n opt_ssl_required))\n {\n if (!silent ||\n\t(mysql_errno(&mysql) != CR_CONN_HOST_ERROR &&\n\t mysql_errno(&mysql) != CR_CONNECTION_ERROR))\n {\n (void) put_error(&mysql);\n (void) fflush(stdout);\n return ignore_errors ? -1 : 1;\t\t// Abort\n }\n return -1;\t\t\t\t\t// Retryable\n }\n \n charset_info= mysql.charset;\n \n connected=1;\n#ifndef EMBEDDED_LIBRARY\n mysql.reconnect= debug_info_flag; // We want to know if this happens\n#else\n mysql.reconnect= 1;\n#endif\n#ifdef HAVE_READLINE\n build_completion_hash(opt_rehash, 1);\n#endif\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-319'], 'message': 'BUG#25575605: SETTING --SSL-MODE=REQUIRED SENDS CREDENTIALS BEFORE VERIFYING SSL CONNECTION\n\nMYSQL_OPT_SSL_MODE option introduced.\nIt is set in case of --ssl-mode=REQUIRED and permits only SSL connection.\n\n(cherry picked from commit 3b2d28578c526f347f5cfe763681eff365731f99)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: */\nstatic int send_client_reply_packet(MCPVIO_EXT *mpvio,\n const uchar *data, int data_len)\n{\n MYSQL *mysql= mpvio->mysql;\n NET *net= &mysql->net;\n char *buff, *end;\n\n /* see end= buff+32 below, fixed size of the packet is 32 bytes */\n buff= my_alloca(33 + USERNAME_LENGTH + data_len + NAME_LEN + NAME_LEN);\n \n mysql->client_flag|= mysql->options.client_flag;\n mysql->client_flag|= CLIENT_CAPABILITIES;\n\n if (mysql->client_flag & CLIENT_MULTI_STATEMENTS)\n mysql->client_flag|= CLIENT_MULTI_RESULTS;\n\n#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)\n if (mysql->options.ssl_key || mysql->options.ssl_cert ||\n mysql->options.ssl_ca || mysql->options.ssl_capath ||\n mysql->options.ssl_cipher)\n mysql->options.use_ssl= 1;\n if (mysql->options.use_ssl)\n mysql->client_flag|= CLIENT_SSL;\n#endif /* HAVE_OPENSSL && !EMBEDDED_LIBRARY*/\n if (mpvio->db)\n mysql->client_flag|= CLIENT_CONNECT_WITH_DB;\n\n /* Remove options that server doesn't support */\n mysql->client_flag= mysql->client_flag &\n (~(CLIENT_COMPRESS | CLIENT_SSL | CLIENT_PROTOCOL_41) \n | mysql->server_capabilities);\n\n#ifndef HAVE_COMPRESS\n mysql->client_flag&= ~CLIENT_COMPRESS;\n#endif\n\n if (mysql->client_flag & CLIENT_PROTOCOL_41)\n {\n /* 4.1 server and 4.1 client has a 32 byte option flag */\n int4store(buff,mysql->client_flag);\n int4store(buff+4, net->max_packet_size);\n buff[8]= (char) mysql->charset->number;\n bzero(buff+9, 32-9);\n end= buff+32;\n }\n else\n {\n int2store(buff, mysql->client_flag);\n int3store(buff+2, net->max_packet_size);\n end= buff+5;\n }\n#ifdef HAVE_OPENSSL\n if (mysql->client_flag & CLIENT_SSL)\n {\n /* Do the SSL layering. */\n struct st_mysql_options *options= &mysql->options;\n struct st_VioSSLFd *ssl_fd;\n enum enum_ssl_init_error ssl_init_error;\n const char *cert_error;\n unsigned long ssl_error;\n\n /*\n Send mysql->client_flag, max_packet_size - unencrypted otherwise\n the server does not know we want to do SSL\n */\n if (my_net_write(net, (uchar*)buff, (size_t) (end-buff)) || net_flush(net))\n {\n set_mysql_extended_error(mysql, CR_SERVER_LOST, unknown_sqlstate,\n ER(CR_SERVER_LOST_EXTENDED),\n \"sending connection information to server\",\n errno);\n goto error;\n }\n\n /* Create the VioSSLConnectorFd - init SSL and load certs */\n if (!(ssl_fd= new_VioSSLConnectorFd(options->ssl_key,\n options->ssl_cert,\n options->ssl_ca,\n options->ssl_capath,\n options->ssl_cipher,\n &ssl_init_error)))\n {\n set_mysql_extended_error(mysql, CR_SSL_CONNECTION_ERROR, unknown_sqlstate,\n ER(CR_SSL_CONNECTION_ERROR), sslGetErrString(ssl_init_error));\n goto error;\n }\n mysql->connector_fd= (unsigned char *) ssl_fd;\n\n /* Connect to the server */\n DBUG_PRINT(\"info\", (\"IO layer change in progress...\"));\n if (sslconnect(ssl_fd, net->vio,\n (long) (mysql->options.connect_timeout), &ssl_error))\n { \n char buf[512];\n ERR_error_string_n(ssl_error, buf, 512);\n buf[511]= 0;\n set_mysql_extended_error(mysql, CR_SSL_CONNECTION_ERROR, unknown_sqlstate,\n ER(CR_SSL_CONNECTION_ERROR),\n buf);\n goto error;\n } \n DBUG_PRINT(\"info\", (\"IO layer change done!\"));\n\n /* Verify server cert */\n if ((mysql->client_flag & CLIENT_SSL_VERIFY_SERVER_CERT) &&\n ssl_verify_server_cert(net->vio, mysql->host, &cert_error))\n {\n set_mysql_extended_error(mysql, CR_SSL_CONNECTION_ERROR, unknown_sqlstate,\n ER(CR_SSL_CONNECTION_ERROR), cert_error);\n goto error;\n }\n }\n#endif /* HAVE_OPENSSL */\n\n DBUG_PRINT(\"info\",(\"Server version = '%s' capabilites: %lu status: %u client_flag: %lu\",\n\t\t mysql->server_version, mysql->server_capabilities,\n\t\t mysql->server_status, mysql->client_flag));\n\n compile_time_assert(MYSQL_USERNAME_LENGTH == USERNAME_LENGTH);\n\n /* This needs to be changed as it's not useful with big packets */\n if (mysql->user[0])\n strmake(end, mysql->user, USERNAME_LENGTH);\n else\n read_user_name(end);\n\n /* We have to handle different version of handshake here */\n DBUG_PRINT(\"info\",(\"user: %s\",end));\n end= strend(end) + 1;\n if (data_len)\n {\n if (mysql->server_capabilities & CLIENT_SECURE_CONNECTION)\n {\n *end++= data_len;\n memcpy(end, data, data_len);\n end+= data_len;\n }\n else\n {\n DBUG_ASSERT(data_len == SCRAMBLE_LENGTH_323 + 1); /* incl. \\0 at the end */\n memcpy(end, data, data_len);\n end+= data_len;\n }\n }\n else\n *end++= 0;\n\n /* Add database if needed */\n if (mpvio->db && (mysql->server_capabilities & CLIENT_CONNECT_WITH_DB))\n {\n end= strmake(end, mpvio->db, NAME_LEN) + 1;\n mysql->db= my_strdup(mpvio->db, MYF(MY_WME));\n }\n\n if (mysql->server_capabilities & CLIENT_PLUGIN_AUTH)\n end= strmake(end, mpvio->plugin->name, NAME_LEN) + 1;\n\n /* Write authentication package */\n if (my_net_write(net, (uchar*) buff, (size_t) (end-buff)) || net_flush(net))\n {\n set_mysql_extended_error(mysql, CR_SERVER_LOST, unknown_sqlstate,\n ER(CR_SERVER_LOST_EXTENDED),\n \"sending authentication information\",\n errno);\n goto error;\n }\n my_afree(buff);\n return 0;\n \nerror:\n my_afree(buff);\n return 1; ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-319'], 'message': 'BUG#25575605: SETTING --SSL-MODE=REQUIRED SENDS CREDENTIALS BEFORE VERIFYING SSL CONNECTION\n\nMYSQL_OPT_SSL_MODE option introduced.\nIt is set in case of --ssl-mode=REQUIRED and permits only SSL connection.\n\n(cherry picked from commit 3b2d28578c526f347f5cfe763681eff365731f99)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static plist_t parse_bin_node(struct bplist_data *bplist, const char** object)\n{\n uint16_t type = 0;\n uint64_t size = 0;\n\n if (!object)\n return NULL;\n\n type = (**object) & BPLIST_MASK;\n size = (**object) & BPLIST_FILL;\n (*object)++;\n\n if (size == BPLIST_FILL) {\n switch (type) {\n case BPLIST_DATA:\n case BPLIST_STRING:\n case BPLIST_UNICODE:\n case BPLIST_ARRAY:\n case BPLIST_SET:\n case BPLIST_DICT:\n {\n uint16_t next_size = **object & BPLIST_FILL;\n if ((**object & BPLIST_MASK) != BPLIST_UINT) {\n PLIST_BIN_ERR(\"%s: invalid size node type for node type 0x%02x: found 0x%02x, expected 0x%02x\\n\", __func__, type, **object & BPLIST_MASK, BPLIST_UINT);\n return NULL;\n }\n (*object)++;\n next_size = 1 << next_size;\n if (*object + next_size > bplist->offset_table) {\n PLIST_BIN_ERR(\"%s: size node data bytes for node type 0x%02x point outside of valid range\\n\", __func__, type);\n return NULL;\n }\n size = UINT_TO_HOST(*object, next_size);\n (*object) += next_size;\n break;\n }\n default:\n break;\n }\n }\n\n switch (type)\n {\n\n case BPLIST_NULL:\n switch (size)\n {\n\n case BPLIST_TRUE:\n {\n plist_data_t data = plist_new_plist_data();\n data->type = PLIST_BOOLEAN;\n data->boolval = TRUE;\n data->length = 1;\n return node_create(NULL, data);\n }\n\n case BPLIST_FALSE:\n {\n plist_data_t data = plist_new_plist_data();\n data->type = PLIST_BOOLEAN;\n data->boolval = FALSE;\n data->length = 1;\n return node_create(NULL, data);\n }\n\n case BPLIST_NULL:\n default:\n return NULL;\n }\n\n case BPLIST_UINT:\n if (*object + (uint64_t)(1 << size) > bplist->offset_table) {\n PLIST_BIN_ERR(\"%s: BPLIST_UINT data bytes point outside of valid range\\n\", __func__);\n return NULL;\n }\n return parse_uint_node(object, size);\n\n case BPLIST_REAL:\n if (*object + (uint64_t)(1 << size) > bplist->offset_table) {\n PLIST_BIN_ERR(\"%s: BPLIST_REAL data bytes point outside of valid range\\n\", __func__);\n return NULL;\n }\n return parse_real_node(object, size);\n\n case BPLIST_DATE:\n if (3 != size) {\n PLIST_BIN_ERR(\"%s: invalid data size for BPLIST_DATE node\\n\", __func__);\n return NULL;\n }\n if (*object + (uint64_t)(1 << size) > bplist->offset_table) {\n PLIST_BIN_ERR(\"%s: BPLIST_DATE data bytes point outside of valid range\\n\", __func__);\n return NULL;\n }\n return parse_date_node(object, size);\n\n case BPLIST_DATA:\n if (*object + size > bplist->offset_table) {\n PLIST_BIN_ERR(\"%s: BPLIST_DATA data bytes point outside of valid range\\n\", __func__);\n return NULL;\n }\n return parse_data_node(object, size);\n\n case BPLIST_STRING:\n if (*object + size > bplist->offset_table) {\n PLIST_BIN_ERR(\"%s: BPLIST_STRING data bytes point outside of valid range\\n\", __func__);\n return NULL;\n }\n return parse_string_node(object, size);\n\n case BPLIST_UNICODE:\n if (size*2 < size) {\n PLIST_BIN_ERR(\"%s: Integer overflow when calculating BPLIST_UNICODE data size.\\n\", __func__);\n return NULL;\n }\n if (*object + size*2 > bplist->offset_table) {\n PLIST_BIN_ERR(\"%s: BPLIST_UNICODE data bytes point outside of valid range\\n\", __func__);\n return NULL;\n }\n return parse_unicode_node(object, size);\n\n case BPLIST_SET:\n case BPLIST_ARRAY:\n if (*object + size > bplist->offset_table) {\n PLIST_BIN_ERR(\"%s: BPLIST_ARRAY data bytes point outside of valid range\\n\", __func__);\n return NULL;\n }\n return parse_array_node(bplist, object, size);\n\n case BPLIST_UID:\n if (*object + size+1 > bplist->offset_table) {\n PLIST_BIN_ERR(\"%s: BPLIST_UID data bytes point outside of valid range\\n\", __func__);\n return NULL;\n }\n return parse_uid_node(object, size);\n\n case BPLIST_DICT:\n if (*object + size > bplist->offset_table) {\n PLIST_BIN_ERR(\"%s: BPLIST_REAL data bytes point outside of valid range\\n\", __func__);\n return NULL;\n }\n return parse_dict_node(bplist, object, size);\n\n default:\n PLIST_BIN_ERR(\"%s: unexpected node type 0x%02x\\n\", __func__, type);\n return NULL;\n }\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-119', 'CWE-415', 'CWE-787'], 'message': 'bplist: Fix data range check for string/data/dict/array nodes\n\nPassing a size of 0xFFFFFFFFFFFFFFFF to parse_string_node() might result\nin a memcpy with a size of -1, leading to undefined behavior.\nThis commit makes sure that the actual node data (which depends on the size)\nis in the range start_of_object..start_of_object+size.\n\nCredit to OSS-Fuzz'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: sg_ioctl(struct file *filp, unsigned int cmd_in, unsigned long arg)\n{\n\tvoid __user *p = (void __user *)arg;\n\tint __user *ip = p;\n\tint result, val, read_only;\n\tSg_device *sdp;\n\tSg_fd *sfp;\n\tSg_request *srp;\n\tunsigned long iflags;\n\n\tif ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))\n\t\treturn -ENXIO;\n\n\tSCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,\n\t\t\t\t \"sg_ioctl: cmd=0x%x\\n\", (int) cmd_in));\n\tread_only = (O_RDWR != (filp->f_flags & O_ACCMODE));\n\n\tswitch (cmd_in) {\n\tcase SG_IO:\n\t\tif (atomic_read(&sdp->detaching))\n\t\t\treturn -ENODEV;\n\t\tif (!scsi_block_when_processing_errors(sdp->device))\n\t\t\treturn -ENXIO;\n\t\tif (!access_ok(VERIFY_WRITE, p, SZ_SG_IO_HDR))\n\t\t\treturn -EFAULT;\n\t\tresult = sg_new_write(sfp, filp, p, SZ_SG_IO_HDR,\n\t\t\t\t 1, read_only, 1, &srp);\n\t\tif (result < 0)\n\t\t\treturn result;\n\t\tresult = wait_event_interruptible(sfp->read_wait,\n\t\t\t(srp_done(sfp, srp) || atomic_read(&sdp->detaching)));\n\t\tif (atomic_read(&sdp->detaching))\n\t\t\treturn -ENODEV;\n\t\twrite_lock_irq(&sfp->rq_list_lock);\n\t\tif (srp->done) {\n\t\t\tsrp->done = 2;\n\t\t\twrite_unlock_irq(&sfp->rq_list_lock);\n\t\t\tresult = sg_new_read(sfp, p, SZ_SG_IO_HDR, srp);\n\t\t\treturn (result < 0) ? result : 0;\n\t\t}\n\t\tsrp->orphan = 1;\n\t\twrite_unlock_irq(&sfp->rq_list_lock);\n\t\treturn result;\t/* -ERESTARTSYS because signal hit process */\n\tcase SG_SET_TIMEOUT:\n\t\tresult = get_user(val, ip);\n\t\tif (result)\n\t\t\treturn result;\n\t\tif (val < 0)\n\t\t\treturn -EIO;\n\t\tif (val >= mult_frac((s64)INT_MAX, USER_HZ, HZ))\n\t\t\tval = min_t(s64, mult_frac((s64)INT_MAX, USER_HZ, HZ),\n\t\t\t\t INT_MAX);\n\t\tsfp->timeout_user = val;\n\t\tsfp->timeout = mult_frac(val, HZ, USER_HZ);\n\n\t\treturn 0;\n\tcase SG_GET_TIMEOUT:\t/* N.B. User receives timeout as return value */\n\t\t\t\t/* strange ..., for backward compatibility */\n\t\treturn sfp->timeout_user;\n\tcase SG_SET_FORCE_LOW_DMA:\n\t\tresult = get_user(val, ip);\n\t\tif (result)\n\t\t\treturn result;\n\t\tif (val) {\n\t\t\tsfp->low_dma = 1;\n\t\t\tif ((0 == sfp->low_dma) && (0 == sg_res_in_use(sfp))) {\n\t\t\t\tval = (int) sfp->reserve.bufflen;\n\t\t\t\tsg_remove_scat(sfp, &sfp->reserve);\n\t\t\t\tsg_build_reserve(sfp, val);\n\t\t\t}\n\t\t} else {\n\t\t\tif (atomic_read(&sdp->detaching))\n\t\t\t\treturn -ENODEV;\n\t\t\tsfp->low_dma = sdp->device->host->unchecked_isa_dma;\n\t\t}\n\t\treturn 0;\n\tcase SG_GET_LOW_DMA:\n\t\treturn put_user((int) sfp->low_dma, ip);\n\tcase SG_GET_SCSI_ID:\n\t\tif (!access_ok(VERIFY_WRITE, p, sizeof (sg_scsi_id_t)))\n\t\t\treturn -EFAULT;\n\t\telse {\n\t\t\tsg_scsi_id_t __user *sg_idp = p;\n\n\t\t\tif (atomic_read(&sdp->detaching))\n\t\t\t\treturn -ENODEV;\n\t\t\t__put_user((int) sdp->device->host->host_no,\n\t\t\t\t &sg_idp->host_no);\n\t\t\t__put_user((int) sdp->device->channel,\n\t\t\t\t &sg_idp->channel);\n\t\t\t__put_user((int) sdp->device->id, &sg_idp->scsi_id);\n\t\t\t__put_user((int) sdp->device->lun, &sg_idp->lun);\n\t\t\t__put_user((int) sdp->device->type, &sg_idp->scsi_type);\n\t\t\t__put_user((short) sdp->device->host->cmd_per_lun,\n\t\t\t\t &sg_idp->h_cmd_per_lun);\n\t\t\t__put_user((short) sdp->device->queue_depth,\n\t\t\t\t &sg_idp->d_queue_depth);\n\t\t\t__put_user(0, &sg_idp->unused[0]);\n\t\t\t__put_user(0, &sg_idp->unused[1]);\n\t\t\treturn 0;\n\t\t}\n\tcase SG_SET_FORCE_PACK_ID:\n\t\tresult = get_user(val, ip);\n\t\tif (result)\n\t\t\treturn result;\n\t\tsfp->force_packid = val ? 1 : 0;\n\t\treturn 0;\n\tcase SG_GET_PACK_ID:\n\t\tif (!access_ok(VERIFY_WRITE, ip, sizeof (int)))\n\t\t\treturn -EFAULT;\n\t\tread_lock_irqsave(&sfp->rq_list_lock, iflags);\n\t\tfor (srp = sfp->headrp; srp; srp = srp->nextrp) {\n\t\t\tif ((1 == srp->done) && (!srp->sg_io_owned)) {\n\t\t\t\tread_unlock_irqrestore(&sfp->rq_list_lock,\n\t\t\t\t\t\t iflags);\n\t\t\t\t__put_user(srp->header.pack_id, ip);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t\tread_unlock_irqrestore(&sfp->rq_list_lock, iflags);\n\t\t__put_user(-1, ip);\n\t\treturn 0;\n\tcase SG_GET_NUM_WAITING:\n\t\tread_lock_irqsave(&sfp->rq_list_lock, iflags);\n\t\tfor (val = 0, srp = sfp->headrp; srp; srp = srp->nextrp) {\n\t\t\tif ((1 == srp->done) && (!srp->sg_io_owned))\n\t\t\t\t++val;\n\t\t}\n\t\tread_unlock_irqrestore(&sfp->rq_list_lock, iflags);\n\t\treturn put_user(val, ip);\n\tcase SG_GET_SG_TABLESIZE:\n\t\treturn put_user(sdp->sg_tablesize, ip);\n\tcase SG_SET_RESERVED_SIZE:\n\t\tresult = get_user(val, ip);\n\t\tif (result)\n\t\t\treturn result;\n if (val < 0)\n return -EINVAL;\n\t\tval = min_t(int, val,\n\t\t\t max_sectors_bytes(sdp->device->request_queue));\n\t\tif (val != sfp->reserve.bufflen) {\n\t\t\tif (sg_res_in_use(sfp) || sfp->mmap_called)\n\t\t\t\treturn -EBUSY;\n\t\t\tsg_remove_scat(sfp, &sfp->reserve);\n\t\t\tsg_build_reserve(sfp, val);\n\t\t}\n\t\treturn 0;\n\tcase SG_GET_RESERVED_SIZE:\n\t\tval = min_t(int, sfp->reserve.bufflen,\n\t\t\t max_sectors_bytes(sdp->device->request_queue));\n\t\treturn put_user(val, ip);\n\tcase SG_SET_COMMAND_Q:\n\t\tresult = get_user(val, ip);\n\t\tif (result)\n\t\t\treturn result;\n\t\tsfp->cmd_q = val ? 1 : 0;\n\t\treturn 0;\n\tcase SG_GET_COMMAND_Q:\n\t\treturn put_user((int) sfp->cmd_q, ip);\n\tcase SG_SET_KEEP_ORPHAN:\n\t\tresult = get_user(val, ip);\n\t\tif (result)\n\t\t\treturn result;\n\t\tsfp->keep_orphan = val;\n\t\treturn 0;\n\tcase SG_GET_KEEP_ORPHAN:\n\t\treturn put_user((int) sfp->keep_orphan, ip);\n\tcase SG_NEXT_CMD_LEN:\n\t\tresult = get_user(val, ip);\n\t\tif (result)\n\t\t\treturn result;\n\t\tsfp->next_cmd_len = (val > 0) ? val : 0;\n\t\treturn 0;\n\tcase SG_GET_VERSION_NUM:\n\t\treturn put_user(sg_version_num, ip);\n\tcase SG_GET_ACCESS_COUNT:\n\t\t/* faked - we don't have a real access count anymore */\n\t\tval = (sdp->device ? 1 : 0);\n\t\treturn put_user(val, ip);\n\tcase SG_GET_REQUEST_TABLE:\n\t\tif (!access_ok(VERIFY_WRITE, p, SZ_SG_REQ_INFO * SG_MAX_QUEUE))\n\t\t\treturn -EFAULT;\n\t\telse {\n\t\t\tsg_req_info_t *rinfo;\n\t\t\tunsigned int ms;\n\n\t\t\trinfo = kmalloc(SZ_SG_REQ_INFO * SG_MAX_QUEUE,\n\t\t\t\t\t\t\t\tGFP_KERNEL);\n\t\t\tif (!rinfo)\n\t\t\t\treturn -ENOMEM;\n\t\t\tread_lock_irqsave(&sfp->rq_list_lock, iflags);\n\t\t\tfor (srp = sfp->headrp, val = 0; val < SG_MAX_QUEUE;\n\t\t\t ++val, srp = srp ? srp->nextrp : srp) {\n\t\t\t\tmemset(&rinfo[val], 0, SZ_SG_REQ_INFO);\n\t\t\t\tif (srp) {\n\t\t\t\t\trinfo[val].req_state = srp->done + 1;\n\t\t\t\t\trinfo[val].problem =\n\t\t\t\t\t srp->header.masked_status & \n\t\t\t\t\t srp->header.host_status & \n\t\t\t\t\t srp->header.driver_status;\n\t\t\t\t\tif (srp->done)\n\t\t\t\t\t\trinfo[val].duration =\n\t\t\t\t\t\t\tsrp->header.duration;\n\t\t\t\t\telse {\n\t\t\t\t\t\tms = jiffies_to_msecs(jiffies);\n\t\t\t\t\t\trinfo[val].duration =\n\t\t\t\t\t\t (ms > srp->header.duration) ?\n\t\t\t\t\t\t (ms - srp->header.duration) : 0;\n\t\t\t\t\t}\n\t\t\t\t\trinfo[val].orphan = srp->orphan;\n\t\t\t\t\trinfo[val].sg_io_owned =\n\t\t\t\t\t\t\tsrp->sg_io_owned;\n\t\t\t\t\trinfo[val].pack_id =\n\t\t\t\t\t\t\tsrp->header.pack_id;\n\t\t\t\t\trinfo[val].usr_ptr =\n\t\t\t\t\t\t\tsrp->header.usr_ptr;\n\t\t\t\t}\n\t\t\t}\n\t\t\tread_unlock_irqrestore(&sfp->rq_list_lock, iflags);\n\t\t\tresult = __copy_to_user(p, rinfo, \n\t\t\t\t\t\tSZ_SG_REQ_INFO * SG_MAX_QUEUE);\n\t\t\tresult = result ? -EFAULT : 0;\n\t\t\tkfree(rinfo);\n\t\t\treturn result;\n\t\t}\n\tcase SG_EMULATED_HOST:\n\t\tif (atomic_read(&sdp->detaching))\n\t\t\treturn -ENODEV;\n\t\treturn put_user(sdp->device->host->hostt->emulated, ip);\n\tcase SCSI_IOCTL_SEND_COMMAND:\n\t\tif (atomic_read(&sdp->detaching))\n\t\t\treturn -ENODEV;\n\t\tif (read_only) {\n\t\t\tunsigned char opcode = WRITE_6;\n\t\t\tScsi_Ioctl_Command __user *siocp = p;\n\n\t\t\tif (copy_from_user(&opcode, siocp->data, 1))\n\t\t\t\treturn -EFAULT;\n\t\t\tif (sg_allow_access(filp, &opcode))\n\t\t\t\treturn -EPERM;\n\t\t}\n\t\treturn sg_scsi_ioctl(sdp->device->request_queue, NULL, filp->f_mode, p);\n\tcase SG_SET_DEBUG:\n\t\tresult = get_user(val, ip);\n\t\tif (result)\n\t\t\treturn result;\n\t\tsdp->sgdebug = (char) val;\n\t\treturn 0;\n\tcase BLKSECTGET:\n\t\treturn put_user(max_sectors_bytes(sdp->device->request_queue),\n\t\t\t\tip);\n\tcase BLKTRACESETUP:\n\t\treturn blk_trace_setup(sdp->device->request_queue,\n\t\t\t\t sdp->disk->disk_name,\n\t\t\t\t MKDEV(SCSI_GENERIC_MAJOR, sdp->index),\n\t\t\t\t NULL,\n\t\t\t\t (char *)arg);\n\tcase BLKTRACESTART:\n\t\treturn blk_trace_startstop(sdp->device->request_queue, 1);\n\tcase BLKTRACESTOP:\n\t\treturn blk_trace_startstop(sdp->device->request_queue, 0);\n\tcase BLKTRACETEARDOWN:\n\t\treturn blk_trace_remove(sdp->device->request_queue);\n\tcase SCSI_IOCTL_GET_IDLUN:\n\tcase SCSI_IOCTL_GET_BUS_NUMBER:\n\tcase SCSI_IOCTL_PROBE_HOST:\n\tcase SG_GET_TRANSFORM:\n\tcase SG_SCSI_RESET:\n\t\tif (atomic_read(&sdp->detaching))\n\t\t\treturn -ENODEV;\n\t\tbreak;\n\tdefault:\n\t\tif (read_only)\n\t\t\treturn -EPERM;\t/* don't know so take safe approach */\n\t\tbreak;\n\t}\n\n\tresult = scsi_ioctl_block_when_processing_errors(sdp->device,\n\t\t\tcmd_in, filp->f_flags & O_NDELAY);\n\tif (result)\n\t\treturn result;\n\treturn scsi_ioctl(sdp->device, cmd_in, p);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'scsi: sg: check length passed to SG_NEXT_CMD_LEN\n\nThe user can control the size of the next command passed along, but the\nvalue passed to the ioctl isn't checked against the usable max command\nsize.\n\nCc: \nSigned-off-by: Peter Chang \nAcked-by: Douglas Gilbert \nSigned-off-by: Martin K. Petersen '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int jp2_cmap_getdata(jp2_box_t *box, jas_stream_t *in)\n{\n\tjp2_cmap_t *cmap = &box->data.cmap;\n\tjp2_cmapent_t *ent;\n\tunsigned int i;\n\n\tcmap->numchans = (box->datalen) / 4;\n\tif (!(cmap->ents = jas_alloc2(cmap->numchans, sizeof(jp2_cmapent_t)))) {\n\t\treturn -1;\n\t}\n\tfor (i = 0; i < cmap->numchans; ++i) {\n\t\tent = &cmap->ents[i];\n\t\tif (jp2_getuint16(in, &ent->cmptno) ||\n\t\t jp2_getuint8(in, &ent->map) ||\n\t\t jp2_getuint8(in, &ent->pcol)) {\n\t\t\treturn -1;\n\t\t}\n\t}\n\t\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed bugs due to uninitialized data in the JP2 decoder.\nAlso, added some comments marking I/O stream interfaces that probably\nneed to be changed (in the long term) to fix integer overflow problems.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void __sock_recv_timestamp(struct msghdr *msg, struct sock *sk,\n\tstruct sk_buff *skb)\n{\n\tint need_software_tstamp = sock_flag(sk, SOCK_RCVTSTAMP);\n\tstruct scm_timestamping tss;\n\tint empty = 1;\n\tstruct skb_shared_hwtstamps *shhwtstamps =\n\t\tskb_hwtstamps(skb);\n\n\t/* Race occurred between timestamp enabling and packet\n\t receiving. Fill in the current time for now. */\n\tif (need_software_tstamp && skb->tstamp == 0)\n\t\t__net_timestamp(skb);\n\n\tif (need_software_tstamp) {\n\t\tif (!sock_flag(sk, SOCK_RCVTSTAMPNS)) {\n\t\t\tstruct timeval tv;\n\t\t\tskb_get_timestamp(skb, &tv);\n\t\t\tput_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMP,\n\t\t\t\t sizeof(tv), &tv);\n\t\t} else {\n\t\t\tstruct timespec ts;\n\t\t\tskb_get_timestampns(skb, &ts);\n\t\t\tput_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPNS,\n\t\t\t\t sizeof(ts), &ts);\n\t\t}\n\t}\n\n\tmemset(&tss, 0, sizeof(tss));\n\tif ((sk->sk_tsflags & SOF_TIMESTAMPING_SOFTWARE) &&\n\t ktime_to_timespec_cond(skb->tstamp, tss.ts + 0))\n\t\tempty = 0;\n\tif (shhwtstamps &&\n\t (sk->sk_tsflags & SOF_TIMESTAMPING_RAW_HARDWARE) &&\n\t ktime_to_timespec_cond(shhwtstamps->hwtstamp, tss.ts + 2))\n\t\tempty = 0;\n\tif (!empty) {\n\t\tput_cmsg(msg, SOL_SOCKET,\n\t\t\t SCM_TIMESTAMPING, sizeof(tss), &tss);\n\n\t\tif (skb_is_err_queue(skb) && skb->len &&\n\t\t (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS))\n\t\t\tput_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING_OPT_STATS,\n\t\t\t\t skb->len, skb->data);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'tcp: mark skbs with SCM_TIMESTAMPING_OPT_STATS\n\nSOF_TIMESTAMPING_OPT_STATS can be enabled and disabled\nwhile packets are collected on the error queue.\nSo, checking SOF_TIMESTAMPING_OPT_STATS in sk->sk_tsflags\nis not enough to safely assume that the skb contains\nOPT_STATS data.\n\nAdd a bit in sock_exterr_skb to indicate whether the\nskb contains opt_stats data.\n\nFixes: 1c885808e456 (\"tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING\")\nReported-by: JongHwan Kim \nSigned-off-by: Soheil Hassas Yeganeh \nSigned-off-by: Eric Dumazet \nSigned-off-by: Willem de Bruijn \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int fscrypt_d_revalidate(struct dentry *dentry, unsigned int flags)\n{\n\tstruct dentry *dir;\n\tstruct fscrypt_info *ci;\n\tint dir_has_key, cached_with_key;\n\n\tif (flags & LOOKUP_RCU)\n\t\treturn -ECHILD;\n\n\tdir = dget_parent(dentry);\n\tif (!d_inode(dir)->i_sb->s_cop->is_encrypted(d_inode(dir))) {\n\t\tdput(dir);\n\t\treturn 0;\n\t}\n\n\tci = d_inode(dir)->i_crypt_info;\n\tif (ci && ci->ci_keyring_key &&\n\t (ci->ci_keyring_key->flags & ((1 << KEY_FLAG_INVALIDATED) |\n\t\t\t\t\t (1 << KEY_FLAG_REVOKED) |\n\t\t\t\t\t (1 << KEY_FLAG_DEAD))))\n\t\tci = NULL;\n\n\t/* this should eventually be an flag in d_flags */\n\tspin_lock(&dentry->d_lock);\n\tcached_with_key = dentry->d_flags & DCACHE_ENCRYPTED_WITH_KEY;\n\tspin_unlock(&dentry->d_lock);\n\tdir_has_key = (ci != NULL);\n\tdput(dir);\n\n\t/*\n\t * If the dentry was cached without the key, and it is a\n\t * negative dentry, it might be a valid name. We can't check\n\t * if the key has since been made available due to locking\n\t * reasons, so we fail the validation so ext4_lookup() can do\n\t * this check.\n\t *\n\t * We also fail the validation if the dentry was created with\n\t * the key present, but we no longer have the key, or vice versa.\n\t */\n\tif ((!cached_with_key && d_is_negative(dentry)) ||\n\t\t\t(!cached_with_key && dir_has_key) ||\n\t\t\t(cached_with_key && !dir_has_key))\n\t\treturn 0;\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-476'], 'message': 'fscrypt: remove broken support for detecting keyring key revocation\n\nFilesystem encryption ostensibly supported revoking a keyring key that\nhad been used to \"unlock\" encrypted files, causing those files to become\n\"locked\" again. This was, however, buggy for several reasons, the most\nsevere of which was that when key revocation happened to be detected for\nan inode, its fscrypt_info was immediately freed, even while other\nthreads could be using it for encryption or decryption concurrently.\nThis could be exploited to crash the kernel or worse.\n\nThis patch fixes the use-after-free by removing the code which detects\nthe keyring key having been revoked, invalidated, or expired. Instead,\nan encrypted inode that is \"unlocked\" now simply remains unlocked until\nit is evicted from memory. Note that this is no worse than the case for\nblock device-level encryption, e.g. dm-crypt, and it still remains\npossible for a privileged user to evict unused pages, inodes, and\ndentries by running 'sync; echo 3 > /proc/sys/vm/drop_caches', or by\nsimply unmounting the filesystem. In fact, one of those actions was\nalready needed anyway for key revocation to work even somewhat sanely.\nThis change is not expected to break any applications.\n\nIn the future I'd like to implement a real API for fscrypt key\nrevocation that interacts sanely with ongoing filesystem operations ---\nwaiting for existing operations to complete and blocking new operations,\nand invalidating and sanitizing key material and plaintext from the VFS\ncaches. But this is a hard problem, and for now this bug must be fixed.\n\nThis bug affected almost all versions of ext4, f2fs, and ubifs\nencryption, and it was potentially reachable in any kernel configured\nwith encryption support (CONFIG_EXT4_ENCRYPTION=y,\nCONFIG_EXT4_FS_ENCRYPTION=y, CONFIG_F2FS_FS_ENCRYPTION=y, or\nCONFIG_UBIFS_FS_ENCRYPTION=y). Note that older kernels did not use the\nshared fs/crypto/ code, but due to the potential security implications\nof this bug, it may still be worthwhile to backport this fix to them.\n\nFixes: b7236e21d55f (\"ext4 crypto: reorganize how we store keys in the inode\")\nCc: stable@vger.kernel.org # v4.2+\nSigned-off-by: Eric Biggers \nSigned-off-by: Theodore Ts'o \nAcked-by: Michael Halcrow '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: archive_strncat_l(struct archive_string *as, const void *_p, size_t n,\n struct archive_string_conv *sc)\n{\n\tconst void *s;\n\tsize_t length;\n\tint i, r = 0, r2;\n\n\t/* We must allocate memory even if there is no data for conversion\n\t * or copy. This simulates archive_string_append behavior. */\n\tif (_p == NULL || n == 0) {\n\t\tint tn = 1;\n\t\tif (sc != NULL && (sc->flag & SCONV_TO_UTF16))\n\t\t\ttn = 2;\n\t\tif (archive_string_ensure(as, as->length + tn) == NULL)\n\t\t\treturn (-1);\n\t\tas->s[as->length] = 0;\n\t\tif (tn == 2)\n\t\t\tas->s[as->length+1] = 0;\n\t\treturn (0);\n\t}\n\n\t/*\n\t * If sc is NULL, we just make a copy.\n\t */\n\tif (sc == NULL) {\n\t\tlength = mbsnbytes(_p, n);\n\t\tif (archive_string_append(as, _p, length) == NULL)\n\t\t\treturn (-1);/* No memory */\n\t\treturn (0);\n\t}\n\n\tif (sc->flag & SCONV_FROM_UTF16)\n\t\tlength = utf16nbytes(_p, n);\n\telse\n\t\tlength = mbsnbytes(_p, n);\n\ts = _p;\n\ti = 0;\n\tif (sc->nconverter > 1) {\n\t\tsc->utftmp.length = 0;\n\t\tr2 = sc->converter[0](&(sc->utftmp), s, length, sc);\n\t\tif (r2 != 0 && errno == ENOMEM)\n\t\t\treturn (r2);\n\t\tif (r > r2)\n\t\t\tr = r2;\n\t\ts = sc->utftmp.s;\n\t\tlength = sc->utftmp.length;\n\t\t++i;\n\t}\n\tr2 = sc->converter[i](as, s, length, sc);\n\tif (r > r2)\n\t\tr = r2;\n\treturn (r);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'archive_strncat_l(): allocate and do not convert if length == 0\n\nThis ensures e.g. that archive_mstring_copy_mbs_len_l() does not set\naes_set = AES_SET_MBS with aes_mbs.s == NULL.\n\nResolves possible null-pointer dereference reported by OSS-Fuzz.\n\nReported-By:\tOSS-Fuzz issue 286'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: */\nstatic void re_yyensure_buffer_stack (yyscan_t yyscanner)\n{\n\tyy_size_t num_to_alloc;\n struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;\n\n\tif (!yyg->yy_buffer_stack) {\n\n\t\t/* First allocation is just for 2 elements, since we don't know if this\n\t\t * scanner will even need a stack. We use 2 instead of 1 to avoid an\n\t\t * immediate realloc on the next call.\n */\n\t\tnum_to_alloc = 1; // After all that talk, this was set to 1 anyways...\n\t\tyyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyalloc\n\t\t\t\t\t\t\t\t(num_to_alloc * sizeof(struct yy_buffer_state*)\n\t\t\t\t\t\t\t\t, yyscanner);\n\t\tif ( ! yyg->yy_buffer_stack )\n\t\t\tYY_FATAL_ERROR( \"out of dynamic memory in re_yyensure_buffer_stack()\" );\n\t\t\t\t\t\t\t\t \n\t\tmemset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*));\n\t\t\t\t\n\t\tyyg->yy_buffer_stack_max = num_to_alloc;\n\t\tyyg->yy_buffer_stack_top = 0;\n\t\treturn;\n\t}\n\n\tif (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){\n\n\t\t/* Increase the buffer to prepare for a possible push. */\n\t\tyy_size_t grow_size = 8 /* arbitrary grow size */;\n\n\t\tnum_to_alloc = yyg->yy_buffer_stack_max + grow_size;\n\t\tyyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyrealloc\n\t\t\t\t\t\t\t\t(yyg->yy_buffer_stack,\n\t\t\t\t\t\t\t\tnum_to_alloc * sizeof(struct yy_buffer_state*)\n\t\t\t\t\t\t\t\t, yyscanner);\n\t\tif ( ! yyg->yy_buffer_stack )\n\t\t\tYY_FATAL_ERROR( \"out of dynamic memory in re_yyensure_buffer_stack()\" );\n\n\t\t/* zero only the new slots.*/\n\t\tmemset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*));\n\t\tyyg->yy_buffer_stack_max = num_to_alloc;\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-703', 'CWE-125'], 'message': 're_lexer: Make reading escape sequences more robust (#586)\n\n* Add test for issue #503\r\n\r\n* re_lexer: Make reading escape sequences more robust\r\n\r\nThis commit fixes parsing incomplete escape sequences at the end of a\r\nregular expression and parsing things like \\xxy (invalid hex digits)\r\nwhich before were silently turned into (char)255.\r\n\r\nClose #503\r\n\r\n* Update re_lexer.c'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: psf_binheader_readf (SF_PRIVATE *psf, char const *format, ...)\n{\tva_list\t\t\targptr ;\n\tsf_count_t\t\t*countptr, countdata ;\n\tunsigned char\t*ucptr, sixteen_bytes [16] ;\n\tunsigned int \t*intptr, intdata ;\n\tunsigned short\t*shortptr ;\n\tchar\t\t\t*charptr ;\n\tfloat\t\t\t*floatptr ;\n\tdouble\t\t\t*doubleptr ;\n\tchar\t\t\tc ;\n\tint\t\t\t\tbyte_count = 0, count ;\n\n\tif (! format)\n\t\treturn psf_ftell (psf) ;\n\n\tva_start (argptr, format) ;\n\n\twhile ((c = *format++))\n\t{\tswitch (c)\n\t\t{\tcase 'e' : /* All conversions are now from LE to host. */\n\t\t\t\t\tpsf->rwf_endian = SF_ENDIAN_LITTLE ;\n\t\t\t\t\tbreak ;\n\n\t\t\tcase 'E' : /* All conversions are now from BE to host. */\n\t\t\t\t\tpsf->rwf_endian = SF_ENDIAN_BIG ;\n\t\t\t\t\tbreak ;\n\n\t\t\tcase 'm' : /* 4 byte marker value eg 'RIFF' */\n\t\t\t\t\tintptr = va_arg (argptr, unsigned int*) ;\n\t\t\t\t\tucptr = (unsigned char*) intptr ;\n\t\t\t\t\tbyte_count += header_read (psf, ucptr, sizeof (int)) ;\n\t\t\t\t\t*intptr = GET_MARKER (ucptr) ;\n\t\t\t\t\tbreak ;\n\n\t\t\tcase 'h' :\n\t\t\t\t\tintptr = va_arg (argptr, unsigned int*) ;\n\t\t\t\t\tucptr = (unsigned char*) intptr ;\n\t\t\t\t\tbyte_count += header_read (psf, sixteen_bytes, sizeof (sixteen_bytes)) ;\n\t\t\t\t\t{\tint k ;\n\t\t\t\t\t\tintdata = 0 ;\n\t\t\t\t\t\tfor (k = 0 ; k < 16 ; k++)\n\t\t\t\t\t\t\tintdata ^= sixteen_bytes [k] << k ;\n\t\t\t\t\t\t}\n\t\t\t\t\t*intptr = intdata ;\n\t\t\t\t\tbreak ;\n\n\t\t\tcase '1' :\n\t\t\t\t\tcharptr = va_arg (argptr, char*) ;\n\t\t\t\t\t*charptr = 0 ;\n\t\t\t\t\tbyte_count += header_read (psf, charptr, sizeof (char)) ;\n\t\t\t\t\tbreak ;\n\n\t\t\tcase '2' : /* 2 byte value with the current endian-ness */\n\t\t\t\t\tshortptr = va_arg (argptr, unsigned short*) ;\n\t\t\t\t\t*shortptr = 0 ;\n\t\t\t\t\tucptr = (unsigned char*) shortptr ;\n\t\t\t\t\tbyte_count += header_read (psf, ucptr, sizeof (short)) ;\n\t\t\t\t\tif (psf->rwf_endian == SF_ENDIAN_BIG)\n\t\t\t\t\t\t*shortptr = GET_BE_SHORT (ucptr) ;\n\t\t\t\t\telse\n\t\t\t\t\t\t*shortptr = GET_LE_SHORT (ucptr) ;\n\t\t\t\t\tbreak ;\n\n\t\t\tcase '3' : /* 3 byte value with the current endian-ness */\n\t\t\t\t\tintptr = va_arg (argptr, unsigned int*) ;\n\t\t\t\t\t*intptr = 0 ;\n\t\t\t\t\tbyte_count += header_read (psf, sixteen_bytes, 3) ;\n\t\t\t\t\tif (psf->rwf_endian == SF_ENDIAN_BIG)\n\t\t\t\t\t\t*intptr = GET_BE_3BYTE (sixteen_bytes) ;\n\t\t\t\t\telse\n\t\t\t\t\t\t*intptr = GET_LE_3BYTE (sixteen_bytes) ;\n\t\t\t\t\tbreak ;\n\n\t\t\tcase '4' : /* 4 byte value with the current endian-ness */\n\t\t\t\t\tintptr = va_arg (argptr, unsigned int*) ;\n\t\t\t\t\t*intptr = 0 ;\n\t\t\t\t\tucptr = (unsigned char*) intptr ;\n\t\t\t\t\tbyte_count += header_read (psf, ucptr, sizeof (int)) ;\n\t\t\t\t\tif (psf->rwf_endian == SF_ENDIAN_BIG)\n\t\t\t\t\t\t*intptr = psf_get_be32 (ucptr, 0) ;\n\t\t\t\t\telse\n\t\t\t\t\t\t*intptr = psf_get_le32 (ucptr, 0) ;\n\t\t\t\t\tbreak ;\n\n\t\t\tcase '8' : /* 8 byte value with the current endian-ness */\n\t\t\t\t\tcountptr = va_arg (argptr, sf_count_t *) ;\n\t\t\t\t\t*countptr = 0 ;\n\t\t\t\t\tbyte_count += header_read (psf, sixteen_bytes, 8) ;\n\t\t\t\t\tif (psf->rwf_endian == SF_ENDIAN_BIG)\n\t\t\t\t\t\tcountdata = psf_get_be64 (sixteen_bytes, 0) ;\n\t\t\t\t\telse\n\t\t\t\t\t\tcountdata = psf_get_le64 (sixteen_bytes, 0) ;\n\t\t\t\t\t*countptr = countdata ;\n\t\t\t\t\tbreak ;\n\n\t\t\tcase 'f' : /* Float conversion */\n\t\t\t\t\tfloatptr = va_arg (argptr, float *) ;\n\t\t\t\t\t*floatptr = 0.0 ;\n\t\t\t\t\tbyte_count += header_read (psf, floatptr, sizeof (float)) ;\n\t\t\t\t\tif (psf->rwf_endian == SF_ENDIAN_BIG)\n\t\t\t\t\t\t*floatptr = float32_be_read ((unsigned char*) floatptr) ;\n\t\t\t\t\telse\n\t\t\t\t\t\t*floatptr = float32_le_read ((unsigned char*) floatptr) ;\n\t\t\t\t\tbreak ;\n\n\t\t\tcase 'd' : /* double conversion */\n\t\t\t\t\tdoubleptr = va_arg (argptr, double *) ;\n\t\t\t\t\t*doubleptr = 0.0 ;\n\t\t\t\t\tbyte_count += header_read (psf, doubleptr, sizeof (double)) ;\n\t\t\t\t\tif (psf->rwf_endian == SF_ENDIAN_BIG)\n\t\t\t\t\t\t*doubleptr = double64_be_read ((unsigned char*) doubleptr) ;\n\t\t\t\t\telse\n\t\t\t\t\t\t*doubleptr = double64_le_read ((unsigned char*) doubleptr) ;\n\t\t\t\t\tbreak ;\n\n\t\t\tcase 's' :\n\t\t\t\t\tpsf_log_printf (psf, \"Format conversion 's' not implemented yet.\\n\") ;\n\t\t\t\t\t/*\n\t\t\t\t\tstrptr = va_arg (argptr, char *) ;\n\t\t\t\t\tsize = strlen (strptr) + 1 ;\n\t\t\t\t\tsize += (size & 1) ;\n\t\t\t\t\tlongdata = H2LE_32 (size) ;\n\t\t\t\t\tget_int (psf, longdata) ;\n\t\t\t\t\tmemcpy (&(psf->header [psf->headindex]), strptr, size) ;\n\t\t\t\t\tpsf->headindex += size ;\n\t\t\t\t\t*/\n\t\t\t\t\tbreak ;\n\n\t\t\tcase 'b' : /* Raw bytes */\n\t\t\t\t\tcharptr = va_arg (argptr, char*) ;\n\t\t\t\t\tcount = va_arg (argptr, size_t) ;\n\t\t\t\t\tif (count > 0)\n\t\t\t\t\t\tbyte_count += header_read (psf, charptr, count) ;\n\t\t\t\t\tbreak ;\n\n\t\t\tcase 'G' :\n\t\t\t\t\tcharptr = va_arg (argptr, char*) ;\n\t\t\t\t\tcount = va_arg (argptr, size_t) ;\n\t\t\t\t\tif (count > 0)\n\t\t\t\t\t\tbyte_count += header_gets (psf, charptr, count) ;\n\t\t\t\t\tbreak ;\n\n\t\t\tcase 'z' :\n\t\t\t\t\tpsf_log_printf (psf, \"Format conversion 'z' not implemented yet.\\n\") ;\n\t\t\t\t\t/*\n\t\t\t\t\tsize = va_arg (argptr, size_t) ;\n\t\t\t\t\twhile (size)\n\t\t\t\t\t{\tpsf->header [psf->headindex] = 0 ;\n\t\t\t\t\t\tpsf->headindex ++ ;\n\t\t\t\t\t\tsize -- ;\n\t\t\t\t\t\t} ;\n\t\t\t\t\t*/\n\t\t\t\t\tbreak ;\n\n\t\t\tcase 'p' :\n\t\t\t\t\t/* Get the seek position first. */\n\t\t\t\t\tcount = va_arg (argptr, size_t) ;\n\t\t\t\t\theader_seek (psf, count, SEEK_SET) ;\n\t\t\t\t\tbyte_count = count ;\n\t\t\t\t\tbreak ;\n\n\t\t\tcase 'j' :\n\t\t\t\t\t/* Get the seek position first. */\n\t\t\t\t\tcount = va_arg (argptr, size_t) ;\n\t\t\t\t\tif (count)\n\t\t\t\t\t{\theader_seek (psf, count, SEEK_CUR) ;\n\t\t\t\t\t\tbyte_count += count ;\n\t\t\t\t\t\t} ;\n\t\t\t\t\tbreak ;\n\n\t\t\tdefault :\n\t\t\t\tpsf_log_printf (psf, \"*** Invalid format specifier `%c'\\n\", c) ;\n\t\t\t\tpsf->error = SFE_INTERNAL ;\n\t\t\t\tbreak ;\n\t\t\t} ;\n\t\t} ;\n\n\tva_end (argptr) ;\n\n\treturn byte_count ;\n} /* psf_binheader_readf */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'src/ : Move to a variable length header buffer\n\nPreviously, the `psf->header` buffer was a fixed length specified by\n`SF_HEADER_LEN` which was set to `12292`. This was problematic for\ntwo reasons; this value was un-necessarily large for the majority\nof files and too small for some others.\n\nNow the size of the header buffer starts at 256 bytes and grows as\nnecessary up to a maximum of 100k.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: header_put_marker (SF_PRIVATE *psf, int x)\n{\tif (psf->headindex < SIGNED_SIZEOF (psf->header) - 4)\n\t{\tpsf->header [psf->headindex++] = (x >> 24) ;\n\t\tpsf->header [psf->headindex++] = (x >> 16) ;\n\t\tpsf->header [psf->headindex++] = (x >> 8) ;\n\t\tpsf->header [psf->headindex++] = x ;\n\t\t} ;\n} /* header_put_marker */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'src/ : Move to a variable length header buffer\n\nPreviously, the `psf->header` buffer was a fixed length specified by\n`SF_HEADER_LEN` which was set to `12292`. This was problematic for\ntwo reasons; this value was un-necessarily large for the majority\nof files and too small for some others.\n\nNow the size of the header buffer starts at 256 bytes and grows as\nnecessary up to a maximum of 100k.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: header_put_be_int (SF_PRIVATE *psf, int x)\n{\tif (psf->headindex < SIGNED_SIZEOF (psf->header) - 4)\n\t{\tpsf->header [psf->headindex++] = (x >> 24) ;\n\t\tpsf->header [psf->headindex++] = (x >> 16) ;\n\t\tpsf->header [psf->headindex++] = (x >> 8) ;\n\t\tpsf->header [psf->headindex++] = x ;\n\t\t} ;\n} /* header_put_be_int */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'src/ : Move to a variable length header buffer\n\nPreviously, the `psf->header` buffer was a fixed length specified by\n`SF_HEADER_LEN` which was set to `12292`. This was problematic for\ntwo reasons; this value was un-necessarily large for the majority\nof files and too small for some others.\n\nNow the size of the header buffer starts at 256 bytes and grows as\nnecessary up to a maximum of 100k.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void ahash_restore_req(struct ahash_request *req)\n{\n\tstruct ahash_request_priv *priv = req->priv;\n\n\t/* Restore the original crypto request. */\n\treq->result = priv->result;\n\treq->base.complete = priv->complete;\n\treq->base.data = priv->data;\n\treq->priv = NULL;\n\n\t/* Free the req->priv.priv from the ADJUSTED request. */\n\tkzfree(priv);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': 'crypto: ahash - Fix EINPROGRESS notification callback\n\nThe ahash API modifies the request's callback function in order\nto clean up after itself in some corner cases (unaligned final\nand missing finup).\n\nWhen the request is complete ahash will restore the original\ncallback and everything is fine. However, when the request gets\nan EBUSY on a full queue, an EINPROGRESS callback is made while\nthe request is still ongoing.\n\nIn this case the ahash API will incorrectly call its own callback.\n\nThis patch fixes the problem by creating a temporary request\nobject on the stack which is used to relay EINPROGRESS back to\nthe original completion function.\n\nThis patch also adds code to preserve the original flags value.\n\nFixes: ab6bf4e5e5e4 (\"crypto: hash - Fix the pointer voodoo in...\")\nCc: \nReported-by: Sabrina Dubroca \nTested-by: Sabrina Dubroca \nSigned-off-by: Herbert Xu '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline void ModulateHSB(const double percent_hue,\n const double percent_saturation,const double percent_brightness,double *red,\n double *green,double *blue)\n{\n double\n brightness,\n hue,\n saturation;\n\n /*\n Increase or decrease color brightness, saturation, or hue.\n */\n ConvertRGBToHSB(*red,*green,*blue,&hue,&saturation,&brightness);\n hue+=0.5*(0.01*percent_hue-1.0);\n while (hue < 0.0)\n hue+=1.0;\n while (hue > 1.0)\n hue-=1.0;\n saturation*=0.01*percent_saturation;\n brightness*=0.01*percent_brightness;\n ConvertHSBToRGB(hue,saturation,brightness,red,green,blue);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': 'https://www.imagemagick.org/discourse-server/viewtopic.php?f=3&t=31506'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n#define SkipLinesOp 0x01\n#define SetColorOp 0x02\n#define SkipPixelsOp 0x03\n#define ByteDataOp 0x05\n#define RunDataOp 0x06\n#define EOFOp 0x07\n\n char\n magick[12];\n\n Image\n *image;\n\n int\n opcode,\n operand,\n status;\n\n MagickStatusType\n flags;\n\n MagickSizeType\n number_pixels;\n\n MemoryInfo\n *pixel_info;\n\n Quantum\n index;\n\n register ssize_t\n x;\n\n register Quantum\n *q;\n\n register ssize_t\n i;\n\n register unsigned char\n *p;\n\n size_t\n bits_per_pixel,\n map_length,\n number_colormaps,\n number_planes,\n number_planes_filled,\n one,\n pixel_info_length;\n\n ssize_t\n count,\n offset,\n y;\n\n unsigned char\n background_color[256],\n *colormap,\n pixel,\n plane,\n *pixels;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n /*\n Determine if this a RLE file.\n */\n count=ReadBlob(image,2,(unsigned char *) magick);\n if ((count != 2) || (memcmp(magick,\"\\122\\314\",2) != 0))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n do\n {\n /*\n Read image header.\n */\n image->page.x=ReadBlobLSBShort(image);\n image->page.y=ReadBlobLSBShort(image);\n image->columns=ReadBlobLSBShort(image);\n image->rows=ReadBlobLSBShort(image);\n flags=(MagickStatusType) ReadBlobByte(image);\n image->alpha_trait=flags & 0x04 ? BlendPixelTrait : UndefinedPixelTrait;\n number_planes=(size_t) ReadBlobByte(image);\n bits_per_pixel=(size_t) ReadBlobByte(image);\n number_colormaps=(size_t) ReadBlobByte(image);\n map_length=(unsigned char) ReadBlobByte(image);\n if (map_length >= 22)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n one=1;\n map_length=one << map_length;\n if ((number_planes == 0) || (number_planes == 2) ||\n ((flags & 0x04) && (number_colormaps > 254)) || (bits_per_pixel != 8) ||\n (image->columns == 0))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (flags & 0x02)\n {\n /*\n No background color-- initialize to black.\n */\n for (i=0; i < (ssize_t) number_planes; i++)\n background_color[i]=0;\n (void) ReadBlobByte(image);\n }\n else\n {\n /*\n Initialize background color.\n */\n p=background_color;\n for (i=0; i < (ssize_t) number_planes; i++)\n *p++=(unsigned char) ReadBlobByte(image);\n }\n if ((number_planes & 0x01) == 0)\n (void) ReadBlobByte(image);\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n colormap=(unsigned char *) NULL;\n if (number_colormaps != 0)\n {\n /*\n Read image colormaps.\n */\n colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps,\n 3*map_length*sizeof(*colormap));\n if (colormap == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n p=colormap;\n for (i=0; i < (ssize_t) number_colormaps; i++)\n for (x=0; x < (ssize_t) map_length; x++)\n *p++=(unsigned char) ScaleShortToQuantum(ReadBlobLSBShort(image));\n }\n if ((flags & 0x08) != 0)\n {\n char\n *comment;\n\n size_t\n length;\n\n /*\n Read image comment.\n */\n length=ReadBlobLSBShort(image);\n if (length != 0)\n {\n comment=(char *) AcquireQuantumMemory(length,sizeof(*comment));\n if (comment == (char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n count=ReadBlob(image,length-1,(unsigned char *) comment);\n comment[length-1]='\\0';\n (void) SetImageProperty(image,\"comment\",comment,exception);\n comment=DestroyString(comment);\n if ((length & 0x01) == 0)\n (void) ReadBlobByte(image);\n }\n }\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n /*\n Allocate RLE pixels.\n */\n if (image->alpha_trait != UndefinedPixelTrait)\n number_planes++;\n number_pixels=(MagickSizeType) image->columns*image->rows;\n number_planes_filled=(number_planes % 2 == 0) ? number_planes :\n number_planes+1;\n if ((number_pixels*number_planes_filled) != (size_t) (number_pixels*\n number_planes_filled))\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixel_info=AcquireVirtualMemory(image->columns,image->rows*\n MagickMax(number_planes_filled,4)*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixel_info_length=image->columns*image->rows*\n MagickMax(number_planes_filled,4);\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n (void) ResetMagickMemory(pixels,0,pixel_info_length);\n if ((flags & 0x01) && !(flags & 0x02))\n {\n ssize_t\n j;\n\n /*\n Set background color.\n */\n p=pixels;\n for (i=0; i < (ssize_t) number_pixels; i++)\n {\n if (image->alpha_trait == UndefinedPixelTrait)\n for (j=0; j < (ssize_t) number_planes; j++)\n *p++=background_color[j];\n else\n {\n for (j=0; j < (ssize_t) (number_planes-1); j++)\n *p++=background_color[j];\n *p++=0; /* initialize matte channel */\n }\n }\n }\n /*\n Read runlength-encoded image.\n */\n plane=0;\n x=0;\n y=0;\n opcode=ReadBlobByte(image);\n do\n {\n switch (opcode & 0x3f)\n {\n case SkipLinesOp:\n {\n operand=ReadBlobByte(image);\n if (opcode & 0x40)\n operand=ReadBlobLSBSignedShort(image);\n x=0;\n y+=operand;\n break;\n }\n case SetColorOp:\n {\n operand=ReadBlobByte(image);\n plane=(unsigned char) operand;\n if (plane == 255)\n plane=(unsigned char) (number_planes-1);\n x=0;\n break;\n }\n case SkipPixelsOp:\n {\n operand=ReadBlobByte(image);\n if (opcode & 0x40)\n operand=ReadBlobLSBSignedShort(image);\n x+=operand;\n break;\n }\n case ByteDataOp:\n {\n operand=ReadBlobByte(image);\n if (opcode & 0x40)\n operand=ReadBlobLSBSignedShort(image);\n offset=((image->rows-y-1)*image->columns*number_planes)+x*\n number_planes+plane;\n operand++;\n if ((offset < 0) ||\n (offset+((size_t) operand*number_planes) > pixel_info_length))\n {\n if (number_colormaps != 0)\n colormap=(unsigned char *) RelinquishMagickMemory(colormap);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n }\n p=pixels+offset;\n for (i=0; i < (ssize_t) operand; i++)\n {\n pixel=(unsigned char) ReadBlobByte(image);\n if ((y < (ssize_t) image->rows) &&\n ((x+i) < (ssize_t) image->columns))\n *p=pixel;\n p+=number_planes;\n }\n if (operand & 0x01)\n (void) ReadBlobByte(image);\n x+=operand;\n break;\n }\n case RunDataOp:\n {\n operand=ReadBlobByte(image);\n if (opcode & 0x40)\n operand=ReadBlobLSBSignedShort(image);\n pixel=(unsigned char) ReadBlobByte(image);\n (void) ReadBlobByte(image);\n offset=((image->rows-y-1)*image->columns*number_planes)+x*\n number_planes+plane;\n operand++;\n if ((offset < 0) ||\n (offset+((size_t) operand*number_planes) > pixel_info_length))\n {\n if (number_colormaps != 0)\n colormap=(unsigned char *) RelinquishMagickMemory(colormap);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n }\n p=pixels+offset;\n for (i=0; i < (ssize_t) operand; i++)\n {\n if ((y < (ssize_t) image->rows) &&\n ((x+i) < (ssize_t) image->columns))\n *p=pixel;\n p+=number_planes;\n }\n x+=operand;\n break;\n }\n default:\n break;\n }\n opcode=ReadBlobByte(image);\n } while (((opcode & 0x3f) != EOFOp) && (opcode != EOF));\n if (number_colormaps != 0)\n {\n MagickStatusType\n mask;\n\n /*\n Apply colormap affineation to image.\n */\n mask=(MagickStatusType) (map_length-1);\n p=pixels;\n x=(ssize_t) number_planes;\n if (number_colormaps == 1)\n for (i=0; i < (ssize_t) number_pixels; i++)\n {\n ValidateColormapValue(image,*p & mask,&index,exception);\n *p=colormap[(ssize_t) index];\n p++;\n }\n else\n if ((number_planes >= 3) && (number_colormaps >= 3))\n for (i=0; i < (ssize_t) number_pixels; i++)\n for (x=0; x < (ssize_t) number_planes; x++)\n {\n ValidateColormapValue(image,(size_t) (x*map_length+\n (*p & mask)),&index,exception);\n *p=colormap[(ssize_t) index];\n p++;\n }\n if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes))\n {\n colormap=(unsigned char *) RelinquishMagickMemory(colormap);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n }\n }\n /*\n Initialize image structure.\n */\n if (number_planes >= 3)\n {\n /*\n Convert raster image to DirectClass pixel packets.\n */\n p=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelRed(image,ScaleCharToQuantum(*p++),q);\n SetPixelGreen(image,ScaleCharToQuantum(*p++),q);\n SetPixelBlue(image,ScaleCharToQuantum(*p++),q);\n if (image->alpha_trait != UndefinedPixelTrait)\n SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n }\n else\n {\n /*\n Create colormap.\n */\n if (number_colormaps == 0)\n map_length=256;\n if (AcquireImageColormap(image,map_length,exception) == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n p=colormap;\n if (number_colormaps == 1)\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n /*\n Pseudocolor.\n */\n image->colormap[i].red=(MagickRealType)\n ScaleCharToQuantum((unsigned char) i);\n image->colormap[i].green=(MagickRealType)\n ScaleCharToQuantum((unsigned char) i);\n image->colormap[i].blue=(MagickRealType)\n ScaleCharToQuantum((unsigned char) i);\n }\n else\n if (number_colormaps > 1)\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n image->colormap[i].red=(MagickRealType)\n ScaleCharToQuantum(*p);\n image->colormap[i].green=(MagickRealType)\n ScaleCharToQuantum(*(p+map_length));\n image->colormap[i].blue=(MagickRealType)\n ScaleCharToQuantum(*(p+map_length*2));\n p++;\n }\n p=pixels;\n if (image->alpha_trait == UndefinedPixelTrait)\n {\n /*\n Convert raster image to PseudoClass pixel packets.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelIndex(image,*p++,q);\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n (void) SyncImage(image,exception);\n }\n else\n {\n /*\n Image has a matte channel-- promote to DirectClass.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n ValidateColormapValue(image,(ssize_t) *p++,&index,exception);\n SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t)\n index].red),q);\n ValidateColormapValue(image,(ssize_t) *p++,&index,exception);\n SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t)\n index].green),q);\n ValidateColormapValue(image,(ssize_t) *p++,&index,exception);\n SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t)\n index].blue),q);\n SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);\n q+=GetPixelChannels(image);\n }\n if (x < (ssize_t) image->columns)\n break;\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n image->colormap=(PixelInfo *) RelinquishMagickMemory(\n image->colormap);\n image->storage_class=DirectClass;\n image->colors=0;\n }\n }\n if (number_colormaps != 0)\n colormap=(unsigned char *) RelinquishMagickMemory(colormap);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n /*\n Proceed to next image.\n */\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n (void) ReadBlobByte(image);\n count=ReadBlob(image,2,(unsigned char *) magick);\n if ((count != 0) && (memcmp(magick,\"\\122\\314\",2) == 0))\n {\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image,exception);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n GetBlobSize(image));\n if (status == MagickFalse)\n break;\n }\n } while ((count != 0) && (memcmp(magick,\"\\122\\314\",2) == 0));\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/415'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: glue(glue(cirrus_bitblt_rop_fwd_transp_, ROP_NAME),_16)(CirrusVGAState *s,\n\t\t\t\t\t\t\tuint8_t *dst,const uint8_t *src,\n\t\t\t\t\t\t\tint dstpitch,int srcpitch,\n\t\t\t\t\t\t\tint bltwidth,int bltheight)\n{\n int x,y;\n uint8_t p1, p2;\n dstpitch -= bltwidth;\n srcpitch -= bltwidth;\n for (y = 0; y < bltheight; y++) {\n for (x = 0; x < bltwidth; x+=2) {\n\t p1 = *dst;\n\t p2 = *(dst+1);\n ROP_OP(&p1, *src);\n ROP_OP(&p2, *(src + 1));\n\t if ((p1 != s->vga.gr[0x34]) || (p2 != s->vga.gr[0x35])) {\n\t\t*dst = p1;\n\t\t*(dst+1) = p2;\n\t }\n dst+=2;\n src+=2;\n }\n dst += dstpitch;\n src += srcpitch;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'fix :cirrus_vga fix OOB read case qemu Segmentation fault\n\ncheck the validity of parameters in cirrus_bitblt_rop_fwd_transp_xxx\nand cirrus_bitblt_rop_fwd_xxx to avoid the OOB read which causes qemu Segmentation fault.\n\nAfter the fix, we will touch the assert in\ncirrus_invalidate_region:\nassert(off_cur_end >= off_cur);\n\nSigned-off-by: fangying \nSigned-off-by: hangaohuai \nMessage-id: 20170314063919.16200-1-hangaohuai@huawei.com\nSigned-off-by: Gerd Hoffmann '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void cirrus_bitblt_cputovideo_next(CirrusVGAState * s)\n{\n int copy_count;\n uint8_t *end_ptr;\n\n if (s->cirrus_srccounter > 0) {\n if (s->cirrus_blt_mode & CIRRUS_BLTMODE_PATTERNCOPY) {\n cirrus_bitblt_common_patterncopy(s, false);\n the_end:\n s->cirrus_srccounter = 0;\n cirrus_bitblt_reset(s);\n } else {\n /* at least one scan line */\n do {\n (*s->cirrus_rop)(s, s->vga.vram_ptr + s->cirrus_blt_dstaddr,\n s->cirrus_bltbuf, 0, 0, s->cirrus_blt_width, 1);\n cirrus_invalidate_region(s, s->cirrus_blt_dstaddr, 0,\n s->cirrus_blt_width, 1);\n s->cirrus_blt_dstaddr += s->cirrus_blt_dstpitch;\n s->cirrus_srccounter -= s->cirrus_blt_srcpitch;\n if (s->cirrus_srccounter <= 0)\n goto the_end;\n /* more bytes than needed can be transferred because of\n word alignment, so we keep them for the next line */\n /* XXX: keep alignment to speed up transfer */\n end_ptr = s->cirrus_bltbuf + s->cirrus_blt_srcpitch;\n copy_count = s->cirrus_srcptr_end - end_ptr;\n memmove(s->cirrus_bltbuf, end_ptr, copy_count);\n s->cirrus_srcptr = s->cirrus_bltbuf + copy_count;\n s->cirrus_srcptr_end = s->cirrus_bltbuf + s->cirrus_blt_srcpitch;\n } while (s->cirrus_srcptr >= s->cirrus_srcptr_end);\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'cirrus: stop passing around dst pointers in the blitter\n\nInstead pass around the address (aka offset into vga memory). Calculate\nthe pointer in the rop_* functions, after applying the mask to the\naddress, to make sure the address stays within the valid range.\n\nSigned-off-by: Gerd Hoffmann \nMessage-id: 1489574872-8679-1-git-send-email-kraxel@redhat.com'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: (CirrusVGAState * s, uint8_t * dst,\n const uint8_t * src,\n int dstpitch, int srcpitch,\n int bltwidth, int bltheight)\n{\n uint8_t *d;\n int x, y, pattern_y, pattern_pitch, pattern_x;\n unsigned int col;\n const uint8_t *src1;\n#if DEPTH == 24\n int skipleft = s->vga.gr[0x2f] & 0x1f;\n#else\n int skipleft = (s->vga.gr[0x2f] & 0x07) * (DEPTH / 8);\n#endif\n\n#if DEPTH == 8\n pattern_pitch = 8;\n#elif DEPTH == 16\n pattern_pitch = 16;\n#else\n pattern_pitch = 32;\n#endif\n pattern_y = s->cirrus_blt_srcaddr & 7;\n for(y = 0; y < bltheight; y++) {\n pattern_x = skipleft;\n d = dst + skipleft;\n src1 = src + pattern_y * pattern_pitch;\n for (x = skipleft; x < bltwidth; x += (DEPTH / 8)) {\n#if DEPTH == 8\n col = src1[pattern_x];\n pattern_x = (pattern_x + 1) & 7;\n#elif DEPTH == 16\n col = ((uint16_t *)(src1 + pattern_x))[0];\n pattern_x = (pattern_x + 2) & 15;\n#elif DEPTH == 24\n {\n const uint8_t *src2 = src1 + pattern_x * 3;\n col = src2[0] | (src2[1] << 8) | (src2[2] << 16);\n pattern_x = (pattern_x + 1) & 7;\n }\n#else\n col = ((uint32_t *)(src1 + pattern_x))[0];\n pattern_x = (pattern_x + 4) & 31;\n#endif\n PUTPIXEL();\n d += (DEPTH / 8);\n }\n pattern_y = (pattern_y + 1) & 7;\n dst += dstpitch;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'cirrus: stop passing around dst pointers in the blitter\n\nInstead pass around the address (aka offset into vga memory). Calculate\nthe pointer in the rop_* functions, after applying the mask to the\naddress, to make sure the address stays within the valid range.\n\nSigned-off-by: Gerd Hoffmann \nMessage-id: 1489574872-8679-1-git-send-email-kraxel@redhat.com'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: glue(glue(cirrus_bitblt_rop_fwd_transp_, ROP_NAME),_16)(CirrusVGAState *s,\n uint32_t dstaddr,\n const uint8_t *src,\n int dstpitch,\n int srcpitch,\n int bltwidth,\n int bltheight)\n{\n int x,y;\n uint16_t transp = s->vga.gr[0x34] | (uint16_t)s->vga.gr[0x35] << 8;\n dstpitch -= bltwidth;\n srcpitch -= bltwidth;\n\n if (bltheight > 1 && (dstpitch < 0 || srcpitch < 0)) {\n return;\n }\n\n for (y = 0; y < bltheight; y++) {\n for (x = 0; x < bltwidth; x+=2) {\n ROP_OP_TR_16(s, dstaddr, *(uint16_t *)src, transp);\n dstaddr += 2;\n src += 2;\n }\n dstaddr += dstpitch;\n src += srcpitch;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'cirrus: stop passing around src pointers in the blitter\n\nDoes basically the same as \"cirrus: stop passing around dst pointers in\nthe blitter\", just for the src pointer instead of the dst pointer.\n\nFor the src we have to care about cputovideo blits though and fetch the\ndata from s->cirrus_bltbuf instead of vga memory. The cirrus_src*()\nhelper functions handle that.\n\nSigned-off-by: Gerd Hoffmann \nMessage-id: 1489584487-3489-1-git-send-email-kraxel@redhat.com'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: (CirrusVGAState *s, uint32_t dstaddr,\n const uint8_t *src,\n int dstpitch, int srcpitch,\n int bltwidth, int bltheight)\n{\n uint32_t addr;\n int x, y, pattern_y, pattern_pitch, pattern_x;\n unsigned int col;\n const uint8_t *src1;\n#if DEPTH == 24\n int skipleft = s->vga.gr[0x2f] & 0x1f;\n#else\n int skipleft = (s->vga.gr[0x2f] & 0x07) * (DEPTH / 8);\n#endif\n\n#if DEPTH == 8\n pattern_pitch = 8;\n#elif DEPTH == 16\n pattern_pitch = 16;\n#else\n pattern_pitch = 32;\n#endif\n pattern_y = s->cirrus_blt_srcaddr & 7;\n for(y = 0; y < bltheight; y++) {\n pattern_x = skipleft;\n addr = dstaddr + skipleft;\n src1 = src + pattern_y * pattern_pitch;\n for (x = skipleft; x < bltwidth; x += (DEPTH / 8)) {\n#if DEPTH == 8\n col = src1[pattern_x];\n pattern_x = (pattern_x + 1) & 7;\n#elif DEPTH == 16\n col = ((uint16_t *)(src1 + pattern_x))[0];\n pattern_x = (pattern_x + 2) & 15;\n#elif DEPTH == 24\n {\n const uint8_t *src2 = src1 + pattern_x * 3;\n col = src2[0] | (src2[1] << 8) | (src2[2] << 16);\n pattern_x = (pattern_x + 1) & 7;\n }\n#else\n col = ((uint32_t *)(src1 + pattern_x))[0];\n pattern_x = (pattern_x + 4) & 31;\n#endif\n PUTPIXEL(s, addr, col);\n addr += (DEPTH / 8);\n }\n pattern_y = (pattern_y + 1) & 7;\n dstaddr += dstpitch;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'cirrus: stop passing around src pointers in the blitter\n\nDoes basically the same as \"cirrus: stop passing around dst pointers in\nthe blitter\", just for the src pointer instead of the dst pointer.\n\nFor the src we have to care about cputovideo blits though and fetch the\ndata from s->cirrus_bltbuf instead of vga memory. The cirrus_src*()\nhelper functions handle that.\n\nSigned-off-by: Gerd Hoffmann \nMessage-id: 1489584487-3489-1-git-send-email-kraxel@redhat.com'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static struct sk_buff *macsec_decrypt(struct sk_buff *skb,\n\t\t\t\t struct net_device *dev,\n\t\t\t\t struct macsec_rx_sa *rx_sa,\n\t\t\t\t sci_t sci,\n\t\t\t\t struct macsec_secy *secy)\n{\n\tint ret;\n\tstruct scatterlist *sg;\n\tunsigned char *iv;\n\tstruct aead_request *req;\n\tstruct macsec_eth_header *hdr;\n\tu16 icv_len = secy->icv_len;\n\n\tmacsec_skb_cb(skb)->valid = false;\n\tskb = skb_share_check(skb, GFP_ATOMIC);\n\tif (!skb)\n\t\treturn ERR_PTR(-ENOMEM);\n\n\treq = macsec_alloc_req(rx_sa->key.tfm, &iv, &sg);\n\tif (!req) {\n\t\tkfree_skb(skb);\n\t\treturn ERR_PTR(-ENOMEM);\n\t}\n\n\thdr = (struct macsec_eth_header *)skb->data;\n\tmacsec_fill_iv(iv, sci, ntohl(hdr->packet_number));\n\n\tsg_init_table(sg, MAX_SKB_FRAGS + 1);\n\tskb_to_sgvec(skb, sg, 0, skb->len);\n\n\tif (hdr->tci_an & MACSEC_TCI_E) {\n\t\t/* confidentiality: ethernet + macsec header\n\t\t * authenticated, encrypted payload\n\t\t */\n\t\tint len = skb->len - macsec_hdr_len(macsec_skb_cb(skb)->has_sci);\n\n\t\taead_request_set_crypt(req, sg, sg, len, iv);\n\t\taead_request_set_ad(req, macsec_hdr_len(macsec_skb_cb(skb)->has_sci));\n\t\tskb = skb_unshare(skb, GFP_ATOMIC);\n\t\tif (!skb) {\n\t\t\taead_request_free(req);\n\t\t\treturn ERR_PTR(-ENOMEM);\n\t\t}\n\t} else {\n\t\t/* integrity only: all headers + data authenticated */\n\t\taead_request_set_crypt(req, sg, sg, icv_len, iv);\n\t\taead_request_set_ad(req, skb->len - icv_len);\n\t}\n\n\tmacsec_skb_cb(skb)->req = req;\n\tskb->dev = dev;\n\taead_request_set_callback(req, 0, macsec_decrypt_done, skb);\n\n\tdev_hold(dev);\n\tret = crypto_aead_decrypt(req);\n\tif (ret == -EINPROGRESS) {\n\t\treturn ERR_PTR(ret);\n\t} else if (ret != 0) {\n\t\t/* decryption/authentication failed\n\t\t * 10.6 if validateFrames is disabled, deliver anyway\n\t\t */\n\t\tif (ret != -EBADMSG) {\n\t\t\tkfree_skb(skb);\n\t\t\tskb = ERR_PTR(ret);\n\t\t}\n\t} else {\n\t\tmacsec_skb_cb(skb)->valid = true;\n\t}\n\tdev_put(dev);\n\n\taead_request_free(req);\n\n\treturn skb;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'macsec: dynamically allocate space for sglist\n\nWe call skb_cow_data, which is good anyway to ensure we can actually\nmodify the skb as such (another error from prior). Now that we have the\nnumber of fragments required, we can safely allocate exactly that amount\nof memory.\n\nFixes: c09440f7dcb3 (\"macsec: introduce IEEE 802.1AE driver\")\nSigned-off-by: Jason A. Donenfeld \nAcked-by: Sabrina Dubroca \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int cp2112_gpio_get_all(struct gpio_chip *chip)\n{\n\tstruct cp2112_device *dev = gpiochip_get_data(chip);\n\tstruct hid_device *hdev = dev->hdev;\n\tu8 *buf = dev->in_out_buffer;\n\tunsigned long flags;\n\tint ret;\n\n\tspin_lock_irqsave(&dev->lock, flags);\n\n\tret = hid_hw_raw_request(hdev, CP2112_GPIO_GET, buf,\n\t\t\t\t CP2112_GPIO_GET_LENGTH, HID_FEATURE_REPORT,\n\t\t\t\t HID_REQ_GET_REPORT);\n\tif (ret != CP2112_GPIO_GET_LENGTH) {\n\t\thid_err(hdev, \"error requesting GPIO values: %d\\n\", ret);\n\t\tret = ret < 0 ? ret : -EIO;\n\t\tgoto exit;\n\t}\n\n\tret = buf[1];\n\nexit:\n\tspin_unlock_irqrestore(&dev->lock, flags);\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-404', 'CWE-703'], 'message': 'HID: cp2112: fix sleep-while-atomic\n\nA recent commit fixing DMA-buffers on stack added a shared transfer\nbuffer protected by a spinlock. This is broken as the USB HID request\ncallbacks can sleep. Fix this up by replacing the spinlock with a mutex.\n\nFixes: 1ffb3c40ffb5 (\"HID: cp2112: make transfer buffers DMA capable\")\nCc: stable \t# 4.9\nSigned-off-by: Johan Hovold \nReviewed-by: Benjamin Tissoires \nSigned-off-by: Jiri Kosina '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void dvb_usbv2_disconnect(struct usb_interface *intf)\n{\n\tstruct dvb_usb_device *d = usb_get_intfdata(intf);\n\tconst char *name = d->name;\n\tstruct device dev = d->udev->dev;\n\n\tdev_dbg(&d->udev->dev, \"%s: bInterfaceNumber=%d\\n\", __func__,\n\t\t\tintf->cur_altsetting->desc.bInterfaceNumber);\n\n\tif (d->props->exit)\n\t\td->props->exit(d);\n\n\tdvb_usbv2_exit(d);\n\n\tdev_info(&dev, \"%s: '%s' successfully deinitialized and disconnected\\n\",\n\t\t\tKBUILD_MODNAME, name);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': '[media] dvb-usb-v2: avoid use-after-free\n\nI ran into a stack frame size warning because of the on-stack copy of\nthe USB device structure:\n\ndrivers/media/usb/dvb-usb-v2/dvb_usb_core.c: In function 'dvb_usbv2_disconnect':\ndrivers/media/usb/dvb-usb-v2/dvb_usb_core.c:1029:1: error: the frame size of 1104 bytes is larger than 1024 bytes [-Werror=frame-larger-than=]\n\nCopying a device structure like this is wrong for a number of other reasons\ntoo aside from the possible stack overflow. One of them is that the\ndev_info() call will print the name of the device later, but AFAICT\nwe have only copied a pointer to the name earlier and the actual name\nhas been freed by the time it gets printed.\n\nThis removes the on-stack copy of the device and instead copies the\ndevice name using kstrdup(). I'm ignoring the possible failure here\nas both printk() and kfree() are able to deal with NULL pointers.\n\nSigned-off-by: Arnd Bergmann \nSigned-off-by: Mauro Carvalho Chehab '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int rxrpc_krb5_decode_ticket(u8 **_ticket, u16 *_tktlen,\n\t\t\t\t const __be32 **_xdr, unsigned int *_toklen)\n{\n\tconst __be32 *xdr = *_xdr;\n\tunsigned int toklen = *_toklen, len;\n\n\t/* there must be at least one length word */\n\tif (toklen <= 4)\n\t\treturn -EINVAL;\n\n\t_enter(\",{%x},%u\", ntohl(xdr[0]), toklen);\n\n\tlen = ntohl(*xdr++);\n\ttoklen -= 4;\n\tif (len > AFSTOKEN_K5_TIX_MAX)\n\t\treturn -EINVAL;\n\t*_tktlen = len;\n\n\t_debug(\"ticket len %u\", len);\n\n\tif (len > 0) {\n\t\t*_ticket = kmemdup(xdr, len, GFP_KERNEL);\n\t\tif (!*_ticket)\n\t\t\treturn -ENOMEM;\n\t\tlen = (len + 3) & ~3;\n\t\ttoklen -= len;\n\t\txdr += len >> 2;\n\t}\n\n\t*_xdr = xdr;\n\t*_toklen = toklen;\n\t_leave(\" = 0 [toklen=%u]\", toklen);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'rxrpc: Fix several cases where a padded len isn't checked in ticket decode\n\nThis fixes CVE-2017-7482.\n\nWhen a kerberos 5 ticket is being decoded so that it can be loaded into an\nrxrpc-type key, there are several places in which the length of a\nvariable-length field is checked to make sure that it's not going to\noverrun the available data - but the data is padded to the nearest\nfour-byte boundary and the code doesn't check for this extra. This could\nlead to the size-remaining variable wrapping and the data pointer going\nover the end of the buffer.\n\nFix this by making the various variable-length data checks use the padded\nlength.\n\nReported-by: \u77f3\u78ca \nSigned-off-by: David Howells \nReviewed-by: Marc Dionne \nReviewed-by: Dan Carpenter \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool Smb4KMountJob::fillArgs(Smb4KShare *share, QMap& map)\n{\n // Find the mount program.\n QString mount;\n QStringList paths;\n paths << \"/bin\";\n paths << \"/sbin\";\n paths << \"/usr/bin\";\n paths << \"/usr/sbin\";\n paths << \"/usr/local/bin\";\n paths << \"/usr/local/sbin\";\n\n for (int i = 0; i < paths.size(); ++i)\n {\n mount = KGlobal::dirs()->findExe(\"mount.cifs\", paths.at(i));\n\n if (!mount.isEmpty())\n {\n map.insert(\"mh_command\", mount);\n break;\n }\n else\n {\n continue;\n }\n }\n\n if (mount.isEmpty())\n {\n Smb4KNotification::commandNotFound(\"mount.cifs\");\n return false;\n }\n else\n {\n // Do nothing\n }\n \n // Mount arguments.\n QMap global_options = globalSambaOptions();\n Smb4KCustomOptions *options = Smb4KCustomOptionsManager::self()->findOptions(share);\n\n // Set some settings for the share.\n share->setFileSystem(Smb4KShare::CIFS);\n \n if (options)\n {\n share->setPort(options->fileSystemPort() != Smb4KMountSettings::remoteFileSystemPort() ?\n options->fileSystemPort() : Smb4KMountSettings::remoteFileSystemPort());\n }\n else\n {\n share->setPort(Smb4KMountSettings::remoteFileSystemPort());\n }\n \n // Compile the list of arguments, that is added to the\n // mount command via \"-o ...\".\n QStringList args_list;\n \n // Workgroup or domain\n if (!share->workgroupName().trimmed().isEmpty())\n {\n args_list << QString(\"domain=%1\").arg(KShell::quoteArg(share->workgroupName()));\n }\n else\n {\n // Do nothing\n }\n \n // Host IP\n if (!share->hostIP().trimmed().isEmpty())\n {\n args_list << QString(\"ip=%1\").arg(share->hostIP());\n }\n else\n {\n // Do nothing\n }\n \n // User name\n if (!share->login().isEmpty())\n {\n args_list << QString(\"username=%1\").arg(share->login());\n }\n else\n {\n args_list << \"guest\";\n }\n \n // Client's and server's NetBIOS name\n // According to the manual page, this is only needed when port 139\n // is used. So, we only pass the NetBIOS name in that case.\n if (Smb4KMountSettings::remoteFileSystemPort() == 139 || (options && options->fileSystemPort() == 139))\n {\n // The client's NetBIOS name.\n if (!Smb4KSettings::netBIOSName().isEmpty())\n {\n args_list << QString(\"netbiosname=%1\").arg(KShell::quoteArg(Smb4KSettings::netBIOSName()));\n }\n else\n {\n if (!global_options[\"netbios name\"].isEmpty())\n {\n args_list << QString(\"netbiosname=%1\").arg(KShell::quoteArg(global_options[\"netbios name\"]));\n }\n else\n {\n // Do nothing\n }\n }\n\n // The server's NetBIOS name.\n // ('servern' is a synonym for 'servernetbiosname')\n args_list << QString(\"servern=%1\").arg(KShell::quoteArg( share->hostName()));\n }\n else\n {\n // Do nothing\n }\n \n // UID\n args_list << QString(\"uid=%1\").arg(options ? options->uid() : (K_UID)Smb4KMountSettings::userID().toInt());\n \n // Force user\n if (Smb4KMountSettings::forceUID())\n {\n args_list << \"forceuid\";\n }\n else\n {\n // Do nothing\n }\n \n // GID\n args_list << QString(\"gid=%1\").arg(options ? options->gid() : (K_GID)Smb4KMountSettings::groupID().toInt());\n \n // Force GID\n if (Smb4KMountSettings::forceGID())\n {\n args_list << \"forcegid\";\n }\n else\n {\n // Do nothing\n }\n \n // Client character set\n switch (Smb4KMountSettings::clientCharset())\n {\n case Smb4KMountSettings::EnumClientCharset::default_charset:\n {\n if (!global_options[\"unix charset\"].isEmpty())\n {\n args_list << QString(\"iocharset=%1\").arg(global_options[\"unix charset\"].toLower());\n }\n else\n {\n // Do nothing\n }\n break;\n }\n default:\n {\n args_list << QString(\"iocharset=%1\")\n .arg(Smb4KMountSettings::self()->clientCharsetItem()->choices().value(Smb4KMountSettings::clientCharset()).label);\n break;\n }\n }\n \n // Port. \n args_list << QString(\"port=%1\").arg(share->port());\n \n // Write access\n if (options)\n {\n switch (options->writeAccess())\n {\n case Smb4KCustomOptions::ReadWrite:\n {\n args_list << \"rw\";\n break;\n }\n case Smb4KCustomOptions::ReadOnly:\n {\n args_list << \"ro\";\n break;\n }\n default:\n {\n switch (Smb4KMountSettings::writeAccess())\n {\n case Smb4KMountSettings::EnumWriteAccess::ReadWrite:\n {\n args_list << \"rw\";\n break;\n }\n case Smb4KMountSettings::EnumWriteAccess::ReadOnly:\n {\n args_list << \"ro\";\n break;\n }\n default:\n {\n break;\n }\n }\n break;\n }\n }\n }\n else\n {\n switch (Smb4KMountSettings::writeAccess())\n {\n case Smb4KMountSettings::EnumWriteAccess::ReadWrite:\n {\n args_list << \"rw\";\n break;\n }\n case Smb4KMountSettings::EnumWriteAccess::ReadOnly:\n {\n args_list << \"ro\";\n break;\n }\n default:\n {\n break;\n }\n }\n }\n \n // File mask\n if (!Smb4KMountSettings::fileMask().isEmpty())\n {\n args_list << QString(\"file_mode=%1\").arg(Smb4KMountSettings::fileMask());\n }\n else\n {\n // Do nothing\n }\n\n // Directory mask\n if (!Smb4KMountSettings::directoryMask().isEmpty())\n {\n args_list << QString(\"dir_mode=%1\").arg(Smb4KMountSettings::directoryMask());\n }\n else\n {\n // Do nothing\n }\n \n // Permission checks\n if (Smb4KMountSettings::permissionChecks())\n {\n args_list << \"perm\";\n }\n else\n {\n args_list << \"noperm\";\n }\n \n // Client controls IDs\n if (Smb4KMountSettings::clientControlsIDs())\n {\n args_list << \"setuids\";\n }\n else\n {\n args_list << \"nosetuids\";\n }\n \n // Server inode numbers\n if (Smb4KMountSettings::serverInodeNumbers())\n {\n args_list << \"serverino\";\n }\n else\n {\n args_list << \"noserverino\";\n }\n \n // Cache mode\n switch (Smb4KMountSettings::cacheMode())\n {\n case Smb4KMountSettings::EnumCacheMode::None:\n {\n args_list << \"cache=none\";\n break;\n }\n case Smb4KMountSettings::EnumCacheMode::Strict:\n {\n args_list << \"cache=strict\";\n break;\n }\n case Smb4KMountSettings::EnumCacheMode::Loose:\n {\n args_list << \"cache=loose\";\n break;\n }\n default:\n {\n break;\n }\n }\n \n // Translate reserved characters\n if (Smb4KMountSettings::translateReservedChars())\n {\n args_list << \"mapchars\";\n }\n else\n {\n args_list << \"nomapchars\";\n }\n \n // Locking\n if (Smb4KMountSettings::noLocking())\n {\n args_list << \"nolock\";\n }\n else\n {\n // Do nothing\n }\n \n // Security mode\n if (options)\n {\n switch (options->securityMode())\n {\n case Smb4KCustomOptions::NoSecurityMode:\n {\n args_list << \"sec=none\";\n break;\n }\n case Smb4KCustomOptions::Krb5:\n {\n args_list << \"sec=krb5\";\n args_list << QString(\"cruid=%1\").arg(KUser(KUser::UseRealUserID).uid());\n break;\n }\n case Smb4KCustomOptions::Krb5i:\n {\n args_list << \"sec=krb5i\";\n args_list << QString(\"cruid=%1\").arg(KUser(KUser::UseRealUserID).uid());\n break;\n }\n case Smb4KCustomOptions::Ntlm:\n {\n args_list << \"sec=ntlm\";\n break;\n }\n case Smb4KCustomOptions::Ntlmi:\n {\n args_list << \"sec=ntlmi\";\n break;\n }\n case Smb4KCustomOptions::Ntlmv2:\n {\n args_list << \"sec=ntlmv2\";\n break;\n }\n case Smb4KCustomOptions::Ntlmv2i:\n {\n args_list << \"sec=ntlmv2i\";\n break;\n }\n case Smb4KCustomOptions::Ntlmssp:\n {\n args_list << \"sec=ntlmssp\";\n break;\n }\n case Smb4KCustomOptions::Ntlmsspi:\n {\n args_list << \"sec=ntlmsspi\";\n break;\n }\n default:\n {\n // Smb4KCustomOptions::DefaultSecurityMode\n break;\n }\n }\n }\n else\n {\n switch (Smb4KMountSettings::securityMode())\n {\n case Smb4KMountSettings::EnumSecurityMode::None:\n {\n args_list << \"sec=none\";\n break;\n }\n case Smb4KMountSettings::EnumSecurityMode::Krb5:\n {\n args_list << \"sec=krb5\";\n args_list << QString(\"cruid=%1\").arg(KUser(KUser::UseRealUserID).uid());\n break;\n }\n case Smb4KMountSettings::EnumSecurityMode::Krb5i:\n {\n args_list << \"sec=krb5i\";\n args_list << QString(\"cruid=%1\").arg(KUser(KUser::UseRealUserID).uid());\n break;\n }\n case Smb4KMountSettings::EnumSecurityMode::Ntlm:\n {\n args_list << \"sec=ntlm\";\n break;\n }\n case Smb4KMountSettings::EnumSecurityMode::Ntlmi:\n {\n args_list << \"sec=ntlmi\";\n break;\n }\n case Smb4KMountSettings::EnumSecurityMode::Ntlmv2:\n {\n args_list << \"sec=ntlmv2\";\n break;\n }\n case Smb4KMountSettings::EnumSecurityMode::Ntlmv2i:\n {\n args_list << \"sec=ntlmv2i\";\n break;\n }\n case Smb4KMountSettings::EnumSecurityMode::Ntlmssp:\n {\n args_list << \"sec=ntlmssp\";\n break;\n }\n case Smb4KMountSettings::EnumSecurityMode::Ntlmsspi:\n {\n args_list << \"sec=ntlmsspi\";\n break;\n }\n default:\n {\n // Smb4KSettings::EnumSecurityMode::Default,\n break;\n }\n }\n }\n \n // SMB protocol version\n switch (Smb4KMountSettings::smbProtocolVersion())\n {\n case Smb4KMountSettings::EnumSmbProtocolVersion::OnePointZero:\n {\n args_list << \"vers=1.0\";\n break;\n }\n case Smb4KMountSettings::EnumSmbProtocolVersion::TwoPointZero:\n {\n args_list << \"vers=2.0\";\n break;\n }\n case Smb4KMountSettings::EnumSmbProtocolVersion::TwoPointOne:\n {\n args_list << \"vers=2.1\";\n break;\n }\n case Smb4KMountSettings::EnumSmbProtocolVersion::ThreePointZero:\n {\n args_list << \"vers=3.0\";\n break;\n }\n default:\n {\n break;\n }\n }\n \n // Global custom options provided by the user\n if (!Smb4KMountSettings::customCIFSOptions().isEmpty())\n {\n // SECURITY: Only pass those arguments to mount.cifs that do not pose\n // a potential security risk and that have not already been defined.\n //\n // This is, among others, the proper fix to the security issue reported\n // by Heiner Markert (aka CVE-2014-2581).\n QStringList whitelist = whitelistedMountArguments();\n QStringList list = Smb4KMountSettings::customCIFSOptions().split(',', QString::SkipEmptyParts);\n QMutableStringListIterator it(list);\n \n while (it.hasNext())\n {\n QString arg = it.next().section(\"=\", 0, 0);\n \n if (!whitelist.contains(arg))\n {\n it.remove();\n }\n else\n {\n // Do nothing\n }\n \n args_list += list;\n }\n }\n else\n {\n // Do nothing\n }\n \n // Mount options\n QStringList mh_options;\n mh_options << \"-o\";\n mh_options << args_list.join(\",\");\n map.insert(\"mh_options\", mh_options);\n \n // Mount point\n map.insert(\"mh_mountpoint\", share->canonicalPath());\n \n // UNC\n map.insert(\"mh_unc\", !share->isHomesShare() ? share->unc() : share->homeUNC());;\n \n return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Find the mount/umount commands in the helper\n\nInstead of trusting what we get passed in\nCVE-2017-8849'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int CLASS parse_tiff_ifd(int base)\n{\n unsigned entries, tag, type, len, plen = 16, save;\n int ifd, use_cm = 0, cfa, i, j, c, ima_len = 0;\n char *cbuf, *cp;\n uchar cfa_pat[16], cfa_pc[] = {0, 1, 2, 3}, tab[256];\n double fm[3][4], cc[4][4], cm[4][3], cam_xyz[4][3], num;\n double ab[] = {1, 1, 1, 1}, asn[] = {0, 0, 0, 0}, xyz[] = {1, 1, 1};\n unsigned sony_curve[] = {0, 0, 0, 0, 0, 4095};\n unsigned *buf, sony_offset = 0, sony_length = 0, sony_key = 0;\n struct jhead jh;\n int pana_raw = 0;\n#ifndef LIBRAW_LIBRARY_BUILD\n FILE *sfp;\n#endif\n\n if (tiff_nifds >= sizeof tiff_ifd / sizeof tiff_ifd[0])\n return 1;\n ifd = tiff_nifds++;\n for (j = 0; j < 4; j++)\n for (i = 0; i < 4; i++)\n cc[j][i] = i == j;\n entries = get2();\n if (entries > 512)\n return 1;\n#ifdef LIBRAW_LIBRARY_BUILD\n INT64 fsize = ifp->size();\n#endif\n while (entries--)\n {\n tiff_get(base, &tag, &type, &len, &save);\n#ifdef LIBRAW_LIBRARY_BUILD\n INT64 savepos = ftell(ifp);\n if (len > 8 && len + savepos > fsize * 2)\n continue; // skip tag pointing out of 2xfile\n if (callbacks.exif_cb)\n {\n callbacks.exif_cb(callbacks.exifparser_data, tag | (pana_raw ? 0x30000 : 0), type, len, order, ifp);\n fseek(ifp, savepos, SEEK_SET);\n }\n#endif\n\n#ifdef LIBRAW_LIBRARY_BUILD\n if (!strncasecmp(make, \"SONY\", 4) ||\n (!strncasecmp(make, \"Hasselblad\", 10) &&\n (!strncasecmp(model, \"Stellar\", 7) || !strncasecmp(model, \"Lunar\", 5) || !strncasecmp(model, \"HV\", 2))))\n {\n switch (tag)\n {\n case 0x7300: // SR2 black level\n for (int i = 0; i < 4 && i < len; i++)\n cblack[i] = get2();\n break;\n case 0x7480:\n case 0x7820:\n FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get2();\n imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1];\n break;\n case 0x7481:\n case 0x7821:\n FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c] = get2();\n imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1];\n break;\n case 0x7482:\n case 0x7822:\n FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get2();\n imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1];\n break;\n case 0x7483:\n case 0x7823:\n FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c] = get2();\n imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1];\n break;\n case 0x7484:\n case 0x7824:\n imgdata.color.WBCT_Coeffs[0][0] = 4500;\n FORC3 imgdata.color.WBCT_Coeffs[0][c + 1] = get2();\n imgdata.color.WBCT_Coeffs[0][4] = imgdata.color.WBCT_Coeffs[0][2];\n break;\n case 0x7486:\n FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get2();\n imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1];\n break;\n case 0x7825:\n FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get2();\n imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1];\n break;\n case 0x7826:\n FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c] = get2();\n imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1];\n break;\n case 0x7827:\n FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c] = get2();\n imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1];\n break;\n case 0x7828:\n FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c] = get2();\n imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1];\n break;\n case 0x7829:\n FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c] = get2();\n imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1];\n break;\n case 0x782a:\n imgdata.color.WBCT_Coeffs[1][0] = 8500;\n FORC3 imgdata.color.WBCT_Coeffs[1][c + 1] = get2();\n imgdata.color.WBCT_Coeffs[1][4] = imgdata.color.WBCT_Coeffs[1][2];\n break;\n case 0x782b:\n imgdata.color.WBCT_Coeffs[2][0] = 6000;\n FORC3 imgdata.color.WBCT_Coeffs[2][c + 1] = get2();\n imgdata.color.WBCT_Coeffs[2][4] = imgdata.color.WBCT_Coeffs[2][2];\n break;\n case 0x782c:\n imgdata.color.WBCT_Coeffs[3][0] = 3200;\n FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][c] = imgdata.color.WBCT_Coeffs[3][c + 1] = get2();\n imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][3] = imgdata.color.WBCT_Coeffs[3][4] =\n imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][1];\n break;\n case 0x782d:\n imgdata.color.WBCT_Coeffs[4][0] = 2500;\n FORC3 imgdata.color.WBCT_Coeffs[4][c + 1] = get2();\n imgdata.color.WBCT_Coeffs[4][4] = imgdata.color.WBCT_Coeffs[4][2];\n break;\n case 0x787f:\n FORC3 imgdata.color.linear_max[c] = get2();\n imgdata.color.linear_max[3] = imgdata.color.linear_max[1];\n break;\n }\n }\n#endif\n\n switch (tag)\n {\n case 1:\n if (len == 4)\n pana_raw = get4();\n break;\n case 5:\n width = get2();\n break;\n case 6:\n height = get2();\n break;\n case 7:\n width += get2();\n break;\n case 9:\n if ((i = get2()))\n filters = i;\n#ifdef LIBRAW_LIBRARY_BUILD\n if (pana_raw && len == 1 && type == 3)\n pana_black[3] += i;\n#endif\n break;\n case 8:\n case 10:\n#ifdef LIBRAW_LIBRARY_BUILD\n if (pana_raw && len == 1 && type == 3)\n pana_black[3] += get2();\n#endif\n break;\n case 14:\n case 15:\n case 16:\n#ifdef LIBRAW_LIBRARY_BUILD\n if (pana_raw)\n {\n imgdata.color.linear_max[tag - 14] = get2();\n if (tag == 15)\n imgdata.color.linear_max[3] = imgdata.color.linear_max[1];\n }\n#endif\n break;\n case 17:\n case 18:\n if (type == 3 && len == 1)\n cam_mul[(tag - 17) * 2] = get2() / 256.0;\n break;\n#ifdef LIBRAW_LIBRARY_BUILD\n case 19:\n if (pana_raw)\n {\n ushort nWB, cnt, tWB;\n nWB = get2();\n if (nWB > 0x100)\n break;\n for (cnt = 0; cnt < nWB; cnt++)\n {\n tWB = get2();\n if (tWB < 0x100)\n {\n imgdata.color.WB_Coeffs[tWB][0] = get2();\n imgdata.color.WB_Coeffs[tWB][2] = get2();\n imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = 0x100;\n }\n else\n get4();\n }\n }\n break;\n#endif\n case 23:\n if (type == 3)\n iso_speed = get2();\n break;\n case 28:\n case 29:\n case 30:\n#ifdef LIBRAW_LIBRARY_BUILD\n if (pana_raw && len == 1 && type == 3)\n {\n pana_black[tag - 28] = get2();\n }\n else\n#endif\n {\n cblack[tag - 28] = get2();\n cblack[3] = cblack[1];\n }\n break;\n case 36:\n case 37:\n case 38:\n cam_mul[tag - 36] = get2();\n break;\n case 39:\n#ifdef LIBRAW_LIBRARY_BUILD\n if (pana_raw)\n {\n ushort nWB, cnt, tWB;\n nWB = get2();\n if (nWB > 0x100)\n break;\n for (cnt = 0; cnt < nWB; cnt++)\n {\n tWB = get2();\n if (tWB < 0x100)\n {\n imgdata.color.WB_Coeffs[tWB][0] = get2();\n imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = get2();\n imgdata.color.WB_Coeffs[tWB][2] = get2();\n }\n else\n fseek(ifp, 6, SEEK_CUR);\n }\n }\n break;\n#endif\n if (len < 50 || cam_mul[0])\n break;\n fseek(ifp, 12, SEEK_CUR);\n FORC3 cam_mul[c] = get2();\n break;\n case 46:\n if (type != 7 || fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8)\n break;\n thumb_offset = ftell(ifp) - 2;\n thumb_length = len;\n break;\n case 61440: /* Fuji HS10 table */\n fseek(ifp, get4() + base, SEEK_SET);\n parse_tiff_ifd(base);\n break;\n case 2:\n case 256:\n case 61441: /* ImageWidth */\n tiff_ifd[ifd].t_width = getint(type);\n break;\n case 3:\n case 257:\n case 61442: /* ImageHeight */\n tiff_ifd[ifd].t_height = getint(type);\n break;\n case 258: /* BitsPerSample */\n case 61443:\n tiff_ifd[ifd].samples = len & 7;\n tiff_ifd[ifd].bps = getint(type);\n if (tiff_bps < tiff_ifd[ifd].bps)\n tiff_bps = tiff_ifd[ifd].bps;\n break;\n case 61446:\n raw_height = 0;\n if (tiff_ifd[ifd].bps > 12)\n break;\n load_raw = &CLASS packed_load_raw;\n load_flags = get4() ? 24 : 80;\n break;\n case 259: /* Compression */\n tiff_ifd[ifd].comp = getint(type);\n break;\n case 262: /* PhotometricInterpretation */\n tiff_ifd[ifd].phint = get2();\n break;\n case 270: /* ImageDescription */\n fread(desc, 512, 1, ifp);\n break;\n case 271: /* Make */\n fgets(make, 64, ifp);\n break;\n case 272: /* Model */\n fgets(model, 64, ifp);\n break;\n#ifdef LIBRAW_LIBRARY_BUILD\n case 278:\n tiff_ifd[ifd].rows_per_strip = getint(type);\n break;\n#endif\n case 280: /* Panasonic RW2 offset */\n if (type != 4)\n break;\n load_raw = &CLASS panasonic_load_raw;\n load_flags = 0x2008;\n case 273: /* StripOffset */\n#ifdef LIBRAW_LIBRARY_BUILD\n if (len > 1 && len < 16384)\n {\n off_t sav = ftell(ifp);\n tiff_ifd[ifd].strip_offsets = (int *)calloc(len, sizeof(int));\n tiff_ifd[ifd].strip_offsets_count = len;\n for (int i = 0; i < len; i++)\n tiff_ifd[ifd].strip_offsets[i] = get4() + base;\n fseek(ifp, sav, SEEK_SET); // restore position\n }\n/* fallback */\n#endif\n case 513: /* JpegIFOffset */\n case 61447:\n tiff_ifd[ifd].offset = get4() + base;\n if (!tiff_ifd[ifd].bps && tiff_ifd[ifd].offset > 0)\n {\n fseek(ifp, tiff_ifd[ifd].offset, SEEK_SET);\n if (ljpeg_start(&jh, 1))\n {\n tiff_ifd[ifd].comp = 6;\n tiff_ifd[ifd].t_width = jh.wide;\n tiff_ifd[ifd].t_height = jh.high;\n tiff_ifd[ifd].bps = jh.bits;\n tiff_ifd[ifd].samples = jh.clrs;\n if (!(jh.sraw || (jh.clrs & 1)))\n tiff_ifd[ifd].t_width *= jh.clrs;\n if ((tiff_ifd[ifd].t_width > 4 * tiff_ifd[ifd].t_height) & ~jh.clrs)\n {\n tiff_ifd[ifd].t_width /= 2;\n tiff_ifd[ifd].t_height *= 2;\n }\n i = order;\n parse_tiff(tiff_ifd[ifd].offset + 12);\n order = i;\n }\n }\n break;\n case 274: /* Orientation */\n tiff_ifd[ifd].t_flip = \"50132467\"[get2() & 7] - '0';\n break;\n case 277: /* SamplesPerPixel */\n tiff_ifd[ifd].samples = getint(type) & 7;\n break;\n case 279: /* StripByteCounts */\n#ifdef LIBRAW_LIBRARY_BUILD\n if (len > 1 && len < 16384)\n {\n off_t sav = ftell(ifp);\n tiff_ifd[ifd].strip_byte_counts = (int *)calloc(len, sizeof(int));\n tiff_ifd[ifd].strip_byte_counts_count = len;\n for (int i = 0; i < len; i++)\n tiff_ifd[ifd].strip_byte_counts[i] = get4();\n fseek(ifp, sav, SEEK_SET); // restore position\n }\n/* fallback */\n#endif\n case 514:\n case 61448:\n tiff_ifd[ifd].bytes = get4();\n break;\n case 61454:\n FORC3 cam_mul[(4 - c) % 3] = getint(type);\n break;\n case 305:\n case 11: /* Software */\n fgets(software, 64, ifp);\n if (!strncmp(software, \"Adobe\", 5) || !strncmp(software, \"dcraw\", 5) || !strncmp(software, \"UFRaw\", 5) ||\n !strncmp(software, \"Bibble\", 6) || !strcmp(software, \"Digital Photo Professional\"))\n is_raw = 0;\n break;\n case 306: /* DateTime */\n get_timestamp(0);\n break;\n case 315: /* Artist */\n fread(artist, 64, 1, ifp);\n break;\n case 317:\n tiff_ifd[ifd].predictor = getint(type);\n break;\n case 322: /* TileWidth */\n tiff_ifd[ifd].t_tile_width = getint(type);\n break;\n case 323: /* TileLength */\n tiff_ifd[ifd].t_tile_length = getint(type);\n break;\n case 324: /* TileOffsets */\n tiff_ifd[ifd].offset = len > 1 ? ftell(ifp) : get4();\n if (len == 1)\n tiff_ifd[ifd].t_tile_width = tiff_ifd[ifd].t_tile_length = 0;\n if (len == 4)\n {\n load_raw = &CLASS sinar_4shot_load_raw;\n is_raw = 5;\n }\n break;\n case 325:\n tiff_ifd[ifd].bytes = len > 1 ? ftell(ifp) : get4();\n break;\n case 330: /* SubIFDs */\n if (!strcmp(model, \"DSLR-A100\") && tiff_ifd[ifd].t_width == 3872)\n {\n load_raw = &CLASS sony_arw_load_raw;\n data_offset = get4() + base;\n ifd++;\n break;\n }\n#ifdef LIBRAW_LIBRARY_BUILD\n if (!strncmp(make, \"Hasselblad\", 10) && libraw_internal_data.unpacker_data.hasselblad_parser_flag)\n {\n fseek(ifp, ftell(ifp) + 4, SEEK_SET);\n fseek(ifp, get4() + base, SEEK_SET);\n parse_tiff_ifd(base);\n break;\n }\n#endif\n if (len > 1000)\n len = 1000; /* 1000 SubIFDs is enough */\n while (len--)\n {\n i = ftell(ifp);\n fseek(ifp, get4() + base, SEEK_SET);\n if (parse_tiff_ifd(base))\n break;\n fseek(ifp, i + 4, SEEK_SET);\n }\n break;\n case 339:\n tiff_ifd[ifd].sample_format = getint(type);\n break;\n case 400:\n strcpy(make, \"Sarnoff\");\n maximum = 0xfff;\n break;\n#ifdef LIBRAW_LIBRARY_BUILD\n case 700:\n if ((type == 1 || type == 2 || type == 6 || type == 7) && len > 1 && len < 5100000)\n {\n xmpdata = (char *)malloc(xmplen = len + 1);\n fread(xmpdata, len, 1, ifp);\n xmpdata[len] = 0;\n }\n break;\n#endif\n case 28688:\n FORC4 sony_curve[c + 1] = get2() >> 2 & 0xfff;\n for (i = 0; i < 5; i++)\n for (j = sony_curve[i] + 1; j <= sony_curve[i + 1]; j++)\n curve[j] = curve[j - 1] + (1 << i);\n break;\n case 29184:\n sony_offset = get4();\n break;\n case 29185:\n sony_length = get4();\n break;\n case 29217:\n sony_key = get4();\n break;\n case 29264:\n parse_minolta(ftell(ifp));\n raw_width = 0;\n break;\n case 29443:\n FORC4 cam_mul[c ^ (c < 2)] = get2();\n break;\n case 29459:\n FORC4 cam_mul[c] = get2();\n i = (cam_mul[1] == 1024 && cam_mul[2] == 1024) << 1;\n SWAP(cam_mul[i], cam_mul[i + 1])\n break;\n#ifdef LIBRAW_LIBRARY_BUILD\n case 30720: // Sony matrix, Sony_SR2SubIFD_0x7800\n for (i = 0; i < 3; i++)\n {\n float num = 0.0;\n for (c = 0; c < 3; c++)\n {\n imgdata.color.ccm[i][c] = (float)((short)get2());\n num += imgdata.color.ccm[i][c];\n }\n if (num > 0.01)\n FORC3 imgdata.color.ccm[i][c] = imgdata.color.ccm[i][c] / num;\n }\n break;\n#endif\n case 29456: // Sony black level, Sony_SR2SubIFD_0x7310, no more needs to be divided by 4\n FORC4 cblack[c ^ c >> 1] = get2();\n i = cblack[3];\n FORC3 if (i > cblack[c]) i = cblack[c];\n FORC4 cblack[c] -= i;\n black = i;\n\n#ifdef DCRAW_VERBOSE\n if (verbose)\n fprintf(stderr, _(\"...Sony black: %u cblack: %u %u %u %u\\n\"), black, cblack[0], cblack[1], cblack[2],\n cblack[3]);\n#endif\n break;\n case 33405: /* Model2 */\n fgets(model2, 64, ifp);\n break;\n case 33421: /* CFARepeatPatternDim */\n if (get2() == 6 && get2() == 6)\n filters = 9;\n break;\n case 33422: /* CFAPattern */\n if (filters == 9)\n {\n FORC(36)((char *)xtrans)[c] = fgetc(ifp) & 3;\n break;\n }\n case 64777: /* Kodak P-series */\n if (len == 36)\n {\n filters = 9;\n colors = 3;\n FORC(36) xtrans[0][c] = fgetc(ifp) & 3;\n }\n else if (len > 0)\n {\n if ((plen = len) > 16)\n plen = 16;\n fread(cfa_pat, 1, plen, ifp);\n for (colors = cfa = i = 0; i < plen && colors < 4; i++)\n {\n colors += !(cfa & (1 << cfa_pat[i]));\n cfa |= 1 << cfa_pat[i];\n }\n if (cfa == 070)\n memcpy(cfa_pc, \"\\003\\004\\005\", 3); /* CMY */\n if (cfa == 072)\n memcpy(cfa_pc, \"\\005\\003\\004\\001\", 4); /* GMCY */\n goto guess_cfa_pc;\n }\n break;\n case 33424:\n case 65024:\n fseek(ifp, get4() + base, SEEK_SET);\n parse_kodak_ifd(base);\n break;\n case 33434: /* ExposureTime */\n tiff_ifd[ifd].t_shutter = shutter = getreal(type);\n break;\n case 33437: /* FNumber */\n aperture = getreal(type);\n break;\n#ifdef LIBRAW_LIBRARY_BUILD\n // IB start\n case 0xa405: // FocalLengthIn35mmFormat\n imgdata.lens.FocalLengthIn35mmFormat = get2();\n break;\n case 0xa431: // BodySerialNumber\n case 0xc62f:\n stmread(imgdata.shootinginfo.BodySerial, len, ifp);\n break;\n case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard\n imgdata.lens.MinFocal = getreal(type);\n imgdata.lens.MaxFocal = getreal(type);\n imgdata.lens.MaxAp4MinFocal = getreal(type);\n imgdata.lens.MaxAp4MaxFocal = getreal(type);\n break;\n case 0xa435: // LensSerialNumber\n stmread(imgdata.lens.LensSerial, len, ifp);\n break;\n case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard\n imgdata.lens.MinFocal = getreal(type);\n imgdata.lens.MaxFocal = getreal(type);\n imgdata.lens.MaxAp4MinFocal = getreal(type);\n imgdata.lens.MaxAp4MaxFocal = getreal(type);\n break;\n case 0xa433: // LensMake\n stmread(imgdata.lens.LensMake, len, ifp);\n break;\n case 0xa434: // LensModel\n stmread(imgdata.lens.Lens, len, ifp);\n if (!strncmp(imgdata.lens.Lens, \"----\", 4))\n imgdata.lens.Lens[0] = 0;\n break;\n case 0x9205:\n imgdata.lens.EXIF_MaxAp = powf64(2.0f, (getreal(type) / 2.0f));\n break;\n// IB end\n#endif\n case 34306: /* Leaf white balance */\n FORC4 cam_mul[c ^ 1] = 4096.0 / get2();\n break;\n case 34307: /* Leaf CatchLight color matrix */\n fread(software, 1, 7, ifp);\n if (strncmp(software, \"MATRIX\", 6))\n break;\n colors = 4;\n for (raw_color = i = 0; i < 3; i++)\n {\n FORC4 fscanf(ifp, \"%f\", &rgb_cam[i][c ^ 1]);\n if (!use_camera_wb)\n continue;\n num = 0;\n FORC4 num += rgb_cam[i][c];\n FORC4 rgb_cam[i][c] /= MAX(1, num);\n }\n break;\n case 34310: /* Leaf metadata */\n parse_mos(ftell(ifp));\n case 34303:\n strcpy(make, \"Leaf\");\n break;\n case 34665: /* EXIF tag */\n fseek(ifp, get4() + base, SEEK_SET);\n parse_exif(base);\n break;\n case 34853: /* GPSInfo tag */\n {\n unsigned pos;\n fseek(ifp, pos = (get4() + base), SEEK_SET);\n parse_gps(base);\n#ifdef LIBRAW_LIBRARY_BUILD\n fseek(ifp, pos, SEEK_SET);\n parse_gps_libraw(base);\n#endif\n }\n break;\n case 34675: /* InterColorProfile */\n case 50831: /* AsShotICCProfile */\n profile_offset = ftell(ifp);\n profile_length = len;\n break;\n case 37122: /* CompressedBitsPerPixel */\n kodak_cbpp = get4();\n break;\n case 37386: /* FocalLength */\n focal_len = getreal(type);\n break;\n case 37393: /* ImageNumber */\n shot_order = getint(type);\n break;\n case 37400: /* old Kodak KDC tag */\n for (raw_color = i = 0; i < 3; i++)\n {\n getreal(type);\n FORC3 rgb_cam[i][c] = getreal(type);\n }\n break;\n case 40976:\n strip_offset = get4();\n switch (tiff_ifd[ifd].comp)\n {\n case 32770:\n load_raw = &CLASS samsung_load_raw;\n break;\n case 32772:\n load_raw = &CLASS samsung2_load_raw;\n break;\n case 32773:\n load_raw = &CLASS samsung3_load_raw;\n break;\n }\n break;\n case 46275: /* Imacon tags */\n strcpy(make, \"Imacon\");\n data_offset = ftell(ifp);\n ima_len = len;\n break;\n case 46279:\n if (!ima_len)\n break;\n fseek(ifp, 38, SEEK_CUR);\n case 46274:\n fseek(ifp, 40, SEEK_CUR);\n raw_width = get4();\n raw_height = get4();\n left_margin = get4() & 7;\n width = raw_width - left_margin - (get4() & 7);\n top_margin = get4() & 7;\n height = raw_height - top_margin - (get4() & 7);\n if (raw_width == 7262 && ima_len == 234317952)\n {\n height = 5412;\n width = 7216;\n left_margin = 7;\n filters = 0;\n }\n else if (raw_width == 7262)\n {\n height = 5444;\n width = 7244;\n left_margin = 7;\n }\n fseek(ifp, 52, SEEK_CUR);\n FORC3 cam_mul[c] = getreal(11);\n fseek(ifp, 114, SEEK_CUR);\n flip = (get2() >> 7) * 90;\n if (width * height * 6 == ima_len)\n {\n if (flip % 180 == 90)\n SWAP(width, height);\n raw_width = width;\n raw_height = height;\n left_margin = top_margin = filters = flip = 0;\n }\n sprintf(model, \"Ixpress %d-Mp\", height * width / 1000000);\n load_raw = &CLASS imacon_full_load_raw;\n if (filters)\n {\n if (left_margin & 1)\n filters = 0x61616161;\n load_raw = &CLASS unpacked_load_raw;\n }\n maximum = 0xffff;\n break;\n case 50454: /* Sinar tag */\n case 50455:\n if (len > 2560000 || !(cbuf = (char *)malloc(len)))\n break;\n#ifndef LIBRAW_LIBRARY_BUILD\n fread(cbuf, 1, len, ifp);\n#else\n if (fread(cbuf, 1, len, ifp) != len)\n throw LIBRAW_EXCEPTION_IO_CORRUPT; // cbuf to be free'ed in recycle\n#endif\n cbuf[len - 1] = 0;\n for (cp = cbuf - 1; cp && cp < cbuf + len; cp = strchr(cp, '\\n'))\n if (!strncmp(++cp, \"Neutral \", 8))\n sscanf(cp + 8, \"%f %f %f\", cam_mul, cam_mul + 1, cam_mul + 2);\n free(cbuf);\n break;\n case 50458:\n if (!make[0])\n strcpy(make, \"Hasselblad\");\n break;\n case 50459: /* Hasselblad tag */\n#ifdef LIBRAW_LIBRARY_BUILD\n libraw_internal_data.unpacker_data.hasselblad_parser_flag = 1;\n#endif\n i = order;\n j = ftell(ifp);\n c = tiff_nifds;\n order = get2();\n fseek(ifp, j + (get2(), get4()), SEEK_SET);\n parse_tiff_ifd(j);\n maximum = 0xffff;\n tiff_nifds = c;\n order = i;\n break;\n case 50706: /* DNGVersion */\n FORC4 dng_version = (dng_version << 8) + fgetc(ifp);\n if (!make[0])\n strcpy(make, \"DNG\");\n is_raw = 1;\n break;\n case 50708: /* UniqueCameraModel */\n#ifdef LIBRAW_LIBRARY_BUILD\n stmread(imgdata.color.UniqueCameraModel, len, ifp);\n imgdata.color.UniqueCameraModel[sizeof(imgdata.color.UniqueCameraModel) - 1] = 0;\n#endif\n if (model[0])\n break;\n#ifndef LIBRAW_LIBRARY_BUILD\n fgets(make, 64, ifp);\n#else\n strncpy(make, imgdata.color.UniqueCameraModel, MIN(len, sizeof(imgdata.color.UniqueCameraModel)));\n#endif\n if ((cp = strchr(make, ' ')))\n {\n strcpy(model, cp + 1);\n *cp = 0;\n }\n break;\n case 50710: /* CFAPlaneColor */\n if (filters == 9)\n break;\n if (len > 4)\n len = 4;\n colors = len;\n fread(cfa_pc, 1, colors, ifp);\n guess_cfa_pc:\n FORCC tab[cfa_pc[c]] = c;\n cdesc[c] = 0;\n for (i = 16; i--;)\n filters = filters << 2 | tab[cfa_pat[i % plen]];\n filters -= !filters;\n break;\n case 50711: /* CFALayout */\n if (get2() == 2)\n fuji_width = 1;\n break;\n case 291:\n case 50712: /* LinearizationTable */\n#ifdef LIBRAW_LIBRARY_BUILD\n tiff_ifd[ifd].lineartable_offset = ftell(ifp);\n tiff_ifd[ifd].lineartable_len = len;\n#endif\n linear_table(len);\n break;\n case 50713: /* BlackLevelRepeatDim */\n#ifdef LIBRAW_LIBRARY_BUILD\n tiff_ifd[ifd].dng_levels.dng_cblack[4] =\n#endif\n cblack[4] = get2();\n#ifdef LIBRAW_LIBRARY_BUILD\n tiff_ifd[ifd].dng_levels.dng_cblack[5] =\n#endif\n cblack[5] = get2();\n if (cblack[4] * cblack[5] > (sizeof(cblack) / sizeof(cblack[0]) - 6))\n#ifdef LIBRAW_LIBRARY_BUILD\n tiff_ifd[ifd].dng_levels.dng_cblack[4] = tiff_ifd[ifd].dng_levels.dng_cblack[5] =\n#endif\n cblack[4] = cblack[5] = 1;\n break;\n\n#ifdef LIBRAW_LIBRARY_BUILD\n case 0xf00c:\n {\n unsigned fwb[4];\n FORC4 fwb[c] = get4();\n if (fwb[3] < 0x100)\n {\n imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1];\n imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0];\n imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2];\n if ((fwb[3] == 17) && libraw_internal_data.unpacker_data.lenRAFData > 3 &&\n libraw_internal_data.unpacker_data.lenRAFData < 10240000)\n {\n long long f_save = ftell(ifp);\n int fj, found = 0;\n ushort *rafdata = (ushort *)malloc(sizeof(ushort) * libraw_internal_data.unpacker_data.lenRAFData);\n fseek(ifp, libraw_internal_data.unpacker_data.posRAFData, SEEK_SET);\n fread(rafdata, sizeof(ushort), libraw_internal_data.unpacker_data.lenRAFData, ifp);\n fseek(ifp, f_save, SEEK_SET);\n for (int fi = 0; fi < (libraw_internal_data.unpacker_data.lenRAFData - 3); fi++)\n {\n if ((fwb[0] == rafdata[fi]) && (fwb[1] == rafdata[fi + 1]) && (fwb[2] == rafdata[fi + 2]))\n {\n if (rafdata[fi - 15] != fwb[0])\n continue;\n fi = fi - 15;\n imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][3] =\n rafdata[fi];\n imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][0] = rafdata[fi + 1];\n imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][2] = rafdata[fi + 2];\n\n imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] =\n rafdata[fi + 3];\n imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = rafdata[fi + 4];\n imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = rafdata[fi + 5];\n\n imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] =\n rafdata[fi + 6];\n imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = rafdata[fi + 7];\n imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = rafdata[fi + 8];\n\n imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] =\n rafdata[fi + 9];\n imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][0] = rafdata[fi + 10];\n imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][2] = rafdata[fi + 11];\n\n imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] =\n rafdata[fi + 12];\n imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = rafdata[fi + 13];\n imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = rafdata[fi + 14];\n\n imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] =\n rafdata[fi + 15];\n imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = rafdata[fi + 16];\n imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = rafdata[fi + 17];\n\n fi += 111;\n for (fj = fi; fj < (fi + 15); fj += 3)\n if (rafdata[fj] != rafdata[fi])\n {\n found = 1;\n break;\n }\n if (found)\n {\n int FujiCCT_K[31] = {2500, 2550, 2650, 2700, 2800, 2850, 2950, 3000, 3100, 3200, 3300,\n 3400, 3600, 3700, 3800, 4000, 4200, 4300, 4500, 4800, 5000, 5300,\n 5600, 5900, 6300, 6700, 7100, 7700, 8300, 9100, 10000};\n fj = fj - 93;\n for (int iCCT = 0; iCCT < 31; iCCT++)\n {\n imgdata.color.WBCT_Coeffs[iCCT][0] = FujiCCT_K[iCCT];\n imgdata.color.WBCT_Coeffs[iCCT][1] = rafdata[iCCT * 3 + 1 + fj];\n imgdata.color.WBCT_Coeffs[iCCT][2] = imgdata.color.WBCT_Coeffs[iCCT][4] = rafdata[iCCT * 3 + fj];\n imgdata.color.WBCT_Coeffs[iCCT][3] = rafdata[iCCT * 3 + 2 + fj];\n }\n }\n free(rafdata);\n break;\n }\n }\n }\n }\n FORC4 fwb[c] = get4();\n if (fwb[3] < 0x100)\n {\n imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1];\n imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0];\n imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2];\n }\n }\n break;\n#endif\n\n#ifdef LIBRAW_LIBRARY_BUILD\n case 50709:\n stmread(imgdata.color.LocalizedCameraModel, len, ifp);\n break;\n#endif\n\n case 61450:\n cblack[4] = cblack[5] = MIN(sqrt((double)len), 64);\n case 50714: /* BlackLevel */\n#ifdef LIBRAW_LIBRARY_BUILD\n if (tiff_ifd[ifd].samples > 1 && tiff_ifd[ifd].samples == len) // LinearDNG, per-channel black\n {\n for (i = 0; i < colors && i < 4 && i < len; i++)\n tiff_ifd[ifd].dng_levels.dng_cblack[i] = cblack[i] = getreal(type) + 0.5;\n\n tiff_ifd[ifd].dng_levels.dng_black = black = 0;\n }\n else\n#endif\n if ((cblack[4] * cblack[5] < 2) && len == 1)\n {\n#ifdef LIBRAW_LIBRARY_BUILD\n tiff_ifd[ifd].dng_levels.dng_black =\n#endif\n black = getreal(type);\n }\n else if (cblack[4] * cblack[5] <= len)\n {\n FORC(cblack[4] * cblack[5])\n cblack[6 + c] = getreal(type);\n black = 0;\n FORC4\n cblack[c] = 0;\n\n#ifdef LIBRAW_LIBRARY_BUILD\n if (tag == 50714)\n {\n FORC(cblack[4] * cblack[5])\n tiff_ifd[ifd].dng_levels.dng_cblack[6 + c] = cblack[6 + c];\n tiff_ifd[ifd].dng_levels.dng_black = 0;\n FORC4\n tiff_ifd[ifd].dng_levels.dng_cblack[c] = 0;\n }\n#endif\n }\n break;\n case 50715: /* BlackLevelDeltaH */\n case 50716: /* BlackLevelDeltaV */\n for (num = i = 0; i < len && i < 65536; i++)\n num += getreal(type);\n black += num / len + 0.5;\n#ifdef LIBRAW_LIBRARY_BUILD\n tiff_ifd[ifd].dng_levels.dng_black += num / len + 0.5;\n#endif\n break;\n case 50717: /* WhiteLevel */\n#ifdef LIBRAW_LIBRARY_BUILD\n tiff_ifd[ifd].dng_levels.dng_whitelevel[0] =\n#endif\n maximum = getint(type);\n#ifdef LIBRAW_LIBRARY_BUILD\n if (tiff_ifd[ifd].samples > 1) // Linear DNG case\n for (i = 1; i < colors && i < 4 && i < len; i++)\n tiff_ifd[ifd].dng_levels.dng_whitelevel[i] = getint(type);\n#endif\n break;\n case 50718: /* DefaultScale */\n pixel_aspect = getreal(type);\n pixel_aspect /= getreal(type);\n if (pixel_aspect > 0.995 && pixel_aspect < 1.005)\n pixel_aspect = 1.0;\n break;\n#ifdef LIBRAW_LIBRARY_BUILD\n case 50778:\n tiff_ifd[ifd].dng_color[0].illuminant = get2();\n break;\n case 50779:\n tiff_ifd[ifd].dng_color[1].illuminant = get2();\n break;\n#endif\n case 50721: /* ColorMatrix1 */\n case 50722: /* ColorMatrix2 */\n#ifdef LIBRAW_LIBRARY_BUILD\n i = tag == 50721 ? 0 : 1;\n#endif\n FORCC for (j = 0; j < 3; j++)\n {\n#ifdef LIBRAW_LIBRARY_BUILD\n tiff_ifd[ifd].dng_color[i].colormatrix[c][j] =\n#endif\n cm[c][j] = getreal(type);\n }\n use_cm = 1;\n break;\n\n case 0xc714: /* ForwardMatrix1 */\n case 0xc715: /* ForwardMatrix2 */\n#ifdef LIBRAW_LIBRARY_BUILD\n i = tag == 0xc714 ? 0 : 1;\n#endif\n for (j = 0; j < 3; j++)\n FORCC\n {\n#ifdef LIBRAW_LIBRARY_BUILD\n tiff_ifd[ifd].dng_color[i].forwardmatrix[j][c] =\n#endif\n fm[j][c] = getreal(type);\n }\n break;\n\n case 50723: /* CameraCalibration1 */\n case 50724: /* CameraCalibration2 */\n#ifdef LIBRAW_LIBRARY_BUILD\n j = tag == 50723 ? 0 : 1;\n#endif\n for (i = 0; i < colors; i++)\n FORCC\n {\n#ifdef LIBRAW_LIBRARY_BUILD\n tiff_ifd[ifd].dng_color[j].calibration[i][c] =\n#endif\n cc[i][c] = getreal(type);\n }\n break;\n case 50727: /* AnalogBalance */\n FORCC\n {\n#ifdef LIBRAW_LIBRARY_BUILD\n tiff_ifd[ifd].dng_levels.analogbalance[c] =\n#endif\n ab[c] = getreal(type);\n }\n break;\n case 50728: /* AsShotNeutral */\n FORCC asn[c] = getreal(type);\n break;\n case 50729: /* AsShotWhiteXY */\n xyz[0] = getreal(type);\n xyz[1] = getreal(type);\n xyz[2] = 1 - xyz[0] - xyz[1];\n FORC3 xyz[c] /= d65_white[c];\n break;\n#ifdef LIBRAW_LIBRARY_BUILD\n case 50730: /* DNG: Baseline Exposure */\n baseline_exposure = getreal(type);\n break;\n#endif\n // IB start\n case 50740: /* tag 0xc634 : DNG Adobe, DNG Pentax, Sony SR2, DNG Private */\n#ifdef LIBRAW_LIBRARY_BUILD\n {\n char mbuf[64];\n unsigned short makernote_found = 0;\n INT64 curr_pos, start_pos = ftell(ifp);\n unsigned MakN_order, m_sorder = order;\n unsigned MakN_length;\n unsigned pos_in_original_raw;\n fread(mbuf, 1, 6, ifp);\n\n if (!strcmp(mbuf, \"Adobe\"))\n {\n order = 0x4d4d; // Adobe header is always in \"MM\" / big endian\n curr_pos = start_pos + 6;\n while (curr_pos + 8 - start_pos <= len)\n {\n fread(mbuf, 1, 4, ifp);\n curr_pos += 8;\n if (!strncmp(mbuf, \"MakN\", 4))\n {\n makernote_found = 1;\n MakN_length = get4();\n MakN_order = get2();\n pos_in_original_raw = get4();\n order = MakN_order;\n parse_makernote_0xc634(curr_pos + 6 - pos_in_original_raw, 0, AdobeDNG);\n break;\n }\n }\n }\n else\n {\n fread(mbuf + 6, 1, 2, ifp);\n if (!strcmp(mbuf, \"PENTAX \") || !strcmp(mbuf, \"SAMSUNG\"))\n {\n makernote_found = 1;\n fseek(ifp, start_pos, SEEK_SET);\n parse_makernote_0xc634(base, 0, CameraDNG);\n }\n }\n\n fseek(ifp, start_pos, SEEK_SET);\n order = m_sorder;\n }\n// IB end\n#endif\n if (dng_version)\n break;\n parse_minolta(j = get4() + base);\n fseek(ifp, j, SEEK_SET);\n parse_tiff_ifd(base);\n break;\n case 50752:\n read_shorts(cr2_slice, 3);\n break;\n case 50829: /* ActiveArea */\n top_margin = getint(type);\n left_margin = getint(type);\n height = getint(type) - top_margin;\n width = getint(type) - left_margin;\n break;\n case 50830: /* MaskedAreas */\n for (i = 0; i < len && i < 32; i++)\n ((int *)mask)[i] = getint(type);\n black = 0;\n break;\n case 51009: /* OpcodeList2 */\n#ifdef LIBRAW_LIBRARY_BUILD\n tiff_ifd[ifd].opcode2_offset =\n#endif\n meta_offset = ftell(ifp);\n break;\n case 64772: /* Kodak P-series */\n if (len < 13)\n break;\n fseek(ifp, 16, SEEK_CUR);\n data_offset = get4();\n fseek(ifp, 28, SEEK_CUR);\n data_offset += get4();\n load_raw = &CLASS packed_load_raw;\n break;\n case 65026:\n if (type == 2)\n fgets(model2, 64, ifp);\n }\n fseek(ifp, save, SEEK_SET);\n }\n if (sony_length && sony_length < 10240000 && (buf = (unsigned *)malloc(sony_length)))\n {\n fseek(ifp, sony_offset, SEEK_SET);\n fread(buf, sony_length, 1, ifp);\n sony_decrypt(buf, sony_length / 4, 1, sony_key);\n#ifndef LIBRAW_LIBRARY_BUILD\n sfp = ifp;\n if ((ifp = tmpfile()))\n {\n fwrite(buf, sony_length, 1, ifp);\n fseek(ifp, 0, SEEK_SET);\n parse_tiff_ifd(-sony_offset);\n fclose(ifp);\n }\n ifp = sfp;\n#else\n if (!ifp->tempbuffer_open(buf, sony_length))\n {\n parse_tiff_ifd(-sony_offset);\n ifp->tempbuffer_close();\n }\n#endif\n free(buf);\n }\n for (i = 0; i < colors; i++)\n FORCC cc[i][c] *= ab[i];\n if (use_cm)\n {\n FORCC for (i = 0; i < 3; i++) for (cam_xyz[c][i] = j = 0; j < colors; j++) cam_xyz[c][i] +=\n cc[c][j] * cm[j][i] * xyz[i];\n cam_xyz_coeff(cmatrix, cam_xyz);\n }\n if (asn[0])\n {\n cam_mul[3] = 0;\n FORCC cam_mul[c] = 1 / asn[c];\n }\n if (!use_cm)\n FORCC pre_mul[c] /= cc[c][c];\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-119'], 'message': 'Secunia SA75000 advisory: several buffer overruns'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void virtio_gpu_set_scanout(VirtIOGPU *g,\n struct virtio_gpu_ctrl_command *cmd)\n{\n struct virtio_gpu_simple_resource *res;\n struct virtio_gpu_scanout *scanout;\n pixman_format_code_t format;\n uint32_t offset;\n int bpp;\n struct virtio_gpu_set_scanout ss;\n\n VIRTIO_GPU_FILL_CMD(ss);\n trace_virtio_gpu_cmd_set_scanout(ss.scanout_id, ss.resource_id,\n ss.r.width, ss.r.height, ss.r.x, ss.r.y);\n\n if (ss.scanout_id >= g->conf.max_outputs) {\n qemu_log_mask(LOG_GUEST_ERROR, \"%s: illegal scanout id specified %d\",\n __func__, ss.scanout_id);\n cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_SCANOUT_ID;\n return;\n }\n\n g->enable = 1;\n if (ss.resource_id == 0) {\n scanout = &g->scanout[ss.scanout_id];\n if (scanout->resource_id) {\n res = virtio_gpu_find_resource(g, scanout->resource_id);\n if (res) {\n res->scanout_bitmask &= ~(1 << ss.scanout_id);\n }\n }\n if (ss.scanout_id == 0) {\n qemu_log_mask(LOG_GUEST_ERROR,\n \"%s: illegal scanout id specified %d\",\n __func__, ss.scanout_id);\n cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_SCANOUT_ID;\n return;\n }\n dpy_gfx_replace_surface(g->scanout[ss.scanout_id].con, NULL);\n scanout->ds = NULL;\n scanout->width = 0;\n scanout->height = 0;\n return;\n }\n\n /* create a surface for this scanout */\n res = virtio_gpu_find_resource(g, ss.resource_id);\n if (!res) {\n qemu_log_mask(LOG_GUEST_ERROR, \"%s: illegal resource specified %d\\n\",\n __func__, ss.resource_id);\n cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_RESOURCE_ID;\n return;\n }\n\n if (ss.r.x > res->width ||\n ss.r.y > res->height ||\n ss.r.width > res->width ||\n ss.r.height > res->height ||\n ss.r.x + ss.r.width > res->width ||\n ss.r.y + ss.r.height > res->height) {\n qemu_log_mask(LOG_GUEST_ERROR, \"%s: illegal scanout %d bounds for\"\n \" resource %d, (%d,%d)+%d,%d vs %d %d\\n\",\n __func__, ss.scanout_id, ss.resource_id, ss.r.x, ss.r.y,\n ss.r.width, ss.r.height, res->width, res->height);\n cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_PARAMETER;\n return;\n }\n\n scanout = &g->scanout[ss.scanout_id];\n\n format = pixman_image_get_format(res->image);\n bpp = (PIXMAN_FORMAT_BPP(format) + 7) / 8;\n offset = (ss.r.x * bpp) + ss.r.y * pixman_image_get_stride(res->image);\n if (!scanout->ds || surface_data(scanout->ds)\n != ((uint8_t *)pixman_image_get_data(res->image) + offset) ||\n scanout->width != ss.r.width ||\n scanout->height != ss.r.height) {\n pixman_image_t *rect;\n void *ptr = (uint8_t *)pixman_image_get_data(res->image) + offset;\n rect = pixman_image_create_bits(format, ss.r.width, ss.r.height, ptr,\n pixman_image_get_stride(res->image));\n pixman_image_ref(res->image);\n pixman_image_set_destroy_function(rect, virtio_unref_resource,\n res->image);\n /* realloc the surface ptr */\n scanout->ds = qemu_create_displaysurface_pixman(rect);\n if (!scanout->ds) {\n cmd->error = VIRTIO_GPU_RESP_ERR_UNSPEC;\n return;\n }\n dpy_gfx_replace_surface(g->scanout[ss.scanout_id].con, scanout->ds);\n }\n\n res->scanout_bitmask |= (1 << ss.scanout_id);\n scanout->resource_id = ss.resource_id;\n scanout->x = ss.r.x;\n scanout->y = ss.r.y;\n scanout->width = ss.r.width;\n scanout->height = ss.r.height;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-772', 'CWE-401'], 'message': 'virtio-gpu: fix memory leak in set scanout\n\nIn virtio_gpu_set_scanout function, when creating the 'rect'\nits refcount is set to 2, by pixman_image_create_bits and\nqemu_create_displaysurface_pixman function. This can lead\na memory leak issues. This patch avoid this issue.\n\nSigned-off-by: Li Qiang \nReviewed-by: Marc-Andr\u00e9 Lureau \nMessage-id: 5884626f.5b2f6b0a.1bfff.3037@mx.google.com\nSigned-off-by: Gerd Hoffmann '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n#define SkipLinesOp 0x01\n#define SetColorOp 0x02\n#define SkipPixelsOp 0x03\n#define ByteDataOp 0x05\n#define RunDataOp 0x06\n#define EOFOp 0x07\n\n char\n magick[12];\n\n Image\n *image;\n\n int\n opcode,\n operand,\n status;\n\n MagickStatusType\n flags;\n\n MagickSizeType\n number_pixels;\n\n MemoryInfo\n *pixel_info;\n\n Quantum\n index;\n\n register ssize_t\n x;\n\n register Quantum\n *q;\n\n register ssize_t\n i;\n\n register unsigned char\n *p;\n\n size_t\n bits_per_pixel,\n map_length,\n number_colormaps,\n number_planes,\n number_planes_filled,\n one,\n pixel_info_length;\n\n ssize_t\n count,\n offset,\n y;\n\n unsigned char\n background_color[256],\n *colormap,\n pixel,\n plane,\n *pixels;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n /*\n Determine if this a RLE file.\n */\n count=ReadBlob(image,2,(unsigned char *) magick);\n if ((count != 2) || (memcmp(magick,\"\\122\\314\",2) != 0))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n do\n {\n /*\n Read image header.\n */\n image->page.x=ReadBlobLSBShort(image);\n image->page.y=ReadBlobLSBShort(image);\n image->columns=ReadBlobLSBShort(image);\n image->rows=ReadBlobLSBShort(image);\n flags=(MagickStatusType) ReadBlobByte(image);\n image->alpha_trait=flags & 0x04 ? BlendPixelTrait : UndefinedPixelTrait;\n number_planes=(size_t) ReadBlobByte(image);\n bits_per_pixel=(size_t) ReadBlobByte(image);\n number_colormaps=(size_t) ReadBlobByte(image);\n map_length=(unsigned char) ReadBlobByte(image);\n if (map_length >= 22)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n one=1;\n map_length=one << map_length;\n if ((number_planes == 0) || (number_planes == 2) ||\n ((flags & 0x04) && (number_colormaps > 254)) || (bits_per_pixel != 8) ||\n (image->columns == 0))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (flags & 0x02)\n {\n /*\n No background color-- initialize to black.\n */\n for (i=0; i < (ssize_t) number_planes; i++)\n background_color[i]=0;\n (void) ReadBlobByte(image);\n }\n else\n {\n /*\n Initialize background color.\n */\n p=background_color;\n for (i=0; i < (ssize_t) number_planes; i++)\n *p++=(unsigned char) ReadBlobByte(image);\n }\n if ((number_planes & 0x01) == 0)\n (void) ReadBlobByte(image);\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n colormap=(unsigned char *) NULL;\n if (number_colormaps != 0)\n {\n /*\n Read image colormaps.\n */\n colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps,\n 3*map_length*sizeof(*colormap));\n if (colormap == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n p=colormap;\n for (i=0; i < (ssize_t) number_colormaps; i++)\n for (x=0; x < (ssize_t) map_length; x++)\n *p++=(unsigned char) ScaleShortToQuantum(ReadBlobLSBShort(image));\n }\n if ((flags & 0x08) != 0)\n {\n char\n *comment;\n\n size_t\n length;\n\n /*\n Read image comment.\n */\n length=ReadBlobLSBShort(image);\n if (length != 0)\n {\n comment=(char *) AcquireQuantumMemory(length,sizeof(*comment));\n if (comment == (char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n count=ReadBlob(image,length-1,(unsigned char *) comment);\n comment[length-1]='\\0';\n (void) SetImageProperty(image,\"comment\",comment,exception);\n comment=DestroyString(comment);\n if ((length & 0x01) == 0)\n (void) ReadBlobByte(image);\n }\n }\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n /*\n Allocate RLE pixels.\n */\n if (image->alpha_trait != UndefinedPixelTrait)\n number_planes++;\n number_pixels=(MagickSizeType) image->columns*image->rows;\n number_planes_filled=(number_planes % 2 == 0) ? number_planes :\n number_planes+1;\n if ((number_pixels*number_planes_filled) != (size_t) (number_pixels*\n number_planes_filled))\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixel_info=AcquireVirtualMemory(image->columns,image->rows*\n MagickMax(number_planes_filled,4)*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixel_info_length=image->columns*image->rows*\n MagickMax(number_planes_filled,4);\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n if ((flags & 0x01) && !(flags & 0x02))\n {\n ssize_t\n j;\n\n /*\n Set background color.\n */\n p=pixels;\n for (i=0; i < (ssize_t) number_pixels; i++)\n {\n if (image->alpha_trait == UndefinedPixelTrait)\n for (j=0; j < (ssize_t) number_planes; j++)\n *p++=background_color[j];\n else\n {\n for (j=0; j < (ssize_t) (number_planes-1); j++)\n *p++=background_color[j];\n *p++=0; /* initialize matte channel */\n }\n }\n }\n /*\n Read runlength-encoded image.\n */\n plane=0;\n x=0;\n y=0;\n opcode=ReadBlobByte(image);\n do\n {\n switch (opcode & 0x3f)\n {\n case SkipLinesOp:\n {\n operand=ReadBlobByte(image);\n if (opcode & 0x40)\n operand=ReadBlobLSBSignedShort(image);\n x=0;\n y+=operand;\n break;\n }\n case SetColorOp:\n {\n operand=ReadBlobByte(image);\n plane=(unsigned char) operand;\n if (plane == 255)\n plane=(unsigned char) (number_planes-1);\n x=0;\n break;\n }\n case SkipPixelsOp:\n {\n operand=ReadBlobByte(image);\n if (opcode & 0x40)\n operand=ReadBlobLSBSignedShort(image);\n x+=operand;\n break;\n }\n case ByteDataOp:\n {\n operand=ReadBlobByte(image);\n if (opcode & 0x40)\n operand=ReadBlobLSBSignedShort(image);\n offset=((image->rows-y-1)*image->columns*number_planes)+x*\n number_planes+plane;\n operand++;\n if ((offset < 0) ||\n (offset+((size_t) operand*number_planes) > pixel_info_length))\n {\n if (number_colormaps != 0)\n colormap=(unsigned char *) RelinquishMagickMemory(colormap);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n }\n p=pixels+offset;\n for (i=0; i < (ssize_t) operand; i++)\n {\n pixel=(unsigned char) ReadBlobByte(image);\n if ((y < (ssize_t) image->rows) &&\n ((x+i) < (ssize_t) image->columns))\n *p=pixel;\n p+=number_planes;\n }\n if (operand & 0x01)\n (void) ReadBlobByte(image);\n x+=operand;\n break;\n }\n case RunDataOp:\n {\n operand=ReadBlobByte(image);\n if (opcode & 0x40)\n operand=ReadBlobLSBSignedShort(image);\n pixel=(unsigned char) ReadBlobByte(image);\n (void) ReadBlobByte(image);\n offset=((image->rows-y-1)*image->columns*number_planes)+x*\n number_planes+plane;\n operand++;\n if ((offset < 0) ||\n (offset+((size_t) operand*number_planes) > pixel_info_length))\n {\n if (number_colormaps != 0)\n colormap=(unsigned char *) RelinquishMagickMemory(colormap);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n }\n p=pixels+offset;\n for (i=0; i < (ssize_t) operand; i++)\n {\n if ((y < (ssize_t) image->rows) &&\n ((x+i) < (ssize_t) image->columns))\n *p=pixel;\n p+=number_planes;\n }\n x+=operand;\n break;\n }\n default:\n break;\n }\n opcode=ReadBlobByte(image);\n } while (((opcode & 0x3f) != EOFOp) && (opcode != EOF));\n if (number_colormaps != 0)\n {\n MagickStatusType\n mask;\n\n /*\n Apply colormap affineation to image.\n */\n mask=(MagickStatusType) (map_length-1);\n p=pixels;\n x=(ssize_t) number_planes;\n if (number_colormaps == 1)\n for (i=0; i < (ssize_t) number_pixels; i++)\n {\n ValidateColormapValue(image,*p & mask,&index,exception);\n *p=colormap[(ssize_t) index];\n p++;\n }\n else\n if ((number_planes >= 3) && (number_colormaps >= 3))\n for (i=0; i < (ssize_t) number_pixels; i++)\n for (x=0; x < (ssize_t) number_planes; x++)\n {\n ValidateColormapValue(image,(size_t) (x*map_length+\n (*p & mask)),&index,exception);\n *p=colormap[(ssize_t) index];\n p++;\n }\n if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes))\n {\n colormap=(unsigned char *) RelinquishMagickMemory(colormap);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n }\n }\n /*\n Initialize image structure.\n */\n if (number_planes >= 3)\n {\n /*\n Convert raster image to DirectClass pixel packets.\n */\n p=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelRed(image,ScaleCharToQuantum(*p++),q);\n SetPixelGreen(image,ScaleCharToQuantum(*p++),q);\n SetPixelBlue(image,ScaleCharToQuantum(*p++),q);\n if (image->alpha_trait != UndefinedPixelTrait)\n SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n }\n else\n {\n /*\n Create colormap.\n */\n if (number_colormaps == 0)\n map_length=256;\n if (AcquireImageColormap(image,map_length,exception) == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n p=colormap;\n if (number_colormaps == 1)\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n /*\n Pseudocolor.\n */\n image->colormap[i].red=(MagickRealType)\n ScaleCharToQuantum((unsigned char) i);\n image->colormap[i].green=(MagickRealType)\n ScaleCharToQuantum((unsigned char) i);\n image->colormap[i].blue=(MagickRealType)\n ScaleCharToQuantum((unsigned char) i);\n }\n else\n if (number_colormaps > 1)\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n image->colormap[i].red=(MagickRealType)\n ScaleCharToQuantum(*p);\n image->colormap[i].green=(MagickRealType)\n ScaleCharToQuantum(*(p+map_length));\n image->colormap[i].blue=(MagickRealType)\n ScaleCharToQuantum(*(p+map_length*2));\n p++;\n }\n p=pixels;\n if (image->alpha_trait == UndefinedPixelTrait)\n {\n /*\n Convert raster image to PseudoClass pixel packets.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelIndex(image,*p++,q);\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n (void) SyncImage(image,exception);\n }\n else\n {\n /*\n Image has a matte channel-- promote to DirectClass.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n ValidateColormapValue(image,(ssize_t) *p++,&index,exception);\n SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t)\n index].red),q);\n ValidateColormapValue(image,(ssize_t) *p++,&index,exception);\n SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t)\n index].green),q);\n ValidateColormapValue(image,(ssize_t) *p++,&index,exception);\n SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t)\n index].blue),q);\n SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);\n q+=GetPixelChannels(image);\n }\n if (x < (ssize_t) image->columns)\n break;\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n image->colormap=(PixelInfo *) RelinquishMagickMemory(\n image->colormap);\n image->storage_class=DirectClass;\n image->colors=0;\n }\n }\n if (number_colormaps != 0)\n colormap=(unsigned char *) RelinquishMagickMemory(colormap);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n /*\n Proceed to next image.\n */\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n (void) ReadBlobByte(image);\n count=ReadBlob(image,2,(unsigned char *) magick);\n if ((count != 0) && (memcmp(magick,\"\\122\\314\",2) == 0))\n {\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image,exception);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n GetBlobSize(image));\n if (status == MagickFalse)\n break;\n }\n } while ((count != 0) && (memcmp(magick,\"\\122\\314\",2) == 0));\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-908'], 'message': 'Reset memory for RLE decoder (patch provided by scarybeasts)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: asn1_find_node (asn1_node pointer, const char *name)\n{\n asn1_node p;\n char *n_end, n[ASN1_MAX_NAME_SIZE + 1];\n const char *n_start;\n unsigned int nsize;\n unsigned int nhash;\n\n if (pointer == NULL)\n return NULL;\n\n if (name == NULL)\n return NULL;\n\n p = pointer;\n n_start = name;\n\n if (name[0] == '?' && name[1] == 'C' && p->name[0] == '?')\n { /* ?CURRENT */\n n_start = strchr(n_start, '.');\n if (n_start)\n n_start++;\n }\n else if (p->name[0] != 0)\n {\t\t\t\t/* has *pointer got a name ? */\n n_end = strchr (n_start, '.');\t/* search the first dot */\n if (n_end)\n\t{\n\t nsize = n_end - n_start;\n\t memcpy (n, n_start, nsize);\n\t n[nsize] = 0;\n\t n_start = n_end;\n\t n_start++;\n\n\t nhash = hash_pjw_bare (n, nsize);\n\t}\n else\n\t{\n\t nsize = _asn1_str_cpy (n, sizeof (n), n_start);\n\t nhash = hash_pjw_bare (n, nsize);\n\n\t n_start = NULL;\n\t}\n\n while (p)\n\t{\n\t if (nhash == p->name_hash && (!strcmp (p->name, n)))\n\t break;\n\t else\n\t p = p->right;\n\t}\t\t\t/* while */\n\n if (p == NULL)\n\treturn NULL;\n }\n else\n {\t\t\t\t/* *pointer doesn't have a name */\n if (n_start[0] == 0)\n\treturn p;\n }\n\n while (n_start)\n {\t\t\t\t/* Has the end of NAME been reached? */\n n_end = strchr (n_start, '.');\t/* search the next dot */\n if (n_end)\n\t{\n\t nsize = n_end - n_start;\n\t memcpy (n, n_start, nsize);\n\t n[nsize] = 0;\n\t n_start = n_end;\n\t n_start++;\n\n\t nhash = hash_pjw_bare (n, nsize);\n\t}\n else\n\t{\n\t nsize = _asn1_str_cpy (n, sizeof (n), n_start);\n\t nhash = hash_pjw_bare (n, nsize);\n\t n_start = NULL;\n\t}\n\n if (p->down == NULL)\n\treturn NULL;\n\n p = p->down;\n if (p == NULL)\n return NULL;\n\n /* The identifier \"?LAST\" indicates the last element\n in the right chain. */\n if (n[0] == '?' && n[1] == 'L') /* ?LAST */\n\t{\n\t while (p->right)\n\t p = p->right;\n\t}\n else\n\t{\t\t\t/* no \"?LAST\" */\n\t while (p)\n\t {\n\t if (p->name_hash == nhash && !strcmp (p->name, n))\n\t\tbreak;\n\t else\n\t\tp = p->right;\n\t }\n\t}\n if (p == NULL)\n return NULL;\n }\t\t\t\t/* while */\n\n return p;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'asn1_find_node: added safety check on asn1_find_node()\n\nThis prevents a stack overflow in asn1_find_node() which\nis triggered by too long variable names in the definitions\nfiles. That means that applications have to deliberately\npass a too long 'name' constant to asn1_write_value()\nand friends. Reported by Jakub Jirasek.\n\nSigned-off-by: Nikos Mavrogiannopoulos '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool TestAutoSeededX917()\r\n{\r\n\t// This tests Auto-Seeding and GenerateIntoBufferedTransformation.\r\n\tstd::cout << \"\\nTesting AutoSeeded X917 generator...\\n\\n\";\r\n\r\n\tAutoSeededX917RNG prng;\r\n\tbool pass = true, fail;\r\n\tstatic const unsigned int ENTROPY_SIZE = 32;\r\n\r\n\tMeterFilter meter(new Redirector(TheBitBucket()));\r\n\tRandomNumberSource test(prng, 100000, true, new Deflator(new Redirector(meter)));\r\n\r\n\tfail = false;\r\n\tif (meter.GetTotalBytes() < 100000)\r\n\t\tfail = true;\r\n\r\n\tpass &= !fail;\r\n\tif (fail)\r\n\t\tstd::cout << \"FAILED:\";\r\n\telse\r\n\t\tstd::cout << \"passed:\";\r\n\tstd::cout << \" 100000 generated bytes compressed to \" << meter.GetTotalBytes() << \" bytes by DEFLATE\\n\";\r\n\r\n\ttry\r\n\t{\r\n\t\tfail = false;\r\n\t\tprng.DiscardBytes(100000);\r\n\t}\r\n\tcatch (const Exception&)\r\n\t{\r\n\t\tfail = true;\r\n\t}\r\n\r\n\tpass &= !fail;\r\n\tif (fail)\r\n\t\tstd::cout << \"FAILED:\";\r\n\telse\r\n\t\tstd::cout << \"passed:\";\r\n\tstd::cout << \" discarded 10000 bytes\" << std::endl;\r\n\r\n\ttry\r\n\t{\r\n\t\tfail = false;\r\n\t\tif(prng.CanIncorporateEntropy())\r\n\t\t{\r\n\t\t\tSecByteBlock entropy(ENTROPY_SIZE);\r\n\t\t\tGlobalRNG().GenerateBlock(entropy, entropy.SizeInBytes());\r\n\r\n\t\t\tprng.IncorporateEntropy(entropy, entropy.SizeInBytes());\r\n\t\t\tprng.IncorporateEntropy(entropy, entropy.SizeInBytes());\r\n\t\t\tprng.IncorporateEntropy(entropy, entropy.SizeInBytes());\r\n\t\t\tprng.IncorporateEntropy(entropy, entropy.SizeInBytes());\r\n\t\t}\r\n\t}\r\n\tcatch (const Exception& /*ex*/)\r\n\t{\r\n\t\tfail = true;\r\n\t}\r\n\r\n\tpass &= !fail;\r\n\tif (fail)\r\n\t\tstd::cout << \"FAILED:\";\r\n\telse\r\n\t\tstd::cout << \"passed:\";\r\n\tstd::cout << \" IncorporateEntropy with \" << 4*ENTROPY_SIZE << \" bytes\\n\";\r\n\r\n\ttry\r\n\t{\r\n\t\t// Miscellaneous for code coverage\r\n\t\tfail = false;\r\n\t\t(void)prng.AlgorithmName(); // \"unknown\"\r\n\t\tword32 result = prng.GenerateWord32();\r\n\t\tresult = prng.GenerateWord32((result & 0xff), 0xffffffff - (result & 0xff));\r\n\t\tprng.GenerateBlock(reinterpret_cast(&result), 4);\r\n\t\tprng.GenerateBlock(reinterpret_cast(&result), 3);\r\n\t\tprng.GenerateBlock(reinterpret_cast(&result), 2);\r\n\t\tprng.GenerateBlock(reinterpret_cast(&result), 1);\r\n\t}\r\n\tcatch (const Exception&)\r\n\t{\r\n\t\tfail = true;\r\n\t}\r\n\r\n\tpass &= !fail;\r\n\tif (fail)\r\n\t\tstd::cout << \"FAILED:\";\r\n\telse\r\n\t\tstd::cout << \"passed:\";\r\n\tstd::cout << \" GenerateWord32 and Crop\\n\";\t\r\n\r\n\tstd::cout.flush();\r\n\treturn pass;\r\n}\r ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190', 'CWE-125'], 'message': 'Add Inflator::BadDistanceErr exception (Issue 414)\nThe improved validation and excpetion clears the Address Sanitizer and Undefined Behavior Sanitizer findings'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline int stack_guard_page_start(struct vm_area_struct *vma,\n\t\t\t\t\t unsigned long addr)\n{\n\treturn (vma->vm_flags & VM_GROWSDOWN) &&\n\t\t(vma->vm_start == addr) &&\n\t\t!vma_growsdown(vma->vm_prev, addr);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'mm: larger stack guard gap, between vmas\n\nStack guard page is a useful feature to reduce a risk of stack smashing\ninto a different mapping. We have been using a single page gap which\nis sufficient to prevent having stack adjacent to a different mapping.\nBut this seems to be insufficient in the light of the stack usage in\nuserspace. E.g. glibc uses as large as 64kB alloca() in many commonly\nused functions. Others use constructs liks gid_t buffer[NGROUPS_MAX]\nwhich is 256kB or stack strings with MAX_ARG_STRLEN.\n\nThis will become especially dangerous for suid binaries and the default\nno limit for the stack size limit because those applications can be\ntricked to consume a large portion of the stack and a single glibc call\ncould jump over the guard page. These attacks are not theoretical,\nunfortunatelly.\n\nMake those attacks less probable by increasing the stack guard gap\nto 1MB (on systems with 4k pages; but make it depend on the page size\nbecause systems with larger base pages might cap stack allocations in\nthe PAGE_SIZE units) which should cover larger alloca() and VLA stack\nallocations. It is obviously not a full fix because the problem is\nsomehow inherent, but it should reduce attack space a lot.\n\nOne could argue that the gap size should be configurable from userspace,\nbut that can be done later when somebody finds that the new 1MB is wrong\nfor some special case applications. For now, add a kernel command line\noption (stack_guard_gap) to specify the stack gap size (in page units).\n\nImplementation wise, first delete all the old code for stack guard page:\nbecause although we could get away with accounting one extra page in a\nstack vma, accounting a larger gap can break userspace - case in point,\na program run with \"ulimit -S -v 20000\" failed when the 1MB gap was\ncounted for RLIMIT_AS; similar problems could come with RLIMIT_MLOCK\nand strict non-overcommit mode.\n\nInstead of keeping gap inside the stack vma, maintain the stack guard\ngap as a gap between vmas: using vm_start_gap() in place of vm_start\n(or vm_end_gap() in place of vm_end if VM_GROWSUP) in just those few\nplaces which need to respect the gap - mainly arch_get_unmapped_area(),\nand and the vma tree's subtree_gap support for that.\n\nOriginal-patch-by: Oleg Nesterov \nOriginal-patch-by: Michal Hocko \nSigned-off-by: Hugh Dickins \nAcked-by: Michal Hocko \nTested-by: Helge Deller # parisc\nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: hugetlb_get_unmapped_area(struct file *file, unsigned long addr,\n\t\tunsigned long len, unsigned long pgoff, unsigned long flags)\n{\n\tstruct hstate *h = hstate_file(file);\n\tstruct mm_struct *mm = current->mm;\n\tstruct vm_area_struct *vma;\n\tunsigned long task_size = TASK_SIZE;\n\n\tif (test_thread_flag(TIF_32BIT))\n\t\ttask_size = STACK_TOP32;\n\n\tif (len & ~huge_page_mask(h))\n\t\treturn -EINVAL;\n\tif (len > task_size)\n\t\treturn -ENOMEM;\n\n\tif (flags & MAP_FIXED) {\n\t\tif (prepare_hugepage_range(file, addr, len))\n\t\t\treturn -EINVAL;\n\t\treturn addr;\n\t}\n\n\tif (addr) {\n\t\taddr = ALIGN(addr, huge_page_size(h));\n\t\tvma = find_vma(mm, addr);\n\t\tif (task_size - len >= addr &&\n\t\t (!vma || addr + len <= vma->vm_start))\n\t\t\treturn addr;\n\t}\n\tif (mm->get_unmapped_area == arch_get_unmapped_area)\n\t\treturn hugetlb_get_unmapped_area_bottomup(file, addr, len,\n\t\t\t\tpgoff, flags);\n\telse\n\t\treturn hugetlb_get_unmapped_area_topdown(file, addr, len,\n\t\t\t\tpgoff, flags);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'mm: larger stack guard gap, between vmas\n\nStack guard page is a useful feature to reduce a risk of stack smashing\ninto a different mapping. We have been using a single page gap which\nis sufficient to prevent having stack adjacent to a different mapping.\nBut this seems to be insufficient in the light of the stack usage in\nuserspace. E.g. glibc uses as large as 64kB alloca() in many commonly\nused functions. Others use constructs liks gid_t buffer[NGROUPS_MAX]\nwhich is 256kB or stack strings with MAX_ARG_STRLEN.\n\nThis will become especially dangerous for suid binaries and the default\nno limit for the stack size limit because those applications can be\ntricked to consume a large portion of the stack and a single glibc call\ncould jump over the guard page. These attacks are not theoretical,\nunfortunatelly.\n\nMake those attacks less probable by increasing the stack guard gap\nto 1MB (on systems with 4k pages; but make it depend on the page size\nbecause systems with larger base pages might cap stack allocations in\nthe PAGE_SIZE units) which should cover larger alloca() and VLA stack\nallocations. It is obviously not a full fix because the problem is\nsomehow inherent, but it should reduce attack space a lot.\n\nOne could argue that the gap size should be configurable from userspace,\nbut that can be done later when somebody finds that the new 1MB is wrong\nfor some special case applications. For now, add a kernel command line\noption (stack_guard_gap) to specify the stack gap size (in page units).\n\nImplementation wise, first delete all the old code for stack guard page:\nbecause although we could get away with accounting one extra page in a\nstack vma, accounting a larger gap can break userspace - case in point,\na program run with \"ulimit -S -v 20000\" failed when the 1MB gap was\ncounted for RLIMIT_AS; similar problems could come with RLIMIT_MLOCK\nand strict non-overcommit mode.\n\nInstead of keeping gap inside the stack vma, maintain the stack guard\ngap as a gap between vmas: using vm_start_gap() in place of vm_start\n(or vm_end_gap() in place of vm_end if VM_GROWSUP) in just those few\nplaces which need to respect the gap - mainly arch_get_unmapped_area(),\nand and the vma tree's subtree_gap support for that.\n\nOriginal-patch-by: Oleg Nesterov \nOriginal-patch-by: Michal Hocko \nSigned-off-by: Hugh Dickins \nAcked-by: Michal Hocko \nTested-by: Helge Deller # parisc\nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: arch_get_unmapped_area_topdown(struct file *filp, const unsigned long addr0,\n\t\t\t const unsigned long len, const unsigned long pgoff,\n\t\t\t const unsigned long flags)\n{\n\tstruct vm_area_struct *vma;\n\tstruct mm_struct *mm = current->mm;\n\tunsigned long addr = addr0;\n\tstruct vm_unmapped_area_info info;\n\tint rc;\n\n\t/* requested length too big for entire address space */\n\tif (len > TASK_SIZE - mmap_min_addr)\n\t\treturn -ENOMEM;\n\n\tif (flags & MAP_FIXED)\n\t\tgoto check_asce_limit;\n\n\t/* requesting a specific address */\n\tif (addr) {\n\t\taddr = PAGE_ALIGN(addr);\n\t\tvma = find_vma(mm, addr);\n\t\tif (TASK_SIZE - len >= addr && addr >= mmap_min_addr &&\n\t\t\t\t(!vma || addr + len <= vma->vm_start))\n\t\t\tgoto check_asce_limit;\n\t}\n\n\tinfo.flags = VM_UNMAPPED_AREA_TOPDOWN;\n\tinfo.length = len;\n\tinfo.low_limit = max(PAGE_SIZE, mmap_min_addr);\n\tinfo.high_limit = mm->mmap_base;\n\tif (filp || (flags & MAP_SHARED))\n\t\tinfo.align_mask = MMAP_ALIGN_MASK << PAGE_SHIFT;\n\telse\n\t\tinfo.align_mask = 0;\n\tinfo.align_offset = pgoff << PAGE_SHIFT;\n\taddr = vm_unmapped_area(&info);\n\n\t/*\n\t * A failed mmap() very likely causes application failure,\n\t * so fall back to the bottom-up function here. This scenario\n\t * can happen with large stack limits and large mmap()\n\t * allocations.\n\t */\n\tif (addr & ~PAGE_MASK) {\n\t\tVM_BUG_ON(addr != -ENOMEM);\n\t\tinfo.flags = 0;\n\t\tinfo.low_limit = TASK_UNMAPPED_BASE;\n\t\tinfo.high_limit = TASK_SIZE;\n\t\taddr = vm_unmapped_area(&info);\n\t\tif (addr & ~PAGE_MASK)\n\t\t\treturn addr;\n\t}\n\ncheck_asce_limit:\n\tif (addr + len > current->mm->context.asce_limit) {\n\t\trc = crst_table_upgrade(mm);\n\t\tif (rc)\n\t\t\treturn (unsigned long) rc;\n\t}\n\n\treturn addr;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'mm: larger stack guard gap, between vmas\n\nStack guard page is a useful feature to reduce a risk of stack smashing\ninto a different mapping. We have been using a single page gap which\nis sufficient to prevent having stack adjacent to a different mapping.\nBut this seems to be insufficient in the light of the stack usage in\nuserspace. E.g. glibc uses as large as 64kB alloca() in many commonly\nused functions. Others use constructs liks gid_t buffer[NGROUPS_MAX]\nwhich is 256kB or stack strings with MAX_ARG_STRLEN.\n\nThis will become especially dangerous for suid binaries and the default\nno limit for the stack size limit because those applications can be\ntricked to consume a large portion of the stack and a single glibc call\ncould jump over the guard page. These attacks are not theoretical,\nunfortunatelly.\n\nMake those attacks less probable by increasing the stack guard gap\nto 1MB (on systems with 4k pages; but make it depend on the page size\nbecause systems with larger base pages might cap stack allocations in\nthe PAGE_SIZE units) which should cover larger alloca() and VLA stack\nallocations. It is obviously not a full fix because the problem is\nsomehow inherent, but it should reduce attack space a lot.\n\nOne could argue that the gap size should be configurable from userspace,\nbut that can be done later when somebody finds that the new 1MB is wrong\nfor some special case applications. For now, add a kernel command line\noption (stack_guard_gap) to specify the stack gap size (in page units).\n\nImplementation wise, first delete all the old code for stack guard page:\nbecause although we could get away with accounting one extra page in a\nstack vma, accounting a larger gap can break userspace - case in point,\na program run with \"ulimit -S -v 20000\" failed when the 1MB gap was\ncounted for RLIMIT_AS; similar problems could come with RLIMIT_MLOCK\nand strict non-overcommit mode.\n\nInstead of keeping gap inside the stack vma, maintain the stack guard\ngap as a gap between vmas: using vm_start_gap() in place of vm_start\n(or vm_end_gap() in place of vm_end if VM_GROWSUP) in just those few\nplaces which need to respect the gap - mainly arch_get_unmapped_area(),\nand and the vma tree's subtree_gap support for that.\n\nOriginal-patch-by: Oleg Nesterov \nOriginal-patch-by: Michal Hocko \nSigned-off-by: Hugh Dickins \nAcked-by: Michal Hocko \nTested-by: Helge Deller # parisc\nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: unsigned long arch_get_unmapped_area(struct file *filp, unsigned long addr, unsigned long len,\n\t\t\t\t unsigned long pgoff, unsigned long flags)\n{\n\tstruct vm_area_struct *vma;\n\tstruct vm_unmapped_area_info info;\n\n\tif (len > TASK_SIZE)\n\t\treturn -ENOMEM;\n\n\t/* handle MAP_FIXED */\n\tif (flags & MAP_FIXED)\n\t\treturn addr;\n\n\t/* only honour a hint if we're not going to clobber something doing so */\n\tif (addr) {\n\t\taddr = PAGE_ALIGN(addr);\n\t\tvma = find_vma(current->mm, addr);\n\t\tif (TASK_SIZE - len >= addr &&\n\t\t (!vma || addr + len <= vma->vm_start))\n\t\t\tgoto success;\n\t}\n\n\t/* search between the bottom of user VM and the stack grow area */\n\tinfo.flags = 0;\n\tinfo.length = len;\n\tinfo.low_limit = PAGE_SIZE;\n\tinfo.high_limit = (current->mm->start_stack - 0x00200000);\n\tinfo.align_mask = 0;\n\tinfo.align_offset = 0;\n\taddr = vm_unmapped_area(&info);\n\tif (!(addr & ~PAGE_MASK))\n\t\tgoto success;\n\tVM_BUG_ON(addr != -ENOMEM);\n\n\t/* search from just above the WorkRAM area to the top of memory */\n\tinfo.low_limit = PAGE_ALIGN(0x80000000);\n\tinfo.high_limit = TASK_SIZE;\n\taddr = vm_unmapped_area(&info);\n\tif (!(addr & ~PAGE_MASK))\n\t\tgoto success;\n\tVM_BUG_ON(addr != -ENOMEM);\n\n#if 0\n\tprintk(\"[area] l=%lx (ENOMEM) f='%s'\\n\",\n\t len, filp ? filp->f_path.dentry->d_name.name : \"\");\n#endif\n\treturn -ENOMEM;\n\n success:\n#if 0\n\tprintk(\"[area] l=%lx ad=%lx f='%s'\\n\",\n\t len, addr, filp ? filp->f_path.dentry->d_name.name : \"\");\n#endif\n\treturn addr;\n} /* end arch_get_unmapped_area() */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'mm: larger stack guard gap, between vmas\n\nStack guard page is a useful feature to reduce a risk of stack smashing\ninto a different mapping. We have been using a single page gap which\nis sufficient to prevent having stack adjacent to a different mapping.\nBut this seems to be insufficient in the light of the stack usage in\nuserspace. E.g. glibc uses as large as 64kB alloca() in many commonly\nused functions. Others use constructs liks gid_t buffer[NGROUPS_MAX]\nwhich is 256kB or stack strings with MAX_ARG_STRLEN.\n\nThis will become especially dangerous for suid binaries and the default\nno limit for the stack size limit because those applications can be\ntricked to consume a large portion of the stack and a single glibc call\ncould jump over the guard page. These attacks are not theoretical,\nunfortunatelly.\n\nMake those attacks less probable by increasing the stack guard gap\nto 1MB (on systems with 4k pages; but make it depend on the page size\nbecause systems with larger base pages might cap stack allocations in\nthe PAGE_SIZE units) which should cover larger alloca() and VLA stack\nallocations. It is obviously not a full fix because the problem is\nsomehow inherent, but it should reduce attack space a lot.\n\nOne could argue that the gap size should be configurable from userspace,\nbut that can be done later when somebody finds that the new 1MB is wrong\nfor some special case applications. For now, add a kernel command line\noption (stack_guard_gap) to specify the stack gap size (in page units).\n\nImplementation wise, first delete all the old code for stack guard page:\nbecause although we could get away with accounting one extra page in a\nstack vma, accounting a larger gap can break userspace - case in point,\na program run with \"ulimit -S -v 20000\" failed when the 1MB gap was\ncounted for RLIMIT_AS; similar problems could come with RLIMIT_MLOCK\nand strict non-overcommit mode.\n\nInstead of keeping gap inside the stack vma, maintain the stack guard\ngap as a gap between vmas: using vm_start_gap() in place of vm_start\n(or vm_end_gap() in place of vm_end if VM_GROWSUP) in just those few\nplaces which need to respect the gap - mainly arch_get_unmapped_area(),\nand and the vma tree's subtree_gap support for that.\n\nOriginal-patch-by: Oleg Nesterov \nOriginal-patch-by: Michal Hocko \nSigned-off-by: Hugh Dickins \nAcked-by: Michal Hocko \nTested-by: Helge Deller # parisc\nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: arch_get_unmapped_area(struct file *filp, unsigned long addr,\n\t\tunsigned long len, unsigned long pgoff, unsigned long flags)\n{\n\tstruct mm_struct *mm = current->mm;\n\tstruct vm_area_struct *vma;\n\tstruct vm_unmapped_area_info info;\n\tunsigned long begin, end;\n\n\tif (flags & MAP_FIXED)\n\t\treturn addr;\n\n\tfind_start_end(flags, &begin, &end);\n\n\tif (len > end)\n\t\treturn -ENOMEM;\n\n\tif (addr) {\n\t\taddr = PAGE_ALIGN(addr);\n\t\tvma = find_vma(mm, addr);\n\t\tif (end - len >= addr &&\n\t\t (!vma || addr + len <= vma->vm_start))\n\t\t\treturn addr;\n\t}\n\n\tinfo.flags = 0;\n\tinfo.length = len;\n\tinfo.low_limit = begin;\n\tinfo.high_limit = end;\n\tinfo.align_mask = 0;\n\tinfo.align_offset = pgoff << PAGE_SHIFT;\n\tif (filp) {\n\t\tinfo.align_mask = get_align_mask();\n\t\tinfo.align_offset += get_align_bits();\n\t}\n\treturn vm_unmapped_area(&info);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'mm: larger stack guard gap, between vmas\n\nStack guard page is a useful feature to reduce a risk of stack smashing\ninto a different mapping. We have been using a single page gap which\nis sufficient to prevent having stack adjacent to a different mapping.\nBut this seems to be insufficient in the light of the stack usage in\nuserspace. E.g. glibc uses as large as 64kB alloca() in many commonly\nused functions. Others use constructs liks gid_t buffer[NGROUPS_MAX]\nwhich is 256kB or stack strings with MAX_ARG_STRLEN.\n\nThis will become especially dangerous for suid binaries and the default\nno limit for the stack size limit because those applications can be\ntricked to consume a large portion of the stack and a single glibc call\ncould jump over the guard page. These attacks are not theoretical,\nunfortunatelly.\n\nMake those attacks less probable by increasing the stack guard gap\nto 1MB (on systems with 4k pages; but make it depend on the page size\nbecause systems with larger base pages might cap stack allocations in\nthe PAGE_SIZE units) which should cover larger alloca() and VLA stack\nallocations. It is obviously not a full fix because the problem is\nsomehow inherent, but it should reduce attack space a lot.\n\nOne could argue that the gap size should be configurable from userspace,\nbut that can be done later when somebody finds that the new 1MB is wrong\nfor some special case applications. For now, add a kernel command line\noption (stack_guard_gap) to specify the stack gap size (in page units).\n\nImplementation wise, first delete all the old code for stack guard page:\nbecause although we could get away with accounting one extra page in a\nstack vma, accounting a larger gap can break userspace - case in point,\na program run with \"ulimit -S -v 20000\" failed when the 1MB gap was\ncounted for RLIMIT_AS; similar problems could come with RLIMIT_MLOCK\nand strict non-overcommit mode.\n\nInstead of keeping gap inside the stack vma, maintain the stack guard\ngap as a gap between vmas: using vm_start_gap() in place of vm_start\n(or vm_end_gap() in place of vm_end if VM_GROWSUP) in just those few\nplaces which need to respect the gap - mainly arch_get_unmapped_area(),\nand and the vma tree's subtree_gap support for that.\n\nOriginal-patch-by: Oleg Nesterov \nOriginal-patch-by: Michal Hocko \nSigned-off-by: Hugh Dickins \nAcked-by: Michal Hocko \nTested-by: Helge Deller # parisc\nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: virtual ~TProtocol() {} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'THRIFT-3231 CPP: Limit recursion depth to 64\nClient: cpp\nPatch: Ben Craig '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: grub_ext2_iterate_dir (grub_fshelp_node_t dir,\n\t\t grub_fshelp_iterate_dir_hook_t hook, void *hook_data)\n{\n unsigned int fpos = 0;\n struct grub_fshelp_node *diro = (struct grub_fshelp_node *) dir;\n\n if (! diro->inode_read)\n {\n grub_ext2_read_inode (diro->data, diro->ino, &diro->inode);\n if (grub_errno)\n\treturn 0;\n }\n\n /* Search the file. */\n while (fpos < grub_le_to_cpu32 (diro->inode.size))\n {\n struct ext2_dirent dirent;\n\n grub_ext2_read_file (diro, 0, 0, fpos, sizeof (struct ext2_dirent),\n\t\t\t (char *) &dirent);\n if (grub_errno)\n\treturn 0;\n\n if (dirent.direntlen == 0)\n return 0;\n\n if (dirent.inode != 0 && dirent.namelen != 0)\n\t{\n\t char filename[dirent.namelen + 1];\n\t struct grub_fshelp_node *fdiro;\n\t enum grub_fshelp_filetype type = GRUB_FSHELP_UNKNOWN;\n\n\t grub_ext2_read_file (diro, 0, 0, fpos + sizeof (struct ext2_dirent),\n\t\t\t dirent.namelen, filename);\n\t if (grub_errno)\n\t return 0;\n\n\t fdiro = grub_malloc (sizeof (struct grub_fshelp_node));\n\t if (! fdiro)\n\t return 0;\n\n\t fdiro->data = diro->data;\n\t fdiro->ino = grub_le_to_cpu32 (dirent.inode);\n\n\t filename[dirent.namelen] = '\\0';\n\n\t if (dirent.filetype != FILETYPE_UNKNOWN)\n\t {\n\t fdiro->inode_read = 0;\n\n\t if (dirent.filetype == FILETYPE_DIRECTORY)\n\t\ttype = GRUB_FSHELP_DIR;\n\t else if (dirent.filetype == FILETYPE_SYMLINK)\n\t\ttype = GRUB_FSHELP_SYMLINK;\n\t else if (dirent.filetype == FILETYPE_REG)\n\t\ttype = GRUB_FSHELP_REG;\n\t }\n\t else\n\t {\n\t /* The filetype can not be read from the dirent, read\n\t\t the inode to get more information. */\n\t grub_ext2_read_inode (diro->data,\n grub_le_to_cpu32 (dirent.inode),\n\t\t\t\t &fdiro->inode);\n\t if (grub_errno)\n\t\t{\n\t\t grub_free (fdiro);\n\t\t return 0;\n\t\t}\n\n\t fdiro->inode_read = 1;\n\n\t if ((grub_le_to_cpu16 (fdiro->inode.mode)\n\t\t & FILETYPE_INO_MASK) == FILETYPE_INO_DIRECTORY)\n\t\ttype = GRUB_FSHELP_DIR;\n\t else if ((grub_le_to_cpu16 (fdiro->inode.mode)\n\t\t\t& FILETYPE_INO_MASK) == FILETYPE_INO_SYMLINK)\n\t\ttype = GRUB_FSHELP_SYMLINK;\n\t else if ((grub_le_to_cpu16 (fdiro->inode.mode)\n\t\t\t& FILETYPE_INO_MASK) == FILETYPE_INO_REG)\n\t\ttype = GRUB_FSHELP_REG;\n\t }\n\n\t if (hook (filename, type, fdiro, hook_data))\n\t return 1;\n\t}\n\n fpos += grub_le_to_cpu16 (dirent.direntlen);\n }\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': '* grub-core/fs/ext2.c: Remove variable length arrays.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: secret (gcry_mpi_t output, gcry_mpi_t input, RSA_secret_key *skey )\n{\n /* Remove superfluous leading zeroes from INPUT. */\n mpi_normalize (input);\n\n if (!skey->p || !skey->q || !skey->u)\n {\n mpi_powm (output, input, skey->d, skey->n);\n }\n else\n {\n gcry_mpi_t m1 = mpi_alloc_secure( mpi_get_nlimbs(skey->n)+1 );\n gcry_mpi_t m2 = mpi_alloc_secure( mpi_get_nlimbs(skey->n)+1 );\n gcry_mpi_t h = mpi_alloc_secure( mpi_get_nlimbs(skey->n)+1 );\n\n /* m1 = c ^ (d mod (p-1)) mod p */\n mpi_sub_ui( h, skey->p, 1 );\n mpi_fdiv_r( h, skey->d, h );\n mpi_powm( m1, input, h, skey->p );\n /* m2 = c ^ (d mod (q-1)) mod q */\n mpi_sub_ui( h, skey->q, 1 );\n mpi_fdiv_r( h, skey->d, h );\n mpi_powm( m2, input, h, skey->q );\n /* h = u * ( m2 - m1 ) mod q */\n mpi_sub( h, m2, m1 );\n if ( mpi_has_sign ( h ) )\n mpi_add ( h, h, skey->q );\n mpi_mulm( h, skey->u, h, skey->q );\n /* m = m1 + h * p */\n mpi_mul ( h, h, skey->p );\n mpi_add ( output, m1, h );\n\n mpi_free ( h );\n mpi_free ( m1 );\n mpi_free ( m2 );\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'rsa: Minor refactoring.\n\n* cipher/rsa.c (secret): Factor code out to ...\n(secret_core_std, secret_core_crt): new functions.\n\nSigned-off-by: Werner Koch '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: forward_search_range(regex_t* reg, const UChar* str, const UChar* end, UChar* s,\n\t\t UChar* range, UChar** low, UChar** high, UChar** low_prev)\n{\n UChar *p, *pprev = (UChar* )NULL;\n\n#ifdef ONIG_DEBUG_SEARCH\n fprintf(stderr, \"forward_search_range: str: %d, end: %d, s: %d, range: %d\\n\",\n\t (int )str, (int )end, (int )s, (int )range);\n#endif\n\n p = s;\n if (reg->dmin > 0) {\n if (ONIGENC_IS_SINGLEBYTE(reg->enc)) {\n p += reg->dmin;\n }\n else {\n UChar *q = p + reg->dmin;\n while (p < q) p += enclen(reg->enc, p);\n }\n }\n\n retry:\n switch (reg->optimize) {\n case ONIG_OPTIMIZE_EXACT:\n p = slow_search(reg->enc, reg->exact, reg->exact_end, p, end, range);\n break;\n case ONIG_OPTIMIZE_EXACT_IC:\n p = slow_search_ic(reg->enc, reg->case_fold_flag,\n reg->exact, reg->exact_end, p, end, range);\n break;\n\n case ONIG_OPTIMIZE_EXACT_BM:\n p = bm_search(reg, reg->exact, reg->exact_end, p, end, range);\n break;\n\n case ONIG_OPTIMIZE_EXACT_BM_NOT_REV:\n p = bm_search_notrev(reg, reg->exact, reg->exact_end, p, end, range);\n break;\n\n case ONIG_OPTIMIZE_MAP:\n p = map_search(reg->enc, reg->map, p, range);\n break;\n }\n\n if (p && p < range) {\n if (p - reg->dmin < s) {\n retry_gate:\n pprev = p;\n p += enclen(reg->enc, p);\n goto retry;\n }\n\n if (reg->sub_anchor) {\n UChar* prev;\n\n switch (reg->sub_anchor) {\n case ANCHOR_BEGIN_LINE:\n if (!ON_STR_BEGIN(p)) {\n prev = onigenc_get_prev_char_head(reg->enc,\n (pprev ? pprev : str), p);\n if (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))\n goto retry_gate;\n }\n break;\n\n case ANCHOR_END_LINE:\n if (ON_STR_END(p)) {\n#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE\n prev = (UChar* )onigenc_get_prev_char_head(reg->enc,\n (pprev ? pprev : str), p);\n if (prev && ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))\n goto retry_gate;\n#endif\n }\n else if (! ONIGENC_IS_MBC_NEWLINE(reg->enc, p, end)\n#ifdef USE_CRNL_AS_LINE_TERMINATOR\n && ! ONIGENC_IS_MBC_CRNL(reg->enc, p, end)\n#endif\n )\n goto retry_gate;\n break;\n }\n }\n\n if (reg->dmax == 0) {\n *low = p;\n if (low_prev) {\n if (*low > s)\n *low_prev = onigenc_get_prev_char_head(reg->enc, s, p);\n else\n *low_prev = onigenc_get_prev_char_head(reg->enc,\n (pprev ? pprev : str), p);\n }\n }\n else {\n if (reg->dmax != ONIG_INFINITE_DISTANCE) {\n *low = p - reg->dmax;\n if (*low > s) {\n *low = onigenc_get_right_adjust_char_head_with_prev(reg->enc, s,\n *low, (const UChar** )low_prev);\n if (low_prev && IS_NULL(*low_prev))\n *low_prev = onigenc_get_prev_char_head(reg->enc,\n (pprev ? pprev : s), *low);\n }\n else {\n if (low_prev)\n *low_prev = onigenc_get_prev_char_head(reg->enc,\n (pprev ? pprev : str), *low);\n }\n }\n }\n /* no needs to adjust *high, *high is used as range check only */\n *high = p - reg->dmin;\n\n#ifdef ONIG_DEBUG_SEARCH\n fprintf(stderr,\n \"forward_search_range success: low: %d, high: %d, dmin: %d, dmax: %d\\n\",\n\t (int )(*low - str), (int )(*high - str), reg->dmin, reg->dmax);\n#endif\n return 1; /* success */\n }\n\n return 0; /* fail */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'fix #58 : access to invalid address by reg->dmin value'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int __fsnotify_parent(const struct path *path, struct dentry *dentry, __u32 mask)\n{\n\tstruct dentry *parent;\n\tstruct inode *p_inode;\n\tint ret = 0;\n\n\tif (!dentry)\n\t\tdentry = path->dentry;\n\n\tif (!(dentry->d_flags & DCACHE_FSNOTIFY_PARENT_WATCHED))\n\t\treturn 0;\n\n\tparent = dget_parent(dentry);\n\tp_inode = parent->d_inode;\n\n\tif (unlikely(!fsnotify_inode_watches_children(p_inode)))\n\t\t__fsnotify_update_child_dentry_flags(p_inode);\n\telse if (p_inode->i_fsnotify_mask & mask) {\n\t\t/* we are notifying a parent so come up with the new mask which\n\t\t * specifies these are events which came from a child. */\n\t\tmask |= FS_EVENT_ON_CHILD;\n\n\t\tif (path)\n\t\t\tret = fsnotify(p_inode, mask, path, FSNOTIFY_EVENT_PATH,\n\t\t\t\t dentry->d_name.name, 0);\n\t\telse\n\t\t\tret = fsnotify(p_inode, mask, dentry->d_inode, FSNOTIFY_EVENT_INODE,\n\t\t\t\t dentry->d_name.name, 0);\n\t}\n\n\tdput(parent);\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362', 'CWE-399'], 'message': 'dentry name snapshots\n\ntake_dentry_name_snapshot() takes a safe snapshot of dentry name;\nif the name is a short one, it gets copied into caller-supplied\nstructure, otherwise an extra reference to external name is grabbed\n(those are never modified). In either case the pointer to stable\nstring is stored into the same structure.\n\ndentry must be held by the caller of take_dentry_name_snapshot(),\nbut may be freely dropped afterwards - the snapshot will stay\nuntil destroyed by release_dentry_name_snapshot().\n\nIntended use:\n\tstruct name_snapshot s;\n\n\ttake_dentry_name_snapshot(&s, dentry);\n\t...\n\taccess s.name\n\t...\n\trelease_dentry_name_snapshot(&s);\n\nReplaces fsnotify_oldname_...(), gets used in fsnotify to obtain the name\nto pass down with event.\n\nSigned-off-by: Al Viro '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: gsm_xsmp_client_connect (GsmXSMPClient *client,\n SmsConn conn,\n unsigned long *mask_ret,\n SmsCallbacks *callbacks_ret)\n{\n client->priv->conn = conn;\n\n if (client->priv->protocol_timeout) {\n g_source_remove (client->priv->protocol_timeout);\n client->priv->protocol_timeout = 0;\n }\n\n g_debug (\"GsmXSMPClient: Initializing client %s\", client->priv->description);\n\n *mask_ret = 0;\n\n *mask_ret |= SmsRegisterClientProcMask;\n callbacks_ret->register_client.callback = register_client_callback;\n callbacks_ret->register_client.manager_data = client;\n\n *mask_ret |= SmsInteractRequestProcMask;\n callbacks_ret->interact_request.callback = interact_request_callback;\n callbacks_ret->interact_request.manager_data = client;\n\n *mask_ret |= SmsInteractDoneProcMask;\n callbacks_ret->interact_done.callback = interact_done_callback;\n callbacks_ret->interact_done.manager_data = client;\n\n *mask_ret |= SmsSaveYourselfRequestProcMask;\n callbacks_ret->save_yourself_request.callback = save_yourself_request_callback;\n callbacks_ret->save_yourself_request.manager_data = client;\n\n *mask_ret |= SmsSaveYourselfP2RequestProcMask;\n callbacks_ret->save_yourself_phase2_request.callback = save_yourself_phase2_request_callback;\n callbacks_ret->save_yourself_phase2_request.manager_data = client;\n\n *mask_ret |= SmsSaveYourselfDoneProcMask;\n callbacks_ret->save_yourself_done.callback = save_yourself_done_callback;\n callbacks_ret->save_yourself_done.manager_data = client;\n\n *mask_ret |= SmsCloseConnectionProcMask;\n callbacks_ret->close_connection.callback = close_connection_callback;\n callbacks_ret->close_connection.manager_data = client;\n\n *mask_ret |= SmsSetPropertiesProcMask;\n callbacks_ret->set_properties.callback = set_properties_callback;\n callbacks_ret->set_properties.manager_data = client;\n\n *mask_ret |= SmsDeletePropertiesProcMask;\n callbacks_ret->delete_properties.callback = delete_properties_callback;\n callbacks_ret->delete_properties.manager_data = client;\n\n *mask_ret |= SmsGetPropertiesProcMask;\n callbacks_ret->get_properties.callback = get_properties_callback;\n callbacks_ret->get_properties.manager_data = client;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-835'], 'message': '[gsm] Delay the creation of the GsmXSMPClient until it really exists\n\nWe used to create the GsmXSMPClient before the XSMP connection is really\naccepted. This can lead to some issues, though. An example is:\nhttps://bugzilla.gnome.org/show_bug.cgi?id=598211#c19. Quoting:\n\n \"What is happening is that a new client (probably metacity in your\n case) is opening an ICE connection in the GSM_MANAGER_PHASE_END_SESSION\n phase, which causes a new GsmXSMPClient to be added to the client\n store. The GSM_MANAGER_PHASE_EXIT phase then begins before the client\n has had a chance to establish a xsmp connection, which means that\n client->priv->conn will not be initialized at the point that xsmp_stop\n is called on the new unregistered client.\"\n\nThe fix is to create the GsmXSMPClient object when there's a real XSMP\nconnection. This implies moving the timeout that makes sure we don't\nhave an empty client to the XSMP server.\n\nhttps://bugzilla.gnome.org/show_bug.cgi?id=598211'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int nbd_negotiate_read(QIOChannel *ioc, void *buffer, size_t size)\n{\n ssize_t ret;\n guint watch;\n\n assert(qemu_in_coroutine());\n /* Negotiation are always in main loop. */\n watch = qio_channel_add_watch(ioc,\n G_IO_IN,\n nbd_negotiate_continue,\n qemu_coroutine_self(),\n NULL);\n ret = nbd_read(ioc, buffer, size, NULL);\n g_source_remove(watch);\n return ret;\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'nbd/server: get rid of nbd_negotiate_read and friends\n\nFunctions nbd_negotiate_{read,write,drop_sync} were introduced in\n1a6245a5b, when nbd_rwv (was nbd_wr_sync) was working through\nqemu_co_sendv_recvv (the path is nbd_wr_sync -> qemu_co_{recv/send} ->\nqemu_co_send_recv -> qemu_co_sendv_recvv), which just yields, without\nsetting any handlers. But starting from ff82911cd nbd_rwv (was\nnbd_wr_syncv) works through qio_channel_yield() which sets handlers, so\nwatchers are redundant in nbd_negotiate_{read,write,drop_sync}, then,\nlet's just use nbd_{read,write,drop} functions.\n\nFunctions nbd_{read,write,drop} has errp parameter, which is unused in\nthis patch. This will be fixed later.\n\nSigned-off-by: Vladimir Sementsov-Ogievskiy \nReviewed-by: Eric Blake \nMessage-Id: <20170602150150.258222-4-vsementsov@virtuozzo.com>\nSigned-off-by: Paolo Bonzini '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int nbd_negotiate_send_rep_list(QIOChannel *ioc, NBDExport *exp)\n{\n size_t name_len, desc_len;\n uint32_t len;\n const char *name = exp->name ? exp->name : \"\";\n const char *desc = exp->description ? exp->description : \"\";\n int rc;\n\n TRACE(\"Advertising export name '%s' description '%s'\", name, desc);\n name_len = strlen(name);\n desc_len = strlen(desc);\n len = name_len + desc_len + sizeof(len);\n rc = nbd_negotiate_send_rep_len(ioc, NBD_REP_SERVER, NBD_OPT_LIST, len);\n if (rc < 0) {\n return rc;\n }\n\n len = cpu_to_be32(name_len);\n if (nbd_negotiate_write(ioc, &len, sizeof(len)) < 0) {\n LOG(\"write failed (name length)\");\n return -EINVAL;\n }\n if (nbd_negotiate_write(ioc, name, name_len) < 0) {\n LOG(\"write failed (name buffer)\");\n return -EINVAL;\n }\n if (nbd_negotiate_write(ioc, desc, desc_len) < 0) {\n LOG(\"write failed (description buffer)\");\n return -EINVAL;\n }\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'nbd/server: get rid of nbd_negotiate_read and friends\n\nFunctions nbd_negotiate_{read,write,drop_sync} were introduced in\n1a6245a5b, when nbd_rwv (was nbd_wr_sync) was working through\nqemu_co_sendv_recvv (the path is nbd_wr_sync -> qemu_co_{recv/send} ->\nqemu_co_send_recv -> qemu_co_sendv_recvv), which just yields, without\nsetting any handlers. But starting from ff82911cd nbd_rwv (was\nnbd_wr_syncv) works through qio_channel_yield() which sets handlers, so\nwatchers are redundant in nbd_negotiate_{read,write,drop_sync}, then,\nlet's just use nbd_{read,write,drop} functions.\n\nFunctions nbd_{read,write,drop} has errp parameter, which is unused in\nthis patch. This will be fixed later.\n\nSigned-off-by: Vladimir Sementsov-Ogievskiy \nReviewed-by: Eric Blake \nMessage-Id: <20170602150150.258222-4-vsementsov@virtuozzo.com>\nSigned-off-by: Paolo Bonzini '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadPESImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n char\n filename[MagickPathExtent];\n\n FILE\n *file;\n\n Image\n *image;\n\n ImageInfo\n *read_info;\n\n int\n delta_x,\n delta_y,\n j,\n unique_file,\n x,\n y;\n\n MagickBooleanType\n status;\n\n PESBlockInfo\n blocks[256];\n\n PointInfo\n *stitches;\n\n SegmentInfo\n bounds;\n\n register ssize_t\n i;\n\n size_t\n number_blocks,\n number_colors,\n number_stitches;\n\n ssize_t\n count,\n offset;\n\n unsigned char\n magick[4],\n version[4];\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Verify PES identifier.\n */\n count=ReadBlob(image,4,magick);\n if ((count != 4) || (LocaleNCompare((char *) magick,\"#PES\",4) != 0))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n count=ReadBlob(image,4,version);\n offset=ReadBlobLSBSignedLong(image);\n if (DiscardBlobBytes(image,offset+36) == MagickFalse)\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n if (EOFBlob(image) != MagickFalse)\n ThrowReaderException(CorruptImageError,\"UnexpectedEndOfFile\");\n /*\n Get PES colors.\n */\n number_colors=(size_t) ReadBlobByte(image)+1;\n for (i=0; i < (ssize_t) number_colors; i++)\n {\n j=ReadBlobByte(image);\n blocks[i].color=PESColor+(j < 0 ? 0 : j);\n blocks[i].offset=0;\n }\n for ( ; i < 256L; i++)\n {\n blocks[i].offset=0;\n blocks[i].color=PESColor;\n }\n if (DiscardBlobBytes(image,532L-number_colors-21) == MagickFalse)\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n if (EOFBlob(image) != MagickFalse)\n ThrowReaderException(CorruptImageError,\"UnexpectedEndOfFile\");\n /*\n Stitch away.\n */\n number_stitches=64;\n stitches=(PointInfo *) AcquireQuantumMemory(number_stitches,\n sizeof(*stitches));\n if (stitches == (PointInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n bounds.x1=65535.0;\n bounds.y1=65535.0;\n bounds.x2=(-65535.0);\n bounds.y2=(-65535.0);\n i=0;\n j=0;\n delta_x=0;\n delta_y=0;\n while (EOFBlob(image) != EOF)\n {\n x=ReadBlobByte(image);\n y=ReadBlobByte(image);\n if ((x == 0xff) && (y == 0))\n break;\n if ((x == 254) && (y == 176))\n {\n /*\n Start a new stitch block.\n */\n j++;\n blocks[j].offset=(ssize_t) i;\n if (j >= 256)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) ReadBlobByte(image);\n continue;\n }\n if ((x & 0x80) == 0)\n {\n /*\n Normal stitch.\n */\n if ((x & 0x40) != 0)\n x-=0x80;\n }\n else\n {\n /*\n Jump stitch.\n */\n x=((x & 0x0f) << 8)+y;\n if ((x & 0x800) != 0)\n x-=0x1000;\n y=ReadBlobByte(image);\n }\n if ((y & 0x80) == 0)\n {\n /*\n Normal stitch.\n */\n if ((y & 0x40) != 0)\n y-=0x80;\n }\n else\n {\n /*\n Jump stitch.\n */\n y=((y & 0x0f) << 8)+ReadBlobByte(image);\n if ((y & 0x800) != 0)\n y-=0x1000;\n }\n /*\n Note stitch (x,y).\n */\n x+=delta_x;\n y+=delta_y;\n delta_x=x;\n delta_y=y;\n stitches[i].x=(double) x;\n stitches[i].y=(double) y;\n if ((double) x < bounds.x1)\n bounds.x1=(double) x;\n if ((double) x > bounds.x2)\n bounds.x2=(double) x;\n if ((double) y < bounds.y1)\n bounds.y1=(double) y;\n if ((double) y > bounds.y2)\n bounds.y2=(double) y;\n i++;\n if (i >= (ssize_t) number_stitches)\n {\n /*\n Make room for more stitches.\n */\n number_stitches<<=1;\n stitches=(PointInfo *) ResizeQuantumMemory(stitches,(size_t)\n number_stitches,sizeof(*stitches));\n if (stitches == (PointInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n }\n j++;\n blocks[j].offset=(ssize_t) i;\n number_blocks=(size_t) j;\n /*\n Write stitches as SVG file.\n */\n file=(FILE *) NULL;\n unique_file=AcquireUniqueFileResource(filename);\n if (unique_file != -1)\n file=fdopen(unique_file,\"wb\");\n if ((unique_file == -1) || (file == (FILE *) NULL))\n ThrowImageException(FileOpenError,\"UnableToCreateTemporaryFile\");\n (void) FormatLocaleFile(file,\"\\n\");\n (void) FormatLocaleFile(file,\"\\n\",bounds.x2-bounds.x1,\n bounds.y2-bounds.y1);\n for (i=0; i < (ssize_t) number_blocks; i++)\n {\n offset=blocks[i].offset;\n (void) FormatLocaleFile(file,\" red,blocks[i].color->green,\n blocks[i].color->blue,stitches[offset].x-bounds.x1,\n stitches[offset].y-bounds.y1);\n for (j=1; j < (ssize_t) (blocks[i+1].offset-offset); j++)\n (void) FormatLocaleFile(file,\" L %g %g\",stitches[offset+j].x-bounds.x1,\n stitches[offset+j].y-bounds.y1);\n (void) FormatLocaleFile(file,\"\\\"/>\\n\");\n }\n (void) FormatLocaleFile(file,\"\\n\");\n (void) fclose(file);\n (void) CloseBlob(image);\n image=DestroyImage(image);\n /*\n Read SVG file.\n */\n read_info=CloneImageInfo(image_info);\n SetImageInfoBlob(read_info,(void *) NULL,0);\n (void) FormatLocaleString(read_info->filename,MagickPathExtent,\"svg:%s\",\n filename);\n image=ReadImage(read_info,exception);\n if (image != (Image *) NULL)\n {\n (void) CopyMagickString(image->filename,image_info->filename,\n MagickPathExtent);\n (void) CopyMagickString(image->magick_filename,image_info->filename,\n MagickPathExtent);\n (void) CopyMagickString(image->magick,\"PES\",MagickPathExtent);\n }\n read_info=DestroyImageInfo(read_info);\n (void) RelinquishUniqueFileResource(filename);\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/537'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: QPDFObjectHandle::newIndirect(QPDF* qpdf, int objid, int generation)\n{\n return QPDFObjectHandle(qpdf, objid, generation);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': 'Handle object ID 0 (fixes #99)\n\nThis is CVE-2017-9208.\n\nThe QPDF library uses object ID 0 internally as a sentinel to\nrepresent a direct object, but prior to this fix, was not blocking\nhandling of 0 0 obj or 0 0 R as a special case. Creating an object in\nthe file with 0 0 obj could cause various infinite loops. The PDF spec\ndoesn't allow for object 0. Having qpdf handle object 0 might be a\nbetter fix, but changing all the places in the code that assumes objid\n== 0 means direct would be risky.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: xps_true_callback_glyph_name(gs_font *pfont, gs_glyph glyph, gs_const_string *pstr)\n{\n /* This function is copied verbatim from plfont.c */\n\n int table_length;\n int table_offset;\n\n ulong format;\n uint numGlyphs;\n uint glyph_name_index;\n const byte *postp; /* post table pointer */\n\n /* guess if the font type is not truetype */\n if ( pfont->FontType != ft_TrueType )\n {\n glyph -= 29;\n if (glyph < 258 )\n {\n pstr->data = (byte*) pl_mac_names[glyph];\n pstr->size = strlen((char*)pstr->data);\n return 0;\n }\n else\n {\n return gs_throw1(-1, \"glyph index %lu out of range\", (ulong)glyph);\n }\n }\n\n table_offset = xps_find_sfnt_table((xps_font_t*)pfont->client_data, \"post\", &table_length);\n\n /* no post table */\n if (table_offset < 0)\n return gs_throw(-1, \"no post table\");\n\n /* this shoudn't happen but... */\n if ( table_length == 0 )\n return gs_throw(-1, \"zero-size post table\");\n\n ((gs_font_type42 *)pfont)->data.string_proc((gs_font_type42 *)pfont,\n table_offset, table_length, &postp);\n format = u32(postp);\n\n /* Format 1.0 (mac encoding) is a simple table see the TT spec.\n * We don't implement this because we don't see it in practice.\n * Format 2.5 is deprecated.\n * Format 3.0 means that there is no post data in the font file.\n * We see this a lot but can't do much about it.\n * The only format we support is 2.0.\n */\n if ( format != 0x20000 )\n {\n /* Invent a name if we don't know the table format. */\n char buf[32];\n gs_sprintf(buf, \"glyph%d\", (int)glyph);\n pstr->data = (byte*)buf;\n pstr->size = strlen((char*)pstr->data);\n return 0;\n }\n\n /* skip over the post header */\n numGlyphs = u16(postp + 32);\n if (glyph > numGlyphs - 1)\n {\n return gs_throw1(-1, \"glyph index %lu out of range\", (ulong)glyph);\n }\n\n /* glyph name index starts at post + 34 each entry is 2 bytes */\n glyph_name_index = u16(postp + 34 + (glyph * 2));\n\n /* this shouldn't happen */\n if ( glyph_name_index > 0x7fff )\n return gs_throw(-1, \"post table format error\");\n\n /* mac easy */\n if ( glyph_name_index < 258 )\n {\n // dmprintf2(pfont->memory, \"glyph name (mac) %d = %s\\n\", glyph, pl_mac_names[glyph_name_index]);\n pstr->data = (byte*) pl_mac_names[glyph_name_index];\n pstr->size = strlen((char*)pstr->data);\n return 0;\n }\n\n /* not mac */\n else\n {\n byte *mydata;\n\n /* and here's the tricky part */\n const byte *pascal_stringp = postp + 34 + (numGlyphs * 2);\n\n /* 0 - 257 lives in the mac table above */\n glyph_name_index -= 258;\n\n /* The string we want is the index'th pascal string,\n * so we \"hop\" to each length byte \"index\" times. */\n while (glyph_name_index > 0)\n {\n pascal_stringp += ((int)(*pascal_stringp)+1);\n glyph_name_index--;\n }\n\n /* length byte */\n pstr->size = (int)(*pascal_stringp);\n\n /* + 1 is for the length byte */\n pstr->data = pascal_stringp + 1;\n\n /* sanity check */\n if ( pstr->data + pstr->size > postp + table_length || pstr->data - 1 < postp)\n return gs_throw(-1, \"data out of range\");\n\n /* sigh - we have to allocate a copy of the data - by the\n * time a high level device makes use of it the font data\n * may be freed. This is a necessary leak. */\n mydata = gs_alloc_bytes(pfont->memory, pstr->size + 1, \"glyph to name\");\n if ( mydata == 0 )\n return -1;\n memcpy(mydata, pascal_stringp + 1, pstr->size);\n pstr->data = mydata;\n\n mydata[pstr->size] = 0;\n\n return 0;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Bug 698042: xps: fix glyph index and index bounds check.\n\nIf a gs_glyph has the GS_MIN_GLYPH_INDEX offset, we need to remove the offset\nbefore we try to use it.\n\nSecondly, using a unsigned variable for a value from which we subtract 1, and\nwhich can be zero doesn't work well. Switch to a signed value.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: i_alloc_byte_array_immovable(gs_memory_t * mem, uint num_elements,\n uint elt_size, client_name_t cname)\n{\n gs_ref_memory_t * const imem = (gs_ref_memory_t *)mem;\n obj_header_t *obj;\n\n#ifdef MEMENTO\n if (Memento_failThisEvent())\n return NULL;\n#endif\n\n obj = alloc_obj(imem, (ulong) num_elements * elt_size,\n &st_bytes, ALLOC_IMMOVABLE | ALLOC_DIRECT,\n cname);\n\n if_debug6m('A', mem, \"[a%d|+b.]%s -bytes-*(%lu=%u*%u) = 0x%lx\\n\",\n alloc_trace_space(imem), client_name_string(cname),\n (ulong) num_elements * elt_size,\n num_elements, elt_size, (ulong) obj);\n return (byte *) obj;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Bug 697985: bounds check the array allocations methods\n\nThe clump allocator has four allocation functions that use 'number of elements'\nand 'size of elements' parameters (rather than a simple 'number of bytes').\n\nThose need specific bounds checking.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void Huff_offsetTransmit (huff_t *huff, int ch, byte *fout, int *offset) {\n\tbloc = *offset;\n\tsend(huff->loc[ch], NULL, fout);\n\t*offset = bloc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix/improve buffer overflow in MSG_ReadBits/MSG_WriteBits\n\nPrevent reading past end of message in MSG_ReadBits. If read past\nend of msg->data buffer (16348 bytes) the engine could SEGFAULT.\nMake MSG_WriteBits use an exact buffer overflow check instead of\npossibly failing with a few bytes left.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int sanity_check_raw_super(struct f2fs_sb_info *sbi,\n\t\t\t\tstruct buffer_head *bh)\n{\n\tstruct f2fs_super_block *raw_super = (struct f2fs_super_block *)\n\t\t\t\t\t(bh->b_data + F2FS_SUPER_OFFSET);\n\tstruct super_block *sb = sbi->sb;\n\tunsigned int blocksize;\n\n\tif (F2FS_SUPER_MAGIC != le32_to_cpu(raw_super->magic)) {\n\t\tf2fs_msg(sb, KERN_INFO,\n\t\t\t\"Magic Mismatch, valid(0x%x) - read(0x%x)\",\n\t\t\tF2FS_SUPER_MAGIC, le32_to_cpu(raw_super->magic));\n\t\treturn 1;\n\t}\n\n\t/* Currently, support only 4KB page cache size */\n\tif (F2FS_BLKSIZE != PAGE_SIZE) {\n\t\tf2fs_msg(sb, KERN_INFO,\n\t\t\t\"Invalid page_cache_size (%lu), supports only 4KB\\n\",\n\t\t\tPAGE_SIZE);\n\t\treturn 1;\n\t}\n\n\t/* Currently, support only 4KB block size */\n\tblocksize = 1 << le32_to_cpu(raw_super->log_blocksize);\n\tif (blocksize != F2FS_BLKSIZE) {\n\t\tf2fs_msg(sb, KERN_INFO,\n\t\t\t\"Invalid blocksize (%u), supports only 4KB\\n\",\n\t\t\tblocksize);\n\t\treturn 1;\n\t}\n\n\t/* check log blocks per segment */\n\tif (le32_to_cpu(raw_super->log_blocks_per_seg) != 9) {\n\t\tf2fs_msg(sb, KERN_INFO,\n\t\t\t\"Invalid log blocks per segment (%u)\\n\",\n\t\t\tle32_to_cpu(raw_super->log_blocks_per_seg));\n\t\treturn 1;\n\t}\n\n\t/* Currently, support 512/1024/2048/4096 bytes sector size */\n\tif (le32_to_cpu(raw_super->log_sectorsize) >\n\t\t\t\tF2FS_MAX_LOG_SECTOR_SIZE ||\n\t\tle32_to_cpu(raw_super->log_sectorsize) <\n\t\t\t\tF2FS_MIN_LOG_SECTOR_SIZE) {\n\t\tf2fs_msg(sb, KERN_INFO, \"Invalid log sectorsize (%u)\",\n\t\t\tle32_to_cpu(raw_super->log_sectorsize));\n\t\treturn 1;\n\t}\n\tif (le32_to_cpu(raw_super->log_sectors_per_block) +\n\t\tle32_to_cpu(raw_super->log_sectorsize) !=\n\t\t\tF2FS_MAX_LOG_SECTOR_SIZE) {\n\t\tf2fs_msg(sb, KERN_INFO,\n\t\t\t\"Invalid log sectors per block(%u) log sectorsize(%u)\",\n\t\t\tle32_to_cpu(raw_super->log_sectors_per_block),\n\t\t\tle32_to_cpu(raw_super->log_sectorsize));\n\t\treturn 1;\n\t}\n\n\t/* check reserved ino info */\n\tif (le32_to_cpu(raw_super->node_ino) != 1 ||\n\t\tle32_to_cpu(raw_super->meta_ino) != 2 ||\n\t\tle32_to_cpu(raw_super->root_ino) != 3) {\n\t\tf2fs_msg(sb, KERN_INFO,\n\t\t\t\"Invalid Fs Meta Ino: node(%u) meta(%u) root(%u)\",\n\t\t\tle32_to_cpu(raw_super->node_ino),\n\t\t\tle32_to_cpu(raw_super->meta_ino),\n\t\t\tle32_to_cpu(raw_super->root_ino));\n\t\treturn 1;\n\t}\n\n\t/* check CP/SIT/NAT/SSA/MAIN_AREA area boundary */\n\tif (sanity_check_area_boundary(sbi, bh))\n\t\treturn 1;\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284'], 'message': 'f2fs: sanity check segment count\n\nF2FS uses 4 bytes to represent block address. As a result, supported\nsize of disk is 16 TB and it equals to 16 * 1024 * 1024 / 2 segments.\n\nSigned-off-by: Jin Qian \nSigned-off-by: Jaegeuk Kim '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static MagickBooleanType ProcessMSLScript(const ImageInfo *image_info,\n Image **image,ExceptionInfo *exception)\n{\n char\n message[MagickPathExtent];\n\n Image\n *msl_image;\n\n int\n status;\n\n ssize_t\n n;\n\n MSLInfo\n msl_info;\n\n xmlSAXHandler\n sax_modules;\n\n xmlSAXHandlerPtr\n sax_handler;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(image != (Image **) NULL);\n msl_image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,msl_image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n ThrowFileException(exception,FileOpenError,\"UnableToOpenFile\",\n msl_image->filename);\n msl_image=DestroyImageList(msl_image);\n return(MagickFalse);\n }\n msl_image->columns=1;\n msl_image->rows=1;\n /*\n Parse MSL file.\n */\n (void) ResetMagickMemory(&msl_info,0,sizeof(msl_info));\n msl_info.exception=exception;\n msl_info.image_info=(ImageInfo **) AcquireMagickMemory(\n sizeof(*msl_info.image_info));\n msl_info.draw_info=(DrawInfo **) AcquireMagickMemory(\n sizeof(*msl_info.draw_info));\n /* top of the stack is the MSL file itself */\n msl_info.image=(Image **) AcquireMagickMemory(sizeof(*msl_info.image));\n msl_info.attributes=(Image **) AcquireMagickMemory(\n sizeof(*msl_info.attributes));\n msl_info.group_info=(MSLGroupInfo *) AcquireMagickMemory(\n sizeof(*msl_info.group_info));\n if ((msl_info.image_info == (ImageInfo **) NULL) ||\n (msl_info.image == (Image **) NULL) ||\n (msl_info.attributes == (Image **) NULL) ||\n (msl_info.group_info == (MSLGroupInfo *) NULL))\n ThrowFatalException(ResourceLimitFatalError,\"UnableToInterpretMSLImage\");\n *msl_info.image_info=CloneImageInfo(image_info);\n *msl_info.draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);\n *msl_info.attributes=AcquireImage(image_info,exception);\n msl_info.group_info[0].numImages=0;\n /* the first slot is used to point to the MSL file image */\n *msl_info.image=msl_image;\n if (*image != (Image *) NULL)\n MSLPushImage(&msl_info,*image);\n (void) xmlSubstituteEntitiesDefault(1);\n (void) ResetMagickMemory(&sax_modules,0,sizeof(sax_modules));\n sax_modules.internalSubset=MSLInternalSubset;\n sax_modules.isStandalone=MSLIsStandalone;\n sax_modules.hasInternalSubset=MSLHasInternalSubset;\n sax_modules.hasExternalSubset=MSLHasExternalSubset;\n sax_modules.resolveEntity=MSLResolveEntity;\n sax_modules.getEntity=MSLGetEntity;\n sax_modules.entityDecl=MSLEntityDeclaration;\n sax_modules.notationDecl=MSLNotationDeclaration;\n sax_modules.attributeDecl=MSLAttributeDeclaration;\n sax_modules.elementDecl=MSLElementDeclaration;\n sax_modules.unparsedEntityDecl=MSLUnparsedEntityDeclaration;\n sax_modules.setDocumentLocator=MSLSetDocumentLocator;\n sax_modules.startDocument=MSLStartDocument;\n sax_modules.endDocument=MSLEndDocument;\n sax_modules.startElement=MSLStartElement;\n sax_modules.endElement=MSLEndElement;\n sax_modules.reference=MSLReference;\n sax_modules.characters=MSLCharacters;\n sax_modules.ignorableWhitespace=MSLIgnorableWhitespace;\n sax_modules.processingInstruction=MSLProcessingInstructions;\n sax_modules.comment=MSLComment;\n sax_modules.warning=MSLWarning;\n sax_modules.error=MSLError;\n sax_modules.fatalError=MSLError;\n sax_modules.getParameterEntity=MSLGetParameterEntity;\n sax_modules.cdataBlock=MSLCDataBlock;\n sax_modules.externalSubset=MSLExternalSubset;\n sax_handler=(&sax_modules);\n msl_info.parser=xmlCreatePushParserCtxt(sax_handler,&msl_info,(char *) NULL,0,\n msl_image->filename);\n while (ReadBlobString(msl_image,message) != (char *) NULL)\n {\n n=(ssize_t) strlen(message);\n if (n == 0)\n continue;\n status=xmlParseChunk(msl_info.parser,message,(int) n,MagickFalse);\n if (status != 0)\n break;\n (void) xmlParseChunk(msl_info.parser,\" \",1,MagickFalse);\n if (msl_info.exception->severity >= ErrorException)\n break;\n }\n if (msl_info.exception->severity == UndefinedException)\n (void) xmlParseChunk(msl_info.parser,\" \",1,MagickTrue);\n xmlFreeParserCtxt(msl_info.parser);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"end SAX\");\n msl_info.group_info=(MSLGroupInfo *) RelinquishMagickMemory(\n msl_info.group_info);\n if (*image == (Image *) NULL)\n *image=(*msl_info.image);\n if (msl_info.exception->severity != UndefinedException)\n return(MagickFalse);\n return(MagickTrue);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-772', 'CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/636'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: messageAddArgument(message *m, const char *arg)\n{\n\tint offset;\n\tchar *p;\n\n\tassert(m != NULL);\n\n\tif(arg == NULL)\n\t\treturn;\t/* Note: this is not an error condition */\n\n\twhile(isspace(*arg))\n\t\targ++;\n\n\tif(*arg == '\\0')\n\t\t/* Empty argument? Probably a broken mail client... */\n\t\treturn;\n\n\tcli_dbgmsg(\"messageAddArgument, arg='%s'\\n\", arg);\n\n\tif(!usefulArg(arg))\n\t\treturn;\n\n\tfor(offset = 0; offset < m->numberOfArguments; offset++)\n\t\tif(m->mimeArguments[offset] == NULL)\n\t\t\tbreak;\n\t\telse if(strcasecmp(arg, m->mimeArguments[offset]) == 0)\n\t\t\treturn;\t/* already in there */\n\n\tif(offset == m->numberOfArguments) {\n\t\tchar **q;\n\n\t\tm->numberOfArguments++;\n\t\tq = (char **)cli_realloc(m->mimeArguments, m->numberOfArguments * sizeof(char *));\n\t\tif(q == NULL) {\n\t\t\tm->numberOfArguments--;\n\t\t\treturn;\n\t\t}\n\t\tm->mimeArguments = q;\n\t}\n\n\tp = m->mimeArguments[offset] = rfc2231(arg);\n\tif(!p) {\n\t\t/* problem inside rfc2231() */\n\t\tcli_dbgmsg(\"messageAddArgument, error from rfc2231()\\n\");\n\t\treturn;\n\t}\n\n\tif(strchr(p, '=') == NULL) {\n\t\tif(strncmp(p, \"filename\", 8) == 0) {\n\t\t\t/*\n\t\t\t * FIXME: Bounce message handling is corrupting the in\n\t\t\t * core copies of headers\n\t\t\t */\n\t\t\tcli_dbgmsg(\"Possible data corruption fixed\\n\");\n\t\t\tp[8] = '=';\n\t\t} else {\n\t\t\tif(*p)\n\t\t\t\tcli_dbgmsg(\"messageAddArgument, '%s' contains no '='\\n\", p);\n\t\t\tfree(m->mimeArguments[offset]);\n\t\t\tm->mimeArguments[offset] = NULL;\n\t\t\treturn;\n\t\t}\n\t}\n\n\t/*\n\t * This is terribly broken from an RFC point of view but is useful\n\t * for catching viruses which have a filename but no type of\n\t * mime. By pretending defaulting to an application rather than\n\t * to nomime we can ensure they're saved and scanned\n\t */\n\tif((strncasecmp(p, \"filename=\", 9) == 0) || (strncasecmp(p, \"name=\", 5) == 0))\n\t\tif(messageGetMimeType(m) == NOMIME) {\n\t\t\tcli_dbgmsg(\"Force mime encoding to application\\n\");\n\t\t\tmessageSetMimeType(m, \"application\");\n\t\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'bb11797 - fix invalid read in fuzzed mail file.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER)\n{\n\tconst unsigned char *cursor, *limit, *marker, *start;\n\tzval *rval_ref;\n\n\tlimit = max;\n\tcursor = *p;\n\n\tif (YYCURSOR >= YYLIMIT) {\n\t\treturn 0;\n\t}\n\n\tif (var_hash && (*p)[0] != 'R') {\n\t\tvar_push(var_hash, rval);\n\t}\n\n\tstart = cursor;\n\n\n#line 585 \"ext/standard/var_unserializer.c\"\n{\n\tYYCTYPE yych;\n\tstatic const unsigned char yybm[] = {\n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t128, 128, 128, 128, 128, 128, 128, 128, \n\t\t128, 128, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t};\n\tif ((YYLIMIT - YYCURSOR) < 7) YYFILL(7);\n\tyych = *YYCURSOR;\n\tswitch (yych) {\n\tcase 'C':\n\tcase 'O':\tgoto yy13;\n\tcase 'N':\tgoto yy5;\n\tcase 'R':\tgoto yy2;\n\tcase 'S':\tgoto yy10;\n\tcase 'a':\tgoto yy11;\n\tcase 'b':\tgoto yy6;\n\tcase 'd':\tgoto yy8;\n\tcase 'i':\tgoto yy7;\n\tcase 'o':\tgoto yy12;\n\tcase 'r':\tgoto yy4;\n\tcase 's':\tgoto yy9;\n\tcase '}':\tgoto yy14;\n\tdefault:\tgoto yy16;\n\t}\nyy2:\n\tyych = *(YYMARKER = ++YYCURSOR);\n\tif (yych == ':') goto yy95;\nyy3:\n#line 962 \"ext/standard/var_unserializer.re\"\n\t{ return 0; }\n#line 646 \"ext/standard/var_unserializer.c\"\nyy4:\n\tyych = *(YYMARKER = ++YYCURSOR);\n\tif (yych == ':') goto yy89;\n\tgoto yy3;\nyy5:\n\tyych = *++YYCURSOR;\n\tif (yych == ';') goto yy87;\n\tgoto yy3;\nyy6:\n\tyych = *(YYMARKER = ++YYCURSOR);\n\tif (yych == ':') goto yy83;\n\tgoto yy3;\nyy7:\n\tyych = *(YYMARKER = ++YYCURSOR);\n\tif (yych == ':') goto yy77;\n\tgoto yy3;\nyy8:\n\tyych = *(YYMARKER = ++YYCURSOR);\n\tif (yych == ':') goto yy53;\n\tgoto yy3;\nyy9:\n\tyych = *(YYMARKER = ++YYCURSOR);\n\tif (yych == ':') goto yy46;\n\tgoto yy3;\nyy10:\n\tyych = *(YYMARKER = ++YYCURSOR);\n\tif (yych == ':') goto yy39;\n\tgoto yy3;\nyy11:\n\tyych = *(YYMARKER = ++YYCURSOR);\n\tif (yych == ':') goto yy32;\n\tgoto yy3;\nyy12:\n\tyych = *(YYMARKER = ++YYCURSOR);\n\tif (yych == ':') goto yy25;\n\tgoto yy3;\nyy13:\n\tyych = *(YYMARKER = ++YYCURSOR);\n\tif (yych == ':') goto yy17;\n\tgoto yy3;\nyy14:\n\t++YYCURSOR;\n#line 956 \"ext/standard/var_unserializer.re\"\n\t{\n\t/* this is the case where we have less data than planned */\n\tphp_error_docref(NULL, E_NOTICE, \"Unexpected end of serialized data\");\n\treturn 0; /* not sure if it should be 0 or 1 here? */\n}\n#line 695 \"ext/standard/var_unserializer.c\"\nyy16:\n\tyych = *++YYCURSOR;\n\tgoto yy3;\nyy17:\n\tyych = *++YYCURSOR;\n\tif (yybm[0+yych] & 128) {\n\t\tgoto yy20;\n\t}\n\tif (yych == '+') goto yy19;\nyy18:\n\tYYCURSOR = YYMARKER;\n\tgoto yy3;\nyy19:\n\tyych = *++YYCURSOR;\n\tif (yybm[0+yych] & 128) {\n\t\tgoto yy20;\n\t}\n\tgoto yy18;\nyy20:\n\t++YYCURSOR;\n\tif ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);\n\tyych = *YYCURSOR;\n\tif (yybm[0+yych] & 128) {\n\t\tgoto yy20;\n\t}\n\tif (yych <= '/') goto yy18;\n\tif (yych >= ';') goto yy18;\n\tyych = *++YYCURSOR;\n\tif (yych != '\"') goto yy18;\n\t++YYCURSOR;\n#line 804 \"ext/standard/var_unserializer.re\"\n\t{\n\tsize_t len, len2, len3, maxlen;\n\tzend_long elements;\n\tchar *str;\n\tzend_string *class_name;\n\tzend_class_entry *ce;\n\tint incomplete_class = 0;\n\n\tint custom_object = 0;\n\n\tzval user_func;\n\tzval retval;\n\tzval args[1];\n\n if (!var_hash) return 0;\n\tif (*start == 'C') {\n\t\tcustom_object = 1;\n\t}\n\n\tlen2 = len = parse_uiv(start + 2);\n\tmaxlen = max - YYCURSOR;\n\tif (maxlen < len || len == 0) {\n\t\t*p = start + 2;\n\t\treturn 0;\n\t}\n\n\tstr = (char*)YYCURSOR;\n\n\tYYCURSOR += len;\n\n\tif (*(YYCURSOR) != '\"') {\n\t\t*p = YYCURSOR;\n\t\treturn 0;\n\t}\n\tif (*(YYCURSOR+1) != ':') {\n\t\t*p = YYCURSOR+1;\n\t\treturn 0;\n\t}\n\n\tlen3 = strspn(str, \"0123456789_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\\177\\200\\201\\202\\203\\204\\205\\206\\207\\210\\211\\212\\213\\214\\215\\216\\217\\220\\221\\222\\223\\224\\225\\226\\227\\230\\231\\232\\233\\234\\235\\236\\237\\240\\241\\242\\243\\244\\245\\246\\247\\250\\251\\252\\253\\254\\255\\256\\257\\260\\261\\262\\263\\264\\265\\266\\267\\270\\271\\272\\273\\274\\275\\276\\277\\300\\301\\302\\303\\304\\305\\306\\307\\310\\311\\312\\313\\314\\315\\316\\317\\320\\321\\322\\323\\324\\325\\326\\327\\330\\331\\332\\333\\334\\335\\336\\337\\340\\341\\342\\343\\344\\345\\346\\347\\350\\351\\352\\353\\354\\355\\356\\357\\360\\361\\362\\363\\364\\365\\366\\367\\370\\371\\372\\373\\374\\375\\376\\377\\\\\");\n\tif (len3 != len)\n\t{\n\t\t*p = YYCURSOR + len3 - len;\n\t\treturn 0;\n\t}\n\n\tclass_name = zend_string_init(str, len, 0);\n\n\tdo {\n\t\tif(!unserialize_allowed_class(class_name, classes)) {\n\t\t\tincomplete_class = 1;\n\t\t\tce = PHP_IC_ENTRY;\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Try to find class directly */\n\t\tBG(serialize_lock)++;\n\t\tce = zend_lookup_class(class_name);\n\t\tif (ce) {\n\t\t\tBG(serialize_lock)--;\n\t\t\tif (EG(exception)) {\n\t\t\t\tzend_string_release(class_name);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tBG(serialize_lock)--;\n\n\t\tif (EG(exception)) {\n\t\t\tzend_string_release(class_name);\n\t\t\treturn 0;\n\t\t}\n\n\t\t/* Check for unserialize callback */\n\t\tif ((PG(unserialize_callback_func) == NULL) || (PG(unserialize_callback_func)[0] == '\\0')) {\n\t\t\tincomplete_class = 1;\n\t\t\tce = PHP_IC_ENTRY;\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Call unserialize callback */\n\t\tZVAL_STRING(&user_func, PG(unserialize_callback_func));\n\n\t\tZVAL_STR_COPY(&args[0], class_name);\n\t\tBG(serialize_lock)++;\n\t\tif (call_user_function_ex(CG(function_table), NULL, &user_func, &retval, 1, args, 0, NULL) != SUCCESS) {\n\t\t\tBG(serialize_lock)--;\n\t\t\tif (EG(exception)) {\n\t\t\t\tzend_string_release(class_name);\n\t\t\t\tzval_ptr_dtor(&user_func);\n\t\t\t\tzval_ptr_dtor(&args[0]);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tphp_error_docref(NULL, E_WARNING, \"defined (%s) but not found\", Z_STRVAL(user_func));\n\t\t\tincomplete_class = 1;\n\t\t\tce = PHP_IC_ENTRY;\n\t\t\tzval_ptr_dtor(&user_func);\n\t\t\tzval_ptr_dtor(&args[0]);\n\t\t\tbreak;\n\t\t}\n\t\tBG(serialize_lock)--;\n\t\tzval_ptr_dtor(&retval);\n\t\tif (EG(exception)) {\n\t\t\tzend_string_release(class_name);\n\t\t\tzval_ptr_dtor(&user_func);\n\t\t\tzval_ptr_dtor(&args[0]);\n\t\t\treturn 0;\n\t\t}\n\n\t\t/* The callback function may have defined the class */\n\t\tBG(serialize_lock)++;\n\t\tif ((ce = zend_lookup_class(class_name)) == NULL) {\n\t\t\tphp_error_docref(NULL, E_WARNING, \"Function %s() hasn't defined the class it was called for\", Z_STRVAL(user_func));\n\t\t\tincomplete_class = 1;\n\t\t\tce = PHP_IC_ENTRY;\n\t\t}\n\t\tBG(serialize_lock)--;\n\n\t\tzval_ptr_dtor(&user_func);\n\t\tzval_ptr_dtor(&args[0]);\n\t\tbreak;\n\t} while (1);\n\n\t*p = YYCURSOR;\n\n\tif (custom_object) {\n\t\tint ret;\n\n\t\tret = object_custom(UNSERIALIZE_PASSTHRU, ce);\n\n\t\tif (ret && incomplete_class) {\n\t\t\tphp_store_class_name(rval, ZSTR_VAL(class_name), len2);\n\t\t}\n\t\tzend_string_release(class_name);\n\t\treturn ret;\n\t}\n\n\telements = object_common1(UNSERIALIZE_PASSTHRU, ce);\n\n\tif (elements < 0) {\n\t zend_string_release(class_name);\n\t return 0;\n\t}\n\n\tif (incomplete_class) {\n\t\tphp_store_class_name(rval, ZSTR_VAL(class_name), len2);\n\t}\n\tzend_string_release(class_name);\n\n\treturn object_common2(UNSERIALIZE_PASSTHRU, elements);\n}\n#line 878 \"ext/standard/var_unserializer.c\"\nyy25:\n\tyych = *++YYCURSOR;\n\tif (yych <= ',') {\n\t\tif (yych != '+') goto yy18;\n\t} else {\n\t\tif (yych <= '-') goto yy26;\n\t\tif (yych <= '/') goto yy18;\n\t\tif (yych <= '9') goto yy27;\n\t\tgoto yy18;\n\t}\nyy26:\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy18;\n\tif (yych >= ':') goto yy18;\nyy27:\n\t++YYCURSOR;\n\tif ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);\n\tyych = *YYCURSOR;\n\tif (yych <= '/') goto yy18;\n\tif (yych <= '9') goto yy27;\n\tif (yych >= ';') goto yy18;\n\tyych = *++YYCURSOR;\n\tif (yych != '\"') goto yy18;\n\t++YYCURSOR;\n#line 793 \"ext/standard/var_unserializer.re\"\n\t{\n\tzend_long elements;\n if (!var_hash) return 0;\n\n\telements = object_common1(UNSERIALIZE_PASSTHRU, ZEND_STANDARD_CLASS_DEF_PTR);\n\tif (elements < 0 || elements >= HT_MAX_SIZE) {\n\t\treturn 0;\n\t}\n\treturn object_common2(UNSERIALIZE_PASSTHRU, elements);\n}\n#line 914 \"ext/standard/var_unserializer.c\"\nyy32:\n\tyych = *++YYCURSOR;\n\tif (yych == '+') goto yy33;\n\tif (yych <= '/') goto yy18;\n\tif (yych <= '9') goto yy34;\n\tgoto yy18;\nyy33:\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy18;\n\tif (yych >= ':') goto yy18;\nyy34:\n\t++YYCURSOR;\n\tif ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);\n\tyych = *YYCURSOR;\n\tif (yych <= '/') goto yy18;\n\tif (yych <= '9') goto yy34;\n\tif (yych >= ';') goto yy18;\n\tyych = *++YYCURSOR;\n\tif (yych != '{') goto yy18;\n\t++YYCURSOR;\n#line 769 \"ext/standard/var_unserializer.re\"\n\t{\n\tzend_long elements = parse_iv(start + 2);\n\t/* use iv() not uiv() in order to check data range */\n\t*p = YYCURSOR;\n if (!var_hash) return 0;\n\n\tif (elements < 0 || elements >= HT_MAX_SIZE) {\n\t\treturn 0;\n\t}\n\n\tarray_init_size(rval, elements);\n\tif (elements) {\n\t\t/* we can't convert from packed to hash during unserialization, because\n\t\t reference to some zvals might be keept in var_hash (to support references) */\n\t\tzend_hash_real_init(Z_ARRVAL_P(rval), 0);\n\t}\n\n\tif (!process_nested_data(UNSERIALIZE_PASSTHRU, Z_ARRVAL_P(rval), elements, 0)) {\n\t\treturn 0;\n\t}\n\n\treturn finish_nested_data(UNSERIALIZE_PASSTHRU);\n}\n#line 959 \"ext/standard/var_unserializer.c\"\nyy39:\n\tyych = *++YYCURSOR;\n\tif (yych == '+') goto yy40;\n\tif (yych <= '/') goto yy18;\n\tif (yych <= '9') goto yy41;\n\tgoto yy18;\nyy40:\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy18;\n\tif (yych >= ':') goto yy18;\nyy41:\n\t++YYCURSOR;\n\tif ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);\n\tyych = *YYCURSOR;\n\tif (yych <= '/') goto yy18;\n\tif (yych <= '9') goto yy41;\n\tif (yych >= ';') goto yy18;\n\tyych = *++YYCURSOR;\n\tif (yych != '\"') goto yy18;\n\t++YYCURSOR;\n#line 735 \"ext/standard/var_unserializer.re\"\n\t{\n\tsize_t len, maxlen;\n\tzend_string *str;\n\n\tlen = parse_uiv(start + 2);\n\tmaxlen = max - YYCURSOR;\n\tif (maxlen < len) {\n\t\t*p = start + 2;\n\t\treturn 0;\n\t}\n\n\tif ((str = unserialize_str(&YYCURSOR, len, maxlen)) == NULL) {\n\t\treturn 0;\n\t}\n\n\tif (*(YYCURSOR) != '\"') {\n\t\tzend_string_free(str);\n\t\t*p = YYCURSOR;\n\t\treturn 0;\n\t}\n\n\tif (*(YYCURSOR + 1) != ';') {\n\t\tefree(str);\n\t\t*p = YYCURSOR + 1;\n\t\treturn 0;\n\t}\n\n\tYYCURSOR += 2;\n\t*p = YYCURSOR;\n\n\tZVAL_STR(rval, str);\n\treturn 1;\n}\n#line 1014 \"ext/standard/var_unserializer.c\"\nyy46:\n\tyych = *++YYCURSOR;\n\tif (yych == '+') goto yy47;\n\tif (yych <= '/') goto yy18;\n\tif (yych <= '9') goto yy48;\n\tgoto yy18;\nyy47:\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy18;\n\tif (yych >= ':') goto yy18;\nyy48:\n\t++YYCURSOR;\n\tif ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);\n\tyych = *YYCURSOR;\n\tif (yych <= '/') goto yy18;\n\tif (yych <= '9') goto yy48;\n\tif (yych >= ';') goto yy18;\n\tyych = *++YYCURSOR;\n\tif (yych != '\"') goto yy18;\n\t++YYCURSOR;\n#line 703 \"ext/standard/var_unserializer.re\"\n\t{\n\tsize_t len, maxlen;\n\tchar *str;\n\n\tlen = parse_uiv(start + 2);\n\tmaxlen = max - YYCURSOR;\n\tif (maxlen < len) {\n\t\t*p = start + 2;\n\t\treturn 0;\n\t}\n\n\tstr = (char*)YYCURSOR;\n\n\tYYCURSOR += len;\n\n\tif (*(YYCURSOR) != '\"') {\n\t\t*p = YYCURSOR;\n\t\treturn 0;\n\t}\n\n\tif (*(YYCURSOR + 1) != ';') {\n\t\t*p = YYCURSOR + 1;\n\t\treturn 0;\n\t}\n\n\tYYCURSOR += 2;\n\t*p = YYCURSOR;\n\n\tZVAL_STRINGL(rval, str, len);\n\treturn 1;\n}\n#line 1067 \"ext/standard/var_unserializer.c\"\nyy53:\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') {\n\t\tif (yych <= ',') {\n\t\t\tif (yych == '+') goto yy57;\n\t\t\tgoto yy18;\n\t\t} else {\n\t\t\tif (yych <= '-') goto yy55;\n\t\t\tif (yych <= '.') goto yy60;\n\t\t\tgoto yy18;\n\t\t}\n\t} else {\n\t\tif (yych <= 'I') {\n\t\t\tif (yych <= '9') goto yy58;\n\t\t\tif (yych <= 'H') goto yy18;\n\t\t\tgoto yy56;\n\t\t} else {\n\t\t\tif (yych != 'N') goto yy18;\n\t\t}\n\t}\n\tyych = *++YYCURSOR;\n\tif (yych == 'A') goto yy76;\n\tgoto yy18;\nyy55:\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') {\n\t\tif (yych == '.') goto yy60;\n\t\tgoto yy18;\n\t} else {\n\t\tif (yych <= '9') goto yy58;\n\t\tif (yych != 'I') goto yy18;\n\t}\nyy56:\n\tyych = *++YYCURSOR;\n\tif (yych == 'N') goto yy72;\n\tgoto yy18;\nyy57:\n\tyych = *++YYCURSOR;\n\tif (yych == '.') goto yy60;\n\tif (yych <= '/') goto yy18;\n\tif (yych >= ':') goto yy18;\nyy58:\n\t++YYCURSOR;\n\tif ((YYLIMIT - YYCURSOR) < 4) YYFILL(4);\n\tyych = *YYCURSOR;\n\tif (yych <= ':') {\n\t\tif (yych <= '.') {\n\t\t\tif (yych <= '-') goto yy18;\n\t\t\tgoto yy70;\n\t\t} else {\n\t\t\tif (yych <= '/') goto yy18;\n\t\t\tif (yych <= '9') goto yy58;\n\t\t\tgoto yy18;\n\t\t}\n\t} else {\n\t\tif (yych <= 'E') {\n\t\t\tif (yych <= ';') goto yy63;\n\t\t\tif (yych <= 'D') goto yy18;\n\t\t\tgoto yy65;\n\t\t} else {\n\t\t\tif (yych == 'e') goto yy65;\n\t\t\tgoto yy18;\n\t\t}\n\t}\nyy60:\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy18;\n\tif (yych >= ':') goto yy18;\nyy61:\n\t++YYCURSOR;\n\tif ((YYLIMIT - YYCURSOR) < 4) YYFILL(4);\n\tyych = *YYCURSOR;\n\tif (yych <= ';') {\n\t\tif (yych <= '/') goto yy18;\n\t\tif (yych <= '9') goto yy61;\n\t\tif (yych <= ':') goto yy18;\n\t} else {\n\t\tif (yych <= 'E') {\n\t\t\tif (yych <= 'D') goto yy18;\n\t\t\tgoto yy65;\n\t\t} else {\n\t\t\tif (yych == 'e') goto yy65;\n\t\t\tgoto yy18;\n\t\t}\n\t}\nyy63:\n\t++YYCURSOR;\n#line 694 \"ext/standard/var_unserializer.re\"\n\t{\n#if SIZEOF_ZEND_LONG == 4\nuse_double:\n#endif\n\t*p = YYCURSOR;\n\tZVAL_DOUBLE(rval, zend_strtod((const char *)start + 2, NULL));\n\treturn 1;\n}\n#line 1164 \"ext/standard/var_unserializer.c\"\nyy65:\n\tyych = *++YYCURSOR;\n\tif (yych <= ',') {\n\t\tif (yych != '+') goto yy18;\n\t} else {\n\t\tif (yych <= '-') goto yy66;\n\t\tif (yych <= '/') goto yy18;\n\t\tif (yych <= '9') goto yy67;\n\t\tgoto yy18;\n\t}\nyy66:\n\tyych = *++YYCURSOR;\n\tif (yych <= ',') {\n\t\tif (yych == '+') goto yy69;\n\t\tgoto yy18;\n\t} else {\n\t\tif (yych <= '-') goto yy69;\n\t\tif (yych <= '/') goto yy18;\n\t\tif (yych >= ':') goto yy18;\n\t}\nyy67:\n\t++YYCURSOR;\n\tif (YYLIMIT <= YYCURSOR) YYFILL(1);\n\tyych = *YYCURSOR;\n\tif (yych <= '/') goto yy18;\n\tif (yych <= '9') goto yy67;\n\tif (yych == ';') goto yy63;\n\tgoto yy18;\nyy69:\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy18;\n\tif (yych <= '9') goto yy67;\n\tgoto yy18;\nyy70:\n\t++YYCURSOR;\n\tif ((YYLIMIT - YYCURSOR) < 4) YYFILL(4);\n\tyych = *YYCURSOR;\n\tif (yych <= ';') {\n\t\tif (yych <= '/') goto yy18;\n\t\tif (yych <= '9') goto yy70;\n\t\tif (yych <= ':') goto yy18;\n\t\tgoto yy63;\n\t} else {\n\t\tif (yych <= 'E') {\n\t\t\tif (yych <= 'D') goto yy18;\n\t\t\tgoto yy65;\n\t\t} else {\n\t\t\tif (yych == 'e') goto yy65;\n\t\t\tgoto yy18;\n\t\t}\n\t}\nyy72:\n\tyych = *++YYCURSOR;\n\tif (yych != 'F') goto yy18;\nyy73:\n\tyych = *++YYCURSOR;\n\tif (yych != ';') goto yy18;\n\t++YYCURSOR;\n#line 678 \"ext/standard/var_unserializer.re\"\n\t{\n\t*p = YYCURSOR;\n\n\tif (!strncmp((char*)start + 2, \"NAN\", 3)) {\n\t\tZVAL_DOUBLE(rval, php_get_nan());\n\t} else if (!strncmp((char*)start + 2, \"INF\", 3)) {\n\t\tZVAL_DOUBLE(rval, php_get_inf());\n\t} else if (!strncmp((char*)start + 2, \"-INF\", 4)) {\n\t\tZVAL_DOUBLE(rval, -php_get_inf());\n\t} else {\n\t\tZVAL_NULL(rval);\n\t}\n\n\treturn 1;\n}\n#line 1239 \"ext/standard/var_unserializer.c\"\nyy76:\n\tyych = *++YYCURSOR;\n\tif (yych == 'N') goto yy73;\n\tgoto yy18;\nyy77:\n\tyych = *++YYCURSOR;\n\tif (yych <= ',') {\n\t\tif (yych != '+') goto yy18;\n\t} else {\n\t\tif (yych <= '-') goto yy78;\n\t\tif (yych <= '/') goto yy18;\n\t\tif (yych <= '9') goto yy79;\n\t\tgoto yy18;\n\t}\nyy78:\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy18;\n\tif (yych >= ':') goto yy18;\nyy79:\n\t++YYCURSOR;\n\tif (YYLIMIT <= YYCURSOR) YYFILL(1);\n\tyych = *YYCURSOR;\n\tif (yych <= '/') goto yy18;\n\tif (yych <= '9') goto yy79;\n\tif (yych != ';') goto yy18;\n\t++YYCURSOR;\n#line 652 \"ext/standard/var_unserializer.re\"\n\t{\n#if SIZEOF_ZEND_LONG == 4\n\tint digits = YYCURSOR - start - 3;\n\n\tif (start[2] == '-' || start[2] == '+') {\n\t\tdigits--;\n\t}\n\n\t/* Use double for large zend_long values that were serialized on a 64-bit system */\n\tif (digits >= MAX_LENGTH_OF_LONG - 1) {\n\t\tif (digits == MAX_LENGTH_OF_LONG - 1) {\n\t\t\tint cmp = strncmp((char*)YYCURSOR - MAX_LENGTH_OF_LONG, long_min_digits, MAX_LENGTH_OF_LONG - 1);\n\n\t\t\tif (!(cmp < 0 || (cmp == 0 && start[2] == '-'))) {\n\t\t\t\tgoto use_double;\n\t\t\t}\n\t\t} else {\n\t\t\tgoto use_double;\n\t\t}\n\t}\n#endif\n\t*p = YYCURSOR;\n\tZVAL_LONG(rval, parse_iv(start + 2));\n\treturn 1;\n}\n#line 1292 \"ext/standard/var_unserializer.c\"\nyy83:\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy18;\n\tif (yych >= '2') goto yy18;\n\tyych = *++YYCURSOR;\n\tif (yych != ';') goto yy18;\n\t++YYCURSOR;\n#line 646 \"ext/standard/var_unserializer.re\"\n\t{\n\t*p = YYCURSOR;\n\tZVAL_BOOL(rval, parse_iv(start + 2));\n\treturn 1;\n}\n#line 1306 \"ext/standard/var_unserializer.c\"\nyy87:\n\t++YYCURSOR;\n#line 640 \"ext/standard/var_unserializer.re\"\n\t{\n\t*p = YYCURSOR;\n\tZVAL_NULL(rval);\n\treturn 1;\n}\n#line 1315 \"ext/standard/var_unserializer.c\"\nyy89:\n\tyych = *++YYCURSOR;\n\tif (yych <= ',') {\n\t\tif (yych != '+') goto yy18;\n\t} else {\n\t\tif (yych <= '-') goto yy90;\n\t\tif (yych <= '/') goto yy18;\n\t\tif (yych <= '9') goto yy91;\n\t\tgoto yy18;\n\t}\nyy90:\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy18;\n\tif (yych >= ':') goto yy18;\nyy91:\n\t++YYCURSOR;\n\tif (YYLIMIT <= YYCURSOR) YYFILL(1);\n\tyych = *YYCURSOR;\n\tif (yych <= '/') goto yy18;\n\tif (yych <= '9') goto yy91;\n\tif (yych != ';') goto yy18;\n\t++YYCURSOR;\n#line 615 \"ext/standard/var_unserializer.re\"\n\t{\n\tzend_long id;\n\n \t*p = YYCURSOR;\n\tif (!var_hash) return 0;\n\n\tid = parse_iv(start + 2) - 1;\n\tif (id == -1 || (rval_ref = var_access(var_hash, id)) == NULL) {\n\t\treturn 0;\n\t}\n\n\tif (rval_ref == rval) {\n\t\treturn 0;\n\t}\n\n\tif (Z_ISUNDEF_P(rval_ref) || (Z_ISREF_P(rval_ref) && Z_ISUNDEF_P(Z_REFVAL_P(rval_ref)))) {\n\t\tZVAL_UNDEF(rval);\n\t\treturn 1;\n\t}\n\n\tZVAL_COPY(rval, rval_ref);\n\n\treturn 1;\n}\n#line 1363 \"ext/standard/var_unserializer.c\"\nyy95:\n\tyych = *++YYCURSOR;\n\tif (yych <= ',') {\n\t\tif (yych != '+') goto yy18;\n\t} else {\n\t\tif (yych <= '-') goto yy96;\n\t\tif (yych <= '/') goto yy18;\n\t\tif (yych <= '9') goto yy97;\n\t\tgoto yy18;\n\t}\nyy96:\n\tyych = *++YYCURSOR;\n\tif (yych <= '/') goto yy18;\n\tif (yych >= ':') goto yy18;\nyy97:\n\t++YYCURSOR;\n\tif (YYLIMIT <= YYCURSOR) YYFILL(1);\n\tyych = *YYCURSOR;\n\tif (yych <= '/') goto yy18;\n\tif (yych <= '9') goto yy97;\n\tif (yych != ';') goto yy18;\n\t++YYCURSOR;\n#line 589 \"ext/standard/var_unserializer.re\"\n\t{\n\tzend_long id;\n\n \t*p = YYCURSOR;\n\tif (!var_hash) return 0;\n\n\tid = parse_iv(start + 2) - 1;\n\tif (id == -1 || (rval_ref = var_access(var_hash, id)) == NULL) {\n\t\treturn 0;\n\t}\n\n\tzval_ptr_dtor(rval);\n\tif (Z_ISUNDEF_P(rval_ref) || (Z_ISREF_P(rval_ref) && Z_ISUNDEF_P(Z_REFVAL_P(rval_ref)))) {\n\t\tZVAL_UNDEF(rval);\n\t\treturn 1;\n\t}\n\tif (Z_ISREF_P(rval_ref)) {\n\t\tZVAL_COPY(rval, rval_ref);\n\t} else {\n\t\tZVAL_NEW_REF(rval_ref, rval_ref);\n\t\tZVAL_COPY(rval, rval_ref);\n\t}\n\n\treturn 1;\n}\n#line 1412 \"ext/standard/var_unserializer.c\"\n}\n#line 964 \"ext/standard/var_unserializer.re\"\n\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Fixed bug #74103 and bug #75054\n\nDirectly fail unserialization when trying to acquire an r/R\nreference to an UNDEF HT slot. Previously this left an UNDEF and\nlater deleted the index/key from the HT.\n\nWhat actually caused the issue here is a combination of two\nfactors: First, the key deletion was performed using the hash API,\nrather than the symtable API, such that the element was not actually\nremoved if it used an integral string key. Second, a subsequent\ndeletion operation, while collecting trailing UNDEF ranges, would\nmark the element as available for reuse (leaving a corrupted HT\nstate with nNumOfElemnts > nNumUsed).\n\nFix this by failing early and dropping the deletion code.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static MagickBooleanType WritePDFImage(const ImageInfo *image_info,Image *image,\n ExceptionInfo *exception)\n{\n#define CFormat \"/Filter [ /%s ]\\n\"\n#define ObjectsPerImage 14\n\nDisableMSCWarning(4310)\n static const char\n XMPProfile[]=\n {\n \"\\n\"\n \"\\n\"\n \" \\n\"\n \" \\n\"\n \" %s\\n\"\n \" %s\\n\"\n \" %s\\n\"\n \" %s\\n\"\n \" \\n\"\n \" \\n\"\n \" application/pdf\\n\"\n \" \\n\"\n \" \\n\"\n \" %s\\n\"\n \" \\n\"\n \" \\n\"\n \" \\n\"\n \" \\n\"\n \" uuid:6ec119d7-7982-4f56-808d-dfe64f5b35cf\\n\"\n \" uuid:a79b99b4-6235-447f-9f6c-ec18ef7555cb\\n\"\n \" \\n\"\n \" \\n\"\n \" %s\\n\"\n \" \\n\"\n \" \\n\"\n \" 3\\n\"\n \" B\\n\"\n \" \\n\"\n \" \\n\"\n \"\\n\"\n \"\\n\"\n },\n XMPProfileMagick[4]= { (char) 0xef, (char) 0xbb, (char) 0xbf, (char) 0x00 };\nRestoreMSCWarning\n\n char\n basename[MagickPathExtent],\n buffer[MagickPathExtent],\n *escape,\n date[MagickPathExtent],\n **labels,\n page_geometry[MagickPathExtent],\n *url;\n\n CompressionType\n compression;\n\n const char\n *device,\n *option,\n *value;\n\n const StringInfo\n *profile;\n\n double\n pointsize;\n\n GeometryInfo\n geometry_info;\n\n Image\n *next,\n *tile_image;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n offset,\n scene,\n *xref;\n\n MagickSizeType\n number_pixels;\n\n MagickStatusType\n flags;\n\n PointInfo\n delta,\n resolution,\n scale;\n\n RectangleInfo\n geometry,\n media_info,\n page_info;\n\n register const Quantum\n *p;\n\n register unsigned char\n *q;\n\n register ssize_t\n i,\n x;\n\n size_t\n channels,\n info_id,\n length,\n object,\n pages_id,\n root_id,\n text_size,\n version;\n\n ssize_t\n count,\n page_count,\n y;\n\n struct tm\n local_time;\n\n time_t\n seconds;\n\n unsigned char\n *pixels;\n\n wchar_t\n *utf16;\n\n /*\n Open output image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);\n if (status == MagickFalse)\n return(status);\n /*\n Allocate X ref memory.\n */\n xref=(MagickOffsetType *) AcquireQuantumMemory(2048UL,sizeof(*xref));\n if (xref == (MagickOffsetType *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) ResetMagickMemory(xref,0,2048UL*sizeof(*xref));\n /*\n Write Info object.\n */\n object=0;\n version=3;\n if (image_info->compression == JPEG2000Compression)\n version=(size_t) MagickMax(version,5);\n for (next=image; next != (Image *) NULL; next=GetNextImageInList(next))\n if (next->alpha_trait != UndefinedPixelTrait)\n version=(size_t) MagickMax(version,4);\n if (LocaleCompare(image_info->magick,\"PDFA\") == 0)\n version=(size_t) MagickMax(version,6);\n profile=GetImageProfile(image,\"icc\");\n if (profile != (StringInfo *) NULL)\n version=(size_t) MagickMax(version,7);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%%PDF-1.%.20g \\n\",(double)\n version);\n (void) WriteBlobString(image,buffer);\n if (LocaleCompare(image_info->magick,\"PDFA\") == 0)\n {\n (void) WriteBlobByte(image,'%');\n (void) WriteBlobByte(image,0xe2);\n (void) WriteBlobByte(image,0xe3);\n (void) WriteBlobByte(image,0xcf);\n (void) WriteBlobByte(image,0xd3);\n (void) WriteBlobByte(image,'\\n');\n }\n /*\n Write Catalog object.\n */\n xref[object++]=TellBlob(image);\n root_id=object;\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n if (LocaleCompare(image_info->magick,\"PDFA\") != 0)\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Pages %.20g 0 R\\n\",\n (double) object+1);\n else\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Metadata %.20g 0 R\\n\",\n (double) object+1);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Pages %.20g 0 R\\n\",\n (double) object+2);\n }\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"/Type /Catalog\");\n option=GetImageOption(image_info,\"pdf:page-direction\");\n if ((option != (const char *) NULL) &&\n (LocaleCompare(option,\"right-to-left\") != MagickFalse))\n (void) WriteBlobString(image,\"/ViewerPreferences<>\\n\");\n (void) WriteBlobString(image,\"\\n\");\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n GetPathComponent(image->filename,BasePath,basename);\n if (LocaleCompare(image_info->magick,\"PDFA\") == 0)\n {\n char\n create_date[MagickPathExtent],\n modify_date[MagickPathExtent],\n timestamp[MagickPathExtent],\n *url,\n xmp_profile[MagickPathExtent];\n\n /*\n Write XMP object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n (void) WriteBlobString(image,\"/Subtype /XML\\n\");\n *modify_date='\\0';\n value=GetImageProperty(image,\"date:modify\",exception);\n if (value != (const char *) NULL)\n (void) CopyMagickString(modify_date,value,MagickPathExtent);\n *create_date='\\0';\n value=GetImageProperty(image,\"date:create\",exception);\n if (value != (const char *) NULL)\n (void) CopyMagickString(create_date,value,MagickPathExtent);\n (void) FormatMagickTime(time((time_t *) NULL),MagickPathExtent,timestamp);\n url=GetMagickHomeURL();\n escape=EscapeParenthesis(basename);\n i=FormatLocaleString(xmp_profile,MagickPathExtent,XMPProfile,\n XMPProfileMagick,modify_date,create_date,timestamp,url,escape,url);\n escape=DestroyString(escape);\n url=DestroyString(url);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g\\n\",\n (double) i);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"/Type /Metadata\\n\");\n (void) WriteBlobString(image,\">>\\nstream\\n\");\n (void) WriteBlobString(image,xmp_profile);\n (void) WriteBlobString(image,\"\\nendstream\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n }\n /*\n Write Pages object.\n */\n xref[object++]=TellBlob(image);\n pages_id=object;\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n (void) WriteBlobString(image,\"/Type /Pages\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Kids [ %.20g 0 R \",\n (double) object+1);\n (void) WriteBlobString(image,buffer);\n count=(ssize_t) (pages_id+ObjectsPerImage+1);\n page_count=1;\n if (image_info->adjoin != MagickFalse)\n {\n Image\n *kid_image;\n\n /*\n Predict page object id's.\n */\n kid_image=image;\n for ( ; GetNextImageInList(kid_image) != (Image *) NULL; count+=ObjectsPerImage)\n {\n page_count++;\n profile=GetImageProfile(kid_image,\"icc\");\n if (profile != (StringInfo *) NULL)\n count+=2;\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 R \",(double)\n count);\n (void) WriteBlobString(image,buffer);\n kid_image=GetNextImageInList(kid_image);\n }\n xref=(MagickOffsetType *) ResizeQuantumMemory(xref,(size_t) count+2048UL,\n sizeof(*xref));\n if (xref == (MagickOffsetType *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n (void) WriteBlobString(image,\"]\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Count %.20g\\n\",(double)\n page_count);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n scene=0;\n do\n {\n MagickBooleanType\n has_icc_profile;\n\n profile=GetImageProfile(image,\"icc\");\n has_icc_profile=(profile != (StringInfo *) NULL) ? MagickTrue : MagickFalse;\n compression=image->compression;\n if (image_info->compression != UndefinedCompression)\n compression=image_info->compression;\n switch (compression)\n {\n case FaxCompression:\n case Group4Compression:\n {\n if ((SetImageMonochrome(image,exception) == MagickFalse) ||\n (image->alpha_trait != UndefinedPixelTrait))\n compression=RLECompression;\n break;\n }\n#if !defined(MAGICKCORE_JPEG_DELEGATE)\n case JPEGCompression:\n {\n compression=RLECompression;\n (void) ThrowMagickException(exception,GetMagickModule(),\n MissingDelegateError,\"DelegateLibrarySupportNotBuiltIn\",\"`%s' (JPEG)\",\n image->filename);\n break;\n }\n#endif\n#if !defined(MAGICKCORE_LIBOPENJP2_DELEGATE)\n case JPEG2000Compression:\n {\n compression=RLECompression;\n (void) ThrowMagickException(exception,GetMagickModule(),\n MissingDelegateError,\"DelegateLibrarySupportNotBuiltIn\",\"`%s' (JP2)\",\n image->filename);\n break;\n }\n#endif\n#if !defined(MAGICKCORE_ZLIB_DELEGATE)\n case ZipCompression:\n {\n compression=RLECompression;\n (void) ThrowMagickException(exception,GetMagickModule(),\n MissingDelegateError,\"DelegateLibrarySupportNotBuiltIn\",\"`%s' (ZLIB)\",\n image->filename);\n break;\n }\n#endif\n case LZWCompression:\n {\n if (LocaleCompare(image_info->magick,\"PDFA\") == 0)\n compression=RLECompression; /* LZW compression is forbidden */\n break;\n }\n case NoCompression:\n {\n if (LocaleCompare(image_info->magick,\"PDFA\") == 0)\n compression=RLECompression; /* ASCII 85 compression is forbidden */\n break;\n }\n default:\n break;\n }\n if (compression == JPEG2000Compression)\n (void) TransformImageColorspace(image,sRGBColorspace,exception);\n /*\n Scale relative to dots-per-inch.\n */\n delta.x=DefaultResolution;\n delta.y=DefaultResolution;\n resolution.x=image->resolution.x;\n resolution.y=image->resolution.y;\n if ((resolution.x == 0.0) || (resolution.y == 0.0))\n {\n flags=ParseGeometry(PSDensityGeometry,&geometry_info);\n resolution.x=geometry_info.rho;\n resolution.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n resolution.y=resolution.x;\n }\n if (image_info->density != (char *) NULL)\n {\n flags=ParseGeometry(image_info->density,&geometry_info);\n resolution.x=geometry_info.rho;\n resolution.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n resolution.y=resolution.x;\n }\n if (image->units == PixelsPerCentimeterResolution)\n {\n resolution.x=(double) ((size_t) (100.0*2.54*resolution.x+0.5)/100.0);\n resolution.y=(double) ((size_t) (100.0*2.54*resolution.y+0.5)/100.0);\n }\n SetGeometry(image,&geometry);\n (void) FormatLocaleString(page_geometry,MagickPathExtent,\"%.20gx%.20g\",\n (double) image->columns,(double) image->rows);\n if (image_info->page != (char *) NULL)\n (void) CopyMagickString(page_geometry,image_info->page,MagickPathExtent);\n else\n if ((image->page.width != 0) && (image->page.height != 0))\n (void) FormatLocaleString(page_geometry,MagickPathExtent,\n \"%.20gx%.20g%+.20g%+.20g\",(double) image->page.width,(double)\n image->page.height,(double) image->page.x,(double) image->page.y);\n else\n if ((image->gravity != UndefinedGravity) &&\n (LocaleCompare(image_info->magick,\"PDF\") == 0))\n (void) CopyMagickString(page_geometry,PSPageGeometry,\n MagickPathExtent);\n (void) ConcatenateMagickString(page_geometry,\">\",MagickPathExtent);\n (void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y,\n &geometry.width,&geometry.height);\n scale.x=(double) (geometry.width*delta.x)/resolution.x;\n geometry.width=(size_t) floor(scale.x+0.5);\n scale.y=(double) (geometry.height*delta.y)/resolution.y;\n geometry.height=(size_t) floor(scale.y+0.5);\n (void) ParseAbsoluteGeometry(page_geometry,&media_info);\n (void) ParseGravityGeometry(image,page_geometry,&page_info,exception);\n if (image->gravity != UndefinedGravity)\n {\n geometry.x=(-page_info.x);\n geometry.y=(ssize_t) (media_info.height+page_info.y-image->rows);\n }\n pointsize=12.0;\n if (image_info->pointsize != 0.0)\n pointsize=image_info->pointsize;\n text_size=0;\n value=GetImageProperty(image,\"label\",exception);\n if (value != (const char *) NULL)\n text_size=(size_t) (MultilineCensus(value)*pointsize+12);\n (void) text_size;\n /*\n Write Page object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n (void) WriteBlobString(image,\"/Type /Page\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Parent %.20g 0 R\\n\",\n (double) pages_id);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"/Resources <<\\n\");\n labels=(char **) NULL;\n value=GetImageProperty(image,\"label\",exception);\n if (value != (const char *) NULL)\n labels=StringToList(value);\n if (labels != (char **) NULL)\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"/Font << /F%.20g %.20g 0 R >>\\n\",(double) image->scene,(double)\n object+4);\n (void) WriteBlobString(image,buffer);\n }\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"/XObject << /Im%.20g %.20g 0 R >>\\n\",(double) image->scene,(double)\n object+5);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/ProcSet %.20g 0 R >>\\n\",\n (double) object+3);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"/MediaBox [0 0 %g %g]\\n\",72.0*media_info.width/resolution.x,\n 72.0*media_info.height/resolution.y);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"/CropBox [0 0 %g %g]\\n\",72.0*media_info.width/resolution.x,\n 72.0*media_info.height/resolution.y);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Contents %.20g 0 R\\n\",\n (double) object+1);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Thumb %.20g 0 R\\n\",\n (double) object+(has_icc_profile != MagickFalse ? 10 : 8));\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Contents object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g 0 R\\n\",\n (double) object+1);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"stream\\n\");\n offset=TellBlob(image);\n (void) WriteBlobString(image,\"q\\n\");\n if (labels != (char **) NULL)\n for (i=0; labels[i] != (char *) NULL; i++)\n {\n (void) WriteBlobString(image,\"BT\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/F%.20g %g Tf\\n\",\n (double) image->scene,pointsize);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g %.20g Td\\n\",\n (double) geometry.x,(double) (geometry.y+geometry.height+i*pointsize+\n 12));\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"(%s) Tj\\n\",\n labels[i]);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"ET\\n\");\n labels[i]=DestroyString(labels[i]);\n }\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"%g 0 0 %g %.20g %.20g cm\\n\",scale.x,scale.y,(double) geometry.x,\n (double) geometry.y);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Im%.20g Do\\n\",(double)\n image->scene);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"Q\\n\");\n offset=TellBlob(image)-offset;\n (void) WriteBlobString(image,\"\\nendstream\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Length object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double)\n offset);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Procset object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n if ((image->storage_class == DirectClass) || (image->colors > 256))\n (void) CopyMagickString(buffer,\"[ /PDF /Text /ImageC\",MagickPathExtent);\n else\n if ((compression == FaxCompression) || (compression == Group4Compression))\n (void) CopyMagickString(buffer,\"[ /PDF /Text /ImageB\",MagickPathExtent);\n else\n (void) CopyMagickString(buffer,\"[ /PDF /Text /ImageI\",MagickPathExtent);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\" ]\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Font object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n if (labels != (char **) NULL)\n {\n (void) WriteBlobString(image,\"/Type /Font\\n\");\n (void) WriteBlobString(image,\"/Subtype /Type1\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Name /F%.20g\\n\",\n (double) image->scene);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"/BaseFont /Helvetica\\n\");\n (void) WriteBlobString(image,\"/Encoding /MacRomanEncoding\\n\");\n labels=(char **) RelinquishMagickMemory(labels);\n }\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write XObject object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n (void) WriteBlobString(image,\"/Type /XObject\\n\");\n (void) WriteBlobString(image,\"/Subtype /Image\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Name /Im%.20g\\n\",\n (double) image->scene);\n (void) WriteBlobString(image,buffer);\n switch (compression)\n {\n case NoCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"ASCII85Decode\");\n break;\n }\n case JPEGCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"DCTDecode\");\n if (image->colorspace != CMYKColorspace)\n break;\n (void) WriteBlobString(image,buffer);\n (void) CopyMagickString(buffer,\"/Decode [1 0 1 0 1 0 1 0]\\n\",\n MagickPathExtent);\n break;\n }\n case JPEG2000Compression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"JPXDecode\");\n if (image->colorspace != CMYKColorspace)\n break;\n (void) WriteBlobString(image,buffer);\n (void) CopyMagickString(buffer,\"/Decode [1 0 1 0 1 0 1 0]\\n\",\n MagickPathExtent);\n break;\n }\n case LZWCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"LZWDecode\");\n break;\n }\n case ZipCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"FlateDecode\");\n break;\n }\n case FaxCompression:\n case Group4Compression:\n {\n (void) CopyMagickString(buffer,\"/Filter [ /CCITTFaxDecode ]\\n\",\n MagickPathExtent);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/DecodeParms [ << \"\n \"/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\\n\",CCITTParam,\n (double) image->columns,(double) image->rows);\n break;\n }\n default:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"RunLengthDecode\");\n break;\n }\n }\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Width %.20g\\n\",(double)\n image->columns);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Height %.20g\\n\",(double)\n image->rows);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/ColorSpace %.20g 0 R\\n\",\n (double) object+2);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/BitsPerComponent %d\\n\",\n (compression == FaxCompression) || (compression == Group4Compression) ?\n 1 : 8);\n (void) WriteBlobString(image,buffer);\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/SMask %.20g 0 R\\n\",\n (double) object+(has_icc_profile != MagickFalse ? 9 : 7));\n (void) WriteBlobString(image,buffer);\n }\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g 0 R\\n\",\n (double) object+1);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"stream\\n\");\n offset=TellBlob(image);\n number_pixels=(MagickSizeType) image->columns*image->rows;\n if ((4*number_pixels) != (MagickSizeType) ((size_t) (4*number_pixels)))\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n if ((compression == FaxCompression) || (compression == Group4Compression) ||\n ((image_info->type != TrueColorType) &&\n (SetImageGray(image,exception) != MagickFalse)))\n {\n switch (compression)\n {\n case FaxCompression:\n case Group4Compression:\n {\n if (LocaleCompare(CCITTParam,\"0\") == 0)\n {\n (void) HuffmanEncodeImage(image_info,image,image,exception);\n break;\n }\n (void) Huffman2DEncodeImage(image_info,image,image,exception);\n break;\n }\n case JPEGCompression:\n {\n status=InjectImageBlob(image_info,image,image,\"jpeg\",exception);\n if (status == MagickFalse)\n {\n (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case JPEG2000Compression:\n {\n status=InjectImageBlob(image_info,image,image,\"jp2\",exception);\n if (status == MagickFalse)\n {\n (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case RLECompression:\n default:\n {\n MemoryInfo\n *pixel_info;\n\n /*\n Allocate pixel array.\n */\n length=(size_t) number_pixels;\n pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n /*\n Dump Runlength encoded pixels.\n */\n q=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n *q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma(image,p)));\n p+=GetPixelChannels(image);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)\n y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if (compression == ZipCompression)\n status=ZLIBEncodeImage(image,length,pixels,exception);\n else\n#endif\n if (compression == LZWCompression)\n status=LZWEncodeImage(image,length,pixels,exception);\n else\n status=PackbitsEncodeImage(image,length,pixels,exception);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (status == MagickFalse)\n {\n (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case NoCompression:\n {\n /*\n Dump uncompressed PseudoColor packets.\n */\n Ascii85Initialize(image);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(\n GetPixelLuma(image,p))));\n p+=GetPixelChannels(image);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)\n y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n Ascii85Flush(image);\n break;\n }\n }\n }\n else\n if ((image->storage_class == DirectClass) || (image->colors > 256) ||\n (compression == JPEGCompression) ||\n (compression == JPEG2000Compression))\n switch (compression)\n {\n case JPEGCompression:\n {\n status=InjectImageBlob(image_info,image,image,\"jpeg\",exception);\n if (status == MagickFalse)\n {\n (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case JPEG2000Compression:\n {\n status=InjectImageBlob(image_info,image,image,\"jp2\",exception);\n if (status == MagickFalse)\n {\n (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case RLECompression:\n default:\n {\n MemoryInfo\n *pixel_info;\n\n /*\n Allocate pixel array.\n */\n length=(size_t) number_pixels;\n length*=image->colorspace == CMYKColorspace ? 4UL : 3UL;\n pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n {\n xref=(MagickOffsetType *) RelinquishMagickMemory(xref);\n ThrowWriterException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n /*\n Dump runoffset encoded pixels.\n */\n q=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n *q++=ScaleQuantumToChar(GetPixelRed(image,p));\n *q++=ScaleQuantumToChar(GetPixelGreen(image,p));\n *q++=ScaleQuantumToChar(GetPixelBlue(image,p));\n if (image->colorspace == CMYKColorspace)\n *q++=ScaleQuantumToChar(GetPixelBlack(image,p));\n p+=GetPixelChannels(image);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)\n y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if (compression == ZipCompression)\n status=ZLIBEncodeImage(image,length,pixels,exception);\n else\n#endif\n if (compression == LZWCompression)\n status=LZWEncodeImage(image,length,pixels,exception);\n else\n status=PackbitsEncodeImage(image,length,pixels,exception);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (status == MagickFalse)\n {\n (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case NoCompression:\n {\n /*\n Dump uncompressed DirectColor packets.\n */\n Ascii85Initialize(image);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n Ascii85Encode(image,ScaleQuantumToChar(GetPixelRed(image,p)));\n Ascii85Encode(image,ScaleQuantumToChar(GetPixelGreen(image,p)));\n Ascii85Encode(image,ScaleQuantumToChar(GetPixelBlue(image,p)));\n if (image->colorspace == CMYKColorspace)\n Ascii85Encode(image,ScaleQuantumToChar(\n GetPixelBlack(image,p)));\n p+=GetPixelChannels(image);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)\n y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n Ascii85Flush(image);\n break;\n }\n }\n else\n {\n /*\n Dump number of colors and colormap.\n */\n switch (compression)\n {\n case RLECompression:\n default:\n {\n MemoryInfo\n *pixel_info;\n\n /*\n Allocate pixel array.\n */\n length=(size_t) number_pixels;\n pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n {\n xref=(MagickOffsetType *) RelinquishMagickMemory(xref);\n ThrowWriterException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n /*\n Dump Runlength encoded pixels.\n */\n q=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n *q++=(unsigned char) GetPixelIndex(image,p);\n p+=GetPixelChannels(image);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,\n (MagickOffsetType) y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if (compression == ZipCompression)\n status=ZLIBEncodeImage(image,length,pixels,exception);\n else\n#endif\n if (compression == LZWCompression)\n status=LZWEncodeImage(image,length,pixels,exception);\n else\n status=PackbitsEncodeImage(image,length,pixels,exception);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (status == MagickFalse)\n {\n (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case NoCompression:\n {\n /*\n Dump uncompressed PseudoColor packets.\n */\n Ascii85Initialize(image);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n Ascii85Encode(image,(unsigned char) GetPixelIndex(image,p));\n p+=GetPixelChannels(image);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,\n (MagickOffsetType) y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n Ascii85Flush(image);\n break;\n }\n }\n }\n offset=TellBlob(image)-offset;\n (void) WriteBlobString(image,\"\\nendstream\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Length object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double)\n offset);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Colorspace object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n device=\"DeviceRGB\";\n channels=0;\n if (image->colorspace == CMYKColorspace)\n {\n device=\"DeviceCMYK\";\n channels=4;\n }\n else\n if ((compression == FaxCompression) ||\n (compression == Group4Compression) ||\n ((image_info->type != TrueColorType) &&\n (SetImageGray(image,exception) != MagickFalse)))\n {\n device=\"DeviceGray\";\n channels=1;\n }\n else\n if ((image->storage_class == DirectClass) ||\n (image->colors > 256) || (compression == JPEGCompression) ||\n (compression == JPEG2000Compression))\n {\n device=\"DeviceRGB\";\n channels=3;\n }\n profile=GetImageProfile(image,\"icc\");\n if ((profile == (StringInfo *) NULL) || (channels == 0))\n {\n if (channels != 0)\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/%s\\n\",device);\n else\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"[ /Indexed /%s %.20g %.20g 0 R ]\\n\",device,(double) image->colors-\n 1,(double) object+3);\n (void) WriteBlobString(image,buffer);\n }\n else\n {\n const unsigned char\n *p;\n\n /*\n Write ICC profile. \n */\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"[/ICCBased %.20g 0 R]\\n\",(double) object+1);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"endobj\\n\");\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",\n (double) object);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"<<\\n/N %.20g\\n\"\n \"/Filter /ASCII85Decode\\n/Length %.20g 0 R\\n/Alternate /%s\\n>>\\n\"\n \"stream\\n\",(double) channels,(double) object+1,device);\n (void) WriteBlobString(image,buffer);\n offset=TellBlob(image);\n Ascii85Initialize(image);\n p=GetStringInfoDatum(profile);\n for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++)\n Ascii85Encode(image,(unsigned char) *p++);\n Ascii85Flush(image);\n offset=TellBlob(image)-offset;\n (void) WriteBlobString(image,\"endstream\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Length object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",\n (double) object);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double)\n offset);\n (void) WriteBlobString(image,buffer);\n }\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Thumb object.\n */\n SetGeometry(image,&geometry);\n (void) ParseMetaGeometry(\"106x106+0+0>\",&geometry.x,&geometry.y,\n &geometry.width,&geometry.height);\n tile_image=ThumbnailImage(image,geometry.width,geometry.height,exception);\n if (tile_image == (Image *) NULL)\n return(MagickFalse);\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n switch (compression)\n {\n case NoCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"ASCII85Decode\");\n break;\n }\n case JPEGCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"DCTDecode\");\n if (image->colorspace != CMYKColorspace)\n break;\n (void) WriteBlobString(image,buffer);\n (void) CopyMagickString(buffer,\"/Decode [1 0 1 0 1 0 1 0]\\n\",\n MagickPathExtent);\n break;\n }\n case JPEG2000Compression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"JPXDecode\");\n if (image->colorspace != CMYKColorspace)\n break;\n (void) WriteBlobString(image,buffer);\n (void) CopyMagickString(buffer,\"/Decode [1 0 1 0 1 0 1 0]\\n\",\n MagickPathExtent);\n break;\n }\n case LZWCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"LZWDecode\");\n break;\n }\n case ZipCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"FlateDecode\");\n break;\n }\n case FaxCompression:\n case Group4Compression:\n {\n (void) CopyMagickString(buffer,\"/Filter [ /CCITTFaxDecode ]\\n\",\n MagickPathExtent);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/DecodeParms [ << \"\n \"/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\\n\",CCITTParam,\n (double) tile_image->columns,(double) tile_image->rows);\n break;\n }\n default:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"RunLengthDecode\");\n break;\n }\n }\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Width %.20g\\n\",(double)\n tile_image->columns);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Height %.20g\\n\",(double)\n tile_image->rows);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/ColorSpace %.20g 0 R\\n\",\n (double) object-(has_icc_profile != MagickFalse ? 3 : 1));\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/BitsPerComponent %d\\n\",\n (compression == FaxCompression) || (compression == Group4Compression) ?\n 1 : 8);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g 0 R\\n\",\n (double) object+1);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"stream\\n\");\n offset=TellBlob(image);\n number_pixels=(MagickSizeType) tile_image->columns*tile_image->rows;\n if ((compression == FaxCompression) ||\n (compression == Group4Compression) ||\n ((image_info->type != TrueColorType) &&\n (SetImageGray(tile_image,exception) != MagickFalse)))\n {\n switch (compression)\n {\n case FaxCompression:\n case Group4Compression:\n {\n if (LocaleCompare(CCITTParam,\"0\") == 0)\n {\n (void) HuffmanEncodeImage(image_info,image,tile_image,\n exception);\n break;\n }\n (void) Huffman2DEncodeImage(image_info,image,tile_image,exception);\n break;\n }\n case JPEGCompression:\n {\n status=InjectImageBlob(image_info,image,tile_image,\"jpeg\",\n exception);\n if (status == MagickFalse)\n {\n (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case JPEG2000Compression:\n {\n status=InjectImageBlob(image_info,image,tile_image,\"jp2\",exception);\n if (status == MagickFalse)\n {\n (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case RLECompression:\n default:\n {\n MemoryInfo\n *pixel_info;\n\n /*\n Allocate pixel array.\n */\n length=(size_t) number_pixels;\n pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n {\n tile_image=DestroyImage(tile_image);\n ThrowWriterException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n /*\n Dump runlength encoded pixels.\n */\n q=pixels;\n for (y=0; y < (ssize_t) tile_image->rows; y++)\n {\n p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,\n exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) tile_image->columns; x++)\n {\n *q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma(\n tile_image,p)));\n p+=GetPixelChannels(tile_image);\n }\n }\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if (compression == ZipCompression)\n status=ZLIBEncodeImage(image,length,pixels,exception);\n else\n#endif\n if (compression == LZWCompression)\n status=LZWEncodeImage(image,length,pixels,exception);\n else\n status=PackbitsEncodeImage(image,length,pixels,exception);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (status == MagickFalse)\n {\n (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case NoCompression:\n {\n /*\n Dump uncompressed PseudoColor packets.\n */\n Ascii85Initialize(image);\n for (y=0; y < (ssize_t) tile_image->rows; y++)\n {\n p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,\n exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) tile_image->columns; x++)\n {\n Ascii85Encode(tile_image,ScaleQuantumToChar(ClampToQuantum(\n GetPixelLuma(tile_image,p))));\n p+=GetPixelChannels(tile_image);\n }\n }\n Ascii85Flush(image);\n break;\n }\n }\n }\n else\n if ((tile_image->storage_class == DirectClass) ||\n (tile_image->colors > 256) || (compression == JPEGCompression) ||\n (compression == JPEG2000Compression))\n switch (compression)\n {\n case JPEGCompression:\n {\n status=InjectImageBlob(image_info,image,tile_image,\"jpeg\",\n exception);\n if (status == MagickFalse)\n {\n (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case JPEG2000Compression:\n {\n status=InjectImageBlob(image_info,image,tile_image,\"jp2\",exception);\n if (status == MagickFalse)\n {\n (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case RLECompression:\n default:\n {\n MemoryInfo\n *pixel_info;\n\n /*\n Allocate pixel array.\n */\n length=(size_t) number_pixels;\n length*=tile_image->colorspace == CMYKColorspace ? 4UL : 3UL;\n pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n {\n tile_image=DestroyImage(tile_image);\n ThrowWriterException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n /*\n Dump runlength encoded pixels.\n */\n q=pixels;\n for (y=0; y < (ssize_t) tile_image->rows; y++)\n {\n p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,\n exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) tile_image->columns; x++)\n {\n *q++=ScaleQuantumToChar(GetPixelRed(tile_image,p));\n *q++=ScaleQuantumToChar(GetPixelGreen(tile_image,p));\n *q++=ScaleQuantumToChar(GetPixelBlue(tile_image,p));\n if (tile_image->colorspace == CMYKColorspace)\n *q++=ScaleQuantumToChar(GetPixelBlack(tile_image,p));\n p+=GetPixelChannels(tile_image);\n }\n }\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if (compression == ZipCompression)\n status=ZLIBEncodeImage(image,length,pixels,exception);\n else\n#endif\n if (compression == LZWCompression)\n status=LZWEncodeImage(image,length,pixels,exception);\n else\n status=PackbitsEncodeImage(image,length,pixels,exception);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (status == MagickFalse)\n {\n (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case NoCompression:\n {\n /*\n Dump uncompressed DirectColor packets.\n */\n Ascii85Initialize(image);\n for (y=0; y < (ssize_t) tile_image->rows; y++)\n {\n p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,\n exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) tile_image->columns; x++)\n {\n Ascii85Encode(image,ScaleQuantumToChar(\n GetPixelRed(tile_image,p)));\n Ascii85Encode(image,ScaleQuantumToChar(\n GetPixelGreen(tile_image,p)));\n Ascii85Encode(image,ScaleQuantumToChar(\n GetPixelBlue(tile_image,p)));\n if (image->colorspace == CMYKColorspace)\n Ascii85Encode(image,ScaleQuantumToChar(\n GetPixelBlack(tile_image,p)));\n p+=GetPixelChannels(tile_image);\n }\n }\n Ascii85Flush(image);\n break;\n }\n }\n else\n {\n /*\n Dump number of colors and colormap.\n */\n switch (compression)\n {\n case RLECompression:\n default:\n {\n MemoryInfo\n *pixel_info;\n\n /*\n Allocate pixel array.\n */\n length=(size_t) number_pixels;\n pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n {\n tile_image=DestroyImage(tile_image);\n ThrowWriterException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n /*\n Dump runlength encoded pixels.\n */\n q=pixels;\n for (y=0; y < (ssize_t) tile_image->rows; y++)\n {\n p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,\n exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) tile_image->columns; x++)\n {\n *q++=(unsigned char) GetPixelIndex(tile_image,p);\n p+=GetPixelChannels(tile_image);\n }\n }\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if (compression == ZipCompression)\n status=ZLIBEncodeImage(image,length,pixels,exception);\n else\n#endif\n if (compression == LZWCompression)\n status=LZWEncodeImage(image,length,pixels,exception);\n else\n status=PackbitsEncodeImage(image,length,pixels,exception);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (status == MagickFalse)\n {\n (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case NoCompression:\n {\n /*\n Dump uncompressed PseudoColor packets.\n */\n Ascii85Initialize(image);\n for (y=0; y < (ssize_t) tile_image->rows; y++)\n {\n p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,\n exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) tile_image->columns; x++)\n {\n Ascii85Encode(image,(unsigned char)\n GetPixelIndex(tile_image,p));\n p+=GetPixelChannels(image);\n }\n }\n Ascii85Flush(image);\n break;\n }\n }\n }\n tile_image=DestroyImage(tile_image);\n offset=TellBlob(image)-offset;\n (void) WriteBlobString(image,\"\\nendstream\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Length object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double)\n offset);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"endobj\\n\");\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n if ((image->storage_class == DirectClass) || (image->colors > 256) ||\n (compression == FaxCompression) || (compression == Group4Compression))\n (void) WriteBlobString(image,\">>\\n\");\n else\n {\n /*\n Write Colormap object.\n */\n if (compression == NoCompression)\n (void) WriteBlobString(image,\"/Filter [ /ASCII85Decode ]\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g 0 R\\n\",\n (double) object+1);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"stream\\n\");\n offset=TellBlob(image);\n if (compression == NoCompression)\n Ascii85Initialize(image);\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n if (compression == NoCompression)\n {\n Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(\n image->colormap[i].red)));\n Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(\n image->colormap[i].green)));\n Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(\n image->colormap[i].blue)));\n continue;\n }\n (void) WriteBlobByte(image,ScaleQuantumToChar(\n ClampToQuantum(image->colormap[i].red)));\n (void) WriteBlobByte(image,ScaleQuantumToChar(\n ClampToQuantum(image->colormap[i].green)));\n (void) WriteBlobByte(image,ScaleQuantumToChar(\n ClampToQuantum(image->colormap[i].blue)));\n }\n if (compression == NoCompression)\n Ascii85Flush(image);\n offset=TellBlob(image)-offset;\n (void) WriteBlobString(image,\"\\nendstream\\n\");\n }\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Length object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double)\n offset);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write softmask object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n if (image->alpha_trait == UndefinedPixelTrait)\n (void) WriteBlobString(image,\">>\\n\");\n else\n {\n (void) WriteBlobString(image,\"/Type /XObject\\n\");\n (void) WriteBlobString(image,\"/Subtype /Image\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Name /Ma%.20g\\n\",\n (double) image->scene);\n (void) WriteBlobString(image,buffer);\n switch (compression)\n {\n case NoCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"ASCII85Decode\");\n break;\n }\n case LZWCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"LZWDecode\");\n break;\n }\n case ZipCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"FlateDecode\");\n break;\n }\n default:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"RunLengthDecode\");\n break;\n }\n }\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Width %.20g\\n\",\n (double) image->columns);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Height %.20g\\n\",\n (double) image->rows);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"/ColorSpace /DeviceGray\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"/BitsPerComponent %d\\n\",(compression == FaxCompression) ||\n (compression == Group4Compression) ? 1 : 8);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g 0 R\\n\",\n (double) object+1);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"stream\\n\");\n offset=TellBlob(image);\n number_pixels=(MagickSizeType) image->columns*image->rows;\n switch (compression)\n {\n case RLECompression:\n default:\n {\n MemoryInfo\n *pixel_info;\n\n /*\n Allocate pixel array.\n */\n length=(size_t) number_pixels;\n pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n {\n image=DestroyImage(image);\n ThrowWriterException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n /*\n Dump Runlength encoded pixels.\n */\n q=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n *q++=ScaleQuantumToChar(GetPixelAlpha(image,p));\n p+=GetPixelChannels(image);\n }\n }\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if (compression == ZipCompression)\n status=ZLIBEncodeImage(image,length,pixels,exception);\n else\n#endif\n if (compression == LZWCompression)\n status=LZWEncodeImage(image,length,pixels,exception);\n else\n status=PackbitsEncodeImage(image,length,pixels,exception);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (status == MagickFalse)\n {\n (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case NoCompression:\n {\n /*\n Dump uncompressed PseudoColor packets.\n */\n Ascii85Initialize(image);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n Ascii85Encode(image,ScaleQuantumToChar(GetPixelAlpha(image,p)));\n p+=GetPixelChannels(image);\n }\n }\n Ascii85Flush(image);\n break;\n }\n }\n offset=TellBlob(image)-offset;\n (void) WriteBlobString(image,\"\\nendstream\\n\");\n }\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Length object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double)\n offset);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"endobj\\n\");\n if (GetNextImageInList(image) == (Image *) NULL)\n break;\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,SaveImagesTag,scene++,\n GetImageListLength(image));\n if (status == MagickFalse)\n break;\n } while (image_info->adjoin != MagickFalse);\n /*\n Write Metadata object.\n */\n xref[object++]=TellBlob(image);\n info_id=object;\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n utf16=ConvertUTF8ToUTF16((unsigned char *) basename,&length);\n if (utf16 != (wchar_t *) NULL)\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Title (\\xfe\\xff\");\n (void) WriteBlobString(image,buffer);\n for (i=0; i < (ssize_t) length; i++)\n (void) WriteBlobMSBShort(image,(unsigned short) utf16[i]);\n (void) FormatLocaleString(buffer,MagickPathExtent,\")\\n\");\n (void) WriteBlobString(image,buffer);\n utf16=(wchar_t *) RelinquishMagickMemory(utf16);\n }\n seconds=time((time_t *) NULL);\n#if defined(MAGICKCORE_HAVE_LOCALTIME_R)\n (void) localtime_r(&seconds,&local_time);\n#else\n (void) memcpy(&local_time,localtime(&seconds),sizeof(local_time));\n#endif\n (void) FormatLocaleString(date,MagickPathExtent,\"D:%04d%02d%02d%02d%02d%02d\",\n local_time.tm_year+1900,local_time.tm_mon+1,local_time.tm_mday,\n local_time.tm_hour,local_time.tm_min,local_time.tm_sec);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/CreationDate (%s)\\n\",\n date);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/ModDate (%s)\\n\",date);\n (void) WriteBlobString(image,buffer);\n url=GetMagickHomeURL();\n escape=EscapeParenthesis(url);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Producer (%s)\\n\",escape);\n escape=DestroyString(escape);\n url=DestroyString(url);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Xref object.\n */\n offset=TellBlob(image)-xref[0]+\n (LocaleCompare(image_info->magick,\"PDFA\") == 0 ? 6 : 0)+10;\n (void) WriteBlobString(image,\"xref\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"0 %.20g\\n\",(double)\n object+1);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"0000000000 65535 f \\n\");\n for (i=0; i < (ssize_t) object; i++)\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%010lu 00000 n \\n\",\n (unsigned long) xref[i]);\n (void) WriteBlobString(image,buffer);\n }\n (void) WriteBlobString(image,\"trailer\\n\");\n (void) WriteBlobString(image,\"<<\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Size %.20g\\n\",(double)\n object+1);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Info %.20g 0 R\\n\",(double)\n info_id);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Root %.20g 0 R\\n\",(double)\n root_id);\n (void) WriteBlobString(image,buffer);\n (void) SignatureImage(image,exception);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/ID [<%s> <%s>]\\n\",\n GetImageProperty(image,\"signature\",exception),\n GetImageProperty(image,\"signature\",exception));\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"startxref\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"%%EOF\\n\");\n xref=(MagickOffsetType *) RelinquishMagickMemory(xref);\n (void) CloseBlob(image);\n return(MagickTrue);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/674'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: on_register_handler(TCMUService1HandlerManager1 *interface,\n\t\t GDBusMethodInvocation *invocation,\n\t\t gchar *subtype,\n\t\t gchar *cfg_desc,\n\t\t gpointer user_data)\n{\n\tstruct tcmur_handler *handler;\n\tstruct dbus_info *info;\n\tchar *bus_name;\n\n\tbus_name = g_strdup_printf(\"org.kernel.TCMUService1.HandlerManager1.%s\",\n\t\t\t\t subtype);\n\n\thandler = g_new0(struct tcmur_handler, 1);\n\thandler->subtype = g_strdup(subtype);\n\thandler->cfg_desc = g_strdup(cfg_desc);\n\thandler->open = dbus_handler_open;\n\thandler->close = dbus_handler_close;\n\thandler->handle_cmd = dbus_handler_handle_cmd;\n\n\tinfo = g_new0(struct dbus_info, 1);\n\tinfo->register_invocation = invocation;\n\tinfo->watcher_id = g_bus_watch_name(G_BUS_TYPE_SYSTEM,\n\t\t\t\t\t bus_name,\n\t\t\t\t\t G_BUS_NAME_WATCHER_FLAGS_NONE,\n\t\t\t\t\t on_handler_appeared,\n\t\t\t\t\t on_handler_vanished,\n\t\t\t\t\t handler,\n\t\t\t\t\t NULL);\n\tg_free(bus_name);\n\thandler->opaque = info;\n\treturn TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'only allow dynamic UnregisterHandler for external handlers, thereby fixing DoS\n\nTrying to unregister an internal handler ended up in a SEGFAULT, because\nthe tcmur_handler->opaque was NULL. Way to reproduce:\n\ndbus-send --system --print-reply --dest=org.kernel.TCMUService1 /org/kernel/TCMUService1/HandlerManager1 org.kernel.TCMUService1.HandlerManager1.UnregisterHandler string:qcow\n\nwe use a newly introduced boolean in struct tcmur_handler for keeping\ntrack of external handlers. As suggested by mikechristie adjusting the\npublic data structure is acceptable.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters)\n{\n FILE *f = NULL;\n int w, h, prec;\n int i, numcomps, max;\n OPJ_COLOR_SPACE color_space;\n opj_image_cmptparm_t cmptparm; /* maximum of 1 component */\n opj_image_t * image = NULL;\n int adjustS, ushift, dshift, force8;\n\n char endian1, endian2, sign;\n char signtmp[32];\n\n char temp[32];\n int bigendian;\n opj_image_comp_t *comp = NULL;\n\n numcomps = 1;\n color_space = OPJ_CLRSPC_GRAY;\n\n memset(&cmptparm, 0, sizeof(opj_image_cmptparm_t));\n\n max = 0;\n\n f = fopen(filename, \"rb\");\n if (!f) {\n fprintf(stderr, \"Failed to open %s for reading !\\n\", filename);\n return NULL;\n }\n\n fseek(f, 0, SEEK_SET);\n if (fscanf(f, \"PG%[ \\t]%c%c%[ \\t+-]%d%[ \\t]%d%[ \\t]%d\", temp, &endian1,\n &endian2, signtmp, &prec, temp, &w, temp, &h) != 9) {\n fclose(f);\n fprintf(stderr,\n \"ERROR: Failed to read the right number of element from the fscanf() function!\\n\");\n return NULL;\n }\n\n i = 0;\n sign = '+';\n while (signtmp[i] != '\\0') {\n if (signtmp[i] == '-') {\n sign = '-';\n }\n i++;\n }\n\n fgetc(f);\n if (endian1 == 'M' && endian2 == 'L') {\n bigendian = 1;\n } else if (endian2 == 'M' && endian1 == 'L') {\n bigendian = 0;\n } else {\n fclose(f);\n fprintf(stderr, \"Bad pgx header, please check input file\\n\");\n return NULL;\n }\n\n /* initialize image component */\n\n cmptparm.x0 = (OPJ_UINT32)parameters->image_offset_x0;\n cmptparm.y0 = (OPJ_UINT32)parameters->image_offset_y0;\n cmptparm.w = !cmptparm.x0 ? (OPJ_UINT32)((w - 1) * parameters->subsampling_dx +\n 1) : cmptparm.x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)parameters->subsampling_dx\n + 1;\n cmptparm.h = !cmptparm.y0 ? (OPJ_UINT32)((h - 1) * parameters->subsampling_dy +\n 1) : cmptparm.y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)parameters->subsampling_dy\n + 1;\n\n if (sign == '-') {\n cmptparm.sgnd = 1;\n } else {\n cmptparm.sgnd = 0;\n }\n if (prec < 8) {\n force8 = 1;\n ushift = 8 - prec;\n dshift = prec - ushift;\n if (cmptparm.sgnd) {\n adjustS = (1 << (prec - 1));\n } else {\n adjustS = 0;\n }\n cmptparm.sgnd = 0;\n prec = 8;\n } else {\n ushift = dshift = force8 = adjustS = 0;\n }\n\n cmptparm.prec = (OPJ_UINT32)prec;\n cmptparm.bpp = (OPJ_UINT32)prec;\n cmptparm.dx = (OPJ_UINT32)parameters->subsampling_dx;\n cmptparm.dy = (OPJ_UINT32)parameters->subsampling_dy;\n\n /* create the image */\n image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm, color_space);\n if (!image) {\n fclose(f);\n return NULL;\n }\n /* set image offset and reference grid */\n image->x0 = cmptparm.x0;\n image->y0 = cmptparm.x0;\n image->x1 = cmptparm.w;\n image->y1 = cmptparm.h;\n\n /* set image data */\n\n comp = &image->comps[0];\n\n for (i = 0; i < w * h; i++) {\n int v;\n if (force8) {\n v = readuchar(f) + adjustS;\n v = (v << ushift) + (v >> dshift);\n comp->data[i] = (unsigned char)v;\n\n if (v > max) {\n max = v;\n }\n\n continue;\n }\n if (comp->prec == 8) {\n if (!comp->sgnd) {\n v = readuchar(f);\n } else {\n v = (char) readuchar(f);\n }\n } else if (comp->prec <= 16) {\n if (!comp->sgnd) {\n v = readushort(f, bigendian);\n } else {\n v = (short) readushort(f, bigendian);\n }\n } else {\n if (!comp->sgnd) {\n v = (int)readuint(f, bigendian);\n } else {\n v = (int) readuint(f, bigendian);\n }\n }\n if (v > max) {\n max = v;\n }\n comp->data[i] = v;\n }\n fclose(f);\n comp->bpp = (OPJ_UINT32)int_floorlog2(max) + 1;\n\n return image;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'pgxtoimage(): fix write stack buffer overflow (#997)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static VALUE cState_space_set(VALUE self, VALUE space)\n{\n unsigned long len;\n GET_STATE(self);\n Check_Type(space, T_STRING);\n len = RSTRING_LEN(space);\n if (len == 0) {\n if (state->space) {\n ruby_xfree(state->space);\n state->space = NULL;\n state->space_len = 0;\n }\n } else {\n if (state->space) ruby_xfree(state->space);\n state->space = strdup(RSTRING_PTR(space));\n state->space_len = len;\n }\n return Qnil;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix arbitrary heap exposure problem'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages,\n\t\tconst void __user * __user *, pages,\n\t\tconst int __user *, nodes,\n\t\tint __user *, status, int, flags)\n{\n\tconst struct cred *cred = current_cred(), *tcred;\n\tstruct task_struct *task;\n\tstruct mm_struct *mm;\n\tint err;\n\tnodemask_t task_nodes;\n\n\t/* Check flags */\n\tif (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL))\n\t\treturn -EINVAL;\n\n\tif ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))\n\t\treturn -EPERM;\n\n\t/* Find the mm_struct */\n\trcu_read_lock();\n\ttask = pid ? find_task_by_vpid(pid) : current;\n\tif (!task) {\n\t\trcu_read_unlock();\n\t\treturn -ESRCH;\n\t}\n\tget_task_struct(task);\n\n\t/*\n\t * Check if this process has the right to modify the specified\n\t * process. The right exists if the process has administrative\n\t * capabilities, superuser privileges or the same\n\t * userid as the target process.\n\t */\n\ttcred = __task_cred(task);\n\tif (!uid_eq(cred->euid, tcred->suid) && !uid_eq(cred->euid, tcred->uid) &&\n\t !uid_eq(cred->uid, tcred->suid) && !uid_eq(cred->uid, tcred->uid) &&\n\t !capable(CAP_SYS_NICE)) {\n\t\trcu_read_unlock();\n\t\terr = -EPERM;\n\t\tgoto out;\n\t}\n\trcu_read_unlock();\n\n \terr = security_task_movememory(task);\n \tif (err)\n\t\tgoto out;\n\n\ttask_nodes = cpuset_mems_allowed(task);\n\tmm = get_task_mm(task);\n\tput_task_struct(task);\n\n\tif (!mm)\n\t\treturn -EINVAL;\n\n\tif (nodes)\n\t\terr = do_pages_move(mm, task_nodes, nr_pages, pages,\n\t\t\t\t nodes, status, flags);\n\telse\n\t\terr = do_pages_stat(mm, nr_pages, pages, status);\n\n\tmmput(mm);\n\treturn err;\n\nout:\n\tput_task_struct(task);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Sanitize 'move_pages()' permission checks\n\nThe 'move_paghes()' system call was introduced long long ago with the\nsame permission checks as for sending a signal (except using\nCAP_SYS_NICE instead of CAP_SYS_KILL for the overriding capability).\n\nThat turns out to not be a great choice - while the system call really\nonly moves physical page allocations around (and you need other\ncapabilities to do a lot of it), you can check the return value to map\nout some the virtual address choices and defeat ASLR of a binary that\nstill shares your uid.\n\nSo change the access checks to the more common 'ptrace_may_access()'\nmodel instead.\n\nThis tightens the access checks for the uid, and also effectively\nchanges the CAP_SYS_NICE check to CAP_SYS_PTRACE, but it's unlikely that\nanybody really _uses_ this legacy system call any more (we hav ebetter\nNUMA placement models these days), so I expect nobody to notice.\n\nFamous last words.\n\nReported-by: Otto Ebeling \nAcked-by: Eric W. Biederman \nCc: Willy Tarreau \nCc: stable@kernel.org\nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: gss_wrap_iov_length (minor_status,\n context_handle,\n conf_req_flag,\n qop_req,\n conf_state,\n iov,\n iov_count)\nOM_uint32 *\t\tminor_status;\ngss_ctx_id_t\t\tcontext_handle;\nint\t\t\tconf_req_flag;\ngss_qop_t\t\tqop_req;\nint *\t\t\tconf_state;\ngss_iov_buffer_desc *\tiov;\nint\t\t\tiov_count;\n{\n /* EXPORT DELETE START */\n\n OM_uint32\t\tstatus;\n gss_union_ctx_id_t\tctx;\n gss_mechanism\tmech;\n\n status = val_wrap_iov_args(minor_status, context_handle,\n\t\t\t conf_req_flag, qop_req,\n\t\t\t conf_state, iov, iov_count);\n if (status != GSS_S_COMPLETE)\n\treturn (status);\n\n /*\n * select the approprate underlying mechanism routine and\n * call it.\n */\n\n ctx = (gss_union_ctx_id_t) context_handle;\n mech = gssint_get_mechanism (ctx->mech_type);\n\n if (mech) {\n\tif (mech->gss_wrap_iov_length) {\n\t status = mech->gss_wrap_iov_length(\n\t\t\t\t\t minor_status,\n\t\t\t\t\t ctx->internal_ctx_id,\n\t\t\t\t\t conf_req_flag,\n\t\t\t\t\t qop_req,\n\t\t\t\t\t conf_state,\n\t\t\t\t\t iov,\n\t\t\t\t\t iov_count);\n\t if (status != GSS_S_COMPLETE)\n\t\tmap_error(minor_status, mech);\n\t} else\n\t status = GSS_S_UNAVAILABLE;\n\n\treturn(status);\n }\n /* EXPORT DELETE END */\n\n return (GSS_S_BAD_MECH);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'Preserve GSS context on init/accept failure\n\nAfter gss_init_sec_context() or gss_accept_sec_context() has created a\ncontext, don't delete the mechglue context on failures from subsequent\ncalls, even if the mechanism deletes the mech-specific context (which\nis allowed by RFC 2744 but not preferred). Check for union contexts\nwith no mechanism context in each GSS function which accepts a\ngss_ctx_id_t.\n\nCVE-2017-11462:\n\nRFC 2744 permits a GSS-API implementation to delete an existing\nsecurity context on a second or subsequent call to\ngss_init_sec_context() or gss_accept_sec_context() if the call results\nin an error. This API behavior has been found to be dangerous,\nleading to the possibility of memory errors in some callers. For\nsafety, GSS-API implementations should instead preserve existing\nsecurity contexts on error until the caller deletes them.\n\nAll versions of MIT krb5 prior to this change may delete acceptor\ncontexts on error. Versions 1.13.4 through 1.13.7, 1.14.1 through\n1.14.5, and 1.15 through 1.15.1 may also delete initiator contexts on\nerror.\n\nticket: 8598 (new)\ntarget_version: 1.15-next\ntarget_version: 1.14-next\ntags: pullup'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: gss_complete_auth_token (OM_uint32 *minor_status,\n\t const gss_ctx_id_t context_handle,\n\t gss_buffer_t input_message_buffer)\n{\n OM_uint32\t\tstatus;\n gss_union_ctx_id_t\tctx;\n gss_mechanism\tmech;\n\n if (context_handle == GSS_C_NO_CONTEXT)\n\treturn GSS_S_NO_CONTEXT;\n\n /*\n * select the approprate underlying mechanism routine and\n * call it.\n */\n\n ctx = (gss_union_ctx_id_t) context_handle;\n mech = gssint_get_mechanism (ctx->mech_type);\n\n if (mech != NULL) {\n\tif (mech->gss_complete_auth_token != NULL) {\n\t status = mech->gss_complete_auth_token(minor_status,\n\t\t\t\t\t\t ctx->internal_ctx_id,\n\t\t\t\t\t\t input_message_buffer);\n\t if (status != GSS_S_COMPLETE)\n\t\tmap_error(minor_status, mech);\n\t} else\n\t status = GSS_S_COMPLETE;\n } else\n\tstatus = GSS_S_BAD_MECH;\n\n return status;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'Preserve GSS context on init/accept failure\n\nAfter gss_init_sec_context() or gss_accept_sec_context() has created a\ncontext, don't delete the mechglue context on failures from subsequent\ncalls, even if the mechanism deletes the mech-specific context (which\nis allowed by RFC 2744 but not preferred). Check for union contexts\nwith no mechanism context in each GSS function which accepts a\ngss_ctx_id_t.\n\nCVE-2017-11462:\n\nRFC 2744 permits a GSS-API implementation to delete an existing\nsecurity context on a second or subsequent call to\ngss_init_sec_context() or gss_accept_sec_context() if the call results\nin an error. This API behavior has been found to be dangerous,\nleading to the possibility of memory errors in some callers. For\nsafety, GSS-API implementations should instead preserve existing\nsecurity contexts on error until the caller deletes them.\n\nAll versions of MIT krb5 prior to this change may delete acceptor\ncontexts on error. Versions 1.13.4 through 1.13.7, 1.14.1 through\n1.14.5, and 1.15 through 1.15.1 may also delete initiator contexts on\nerror.\n\nticket: 8598 (new)\ntarget_version: 1.15-next\ntarget_version: 1.14-next\ntags: pullup'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: _zip_read_eocd64(zip_source_t *src, zip_buffer_t *buffer, zip_uint64_t buf_offset, unsigned int flags, zip_error_t *error)\n{\n zip_cdir_t *cd;\n zip_uint64_t offset;\n zip_uint8_t eocd[EOCD64LEN];\n zip_uint64_t eocd_offset;\n zip_uint64_t size, nentry, i, eocdloc_offset;\n bool free_buffer;\n zip_uint32_t num_disks, num_disks64, eocd_disk, eocd_disk64;\n\n eocdloc_offset = _zip_buffer_offset(buffer);\n\n _zip_buffer_get(buffer, 4); /* magic already verified */\n\n num_disks = _zip_buffer_get_16(buffer);\n eocd_disk = _zip_buffer_get_16(buffer);\n eocd_offset = _zip_buffer_get_64(buffer);\n\n if (eocd_offset > ZIP_INT64_MAX || eocd_offset + EOCD64LEN < eocd_offset) {\n zip_error_set(error, ZIP_ER_SEEK, EFBIG);\n return NULL;\n }\n\n if (eocd_offset + EOCD64LEN > eocdloc_offset + buf_offset) {\n\tzip_error_set(error, ZIP_ER_INCONS, 0);\n\treturn NULL;\n }\n\n if (eocd_offset >= buf_offset && eocd_offset + EOCD64LEN <= buf_offset + _zip_buffer_size(buffer)) {\n _zip_buffer_set_offset(buffer, eocd_offset - buf_offset);\n free_buffer = false;\n }\n else {\n if (zip_source_seek(src, (zip_int64_t)eocd_offset, SEEK_SET) < 0) {\n _zip_error_set_from_source(error, src);\n return NULL;\n }\n if ((buffer = _zip_buffer_new_from_source(src, EOCD64LEN, eocd, error)) == NULL) {\n return NULL;\n }\n free_buffer = true;\n }\n\n if (memcmp(_zip_buffer_get(buffer, 4), EOCD64_MAGIC, 4) != 0) {\n\tzip_error_set(error, ZIP_ER_INCONS, 0);\n if (free_buffer) {\n _zip_buffer_free(buffer);\n }\n\treturn NULL;\n }\n\n size = _zip_buffer_get_64(buffer);\n\n if ((flags & ZIP_CHECKCONS) && size + eocd_offset + 12 != buf_offset + eocdloc_offset) {\n\tzip_error_set(error, ZIP_ER_INCONS, 0);\n if (free_buffer) {\n _zip_buffer_free(buffer);\n }\n return NULL;\n }\n\n _zip_buffer_get(buffer, 4); /* skip version made by/needed */\n\n num_disks64 = _zip_buffer_get_32(buffer);\n eocd_disk64 = _zip_buffer_get_32(buffer);\n\n /* if eocd values are 0xffff, we have to use eocd64 values.\n otherwise, if the values are not the same, it's inconsistent;\n in any case, if the value is not 0, we don't support it */\n if (num_disks == 0xffff) {\n\tnum_disks = num_disks64;\n }\n if (eocd_disk == 0xffff) {\n\teocd_disk = eocd_disk64;\n }\n if ((flags & ZIP_CHECKCONS) && (eocd_disk != eocd_disk64 || num_disks != num_disks64)) {\n\tzip_error_set(error, ZIP_ER_INCONS, 0);\n if (free_buffer) {\n _zip_buffer_free(buffer);\n }\n\treturn NULL;\n }\n if (num_disks != 0 || eocd_disk != 0) {\n\tzip_error_set(error, ZIP_ER_MULTIDISK, 0);\n if (free_buffer) {\n _zip_buffer_free(buffer);\n }\n\treturn NULL;\n }\n\n nentry = _zip_buffer_get_64(buffer);\n i = _zip_buffer_get_64(buffer);\n\n if (nentry != i) {\n\tzip_error_set(error, ZIP_ER_MULTIDISK, 0);\n if (free_buffer) {\n _zip_buffer_free(buffer);\n }\n\treturn NULL;\n }\n\n size = _zip_buffer_get_64(buffer);\n offset = _zip_buffer_get_64(buffer);\n\n if (!_zip_buffer_ok(buffer)) {\n zip_error_set(error, ZIP_ER_INTERNAL, 0);\n if (free_buffer) {\n _zip_buffer_free(buffer);\n }\n return NULL;\n }\n\n if (free_buffer) {\n _zip_buffer_free(buffer);\n }\n\n if (offset > ZIP_INT64_MAX || offset+size < offset) {\n zip_error_set(error, ZIP_ER_SEEK, EFBIG);\n return NULL;\n }\n if ((flags & ZIP_CHECKCONS) && offset+size != eocd_offset) {\n\tzip_error_set(error, ZIP_ER_INCONS, 0);\n\treturn NULL;\n }\n\n if ((cd=_zip_cdir_new(nentry, error)) == NULL)\n\treturn NULL;\n\n cd->is_zip64 = true;\n cd->size = size;\n cd->offset = offset;\n\n return cd;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-770', 'CWE-787'], 'message': 'Make eocd checks more consistent between zip and zip64 cases.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void l2cap_add_conf_opt(void **ptr, u8 type, u8 len, unsigned long val)\n{\n\tstruct l2cap_conf_opt *opt = *ptr;\n\n\tBT_DBG(\"type 0x%2.2x len %u val 0x%lx\", type, len, val);\n\n\topt->type = type;\n\topt->len = len;\n\n\tswitch (len) {\n\tcase 1:\n\t\t*((u8 *) opt->val) = val;\n\t\tbreak;\n\n\tcase 2:\n\t\tput_unaligned_le16(val, opt->val);\n\t\tbreak;\n\n\tcase 4:\n\t\tput_unaligned_le32(val, opt->val);\n\t\tbreak;\n\n\tdefault:\n\t\tmemcpy(opt->val, (void *) val, len);\n\t\tbreak;\n\t}\n\n\t*ptr += L2CAP_CONF_OPT_SIZE + len;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Bluetooth: Properly check L2CAP config option output buffer length\n\nValidate the output buffer length for L2CAP config requests and responses\nto avoid overflowing the stack buffer used for building the option blocks.\n\nCc: stable@vger.kernel.org\nSigned-off-by: Ben Seri \nSigned-off-by: Marcel Holtmann \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int l2cap_connect_create_rsp(struct l2cap_conn *conn,\n\t\t\t\t struct l2cap_cmd_hdr *cmd, u16 cmd_len,\n\t\t\t\t u8 *data)\n{\n\tstruct l2cap_conn_rsp *rsp = (struct l2cap_conn_rsp *) data;\n\tu16 scid, dcid, result, status;\n\tstruct l2cap_chan *chan;\n\tu8 req[128];\n\tint err;\n\n\tif (cmd_len < sizeof(*rsp))\n\t\treturn -EPROTO;\n\n\tscid = __le16_to_cpu(rsp->scid);\n\tdcid = __le16_to_cpu(rsp->dcid);\n\tresult = __le16_to_cpu(rsp->result);\n\tstatus = __le16_to_cpu(rsp->status);\n\n\tBT_DBG(\"dcid 0x%4.4x scid 0x%4.4x result 0x%2.2x status 0x%2.2x\",\n\t dcid, scid, result, status);\n\n\tmutex_lock(&conn->chan_lock);\n\n\tif (scid) {\n\t\tchan = __l2cap_get_chan_by_scid(conn, scid);\n\t\tif (!chan) {\n\t\t\terr = -EBADSLT;\n\t\t\tgoto unlock;\n\t\t}\n\t} else {\n\t\tchan = __l2cap_get_chan_by_ident(conn, cmd->ident);\n\t\tif (!chan) {\n\t\t\terr = -EBADSLT;\n\t\t\tgoto unlock;\n\t\t}\n\t}\n\n\terr = 0;\n\n\tl2cap_chan_lock(chan);\n\n\tswitch (result) {\n\tcase L2CAP_CR_SUCCESS:\n\t\tl2cap_state_change(chan, BT_CONFIG);\n\t\tchan->ident = 0;\n\t\tchan->dcid = dcid;\n\t\tclear_bit(CONF_CONNECT_PEND, &chan->conf_state);\n\n\t\tif (test_and_set_bit(CONF_REQ_SENT, &chan->conf_state))\n\t\t\tbreak;\n\n\t\tl2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ,\n\t\t\t l2cap_build_conf_req(chan, req), req);\n\t\tchan->num_conf_req++;\n\t\tbreak;\n\n\tcase L2CAP_CR_PEND:\n\t\tset_bit(CONF_CONNECT_PEND, &chan->conf_state);\n\t\tbreak;\n\n\tdefault:\n\t\tl2cap_chan_del(chan, ECONNREFUSED);\n\t\tbreak;\n\t}\n\n\tl2cap_chan_unlock(chan);\n\nunlock:\n\tmutex_unlock(&conn->chan_lock);\n\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Bluetooth: Properly check L2CAP config option output buffer length\n\nValidate the output buffer length for L2CAP config requests and responses\nto avoid overflowing the stack buffer used for building the option blocks.\n\nCc: stable@vger.kernel.org\nSigned-off-by: Ben Seri \nSigned-off-by: Marcel Holtmann \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadWPGImage(const ImageInfo *image_info,\n ExceptionInfo *exception)\n{\n typedef struct\n {\n size_t FileId;\n MagickOffsetType DataOffset;\n unsigned int ProductType;\n unsigned int FileType;\n unsigned char MajorVersion;\n unsigned char MinorVersion;\n unsigned int EncryptKey;\n unsigned int Reserved;\n } WPGHeader;\n\n typedef struct\n {\n unsigned char RecType;\n size_t RecordLength;\n } WPGRecord;\n\n typedef struct\n {\n unsigned char Class;\n unsigned char RecType;\n size_t Extension;\n size_t RecordLength;\n } WPG2Record;\n\n typedef struct\n {\n unsigned HorizontalUnits;\n unsigned VerticalUnits;\n unsigned char PosSizePrecision;\n } WPG2Start;\n\n typedef struct\n {\n unsigned int Width;\n unsigned int Height;\n unsigned int Depth;\n unsigned int HorzRes;\n unsigned int VertRes;\n } WPGBitmapType1;\n\n typedef struct\n {\n unsigned int Width;\n unsigned int Height;\n unsigned char Depth;\n unsigned char Compression;\n } WPG2BitmapType1;\n\n typedef struct\n {\n unsigned int RotAngle;\n unsigned int LowLeftX;\n unsigned int LowLeftY;\n unsigned int UpRightX;\n unsigned int UpRightY;\n unsigned int Width;\n unsigned int Height;\n unsigned int Depth;\n unsigned int HorzRes;\n unsigned int VertRes;\n } WPGBitmapType2;\n\n typedef struct\n {\n unsigned int StartIndex;\n unsigned int NumOfEntries;\n } WPGColorMapRec;\n\n /*\n typedef struct {\n size_t PS_unknown1;\n unsigned int PS_unknown2;\n unsigned int PS_unknown3;\n } WPGPSl1Record; \n */\n\n Image\n *image;\n\n unsigned int\n status;\n\n WPGHeader\n Header;\n\n WPGRecord\n Rec;\n\n WPG2Record\n Rec2;\n\n WPG2Start StartWPG;\n\n WPGBitmapType1\n BitmapHeader1;\n\n WPG2BitmapType1\n Bitmap2Header1;\n\n WPGBitmapType2\n BitmapHeader2;\n\n WPGColorMapRec\n WPG_Palette;\n\n int\n i,\n bpp,\n WPG2Flags;\n\n ssize_t\n ldblk;\n\n size_t\n one;\n\n unsigned char\n *BImgBuff;\n\n tCTM CTM; /*current transform matrix*/\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n one=1;\n image=AcquireImage(image_info,exception);\n image->depth=8;\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Read WPG image.\n */\n Header.FileId=ReadBlobLSBLong(image);\n Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image);\n Header.ProductType=ReadBlobLSBShort(image);\n Header.FileType=ReadBlobLSBShort(image);\n Header.MajorVersion=ReadBlobByte(image);\n Header.MinorVersion=ReadBlobByte(image);\n Header.EncryptKey=ReadBlobLSBShort(image);\n Header.Reserved=ReadBlobLSBShort(image);\n\n if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (Header.EncryptKey!=0)\n ThrowReaderException(CoderError,\"EncryptedWPGImageFileNotSupported\");\n\n image->columns = 1;\n image->rows = 1;\n image->colors = 0;\n bpp=0;\n BitmapHeader2.RotAngle=0;\n Rec2.RecordLength=0;\n\n switch(Header.FileType)\n {\n case 1: /* WPG level 1 */\n while(!EOFBlob(image)) /* object parser loop */\n {\n (void) SeekBlob(image,Header.DataOffset,SEEK_SET);\n if(EOFBlob(image))\n break;\n\n Rec.RecType=(i=ReadBlobByte(image));\n if(i==EOF)\n break;\n Rd_WP_DWORD(image,&Rec.RecordLength);\n if (Rec.RecordLength > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if(EOFBlob(image))\n break;\n\n Header.DataOffset=TellBlob(image)+Rec.RecordLength;\n\n switch(Rec.RecType)\n {\n case 0x0B: /* bitmap type 1 */\n BitmapHeader1.Width=ReadBlobLSBShort(image);\n BitmapHeader1.Height=ReadBlobLSBShort(image);\n if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n BitmapHeader1.Depth=ReadBlobLSBShort(image);\n BitmapHeader1.HorzRes=ReadBlobLSBShort(image);\n BitmapHeader1.VertRes=ReadBlobLSBShort(image);\n\n if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes)\n {\n image->units=PixelsPerCentimeterResolution;\n image->resolution.x=BitmapHeader1.HorzRes/470.0;\n image->resolution.y=BitmapHeader1.VertRes/470.0;\n }\n image->columns=BitmapHeader1.Width;\n image->rows=BitmapHeader1.Height;\n bpp=BitmapHeader1.Depth;\n\n goto UnpackRaster;\n\n case 0x0E: /*Color palette */\n WPG_Palette.StartIndex=ReadBlobLSBShort(image);\n WPG_Palette.NumOfEntries=ReadBlobLSBShort(image);\n if ((WPG_Palette.NumOfEntries-WPG_Palette.StartIndex) >\n (Rec2.RecordLength-2-2) / 3)\n ThrowReaderException(CorruptImageError,\"InvalidColormapIndex\");\n image->colors=WPG_Palette.NumOfEntries;\n if (!AcquireImageColormap(image,image->colors,exception))\n goto NoMemory;\n for (i=WPG_Palette.StartIndex;\n i < (int)WPG_Palette.NumOfEntries; i++)\n {\n image->colormap[i].red=ScaleCharToQuantum((unsigned char)\n ReadBlobByte(image));\n image->colormap[i].green=ScaleCharToQuantum((unsigned char)\n ReadBlobByte(image));\n image->colormap[i].blue=ScaleCharToQuantum((unsigned char)\n ReadBlobByte(image));\n }\n break;\n \n case 0x11: /* Start PS l1 */\n if(Rec.RecordLength > 8)\n image=ExtractPostscript(image,image_info,\n TellBlob(image)+8, /* skip PS header in the wpg */\n (ssize_t) Rec.RecordLength-8,exception);\n break; \n\n case 0x14: /* bitmap type 2 */\n BitmapHeader2.RotAngle=ReadBlobLSBShort(image);\n BitmapHeader2.LowLeftX=ReadBlobLSBShort(image);\n BitmapHeader2.LowLeftY=ReadBlobLSBShort(image);\n BitmapHeader2.UpRightX=ReadBlobLSBShort(image);\n BitmapHeader2.UpRightY=ReadBlobLSBShort(image);\n BitmapHeader2.Width=ReadBlobLSBShort(image);\n BitmapHeader2.Height=ReadBlobLSBShort(image);\n if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n BitmapHeader2.Depth=ReadBlobLSBShort(image);\n BitmapHeader2.HorzRes=ReadBlobLSBShort(image);\n BitmapHeader2.VertRes=ReadBlobLSBShort(image);\n\n image->units=PixelsPerCentimeterResolution;\n image->page.width=(unsigned int)\n ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0);\n image->page.height=(unsigned int)\n ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0);\n image->page.x=(int) (BitmapHeader2.LowLeftX/470.0);\n image->page.y=(int) (BitmapHeader2.LowLeftX/470.0);\n if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes)\n {\n image->resolution.x=BitmapHeader2.HorzRes/470.0;\n image->resolution.y=BitmapHeader2.VertRes/470.0;\n }\n image->columns=BitmapHeader2.Width;\n image->rows=BitmapHeader2.Height;\n bpp=BitmapHeader2.Depth;\n\n UnpackRaster: \n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n break;\n if ((image->colors == 0) && (bpp != 24))\n {\n image->colors=one << bpp;\n if (!AcquireImageColormap(image,image->colors,exception))\n {\n NoMemory:\n ThrowReaderException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n /* printf(\"Load default colormap \\n\"); */\n for (i=0; (i < (int) image->colors) && (i < 256); i++)\n { \n image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red);\n image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green);\n image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue);\n }\n }\n else\n {\n if (bpp < 24)\n if ( (image->colors < (one << bpp)) && (bpp != 24) )\n image->colormap=(PixelInfo *) ResizeQuantumMemory(\n image->colormap,(size_t) (one << bpp),\n sizeof(*image->colormap));\n }\n \n if (bpp == 1)\n {\n if(image->colormap[0].red==0 &&\n image->colormap[0].green==0 &&\n image->colormap[0].blue==0 &&\n image->colormap[1].red==0 &&\n image->colormap[1].green==0 &&\n image->colormap[1].blue==0)\n { /* fix crippled monochrome palette */\n image->colormap[1].red =\n image->colormap[1].green =\n image->colormap[1].blue = QuantumRange;\n }\n } \n\n if(UnpackWPGRaster(image,bpp,exception) < 0)\n /* The raster cannot be unpacked */\n {\n DecompressionFailed:\n ThrowReaderException(CoderError,\"UnableToDecompressImage\");\n }\n\n if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping)\n { \n /* flop command */\n if(BitmapHeader2.RotAngle & 0x8000)\n {\n Image\n *flop_image;\n\n flop_image = FlopImage(image, exception);\n if (flop_image != (Image *) NULL) {\n DuplicateBlob(flop_image,image);\n ReplaceImageInList(&image,flop_image);\n }\n }\n /* flip command */\n if(BitmapHeader2.RotAngle & 0x2000)\n {\n Image\n *flip_image;\n\n flip_image = FlipImage(image, exception);\n if (flip_image != (Image *) NULL) {\n DuplicateBlob(flip_image,image);\n ReplaceImageInList(&image,flip_image);\n }\n }\n /* rotate command */\n if(BitmapHeader2.RotAngle & 0x0FFF)\n {\n Image\n *rotate_image;\n\n rotate_image=RotateImage(image,(BitmapHeader2.RotAngle &\n 0x0FFF), exception);\n if (rotate_image != (Image *) NULL) {\n DuplicateBlob(rotate_image,image);\n ReplaceImageInList(&image,rotate_image);\n }\n }\n }\n\n /* Allocate next image structure. */\n AcquireNextImage(image_info,image,exception);\n image->depth=8;\n if (image->next == (Image *) NULL)\n goto Finish;\n image=SyncNextImageInList(image);\n image->columns=image->rows=1;\n image->colors=0;\n break;\n\n case 0x1B: /* Postscript l2 */\n if(Rec.RecordLength>0x3C)\n image=ExtractPostscript(image,image_info,\n TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */\n (ssize_t) Rec.RecordLength-0x3C,exception);\n break;\n }\n }\n break;\n\n case 2: /* WPG level 2 */\n (void) memset(CTM,0,sizeof(CTM));\n StartWPG.PosSizePrecision = 0;\n while(!EOFBlob(image)) /* object parser loop */\n {\n (void) SeekBlob(image,Header.DataOffset,SEEK_SET);\n if(EOFBlob(image))\n break;\n\n Rec2.Class=(i=ReadBlobByte(image));\n if(i==EOF)\n break;\n Rec2.RecType=(i=ReadBlobByte(image));\n if(i==EOF)\n break;\n Rd_WP_DWORD(image,&Rec2.Extension);\n Rd_WP_DWORD(image,&Rec2.RecordLength);\n if(EOFBlob(image))\n break;\n\n Header.DataOffset=TellBlob(image)+Rec2.RecordLength;\n\n switch(Rec2.RecType)\n {\n case 1:\n StartWPG.HorizontalUnits=ReadBlobLSBShort(image);\n StartWPG.VerticalUnits=ReadBlobLSBShort(image);\n StartWPG.PosSizePrecision=ReadBlobByte(image);\n break;\n case 0x0C: /* Color palette */\n WPG_Palette.StartIndex=ReadBlobLSBShort(image);\n WPG_Palette.NumOfEntries=ReadBlobLSBShort(image);\n if ((WPG_Palette.NumOfEntries-WPG_Palette.StartIndex) >\n (Rec2.RecordLength-2-2) / 3)\n ThrowReaderException(CorruptImageError,\"InvalidColormapIndex\");\n image->colors=WPG_Palette.NumOfEntries;\n if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)\n ThrowReaderException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n for (i=WPG_Palette.StartIndex;\n i < (int)WPG_Palette.NumOfEntries; i++)\n {\n image->colormap[i].red=ScaleCharToQuantum((char)\n ReadBlobByte(image));\n image->colormap[i].green=ScaleCharToQuantum((char)\n ReadBlobByte(image));\n image->colormap[i].blue=ScaleCharToQuantum((char)\n ReadBlobByte(image));\n (void) ReadBlobByte(image); /*Opacity??*/\n }\n break;\n case 0x0E:\n Bitmap2Header1.Width=ReadBlobLSBShort(image);\n Bitmap2Header1.Height=ReadBlobLSBShort(image);\n if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n Bitmap2Header1.Depth=ReadBlobByte(image);\n Bitmap2Header1.Compression=ReadBlobByte(image);\n\n if(Bitmap2Header1.Compression > 1)\n continue; /*Unknown compression method */\n switch(Bitmap2Header1.Depth)\n {\n case 1:\n bpp=1;\n break;\n case 2:\n bpp=2;\n break;\n case 3:\n bpp=4;\n break;\n case 4:\n bpp=8;\n break;\n case 8:\n bpp=24;\n break;\n default:\n continue; /*Ignore raster with unknown depth*/\n }\n image->columns=Bitmap2Header1.Width;\n image->rows=Bitmap2Header1.Height;\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n break;\n if ((image->colors == 0) && (bpp != 24))\n {\n image->colors=one << bpp;\n if (!AcquireImageColormap(image,image->colors,exception))\n goto NoMemory;\n }\n else\n {\n if(bpp < 24)\n if( image->colors<(one << bpp) && bpp!=24 )\n image->colormap=(PixelInfo *) ResizeQuantumMemory(\n image->colormap,(size_t) (one << bpp),\n sizeof(*image->colormap));\n }\n\n\n switch(Bitmap2Header1.Compression)\n {\n case 0: /*Uncompressed raster*/\n {\n ldblk=(ssize_t) ((bpp*image->columns+7)/8);\n BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t)\n ldblk+1,sizeof(*BImgBuff));\n if (BImgBuff == (unsigned char *) NULL)\n goto NoMemory;\n\n for(i=0; i< (ssize_t) image->rows; i++)\n {\n (void) ReadBlob(image,ldblk,BImgBuff);\n InsertRow(image,BImgBuff,i,bpp,exception);\n }\n\n if(BImgBuff)\n BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);\n break;\n }\n case 1: /*RLE for WPG2 */\n {\n if( UnpackWPG2Raster(image,bpp,exception) < 0)\n goto DecompressionFailed;\n break;\n } \n }\n\n if(CTM[0][0]<0 && !image_info->ping)\n { /*?? RotAngle=360-RotAngle;*/\n Image\n *flop_image;\n\n flop_image = FlopImage(image, exception);\n if (flop_image != (Image *) NULL) {\n DuplicateBlob(flop_image,image);\n ReplaceImageInList(&image,flop_image);\n }\n /* Try to change CTM according to Flip - I am not sure, must be checked.\n Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0;\n Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0;\n Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll);\n Tx(1,2)=0; Tx(2,2)=1; */\n }\n if(CTM[1][1]<0 && !image_info->ping)\n { /*?? RotAngle=360-RotAngle;*/\n Image\n *flip_image;\n\n flip_image = FlipImage(image, exception);\n if (flip_image != (Image *) NULL) {\n DuplicateBlob(flip_image,image);\n ReplaceImageInList(&image,flip_image);\n }\n /* Try to change CTM according to Flip - I am not sure, must be checked.\n float_matrix Tx(3,3);\n Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0;\n Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0;\n Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll);\n Tx(2,2)=1; */\n }\n\n\n /* Allocate next image structure. */\n AcquireNextImage(image_info,image,exception);\n image->depth=8;\n if (image->next == (Image *) NULL)\n goto Finish;\n image=SyncNextImageInList(image);\n image->columns=image->rows=1;\n image->colors=0;\n break;\n\n case 0x12: /* Postscript WPG2*/\n i=ReadBlobLSBShort(image);\n if(Rec2.RecordLength > (unsigned int) i)\n image=ExtractPostscript(image,image_info,\n TellBlob(image)+i, /*skip PS header in the wpg2*/\n (ssize_t) (Rec2.RecordLength-i-2),exception);\n break;\n\n case 0x1B: /*bitmap rectangle*/\n WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM);\n (void) WPG2Flags;\n break;\n }\n }\n\n break;\n\n default:\n {\n ThrowReaderException(CoderError,\"DataEncodingSchemeIsNotSupported\");\n }\n }\n\n Finish:\n (void) CloseBlob(image);\n\n {\n Image\n *p;\n\n ssize_t\n scene=0;\n\n /*\n Rewind list, removing any empty images while rewinding.\n */\n p=image;\n image=NULL;\n while (p != (Image *) NULL)\n {\n Image *tmp=p;\n if ((p->rows == 0) || (p->columns == 0)) {\n p=p->previous;\n DeleteImageFromList(&tmp);\n } else {\n image=p;\n p=p->previous;\n }\n }\n /*\n Fix scene numbers.\n */\n for (p=image; p != (Image *) NULL; p=p->next)\n p->scene=(size_t) scene++;\n }\n if (image == (Image *) NULL)\n ThrowReaderException(CorruptImageError,\n \"ImageFileDoesNotContainAnyImageData\");\n return(image);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': '...'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void CLASS processCanonCameraInfo (unsigned id, uchar *CameraInfo, unsigned maxlen)\n{\n ushort iCanonLensID = 0, iCanonMaxFocal = 0, iCanonMinFocal = 0, iCanonLens = 0, iCanonCurFocal = 0, iCanonFocalType = 0;\n CameraInfo[0] = 0;\n CameraInfo[1] = 0;\n switch (id) {\n case 0x80000001: // 1D\n case 0x80000167: // 1DS\n iCanonCurFocal = 10;\n iCanonLensID = 13;\n iCanonMinFocal = 14;\n iCanonMaxFocal = 16;\n if (!imgdata.lens.makernotes.CurFocal)\n imgdata.lens.makernotes.CurFocal = sget2(CameraInfo + iCanonCurFocal);\n if (!imgdata.lens.makernotes.MinFocal)\n imgdata.lens.makernotes.MinFocal = sget2(CameraInfo + iCanonMinFocal);\n if (!imgdata.lens.makernotes.MaxFocal)\n imgdata.lens.makernotes.MaxFocal = sget2(CameraInfo + iCanonMaxFocal);\n break;\n case 0x80000174: // 1DMkII\n case 0x80000188: // 1DsMkII\n iCanonCurFocal = 9;\n iCanonLensID = 12;\n iCanonMinFocal = 17;\n iCanonMaxFocal = 19;\n iCanonFocalType = 45;\n break;\n case 0x80000232: // 1DMkII N\n iCanonCurFocal = 9;\n iCanonLensID = 12;\n iCanonMinFocal = 17;\n iCanonMaxFocal = 19;\n break;\n case 0x80000169: // 1DMkIII\n case 0x80000215: // 1DsMkIII\n iCanonCurFocal = 29;\n iCanonLensID = 273;\n iCanonMinFocal = 275;\n iCanonMaxFocal = 277;\n break;\n case 0x80000281: // 1DMkIV\n iCanonCurFocal = 30;\n iCanonLensID = 335;\n iCanonMinFocal = 337;\n iCanonMaxFocal = 339;\n break;\n case 0x80000269: // 1D X\n iCanonCurFocal = 35;\n iCanonLensID = 423;\n iCanonMinFocal = 425;\n iCanonMaxFocal = 427;\n break;\n case 0x80000213: // 5D\n iCanonCurFocal = 40;\n if (!sget2Rev(CameraInfo + 12)) iCanonLensID = 151;\n else iCanonLensID = 12;\n iCanonMinFocal = 147;\n iCanonMaxFocal = 149;\n break;\n case 0x80000218: // 5DMkII\n iCanonCurFocal = 30;\n iCanonLensID = 230;\n iCanonMinFocal = 232;\n iCanonMaxFocal = 234;\n break;\n case 0x80000285: // 5DMkIII\n iCanonCurFocal = 35;\n iCanonLensID = 339;\n iCanonMinFocal = 341;\n iCanonMaxFocal = 343;\n break;\n case 0x80000302: // 6D\n iCanonCurFocal = 35;\n iCanonLensID = 353;\n iCanonMinFocal = 355;\n iCanonMaxFocal = 357;\n break;\n case 0x80000250: // 7D\n iCanonCurFocal = 30;\n iCanonLensID = 274;\n iCanonMinFocal = 276;\n iCanonMaxFocal = 278;\n break;\n case 0x80000190: // 40D\n iCanonCurFocal = 29;\n iCanonLensID = 214;\n iCanonMinFocal = 216;\n iCanonMaxFocal = 218;\n iCanonLens = 2347;\n break;\n case 0x80000261: // 50D\n iCanonCurFocal = 30;\n iCanonLensID = 234;\n iCanonMinFocal = 236;\n iCanonMaxFocal = 238;\n break;\n case 0x80000287: // 60D\n iCanonCurFocal = 30;\n iCanonLensID = 232;\n iCanonMinFocal = 234;\n iCanonMaxFocal = 236;\n break;\n case 0x80000325: // 70D\n iCanonCurFocal = 35;\n iCanonLensID = 358;\n iCanonMinFocal = 360;\n iCanonMaxFocal = 362;\n break;\n case 0x80000176: // 450D\n iCanonCurFocal = 29;\n iCanonLensID = 222;\n iCanonLens = 2355;\n break;\n case 0x80000252: // 500D\n iCanonCurFocal = 30;\n iCanonLensID = 246;\n iCanonMinFocal = 248;\n iCanonMaxFocal = 250;\n break;\n case 0x80000270: // 550D\n iCanonCurFocal = 30;\n iCanonLensID = 255;\n iCanonMinFocal = 257;\n iCanonMaxFocal = 259;\n break;\n case 0x80000286: // 600D\n case 0x80000288: // 1100D\n iCanonCurFocal = 30;\n iCanonLensID = 234;\n iCanonMinFocal = 236;\n iCanonMaxFocal = 238;\n break;\n case 0x80000301: // 650D\n case 0x80000326: // 700D\n iCanonCurFocal = 35;\n iCanonLensID = 295;\n iCanonMinFocal = 297;\n iCanonMaxFocal = 299;\n break;\n case 0x80000254: // 1000D\n iCanonCurFocal = 29;\n iCanonLensID = 226;\n iCanonMinFocal = 228;\n iCanonMaxFocal = 230;\n iCanonLens = 2359;\n break;\n }\n if (iCanonFocalType)\n {\n if(iCanonFocalType>=maxlen) return; // broken;\n imgdata.lens.makernotes.FocalType = CameraInfo[iCanonFocalType];\n if (!imgdata.lens.makernotes.FocalType)\t// zero means 'fixed' here, replacing with standard '1'\n imgdata.lens.makernotes.FocalType = 1;\n }\n if (!imgdata.lens.makernotes.CurFocal)\n {\n if(iCanonCurFocal>=maxlen) return; // broken;\n imgdata.lens.makernotes.CurFocal = sget2Rev(CameraInfo + iCanonCurFocal);\n }\n if (!imgdata.lens.makernotes.LensID)\n {\n if(iCanonLensID>=maxlen) return; // broken;\n imgdata.lens.makernotes.LensID = sget2Rev(CameraInfo + iCanonLensID);\n }\n if (!imgdata.lens.makernotes.MinFocal)\n {\n if(iCanonMinFocal>=maxlen) return; // broken;\n imgdata.lens.makernotes.MinFocal = sget2Rev(CameraInfo + iCanonMinFocal);\n }\n if (!imgdata.lens.makernotes.MaxFocal)\n {\n if(iCanonMaxFocal>=maxlen) return; // broken;\n imgdata.lens.makernotes.MaxFocal = sget2Rev(CameraInfo + iCanonMaxFocal);\n }\n if (!imgdata.lens.makernotes.Lens[0] && iCanonLens) {\n if(iCanonLens+64>=maxlen) return; // broken;\n if (CameraInfo[iCanonLens] < 65)\t\t\t\t\t\t\t\t// non-Canon lens\n {\n memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 64);\n }\n else if (!strncmp((char *)CameraInfo + iCanonLens, \"EF-S\", 4))\n {\n memcpy(imgdata.lens.makernotes.Lens, \"EF-S \", 5);\n memcpy(imgdata.lens.makernotes.LensFeatures_pre, \"EF-E\", 4);\n imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S;\n memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);\n }\n else if (!strncmp((char *)CameraInfo + iCanonLens, \"TS-E\", 4)) {\n memcpy(imgdata.lens.makernotes.Lens, \"TS-E \", 5);\n memcpy(imgdata.lens.makernotes.LensFeatures_pre, \"TS-E\", 4);\n imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;\n memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);\n }\n else if (!strncmp((char *)CameraInfo + iCanonLens, \"MP-E\", 4)) {\n memcpy(imgdata.lens.makernotes.Lens, \"MP-E \", 5);\n memcpy(imgdata.lens.makernotes.LensFeatures_pre, \"MP-E\", 4);\n imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;\n memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);\n }\n else if (!strncmp((char *)CameraInfo + iCanonLens, \"EF-M\", 4)) {\n memcpy(imgdata.lens.makernotes.Lens, \"EF-M \", 5);\n memcpy(imgdata.lens.makernotes.LensFeatures_pre, \"EF-M\", 4);\n imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M;\n memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);\n }\n else {\n memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 2);\n memcpy(imgdata.lens.makernotes.LensFeatures_pre, \"EF\", 2);\n imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;\n imgdata.lens.makernotes.Lens[2] = 32;\n memcpy(imgdata.lens.makernotes.Lens + 3, CameraInfo + iCanonLens + 2, 62);\n }\n }\n return;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'processCanonCameraInfo possible buffer overrun on damaged file'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bson_iter_as_double (const bson_iter_t *iter) /* IN */\n{\n BSON_ASSERT (iter);\n\n switch ((int) ITER_TYPE (iter)) {\n case BSON_TYPE_BOOL:\n return (double) bson_iter_bool (iter);\n case BSON_TYPE_DOUBLE:\n return bson_iter_double (iter);\n case BSON_TYPE_INT32:\n return (double) bson_iter_int32 (iter);\n case BSON_TYPE_INT64:\n return (double) bson_iter_int64 (iter);\n default:\n return 0;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'CDRIVER-2269 Check for zero string length in codewscope'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: struct bio *bio_map_user_iov(struct request_queue *q,\n\t\t\t const struct iov_iter *iter,\n\t\t\t gfp_t gfp_mask)\n{\n\tint j;\n\tint nr_pages = 0;\n\tstruct page **pages;\n\tstruct bio *bio;\n\tint cur_page = 0;\n\tint ret, offset;\n\tstruct iov_iter i;\n\tstruct iovec iov;\n\n\tiov_for_each(iov, i, *iter) {\n\t\tunsigned long uaddr = (unsigned long) iov.iov_base;\n\t\tunsigned long len = iov.iov_len;\n\t\tunsigned long end = (uaddr + len + PAGE_SIZE - 1) >> PAGE_SHIFT;\n\t\tunsigned long start = uaddr >> PAGE_SHIFT;\n\n\t\t/*\n\t\t * Overflow, abort\n\t\t */\n\t\tif (end < start)\n\t\t\treturn ERR_PTR(-EINVAL);\n\n\t\tnr_pages += end - start;\n\t\t/*\n\t\t * buffer must be aligned to at least logical block size for now\n\t\t */\n\t\tif (uaddr & queue_dma_alignment(q))\n\t\t\treturn ERR_PTR(-EINVAL);\n\t}\n\n\tif (!nr_pages)\n\t\treturn ERR_PTR(-EINVAL);\n\n\tbio = bio_kmalloc(gfp_mask, nr_pages);\n\tif (!bio)\n\t\treturn ERR_PTR(-ENOMEM);\n\n\tret = -ENOMEM;\n\tpages = kcalloc(nr_pages, sizeof(struct page *), gfp_mask);\n\tif (!pages)\n\t\tgoto out;\n\n\tiov_for_each(iov, i, *iter) {\n\t\tunsigned long uaddr = (unsigned long) iov.iov_base;\n\t\tunsigned long len = iov.iov_len;\n\t\tunsigned long end = (uaddr + len + PAGE_SIZE - 1) >> PAGE_SHIFT;\n\t\tunsigned long start = uaddr >> PAGE_SHIFT;\n\t\tconst int local_nr_pages = end - start;\n\t\tconst int page_limit = cur_page + local_nr_pages;\n\n\t\tret = get_user_pages_fast(uaddr, local_nr_pages,\n\t\t\t\t(iter->type & WRITE) != WRITE,\n\t\t\t\t&pages[cur_page]);\n\t\tif (ret < local_nr_pages) {\n\t\t\tret = -EFAULT;\n\t\t\tgoto out_unmap;\n\t\t}\n\n\t\toffset = offset_in_page(uaddr);\n\t\tfor (j = cur_page; j < page_limit; j++) {\n\t\t\tunsigned int bytes = PAGE_SIZE - offset;\n\n\t\t\tif (len <= 0)\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tif (bytes > len)\n\t\t\t\tbytes = len;\n\n\t\t\t/*\n\t\t\t * sorry...\n\t\t\t */\n\t\t\tif (bio_add_pc_page(q, bio, pages[j], bytes, offset) <\n\t\t\t\t\t bytes)\n\t\t\t\tbreak;\n\n\t\t\tlen -= bytes;\n\t\t\toffset = 0;\n\t\t}\n\n\t\tcur_page = j;\n\t\t/*\n\t\t * release the pages we didn't map into the bio, if any\n\t\t */\n\t\twhile (j < page_limit)\n\t\t\tput_page(pages[j++]);\n\t}\n\n\tkfree(pages);\n\n\tbio_set_flag(bio, BIO_USER_MAPPED);\n\n\t/*\n\t * subtle -- if bio_map_user_iov() ended up bouncing a bio,\n\t * it would normally disappear when its bi_end_io is run.\n\t * however, we need it for the unmap, so grab an extra\n\t * reference to it\n\t */\n\tbio_get(bio);\n\treturn bio;\n\n out_unmap:\n\tfor (j = 0; j < nr_pages; j++) {\n\t\tif (!pages[j])\n\t\t\tbreak;\n\t\tput_page(pages[j]);\n\t}\n out:\n\tkfree(pages);\n\tbio_put(bio);\n\treturn ERR_PTR(ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-772', 'CWE-787'], 'message': 'fix unbalanced page refcounting in bio_map_user_iov\n\nbio_map_user_iov and bio_unmap_user do unbalanced pages refcounting if\nIO vector has small consecutive buffers belonging to the same page.\nbio_add_pc_page merges them into one, but the page reference is never\ndropped.\n\nCc: stable@vger.kernel.org\nSigned-off-by: Vitaly Mayatskikh \nSigned-off-by: Al Viro '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: key_ref_t key_create_or_update(key_ref_t keyring_ref,\n\t\t\t const char *type,\n\t\t\t const char *description,\n\t\t\t const void *payload,\n\t\t\t size_t plen,\n\t\t\t key_perm_t perm,\n\t\t\t unsigned long flags)\n{\n\tstruct keyring_index_key index_key = {\n\t\t.description\t= description,\n\t};\n\tstruct key_preparsed_payload prep;\n\tstruct assoc_array_edit *edit;\n\tconst struct cred *cred = current_cred();\n\tstruct key *keyring, *key = NULL;\n\tkey_ref_t key_ref;\n\tint ret;\n\tstruct key_restriction *restrict_link = NULL;\n\n\t/* look up the key type to see if it's one of the registered kernel\n\t * types */\n\tindex_key.type = key_type_lookup(type);\n\tif (IS_ERR(index_key.type)) {\n\t\tkey_ref = ERR_PTR(-ENODEV);\n\t\tgoto error;\n\t}\n\n\tkey_ref = ERR_PTR(-EINVAL);\n\tif (!index_key.type->instantiate ||\n\t (!index_key.description && !index_key.type->preparse))\n\t\tgoto error_put_type;\n\n\tkeyring = key_ref_to_ptr(keyring_ref);\n\n\tkey_check(keyring);\n\n\tkey_ref = ERR_PTR(-EPERM);\n\tif (!(flags & KEY_ALLOC_BYPASS_RESTRICTION))\n\t\trestrict_link = keyring->restrict_link;\n\n\tkey_ref = ERR_PTR(-ENOTDIR);\n\tif (keyring->type != &key_type_keyring)\n\t\tgoto error_put_type;\n\n\tmemset(&prep, 0, sizeof(prep));\n\tprep.data = payload;\n\tprep.datalen = plen;\n\tprep.quotalen = index_key.type->def_datalen;\n\tprep.expiry = TIME_T_MAX;\n\tif (index_key.type->preparse) {\n\t\tret = index_key.type->preparse(&prep);\n\t\tif (ret < 0) {\n\t\t\tkey_ref = ERR_PTR(ret);\n\t\t\tgoto error_free_prep;\n\t\t}\n\t\tif (!index_key.description)\n\t\t\tindex_key.description = prep.description;\n\t\tkey_ref = ERR_PTR(-EINVAL);\n\t\tif (!index_key.description)\n\t\t\tgoto error_free_prep;\n\t}\n\tindex_key.desc_len = strlen(index_key.description);\n\n\tret = __key_link_begin(keyring, &index_key, &edit);\n\tif (ret < 0) {\n\t\tkey_ref = ERR_PTR(ret);\n\t\tgoto error_free_prep;\n\t}\n\n\tif (restrict_link && restrict_link->check) {\n\t\tret = restrict_link->check(keyring, index_key.type,\n\t\t\t\t\t &prep.payload, restrict_link->key);\n\t\tif (ret < 0) {\n\t\t\tkey_ref = ERR_PTR(ret);\n\t\t\tgoto error_link_end;\n\t\t}\n\t}\n\n\t/* if we're going to allocate a new key, we're going to have\n\t * to modify the keyring */\n\tret = key_permission(keyring_ref, KEY_NEED_WRITE);\n\tif (ret < 0) {\n\t\tkey_ref = ERR_PTR(ret);\n\t\tgoto error_link_end;\n\t}\n\n\t/* if it's possible to update this type of key, search for an existing\n\t * key of the same type and description in the destination keyring and\n\t * update that instead if possible\n\t */\n\tif (index_key.type->update) {\n\t\tkey_ref = find_key_to_update(keyring_ref, &index_key);\n\t\tif (key_ref)\n\t\t\tgoto found_matching_key;\n\t}\n\n\t/* if the client doesn't provide, decide on the permissions we want */\n\tif (perm == KEY_PERM_UNDEF) {\n\t\tperm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR;\n\t\tperm |= KEY_USR_VIEW;\n\n\t\tif (index_key.type->read)\n\t\t\tperm |= KEY_POS_READ;\n\n\t\tif (index_key.type == &key_type_keyring ||\n\t\t index_key.type->update)\n\t\t\tperm |= KEY_POS_WRITE;\n\t}\n\n\t/* allocate a new key */\n\tkey = key_alloc(index_key.type, index_key.description,\n\t\t\tcred->fsuid, cred->fsgid, cred, perm, flags, NULL);\n\tif (IS_ERR(key)) {\n\t\tkey_ref = ERR_CAST(key);\n\t\tgoto error_link_end;\n\t}\n\n\t/* instantiate it and link it into the target keyring */\n\tret = __key_instantiate_and_link(key, &prep, keyring, NULL, &edit);\n\tif (ret < 0) {\n\t\tkey_put(key);\n\t\tkey_ref = ERR_PTR(ret);\n\t\tgoto error_link_end;\n\t}\n\n\tkey_ref = make_key_ref(key, is_key_possessed(keyring_ref));\n\nerror_link_end:\n\t__key_link_end(keyring, &index_key, edit);\nerror_free_prep:\n\tif (index_key.type->preparse)\n\t\tindex_key.type->free_preparse(&prep);\nerror_put_type:\n\tkey_type_put(index_key.type);\nerror:\n\treturn key_ref;\n\n found_matching_key:\n\t/* we found a matching key, so we're going to try to update it\n\t * - we can drop the locks first as we have the key pinned\n\t */\n\t__key_link_end(keyring, &index_key, edit);\n\n\tkey_ref = __key_update(key_ref, &prep);\n\tgoto error_free_prep;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'KEYS: don't let add_key() update an uninstantiated key\n\nCurrently, when passed a key that already exists, add_key() will call the\nkey's ->update() method if such exists. But this is heavily broken in the\ncase where the key is uninstantiated because it doesn't call\n__key_instantiate_and_link(). Consequently, it doesn't do most of the\nthings that are supposed to happen when the key is instantiated, such as\nsetting the instantiation state, clearing KEY_FLAG_USER_CONSTRUCT and\nawakening tasks waiting on it, and incrementing key->user->nikeys.\n\nIt also never takes key_construction_mutex, which means that\n->instantiate() can run concurrently with ->update() on the same key. In\nthe case of the \"user\" and \"logon\" key types this causes a memory leak, at\nbest. Maybe even worse, the ->update() methods of the \"encrypted\" and\n\"trusted\" key types actually just dereference a NULL pointer when passed an\nuninstantiated key.\n\nChange key_create_or_update() to wait interruptibly for the key to finish\nconstruction before continuing.\n\nThis patch only affects *uninstantiated* keys. For now we still allow a\nnegatively instantiated key to be updated (thereby positively\ninstantiating it), although that's broken too (the next patch fixes it)\nand I'm not sure that anyone actually uses that functionality either.\n\nHere is a simple reproducer for the bug using the \"encrypted\" key type\n(requires CONFIG_ENCRYPTED_KEYS=y), though as noted above the bug\npertained to more than just the \"encrypted\" key type:\n\n #include \n #include \n #include \n\n int main(void)\n {\n int ringid = keyctl_join_session_keyring(NULL);\n\n if (fork()) {\n for (;;) {\n const char payload[] = \"update user:foo 32\";\n\n usleep(rand() % 10000);\n add_key(\"encrypted\", \"desc\", payload, sizeof(payload), ringid);\n keyctl_clear(ringid);\n }\n } else {\n for (;;)\n request_key(\"encrypted\", \"desc\", \"callout_info\", ringid);\n }\n }\n\nIt causes:\n\n BUG: unable to handle kernel NULL pointer dereference at 0000000000000018\n IP: encrypted_update+0xb0/0x170\n PGD 7a178067 P4D 7a178067 PUD 77269067 PMD 0\n PREEMPT SMP\n CPU: 0 PID: 340 Comm: reproduce Tainted: G D 4.14.0-rc1-00025-g428490e38b2e #796\n Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011\n task: ffff8a467a39a340 task.stack: ffffb15c40770000\n RIP: 0010:encrypted_update+0xb0/0x170\n RSP: 0018:ffffb15c40773de8 EFLAGS: 00010246\n RAX: 0000000000000000 RBX: ffff8a467a275b00 RCX: 0000000000000000\n RDX: 0000000000000005 RSI: ffff8a467a275b14 RDI: ffffffffb742f303\n RBP: ffffb15c40773e20 R08: 0000000000000000 R09: ffff8a467a275b17\n R10: 0000000000000020 R11: 0000000000000000 R12: 0000000000000000\n R13: 0000000000000000 R14: ffff8a4677057180 R15: ffff8a467a275b0f\n FS: 00007f5d7fb08700(0000) GS:ffff8a467f200000(0000) knlGS:0000000000000000\n CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033\n CR2: 0000000000000018 CR3: 0000000077262005 CR4: 00000000001606f0\n Call Trace:\n key_create_or_update+0x2bc/0x460\n SyS_add_key+0x10c/0x1d0\n entry_SYSCALL_64_fastpath+0x1f/0xbe\n RIP: 0033:0x7f5d7f211259\n RSP: 002b:00007ffed03904c8 EFLAGS: 00000246 ORIG_RAX: 00000000000000f8\n RAX: ffffffffffffffda RBX: 000000003b2a7955 RCX: 00007f5d7f211259\n RDX: 00000000004009e4 RSI: 00000000004009ff RDI: 0000000000400a04\n RBP: 0000000068db8bad R08: 000000003b2a7955 R09: 0000000000000004\n R10: 000000000000001a R11: 0000000000000246 R12: 0000000000400868\n R13: 00007ffed03905d0 R14: 0000000000000000 R15: 0000000000000000\n Code: 77 28 e8 64 34 1f 00 45 31 c0 31 c9 48 8d 55 c8 48 89 df 48 8d 75 d0 e8 ff f9 ff ff 85 c0 41 89 c4 0f 88 84 00 00 00 4c 8b 7d c8 <49> 8b 75 18 4c 89 ff e8 24 f8 ff ff 85 c0 41 89 c4 78 6d 49 8b\n RIP: encrypted_update+0xb0/0x170 RSP: ffffb15c40773de8\n CR2: 0000000000000018\n\nCc: # v2.6.12+\nReported-by: Eric Biggers \nSigned-off-by: David Howells \ncc: Eric Biggers '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: COMPAT_SYSCALL_DEFINE5(waitid,\n\t\tint, which, compat_pid_t, pid,\n\t\tstruct compat_siginfo __user *, infop, int, options,\n\t\tstruct compat_rusage __user *, uru)\n{\n\tstruct rusage ru;\n\tstruct waitid_info info = {.status = 0};\n\tlong err = kernel_waitid(which, pid, &info, options, uru ? &ru : NULL);\n\tint signo = 0;\n\tif (err > 0) {\n\t\tsigno = SIGCHLD;\n\t\terr = 0;\n\t\tif (uru) {\n\t\t\t/* kernel_waitid() overwrites everything in ru */\n\t\t\tif (COMPAT_USE_64BIT_TIME)\n\t\t\t\terr = copy_to_user(uru, &ru, sizeof(ru));\n\t\t\telse\n\t\t\t\terr = put_compat_rusage(&ru, uru);\n\t\t\tif (err)\n\t\t\t\treturn -EFAULT;\n\t\t}\n\t}\n\n\tif (!infop)\n\t\treturn err;\n\n\tuser_access_begin();\n\tunsafe_put_user(signo, &infop->si_signo, Efault);\n\tunsafe_put_user(0, &infop->si_errno, Efault);\n\tunsafe_put_user(info.cause, &infop->si_code, Efault);\n\tunsafe_put_user(info.pid, &infop->si_pid, Efault);\n\tunsafe_put_user(info.uid, &infop->si_uid, Efault);\n\tunsafe_put_user(info.status, &infop->si_status, Efault);\n\tuser_access_end();\n\treturn err;\nEfault:\n\tuser_access_end();\n\treturn -EFAULT;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'waitid(): Add missing access_ok() checks\n\nAdds missing access_ok() checks.\n\nCVE-2017-5123\n\nReported-by: Chris Salls \nSigned-off-by: Kees Cook \nAcked-by: Al Viro \nFixes: 4c48abe91be0 (\"waitid(): switch copyout of siginfo to unsafe_put_user()\")\nCc: stable@kernel.org # 4.13\nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void PackLinuxElf32::unpack(OutputFile *fo)\n{\n unsigned const c_phnum = get_te16(&ehdri.e_phnum);\n unsigned old_data_off = 0;\n unsigned old_data_len = 0;\n unsigned old_dtinit = 0;\n\n unsigned szb_info = sizeof(b_info);\n {\n if (get_te32(&ehdri.e_entry) < 0x401180\n && Elf32_Ehdr::EM_386 ==get_te16(&ehdri.e_machine)\n && Elf32_Ehdr::ET_EXEC==get_te16(&ehdri.e_type)) {\n // Beware ET_DYN.e_entry==0x10f0 (or so) does NOT qualify here.\n /* old style, 8-byte b_info */\n szb_info = 2*sizeof(unsigned);\n }\n }\n\n fi->seek(overlay_offset - sizeof(l_info), SEEK_SET);\n fi->readx(&linfo, sizeof(linfo));\n lsize = get_te16(&linfo.l_lsize);\n p_info hbuf; fi->readx(&hbuf, sizeof(hbuf));\n unsigned orig_file_size = get_te32(&hbuf.p_filesize);\n blocksize = get_te32(&hbuf.p_blocksize);\n if (file_size > (off_t)orig_file_size || blocksize > orig_file_size\n || !mem_size_valid(1, blocksize, OVERHEAD))\n throwCantUnpack(\"p_info corrupted\");\n\n#define MAX_ELF_HDR 512\n union {\n unsigned char buf[MAX_ELF_HDR];\n struct { Elf32_Ehdr ehdr; Elf32_Phdr phdr; } e;\n } u;\n COMPILE_TIME_ASSERT(sizeof(u) == MAX_ELF_HDR)\n Elf32_Ehdr *const ehdr = (Elf32_Ehdr *) u.buf;\n Elf32_Phdr const *phdr = 0;\n\n ibuf.alloc(blocksize + OVERHEAD);\n b_info bhdr; memset(&bhdr, 0, sizeof(bhdr));\n fi->readx(&bhdr, szb_info);\n ph.u_len = get_te32(&bhdr.sz_unc);\n ph.c_len = get_te32(&bhdr.sz_cpr);\n if (ph.c_len > (unsigned)file_size || ph.c_len == 0 || ph.u_len == 0\n || ph.u_len > sizeof(u))\n throwCantUnpack(\"b_info corrupted\");\n ph.filter_cto = bhdr.b_cto8;\n\n // Peek at resulting Ehdr and Phdrs for use in controlling unpacking.\n // Uncompress an extra time, and don't verify or update checksums.\n if (ibuf.getSize() < ph.c_len || sizeof(u) < ph.u_len)\n throwCompressedDataViolation();\n fi->readx(ibuf, ph.c_len);\n decompress(ibuf, (upx_byte *)ehdr, false);\n if (ehdr->e_type !=ehdri.e_type\n || ehdr->e_machine!=ehdri.e_machine\n || ehdr->e_version!=ehdri.e_version\n || ehdr->e_flags !=ehdri.e_flags\n || ehdr->e_ehsize !=ehdri.e_ehsize\n // check EI_MAG[0-3], EI_CLASS, EI_DATA, EI_VERSION\n || memcmp(ehdr->e_ident, ehdri.e_ident, Elf32_Ehdr::EI_OSABI))\n throwCantUnpack(\"ElfXX_Ehdr corrupted\");\n fi->seek(- (off_t) (szb_info + ph.c_len), SEEK_CUR);\n\n unsigned const u_phnum = get_te16(&ehdr->e_phnum);\n unsigned total_in = 0;\n unsigned total_out = 0;\n unsigned c_adler = upx_adler32(NULL, 0);\n unsigned u_adler = upx_adler32(NULL, 0);\n\n // Packed ET_EXE has no PT_DYNAMIC.\n // Packed ET_DYN has original PT_DYNAMIC for info needed by rtld.\n bool const is_shlib = !!elf_find_ptype(Elf32_Phdr::PT_DYNAMIC, phdri, c_phnum);\n if (is_shlib) {\n // Unpack and output the Ehdr and Phdrs for real.\n // This depends on position within input file fi.\n unpackExtent(ph.u_len, fo, total_in, total_out,\n c_adler, u_adler, false, szb_info);\n\n // The first PT_LOAD. Part is not compressed (for benefit of rtld.)\n // Read enough to position the input for next unpackExtent.\n fi->seek(0, SEEK_SET);\n fi->readx(ibuf, overlay_offset + sizeof(hbuf) + szb_info + ph.c_len);\n overlay_offset -= sizeof(linfo);\n if (fo) {\n fo->write(ibuf + ph.u_len, overlay_offset - ph.u_len);\n }\n // Search the Phdrs of compressed\n int n_ptload = 0;\n phdr = (Elf32_Phdr *) (void *) (1+ (Elf32_Ehdr *)(unsigned char *)ibuf);\n for (unsigned j=0; j < u_phnum; ++phdr, ++j) {\n if (PT_LOAD32==get_te32(&phdr->p_type) && 0!=n_ptload++) {\n old_data_off = get_te32(&phdr->p_offset);\n old_data_len = get_te32(&phdr->p_filesz);\n break;\n }\n }\n\n total_in = overlay_offset;\n total_out = overlay_offset;\n ph.u_len = 0;\n\n // Decompress and unfilter the tail of first PT_LOAD.\n phdr = (Elf32_Phdr *) (void *) (1+ ehdr);\n for (unsigned j=0; j < u_phnum; ++phdr, ++j) {\n if (PT_LOAD32==get_te32(&phdr->p_type)) {\n ph.u_len = get_te32(&phdr->p_filesz) - overlay_offset;\n break;\n }\n }\n unpackExtent(ph.u_len, fo, total_in, total_out,\n c_adler, u_adler, false, szb_info);\n }\n else { // main executable\n // Decompress each PT_LOAD.\n bool first_PF_X = true;\n phdr = (Elf32_Phdr *) (void *) (1+ ehdr); // uncompressed\n for (unsigned j=0; j < u_phnum; ++phdr, ++j) {\n if (PT_LOAD32==get_te32(&phdr->p_type)) {\n unsigned const filesz = get_te32(&phdr->p_filesz);\n unsigned const offset = get_te32(&phdr->p_offset);\n if (fo)\n fo->seek(offset, SEEK_SET);\n if (Elf32_Phdr::PF_X & get_te32(&phdr->p_flags)) {\n unpackExtent(filesz, fo, total_in, total_out,\n c_adler, u_adler, first_PF_X, szb_info);\n first_PF_X = false;\n }\n else {\n unpackExtent(filesz, fo, total_in, total_out,\n c_adler, u_adler, false, szb_info);\n }\n }\n }\n }\n phdr = phdri;\n load_va = 0;\n for (unsigned j=0; j < c_phnum; ++j) {\n if (PT_LOAD32==get_te32(&phdr->p_type)) {\n load_va = get_te32(&phdr->p_vaddr);\n break;\n }\n }\n if (is_shlib\n || ((unsigned)(get_te32(&ehdri.e_entry) - load_va) + up4(lsize) +\n ph.getPackHeaderSize() + sizeof(overlay_offset))\n < up4(file_size)) {\n // Loader is not at end; skip past it.\n funpad4(fi); // MATCH01\n unsigned d_info[4]; fi->readx(d_info, sizeof(d_info));\n if (0==old_dtinit) {\n old_dtinit = d_info[2 + (0==d_info[0])];\n }\n fi->seek(lsize - sizeof(d_info), SEEK_CUR);\n }\n\n // The gaps between PT_LOAD and after last PT_LOAD\n phdr = (Elf32_Phdr *) (u.buf + sizeof(*ehdr));\n unsigned hi_offset(0);\n for (unsigned j = 0; j < u_phnum; ++j) {\n if (PT_LOAD32==phdr[j].p_type\n && hi_offset < phdr[j].p_offset)\n hi_offset = phdr[j].p_offset;\n }\n for (unsigned j = 0; j < u_phnum; ++j) {\n unsigned const size = find_LOAD_gap(phdr, j, u_phnum);\n if (size) {\n unsigned const where = get_te32(&phdr[j].p_offset) +\n get_te32(&phdr[j].p_filesz);\n if (fo)\n fo->seek(where, SEEK_SET);\n unpackExtent(size, fo, total_in, total_out,\n c_adler, u_adler, false, szb_info,\n (phdr[j].p_offset != hi_offset));\n }\n }\n\n // check for end-of-file\n fi->readx(&bhdr, szb_info);\n unsigned const sz_unc = ph.u_len = get_te32(&bhdr.sz_unc);\n\n if (sz_unc == 0) { // uncompressed size 0 -> EOF\n // note: magic is always stored le32\n unsigned const sz_cpr = get_le32(&bhdr.sz_cpr);\n if (sz_cpr != UPX_MAGIC_LE32) // sz_cpr must be h->magic\n throwCompressedDataViolation();\n }\n else { // extra bytes after end?\n throwCompressedDataViolation();\n }\n\n if (is_shlib) { // the non-first PT_LOAD\n int n_ptload = 0;\n unsigned load_off = 0;\n phdr = (Elf32_Phdr *) (u.buf + sizeof(*ehdr));\n for (unsigned j= 0; j < u_phnum; ++j, ++phdr) {\n if (PT_LOAD32==get_te32(&phdr->p_type) && 0!=n_ptload++) {\n load_off = get_te32(&phdr->p_offset);\n fi->seek(old_data_off, SEEK_SET);\n fi->readx(ibuf, old_data_len);\n total_in += old_data_len;\n total_out += old_data_len;\n if (fo) {\n fo->seek(get_te32(&phdr->p_offset), SEEK_SET);\n fo->rewrite(ibuf, old_data_len);\n }\n }\n }\n // Restore DT_INIT.d_val\n phdr = (Elf32_Phdr *) (u.buf + sizeof(*ehdr));\n for (unsigned j= 0; j < u_phnum; ++j, ++phdr) {\n if (phdr->PT_DYNAMIC==get_te32(&phdr->p_type)) {\n unsigned const dyn_off = get_te32(&phdr->p_offset);\n unsigned const dyn_len = get_te32(&phdr->p_filesz);\n Elf32_Dyn *dyn = (Elf32_Dyn *)((unsigned char *)ibuf +\n (dyn_off - load_off));\n for (unsigned j2= 0; j2 < dyn_len; ++dyn, j2 += sizeof(*dyn)) {\n if (dyn->DT_INIT==get_te32(&dyn->d_tag)) {\n if (fo) {\n fo->seek(sizeof(unsigned) + j2 + dyn_off, SEEK_SET);\n fo->rewrite(&old_dtinit, sizeof(old_dtinit));\n fo->seek(0, SEEK_END);\n }\n break;\n }\n }\n }\n }\n }\n\n // update header with totals\n ph.c_len = total_in;\n ph.u_len = total_out;\n\n // all bytes must be written\n if (total_out != orig_file_size)\n throwEOFException();\n\n // finally test the checksums\n if (ph.c_adler != c_adler || ph.u_adler != u_adler)\n throwChecksumError();\n#undef MAX_ELF_HDR\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Protect against bad crafted input.\n\nhttps://github.com/upx/upx/issues/128\n\tmodified: p_lx_elf.cpp'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: X509_NAME_oneline_ex(X509_NAME * a,\n char *buf,\n unsigned int *size,\n unsigned long flag)\n{\n BIO *out = NULL;\n\n out = BIO_new(BIO_s_mem ());\n if (X509_NAME_print_ex(out, a, 0, flag) > 0) {\n if (buf != NULL && (*size) > (unsigned int) BIO_number_written(out)) {\n memset(buf, 0, *size);\n BIO_read(out, buf, (int) BIO_number_written(out));\n }\n else {\n *size = BIO_number_written(out);\n }\n }\n BIO_free(out);\n return (buf);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix PKINIT cert matching data construction\n\nRewrite X509_NAME_oneline_ex() and its call sites to use dynamic\nallocation and to perform proper error checking.\n\nticket: 8617\ntarget_version: 1.16\ntarget_version: 1.15-next\ntarget_version: 1.14-next\ntags: pullup'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: glob (const char *pattern, int flags, int (*errfunc) (const char *, int),\n glob_t *pglob)\n{\n const char *filename;\n char *dirname = NULL;\n size_t dirlen;\n int status;\n size_t oldcount;\n int meta;\n int dirname_modified;\n int malloc_dirname = 0;\n glob_t dirs;\n int retval = 0;\n size_t alloca_used = 0;\n\n if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)\n {\n __set_errno (EINVAL);\n return -1;\n }\n\n /* POSIX requires all slashes to be matched. This means that with\n a trailing slash we must match only directories. */\n if (pattern[0] && pattern[strlen (pattern) - 1] == '/')\n flags |= GLOB_ONLYDIR;\n\n if (!(flags & GLOB_DOOFFS))\n /* Have to do this so 'globfree' knows where to start freeing. It\n also makes all the code that uses gl_offs simpler. */\n pglob->gl_offs = 0;\n\n if (!(flags & GLOB_APPEND))\n {\n pglob->gl_pathc = 0;\n if (!(flags & GLOB_DOOFFS))\n pglob->gl_pathv = NULL;\n else\n {\n size_t i;\n\n if (pglob->gl_offs >= ~((size_t) 0) / sizeof (char *))\n return GLOB_NOSPACE;\n\n pglob->gl_pathv = (char **) malloc ((pglob->gl_offs + 1)\n * sizeof (char *));\n if (pglob->gl_pathv == NULL)\n return GLOB_NOSPACE;\n\n for (i = 0; i <= pglob->gl_offs; ++i)\n pglob->gl_pathv[i] = NULL;\n }\n }\n\n if (flags & GLOB_BRACE)\n {\n const char *begin;\n\n if (flags & GLOB_NOESCAPE)\n begin = strchr (pattern, '{');\n else\n {\n begin = pattern;\n while (1)\n {\n if (*begin == '\\0')\n {\n begin = NULL;\n break;\n }\n\n if (*begin == '\\\\' && begin[1] != '\\0')\n ++begin;\n else if (*begin == '{')\n break;\n\n ++begin;\n }\n }\n\n if (begin != NULL)\n {\n /* Allocate working buffer large enough for our work. Note that\n we have at least an opening and closing brace. */\n size_t firstc;\n char *alt_start;\n const char *p;\n const char *next;\n const char *rest;\n size_t rest_len;\n char *onealt;\n size_t pattern_len = strlen (pattern) - 1;\n int alloca_onealt = glob_use_alloca (alloca_used, pattern_len);\n if (alloca_onealt)\n onealt = alloca_account (pattern_len, alloca_used);\n else\n {\n onealt = malloc (pattern_len);\n if (onealt == NULL)\n return GLOB_NOSPACE;\n }\n\n /* We know the prefix for all sub-patterns. */\n alt_start = mempcpy (onealt, pattern, begin - pattern);\n\n /* Find the first sub-pattern and at the same time find the\n rest after the closing brace. */\n next = next_brace_sub (begin + 1, flags);\n if (next == NULL)\n {\n /* It is an invalid expression. */\n illegal_brace:\n if (__glibc_unlikely (!alloca_onealt))\n free (onealt);\n flags &= ~GLOB_BRACE;\n goto no_brace;\n }\n\n /* Now find the end of the whole brace expression. */\n rest = next;\n while (*rest != '}')\n {\n rest = next_brace_sub (rest + 1, flags);\n if (rest == NULL)\n /* It is an illegal expression. */\n goto illegal_brace;\n }\n /* Please note that we now can be sure the brace expression\n is well-formed. */\n rest_len = strlen (++rest) + 1;\n\n /* We have a brace expression. BEGIN points to the opening {,\n NEXT points past the terminator of the first element, and END\n points past the final }. We will accumulate result names from\n recursive runs for each brace alternative in the buffer using\n GLOB_APPEND. */\n firstc = pglob->gl_pathc;\n\n p = begin + 1;\n while (1)\n {\n int result;\n\n /* Construct the new glob expression. */\n mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);\n\n result = glob (onealt,\n ((flags & ~(GLOB_NOCHECK | GLOB_NOMAGIC))\n | GLOB_APPEND), errfunc, pglob);\n\n /* If we got an error, return it. */\n if (result && result != GLOB_NOMATCH)\n {\n if (__glibc_unlikely (!alloca_onealt))\n free (onealt);\n if (!(flags & GLOB_APPEND))\n {\n globfree (pglob);\n pglob->gl_pathc = 0;\n }\n return result;\n }\n\n if (*next == '}')\n /* We saw the last entry. */\n break;\n\n p = next + 1;\n next = next_brace_sub (p, flags);\n assert (next != NULL);\n }\n\n if (__glibc_unlikely (!alloca_onealt))\n free (onealt);\n\n if (pglob->gl_pathc != firstc)\n /* We found some entries. */\n return 0;\n else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))\n return GLOB_NOMATCH;\n }\n }\n\n no_brace:\n oldcount = pglob->gl_pathc + pglob->gl_offs;\n\n /* Find the filename. */\n filename = strrchr (pattern, '/');\n\n#if defined __MSDOS__ || defined WINDOWS32\n /* The case of \"d:pattern\". Since ':' is not allowed in\n file names, we can safely assume that wherever it\n happens in pattern, it signals the filename part. This\n is so we could some day support patterns like \"[a-z]:foo\". */\n if (filename == NULL)\n filename = strchr (pattern, ':');\n#endif /* __MSDOS__ || WINDOWS32 */\n\n dirname_modified = 0;\n if (filename == NULL)\n {\n /* This can mean two things: a simple name or \"~name\". The latter\n case is nothing but a notation for a directory. */\n if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~')\n {\n dirname = (char *) pattern;\n dirlen = strlen (pattern);\n\n /* Set FILENAME to NULL as a special flag. This is ugly but\n other solutions would require much more code. We test for\n this special case below. */\n filename = NULL;\n }\n else\n {\n if (__glibc_unlikely (pattern[0] == '\\0'))\n {\n dirs.gl_pathv = NULL;\n goto no_matches;\n }\n\n filename = pattern;\n dirname = (char *) \".\";\n dirlen = 0;\n }\n }\n else if (filename == pattern\n || (filename == pattern + 1 && pattern[0] == '\\\\'\n && (flags & GLOB_NOESCAPE) == 0))\n {\n /* \"/pattern\" or \"\\\\/pattern\". */\n dirname = (char *) \"/\";\n dirlen = 1;\n ++filename;\n }\n else\n {\n char *newp;\n dirlen = filename - pattern;\n\n#if defined __MSDOS__ || defined WINDOWS32\n if (*filename == ':'\n || (filename > pattern + 1 && filename[-1] == ':'))\n {\n char *drive_spec;\n\n ++dirlen;\n drive_spec = __alloca (dirlen + 1);\n *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\\0';\n /* For now, disallow wildcards in the drive spec, to\n prevent infinite recursion in glob. */\n if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))\n return GLOB_NOMATCH;\n /* If this is \"d:pattern\", we need to copy ':' to DIRNAME\n as well. If it's \"d:/pattern\", don't remove the slash\n from \"d:/\", since \"d:\" and \"d:/\" are not the same.*/\n }\n#endif\n\n if (glob_use_alloca (alloca_used, dirlen + 1))\n newp = alloca_account (dirlen + 1, alloca_used);\n else\n {\n newp = malloc (dirlen + 1);\n if (newp == NULL)\n return GLOB_NOSPACE;\n malloc_dirname = 1;\n }\n *((char *) mempcpy (newp, pattern, dirlen)) = '\\0';\n dirname = newp;\n ++filename;\n\n#if defined __MSDOS__ || defined WINDOWS32\n bool drive_root = (dirlen > 1\n && (dirname[dirlen - 1] == ':'\n || (dirlen > 2 && dirname[dirlen - 2] == ':'\n && dirname[dirlen - 1] == '/')));\n#else\n bool drive_root = false;\n#endif\n\n if (filename[0] == '\\0' && dirlen > 1 && !drive_root)\n /* \"pattern/\". Expand \"pattern\", appending slashes. */\n {\n int orig_flags = flags;\n if (!(flags & GLOB_NOESCAPE) && dirname[dirlen - 1] == '\\\\')\n {\n /* \"pattern\\\\/\". Remove the final backslash if it hasn't\n been quoted. */\n char *p = (char *) &dirname[dirlen - 1];\n\n while (p > dirname && p[-1] == '\\\\') --p;\n if ((&dirname[dirlen] - p) & 1)\n {\n *(char *) &dirname[--dirlen] = '\\0';\n flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);\n }\n }\n int val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);\n if (val == 0)\n pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)\n | (flags & GLOB_MARK));\n else if (val == GLOB_NOMATCH && flags != orig_flags)\n {\n /* Make sure globfree (&dirs); is a nop. */\n dirs.gl_pathv = NULL;\n flags = orig_flags;\n oldcount = pglob->gl_pathc + pglob->gl_offs;\n goto no_matches;\n }\n retval = val;\n goto out;\n }\n }\n\n if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')\n {\n if (dirname[1] == '\\0' || dirname[1] == '/'\n || (!(flags & GLOB_NOESCAPE) && dirname[1] == '\\\\'\n && (dirname[2] == '\\0' || dirname[2] == '/')))\n {\n /* Look up home directory. */\n char *home_dir = getenv (\"HOME\");\n int malloc_home_dir = 0;\n if (home_dir == NULL || home_dir[0] == '\\0')\n {\n#ifdef WINDOWS32\n /* Windows NT defines HOMEDRIVE and HOMEPATH. But give\n preference to HOME, because the user can change HOME. */\n const char *home_drive = getenv (\"HOMEDRIVE\");\n const char *home_path = getenv (\"HOMEPATH\");\n\n if (home_drive != NULL && home_path != NULL)\n {\n size_t home_drive_len = strlen (home_drive);\n size_t home_path_len = strlen (home_path);\n char *mem = alloca (home_drive_len + home_path_len + 1);\n\n memcpy (mem, home_drive, home_drive_len);\n memcpy (mem + home_drive_len, home_path, home_path_len + 1);\n home_dir = mem;\n }\n else\n home_dir = \"c:/users/default\"; /* poor default */\n#else\n int err;\n struct passwd *p;\n struct passwd pwbuf;\n struct scratch_buffer s;\n scratch_buffer_init (&s);\n while (true)\n {\n p = NULL;\n err = __getlogin_r (s.data, s.length);\n if (err == 0)\n {\n# if defined HAVE_GETPWNAM_R || defined _LIBC\n size_t ssize = strlen (s.data) + 1;\n err = getpwnam_r (s.data, &pwbuf, s.data + ssize,\n s.length - ssize, &p);\n# else\n p = getpwnam (s.data);\n if (p == NULL)\n err = errno;\n# endif\n }\n if (err != ERANGE)\n break;\n if (!scratch_buffer_grow (&s))\n {\n retval = GLOB_NOSPACE;\n goto out;\n }\n }\n if (err == 0)\n {\n home_dir = strdup (p->pw_dir);\n malloc_home_dir = 1;\n }\n scratch_buffer_free (&s);\n if (err == 0 && home_dir == NULL)\n {\n retval = GLOB_NOSPACE;\n goto out;\n }\n#endif /* WINDOWS32 */\n }\n if (home_dir == NULL || home_dir[0] == '\\0')\n {\n if (__glibc_unlikely (malloc_home_dir))\n free (home_dir);\n if (flags & GLOB_TILDE_CHECK)\n {\n retval = GLOB_NOMATCH;\n goto out;\n }\n else\n {\n home_dir = (char *) \"~\"; /* No luck. */\n malloc_home_dir = 0;\n }\n }\n /* Now construct the full directory. */\n if (dirname[1] == '\\0')\n {\n if (__glibc_unlikely (malloc_dirname))\n free (dirname);\n\n dirname = home_dir;\n dirlen = strlen (dirname);\n malloc_dirname = malloc_home_dir;\n }\n else\n {\n char *newp;\n size_t home_len = strlen (home_dir);\n int use_alloca = glob_use_alloca (alloca_used, home_len + dirlen);\n if (use_alloca)\n newp = alloca_account (home_len + dirlen, alloca_used);\n else\n {\n newp = malloc (home_len + dirlen);\n if (newp == NULL)\n {\n if (__glibc_unlikely (malloc_home_dir))\n free (home_dir);\n retval = GLOB_NOSPACE;\n goto out;\n }\n }\n\n mempcpy (mempcpy (newp, home_dir, home_len),\n &dirname[1], dirlen);\n\n if (__glibc_unlikely (malloc_dirname))\n free (dirname);\n\n dirname = newp;\n dirlen += home_len - 1;\n malloc_dirname = !use_alloca;\n\n if (__glibc_unlikely (malloc_home_dir))\n free (home_dir);\n }\n dirname_modified = 1;\n }\n else\n {\n#ifndef WINDOWS32\n char *end_name = strchr (dirname, '/');\n char *user_name;\n int malloc_user_name = 0;\n char *unescape = NULL;\n\n if (!(flags & GLOB_NOESCAPE))\n {\n if (end_name == NULL)\n {\n unescape = strchr (dirname, '\\\\');\n if (unescape)\n end_name = strchr (unescape, '\\0');\n }\n else\n unescape = memchr (dirname, '\\\\', end_name - dirname);\n }\n if (end_name == NULL)\n user_name = dirname + 1;\n else\n {\n char *newp;\n if (glob_use_alloca (alloca_used, end_name - dirname))\n newp = alloca_account (end_name - dirname, alloca_used);\n else\n {\n newp = malloc (end_name - dirname);\n if (newp == NULL)\n {\n retval = GLOB_NOSPACE;\n goto out;\n }\n malloc_user_name = 1;\n }\n if (unescape != NULL)\n {\n char *p = mempcpy (newp, dirname + 1,\n unescape - dirname - 1);\n char *q = unescape;\n while (*q != '\\0')\n {\n if (*q == '\\\\')\n {\n if (q[1] == '\\0')\n {\n /* \"~fo\\\\o\\\\\" unescape to user_name \"foo\\\\\",\n but \"~fo\\\\o\\\\/\" unescape to user_name\n \"foo\". */\n if (filename == NULL)\n *p++ = '\\\\';\n break;\n }\n ++q;\n }\n *p++ = *q++;\n }\n *p = '\\0';\n }\n else\n *((char *) mempcpy (newp, dirname + 1, end_name - dirname))\n = '\\0';\n user_name = newp;\n }\n\n /* Look up specific user's home directory. */\n {\n struct passwd *p;\n struct scratch_buffer pwtmpbuf;\n scratch_buffer_init (&pwtmpbuf);\n\n# if defined HAVE_GETPWNAM_R || defined _LIBC\n struct passwd pwbuf;\n\n while (getpwnam_r (user_name, &pwbuf,\n pwtmpbuf.data, pwtmpbuf.length, &p)\n == ERANGE)\n {\n if (!scratch_buffer_grow (&pwtmpbuf))\n {\n retval = GLOB_NOSPACE;\n goto out;\n }\n }\n# else\n p = getpwnam (user_name);\n# endif\n\n if (__glibc_unlikely (malloc_user_name))\n free (user_name);\n\n /* If we found a home directory use this. */\n if (p != NULL)\n {\n size_t home_len = strlen (p->pw_dir);\n size_t rest_len = end_name == NULL ? 0 : strlen (end_name);\n char *d;\n\n if (__glibc_unlikely (malloc_dirname))\n free (dirname);\n malloc_dirname = 0;\n\n if (glob_use_alloca (alloca_used, home_len + rest_len + 1))\n dirname = alloca_account (home_len + rest_len + 1,\n alloca_used);\n else\n {\n dirname = malloc (home_len + rest_len + 1);\n if (dirname == NULL)\n {\n scratch_buffer_free (&pwtmpbuf);\n retval = GLOB_NOSPACE;\n goto out;\n }\n malloc_dirname = 1;\n }\n d = mempcpy (dirname, p->pw_dir, home_len);\n if (end_name != NULL)\n d = mempcpy (d, end_name, rest_len);\n *d = '\\0';\n\n dirlen = home_len + rest_len;\n dirname_modified = 1;\n }\n else\n {\n if (flags & GLOB_TILDE_CHECK)\n {\n /* We have to regard it as an error if we cannot find the\n home directory. */\n retval = GLOB_NOMATCH;\n goto out;\n }\n }\n scratch_buffer_free (&pwtmpbuf);\n }\n#endif /* !WINDOWS32 */\n }\n }\n\n /* Now test whether we looked for \"~\" or \"~NAME\". In this case we\n can give the answer now. */\n if (filename == NULL)\n {\n size_t newcount = pglob->gl_pathc + pglob->gl_offs;\n char **new_gl_pathv;\n\n if (newcount > SIZE_MAX / sizeof (char *) - 2)\n {\n nospace:\n free (pglob->gl_pathv);\n pglob->gl_pathv = NULL;\n pglob->gl_pathc = 0;\n retval = GLOB_NOSPACE;\n goto out;\n }\n\n new_gl_pathv = realloc (pglob->gl_pathv,\n (newcount + 2) * sizeof (char *));\n if (new_gl_pathv == NULL)\n goto nospace;\n pglob->gl_pathv = new_gl_pathv;\n\n if (flags & GLOB_MARK && is_dir (dirname, flags, pglob))\n {\n char *p;\n pglob->gl_pathv[newcount] = malloc (dirlen + 2);\n if (pglob->gl_pathv[newcount] == NULL)\n goto nospace;\n p = mempcpy (pglob->gl_pathv[newcount], dirname, dirlen);\n p[0] = '/';\n p[1] = '\\0';\n if (__glibc_unlikely (malloc_dirname))\n free (dirname);\n }\n else\n {\n if (__glibc_unlikely (malloc_dirname))\n pglob->gl_pathv[newcount] = dirname;\n else\n {\n pglob->gl_pathv[newcount] = strdup (dirname);\n if (pglob->gl_pathv[newcount] == NULL)\n goto nospace;\n }\n }\n pglob->gl_pathv[++newcount] = NULL;\n ++pglob->gl_pathc;\n pglob->gl_flags = flags;\n\n return 0;\n }\n\n meta = __glob_pattern_type (dirname, !(flags & GLOB_NOESCAPE));\n /* meta is 1 if correct glob pattern containing metacharacters.\n If meta has bit (1 << 2) set, it means there was an unterminated\n [ which we handle the same, using fnmatch. Broken unterminated\n pattern bracket expressions ought to be rare enough that it is\n not worth special casing them, fnmatch will do the right thing. */\n if (meta & (GLOBPAT_SPECIAL | GLOBPAT_BRACKET))\n {\n /* The directory name contains metacharacters, so we\n have to glob for the directory, and then glob for\n the pattern in each directory found. */\n size_t i;\n\n if (!(flags & GLOB_NOESCAPE) && dirlen > 0 && dirname[dirlen - 1] == '\\\\')\n {\n /* \"foo\\\\/bar\". Remove the final backslash from dirname\n if it has not been quoted. */\n char *p = (char *) &dirname[dirlen - 1];\n\n while (p > dirname && p[-1] == '\\\\') --p;\n if ((&dirname[dirlen] - p) & 1)\n *(char *) &dirname[--dirlen] = '\\0';\n }\n\n if (__glibc_unlikely ((flags & GLOB_ALTDIRFUNC) != 0))\n {\n /* Use the alternative access functions also in the recursive\n call. */\n dirs.gl_opendir = pglob->gl_opendir;\n dirs.gl_readdir = pglob->gl_readdir;\n dirs.gl_closedir = pglob->gl_closedir;\n dirs.gl_stat = pglob->gl_stat;\n dirs.gl_lstat = pglob->gl_lstat;\n }\n\n status = glob (dirname,\n ((flags & (GLOB_ERR | GLOB_NOESCAPE\n | GLOB_ALTDIRFUNC))\n | GLOB_NOSORT | GLOB_ONLYDIR),\n errfunc, &dirs);\n if (status != 0)\n {\n if ((flags & GLOB_NOCHECK) == 0 || status != GLOB_NOMATCH)\n {\n retval = status;\n goto out;\n }\n goto no_matches;\n }\n\n /* We have successfully globbed the preceding directory name.\n For each name we found, call glob_in_dir on it and FILENAME,\n appending the results to PGLOB. */\n for (i = 0; i < dirs.gl_pathc; ++i)\n {\n size_t old_pathc;\n\n old_pathc = pglob->gl_pathc;\n status = glob_in_dir (filename, dirs.gl_pathv[i],\n ((flags | GLOB_APPEND)\n & ~(GLOB_NOCHECK | GLOB_NOMAGIC)),\n errfunc, pglob, alloca_used);\n if (status == GLOB_NOMATCH)\n /* No matches in this directory. Try the next. */\n continue;\n\n if (status != 0)\n {\n globfree (&dirs);\n globfree (pglob);\n pglob->gl_pathc = 0;\n retval = status;\n goto out;\n }\n\n /* Stick the directory on the front of each name. */\n if (prefix_array (dirs.gl_pathv[i],\n &pglob->gl_pathv[old_pathc + pglob->gl_offs],\n pglob->gl_pathc - old_pathc))\n {\n globfree (&dirs);\n globfree (pglob);\n pglob->gl_pathc = 0;\n retval = GLOB_NOSPACE;\n goto out;\n }\n }\n\n flags |= GLOB_MAGCHAR;\n\n /* We have ignored the GLOB_NOCHECK flag in the 'glob_in_dir' calls.\n But if we have not found any matching entry and the GLOB_NOCHECK\n flag was set we must return the input pattern itself. */\n if (pglob->gl_pathc + pglob->gl_offs == oldcount)\n {\n no_matches:\n /* No matches. */\n if (flags & GLOB_NOCHECK)\n {\n size_t newcount = pglob->gl_pathc + pglob->gl_offs;\n char **new_gl_pathv;\n\n if (newcount > SIZE_MAX / sizeof (char *) - 2)\n {\n nospace2:\n globfree (&dirs);\n retval = GLOB_NOSPACE;\n goto out;\n }\n\n new_gl_pathv = realloc (pglob->gl_pathv,\n (newcount + 2) * sizeof (char *));\n if (new_gl_pathv == NULL)\n goto nospace2;\n pglob->gl_pathv = new_gl_pathv;\n\n pglob->gl_pathv[newcount] = strdup (pattern);\n if (pglob->gl_pathv[newcount] == NULL)\n {\n globfree (&dirs);\n globfree (pglob);\n pglob->gl_pathc = 0;\n retval = GLOB_NOSPACE;\n goto out;\n }\n\n ++pglob->gl_pathc;\n ++newcount;\n\n pglob->gl_pathv[newcount] = NULL;\n pglob->gl_flags = flags;\n }\n else\n {\n globfree (&dirs);\n retval = GLOB_NOMATCH;\n goto out;\n }\n }\n\n globfree (&dirs);\n }\n else\n {\n size_t old_pathc = pglob->gl_pathc;\n int orig_flags = flags;\n\n if (meta & GLOBPAT_BACKSLASH)\n {\n char *p = strchr (dirname, '\\\\'), *q;\n /* We need to unescape the dirname string. It is certainly\n allocated by alloca, as otherwise filename would be NULL\n or dirname wouldn't contain backslashes. */\n q = p;\n do\n {\n if (*p == '\\\\')\n {\n *q = *++p;\n --dirlen;\n }\n else\n *q = *p;\n ++q;\n }\n while (*p++ != '\\0');\n dirname_modified = 1;\n }\n if (dirname_modified)\n flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);\n status = glob_in_dir (filename, dirname, flags, errfunc, pglob,\n alloca_used);\n if (status != 0)\n {\n if (status == GLOB_NOMATCH && flags != orig_flags\n && pglob->gl_pathc + pglob->gl_offs == oldcount)\n {\n /* Make sure globfree (&dirs); is a nop. */\n dirs.gl_pathv = NULL;\n flags = orig_flags;\n goto no_matches;\n }\n retval = status;\n goto out;\n }\n\n if (dirlen > 0)\n {\n /* Stick the directory on the front of each name. */\n if (prefix_array (dirname,\n &pglob->gl_pathv[old_pathc + pglob->gl_offs],\n pglob->gl_pathc - old_pathc))\n {\n globfree (pglob);\n pglob->gl_pathc = 0;\n retval = GLOB_NOSPACE;\n goto out;\n }\n }\n }\n\n if (flags & GLOB_MARK)\n {\n /* Append slashes to directory names. */\n size_t i;\n\n for (i = oldcount; i < pglob->gl_pathc + pglob->gl_offs; ++i)\n if (is_dir (pglob->gl_pathv[i], flags, pglob))\n {\n size_t len = strlen (pglob->gl_pathv[i]) + 2;\n char *new = realloc (pglob->gl_pathv[i], len);\n if (new == NULL)\n {\n globfree (pglob);\n pglob->gl_pathc = 0;\n retval = GLOB_NOSPACE;\n goto out;\n }\n strcpy (&new[len - 2], \"/\");\n pglob->gl_pathv[i] = new;\n }\n }\n\n if (!(flags & GLOB_NOSORT))\n {\n /* Sort the vector. */\n qsort (&pglob->gl_pathv[oldcount],\n pglob->gl_pathc + pglob->gl_offs - oldcount,\n sizeof (char *), collated_compare);\n }\n\n out:\n if (__glibc_unlikely (malloc_dirname))\n free (dirname);\n\n return retval;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'glob: fix heap buffer overflow\n\n* lib/glob.c (glob): Fix off-by-one error introduced into\nglibc in commit dd7d45e838a42b0ed470c44b55901ea98d0c2bab\ndated 1997-10-29 20:33:40. Problem reported by Tim R\u00fchsen in:\nhttps://sourceware.org/bugzilla/show_bug.cgi?id=22320\nFix suggested by Bruno Haible.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void request_key_auth_describe(const struct key *key,\n\t\t\t\t struct seq_file *m)\n{\n\tstruct request_key_auth *rka = key->payload.data[0];\n\n\tseq_puts(m, \"key:\");\n\tseq_puts(m, key->description);\n\tif (key_is_instantiated(key))\n\t\tseq_printf(m, \" pid:%d ci:%zu\", rka->pid, rka->callout_len);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'KEYS: Fix race between updating and finding a negative key\n\nConsolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection\nerror into one field such that:\n\n (1) The instantiation state can be modified/read atomically.\n\n (2) The error can be accessed atomically with the state.\n\n (3) The error isn't stored unioned with the payload pointers.\n\nThis deals with the problem that the state is spread over three different\nobjects (two bits and a separate variable) and reading or updating them\natomically isn't practical, given that not only can uninstantiated keys\nchange into instantiated or rejected keys, but rejected keys can also turn\ninto instantiated keys - and someone accessing the key might not be using\nany locking.\n\nThe main side effect of this problem is that what was held in the payload\nmay change, depending on the state. For instance, you might observe the\nkey to be in the rejected state. You then read the cached error, but if\nthe key semaphore wasn't locked, the key might've become instantiated\nbetween the two reads - and you might now have something in hand that isn't\nactually an error code.\n\nThe state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error\ncode if the key is negatively instantiated. The key_is_instantiated()\nfunction is replaced with key_is_positive() to avoid confusion as negative\nkeys are also 'instantiated'.\n\nAdditionally, barriering is included:\n\n (1) Order payload-set before state-set during instantiation.\n\n (2) Order state-read before payload-read when using the key.\n\nFurther separate barriering is necessary if RCU is being used to access the\npayload content after reading the payload pointers.\n\nFixes: 146aa8b1453b (\"KEYS: Merge the type-specific data with the payload data\")\nCc: stable@vger.kernel.org # v4.4+\nReported-by: Eric Biggers \nSigned-off-by: David Howells \nReviewed-by: Eric Biggers '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void user_describe(const struct key *key, struct seq_file *m)\n{\n\tseq_puts(m, key->description);\n\tif (key_is_instantiated(key))\n\t\tseq_printf(m, \": %u\", key->datalen);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'KEYS: Fix race between updating and finding a negative key\n\nConsolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection\nerror into one field such that:\n\n (1) The instantiation state can be modified/read atomically.\n\n (2) The error can be accessed atomically with the state.\n\n (3) The error isn't stored unioned with the payload pointers.\n\nThis deals with the problem that the state is spread over three different\nobjects (two bits and a separate variable) and reading or updating them\natomically isn't practical, given that not only can uninstantiated keys\nchange into instantiated or rejected keys, but rejected keys can also turn\ninto instantiated keys - and someone accessing the key might not be using\nany locking.\n\nThe main side effect of this problem is that what was held in the payload\nmay change, depending on the state. For instance, you might observe the\nkey to be in the rejected state. You then read the cached error, but if\nthe key semaphore wasn't locked, the key might've become instantiated\nbetween the two reads - and you might now have something in hand that isn't\nactually an error code.\n\nThe state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error\ncode if the key is negatively instantiated. The key_is_instantiated()\nfunction is replaced with key_is_positive() to avoid confusion as negative\nkeys are also 'instantiated'.\n\nAdditionally, barriering is included:\n\n (1) Order payload-set before state-set during instantiation.\n\n (2) Order state-read before payload-read when using the key.\n\nFurther separate barriering is necessary if RCU is being used to access the\npayload content after reading the payload pointers.\n\nFixes: 146aa8b1453b (\"KEYS: Merge the type-specific data with the payload data\")\nCc: stable@vger.kernel.org # v4.4+\nReported-by: Eric Biggers \nSigned-off-by: David Howells \nReviewed-by: Eric Biggers '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void uwbd_stop(struct uwb_rc *rc)\n{\n\tkthread_stop(rc->uwbd.task);\n\tuwbd_flush(rc);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'uwb: properly check kthread_run return value\n\nuwbd_start() calls kthread_run() and checks that the return value is\nnot NULL. But the return value is not NULL in case kthread_run() fails,\nit takes the form of ERR_PTR(-EINTR).\n\nUse IS_ERR() instead.\n\nAlso add a check to uwbd_stop().\n\nSigned-off-by: Andrey Konovalov \nCc: stable \nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: get_endpoints(struct usbtest_dev *dev, struct usb_interface *intf)\n{\n\tint\t\t\t\ttmp;\n\tstruct usb_host_interface\t*alt;\n\tstruct usb_host_endpoint\t*in, *out;\n\tstruct usb_host_endpoint\t*iso_in, *iso_out;\n\tstruct usb_host_endpoint\t*int_in, *int_out;\n\tstruct usb_device\t\t*udev;\n\n\tfor (tmp = 0; tmp < intf->num_altsetting; tmp++) {\n\t\tunsigned\tep;\n\n\t\tin = out = NULL;\n\t\tiso_in = iso_out = NULL;\n\t\tint_in = int_out = NULL;\n\t\talt = intf->altsetting + tmp;\n\n\t\tif (override_alt >= 0 &&\n\t\t\t\toverride_alt != alt->desc.bAlternateSetting)\n\t\t\tcontinue;\n\n\t\t/* take the first altsetting with in-bulk + out-bulk;\n\t\t * ignore other endpoints and altsettings.\n\t\t */\n\t\tfor (ep = 0; ep < alt->desc.bNumEndpoints; ep++) {\n\t\t\tstruct usb_host_endpoint\t*e;\n\t\t\tint edi;\n\n\t\t\te = alt->endpoint + ep;\n\t\t\tedi = usb_endpoint_dir_in(&e->desc);\n\n\t\t\tswitch (usb_endpoint_type(&e->desc)) {\n\t\t\tcase USB_ENDPOINT_XFER_BULK:\n\t\t\t\tendpoint_update(edi, &in, &out, e);\n\t\t\t\tcontinue;\n\t\t\tcase USB_ENDPOINT_XFER_INT:\n\t\t\t\tif (dev->info->intr)\n\t\t\t\t\tendpoint_update(edi, &int_in, &int_out, e);\n\t\t\t\tcontinue;\n\t\t\tcase USB_ENDPOINT_XFER_ISOC:\n\t\t\t\tif (dev->info->iso)\n\t\t\t\t\tendpoint_update(edi, &iso_in, &iso_out, e);\n\t\t\t\t/* FALLTHROUGH */\n\t\t\tdefault:\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tif ((in && out) || iso_in || iso_out || int_in || int_out)\n\t\t\tgoto found;\n\t}\n\treturn -EINVAL;\n\nfound:\n\tudev = testdev_to_usbdev(dev);\n\tdev->info->alt = alt->desc.bAlternateSetting;\n\tif (alt->desc.bAlternateSetting != 0) {\n\t\ttmp = usb_set_interface(udev,\n\t\t\t\talt->desc.bInterfaceNumber,\n\t\t\t\talt->desc.bAlternateSetting);\n\t\tif (tmp < 0)\n\t\t\treturn tmp;\n\t}\n\n\tif (in) {\n\t\tdev->in_pipe = usb_rcvbulkpipe(udev,\n\t\t\tin->desc.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);\n\t\tdev->out_pipe = usb_sndbulkpipe(udev,\n\t\t\tout->desc.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);\n\t}\n\tif (iso_in) {\n\t\tdev->iso_in = &iso_in->desc;\n\t\tdev->in_iso_pipe = usb_rcvisocpipe(udev,\n\t\t\t\tiso_in->desc.bEndpointAddress\n\t\t\t\t\t& USB_ENDPOINT_NUMBER_MASK);\n\t}\n\n\tif (iso_out) {\n\t\tdev->iso_out = &iso_out->desc;\n\t\tdev->out_iso_pipe = usb_sndisocpipe(udev,\n\t\t\t\tiso_out->desc.bEndpointAddress\n\t\t\t\t\t& USB_ENDPOINT_NUMBER_MASK);\n\t}\n\n\tif (int_in) {\n\t\tdev->int_in = &int_in->desc;\n\t\tdev->in_int_pipe = usb_rcvintpipe(udev,\n\t\t\t\tint_in->desc.bEndpointAddress\n\t\t\t\t\t& USB_ENDPOINT_NUMBER_MASK);\n\t}\n\n\tif (int_out) {\n\t\tdev->int_out = &int_out->desc;\n\t\tdev->out_int_pipe = usb_sndintpipe(udev,\n\t\t\t\tint_out->desc.bEndpointAddress\n\t\t\t\t\t& USB_ENDPOINT_NUMBER_MASK);\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'usb: usbtest: fix NULL pointer dereference\n\nIf the usbtest driver encounters a device with an IN bulk endpoint but\nno OUT bulk endpoint, it will try to dereference a NULL pointer\n(out->desc.bEndpointAddress). The problem can be solved by adding a\nmissing test.\n\nSigned-off-by: Alan Stern \nReported-by: Andrey Konovalov \nTested-by: Andrey Konovalov \nSigned-off-by: Felipe Balbi '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: char **recode_split(const SERVER_REC *server, const char *str,\n\t\t const char *target, int len, gboolean onspace)\n{\n\tGIConv cd = (GIConv)-1;\n\tconst char *from = translit_charset;\n\tconst char *to = translit_charset;\n\tchar *translit_to = NULL;\n\tconst char *inbuf = str;\n\tconst char *previnbuf = inbuf;\n\tchar *tmp = NULL;\n\tchar *outbuf;\n\tgsize inbytesleft = strlen(inbuf);\n\tgsize outbytesleft = len;\n\tint n = 0;\n\tchar **ret;\n\n\tg_return_val_if_fail(str != NULL, NULL);\n\n\tif (settings_get_bool(\"recode\")) {\n\t\tto = find_conversion(server, target);\n\t\tif (to == NULL)\n\t\t\t/* default outgoing charset if set */\n\t\t\tto = settings_get_str(\"recode_out_default_charset\");\n\t\tif (to != NULL && *to != '\\0') {\n\t\t\tif (settings_get_bool(\"recode_transliterate\") &&\n\t\t\t !is_translit(to))\n\t\t\t\tto = translit_to = g_strconcat(to,\n\t\t\t\t\t\t\t \"//TRANSLIT\",\n\t\t\t\t\t\t\t NULL);\n\t\t} else {\n\t\t\tto = from;\n\t\t}\n\t}\n\n\tcd = g_iconv_open(to, from);\n\tif (cd == (GIConv)-1) {\n\t\t/* Fall back to splitting by byte. */\n\t\tret = strsplit_len(str, len, onspace);\n\t\tgoto out;\n\t}\n\n\ttmp = g_malloc(outbytesleft);\n\toutbuf = tmp;\n\tret = g_new(char *, 1);\n\twhile (g_iconv(cd, (char **)&inbuf, &inbytesleft, &outbuf,\n\t\t &outbytesleft) == -1) {\n\t\tif (errno != E2BIG) {\n\t\t\t/*\n\t\t\t * Conversion failed. Fall back to splitting\n\t\t\t * by byte.\n\t\t\t */\n\t\t\tret[n] = NULL;\n\t\t\tg_strfreev(ret);\n\t\t\tret = strsplit_len(str, len, onspace);\n\t\t\tgoto out;\n\t\t}\n\n\t\t/* Outbuf overflowed, split the input string. */\n\t\tif (onspace) {\n\t\t\t/*\n\t\t\t * Try to find a space to split on and leave\n\t\t\t * the space on the previous line.\n\t\t\t */\n\t\t\tint i;\n\t\t\tfor (i = 0; i < inbuf - previnbuf; i++) {\n\t\t\t\tif (previnbuf[inbuf-previnbuf-1-i] == ' ') {\n\t\t\t\t\tinbuf -= i;\n\t\t\t\t\tinbytesleft += i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tret[n++] = g_strndup(previnbuf, inbuf - previnbuf);\n\t\tret = g_renew(char *, ret, n + 1);\n\t\tprevinbuf = inbuf;\n\n\t\t/* Reset outbuf for the next substring. */\n\t\toutbuf = tmp;\n\t\toutbytesleft = len;\n\t}\n\t/* Copy the last substring into the array. */\n\tret[n++] = g_strndup(previnbuf, inbuf - previnbuf);\n\tret = g_renew(char *, ret, n + 1);\n\tret[n] = NULL;\n\nout:\n\tif (cd != (GIConv)-1)\n\t\tg_iconv_close(cd);\n\tg_free(translit_to);\n\tg_free(tmp);\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Merge branch 'security' into 'master'\n\nSecurity\n\nCloses GL#12, GL#13, GL#14, GL#15, GL#16\n\nSee merge request irssi/irssi!23'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: parse_escape(uint8_t *s, uint8_t *q) {\n\tuint16_t val;\n\tif (strlen((char *)s) > 3 &&\n\t isdigit((int) s[1]) &&\n\t isdigit((int) s[2]) &&\n\t isdigit((int) s[3])) {\n\t\t/* cast this so it fits */\n\t\tval = (uint16_t) ldns_hexdigit_to_int((char) s[1]) * 100 +\n\t\t ldns_hexdigit_to_int((char) s[2]) * 10 +\n\t\t ldns_hexdigit_to_int((char) s[3]);\n\t\tif (val > 255) {\n\t\t\t/* outside range */\n\t\t\treturn 0;\n\t\t}\n\t\t*q = (uint8_t) val;\n return 3;\n\t} else {\n\t\ts++;\n\t\tif (*s == '\\0' || isdigit((int) *s)) {\n\t\t\t/* apparently the string terminator\n\t\t\t * or a digit has been escaped...\n\t\t */\n\t\t\treturn 0;\n\t\t}\n\t\t*q = *s;\n\t\treturn 1;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'CAA and URI'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline void drbg_set_testdata(struct drbg_state *drbg,\n\t\t\t\t struct drbg_test_data *test_data)\n{\n\tif (!test_data || !test_data->testentropy)\n\t\treturn;\n\tmutex_lock(&drbg->drbg_mutex);;\n\tdrbg->test_data = test_data;\n\tmutex_unlock(&drbg->drbg_mutex);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'crypto: drbg - Convert to new rng interface\n\nThis patch converts the DRBG implementation to the new low-level\nrng interface.\n\nThis allows us to get rid of struct drbg_gen by using the new RNG\nAPI instead.\n\nSigned-off-by: Herbert Xu \nAcked-by: Stephan Mueller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: char *auth_server(int f_in, int f_out, int module, const char *host,\n\t\t const char *addr, const char *leader)\n{\n\tchar *users = lp_auth_users(module);\n\tchar challenge[MAX_DIGEST_LEN*2];\n\tchar line[BIGPATHBUFLEN];\n\tchar **auth_uid_groups = NULL;\n\tint auth_uid_groups_cnt = -1;\n\tconst char *err = NULL;\n\tint group_match = -1;\n\tchar *tok, *pass;\n\tchar opt_ch = '\\0';\n\n\t/* if no auth list then allow anyone in! */\n\tif (!users || !*users)\n\t\treturn \"\";\n\n\tgen_challenge(addr, challenge);\n\n\tio_printf(f_out, \"%s%s\\n\", leader, challenge);\n\n\tif (!read_line_old(f_in, line, sizeof line, 0)\n\t || (pass = strchr(line, ' ')) == NULL) {\n\t\trprintf(FLOG, \"auth failed on module %s from %s (%s): \"\n\t\t\t\"invalid challenge response\\n\",\n\t\t\tlp_name(module), host, addr);\n\t\treturn NULL;\n\t}\n\t*pass++ = '\\0';\n\n\tif (!(users = strdup(users)))\n\t\tout_of_memory(\"auth_server\");\n\n\tfor (tok = strtok(users, \" ,\\t\"); tok; tok = strtok(NULL, \" ,\\t\")) {\n\t\tchar *opts;\n\t\t/* See if the user appended :deny, :ro, or :rw. */\n\t\tif ((opts = strchr(tok, ':')) != NULL) {\n\t\t\t*opts++ = '\\0';\n\t\t\topt_ch = isUpper(opts) ? toLower(opts) : *opts;\n\t\t\tif (opt_ch == 'r') { /* handle ro and rw */\n\t\t\t\topt_ch = isUpper(opts+1) ? toLower(opts+1) : opts[1];\n\t\t\t\tif (opt_ch == 'o')\n\t\t\t\t\topt_ch = 'r';\n\t\t\t\telse if (opt_ch != 'w')\n\t\t\t\t\topt_ch = '\\0';\n\t\t\t} else if (opt_ch != 'd') /* if it's not deny, ignore it */\n\t\t\t\topt_ch = '\\0';\n\t\t} else\n\t\t\topt_ch = '\\0';\n\t\tif (*tok != '@') {\n\t\t\t/* Match the username */\n\t\t\tif (wildmatch(tok, line))\n\t\t\t\tbreak;\n\t\t} else {\n#ifdef HAVE_GETGROUPLIST\n\t\t\tint j;\n\t\t\t/* See if authorizing user is a real user, and if so, see\n\t\t\t * if it is in a group that matches tok+1 wildmat. */\n\t\t\tif (auth_uid_groups_cnt < 0) {\n\t\t\t\titem_list gid_list = EMPTY_ITEM_LIST;\n\t\t\t\tuid_t auth_uid;\n\t\t\t\tif (!user_to_uid(line, &auth_uid, False)\n\t\t\t\t || getallgroups(auth_uid, &gid_list) != NULL)\n\t\t\t\t\tauth_uid_groups_cnt = 0;\n\t\t\t\telse {\n\t\t\t\t\tgid_t *gid_array = gid_list.items;\n\t\t\t\t\tauth_uid_groups_cnt = gid_list.count;\n\t\t\t\t\tif ((auth_uid_groups = new_array(char *, auth_uid_groups_cnt)) == NULL)\n\t\t\t\t\t\tout_of_memory(\"auth_server\");\n\t\t\t\t\tfor (j = 0; j < auth_uid_groups_cnt; j++)\n\t\t\t\t\t\tauth_uid_groups[j] = gid_to_group(gid_array[j]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (j = 0; j < auth_uid_groups_cnt; j++) {\n\t\t\t\tif (auth_uid_groups[j] && wildmatch(tok+1, auth_uid_groups[j])) {\n\t\t\t\t\tgroup_match = j;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (group_match >= 0)\n\t\t\t\tbreak;\n#else\n\t\t\trprintf(FLOG, \"your computer doesn't support getgrouplist(), so no @group authorization is possible.\\n\");\n#endif\n\t\t}\n\t}\n\n\tfree(users);\n\n\tif (!tok)\n\t\terr = \"no matching rule\";\n\telse if (opt_ch == 'd')\n\t\terr = \"denied by rule\";\n\telse {\n\t\tchar *group = group_match >= 0 ? auth_uid_groups[group_match] : NULL;\n\t\terr = check_secret(module, line, group, challenge, pass);\n\t}\n\n\tmemset(challenge, 0, sizeof challenge);\n\tmemset(pass, 0, strlen(pass));\n\n\tif (auth_uid_groups) {\n\t\tint j;\n\t\tfor (j = 0; j < auth_uid_groups_cnt; j++) {\n\t\t\tif (auth_uid_groups[j])\n\t\t\t\tfree(auth_uid_groups[j]);\n\t\t}\n\t\tfree(auth_uid_groups);\n\t}\n\n\tif (err) {\n\t\trprintf(FLOG, \"auth failed on module %s from %s (%s) for %s: %s\\n\",\n\t\t\tlp_name(module), host, addr, line, err);\n\t\treturn NULL;\n\t}\n\n\tif (opt_ch == 'r')\n\t\tread_only = 1;\n\telse if (opt_ch == 'w')\n\t\tread_only = 0;\n\n\treturn strdup(line);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-354'], 'message': 'Only allow a modern checksum method for passwords.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void __dvb_frontend_free(struct dvb_frontend *fe)\n{\n\tstruct dvb_frontend_private *fepriv = fe->frontend_priv;\n\n\tif (fepriv)\n\t\tdvb_free_device(fepriv->dvbdev);\n\n\tdvb_frontend_invoke_release(fe, fe->ops.release);\n\n\tif (fepriv)\n\t\tkfree(fepriv);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'media: dvb_frontend: fix ifnullfree.cocci warnings\n\ndrivers/media/dvb-core/dvb_frontend.c:154:2-7: WARNING: NULL check before freeing functions like kfree, debugfs_remove, debugfs_remove_recursive or usb_free_urb is not needed. Maybe consider reorganizing relevant code to avoid passing NULL values.\n\n NULL check before some freeing functions is not needed.\n\n Based on checkpatch warning\n \"kfree(NULL) is safe this check is probably not required\"\n and kfreeaddr.cocci by Julia Lawall.\n\nGenerated by: scripts/coccinelle/free/ifnullfree.cocci\n\nFixes: b1cb7372fa82 (\"dvb_frontend: don't use-after-free the frontend struct\")\n\nSigned-off-by: Fengguang Wu \nSigned-off-by: Mauro Carvalho Chehab '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: xmlParseNameComplex(xmlParserCtxtPtr ctxt) {\n int len = 0, l;\n int c;\n int count = 0;\n\n#ifdef DEBUG\n nbParseNameComplex++;\n#endif\n\n /*\n * Handler for more complex cases\n */\n GROW;\n if (ctxt->instate == XML_PARSER_EOF)\n return(NULL);\n c = CUR_CHAR(l);\n if ((ctxt->options & XML_PARSE_OLD10) == 0) {\n /*\n\t * Use the new checks of production [4] [4a] amd [5] of the\n\t * Update 5 of XML-1.0\n\t */\n\tif ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */\n\t (!(((c >= 'a') && (c <= 'z')) ||\n\t ((c >= 'A') && (c <= 'Z')) ||\n\t (c == '_') || (c == ':') ||\n\t ((c >= 0xC0) && (c <= 0xD6)) ||\n\t ((c >= 0xD8) && (c <= 0xF6)) ||\n\t ((c >= 0xF8) && (c <= 0x2FF)) ||\n\t ((c >= 0x370) && (c <= 0x37D)) ||\n\t ((c >= 0x37F) && (c <= 0x1FFF)) ||\n\t ((c >= 0x200C) && (c <= 0x200D)) ||\n\t ((c >= 0x2070) && (c <= 0x218F)) ||\n\t ((c >= 0x2C00) && (c <= 0x2FEF)) ||\n\t ((c >= 0x3001) && (c <= 0xD7FF)) ||\n\t ((c >= 0xF900) && (c <= 0xFDCF)) ||\n\t ((c >= 0xFDF0) && (c <= 0xFFFD)) ||\n\t ((c >= 0x10000) && (c <= 0xEFFFF))))) {\n\t return(NULL);\n\t}\n\tlen += l;\n\tNEXTL(l);\n\tc = CUR_CHAR(l);\n\twhile ((c != ' ') && (c != '>') && (c != '/') && /* accelerators */\n\t (((c >= 'a') && (c <= 'z')) ||\n\t ((c >= 'A') && (c <= 'Z')) ||\n\t ((c >= '0') && (c <= '9')) || /* !start */\n\t (c == '_') || (c == ':') ||\n\t (c == '-') || (c == '.') || (c == 0xB7) || /* !start */\n\t ((c >= 0xC0) && (c <= 0xD6)) ||\n\t ((c >= 0xD8) && (c <= 0xF6)) ||\n\t ((c >= 0xF8) && (c <= 0x2FF)) ||\n\t ((c >= 0x300) && (c <= 0x36F)) || /* !start */\n\t ((c >= 0x370) && (c <= 0x37D)) ||\n\t ((c >= 0x37F) && (c <= 0x1FFF)) ||\n\t ((c >= 0x200C) && (c <= 0x200D)) ||\n\t ((c >= 0x203F) && (c <= 0x2040)) || /* !start */\n\t ((c >= 0x2070) && (c <= 0x218F)) ||\n\t ((c >= 0x2C00) && (c <= 0x2FEF)) ||\n\t ((c >= 0x3001) && (c <= 0xD7FF)) ||\n\t ((c >= 0xF900) && (c <= 0xFDCF)) ||\n\t ((c >= 0xFDF0) && (c <= 0xFFFD)) ||\n\t ((c >= 0x10000) && (c <= 0xEFFFF))\n\t\t)) {\n\t if (count++ > XML_PARSER_CHUNK_SIZE) {\n\t\tcount = 0;\n\t\tGROW;\n if (ctxt->instate == XML_PARSER_EOF)\n return(NULL);\n\t }\n\t len += l;\n\t NEXTL(l);\n\t c = CUR_CHAR(l);\n\t}\n } else {\n\tif ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */\n\t (!IS_LETTER(c) && (c != '_') &&\n\t (c != ':'))) {\n\t return(NULL);\n\t}\n\tlen += l;\n\tNEXTL(l);\n\tc = CUR_CHAR(l);\n\n\twhile ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */\n\t ((IS_LETTER(c)) || (IS_DIGIT(c)) ||\n\t\t(c == '.') || (c == '-') ||\n\t\t(c == '_') || (c == ':') ||\n\t\t(IS_COMBINING(c)) ||\n\t\t(IS_EXTENDER(c)))) {\n\t if (count++ > XML_PARSER_CHUNK_SIZE) {\n\t\tcount = 0;\n\t\tGROW;\n if (ctxt->instate == XML_PARSER_EOF)\n return(NULL);\n\t }\n\t len += l;\n\t NEXTL(l);\n\t c = CUR_CHAR(l);\n\t if (c == 0) {\n\t\tcount = 0;\n\t\tGROW;\n if (ctxt->instate == XML_PARSER_EOF)\n return(NULL);\n\t\tc = CUR_CHAR(l);\n\t }\n\t}\n }\n if ((len > XML_MAX_NAME_LENGTH) &&\n ((ctxt->options & XML_PARSE_HUGE) == 0)) {\n xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, \"Name\");\n return(NULL);\n }\n if ((*ctxt->input->cur == '\\n') && (ctxt->input->cur[-1] == '\\r'))\n return(xmlDictLookup(ctxt->dict, ctxt->input->cur - (len + 1), len));\n return(xmlDictLookup(ctxt->dict, ctxt->input->cur - len, len));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix handling of parameter-entity references\n\nThere were two bugs where parameter-entity references could lead to an\nunexpected change of the input buffer in xmlParseNameComplex and\nxmlDictLookup being called with an invalid pointer.\n\nPercent sign in DTD Names\n=========================\n\nThe NEXTL macro used to call xmlParserHandlePEReference. When parsing\n\"complex\" names inside the DTD, this could result in entity expansion\nwhich created a new input buffer. The fix is to simply remove the call\nto xmlParserHandlePEReference from the NEXTL macro. This is safe because\nno users of the macro require expansion of parameter entities.\n\n- xmlParseNameComplex\n- xmlParseNCNameComplex\n- xmlParseNmtoken\n\nThe percent sign is not allowed in names, which are grammatical tokens.\n\n- xmlParseEntityValue\n\nParameter-entity references in entity values are expanded but this\nhappens in a separate step in this function.\n\n- xmlParseSystemLiteral\n\nParameter-entity references are ignored in the system literal.\n\n- xmlParseAttValueComplex\n- xmlParseCharDataComplex\n- xmlParseCommentComplex\n- xmlParsePI\n- xmlParseCDSect\n\nParameter-entity references are ignored outside the DTD.\n\n- xmlLoadEntityContent\n\nThis function is only called from xmlStringLenDecodeEntities and\nentities are replaced in a separate step immediately after the function\ncall.\n\nThis bug could also be triggered with an internal subset and double\nentity expansion.\n\nThis fixes bug 766956 initially reported by Wei Lei and independently by\nChromium's ClusterFuzz, Hanno B\u00f6ck, and Marco Grassi. Thanks to everyone\ninvolved.\n\nxmlParseNameComplex with XML_PARSE_OLD10\n========================================\n\nWhen parsing Names inside an expanded parameter entity with the\nXML_PARSE_OLD10 option, xmlParseNameComplex would call xmlGROW via the\nGROW macro if the input buffer was exhausted. At the end of the\nparameter entity's replacement text, this function would then call\nxmlPopInput which invalidated the input buffer.\n\nThere should be no need to invoke GROW in this situation because the\nbuffer is grown periodically every XML_PARSER_CHUNK_SIZE characters and,\nat least for UTF-8, in xmlCurrentChar. This also matches the code path\nexecuted when XML_PARSE_OLD10 is not set.\n\nThis fixes bugs 781205 (CVE-2017-9049) and 781361 (CVE-2017-9050).\nThanks to Marcel B\u00f6hme and Thuan Pham for the report.\n\nAdditional hardening\n====================\n\nA separate check was added in xmlParseNameComplex to validate the\nbuffer size.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline int init_new_context(struct task_struct *tsk,\n\t\t\t\t struct mm_struct *mm)\n{\n\t#ifdef CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS\n\tif (cpu_feature_enabled(X86_FEATURE_OSPKE)) {\n\t\t/* pkey 0 is the default and always allocated */\n\t\tmm->context.pkey_allocation_map = 0x1;\n\t\t/* -1 means unallocated or invalid */\n\t\tmm->context.execute_only_pkey = -1;\n\t}\n\t#endif\n\tinit_new_context_ldt(tsk, mm);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'x86/mm: Fix use-after-free of ldt_struct\n\nThe following commit:\n\n 39a0526fb3f7 (\"x86/mm: Factor out LDT init from context init\")\n\nrenamed init_new_context() to init_new_context_ldt() and added a new\ninit_new_context() which calls init_new_context_ldt(). However, the\nerror code of init_new_context_ldt() was ignored. Consequently, if a\nmemory allocation in alloc_ldt_struct() failed during a fork(), the\n->context.ldt of the new task remained the same as that of the old task\n(due to the memcpy() in dup_mm()). ldt_struct's are not intended to be\nshared, so a use-after-free occurred after one task exited.\n\nFix the bug by making init_new_context() pass through the error code of\ninit_new_context_ldt().\n\nThis bug was found by syzkaller, which encountered the following splat:\n\n BUG: KASAN: use-after-free in free_ldt_struct.part.2+0x10a/0x150 arch/x86/kernel/ldt.c:116\n Read of size 4 at addr ffff88006d2cb7c8 by task kworker/u9:0/3710\n\n CPU: 1 PID: 3710 Comm: kworker/u9:0 Not tainted 4.13.0-rc4-next-20170811 #2\n Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011\n Call Trace:\n __dump_stack lib/dump_stack.c:16 [inline]\n dump_stack+0x194/0x257 lib/dump_stack.c:52\n print_address_description+0x73/0x250 mm/kasan/report.c:252\n kasan_report_error mm/kasan/report.c:351 [inline]\n kasan_report+0x24e/0x340 mm/kasan/report.c:409\n __asan_report_load4_noabort+0x14/0x20 mm/kasan/report.c:429\n free_ldt_struct.part.2+0x10a/0x150 arch/x86/kernel/ldt.c:116\n free_ldt_struct arch/x86/kernel/ldt.c:173 [inline]\n destroy_context_ldt+0x60/0x80 arch/x86/kernel/ldt.c:171\n destroy_context arch/x86/include/asm/mmu_context.h:157 [inline]\n __mmdrop+0xe9/0x530 kernel/fork.c:889\n mmdrop include/linux/sched/mm.h:42 [inline]\n exec_mmap fs/exec.c:1061 [inline]\n flush_old_exec+0x173c/0x1ff0 fs/exec.c:1291\n load_elf_binary+0x81f/0x4ba0 fs/binfmt_elf.c:855\n search_binary_handler+0x142/0x6b0 fs/exec.c:1652\n exec_binprm fs/exec.c:1694 [inline]\n do_execveat_common.isra.33+0x1746/0x22e0 fs/exec.c:1816\n do_execve+0x31/0x40 fs/exec.c:1860\n call_usermodehelper_exec_async+0x457/0x8f0 kernel/umh.c:100\n ret_from_fork+0x2a/0x40 arch/x86/entry/entry_64.S:431\n\n Allocated by task 3700:\n save_stack_trace+0x16/0x20 arch/x86/kernel/stacktrace.c:59\n save_stack+0x43/0xd0 mm/kasan/kasan.c:447\n set_track mm/kasan/kasan.c:459 [inline]\n kasan_kmalloc+0xad/0xe0 mm/kasan/kasan.c:551\n kmem_cache_alloc_trace+0x136/0x750 mm/slab.c:3627\n kmalloc include/linux/slab.h:493 [inline]\n alloc_ldt_struct+0x52/0x140 arch/x86/kernel/ldt.c:67\n write_ldt+0x7b7/0xab0 arch/x86/kernel/ldt.c:277\n sys_modify_ldt+0x1ef/0x240 arch/x86/kernel/ldt.c:307\n entry_SYSCALL_64_fastpath+0x1f/0xbe\n\n Freed by task 3700:\n save_stack_trace+0x16/0x20 arch/x86/kernel/stacktrace.c:59\n save_stack+0x43/0xd0 mm/kasan/kasan.c:447\n set_track mm/kasan/kasan.c:459 [inline]\n kasan_slab_free+0x71/0xc0 mm/kasan/kasan.c:524\n __cache_free mm/slab.c:3503 [inline]\n kfree+0xca/0x250 mm/slab.c:3820\n free_ldt_struct.part.2+0xdd/0x150 arch/x86/kernel/ldt.c:121\n free_ldt_struct arch/x86/kernel/ldt.c:173 [inline]\n destroy_context_ldt+0x60/0x80 arch/x86/kernel/ldt.c:171\n destroy_context arch/x86/include/asm/mmu_context.h:157 [inline]\n __mmdrop+0xe9/0x530 kernel/fork.c:889\n mmdrop include/linux/sched/mm.h:42 [inline]\n __mmput kernel/fork.c:916 [inline]\n mmput+0x541/0x6e0 kernel/fork.c:927\n copy_process.part.36+0x22e1/0x4af0 kernel/fork.c:1931\n copy_process kernel/fork.c:1546 [inline]\n _do_fork+0x1ef/0xfb0 kernel/fork.c:2025\n SYSC_clone kernel/fork.c:2135 [inline]\n SyS_clone+0x37/0x50 kernel/fork.c:2129\n do_syscall_64+0x26c/0x8c0 arch/x86/entry/common.c:287\n return_from_SYSCALL_64+0x0/0x7a\n\nHere is a C reproducer:\n\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n\n static void *fork_thread(void *_arg)\n {\n fork();\n }\n\n int main(void)\n {\n struct user_desc desc = { .entry_number = 8191 };\n\n syscall(__NR_modify_ldt, 1, &desc, sizeof(desc));\n\n for (;;) {\n if (fork() == 0) {\n pthread_t t;\n\n srand(getpid());\n pthread_create(&t, NULL, fork_thread, NULL);\n usleep(rand() % 10000);\n syscall(__NR_exit_group, 0);\n }\n wait(NULL);\n }\n }\n\nNote: the reproducer takes advantage of the fact that alloc_ldt_struct()\nmay use vmalloc() to allocate a large ->entries array, and after\ncommit:\n\n 5d17a73a2ebe (\"vmalloc: back off when the current task is killed\")\n\nit is possible for userspace to fail a task's vmalloc() by\nsending a fatal signal, e.g. via exit_group(). It would be more\ndifficult to reproduce this bug on kernels without that commit.\n\nThis bug only affected kernels with CONFIG_MODIFY_LDT_SYSCALL=y.\n\nSigned-off-by: Eric Biggers \nAcked-by: Dave Hansen \nCc: [v4.6+]\nCc: Andrew Morton \nCc: Andy Lutomirski \nCc: Borislav Petkov \nCc: Brian Gerst \nCc: Christoph Hellwig \nCc: Denys Vlasenko \nCc: Dmitry Vyukov \nCc: Linus Torvalds \nCc: Michal Hocko \nCc: Peter Zijlstra \nCc: Rik van Riel \nCc: Tetsuo Handa \nCc: Thomas Gleixner \nCc: linux-mm@kvack.org\nFixes: 39a0526fb3f7 (\"x86/mm: Factor out LDT init from context init\")\nLink: http://lkml.kernel.org/r/20170824175029.76040-1-ebiggers3@gmail.com\nSigned-off-by: Ingo Molnar '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: _kdc_as_rep(kdc_request_t r,\n\t krb5_data *reply,\n\t const char *from,\n\t struct sockaddr *from_addr,\n\t int datagram_reply)\n{\n krb5_context context = r->context;\n krb5_kdc_configuration *config = r->config;\n KDC_REQ *req = &r->req;\n KDC_REQ_BODY *b = NULL;\n AS_REP rep;\n KDCOptions f;\n krb5_enctype setype;\n krb5_error_code ret = 0;\n Key *skey;\n int found_pa = 0;\n int i, flags = HDB_F_FOR_AS_REQ;\n METHOD_DATA error_method;\n const PA_DATA *pa;\n\n memset(&rep, 0, sizeof(rep));\n error_method.len = 0;\n error_method.val = NULL;\n\n /*\n * Look for FAST armor and unwrap\n */\n ret = _kdc_fast_unwrap_request(r);\n if (ret) {\n\t_kdc_r_log(r, 0, \"FAST unwrap request from %s failed: %d\", from, ret);\n\tgoto out;\n }\n\n b = &req->req_body;\n f = b->kdc_options;\n\n if (f.canonicalize)\n\tflags |= HDB_F_CANON;\n\n if(b->sname == NULL){\n\tret = KRB5KRB_ERR_GENERIC;\n\t_kdc_set_e_text(r, \"No server in request\");\n } else{\n\tret = _krb5_principalname2krb5_principal (context,\n\t\t\t\t\t\t &r->server_princ,\n\t\t\t\t\t\t *(b->sname),\n\t\t\t\t\t\t b->realm);\n\tif (ret == 0)\n\t ret = krb5_unparse_name(context, r->server_princ, &r->server_name);\n }\n if (ret) {\n\tkdc_log(context, config, 0,\n\t\t\"AS-REQ malformed server name from %s\", from);\n\tgoto out;\n }\n if(b->cname == NULL){\n\tret = KRB5KRB_ERR_GENERIC;\n\t_kdc_set_e_text(r, \"No client in request\");\n } else {\n\tret = _krb5_principalname2krb5_principal (context,\n\t\t\t\t\t\t &r->client_princ,\n\t\t\t\t\t\t *(b->cname),\n\t\t\t\t\t\t b->realm);\n\tif (ret)\n\t goto out;\n\n\tret = krb5_unparse_name(context, r->client_princ, &r->client_name);\n }\n if (ret) {\n\tkdc_log(context, config, 0,\n\t\t\"AS-REQ malformed client name from %s\", from);\n\tgoto out;\n }\n\n kdc_log(context, config, 0, \"AS-REQ %s from %s for %s\",\n\t r->client_name, from, r->server_name);\n\n /*\n *\n */\n\n if (_kdc_is_anonymous(context, r->client_princ)) {\n\tif (!_kdc_is_anon_request(b)) {\n\t kdc_log(context, config, 0, \"Anonymous ticket w/o anonymous flag\");\n\t ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;\n\t goto out;\n\t}\n } else if (_kdc_is_anon_request(b)) {\n\tkdc_log(context, config, 0,\n\t\t\"Request for a anonymous ticket with non \"\n\t\t\"anonymous client name: %s\", r->client_name);\n\tret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;\n\tgoto out;\n }\n\n /*\n *\n */\n\n ret = _kdc_db_fetch(context, config, r->client_princ,\n\t\t\tHDB_F_GET_CLIENT | flags, NULL,\n\t\t\t&r->clientdb, &r->client);\n if(ret == HDB_ERR_NOT_FOUND_HERE) {\n\tkdc_log(context, config, 5, \"client %s does not have secrets at this KDC, need to proxy\",\n\t\tr->client_name);\n\tgoto out;\n } else if (ret == HDB_ERR_WRONG_REALM) {\n\tchar *fixed_client_name = NULL;\n\n\tret = krb5_unparse_name(context, r->client->entry.principal,\n\t\t\t\t&fixed_client_name);\n\tif (ret) {\n\t goto out;\n\t}\n\n\tkdc_log(context, config, 0, \"WRONG_REALM - %s -> %s\",\n\t\tr->client_name, fixed_client_name);\n\tfree(fixed_client_name);\n\n\tret = _kdc_fast_mk_error(context, r,\n\t\t\t\t &error_method,\n\t\t\t\t r->armor_crypto,\n\t\t\t\t &req->req_body,\n\t\t\t\t KRB5_KDC_ERR_WRONG_REALM,\n\t\t\t\t NULL,\n\t\t\t\t r->server_princ,\n\t\t\t\t NULL,\n\t\t\t\t &r->client->entry.principal->realm,\n\t\t\t\t NULL, NULL,\n\t\t\t\t reply);\n\tgoto out;\n } else if(ret){\n\tconst char *msg = krb5_get_error_message(context, ret);\n\tkdc_log(context, config, 0, \"UNKNOWN -- %s: %s\", r->client_name, msg);\n\tkrb5_free_error_message(context, msg);\n\tret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;\n\tgoto out;\n }\n ret = _kdc_db_fetch(context, config, r->server_princ,\n\t\t\tHDB_F_GET_SERVER|HDB_F_GET_KRBTGT | flags,\n\t\t\tNULL, NULL, &r->server);\n if(ret == HDB_ERR_NOT_FOUND_HERE) {\n\tkdc_log(context, config, 5, \"target %s does not have secrets at this KDC, need to proxy\",\n\t\tr->server_name);\n\tgoto out;\n } else if(ret){\n\tconst char *msg = krb5_get_error_message(context, ret);\n\tkdc_log(context, config, 0, \"UNKNOWN -- %s: %s\", r->server_name, msg);\n\tkrb5_free_error_message(context, msg);\n\tret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;\n\tgoto out;\n }\n\n /*\n * Select a session enctype from the list of the crypto system\n * supported enctypes that is supported by the client and is one of\n * the enctype of the enctype of the service (likely krbtgt).\n *\n * The latter is used as a hint of what enctypes all KDC support,\n * to make sure a newer version of KDC won't generate a session\n * enctype that an older version of a KDC in the same realm can't\n * decrypt.\n */\n\n ret = _kdc_find_etype(context,\n\t\t\t krb5_principal_is_krbtgt(context, r->server_princ) ?\n\t\t\t config->tgt_use_strongest_session_key :\n\t\t\t config->svc_use_strongest_session_key, FALSE,\n\t\t\t r->client, b->etype.val, b->etype.len, &r->sessionetype,\n\t\t\t NULL);\n if (ret) {\n\tkdc_log(context, config, 0,\n\t\t\"Client (%s) from %s has no common enctypes with KDC \"\n\t\t\"to use for the session key\",\n\t\tr->client_name, from);\n\tgoto out;\n }\n\n /*\n * Pre-auth processing\n */\n\n if(req->padata){\n\tunsigned int n;\n\n\tlog_patypes(context, config, req->padata);\n\n\t/* Check if preauth matching */\n\n\tfor (n = 0; !found_pa && n < sizeof(pat) / sizeof(pat[0]); n++) {\n\t if (pat[n].validate == NULL)\n\t\tcontinue;\n\t if (r->armor_crypto == NULL && (pat[n].flags & PA_REQ_FAST))\n\t\tcontinue;\n\n\t kdc_log(context, config, 5,\n\t\t \"Looking for %s pa-data -- %s\", pat[n].name, r->client_name);\n\t i = 0;\n\t pa = _kdc_find_padata(req, &i, pat[n].type);\n\t if (pa) {\n\t\tret = pat[n].validate(r, pa);\n\t\tif (ret != 0) {\n\t\t goto out;\n\t\t}\n\t\tkdc_log(context, config, 0,\n\t\t\t\"%s pre-authentication succeeded -- %s\",\n\t\t\tpat[n].name, r->client_name);\n\t\tfound_pa = 1;\n\t\tr->et.flags.pre_authent = 1;\n\t }\n\t}\n }\n\n if (found_pa == 0) {\n\tKey *ckey = NULL;\n\tsize_t n;\n\n\tfor (n = 0; n < sizeof(pat) / sizeof(pat[0]); n++) {\n\t if ((pat[n].flags & PA_ANNOUNCE) == 0)\n\t\tcontinue;\n\t ret = krb5_padata_add(context, &error_method,\n\t\t\t\t pat[n].type, NULL, 0);\n\t if (ret)\n\t\tgoto out;\n\t}\n\n\t/*\n\t * If there is a client key, send ETYPE_INFO{,2}\n\t */\n\tret = _kdc_find_etype(context,\n\t\t\t config->preauth_use_strongest_session_key, TRUE,\n\t\t\t r->client, b->etype.val, b->etype.len, NULL, &ckey);\n\tif (ret == 0) {\n\n\t /*\n\t * RFC4120 requires:\n\t * - If the client only knows about old enctypes, then send\n\t * both info replies (we send 'info' first in the list).\n\t * - If the client is 'modern', because it knows about 'new'\n\t * enctype types, then only send the 'info2' reply.\n\t *\n\t * Before we send the full list of etype-info data, we pick\n\t * the client key we would have used anyway below, just pick\n\t * that instead.\n\t */\n\n\t if (older_enctype(ckey->key.keytype)) {\n\t\tret = get_pa_etype_info(context, config,\n\t\t\t\t\t&error_method, ckey);\n\t\tif (ret)\n\t\t goto out;\n\t }\n\t ret = get_pa_etype_info2(context, config,\n\t\t\t\t &error_method, ckey);\n\t if (ret)\n\t\tgoto out;\n\t}\n\n\t/* \n\t * send requre preauth is its required or anon is requested,\n\t * anon is today only allowed via preauth mechanisms.\n\t */\n\tif (require_preauth_p(r) || _kdc_is_anon_request(b)) {\n\t ret = KRB5KDC_ERR_PREAUTH_REQUIRED;\n\t _kdc_set_e_text(r, \"Need to use PA-ENC-TIMESTAMP/PA-PK-AS-REQ\");\n\t goto out;\n\t}\n\n\tif (ckey == NULL) {\n\t ret = KRB5KDC_ERR_CLIENT_NOTYET;\n\t _kdc_set_e_text(r, \"Doesn't have a client key available\");\n\t goto out;\n\t}\n\tkrb5_free_keyblock_contents(r->context, &r->reply_key);\n\tret = krb5_copy_keyblock_contents(r->context, &ckey->key, &r->reply_key);\n\tif (ret)\n\t goto out;\n }\n\n if (r->clientdb->hdb_auth_status) {\n\tr->clientdb->hdb_auth_status(context, r->clientdb, r->client, \n\t\t\t\t HDB_AUTH_SUCCESS);\n }\n\n /*\n * Verify flags after the user been required to prove its identity\n * with in a preauth mech.\n */\n\n ret = _kdc_check_access(context, config, r->client, r->client_name,\n\t\t\t r->server, r->server_name,\n\t\t\t req, &error_method);\n if(ret)\n\tgoto out;\n\n /*\n * Select the best encryption type for the KDC with out regard to\n * the client since the client never needs to read that data.\n */\n\n ret = _kdc_get_preferred_key(context, config,\n\t\t\t\t r->server, r->server_name,\n\t\t\t\t &setype, &skey);\n if(ret)\n\tgoto out;\n\n if(f.renew || f.validate || f.proxy || f.forwarded || f.enc_tkt_in_skey\n || (_kdc_is_anon_request(b) && !config->allow_anonymous)) {\n\tret = KRB5KDC_ERR_BADOPTION;\n\t_kdc_set_e_text(r, \"Bad KDC options\");\n\tgoto out;\n }\n\n /*\n * Build reply\n */\n\n rep.pvno = 5;\n rep.msg_type = krb_as_rep;\n\n if (_kdc_is_anonymous(context, r->client_princ)) {\n\tRealm anon_realm=KRB5_ANON_REALM;\n\tret = copy_Realm(&anon_realm, &rep.crealm);\n } else\n\tret = copy_Realm(&r->client->entry.principal->realm, &rep.crealm);\n if (ret)\n\tgoto out;\n ret = _krb5_principal2principalname(&rep.cname, r->client->entry.principal);\n if (ret)\n\tgoto out;\n\n rep.ticket.tkt_vno = 5;\n ret = copy_Realm(&r->server->entry.principal->realm, &rep.ticket.realm);\n if (ret)\n\tgoto out;\n _krb5_principal2principalname(&rep.ticket.sname,\n\t\t\t\t r->server->entry.principal);\n /* java 1.6 expects the name to be the same type, lets allow that\n * uncomplicated name-types. */\n#define CNT(sp,t) (((sp)->sname->name_type) == KRB5_NT_##t)\n if (CNT(b, UNKNOWN) || CNT(b, PRINCIPAL) || CNT(b, SRV_INST) || CNT(b, SRV_HST) || CNT(b, SRV_XHST))\n\trep.ticket.sname.name_type = b->sname->name_type;\n#undef CNT\n\n r->et.flags.initial = 1;\n if(r->client->entry.flags.forwardable && r->server->entry.flags.forwardable)\n\tr->et.flags.forwardable = f.forwardable;\n else if (f.forwardable) {\n\t_kdc_set_e_text(r, \"Ticket may not be forwardable\");\n\tret = KRB5KDC_ERR_POLICY;\n\tgoto out;\n }\n if(r->client->entry.flags.proxiable && r->server->entry.flags.proxiable)\n\tr->et.flags.proxiable = f.proxiable;\n else if (f.proxiable) {\n\t_kdc_set_e_text(r, \"Ticket may not be proxiable\");\n\tret = KRB5KDC_ERR_POLICY;\n\tgoto out;\n }\n if(r->client->entry.flags.postdate && r->server->entry.flags.postdate)\n\tr->et.flags.may_postdate = f.allow_postdate;\n else if (f.allow_postdate){\n\t_kdc_set_e_text(r, \"Ticket may not be postdate\");\n\tret = KRB5KDC_ERR_POLICY;\n\tgoto out;\n }\n\n /* check for valid set of addresses */\n if(!_kdc_check_addresses(context, config, b->addresses, from_addr)) {\n\t_kdc_set_e_text(r, \"Bad address list in requested\");\n\tret = KRB5KRB_AP_ERR_BADADDR;\n\tgoto out;\n }\n\n ret = copy_PrincipalName(&rep.cname, &r->et.cname);\n if (ret)\n\tgoto out;\n ret = copy_Realm(&rep.crealm, &r->et.crealm);\n if (ret)\n\tgoto out;\n\n {\n\ttime_t start;\n\ttime_t t;\n\t\n\tstart = r->et.authtime = kdc_time;\n\n\tif(f.postdated && req->req_body.from){\n\t ALLOC(r->et.starttime);\n\t start = *r->et.starttime = *req->req_body.from;\n\t r->et.flags.invalid = 1;\n\t r->et.flags.postdated = 1; /* XXX ??? */\n\t}\n\t_kdc_fix_time(&b->till);\n\tt = *b->till;\n\n\t/* be careful not overflowing */\n\n\tif(r->client->entry.max_life)\n\t t = start + min(t - start, *r->client->entry.max_life);\n\tif(r->server->entry.max_life)\n\t t = start + min(t - start, *r->server->entry.max_life);\n#if 0\n\tt = min(t, start + realm->max_life);\n#endif\n\tr->et.endtime = t;\n\tif(f.renewable_ok && r->et.endtime < *b->till){\n\t f.renewable = 1;\n\t if(b->rtime == NULL){\n\t\tALLOC(b->rtime);\n\t\t*b->rtime = 0;\n\t }\n\t if(*b->rtime < *b->till)\n\t\t*b->rtime = *b->till;\n\t}\n\tif(f.renewable && b->rtime){\n\t t = *b->rtime;\n\t if(t == 0)\n\t\tt = MAX_TIME;\n\t if(r->client->entry.max_renew)\n\t\tt = start + min(t - start, *r->client->entry.max_renew);\n\t if(r->server->entry.max_renew)\n\t\tt = start + min(t - start, *r->server->entry.max_renew);\n#if 0\n\t t = min(t, start + realm->max_renew);\n#endif\n\t ALLOC(r->et.renew_till);\n\t *r->et.renew_till = t;\n\t r->et.flags.renewable = 1;\n\t}\n }\n\n if (_kdc_is_anon_request(b))\n\tr->et.flags.anonymous = 1;\n\n if(b->addresses){\n\tALLOC(r->et.caddr);\n\tcopy_HostAddresses(b->addresses, r->et.caddr);\n }\n\n r->et.transited.tr_type = DOMAIN_X500_COMPRESS;\n krb5_data_zero(&r->et.transited.contents);\n\n /* The MIT ASN.1 library (obviously) doesn't tell lengths encoded\n * as 0 and as 0x80 (meaning indefinite length) apart, and is thus\n * incapable of correctly decoding SEQUENCE OF's of zero length.\n *\n * To fix this, always send at least one no-op last_req\n *\n * If there's a pw_end or valid_end we will use that,\n * otherwise just a dummy lr.\n */\n r->ek.last_req.val = malloc(2 * sizeof(*r->ek.last_req.val));\n if (r->ek.last_req.val == NULL) {\n\tret = ENOMEM;\n\tgoto out;\n }\n r->ek.last_req.len = 0;\n if (r->client->entry.pw_end\n\t&& (config->kdc_warn_pwexpire == 0\n\t || kdc_time + config->kdc_warn_pwexpire >= *r->client->entry.pw_end)) {\n\tr->ek.last_req.val[r->ek.last_req.len].lr_type = LR_PW_EXPTIME;\n\tr->ek.last_req.val[r->ek.last_req.len].lr_value = *r->client->entry.pw_end;\n\t++r->ek.last_req.len;\n }\n if (r->client->entry.valid_end) {\n\tr->ek.last_req.val[r->ek.last_req.len].lr_type = LR_ACCT_EXPTIME;\n\tr->ek.last_req.val[r->ek.last_req.len].lr_value = *r->client->entry.valid_end;\n\t++r->ek.last_req.len;\n }\n if (r->ek.last_req.len == 0) {\n\tr->ek.last_req.val[r->ek.last_req.len].lr_type = LR_NONE;\n\tr->ek.last_req.val[r->ek.last_req.len].lr_value = 0;\n\t++r->ek.last_req.len;\n }\n r->ek.nonce = b->nonce;\n if (r->client->entry.valid_end || r->client->entry.pw_end) {\n\tALLOC(r->ek.key_expiration);\n\tif (r->client->entry.valid_end) {\n\t if (r->client->entry.pw_end)\n\t\t*r->ek.key_expiration = min(*r->client->entry.valid_end,\n\t\t\t\t\t *r->client->entry.pw_end);\n\t else\n\t\t*r->ek.key_expiration = *r->client->entry.valid_end;\n\t} else\n\t *r->ek.key_expiration = *r->client->entry.pw_end;\n } else\n\tr->ek.key_expiration = NULL;\n r->ek.flags = r->et.flags;\n r->ek.authtime = r->et.authtime;\n if (r->et.starttime) {\n\tALLOC(r->ek.starttime);\n\t*r->ek.starttime = *r->et.starttime;\n }\n r->ek.endtime = r->et.endtime;\n if (r->et.renew_till) {\n\tALLOC(r->ek.renew_till);\n\t*r->ek.renew_till = *r->et.renew_till;\n }\n ret = copy_Realm(&rep.ticket.realm, &r->ek.srealm);\n if (ret)\n\tgoto out;\n ret = copy_PrincipalName(&rep.ticket.sname, &r->ek.sname);\n if (ret)\n\tgoto out;\n if(r->et.caddr){\n\tALLOC(r->ek.caddr);\n\tcopy_HostAddresses(r->et.caddr, r->ek.caddr);\n }\n\n /*\n * Check and session and reply keys\n */\n\n if (r->session_key.keytype == ETYPE_NULL) {\n\tret = krb5_generate_random_keyblock(context, r->sessionetype, &r->session_key);\n\tif (ret)\n\t goto out;\n }\n\n if (r->reply_key.keytype == ETYPE_NULL) {\n\t_kdc_set_e_text(r, \"Client have no reply key\");\n\tret = KRB5KDC_ERR_CLIENT_NOTYET;\n\tgoto out;\n }\n\n ret = copy_EncryptionKey(&r->session_key, &r->et.key);\n if (ret)\n\tgoto out;\n\n ret = copy_EncryptionKey(&r->session_key, &r->ek.key);\n if (ret)\n\tgoto out;\n\n if (r->outpadata.len) {\n\n\tALLOC(rep.padata);\n\tif (rep.padata == NULL) {\n\t ret = ENOMEM;\n\t goto out;\n\t}\n\tret = copy_METHOD_DATA(&r->outpadata, rep.padata);\n\tif (ret)\n\t goto out;\n }\n\n /* Add the PAC */\n if (send_pac_p(context, req)) {\n\tgenerate_pac(r, skey);\n }\n\n _kdc_log_timestamp(context, config, \"AS-REQ\", r->et.authtime, r->et.starttime,\n\t\t r->et.endtime, r->et.renew_till);\n\n /* do this as the last thing since this signs the EncTicketPart */\n ret = _kdc_add_KRB5SignedPath(context,\n\t\t\t\t config,\n\t\t\t\t r->server,\n\t\t\t\t setype,\n\t\t\t\t r->client->entry.principal,\n\t\t\t\t NULL,\n\t\t\t\t NULL,\n\t\t\t\t &r->et);\n if (ret)\n\tgoto out;\n\n log_as_req(context, config, r->reply_key.keytype, setype, b);\n\n /*\n * We always say we support FAST/enc-pa-rep\n */\n\n r->et.flags.enc_pa_rep = r->ek.flags.enc_pa_rep = 1;\n\n /*\n * Add REQ_ENC_PA_REP if client supports it\n */\n\n i = 0;\n pa = _kdc_find_padata(req, &i, KRB5_PADATA_REQ_ENC_PA_REP);\n if (pa) {\n\n\tret = add_enc_pa_rep(r);\n\tif (ret) {\n\t const char *msg = krb5_get_error_message(r->context, ret);\n\t _kdc_r_log(r, 0, \"add_enc_pa_rep failed: %s: %d\", msg, ret);\n\t krb5_free_error_message(r->context, msg);\n\t goto out;\n\t}\n }\n\n /*\n *\n */\n\n ret = _kdc_encode_reply(context, config,\n\t\t\t r->armor_crypto, req->req_body.nonce,\n\t\t\t &rep, &r->et, &r->ek, setype, r->server->entry.kvno,\n\t\t\t &skey->key, r->client->entry.kvno,\n\t\t\t &r->reply_key, 0, &r->e_text, reply);\n if (ret)\n\tgoto out;\n\n /*\n * Check if message too large\n */\n if (datagram_reply && reply->length > config->max_datagram_reply_length) {\n\tkrb5_data_free(reply);\n\tret = KRB5KRB_ERR_RESPONSE_TOO_BIG;\n\t_kdc_set_e_text(r, \"Reply packet too large\");\n }\n\nout:\n free_AS_REP(&rep);\n\n /*\n * In case of a non proxy error, build an error message.\n */\n if(ret != 0 && ret != HDB_ERR_NOT_FOUND_HERE && reply->length == 0) {\n\tret = _kdc_fast_mk_error(context, r,\n\t\t\t\t &error_method,\n\t\t\t\t r->armor_crypto,\n\t\t\t\t &req->req_body,\n\t\t\t\t ret, r->e_text,\n\t\t\t\t r->server_princ,\n\t\t\t\t &r->client_princ->name,\n\t\t\t\t &r->client_princ->realm,\n\t\t\t\t NULL, NULL,\n\t\t\t\t reply);\n\tif (ret)\n\t goto out2;\n }\nout2:\n free_EncTicketPart(&r->et);\n free_EncKDCRepPart(&r->ek);\n free_KDCFastState(&r->fast);\n\n if (error_method.len)\n\tfree_METHOD_DATA(&error_method);\n if (r->outpadata.len)\n\tfree_METHOD_DATA(&r->outpadata);\n if (r->client_princ) {\n\tkrb5_free_principal(context, r->client_princ);\n\tr->client_princ = NULL;\n }\n if (r->client_name) {\n\tfree(r->client_name);\n\tr->client_name = NULL;\n }\n if (r->server_princ){\n\tkrb5_free_principal(context, r->server_princ);\n\tr->server_princ = NULL;\n }\n if (r->server_name) {\n\tfree(r->server_name);\n\tr->server_name = NULL;\n }\n if (r->client)\n\t_kdc_free_ent(context, r->client);\n if (r->server)\n\t_kdc_free_ent(context, r->server);\n if (r->armor_crypto) {\n\tkrb5_crypto_destroy(r->context, r->armor_crypto);\n\tr->armor_crypto = NULL;\n }\n krb5_free_keyblock_contents(r->context, &r->reply_key);\n krb5_free_keyblock_contents(r->context, &r->session_key);\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Security: Avoid NULL structure pointer member dereference\n\nThis can happen in the error path when processing malformed AS\nrequests with a NULL client name. Bug originally introduced on\nFri Feb 13 09:26:01 2015 +0100 in commit:\n\n a873e21d7c06f22943a90a41dc733ae76799390d\n\n kdc: base _kdc_fast_mk_error() on krb5_mk_error_ext()\n\nOriginal patch by Jeffrey Altman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadXPMImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n char\n *grey,\n key[MagickPathExtent],\n target[MagickPathExtent],\n *xpm_buffer;\n\n Image\n *image;\n\n MagickBooleanType\n active,\n status;\n\n register char\n *next,\n *p,\n *q;\n\n register ssize_t\n x;\n\n register Quantum\n *r;\n\n size_t\n length;\n\n SplayTreeInfo\n *xpm_colors;\n\n ssize_t\n count,\n j,\n y;\n\n unsigned long\n colors,\n columns,\n rows,\n width;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Read XPM file.\n */\n length=MagickPathExtent;\n xpm_buffer=(char *) AcquireQuantumMemory((size_t) length,sizeof(*xpm_buffer));\n if (xpm_buffer == (char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n *xpm_buffer='\\0';\n p=xpm_buffer;\n while (ReadBlobString(image,p) != (char *) NULL)\n {\n if ((*p == '#') && ((p == xpm_buffer) || (*(p-1) == '\\n')))\n continue;\n if ((*p == '}') && (*(p+1) == ';'))\n break;\n p+=strlen(p);\n if ((size_t) (p-xpm_buffer+MagickPathExtent) < length)\n continue;\n length<<=1;\n xpm_buffer=(char *) ResizeQuantumMemory(xpm_buffer,length+MagickPathExtent,\n sizeof(*xpm_buffer));\n if (xpm_buffer == (char *) NULL)\n break;\n p=xpm_buffer+strlen(xpm_buffer);\n }\n if (xpm_buffer == (char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n /*\n Remove comments.\n */\n count=0;\n width=0;\n for (p=xpm_buffer; *p != '\\0'; p++)\n {\n if (*p != '\"')\n continue;\n count=(ssize_t) sscanf(p+1,\"%lu %lu %lu %lu\",&columns,&rows,&colors,&width);\n image->columns=columns;\n image->rows=rows;\n image->colors=colors;\n if (count == 4)\n break;\n }\n if ((count != 4) || (width == 0) || (width > 3) ||\n (image->columns == 0) || (image->rows == 0) ||\n (image->colors == 0) || (image->colors > MaxColormapSize))\n {\n xpm_buffer=DestroyString(xpm_buffer);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n /*\n Remove unquoted characters.\n */\n active=MagickFalse;\n for (q=xpm_buffer; *p != '\\0'; )\n {\n if (*p++ == '\"')\n {\n if (active != MagickFalse)\n *q++='\\n';\n active=active != MagickFalse ? MagickFalse : MagickTrue;\n }\n if (active != MagickFalse)\n *q++=(*p);\n }\n *q='\\0';\n /*\n Initialize image structure.\n */\n xpm_colors=NewSplayTree(CompareXPMColor,RelinquishMagickMemory,\n (void *(*)(void *)) NULL);\n if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)\n {\n xpm_buffer=DestroyString(xpm_buffer);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n /*\n Read image colormap.\n */\n image->depth=1;\n next=NextXPMLine(xpm_buffer);\n for (j=0; (j < (ssize_t) image->colors) && (next != (char *) NULL); j++)\n {\n p=next;\n next=NextXPMLine(p);\n (void) CopyXPMColor(key,p,MagickMin((size_t) width,MagickPathExtent-1));\n status=AddValueToSplayTree(xpm_colors,ConstantString(key),(void *) j);\n /*\n Parse color.\n */\n (void) CopyMagickString(target,\"gray\",MagickPathExtent);\n q=ParseXPMColor(p+width,MagickTrue);\n if (q != (char *) NULL)\n {\n while ((isspace((int) ((unsigned char) *q)) == 0) && (*q != '\\0'))\n q++;\n if ((next-q) < 0)\n break;\n if (next != (char *) NULL)\n (void) CopyXPMColor(target,q,MagickMin((size_t) (next-q),\n MagickPathExtent-1));\n else\n (void) CopyMagickString(target,q,MagickPathExtent);\n q=ParseXPMColor(target,MagickFalse);\n if (q != (char *) NULL)\n *q='\\0';\n }\n StripString(target);\n grey=strstr(target,\"grey\");\n if (grey != (char *) NULL)\n grey[2]='a';\n if (LocaleCompare(target,\"none\") == 0)\n {\n image->storage_class=DirectClass;\n image->alpha_trait=BlendPixelTrait;\n }\n status=QueryColorCompliance(target,XPMCompliance,&image->colormap[j],\n exception);\n if (status == MagickFalse)\n break;\n if (image->depth < image->colormap[j].depth)\n image->depth=image->colormap[j].depth;\n }\n if (j < (ssize_t) image->colors)\n {\n xpm_colors=DestroySplayTree(xpm_colors);\n xpm_buffer=DestroyString(xpm_buffer);\n ThrowReaderException(CorruptImageError,\"CorruptImage\");\n }\n j=0;\n if (image_info->ping == MagickFalse)\n {\n /*\n Read image pixels.\n */\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=NextXPMLine(p);\n if (p == (char *) NULL)\n break;\n r=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (r == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n ssize_t count=CopyXPMColor(key,p,MagickMin(width,MagickPathExtent-1));\n if (count != (ssize_t) width)\n break;\n j=(ssize_t) GetValueFromSplayTree(xpm_colors,key);\n if (image->storage_class == PseudoClass)\n SetPixelIndex(image,(Quantum) j,r);\n SetPixelViaPixelInfo(image,image->colormap+j,r);\n p+=count;\n r+=GetPixelChannels(image);\n }\n if (x < (ssize_t) image->columns)\n break;\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n if (y < (ssize_t) image->rows)\n {\n xpm_colors=DestroySplayTree(xpm_colors);\n xpm_buffer=DestroyString(xpm_buffer);\n ThrowReaderException(CorruptImageError,\"NotEnoughPixelData\");\n }\n }\n /*\n Relinquish resources.\n */\n xpm_buffer=DestroyString(xpm_buffer);\n xpm_colors=DestroySplayTree(xpm_colors);\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-772'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/873'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int encrypt(struct blkcipher_desc *desc,\n\t\t struct scatterlist *dst, struct scatterlist *src,\n\t\t unsigned int nbytes)\n{\n\tstruct blkcipher_walk walk;\n\tstruct crypto_blkcipher *tfm = desc->tfm;\n\tstruct salsa20_ctx *ctx = crypto_blkcipher_ctx(tfm);\n\tint err;\n\n\tblkcipher_walk_init(&walk, dst, src, nbytes);\n\terr = blkcipher_walk_virt_block(desc, &walk, 64);\n\n\tsalsa20_ivsetup(ctx, walk.iv);\n\n\tif (likely(walk.nbytes == nbytes))\n\t{\n\t\tsalsa20_encrypt_bytes(ctx, walk.dst.virt.addr,\n\t\t\t\t walk.src.virt.addr, nbytes);\n\t\treturn blkcipher_walk_done(desc, &walk, 0);\n\t}\n\n\twhile (walk.nbytes >= 64) {\n\t\tsalsa20_encrypt_bytes(ctx, walk.dst.virt.addr,\n\t\t\t\t walk.src.virt.addr,\n\t\t\t\t walk.nbytes - (walk.nbytes % 64));\n\t\terr = blkcipher_walk_done(desc, &walk, walk.nbytes % 64);\n\t}\n\n\tif (walk.nbytes) {\n\t\tsalsa20_encrypt_bytes(ctx, walk.dst.virt.addr,\n\t\t\t\t walk.src.virt.addr, walk.nbytes);\n\t\terr = blkcipher_walk_done(desc, &walk, 0);\n\t}\n\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-200'], 'message': 'crypto: salsa20 - fix blkcipher_walk API usage\n\nWhen asked to encrypt or decrypt 0 bytes, both the generic and x86\nimplementations of Salsa20 crash in blkcipher_walk_done(), either when\ndoing 'kfree(walk->buffer)' or 'free_page((unsigned long)walk->page)',\nbecause walk->buffer and walk->page have not been initialized.\n\nThe bug is that Salsa20 is calling blkcipher_walk_done() even when\nnothing is in 'walk.nbytes'. But blkcipher_walk_done() is only meant to\nbe called when a nonzero number of bytes have been provided.\n\nThe broken code is part of an optimization that tries to make only one\ncall to salsa20_encrypt_bytes() to process inputs that are not evenly\ndivisible by 64 bytes. To fix the bug, just remove this \"optimization\"\nand use the blkcipher_walk API the same way all the other users do.\n\nReproducer:\n\n #include \n #include \n #include \n\n int main()\n {\n int algfd, reqfd;\n struct sockaddr_alg addr = {\n .salg_type = \"skcipher\",\n .salg_name = \"salsa20\",\n };\n char key[16] = { 0 };\n\n algfd = socket(AF_ALG, SOCK_SEQPACKET, 0);\n bind(algfd, (void *)&addr, sizeof(addr));\n reqfd = accept(algfd, 0, 0);\n setsockopt(algfd, SOL_ALG, ALG_SET_KEY, key, sizeof(key));\n read(reqfd, key, sizeof(key));\n }\n\nReported-by: syzbot \nFixes: eb6f13eb9f81 (\"[CRYPTO] salsa20_generic: Fix multi-page processing\")\nCc: # v2.6.25+\nSigned-off-by: Eric Biggers \nSigned-off-by: Herbert Xu '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: read_creator_block (FILE *f,\n gint image_ID,\n guint total_len,\n PSPimage *ia)\n{\n long data_start;\n guchar buf[4];\n guint16 keyword;\n guint32 length;\n gchar *string;\n gchar *title = NULL, *artist = NULL, *copyright = NULL, *description = NULL;\n guint32 dword;\n guint32 cdate = 0, mdate = 0, appid, appver;\n GString *comment;\n GimpParasite *comment_parasite;\n\n data_start = ftell (f);\n comment = g_string_new (NULL);\n\n while (ftell (f) < data_start + total_len)\n {\n if (fread (buf, 4, 1, f) < 1\n || fread (&keyword, 2, 1, f) < 1\n || fread (&length, 4, 1, f) < 1)\n {\n g_message (\"Error reading creator keyword chunk\");\n return -1;\n }\n if (memcmp (buf, \"~FL\\0\", 4) != 0)\n {\n g_message (\"Invalid keyword chunk header\");\n return -1;\n }\n keyword = GUINT16_FROM_LE (keyword);\n length = GUINT32_FROM_LE (length);\n switch (keyword)\n {\n case PSP_CRTR_FLD_TITLE:\n case PSP_CRTR_FLD_ARTIST:\n case PSP_CRTR_FLD_CPYRGHT:\n case PSP_CRTR_FLD_DESC:\n string = g_malloc (length + 1);\n if (fread (string, length, 1, f) < 1)\n {\n g_message (\"Error reading creator keyword data\");\n g_free (string);\n return -1;\n }\n switch (keyword)\n {\n case PSP_CRTR_FLD_TITLE:\n g_free (title); title = string; break;\n case PSP_CRTR_FLD_ARTIST:\n g_free (artist); artist = string; break;\n case PSP_CRTR_FLD_CPYRGHT:\n g_free (copyright); copyright = string; break;\n case PSP_CRTR_FLD_DESC:\n g_free (description); description = string; break;\n default:\n g_free (string);\n }\n break;\n case PSP_CRTR_FLD_CRT_DATE:\n case PSP_CRTR_FLD_MOD_DATE:\n case PSP_CRTR_FLD_APP_ID:\n case PSP_CRTR_FLD_APP_VER:\n if (fread (&dword, 4, 1, f) < 1)\n {\n g_message (\"Error reading creator keyword data\");\n return -1;\n }\n switch (keyword)\n {\n case PSP_CRTR_FLD_CRT_DATE:\n cdate = dword; break;\n case PSP_CRTR_FLD_MOD_DATE:\n mdate = dword; break;\n case PSP_CRTR_FLD_APP_ID:\n appid = dword; break;\n case PSP_CRTR_FLD_APP_VER:\n appver = dword; break;\n }\n break;\n default:\n if (try_fseek (f, length, SEEK_CUR) < 0)\n {\n return -1;\n }\n break;\n }\n }\n\n if (title)\n {\n g_string_append (comment, title);\n g_free (title);\n g_string_append (comment, \"\\n\");\n }\n if (artist)\n {\n g_string_append (comment, artist);\n g_free (artist);\n g_string_append (comment, \"\\n\");\n }\n if (copyright)\n {\n g_string_append (comment, \"Copyright \");\n g_string_append (comment, copyright);\n g_free (copyright);\n g_string_append (comment, \"\\n\");\n }\n if (description)\n {\n g_string_append (comment, description);\n g_free (description);\n g_string_append (comment, \"\\n\");\n }\n if (comment->len > 0)\n {\n comment_parasite = gimp_parasite_new (\"gimp-comment\",\n GIMP_PARASITE_PERSISTENT,\n strlen (comment->str) + 1,\n comment->str);\n gimp_image_attach_parasite (image_ID, comment_parasite);\n gimp_parasite_free (comment_parasite);\n }\n\n g_string_free (comment, FALSE);\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Bug 790853 - (CVE-2017-17787) heap overread in psp importer.\n\nAs any external data, we have to check that strings being read at fixed\nlength are properly nul-terminated.\n\n(cherry picked from commit eb2980683e6472aff35a3117587c4f814515c74d)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void fli_read_brun(FILE *f, s_fli_header *fli_header, unsigned char *framebuf)\n{\n\tunsigned short yc;\n\tunsigned char *pos;\n\tfor (yc=0; yc < fli_header->height; yc++) {\n\t\tunsigned short xc, pc, pcnt;\n\t\tpc=fli_read_char(f);\n\t\txc=0;\n\t\tpos=framebuf+(fli_header->width * yc);\n\t\tfor (pcnt=pc; pcnt>0; pcnt--) {\n\t\t\tunsigned short ps;\n\t\t\tps=fli_read_char(f);\n\t\t\tif (ps & 0x80) {\n\t\t\t\tunsigned short len;\n\t\t\t\tfor (len=-(signed char)ps; len>0; len--) {\n\t\t\t\t\tpos[xc++]=fli_read_char(f);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tunsigned char val;\n\t\t\t\tval=fli_read_char(f);\n\t\t\t\tmemset(&(pos[xc]), val, ps);\n\t\t\t\txc+=ps;\n\t\t\t}\n\t\t}\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Bug 739133 - (CVE-2017-17785) Heap overflow while parsing FLI files.\n\nIt is possible to trigger a heap overflow while parsing FLI files. The\nRLE decoder is vulnerable to out of boundary writes due to lack of\nboundary checks.\n\nThe variable \"framebuf\" points to a memory area which was allocated\nwith fli_header->width * fli_header->height bytes. The RLE decoder\ntherefore must never write beyond that limit.\n\nIf an illegal frame is detected, the parser won't stop, which means\nthat the next valid sequence is properly parsed again. This should\nallow GIMP to parse FLI files as good as possible even if they are\nbroken by an attacker or by accident.\n\nWhile at it, I changed the variable xc to be of type size_t, because\nthe multiplication of width and height could overflow a 16 bit type.\n\nSigned-off-by: Tobias Stoeckmann '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Cache GetImagePixelCache(Image *image,const MagickBooleanType clone,\n ExceptionInfo *exception)\n{\n CacheInfo\n *magick_restrict cache_info;\n\n MagickBooleanType\n destroy,\n status;\n\n static MagickSizeType\n cache_timelimit = MagickResourceInfinity,\n cpu_throttle = MagickResourceInfinity,\n cycles = 0;\n\n status=MagickTrue;\n if (cpu_throttle == MagickResourceInfinity)\n cpu_throttle=GetMagickResourceLimit(ThrottleResource);\n if ((cpu_throttle != 0) && ((cycles++ % 32) == 0))\n MagickDelay(cpu_throttle);\n if (cache_epoch == 0)\n {\n /*\n Set the expire time in seconds.\n */\n cache_timelimit=GetMagickResourceLimit(TimeResource);\n cache_epoch=time((time_t *) NULL);\n }\n if ((cache_timelimit != MagickResourceInfinity) &&\n ((MagickSizeType) (time((time_t *) NULL)-cache_epoch) >= cache_timelimit))\n {\n#if defined(ECANCELED)\n errno=ECANCELED;\n#endif\n ThrowFatalException(ResourceLimitFatalError,\"TimeLimitExceeded\");\n }\n LockSemaphoreInfo(image->semaphore);\n assert(image->cache != (Cache) NULL);\n cache_info=(CacheInfo *) image->cache;\n#if defined(MAGICKCORE_OPENCL_SUPPORT)\n CopyOpenCLBuffer(cache_info);\n#endif\n destroy=MagickFalse;\n if ((cache_info->reference_count > 1) || (cache_info->mode == ReadMode))\n {\n LockSemaphoreInfo(cache_info->semaphore);\n if ((cache_info->reference_count > 1) || (cache_info->mode == ReadMode))\n {\n CacheInfo\n *clone_info;\n\n Image\n clone_image;\n\n /*\n Clone pixel cache.\n */\n clone_image=(*image);\n clone_image.semaphore=AcquireSemaphoreInfo();\n clone_image.reference_count=1;\n clone_image.cache=ClonePixelCache(cache_info);\n clone_info=(CacheInfo *) clone_image.cache;\n status=OpenPixelCache(&clone_image,IOMode,exception);\n if (status != MagickFalse)\n {\n if (clone != MagickFalse)\n status=ClonePixelCacheRepository(clone_info,cache_info,\n exception);\n if (status != MagickFalse)\n {\n destroy=MagickTrue;\n image->cache=clone_image.cache;\n }\n }\n RelinquishSemaphoreInfo(&clone_image.semaphore);\n }\n UnlockSemaphoreInfo(cache_info->semaphore);\n }\n if (destroy != MagickFalse)\n cache_info=(CacheInfo *) DestroyPixelCache(cache_info);\n if (status != MagickFalse)\n {\n /*\n Ensure the image matches the pixel cache morphology.\n */\n image->type=UndefinedType;\n if (ValidatePixelCacheMorphology(image) == MagickFalse)\n {\n status=OpenPixelCache(image,IOMode,exception);\n cache_info=(CacheInfo *) image->cache;\n if (cache_info->type == DiskCache)\n (void) ClosePixelCacheOnDisk(cache_info);\n }\n }\n UnlockSemaphoreInfo(image->semaphore);\n if (status == MagickFalse)\n return((Cache) NULL);\n return(image->cache);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-772'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/903'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: read_gif(Gif_Reader *grr, int read_flags,\n\t const char* landmark, Gif_ReadErrorHandler handler)\n{\n Gif_Stream *gfs;\n Gif_Image *gfi;\n Gif_Context gfc;\n int unknown_block_type = 0;\n\n if (gifgetc(grr) != 'G' ||\n gifgetc(grr) != 'I' ||\n gifgetc(grr) != 'F')\n return 0;\n (void)gifgetc(grr);\n (void)gifgetc(grr);\n (void)gifgetc(grr);\n\n gfs = Gif_NewStream();\n gfi = Gif_NewImage();\n\n gfc.stream = gfs;\n gfc.prefix = Gif_NewArray(Gif_Code, GIF_MAX_CODE);\n gfc.suffix = Gif_NewArray(uint8_t, GIF_MAX_CODE);\n gfc.length = Gif_NewArray(uint16_t, GIF_MAX_CODE);\n gfc.handler = handler;\n gfc.gfi = gfi;\n gfc.errors[0] = gfc.errors[1] = 0;\n\n if (!gfs || !gfi || !gfc.prefix || !gfc.suffix || !gfc.length)\n goto done;\n gfs->landmark = landmark;\n\n GIF_DEBUG((\"\\nGIF \"));\n if (!read_logical_screen_descriptor(gfs, grr))\n goto done;\n GIF_DEBUG((\"logscrdesc \"));\n\n while (!gifeof(grr)) {\n\n uint8_t block = gifgetbyte(grr);\n\n switch (block) {\n\n case ',': /* image block */\n GIF_DEBUG((\"imageread %d \", gfs->nimages));\n\n gfi->identifier = last_name;\n last_name = 0;\n if (!Gif_AddImage(gfs, gfi))\n goto done;\n else if (!read_image(grr, &gfc, gfi, read_flags)) {\n Gif_RemoveImage(gfs, gfs->nimages - 1);\n goto done;\n }\n\n gfc.gfi = gfi = Gif_NewImage();\n if (!gfi)\n goto done;\n break;\n\n case ';': /* terminator */\n GIF_DEBUG((\"term\\n\"));\n goto done;\n\n case '!': /* extension */\n block = gifgetbyte(grr);\n GIF_DEBUG((\"ext(0x%02X) \", block));\n switch (block) {\n\n case 0xF9:\n\tread_graphic_control_extension(&gfc, gfi, grr);\n\tbreak;\n\n case 0xCE:\n\tlast_name = suck_data(last_name, 0, grr);\n\tbreak;\n\n case 0xFE:\n\tif (!read_comment_extension(gfi, grr)) goto done;\n\tbreak;\n\n case 0xFF:\n\tread_application_extension(&gfc, grr);\n\tbreak;\n\n default:\n read_unknown_extension(&gfc, grr, block, 0, 0);\n\tbreak;\n\n }\n break;\n\n default:\n if (!unknown_block_type) {\n\t char buf[256];\n\t sprintf(buf, \"unknown block type %d at file offset %u\", block, grr->pos - 1);\n\t gif_read_error(&gfc, 1, buf);\n\t unknown_block_type = 1;\n }\n break;\n\n }\n\n }\n\n done:\n\n /* Move comments and extensions after last image into stream. */\n if (gfs && gfi) {\n Gif_Extension* gfex;\n gfs->end_comment = gfi->comment;\n gfi->comment = 0;\n gfs->end_extension_list = gfi->extension_list;\n gfi->extension_list = 0;\n for (gfex = gfs->end_extension_list; gfex; gfex = gfex->next)\n gfex->image = NULL;\n }\n\n Gif_DeleteImage(gfi);\n Gif_DeleteArray(last_name);\n Gif_DeleteArray(gfc.prefix);\n Gif_DeleteArray(gfc.suffix);\n Gif_DeleteArray(gfc.length);\n gfc.gfi = 0;\n\n if (gfs)\n gfs->errors = gfc.errors[1];\n if (gfs && gfc.errors[1] == 0\n && !(read_flags & GIF_READ_TRAILING_GARBAGE_OK)\n && !grr->eofer(grr))\n gif_read_error(&gfc, 0, \"trailing garbage after GIF ignored\");\n /* finally, export last message */\n gif_read_error(&gfc, -1, 0);\n\n return gfs;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Fix use-after-free problems reported in #114.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void ZipTest::testCrcAndSizeAfterData()\n{\n\tstd::string testFile = getTestFile(\"data\", \"data.zip\");\n\tstd::ifstream inp(testFile.c_str(), std::ios::binary);\n\tassert (inp.good());\n\tDecompress dec(inp, Poco::Path());\n\tdec.EError += Poco::Delegate >(this, &ZipTest::onDecompressError);\n\tdec.decompressAllFiles();\n\tdec.EError -= Poco::Delegate >(this, &ZipTest::onDecompressError);\n\tassert (_errCnt == 0);\n\tassert (!dec.mapping().empty());\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-22'], 'message': 'merge zip entry absolute path vulnerability fix (#1968) from develop'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void CompressTest::testDirectory()\n{\n\tstd::ofstream out(\"pocobin.zip\", std::ios::binary);\n\tPoco::File aFile(\"some/\");\n\tif (aFile.exists())\n\t\taFile.remove(true);\n\tPoco::File aDir(\"some/recursive/dir/\");\n\taDir.createDirectories();\n\tPoco::File aDir2(\"some/other/recursive/dir/\");\n\taDir2.createDirectories();\n\tPoco::File aF(\"some/recursive/dir/test.file\");\n\taF.createFile();\n\tPoco::FileOutputStream fos(aF.path());\n\tfos << \"just some test data\";\n\tfos.close();\n\n\tPoco::Path theFile(aFile.path());\n\ttheFile.makeDirectory();\n\tCompress c(out, true);\n\tc.addRecursive(theFile, ZipCommon::CL_MAXIMUM, false, theFile);\n\tZipArchive a(c.close());\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-22'], 'message': 'merge zip entry absolute path vulnerability fix (#1968) from develop'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void automount_enter_runnning(Automount *a) {\n _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;\n struct stat st;\n int r;\n\n assert(a);\n\n /* If the user masked our unit in the meantime, fail */\n if (UNIT(a)->load_state != UNIT_LOADED) {\n log_unit_error(UNIT(a), \"Suppressing automount event since unit is no longer loaded.\");\n goto fail;\n }\n\n /* We don't take mount requests anymore if we are supposed to\n * shut down anyway */\n if (unit_stop_pending(UNIT(a))) {\n log_unit_debug(UNIT(a), \"Suppressing automount request since unit stop is scheduled.\");\n automount_send_ready(a, a->tokens, -EHOSTDOWN);\n automount_send_ready(a, a->expire_tokens, -EHOSTDOWN);\n return;\n }\n\n mkdir_p_label(a->where, a->directory_mode);\n\n /* Before we do anything, let's see if somebody is playing games with us? */\n if (lstat(a->where, &st) < 0) {\n log_unit_warning_errno(UNIT(a), errno, \"Failed to stat automount point: %m\");\n goto fail;\n }\n\n if (!S_ISDIR(st.st_mode) || st.st_dev != a->dev_id)\n log_unit_info(UNIT(a), \"Automount point already active?\");\n else {\n Unit *trigger;\n\n trigger = UNIT_TRIGGER(UNIT(a));\n if (!trigger) {\n log_unit_error(UNIT(a), \"Unit to trigger vanished.\");\n goto fail;\n }\n\n r = manager_add_job(UNIT(a)->manager, JOB_START, trigger, JOB_REPLACE, &error, NULL);\n if (r < 0) {\n log_unit_warning(UNIT(a), \"Failed to queue mount startup job: %s\", bus_error_message(&error, r));\n goto fail;\n }\n }\n\n automount_set_state(a, AUTOMOUNT_RUNNING);\n return;\n\nfail:\n automount_enter_dead(a, AUTOMOUNT_FAILURE_RESOURCES);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'automount: ack automount requests even when already mounted (#5916)\n\nIf a process accesses an autofs filesystem while systemd is in the\r\nmiddle of starting the mount unit on top of it, it is possible for the\r\nautofs_ptype_missing_direct request from the kernel to be received after\r\nthe mount unit has been fully started:\r\n\r\n systemd forks and execs mount ...\r\n ... access autofs, blocks\r\n mount exits ...\r\n systemd receives SIGCHLD ...\r\n ... kernel sends request\r\n systemd receives request ...\r\n\r\nsystemd needs to respond to this request, otherwise the kernel will\r\ncontinue to block access to the mount point.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: BGD_DECLARE(gdImagePtr) gdImageCreateFromGifCtx(gdIOCtxPtr fd)\n{\n\tint BitPixel;\n#if 0\n\tint ColorResolution;\n\tint Background;\n\tint AspectRatio;\n#endif\n\tint Transparent = (-1);\n\tunsigned char buf[16];\n\tunsigned char c;\n\tunsigned char ColorMap[3][MAXCOLORMAPSIZE];\n\tunsigned char localColorMap[3][MAXCOLORMAPSIZE];\n\tint imw, imh, screen_width, screen_height;\n\tint useGlobalColormap;\n\tint bitPixel, i;\n\t/*1.4//int imageCount = 0; */\n\t/* 2.0.28: threadsafe storage */\n\tint ZeroDataBlock = FALSE;\n\tint haveGlobalColormap;\n\n\tgdImagePtr im = 0;\n\n\tmemset(ColorMap, 0, 3 * MAXCOLORMAPSIZE);\n\tmemset(localColorMap, 0, 3 * MAXCOLORMAPSIZE);\n\n\tif(!ReadOK(fd, buf, 6)) {\n\t\treturn 0;\n\t}\n\n\tif(strncmp((char *)buf, \"GIF\", 3) != 0) {\n\t\treturn 0;\n\t}\n\n\tif(memcmp((char *)buf + 3, \"87a\", 3) == 0) {\n\t\t/* GIF87a */\n\t} else if(memcmp((char *)buf + 3, \"89a\", 3) == 0) {\n\t\t/* GIF89a */\n\t} else {\n\t\treturn 0;\n\t}\n\n\tif(!ReadOK(fd, buf, 7)) {\n\t\treturn 0;\n\t}\n\n\tBitPixel = 2 << (buf[4] & 0x07);\n#if 0\n\tColorResolution = (int) (((buf[4]&0x70)>>3)+1);\n\tBackground = buf[5];\n\tAspectRatio = buf[6];\n#endif\n\tscreen_width = imw = LM_to_uint(buf[0], buf[1]);\n\tscreen_height = imh = LM_to_uint(buf[2], buf[3]);\n\n\thaveGlobalColormap = BitSet(buf[4], LOCALCOLORMAP); /* Global Colormap */\n\tif(haveGlobalColormap) {\n\t\tif(ReadColorMap(fd, BitPixel, ColorMap)) {\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\tfor (;;) {\n\t\tint top, left;\n\t\tint width, height;\n\n\t\tif(!ReadOK(fd, &c, 1)) {\n\t\t\treturn 0;\n\t\t}\n\n\t\tif (c == ';') { /* GIF terminator */\n\t\t\tgoto terminated;\n\t\t}\n\n\t\tif(c == '!') { /* Extension */\n\t\t\tif(!ReadOK(fd, &c, 1)) {\n\t\t\t\treturn 0;\n\t\t\t}\n\n\t\t\tDoExtension(fd, c, &Transparent, &ZeroDataBlock);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif(c != ',') { /* Not a valid start character */\n\t\t\tcontinue;\n\t\t}\n\n\t\t/*1.4//++imageCount; */\n\n\t\tif(!ReadOK(fd, buf, 9)) {\n\t\t\treturn 0;\n\t\t}\n\n\t\tuseGlobalColormap = !BitSet(buf[8], LOCALCOLORMAP);\n\n\t\tbitPixel = 1 << ((buf[8] & 0x07) + 1);\n\t\tleft = LM_to_uint(buf[0], buf[1]);\n\t\ttop = LM_to_uint(buf[2], buf[3]);\n\t\twidth = LM_to_uint(buf[4], buf[5]);\n\t\theight = LM_to_uint(buf[6], buf[7]);\n\n\t\tif(((left + width) > screen_width) || ((top + height) > screen_height)) {\n\t\t\tif(VERBOSE) {\n\t\t\t\tprintf(\"Frame is not confined to screen dimension.\\n\");\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\n\t\tif(!(im = gdImageCreate(width, height))) {\n\t\t\treturn 0;\n\t\t}\n\n\t\tim->interlace = BitSet(buf[8], INTERLACE);\n\t\tif(!useGlobalColormap) {\n\t\t\tif(ReadColorMap(fd, bitPixel, localColorMap)) {\n\t\t\t\tgdImageDestroy(im);\n\t\t\t\treturn 0;\n\t\t\t}\n\n\t\t\tReadImage(im, fd, width, height, localColorMap, BitSet(buf[8], INTERLACE), &ZeroDataBlock);\n\t\t} else {\n\t\t\tif(!haveGlobalColormap) {\n\t\t\t\tgdImageDestroy(im);\n\t\t\t\treturn 0;\n\t\t\t}\n\n\t\t\tReadImage(im, fd, width, height, ColorMap, BitSet(buf[8], INTERLACE), &ZeroDataBlock);\n\t\t}\n\n\t\tif(Transparent != (-1)) {\n\t\t\tgdImageColorTransparent(im, Transparent);\n\t\t}\n\n\t\tgoto terminated;\n\t}\n\nterminated:\n\t/* Terminator before any image was declared! */\n\tif(!im) {\n\t\treturn 0;\n\t}\n\n\tif(!im->colorsTotal) {\n\t\tgdImageDestroy(im);\n\t\treturn 0;\n\t}\n\n\t/* Check for open colors at the end, so\n\t * we can reduce colorsTotal and ultimately\n\t * BitsPerPixel */\n\tfor(i = im->colorsTotal - 1; i >= 0; i--) {\n\t\tif(im->open[i]) {\n\t\t\tim->colorsTotal--;\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn im;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-681'], 'message': 'Fix #420: Potential infinite loop in gdImageCreateFromGifCtx\n\nDue to a signedness confusion in `GetCode_` a corrupt GIF file can\ntrigger an infinite loop. Furthermore we make sure that a GIF without\nany palette entries is treated as invalid *after* open palette entries\nhave been removed.\n\nCVE-2018-5711\n\nSee also https://bugs.php.net/bug.php?id=75571.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void pcrypt_free(struct crypto_instance *inst)\n{\n\tstruct pcrypt_instance_ctx *ctx = crypto_instance_ctx(inst);\n\n\tcrypto_drop_aead(&ctx->spawn);\n\tkfree(inst);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-763'], 'message': 'crypto: pcrypt - fix freeing pcrypt instances\n\npcrypt is using the old way of freeing instances, where the ->free()\nmethod specified in the 'struct crypto_template' is passed a pointer to\nthe 'struct crypto_instance'. But the crypto_instance is being\nkfree()'d directly, which is incorrect because the memory was actually\nallocated as an aead_instance, which contains the crypto_instance at a\nnonzero offset. Thus, the wrong pointer was being kfree()'d.\n\nFix it by switching to the new way to free aead_instance's where the\n->free() method is specified in the aead_instance itself.\n\nReported-by: syzbot \nFixes: 0496f56065e0 (\"crypto: pcrypt - Add support for new AEAD interface\")\nCc: # v4.2+\nSigned-off-by: Eric Biggers \nSigned-off-by: Herbert Xu '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static js_Ast *multiplicative(js_State *J)\n{\n\tjs_Ast *a = unary(J);\nloop:\n\tif (jsP_accept(J, '*')) { a = EXP2(MUL, a, unary(J)); goto loop; }\n\tif (jsP_accept(J, '/')) { a = EXP2(DIV, a, unary(J)); goto loop; }\n\tif (jsP_accept(J, '%')) { a = EXP2(MOD, a, unary(J)); goto loop; }\n\treturn a;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-674'], 'message': 'Guard binary expressions from too much recursion.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static irqreturn_t i8042_interrupt(int irq, void *dev_id)\n{\n\tstruct i8042_port *port;\n\tstruct serio *serio;\n\tunsigned long flags;\n\tunsigned char str, data;\n\tunsigned int dfl;\n\tunsigned int port_no;\n\tbool filtered;\n\tint ret = 1;\n\n\tspin_lock_irqsave(&i8042_lock, flags);\n\n\tstr = i8042_read_status();\n\tif (unlikely(~str & I8042_STR_OBF)) {\n\t\tspin_unlock_irqrestore(&i8042_lock, flags);\n\t\tif (irq)\n\t\t\tdbg(\"Interrupt %d, without any data\\n\", irq);\n\t\tret = 0;\n\t\tgoto out;\n\t}\n\n\tdata = i8042_read_data();\n\n\tif (i8042_mux_present && (str & I8042_STR_AUXDATA)) {\n\t\tstatic unsigned long last_transmit;\n\t\tstatic unsigned char last_str;\n\n\t\tdfl = 0;\n\t\tif (str & I8042_STR_MUXERR) {\n\t\t\tdbg(\"MUX error, status is %02x, data is %02x\\n\",\n\t\t\t str, data);\n/*\n * When MUXERR condition is signalled the data register can only contain\n * 0xfd, 0xfe or 0xff if implementation follows the spec. Unfortunately\n * it is not always the case. Some KBCs also report 0xfc when there is\n * nothing connected to the port while others sometimes get confused which\n * port the data came from and signal error leaving the data intact. They\n * _do not_ revert to legacy mode (actually I've never seen KBC reverting\n * to legacy mode yet, when we see one we'll add proper handling).\n * Anyway, we process 0xfc, 0xfd, 0xfe and 0xff as timeouts, and for the\n * rest assume that the data came from the same serio last byte\n * was transmitted (if transmission happened not too long ago).\n */\n\n\t\t\tswitch (data) {\n\t\t\t\tdefault:\n\t\t\t\t\tif (time_before(jiffies, last_transmit + HZ/10)) {\n\t\t\t\t\t\tstr = last_str;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t/* fall through - report timeout */\n\t\t\t\tcase 0xfc:\n\t\t\t\tcase 0xfd:\n\t\t\t\tcase 0xfe: dfl = SERIO_TIMEOUT; data = 0xfe; break;\n\t\t\t\tcase 0xff: dfl = SERIO_PARITY; data = 0xfe; break;\n\t\t\t}\n\t\t}\n\n\t\tport_no = I8042_MUX_PORT_NO + ((str >> 6) & 3);\n\t\tlast_str = str;\n\t\tlast_transmit = jiffies;\n\t} else {\n\n\t\tdfl = ((str & I8042_STR_PARITY) ? SERIO_PARITY : 0) |\n\t\t ((str & I8042_STR_TIMEOUT && !i8042_notimeout) ? SERIO_TIMEOUT : 0);\n\n\t\tport_no = (str & I8042_STR_AUXDATA) ?\n\t\t\t\tI8042_AUX_PORT_NO : I8042_KBD_PORT_NO;\n\t}\n\n\tport = &i8042_ports[port_no];\n\tserio = port->exists ? port->serio : NULL;\n\n\tfilter_dbg(port->driver_bound, data, \"<- i8042 (interrupt, %d, %d%s%s)\\n\",\n\t\t port_no, irq,\n\t\t dfl & SERIO_PARITY ? \", bad parity\" : \"\",\n\t\t dfl & SERIO_TIMEOUT ? \", timeout\" : \"\");\n\n\tfiltered = i8042_filter(data, str, serio);\n\n\tspin_unlock_irqrestore(&i8042_lock, flags);\n\n\tif (likely(port->exists && !filtered))\n\t\tserio_interrupt(serio, data, dfl);\n\n out:\n\treturn IRQ_RETVAL(ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Input: i8042 - fix crash at boot time\n\nThe driver checks port->exists twice in i8042_interrupt(), first when\ntrying to assign temporary \"serio\" variable, and second time when deciding\nwhether it should call serio_interrupt(). The value of port->exists may\nchange between the 2 checks, and we may end up calling serio_interrupt()\nwith a NULL pointer:\n\nBUG: unable to handle kernel NULL pointer dereference at 0000000000000050\nIP: [] _spin_lock_irqsave+0x1f/0x40\nPGD 0\nOops: 0002 [#1] SMP\nlast sysfs file:\nCPU 0\nModules linked in:\n\nPid: 1, comm: swapper Not tainted 2.6.32-358.el6.x86_64 #1 QEMU Standard PC (i440FX + PIIX, 1996)\nRIP: 0010:[] [] _spin_lock_irqsave+0x1f/0x40\nRSP: 0018:ffff880028203cc0 EFLAGS: 00010082\nRAX: 0000000000010000 RBX: 0000000000000000 RCX: 0000000000000000\nRDX: 0000000000000282 RSI: 0000000000000098 RDI: 0000000000000050\nRBP: ffff880028203cc0 R08: ffff88013e79c000 R09: ffff880028203ee0\nR10: 0000000000000298 R11: 0000000000000282 R12: 0000000000000050\nR13: 0000000000000000 R14: 0000000000000000 R15: 0000000000000098\nFS: 0000000000000000(0000) GS:ffff880028200000(0000) knlGS:0000000000000000\nCS: 0010 DS: 0018 ES: 0018 CR0: 000000008005003b\nCR2: 0000000000000050 CR3: 0000000001a85000 CR4: 00000000001407f0\nDR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000\nDR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400\nProcess swapper (pid: 1, threadinfo ffff88013e79c000, task ffff88013e79b500)\nStack:\nffff880028203d00 ffffffff813de186 ffffffffffffff02 0000000000000000\n 0000000000000000 0000000000000000 0000000000000000 0000000000000098\n ffff880028203d70 ffffffff813e0162 ffff880028203d20 ffffffff8103b8ac\nCall Trace:\n\n [] serio_interrupt+0x36/0xa0\n[] i8042_interrupt+0x132/0x3a0\n[] ? kvm_clock_read+0x1c/0x20\n[] ? kvm_clock_get_cycles+0x9/0x10\n[] handle_IRQ_event+0x60/0x170\n[] ? kvm_guest_apic_eoi_write+0x44/0x50\n[] handle_edge_irq+0xde/0x180\n[] handle_irq+0x49/0xa0\n[] do_IRQ+0x6c/0xf0\n[] ret_from_intr+0x0/0x11\n[] ? __do_softirq+0x73/0x1e0\n[] ? hrtimer_interrupt+0x14b/0x260\n[] ? call_softirq+0x1c/0x30\n[] ? do_softirq+0x65/0xa0\n[] ? irq_exit+0x85/0x90\n[] ? smp_apic_timer_interrupt+0x70/0x9b\n[] ? apic_timer_interrupt+0x13/0x20\n\nTo avoid the issue let's change the second check to test whether serio is\nNULL or not.\n\nAlso, let's take i8042_lock in i8042_start() and i8042_stop() instead of\ntrying to be overly smart and using memory barriers.\n\nSigned-off-by: Chen Hong \n[dtor: take lock in i8042_start()/i8042_stop()]\nCc: stable@vger.kernel.org\nSigned-off-by: Dmitry Torokhov '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int parse_status(const char *value)\n{\n\tint ret = 0;\n\tchar *c;\n\n\t/* skip a header line */\n\tc = strchr(value, '\\n');\n\tif (!c)\n\t\treturn -1;\n\tc++;\n\n\twhile (*c != '\\0') {\n\t\tint port, status, speed, devid;\n\t\tunsigned long socket;\n\t\tchar lbusid[SYSFS_BUS_ID_SIZE];\n\t\tstruct usbip_imported_device *idev;\n\t\tchar hub[3];\n\n\t\tret = sscanf(c, \"%2s %d %d %d %x %lx %31s\\n\",\n\t\t\t\thub, &port, &status, &speed,\n\t\t\t\t&devid, &socket, lbusid);\n\n\t\tif (ret < 5) {\n\t\t\tdbg(\"sscanf failed: %d\", ret);\n\t\t\tBUG();\n\t\t}\n\n\t\tdbg(\"hub %s port %d status %d speed %d devid %x\",\n\t\t\t\thub, port, status, speed, devid);\n\t\tdbg(\"socket %lx lbusid %s\", socket, lbusid);\n\n\t\t/* if a device is connected, look at it */\n\t\tidev = &vhci_driver->idev[port];\n\t\tmemset(idev, 0, sizeof(*idev));\n\n\t\tif (strncmp(\"hs\", hub, 2) == 0)\n\t\t\tidev->hub = HUB_SPEED_HIGH;\n\t\telse /* strncmp(\"ss\", hub, 2) == 0 */\n\t\t\tidev->hub = HUB_SPEED_SUPER;\n\n\t\tidev->port\t= port;\n\t\tidev->status\t= status;\n\n\t\tidev->devid\t= devid;\n\n\t\tidev->busnum\t= (devid >> 16);\n\t\tidev->devnum\t= (devid & 0x0000ffff);\n\n\t\tif (idev->status != VDEV_ST_NULL\n\t\t && idev->status != VDEV_ST_NOTASSIGNED) {\n\t\t\tidev = imported_device_init(idev, lbusid);\n\t\t\tif (!idev) {\n\t\t\t\tdbg(\"imported_device_init failed\");\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\n\t\t/* go to the next line */\n\t\tc = strchr(c, '\\n');\n\t\tif (!c)\n\t\t\tbreak;\n\t\tc++;\n\t}\n\n\tdbg(\"exit\");\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'usbip: prevent vhci_hcd driver from leaking a socket pointer address\n\nWhen a client has a USB device attached over IP, the vhci_hcd driver is\nlocally leaking a socket pointer address via the\n\n/sys/devices/platform/vhci_hcd/status file (world-readable) and in debug\noutput when \"usbip --debug port\" is run.\n\nFix it to not leak. The socket pointer address is not used at the moment\nand it was made visible as a convenient way to find IP address from socket\npointer address by looking up /proc/net/{tcp,tcp6}.\n\nAs this opens a security hole, the fix replaces socket pointer address with\nsockfd.\n\nReported-by: Secunia Research \nCc: stable \nSigned-off-by: Shuah Khan \nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: flatpak_proxy_client_finalize (GObject *object)\n{\n FlatpakProxyClient *client = FLATPAK_PROXY_CLIENT (object);\n\n client->proxy->clients = g_list_remove (client->proxy->clients, client);\n g_clear_object (&client->proxy);\n\n g_hash_table_destroy (client->rewrite_reply);\n g_hash_table_destroy (client->get_owner_reply);\n g_hash_table_destroy (client->unique_id_policy);\n\n free_side (&client->client_side);\n free_side (&client->bus_side);\n\n G_OBJECT_CLASS (flatpak_proxy_client_parent_class)->finalize (object);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284', 'CWE-436'], 'message': 'Fix vulnerability in dbus proxy\n\nDuring the authentication all client data is directly forwarded\nto the dbus daemon as is, until we detect the BEGIN command after\nwhich we start filtering the binary dbus protocol.\n\nUnfortunately the detection of the BEGIN command in the proxy\ndid not exactly match the detection in the dbus daemon. A BEGIN\nfollowed by a space or tab was considered ok in the daemon but\nnot by the proxy. This could be exploited to send arbitrary\ndbus messages to the host, which can be used to break out of\nthe sandbox.\n\nThis was noticed by Gabriel Campana of The Google Security Team.\n\nThis fix makes the detection of the authentication phase end\nmatch the dbus code. In addition we duplicate the authentication\nline validation from dbus, which includes ensuring all data is\nASCII, and limiting the size of a line to 16k. In fact, we add\nsome extra stringent checks, disallowing ASCII control chars and\nrequiring that auth lines start with a capital letter.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int futex_requeue(u32 __user *uaddr1, unsigned int flags,\n\t\t\t u32 __user *uaddr2, int nr_wake, int nr_requeue,\n\t\t\t u32 *cmpval, int requeue_pi)\n{\n\tunion futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;\n\tint drop_count = 0, task_count = 0, ret;\n\tstruct futex_pi_state *pi_state = NULL;\n\tstruct futex_hash_bucket *hb1, *hb2;\n\tstruct futex_q *this, *next;\n\tDEFINE_WAKE_Q(wake_q);\n\n\t/*\n\t * When PI not supported: return -ENOSYS if requeue_pi is true,\n\t * consequently the compiler knows requeue_pi is always false past\n\t * this point which will optimize away all the conditional code\n\t * further down.\n\t */\n\tif (!IS_ENABLED(CONFIG_FUTEX_PI) && requeue_pi)\n\t\treturn -ENOSYS;\n\n\tif (requeue_pi) {\n\t\t/*\n\t\t * Requeue PI only works on two distinct uaddrs. This\n\t\t * check is only valid for private futexes. See below.\n\t\t */\n\t\tif (uaddr1 == uaddr2)\n\t\t\treturn -EINVAL;\n\n\t\t/*\n\t\t * requeue_pi requires a pi_state, try to allocate it now\n\t\t * without any locks in case it fails.\n\t\t */\n\t\tif (refill_pi_state_cache())\n\t\t\treturn -ENOMEM;\n\t\t/*\n\t\t * requeue_pi must wake as many tasks as it can, up to nr_wake\n\t\t * + nr_requeue, since it acquires the rt_mutex prior to\n\t\t * returning to userspace, so as to not leave the rt_mutex with\n\t\t * waiters and no owner. However, second and third wake-ups\n\t\t * cannot be predicted as they involve race conditions with the\n\t\t * first wake and a fault while looking up the pi_state. Both\n\t\t * pthread_cond_signal() and pthread_cond_broadcast() should\n\t\t * use nr_wake=1.\n\t\t */\n\t\tif (nr_wake != 1)\n\t\t\treturn -EINVAL;\n\t}\n\nretry:\n\tret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, VERIFY_READ);\n\tif (unlikely(ret != 0))\n\t\tgoto out;\n\tret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2,\n\t\t\t requeue_pi ? VERIFY_WRITE : VERIFY_READ);\n\tif (unlikely(ret != 0))\n\t\tgoto out_put_key1;\n\n\t/*\n\t * The check above which compares uaddrs is not sufficient for\n\t * shared futexes. We need to compare the keys:\n\t */\n\tif (requeue_pi && match_futex(&key1, &key2)) {\n\t\tret = -EINVAL;\n\t\tgoto out_put_keys;\n\t}\n\n\thb1 = hash_futex(&key1);\n\thb2 = hash_futex(&key2);\n\nretry_private:\n\thb_waiters_inc(hb2);\n\tdouble_lock_hb(hb1, hb2);\n\n\tif (likely(cmpval != NULL)) {\n\t\tu32 curval;\n\n\t\tret = get_futex_value_locked(&curval, uaddr1);\n\n\t\tif (unlikely(ret)) {\n\t\t\tdouble_unlock_hb(hb1, hb2);\n\t\t\thb_waiters_dec(hb2);\n\n\t\t\tret = get_user(curval, uaddr1);\n\t\t\tif (ret)\n\t\t\t\tgoto out_put_keys;\n\n\t\t\tif (!(flags & FLAGS_SHARED))\n\t\t\t\tgoto retry_private;\n\n\t\t\tput_futex_key(&key2);\n\t\t\tput_futex_key(&key1);\n\t\t\tgoto retry;\n\t\t}\n\t\tif (curval != *cmpval) {\n\t\t\tret = -EAGAIN;\n\t\t\tgoto out_unlock;\n\t\t}\n\t}\n\n\tif (requeue_pi && (task_count - nr_wake < nr_requeue)) {\n\t\t/*\n\t\t * Attempt to acquire uaddr2 and wake the top waiter. If we\n\t\t * intend to requeue waiters, force setting the FUTEX_WAITERS\n\t\t * bit. We force this here where we are able to easily handle\n\t\t * faults rather in the requeue loop below.\n\t\t */\n\t\tret = futex_proxy_trylock_atomic(uaddr2, hb1, hb2, &key1,\n\t\t\t\t\t\t &key2, &pi_state, nr_requeue);\n\n\t\t/*\n\t\t * At this point the top_waiter has either taken uaddr2 or is\n\t\t * waiting on it. If the former, then the pi_state will not\n\t\t * exist yet, look it up one more time to ensure we have a\n\t\t * reference to it. If the lock was taken, ret contains the\n\t\t * vpid of the top waiter task.\n\t\t * If the lock was not taken, we have pi_state and an initial\n\t\t * refcount on it. In case of an error we have nothing.\n\t\t */\n\t\tif (ret > 0) {\n\t\t\tWARN_ON(pi_state);\n\t\t\tdrop_count++;\n\t\t\ttask_count++;\n\t\t\t/*\n\t\t\t * If we acquired the lock, then the user space value\n\t\t\t * of uaddr2 should be vpid. It cannot be changed by\n\t\t\t * the top waiter as it is blocked on hb2 lock if it\n\t\t\t * tries to do so. If something fiddled with it behind\n\t\t\t * our back the pi state lookup might unearth it. So\n\t\t\t * we rather use the known value than rereading and\n\t\t\t * handing potential crap to lookup_pi_state.\n\t\t\t *\n\t\t\t * If that call succeeds then we have pi_state and an\n\t\t\t * initial refcount on it.\n\t\t\t */\n\t\t\tret = lookup_pi_state(uaddr2, ret, hb2, &key2, &pi_state);\n\t\t}\n\n\t\tswitch (ret) {\n\t\tcase 0:\n\t\t\t/* We hold a reference on the pi state. */\n\t\t\tbreak;\n\n\t\t\t/* If the above failed, then pi_state is NULL */\n\t\tcase -EFAULT:\n\t\t\tdouble_unlock_hb(hb1, hb2);\n\t\t\thb_waiters_dec(hb2);\n\t\t\tput_futex_key(&key2);\n\t\t\tput_futex_key(&key1);\n\t\t\tret = fault_in_user_writeable(uaddr2);\n\t\t\tif (!ret)\n\t\t\t\tgoto retry;\n\t\t\tgoto out;\n\t\tcase -EAGAIN:\n\t\t\t/*\n\t\t\t * Two reasons for this:\n\t\t\t * - Owner is exiting and we just wait for the\n\t\t\t * exit to complete.\n\t\t\t * - The user space value changed.\n\t\t\t */\n\t\t\tdouble_unlock_hb(hb1, hb2);\n\t\t\thb_waiters_dec(hb2);\n\t\t\tput_futex_key(&key2);\n\t\t\tput_futex_key(&key1);\n\t\t\tcond_resched();\n\t\t\tgoto retry;\n\t\tdefault:\n\t\t\tgoto out_unlock;\n\t\t}\n\t}\n\n\tplist_for_each_entry_safe(this, next, &hb1->chain, list) {\n\t\tif (task_count - nr_wake >= nr_requeue)\n\t\t\tbreak;\n\n\t\tif (!match_futex(&this->key, &key1))\n\t\t\tcontinue;\n\n\t\t/*\n\t\t * FUTEX_WAIT_REQEUE_PI and FUTEX_CMP_REQUEUE_PI should always\n\t\t * be paired with each other and no other futex ops.\n\t\t *\n\t\t * We should never be requeueing a futex_q with a pi_state,\n\t\t * which is awaiting a futex_unlock_pi().\n\t\t */\n\t\tif ((requeue_pi && !this->rt_waiter) ||\n\t\t (!requeue_pi && this->rt_waiter) ||\n\t\t this->pi_state) {\n\t\t\tret = -EINVAL;\n\t\t\tbreak;\n\t\t}\n\n\t\t/*\n\t\t * Wake nr_wake waiters. For requeue_pi, if we acquired the\n\t\t * lock, we already woke the top_waiter. If not, it will be\n\t\t * woken by futex_unlock_pi().\n\t\t */\n\t\tif (++task_count <= nr_wake && !requeue_pi) {\n\t\t\tmark_wake_futex(&wake_q, this);\n\t\t\tcontinue;\n\t\t}\n\n\t\t/* Ensure we requeue to the expected futex for requeue_pi. */\n\t\tif (requeue_pi && !match_futex(this->requeue_pi_key, &key2)) {\n\t\t\tret = -EINVAL;\n\t\t\tbreak;\n\t\t}\n\n\t\t/*\n\t\t * Requeue nr_requeue waiters and possibly one more in the case\n\t\t * of requeue_pi if we couldn't acquire the lock atomically.\n\t\t */\n\t\tif (requeue_pi) {\n\t\t\t/*\n\t\t\t * Prepare the waiter to take the rt_mutex. Take a\n\t\t\t * refcount on the pi_state and store the pointer in\n\t\t\t * the futex_q object of the waiter.\n\t\t\t */\n\t\t\tget_pi_state(pi_state);\n\t\t\tthis->pi_state = pi_state;\n\t\t\tret = rt_mutex_start_proxy_lock(&pi_state->pi_mutex,\n\t\t\t\t\t\t\tthis->rt_waiter,\n\t\t\t\t\t\t\tthis->task);\n\t\t\tif (ret == 1) {\n\t\t\t\t/*\n\t\t\t\t * We got the lock. We do neither drop the\n\t\t\t\t * refcount on pi_state nor clear\n\t\t\t\t * this->pi_state because the waiter needs the\n\t\t\t\t * pi_state for cleaning up the user space\n\t\t\t\t * value. It will drop the refcount after\n\t\t\t\t * doing so.\n\t\t\t\t */\n\t\t\t\trequeue_pi_wake_futex(this, &key2, hb2);\n\t\t\t\tdrop_count++;\n\t\t\t\tcontinue;\n\t\t\t} else if (ret) {\n\t\t\t\t/*\n\t\t\t\t * rt_mutex_start_proxy_lock() detected a\n\t\t\t\t * potential deadlock when we tried to queue\n\t\t\t\t * that waiter. Drop the pi_state reference\n\t\t\t\t * which we took above and remove the pointer\n\t\t\t\t * to the state from the waiters futex_q\n\t\t\t\t * object.\n\t\t\t\t */\n\t\t\t\tthis->pi_state = NULL;\n\t\t\t\tput_pi_state(pi_state);\n\t\t\t\t/*\n\t\t\t\t * We stop queueing more waiters and let user\n\t\t\t\t * space deal with the mess.\n\t\t\t\t */\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\trequeue_futex(this, hb1, hb2, &key2);\n\t\tdrop_count++;\n\t}\n\n\t/*\n\t * We took an extra initial reference to the pi_state either\n\t * in futex_proxy_trylock_atomic() or in lookup_pi_state(). We\n\t * need to drop it here again.\n\t */\n\tput_pi_state(pi_state);\n\nout_unlock:\n\tdouble_unlock_hb(hb1, hb2);\n\twake_up_q(&wake_q);\n\thb_waiters_dec(hb2);\n\n\t/*\n\t * drop_futex_key_refs() must be called outside the spinlocks. During\n\t * the requeue we moved futex_q's from the hash bucket at key1 to the\n\t * one at key2 and updated their key pointer. We no longer need to\n\t * hold the references to key1.\n\t */\n\twhile (--drop_count >= 0)\n\t\tdrop_futex_key_refs(&key1);\n\nout_put_keys:\n\tput_futex_key(&key2);\nout_put_key1:\n\tput_futex_key(&key1);\nout:\n\treturn ret ? ret : task_count;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'futex: Prevent overflow by strengthen input validation\n\nUBSAN reports signed integer overflow in kernel/futex.c:\n\n UBSAN: Undefined behaviour in kernel/futex.c:2041:18\n signed integer overflow:\n 0 - -2147483648 cannot be represented in type 'int'\n\nAdd a sanity check to catch negative values of nr_wake and nr_requeue.\n\nSigned-off-by: Li Jinyue \nSigned-off-by: Thomas Gleixner \nCc: peterz@infradead.org\nCc: dvhart@infradead.org\nCc: stable@vger.kernel.org\nLink: https://lkml.kernel.org/r/1513242294-31786-1-git-send-email-lijinyue@huawei.com'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: Header readHeader(BasicIo& io)\n {\n byte header[2];\n io.read(header, 2);\n\n ByteOrder byteOrder = invalidByteOrder;\n if (header[0] == 'I' && header[1] == 'I')\n byteOrder = littleEndian;\n else if (header[0] == 'M' && header[1] == 'M')\n byteOrder = bigEndian;\n\n if (byteOrder == invalidByteOrder)\n return Header();\n\n byte version[2];\n io.read(version, 2);\n\n const uint16_t magic = getUShort(version, byteOrder);\n\n if (magic != 0x2A && magic != 0x2B)\n return Header();\n\n Header result;\n\n if (magic == 0x2A)\n {\n byte buffer[4];\n io.read(buffer, 4);\n\n const uint32_t offset = getULong(buffer, byteOrder);\n result = Header(byteOrder, magic, 4, offset);\n }\n else\n {\n byte buffer[8];\n io.read(buffer, 2);\n const int size = getUShort(buffer, byteOrder);\n assert(size == 8);\n\n io.read(buffer, 2); // null\n\n io.read(buffer, 8);\n const uint64_t offset = getULongLong(buffer, byteOrder);\n\n result = Header(byteOrder, magic, size, offset);\n }\n\n return result;\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617'], 'message': 'fix for crash in bigtiff (issue #208)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: compute_O_value(std::string const& user_password,\n\t\tstd::string const& owner_password,\n\t\tQPDF::EncryptionData const& data)\n{\n // Algorithm 3.3 from the PDF 1.7 Reference Manual\n\n unsigned char O_key[OU_key_bytes_V4];\n compute_O_rc4_key(user_password, owner_password, data, O_key);\n\n char upass[key_bytes];\n pad_or_truncate_password_V4(user_password, upass);\n iterate_rc4(QUtil::unsigned_char_pointer(upass), key_bytes,\n\t\tO_key, data.getLengthBytes(),\n (data.getR() >= 3) ? 20 : 1, false);\n return std::string(upass, key_bytes);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Pad keys to avoid memory errors (fixes #147)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: QPDF::parse_xrefEntry(std::string const& line,\n qpdf_offset_t& f1, int& f2, char& type)\n{\n // is_space and is_digit both return false on '\\0', so this will\n // not overrun the null-terminated buffer.\n char const* p = line.c_str();\n\n // Skip zero or more spaces. There aren't supposed to be any.\n bool invalid = false;\n while (QUtil::is_space(*p))\n {\n ++p;\n QTC::TC(\"qpdf\", \"QPDF ignore first space in xref entry\");\n invalid = true;\n }\n // Require digit\n if (! QUtil::is_digit(*p))\n {\n return false;\n }\n // Gather digits\n std::string f1_str;\n while (QUtil::is_digit(*p))\n {\n f1_str.append(1, *p++);\n }\n // Require space\n if (! QUtil::is_space(*p))\n {\n return false;\n }\n if (QUtil::is_space(*(p+1)))\n {\n QTC::TC(\"qpdf\", \"QPDF ignore first extra space in xref entry\");\n invalid = true;\n }\n // Skip spaces\n while (QUtil::is_space(*p))\n {\n ++p;\n }\n // Require digit\n if (! QUtil::is_digit(*p))\n {\n return false;\n }\n // Gather digits\n std::string f2_str;\n while (QUtil::is_digit(*p))\n {\n f2_str.append(1, *p++);\n }\n // Require space\n if (! QUtil::is_space(*p))\n {\n return false;\n }\n if (QUtil::is_space(*(p+1)))\n {\n QTC::TC(\"qpdf\", \"QPDF ignore second extra space in xref entry\");\n invalid = true;\n }\n // Skip spaces\n while (QUtil::is_space(*p))\n {\n ++p;\n }\n if ((*p == 'f') || (*p == 'n'))\n {\n type = *p;\n }\n else\n {\n return false;\n }\n if ((f1_str.length() != 10) || (f2_str.length() != 5))\n {\n QTC::TC(\"qpdf\", \"QPDF ignore length error xref entry\");\n invalid = true;\n }\n\n if (invalid)\n {\n warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),\n \"xref table\",\n this->m->file->getLastOffset(),\n \"accepting invalid xref table entry\"));\n }\n\n f1 = QUtil::string_to_ll(f1_str.c_str());\n f2 = atoi(f2_str.c_str());\n\n return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Replace all atoi calls with QUtil::string_to_int\n\nThe latter catches underflow/overflow.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int ssl_parse_client_psk_identity( mbedtls_ssl_context *ssl, unsigned char **p,\n const unsigned char *end )\n{\n int ret = 0;\n size_t n;\n\n if( ssl->conf->f_psk == NULL &&\n ( ssl->conf->psk == NULL || ssl->conf->psk_identity == NULL ||\n ssl->conf->psk_identity_len == 0 || ssl->conf->psk_len == 0 ) )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"got no pre-shared key\" ) );\n return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );\n }\n\n /*\n * Receive client pre-shared key identity name\n */\n if( *p + 2 > end )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client key exchange message\" ) );\n return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );\n }\n\n n = ( (*p)[0] << 8 ) | (*p)[1];\n *p += 2;\n\n if( n < 1 || n > 65535 || *p + n > end )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client key exchange message\" ) );\n return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );\n }\n\n if( ssl->conf->f_psk != NULL )\n {\n if( ssl->conf->f_psk( ssl->conf->p_psk, ssl, *p, n ) != 0 )\n ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;\n }\n else\n {\n /* Identity is not a big secret since clients send it in the clear,\n * but treat it carefully anyway, just in case */\n if( n != ssl->conf->psk_identity_len ||\n mbedtls_ssl_safer_memcmp( ssl->conf->psk_identity, *p, n ) != 0 )\n {\n ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;\n }\n }\n\n if( ret == MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY )\n {\n MBEDTLS_SSL_DEBUG_BUF( 3, \"Unknown PSK identity\", *p, n );\n mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY );\n return( MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY );\n }\n\n *p += n;\n\n return( 0 );\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-190'], 'message': 'Prevent bounds check bypass through overflow in PSK identity parsing\n\nThe check `if( *p + n > end )` in `ssl_parse_client_psk_identity` is\nunsafe because `*p + n` might overflow, thus bypassing the check. As\n`n` is a user-specified value up to 65K, this is relevant if the\nlibrary happens to be located in the last 65K of virtual memory.\n\nThis commit replaces the check by a safe version.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: gplotMakeOutput(GPLOT *gplot)\n{\nchar buf[L_BUF_SIZE];\nchar *cmdname;\nl_int32 ignore;\n\n PROCNAME(\"gplotMakeOutput\");\n\n if (!gplot)\n return ERROR_INT(\"gplot not defined\", procName, 1);\n\n gplotGenCommandFile(gplot);\n gplotGenDataFiles(gplot);\n cmdname = genPathname(gplot->cmdname, NULL);\n\n#ifndef _WIN32\n snprintf(buf, L_BUF_SIZE, \"gnuplot %s\", cmdname);\n#else\n snprintf(buf, L_BUF_SIZE, \"wgnuplot %s\", cmdname);\n#endif /* _WIN32 */\n\n#ifndef OS_IOS /* iOS 11 does not support system() */\n ignore = system(buf); /* gnuplot || wgnuplot */\n#endif /* !OS_IOS */\n\n LEPT_FREE(cmdname);\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Security fixes: expect final changes for release 1.75.3.\n* Fixed a debian security issue with fscanf() reading a string with\n possible buffer overflow.\n* There were also a few similar situations with sscanf().'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void server_init(IRC_SERVER_REC *server)\n{\n\tIRC_SERVER_CONNECT_REC *conn;\n\tchar *address, *ptr, *username, *cmd;\n\tGTimeVal now;\n\n\tg_return_if_fail(server != NULL);\n\n\tconn = server->connrec;\n\n\tif (conn->proxy != NULL && conn->proxy_password != NULL &&\n\t *conn->proxy_password != '\\0') {\n\t\tcmd = g_strdup_printf(\"PASS %s\", conn->proxy_password);\n\t\tirc_send_cmd_now(server, cmd);\n\t\tg_free(cmd);\n\t}\n\n\tif (conn->proxy != NULL && conn->proxy_string != NULL) {\n\t\tcmd = g_strdup_printf(conn->proxy_string, conn->address, conn->port);\n\t\tirc_send_cmd_now(server, cmd);\n\t\tg_free(cmd);\n\t}\n\n\tirc_send_cmd_now(server, \"CAP LS\");\n\n\tif (conn->password != NULL && *conn->password != '\\0') {\n /* send password */\n\t\tcmd = g_strdup_printf(\"PASS %s\", conn->password);\n\t\tirc_send_cmd_now(server, cmd);\n\t\tg_free(cmd);\n\t}\n\n /* send nick */\n\tcmd = g_strdup_printf(\"NICK %s\", conn->nick);\n\tirc_send_cmd_now(server, cmd);\n\tg_free(cmd);\n\n\t/* send user/realname */\n\taddress = server->connrec->address;\n ptr = strrchr(address, ':');\n\tif (ptr != NULL) {\n\t\t/* IPv6 address .. doesn't work here, use the string after\n\t\t the last : char */\n\t\taddress = ptr+1;\n\t\tif (*address == '\\0')\n\t\t\taddress = \"x\";\n\t}\n\n\tusername = g_strdup(conn->username);\n\tptr = strchr(username, ' ');\n\tif (ptr != NULL) *ptr = '\\0';\n\n\tcmd = g_strdup_printf(\"USER %s %s %s :%s\", username, username, address, conn->realname);\n\tirc_send_cmd_now(server, cmd);\n\tg_free(cmd);\n\tg_free(username);\n\n\tif (conn->proxy != NULL && conn->proxy_string_after != NULL) {\n\t\tcmd = g_strdup_printf(conn->proxy_string_after, conn->address, conn->port);\n\t\tirc_send_cmd_now(server, cmd);\n\t\tg_free(cmd);\n\t}\n\n\tserver->isupport = g_hash_table_new((GHashFunc) g_istr_hash,\n\t\t\t\t\t (GCompareFunc) g_istr_equal);\n\n\t/* set the standards */\n\tg_hash_table_insert(server->isupport, g_strdup(\"CHANMODES\"), g_strdup(\"beI,k,l,imnpst\"));\n\tg_hash_table_insert(server->isupport, g_strdup(\"PREFIX\"), g_strdup(\"(ohv)@%+\"));\n\n\tserver->cmdcount = 0;\n\n\t/* prevent the queue from sending too early, we have a max cut off of 120 secs */\n\t/* this will reset to 1 sec after we get the 001 event */\n\tg_get_current_time(&now);\n\tmemcpy(&((IRC_SERVER_REC *)server)->wait_cmd, &now, sizeof(GTimeVal));\n\t((IRC_SERVER_REC *)server)->wait_cmd.tv_sec += 120;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'SASL support\n\nThe only supported methods are PLAIN and EXTERNAL, the latter is untested as of\nnow.\nThe code gets the values from the keys named sasl_{mechanism,username,password}\nspecified for each chatnet.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void sasl_step_fail(IRC_SERVER_REC *server)\n{\n\tirc_send_cmd_now(server, \"AUTHENTICATE *\");\n\tcap_finish_negotiation(server);\n\n\tserver->sasl_timeout = 0;\n\n\tsignal_emit(\"server sasl failure\", 2, server, \"The server sent an invalid payload\");\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Merge branch 'security' into 'master'\n\nSecurity\n\nSee merge request irssi/irssi!34\n\n(cherry picked from commit b0d9cb33cd9ef9da7c331409e8b7c57a6f3aef3f)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: pixHtmlViewer(const char *dirin,\n const char *dirout,\n const char *rootname,\n l_int32 thumbwidth,\n l_int32 viewwidth)\n{\nchar *fname, *fullname, *outname;\nchar *mainname, *linkname, *linknameshort;\nchar *viewfile, *thumbfile;\nchar *shtml, *slink;\nchar charbuf[512];\nchar htmlstring[] = \"\";\nchar framestring[] = \"\";\nl_int32 i, nfiles, index, w, d, nimages, ret;\nl_float32 factor;\nPIX *pix, *pixthumb, *pixview;\nSARRAY *safiles, *sathumbs, *saviews, *sahtml, *salink;\n\n PROCNAME(\"pixHtmlViewer\");\n\n if (!dirin)\n return ERROR_INT(\"dirin not defined\", procName, 1);\n if (!dirout)\n return ERROR_INT(\"dirout not defined\", procName, 1);\n if (!rootname)\n return ERROR_INT(\"rootname not defined\", procName, 1);\n\n if (thumbwidth == 0)\n thumbwidth = DEFAULT_THUMB_WIDTH;\n if (thumbwidth < MIN_THUMB_WIDTH) {\n L_WARNING(\"thumbwidth too small; using min value\\n\", procName);\n thumbwidth = MIN_THUMB_WIDTH;\n }\n if (viewwidth == 0)\n viewwidth = DEFAULT_VIEW_WIDTH;\n if (viewwidth < MIN_VIEW_WIDTH) {\n L_WARNING(\"viewwidth too small; using min value\\n\", procName);\n viewwidth = MIN_VIEW_WIDTH;\n }\n\n /* Make the output directory if it doesn't already exist */\n#ifndef _WIN32\n snprintf(charbuf, sizeof(charbuf), \"mkdir -p %s\", dirout);\n ret = system(charbuf);\n#else\n ret = CreateDirectory(dirout, NULL) ? 0 : 1;\n#endif /* !_WIN32 */\n if (ret) {\n L_ERROR(\"output directory %s not made\\n\", procName, dirout);\n return 1;\n }\n\n /* Capture the filenames in the input directory */\n if ((safiles = getFilenamesInDirectory(dirin)) == NULL)\n return ERROR_INT(\"safiles not made\", procName, 1);\n\n /* Generate output text file names */\n sprintf(charbuf, \"%s/%s.html\", dirout, rootname);\n mainname = stringNew(charbuf);\n sprintf(charbuf, \"%s/%s-links.html\", dirout, rootname);\n linkname = stringNew(charbuf);\n linknameshort = stringJoin(rootname, \"-links.html\");\n\n /* Generate the thumbs and views */\n sathumbs = sarrayCreate(0);\n saviews = sarrayCreate(0);\n nfiles = sarrayGetCount(safiles);\n index = 0;\n for (i = 0; i < nfiles; i++) {\n fname = sarrayGetString(safiles, i, L_NOCOPY);\n fullname = genPathname(dirin, fname);\n fprintf(stderr, \"name: %s\\n\", fullname);\n if ((pix = pixRead(fullname)) == NULL) {\n fprintf(stderr, \"file %s not a readable image\\n\", fullname);\n lept_free(fullname);\n continue;\n }\n lept_free(fullname);\n\n /* Make and store the thumbnail images */\n pixGetDimensions(pix, &w, NULL, &d);\n factor = (l_float32)thumbwidth / (l_float32)w;\n pixthumb = pixScale(pix, factor, factor);\n sprintf(charbuf, \"%s_thumb_%03d\", rootname, index);\n sarrayAddString(sathumbs, charbuf, L_COPY);\n outname = genPathname(dirout, charbuf);\n WriteFormattedPix(outname, pixthumb);\n lept_free(outname);\n pixDestroy(&pixthumb);\n\n /* Make and store the view images */\n factor = (l_float32)viewwidth / (l_float32)w;\n if (factor >= 1.0)\n pixview = pixClone(pix); /* no upscaling */\n else\n pixview = pixScale(pix, factor, factor);\n snprintf(charbuf, sizeof(charbuf), \"%s_view_%03d\", rootname, index);\n sarrayAddString(saviews, charbuf, L_COPY);\n outname = genPathname(dirout, charbuf);\n WriteFormattedPix(outname, pixview);\n lept_free(outname);\n pixDestroy(&pixview);\n pixDestroy(&pix);\n index++;\n }\n\n /* Generate the main html file */\n sahtml = sarrayCreate(0);\n sarrayAddString(sahtml, htmlstring, L_COPY);\n sprintf(charbuf, \"\", thumbwidth + 30);\n sarrayAddString(sahtml, charbuf, L_COPY);\n sprintf(charbuf, \"\", linknameshort);\n sarrayAddString(sahtml, charbuf, L_COPY);\n sprintf(charbuf, \"\",\n sarrayGetString(saviews, 0, L_NOCOPY));\n sarrayAddString(sahtml, charbuf, L_COPY);\n sarrayAddString(sahtml, framestring, L_COPY);\n shtml = sarrayToString(sahtml, 1);\n l_binaryWrite(mainname, \"w\", shtml, strlen(shtml));\n fprintf(stderr, \"******************************************\\n\"\n \"Writing html file: %s\\n\"\n \"******************************************\\n\", mainname);\n lept_free(shtml);\n lept_free(mainname);\n\n /* Generate the link html file */\n nimages = sarrayGetCount(saviews);\n fprintf(stderr, \"num. images = %d\\n\", nimages);\n salink = sarrayCreate(0);\n for (i = 0; i < nimages; i++) {\n viewfile = sarrayGetString(saviews, i, L_NOCOPY);\n thumbfile = sarrayGetString(sathumbs, i, L_NOCOPY);\n sprintf(charbuf, \"\",\n viewfile, thumbfile);\n sarrayAddString(salink, charbuf, L_COPY);\n }\n slink = sarrayToString(salink, 1);\n l_binaryWrite(linkname, \"w\", slink, strlen(slink));\n lept_free(slink);\n lept_free(linkname);\n lept_free(linknameshort);\n sarrayDestroy(&safiles);\n sarrayDestroy(&sathumbs);\n sarrayDestroy(&saviews);\n sarrayDestroy(&sahtml);\n sarrayDestroy(&salink);\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'prog/htmlviewer: Catch unbound memory access (CID 1386222)\n\nrootname can have any size, so limit the amount of copied bytes.\n\nSigned-off-by: Stefan Weil '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int get_v4l2_window32(struct v4l2_window *kp, struct v4l2_window32 __user *up)\n{\n\tstruct v4l2_clip32 __user *uclips;\n\tstruct v4l2_clip __user *kclips;\n\tcompat_caddr_t p;\n\tu32 n;\n\n\tif (!access_ok(VERIFY_READ, up, sizeof(*up)) ||\n\t copy_from_user(&kp->w, &up->w, sizeof(up->w)) ||\n\t get_user(kp->field, &up->field) ||\n\t get_user(kp->chromakey, &up->chromakey) ||\n\t get_user(kp->clipcount, &up->clipcount) ||\n\t get_user(kp->global_alpha, &up->global_alpha))\n\t\treturn -EFAULT;\n\tif (kp->clipcount > 2048)\n\t\treturn -EINVAL;\n\tif (!kp->clipcount) {\n\t\tkp->clips = NULL;\n\t\treturn 0;\n\t}\n\n\tn = kp->clipcount;\n\tif (get_user(p, &up->clips))\n\t\treturn -EFAULT;\n\tuclips = compat_ptr(p);\n\tkclips = compat_alloc_user_space(n * sizeof(*kclips));\n\tkp->clips = kclips;\n\twhile (n--) {\n\t\tif (copy_in_user(&kclips->c, &uclips->c, sizeof(uclips->c)))\n\t\t\treturn -EFAULT;\n\t\tif (put_user(n ? kclips + 1 : NULL, &kclips->next))\n\t\t\treturn -EFAULT;\n\t\tuclips++;\n\t\tkclips++;\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'media: v4l2-compat-ioctl32.c: refactor compat ioctl32 logic\n\nThe 32-bit compat v4l2 ioctl handling is implemented based on its 64-bit\nequivalent. It converts 32-bit data structures into its 64-bit\nequivalents and needs to provide the data to the 64-bit ioctl in user\nspace memory which is commonly allocated using\ncompat_alloc_user_space().\n\nHowever, due to how that function is implemented, it can only be called\na single time for every syscall invocation.\n\nSupposedly to avoid this limitation, the existing code uses a mix of\nmemory from the kernel stack and memory allocated through\ncompat_alloc_user_space().\n\nUnder normal circumstances, this would not work, because the 64-bit\nioctl expects all pointers to point to user space memory. As a\nworkaround, set_fs(KERNEL_DS) is called to temporarily disable this\nextra safety check and allow kernel pointers. However, this might\nintroduce a security vulnerability: The result of the 32-bit to 64-bit\nconversion is writeable by user space because the output buffer has been\nallocated via compat_alloc_user_space(). A malicious user space process\ncould then manipulate pointers inside this output buffer, and due to the\nprevious set_fs(KERNEL_DS) call, functions like get_user() or put_user()\nno longer prevent kernel memory access.\n\nThe new approach is to pre-calculate the total amount of user space\nmemory that is needed, allocate it using compat_alloc_user_space() and\nthen divide up the allocated memory to accommodate all data structures\nthat need to be converted.\n\nAn alternative approach would have been to retain the union type karg\nthat they allocated on the kernel stack in do_video_ioctl(), copy all\ndata from user space into karg and then back to user space. However, we\ndecided against this approach because it does not align with other\ncompat syscall implementations. Instead, we tried to replicate the\nget_user/put_user pairs as found in other places in the kernel:\n\n if (get_user(clipcount, &up->clipcount) ||\n put_user(clipcount, &kp->clipcount)) return -EFAULT;\n\nNotes from hans.verkuil@cisco.com:\n\nThis patch was taken from:\n https://github.com/LineageOS/android_kernel_samsung_apq8084/commit/97b733953c06e4f0398ade18850f0817778255f7\n\nClearly nobody could be bothered to upstream this patch or at minimum\ntell us :-( We only heard about this a week ago.\n\nThis patch was rebased and cleaned up. Compared to the original I\nalso swapped the order of the convert_in_user arguments so that they\nmatched copy_in_user. It was hard to review otherwise. I also replaced\nthe ALLOC_USER_SPACE/ALLOC_AND_GET by a normal function.\n\nFixes: 6b5a9492ca (\"v4l: introduce string control support.\")\n\nSigned-off-by: Daniel Mentz \nCo-developed-by: Hans Verkuil \nAcked-by: Sakari Ailus \nSigned-off-by: Hans Verkuil \nCc: # for v4.15 and up\nSigned-off-by: Mauro Carvalho Chehab '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int put_v4l2_ext_controls32(struct file *file,\n\t\t\t\t struct v4l2_ext_controls *kp,\n\t\t\t\t struct v4l2_ext_controls32 __user *up)\n{\n\tstruct v4l2_ext_control32 __user *ucontrols;\n\tstruct v4l2_ext_control __user *kcontrols =\n\t\t(__force struct v4l2_ext_control __user *)kp->controls;\n\tint n = kp->count;\n\tcompat_caddr_t p;\n\n\tif (!access_ok(VERIFY_WRITE, up, sizeof(*up)) ||\n\t put_user(kp->which, &up->which) ||\n\t put_user(kp->count, &up->count) ||\n\t put_user(kp->error_idx, &up->error_idx) ||\n\t copy_to_user(up->reserved, kp->reserved, sizeof(up->reserved)))\n\t\treturn -EFAULT;\n\tif (!kp->count)\n\t\treturn 0;\n\n\tif (get_user(p, &up->controls))\n\t\treturn -EFAULT;\n\tucontrols = compat_ptr(p);\n\tif (!access_ok(VERIFY_WRITE, ucontrols, n * sizeof(*ucontrols)))\n\t\treturn -EFAULT;\n\n\twhile (--n >= 0) {\n\t\tunsigned size = sizeof(*ucontrols);\n\t\tu32 id;\n\n\t\tif (get_user(id, &kcontrols->id))\n\t\t\treturn -EFAULT;\n\t\t/* Do not modify the pointer when copying a pointer control.\n\t\t The contents of the pointer was changed, not the pointer\n\t\t itself. */\n\t\tif (ctrl_is_pointer(file, id))\n\t\t\tsize -= sizeof(ucontrols->value64);\n\t\tif (copy_in_user(ucontrols, kcontrols, size))\n\t\t\treturn -EFAULT;\n\t\tucontrols++;\n\t\tkcontrols++;\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'media: v4l2-compat-ioctl32.c: refactor compat ioctl32 logic\n\nThe 32-bit compat v4l2 ioctl handling is implemented based on its 64-bit\nequivalent. It converts 32-bit data structures into its 64-bit\nequivalents and needs to provide the data to the 64-bit ioctl in user\nspace memory which is commonly allocated using\ncompat_alloc_user_space().\n\nHowever, due to how that function is implemented, it can only be called\na single time for every syscall invocation.\n\nSupposedly to avoid this limitation, the existing code uses a mix of\nmemory from the kernel stack and memory allocated through\ncompat_alloc_user_space().\n\nUnder normal circumstances, this would not work, because the 64-bit\nioctl expects all pointers to point to user space memory. As a\nworkaround, set_fs(KERNEL_DS) is called to temporarily disable this\nextra safety check and allow kernel pointers. However, this might\nintroduce a security vulnerability: The result of the 32-bit to 64-bit\nconversion is writeable by user space because the output buffer has been\nallocated via compat_alloc_user_space(). A malicious user space process\ncould then manipulate pointers inside this output buffer, and due to the\nprevious set_fs(KERNEL_DS) call, functions like get_user() or put_user()\nno longer prevent kernel memory access.\n\nThe new approach is to pre-calculate the total amount of user space\nmemory that is needed, allocate it using compat_alloc_user_space() and\nthen divide up the allocated memory to accommodate all data structures\nthat need to be converted.\n\nAn alternative approach would have been to retain the union type karg\nthat they allocated on the kernel stack in do_video_ioctl(), copy all\ndata from user space into karg and then back to user space. However, we\ndecided against this approach because it does not align with other\ncompat syscall implementations. Instead, we tried to replicate the\nget_user/put_user pairs as found in other places in the kernel:\n\n if (get_user(clipcount, &up->clipcount) ||\n put_user(clipcount, &kp->clipcount)) return -EFAULT;\n\nNotes from hans.verkuil@cisco.com:\n\nThis patch was taken from:\n https://github.com/LineageOS/android_kernel_samsung_apq8084/commit/97b733953c06e4f0398ade18850f0817778255f7\n\nClearly nobody could be bothered to upstream this patch or at minimum\ntell us :-( We only heard about this a week ago.\n\nThis patch was rebased and cleaned up. Compared to the original I\nalso swapped the order of the convert_in_user arguments so that they\nmatched copy_in_user. It was hard to review otherwise. I also replaced\nthe ALLOC_USER_SPACE/ALLOC_AND_GET by a normal function.\n\nFixes: 6b5a9492ca (\"v4l: introduce string control support.\")\n\nSigned-off-by: Daniel Mentz \nCo-developed-by: Hans Verkuil \nAcked-by: Sakari Ailus \nSigned-off-by: Hans Verkuil \nCc: # for v4.15 and up\nSigned-off-by: Mauro Carvalho Chehab '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int get_v4l2_plane32(struct v4l2_plane __user *up, struct v4l2_plane32 __user *up32,\n\t\t\t enum v4l2_memory memory)\n{\n\tvoid __user *up_pln;\n\tcompat_long_t p;\n\n\tif (copy_in_user(up, up32, 2 * sizeof(__u32)) ||\n\t copy_in_user(&up->data_offset, &up32->data_offset,\n\t\t\t sizeof(up->data_offset)))\n\t\treturn -EFAULT;\n\n\tswitch (memory) {\n\tcase V4L2_MEMORY_MMAP:\n\tcase V4L2_MEMORY_OVERLAY:\n\t\tif (copy_in_user(&up->m.mem_offset, &up32->m.mem_offset,\n\t\t\t\t sizeof(up32->m.mem_offset)))\n\t\t\treturn -EFAULT;\n\t\tbreak;\n\tcase V4L2_MEMORY_USERPTR:\n\t\tif (get_user(p, &up32->m.userptr))\n\t\t\treturn -EFAULT;\n\t\tup_pln = compat_ptr(p);\n\t\tif (put_user((unsigned long)up_pln, &up->m.userptr))\n\t\t\treturn -EFAULT;\n\t\tbreak;\n\tcase V4L2_MEMORY_DMABUF:\n\t\tif (copy_in_user(&up->m.fd, &up32->m.fd, sizeof(up32->m.fd)))\n\t\t\treturn -EFAULT;\n\t\tbreak;\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'media: v4l2-compat-ioctl32.c: refactor compat ioctl32 logic\n\nThe 32-bit compat v4l2 ioctl handling is implemented based on its 64-bit\nequivalent. It converts 32-bit data structures into its 64-bit\nequivalents and needs to provide the data to the 64-bit ioctl in user\nspace memory which is commonly allocated using\ncompat_alloc_user_space().\n\nHowever, due to how that function is implemented, it can only be called\na single time for every syscall invocation.\n\nSupposedly to avoid this limitation, the existing code uses a mix of\nmemory from the kernel stack and memory allocated through\ncompat_alloc_user_space().\n\nUnder normal circumstances, this would not work, because the 64-bit\nioctl expects all pointers to point to user space memory. As a\nworkaround, set_fs(KERNEL_DS) is called to temporarily disable this\nextra safety check and allow kernel pointers. However, this might\nintroduce a security vulnerability: The result of the 32-bit to 64-bit\nconversion is writeable by user space because the output buffer has been\nallocated via compat_alloc_user_space(). A malicious user space process\ncould then manipulate pointers inside this output buffer, and due to the\nprevious set_fs(KERNEL_DS) call, functions like get_user() or put_user()\nno longer prevent kernel memory access.\n\nThe new approach is to pre-calculate the total amount of user space\nmemory that is needed, allocate it using compat_alloc_user_space() and\nthen divide up the allocated memory to accommodate all data structures\nthat need to be converted.\n\nAn alternative approach would have been to retain the union type karg\nthat they allocated on the kernel stack in do_video_ioctl(), copy all\ndata from user space into karg and then back to user space. However, we\ndecided against this approach because it does not align with other\ncompat syscall implementations. Instead, we tried to replicate the\nget_user/put_user pairs as found in other places in the kernel:\n\n if (get_user(clipcount, &up->clipcount) ||\n put_user(clipcount, &kp->clipcount)) return -EFAULT;\n\nNotes from hans.verkuil@cisco.com:\n\nThis patch was taken from:\n https://github.com/LineageOS/android_kernel_samsung_apq8084/commit/97b733953c06e4f0398ade18850f0817778255f7\n\nClearly nobody could be bothered to upstream this patch or at minimum\ntell us :-( We only heard about this a week ago.\n\nThis patch was rebased and cleaned up. Compared to the original I\nalso swapped the order of the convert_in_user arguments so that they\nmatched copy_in_user. It was hard to review otherwise. I also replaced\nthe ALLOC_USER_SPACE/ALLOC_AND_GET by a normal function.\n\nFixes: 6b5a9492ca (\"v4l: introduce string control support.\")\n\nSigned-off-by: Daniel Mentz \nCo-developed-by: Hans Verkuil \nAcked-by: Sakari Ailus \nSigned-off-by: Hans Verkuil \nCc: # for v4.15 and up\nSigned-off-by: Mauro Carvalho Chehab '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int f2fs_trim_fs(struct f2fs_sb_info *sbi, struct fstrim_range *range)\n{\n\t__u64 start = F2FS_BYTES_TO_BLK(range->start);\n\t__u64 end = start + F2FS_BYTES_TO_BLK(range->len) - 1;\n\tunsigned int start_segno, end_segno;\n\tstruct cp_control cpc;\n\tint err = 0;\n\n\tif (start >= MAX_BLKADDR(sbi) || range->len < sbi->blocksize)\n\t\treturn -EINVAL;\n\n\tcpc.trimmed = 0;\n\tif (end <= MAIN_BLKADDR(sbi))\n\t\tgoto out;\n\n\tif (is_sbi_flag_set(sbi, SBI_NEED_FSCK)) {\n\t\tf2fs_msg(sbi->sb, KERN_WARNING,\n\t\t\t\"Found FS corruption, run fsck to fix.\");\n\t\tgoto out;\n\t}\n\n\t/* start/end segment number in main_area */\n\tstart_segno = (start <= MAIN_BLKADDR(sbi)) ? 0 : GET_SEGNO(sbi, start);\n\tend_segno = (end >= MAX_BLKADDR(sbi)) ? MAIN_SEGS(sbi) - 1 :\n\t\t\t\t\t\tGET_SEGNO(sbi, end);\n\tcpc.reason = CP_DISCARD;\n\tcpc.trim_minlen = max_t(__u64, 1, F2FS_BYTES_TO_BLK(range->minlen));\n\n\t/* do checkpoint to issue discard commands safely */\n\tfor (; start_segno <= end_segno; start_segno = cpc.trim_end + 1) {\n\t\tcpc.trim_start = start_segno;\n\n\t\tif (sbi->discard_blks == 0)\n\t\t\tbreak;\n\t\telse if (sbi->discard_blks < BATCHED_TRIM_BLOCKS(sbi))\n\t\t\tcpc.trim_end = end_segno;\n\t\telse\n\t\t\tcpc.trim_end = min_t(unsigned int,\n\t\t\t\trounddown(start_segno +\n\t\t\t\tBATCHED_TRIM_SEGMENTS(sbi),\n\t\t\t\tsbi->segs_per_sec) - 1, end_segno);\n\n\t\tmutex_lock(&sbi->gc_mutex);\n\t\terr = write_checkpoint(sbi, &cpc);\n\t\tmutex_unlock(&sbi->gc_mutex);\n\t\tif (err)\n\t\t\tbreak;\n\n\t\tschedule();\n\t}\n\t/* It's time to issue all the filed discards */\n\tmark_discard_range_all(sbi);\n\tf2fs_wait_discard_bios(sbi);\nout:\n\trange->len = F2FS_BLK_TO_BYTES(cpc.trimmed);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'f2fs: fix potential panic during fstrim\n\nAs Ju Hyung Park reported:\n\n\"When 'fstrim' is called for manual trim, a BUG() can be triggered\nrandomly with this patch.\n\nI'm seeing this issue on both x86 Desktop and arm64 Android phone.\n\nOn x86 Desktop, this was caused during Ubuntu boot-up. I have a\ncronjob installed which calls 'fstrim -v /' during boot. On arm64\nAndroid, this was caused during GC looping with 1ms gc_min_sleep_time\n& gc_max_sleep_time.\"\n\nRoot cause of this issue is that f2fs_wait_discard_bios can only be\nused by f2fs_put_super, because during put_super there must be no\nother referrers, so it can ignore discard entry's reference count\nwhen removing the entry, otherwise in other caller we will hit bug_on\nin __remove_discard_cmd as there may be other issuer added reference\ncount in discard entry.\n\nThread A\t\t\t\tThread B\n\t\t\t\t\t- issue_discard_thread\n- f2fs_ioc_fitrim\n - f2fs_trim_fs\n - f2fs_wait_discard_bios\n - __issue_discard_cmd\n - __submit_discard_cmd\n\t\t\t\t\t - __wait_discard_cmd\n\t\t\t\t\t - dc->ref++\n\t\t\t\t\t - __wait_one_discard_bio\n - __wait_discard_cmd\n - __remove_discard_cmd\n - f2fs_bug_on(sbi, dc->ref)\n\nFixes: 969d1b180d987c2be02de890d0fff0f66a0e80de\nReported-by: Ju Hyung Park \nSigned-off-by: Chao Yu \nSigned-off-by: Jaegeuk Kim '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static struct sctp_chunk *_sctp_make_chunk(const struct sctp_association *asoc,\n\t\t\t\t\t __u8 type, __u8 flags, int paylen,\n\t\t\t\t\t gfp_t gfp)\n{\n\tstruct sctp_chunkhdr *chunk_hdr;\n\tstruct sctp_chunk *retval;\n\tstruct sk_buff *skb;\n\tstruct sock *sk;\n\n\t/* No need to allocate LL here, as this is only a chunk. */\n\tskb = alloc_skb(SCTP_PAD4(sizeof(*chunk_hdr) + paylen), gfp);\n\tif (!skb)\n\t\tgoto nodata;\n\n\t/* Make room for the chunk header. */\n\tchunk_hdr = (struct sctp_chunkhdr *)skb_put(skb, sizeof(*chunk_hdr));\n\tchunk_hdr->type\t = type;\n\tchunk_hdr->flags = flags;\n\tchunk_hdr->length = htons(sizeof(*chunk_hdr));\n\n\tsk = asoc ? asoc->base.sk : NULL;\n\tretval = sctp_chunkify(skb, asoc, sk, gfp);\n\tif (!retval) {\n\t\tkfree_skb(skb);\n\t\tgoto nodata;\n\t}\n\n\tretval->chunk_hdr = chunk_hdr;\n\tretval->chunk_end = ((__u8 *)chunk_hdr) + sizeof(*chunk_hdr);\n\n\t/* Determine if the chunk needs to be authenticated */\n\tif (sctp_auth_send_cid(type, asoc))\n\t\tretval->auth = 1;\n\n\treturn retval;\nnodata:\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'sctp: verify size of a new chunk in _sctp_make_chunk()\n\nWhen SCTP makes INIT or INIT_ACK packet the total chunk length\ncan exceed SCTP_MAX_CHUNK_LEN which leads to kernel panic when\ntransmitting these packets, e.g. the crash on sending INIT_ACK:\n\n[ 597.804948] skbuff: skb_over_panic: text:00000000ffae06e4 len:120168\n put:120156 head:000000007aa47635 data:00000000d991c2de\n tail:0x1d640 end:0xfec0 dev:\n...\n[ 597.976970] ------------[ cut here ]------------\n[ 598.033408] kernel BUG at net/core/skbuff.c:104!\n[ 600.314841] Call Trace:\n[ 600.345829] \n[ 600.371639] ? sctp_packet_transmit+0x2095/0x26d0 [sctp]\n[ 600.436934] skb_put+0x16c/0x200\n[ 600.477295] sctp_packet_transmit+0x2095/0x26d0 [sctp]\n[ 600.540630] ? sctp_packet_config+0x890/0x890 [sctp]\n[ 600.601781] ? __sctp_packet_append_chunk+0x3b4/0xd00 [sctp]\n[ 600.671356] ? sctp_cmp_addr_exact+0x3f/0x90 [sctp]\n[ 600.731482] sctp_outq_flush+0x663/0x30d0 [sctp]\n[ 600.788565] ? sctp_make_init+0xbf0/0xbf0 [sctp]\n[ 600.845555] ? sctp_check_transmitted+0x18f0/0x18f0 [sctp]\n[ 600.912945] ? sctp_outq_tail+0x631/0x9d0 [sctp]\n[ 600.969936] sctp_cmd_interpreter.isra.22+0x3be1/0x5cb0 [sctp]\n[ 601.041593] ? sctp_sf_do_5_1B_init+0x85f/0xc30 [sctp]\n[ 601.104837] ? sctp_generate_t1_cookie_event+0x20/0x20 [sctp]\n[ 601.175436] ? sctp_eat_data+0x1710/0x1710 [sctp]\n[ 601.233575] sctp_do_sm+0x182/0x560 [sctp]\n[ 601.284328] ? sctp_has_association+0x70/0x70 [sctp]\n[ 601.345586] ? sctp_rcv+0xef4/0x32f0 [sctp]\n[ 601.397478] ? sctp6_rcv+0xa/0x20 [sctp]\n...\n\nHere the chunk size for INIT_ACK packet becomes too big, mostly\nbecause of the state cookie (INIT packet has large size with\nmany address parameters), plus additional server parameters.\n\nLater this chunk causes the panic in skb_put_data():\n\n skb_packet_transmit()\n sctp_packet_pack()\n skb_put_data(nskb, chunk->skb->data, chunk->skb->len);\n\n'nskb' (head skb) was previously allocated with packet->size\nfrom u16 'chunk->chunk_hdr->length'.\n\nAs suggested by Marcelo we should check the chunk's length in\n_sctp_make_chunk() before trying to allocate skb for it and\ndiscard a chunk if its size bigger than SCTP_MAX_CHUNK_LEN.\n\nSigned-off-by: Alexey Kodanev \nAcked-by: Marcelo Ricardo Leitner \nAcked-by: Neil Horman \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static ssize_t o2nm_node_local_store(struct config_item *item, const char *page,\n\t\t\t\t size_t count)\n{\n\tstruct o2nm_node *node = to_o2nm_node(item);\n\tstruct o2nm_cluster *cluster = to_o2nm_cluster_from_node(node);\n\tunsigned long tmp;\n\tchar *p = (char *)page;\n\tssize_t ret;\n\n\ttmp = simple_strtoul(p, &p, 0);\n\tif (!p || (*p && (*p != '\\n')))\n\t\treturn -EINVAL;\n\n\ttmp = !!tmp; /* boolean of whether this node wants to be local */\n\n\t/* setting local turns on networking rx for now so we require having\n\t * set everything else first */\n\tif (!test_bit(O2NM_NODE_ATTR_ADDRESS, &node->nd_set_attributes) ||\n\t !test_bit(O2NM_NODE_ATTR_NUM, &node->nd_set_attributes) ||\n\t !test_bit(O2NM_NODE_ATTR_PORT, &node->nd_set_attributes))\n\t\treturn -EINVAL; /* XXX */\n\n\t/* the only failure case is trying to set a new local node\n\t * when a different one is already set */\n\tif (tmp && tmp == cluster->cl_has_local &&\n\t cluster->cl_local_node != node->nd_num)\n\t\treturn -EBUSY;\n\n\t/* bring up the rx thread if we're setting the new local node. */\n\tif (tmp && !cluster->cl_has_local) {\n\t\tret = o2net_start_listening(node);\n\t\tif (ret)\n\t\t\treturn ret;\n\t}\n\n\tif (!tmp && cluster->cl_has_local &&\n\t cluster->cl_local_node == node->nd_num) {\n\t\to2net_stop_listening(node);\n\t\tcluster->cl_local_node = O2NM_INVALID_NODE_NUM;\n\t}\n\n\tnode->nd_local = tmp;\n\tif (node->nd_local) {\n\t\tcluster->cl_has_local = tmp;\n\t\tcluster->cl_local_node = node->nd_num;\n\t}\n\n\treturn count;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-284'], 'message': 'ocfs2: subsystem.su_mutex is required while accessing the item->ci_parent\n\nThe subsystem.su_mutex is required while accessing the item->ci_parent,\notherwise, NULL pointer dereference to the item->ci_parent will be\ntriggered in the following situation:\n\nadd node delete node\nsys_write\n vfs_write\n configfs_write_file\n o2nm_node_store\n o2nm_node_local_write\n do_rmdir\n vfs_rmdir\n configfs_rmdir\n mutex_lock(&subsys->su_mutex);\n unlink_obj\n item->ci_group = NULL;\n item->ci_parent = NULL;\n\t to_o2nm_cluster_from_node\n\t node->nd_item.ci_parent->ci_parent\n\t BUG since of NULL pointer dereference to nd_item.ci_parent\n\nMoreover, the o2nm_cluster also should be protected by the\nsubsystem.su_mutex.\n\n[alex.chen@huawei.com: v2]\n Link: http://lkml.kernel.org/r/59EEAA69.9080703@huawei.com\nLink: http://lkml.kernel.org/r/59E9B36A.10700@huawei.com\nSigned-off-by: Alex Chen \nReviewed-by: Jun Piao \nReviewed-by: Joseph Qi \nCc: Mark Fasheh \nCc: Joel Becker \nCc: Junxiao Bi \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int sas_smp_get_phy_events(struct sas_phy *phy)\n{\n\tint res;\n\tu8 *req;\n\tu8 *resp;\n\tstruct sas_rphy *rphy = dev_to_rphy(phy->dev.parent);\n\tstruct domain_device *dev = sas_find_dev_by_rphy(rphy);\n\n\treq = alloc_smp_req(RPEL_REQ_SIZE);\n\tif (!req)\n\t\treturn -ENOMEM;\n\n\tresp = alloc_smp_resp(RPEL_RESP_SIZE);\n\tif (!resp) {\n\t\tkfree(req);\n\t\treturn -ENOMEM;\n\t}\n\n\treq[1] = SMP_REPORT_PHY_ERR_LOG;\n\treq[9] = phy->number;\n\n\tres = smp_execute_task(dev, req, RPEL_REQ_SIZE,\n\t\t\t resp, RPEL_RESP_SIZE);\n\n\tif (!res)\n\t\tgoto out;\n\n\tphy->invalid_dword_count = scsi_to_u32(&resp[12]);\n\tphy->running_disparity_error_count = scsi_to_u32(&resp[16]);\n\tphy->loss_of_dword_sync_count = scsi_to_u32(&resp[20]);\n\tphy->phy_reset_problem_count = scsi_to_u32(&resp[24]);\n\n out:\n\tkfree(resp);\n\treturn res;\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-772'], 'message': 'scsi: libsas: fix memory leak in sas_smp_get_phy_events()\n\nWe've got a memory leak with the following producer:\n\nwhile true;\ndo cat /sys/class/sas_phy/phy-1:0:12/invalid_dword_count >/dev/null;\ndone\n\nThe buffer req is allocated and not freed after we return. Fix it.\n\nFixes: 2908d778ab3e (\"[SCSI] aic94xx: new driver\")\nSigned-off-by: Jason Yan \nCC: John Garry \nCC: chenqilin \nCC: chenxiang \nReviewed-by: Christoph Hellwig \nReviewed-by: Hannes Reinecke \nSigned-off-by: Martin K. Petersen '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int read_entry(\n\tgit_index_entry **out,\n\tsize_t *out_size,\n\tgit_index *index,\n\tconst void *buffer,\n\tsize_t buffer_size,\n\tconst char *last)\n{\n\tsize_t path_length, entry_size;\n\tconst char *path_ptr;\n\tstruct entry_short source;\n\tgit_index_entry entry = {{0}};\n\tbool compressed = index->version >= INDEX_VERSION_NUMBER_COMP;\n\tchar *tmp_path = NULL;\n\n\tif (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size)\n\t\treturn -1;\n\n\t/* buffer is not guaranteed to be aligned */\n\tmemcpy(&source, buffer, sizeof(struct entry_short));\n\n\tentry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds);\n\tentry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds);\n\tentry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds);\n\tentry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds);\n\tentry.dev = ntohl(source.dev);\n\tentry.ino = ntohl(source.ino);\n\tentry.mode = ntohl(source.mode);\n\tentry.uid = ntohl(source.uid);\n\tentry.gid = ntohl(source.gid);\n\tentry.file_size = ntohl(source.file_size);\n\tgit_oid_cpy(&entry.id, &source.oid);\n\tentry.flags = ntohs(source.flags);\n\n\tif (entry.flags & GIT_IDXENTRY_EXTENDED) {\n\t\tuint16_t flags_raw;\n\t\tsize_t flags_offset;\n\n\t\tflags_offset = offsetof(struct entry_long, flags_extended);\n\t\tmemcpy(&flags_raw, (const char *) buffer + flags_offset,\n\t\t\tsizeof(flags_raw));\n\t\tflags_raw = ntohs(flags_raw);\n\n\t\tmemcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw));\n\t\tpath_ptr = (const char *) buffer + offsetof(struct entry_long, path);\n\t} else\n\t\tpath_ptr = (const char *) buffer + offsetof(struct entry_short, path);\n\n\tif (!compressed) {\n\t\tpath_length = entry.flags & GIT_IDXENTRY_NAMEMASK;\n\n\t\t/* if this is a very long string, we must find its\n\t\t * real length without overflowing */\n\t\tif (path_length == 0xFFF) {\n\t\t\tconst char *path_end;\n\n\t\t\tpath_end = memchr(path_ptr, '\\0', buffer_size);\n\t\t\tif (path_end == NULL)\n\t\t\t\treturn -1;\n\n\t\t\tpath_length = path_end - path_ptr;\n\t\t}\n\n\t\tentry_size = index_entry_size(path_length, 0, entry.flags);\n\t\tentry.path = (char *)path_ptr;\n\t} else {\n\t\tsize_t varint_len;\n\t\tsize_t strip_len = git_decode_varint((const unsigned char *)path_ptr,\n\t\t\t\t\t\t &varint_len);\n\t\tsize_t last_len = strlen(last);\n\t\tsize_t prefix_len = last_len - strip_len;\n\t\tsize_t suffix_len = strlen(path_ptr + varint_len);\n\t\tsize_t path_len;\n\n\t\tif (varint_len == 0)\n\t\t\treturn index_error_invalid(\"incorrect prefix length\");\n\n\t\tGITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len);\n\t\tGITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1);\n\t\ttmp_path = git__malloc(path_len);\n\t\tGITERR_CHECK_ALLOC(tmp_path);\n\n\t\tmemcpy(tmp_path, last, prefix_len);\n\t\tmemcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1);\n\t\tentry_size = index_entry_size(suffix_len, varint_len, entry.flags);\n\t\tentry.path = tmp_path;\n\t}\n\n\tif (entry_size == 0)\n\t\treturn -1;\n\n\tif (INDEX_FOOTER_SIZE + entry_size > buffer_size)\n\t\treturn -1;\n\n\tif (index_entry_dup(out, index, &entry) < 0) {\n\t\tgit__free(tmp_path);\n\t\treturn -1;\n\t}\n\n\tgit__free(tmp_path);\n\t*out_size = entry_size;\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415', 'CWE-190'], 'message': 'index: fix out-of-bounds read with invalid index entry prefix length\n\nThe index format in version 4 has prefix-compressed entries, where every\nindex entry can compress its path by using a path prefix of the previous\nentry. Since implmenting support for this index format version in commit\n5625d86b9 (index: support index v4, 2016-05-17), though, we do not\ncorrectly verify that the prefix length that we want to reuse is\nactually smaller or equal to the amount of characters than the length of\nthe previous index entry's path. This can lead to a an integer underflow\nand subsequently to an out-of-bounds read.\n\nFix this by verifying that the prefix is actually smaller than the\nprevious entry's path length.\n\nReported-by: Krishna Ram Prakash R \nReported-by: Vivek Parikh '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: zzip_mem_entry_fopen(ZZIP_MEM_DISK * dir, ZZIP_MEM_ENTRY * entry)\n{\n /* keep this in sync with zzip_disk_entry_fopen */\n ZZIP_DISK_FILE *file = malloc(sizeof(ZZIP_MEM_DISK_FILE));\n if (! file)\n return file;\n file->buffer = dir->disk->buffer;\n file->endbuf = dir->disk->endbuf;\n file->avail = zzip_mem_entry_usize(entry);\n\n if (! file->avail || zzip_mem_entry_data_stored(entry))\n { file->stored = zzip_mem_entry_to_data (entry); return file; }\n\n file->stored = 0;\n file->zlib.opaque = 0;\n file->zlib.zalloc = Z_NULL;\n file->zlib.zfree = Z_NULL;\n file->zlib.avail_in = zzip_mem_entry_csize(entry);\n file->zlib.next_in = zzip_mem_entry_to_data(entry);\n\n if (! zzip_mem_entry_data_deflated(entry) ||\n inflateInit2(&file->zlib, -MAX_WBITS) != Z_OK)\n { free (file); return 0; }\n\n return file;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'check zlib space to be within buffer #39'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: zzip_mem_disk_findfile(ZZIP_MEM_DISK* dir, \n char* filename, ZZIP_DISK_ENTRY* after,\n\t\t zzip_strcmp_fn_t compare) {\n return zzip_disk_findfile(dir->disk, filename, after, compare); } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'memdisk\n (.)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: __zzip_parse_root_directory(int fd,\n struct _disk_trailer *trailer,\n struct zzip_dir_hdr **hdr_return,\n zzip_plugin_io_t io)\n{\n auto struct zzip_disk_entry dirent;\n struct zzip_dir_hdr *hdr;\n struct zzip_dir_hdr *hdr0;\n uint16_t *p_reclen = 0;\n zzip_off64_t entries;\n zzip_off64_t zz_offset; /* offset from start of root directory */\n char *fd_map = 0;\n zzip_off64_t zz_fd_gap = 0;\n zzip_off64_t zz_entries = _disk_trailer_localentries(trailer);\n zzip_off64_t zz_rootsize = _disk_trailer_rootsize(trailer);\n zzip_off64_t zz_rootseek = _disk_trailer_rootseek(trailer);\n __correct_rootseek(zz_rootseek, zz_rootsize, trailer);\n\n hdr0 = (struct zzip_dir_hdr *) malloc(zz_rootsize);\n if (! hdr0)\n return ZZIP_DIRSIZE;\n hdr = hdr0;\n __debug_dir_hdr(hdr);\n\n if (USE_MMAP && io->fd.sys)\n {\n zz_fd_gap = zz_rootseek & (_zzip_getpagesize(io->fd.sys) - 1);\n HINT4(\" fd_gap=%ld, mapseek=0x%lx, maplen=%ld\", (long) (zz_fd_gap),\n (long) (zz_rootseek - zz_fd_gap),\n (long) (zz_rootsize + zz_fd_gap));\n fd_map =\n _zzip_mmap(io->fd.sys, fd, zz_rootseek - zz_fd_gap,\n zz_rootsize + zz_fd_gap);\n /* if mmap failed we will fallback to seek/read mode */\n if (fd_map == MAP_FAILED)\n {\n NOTE2(\"map failed: %s\", strerror(errno));\n fd_map = 0;\n } else\n {\n HINT3(\"mapped *%p len=%li\", fd_map,\n (long) (zz_rootsize + zz_fd_gap));\n }\n }\n\n for (entries=0, zz_offset=0; ; entries++)\n {\n register struct zzip_disk_entry *d;\n uint16_t u_extras, u_comment, u_namlen;\n\n# ifndef ZZIP_ALLOW_MODULO_ENTRIES\n if (entries >= zz_entries) {\n if (zz_offset + 256 < zz_rootsize) {\n FAIL4(\"%li's entry is long before the end of directory - enable modulo_entries? (O:%li R:%li)\",\n (long) entries, (long) (zz_offset), (long) zz_rootsize);\n }\n break;\n }\n# endif\n\n if (fd_map)\n { d = (void*)(fd_map+zz_fd_gap+zz_offset); } /* fd_map+fd_gap==u_rootseek */\n else\n {\n if (io->fd.seeks(fd, zz_rootseek + zz_offset, SEEK_SET) < 0)\n return ZZIP_DIR_SEEK;\n if (io->fd.read(fd, &dirent, sizeof(dirent)) < __sizeof(dirent))\n return ZZIP_DIR_READ;\n d = &dirent;\n }\n\n if ((zzip_off64_t) (zz_offset + sizeof(*d)) > zz_rootsize ||\n (zzip_off64_t) (zz_offset + sizeof(*d)) < 0)\n {\n FAIL4(\"%li's entry stretches beyond root directory (O:%li R:%li)\",\n (long) entries, (long) (zz_offset), (long) zz_rootsize);\n break;\n }\n\n if (! zzip_disk_entry_check_magic(d)) {\n# ifndef ZZIP_ALLOW_MODULO_ENTRIES\n FAIL4(\"%li's entry has no disk_entry magic indicator (O:%li R:%li)\",\n (long) entries, (long) (zz_offset), (long) zz_rootsize);\n# endif\n break;\n }\n\n# if 0 && defined DEBUG\n zzip_debug_xbuf((unsigned char *) d, sizeof(*d) + 8);\n# endif\n\n u_extras = zzip_disk_entry_get_extras(d);\n u_comment = zzip_disk_entry_get_comment(d);\n u_namlen = zzip_disk_entry_get_namlen(d);\n HINT5(\"offset=0x%lx, size %ld, dirent *%p, hdr %p\\n\",\n (long) (zz_offset + zz_rootseek), (long) zz_rootsize, d, hdr);\n\n /* writes over the read buffer, Since the structure where data is\n copied is smaller than the data in buffer this can be done.\n It is important that the order of setting the fields is considered\n when filling the structure, so that some data is not trashed in\n first structure read.\n at the end the whole copied list of structures is copied into\n newly allocated buffer */\n hdr->d_crc32 = zzip_disk_entry_get_crc32(d);\n hdr->d_csize = zzip_disk_entry_get_csize(d);\n hdr->d_usize = zzip_disk_entry_get_usize(d);\n hdr->d_off = zzip_disk_entry_get_offset(d);\n hdr->d_compr = zzip_disk_entry_get_compr(d);\n if (hdr->d_compr > _255)\n hdr->d_compr = 255;\n\n if ((zzip_off64_t) (zz_offset + sizeof(*d) + u_namlen) > zz_rootsize ||\n (zzip_off64_t) (zz_offset + sizeof(*d) + u_namlen) < 0)\n {\n FAIL4(\"%li's name stretches beyond root directory (O:%li N:%li)\",\n (long) entries, (long) (zz_offset), (long) (u_namlen));\n break;\n }\n\n if (fd_map)\n { memcpy(hdr->d_name, fd_map+zz_fd_gap + zz_offset+sizeof(*d), u_namlen); }\n else\n { io->fd.read(fd, hdr->d_name, u_namlen); }\n hdr->d_name[u_namlen] = '\\0';\n hdr->d_namlen = u_namlen;\n\n /* update offset by the total length of this entry -> next entry */\n zz_offset += sizeof(*d) + u_namlen + u_extras + u_comment;\n\n if (zz_offset > zz_rootsize)\n {\n FAIL3(\"%li's entry stretches beyond root directory (O:%li)\",\n (long) entries, (long) (zz_offset));\n entries ++;\n break;\n }\n\n HINT5(\"file %ld { compr=%d crc32=$%x offset=%d\",\n (long) entries, hdr->d_compr, hdr->d_crc32, hdr->d_off);\n HINT5(\"csize=%d usize=%d namlen=%d extras=%d\",\n hdr->d_csize, hdr->d_usize, u_namlen, u_extras);\n HINT5(\"comment=%d name='%s' %s } \",\n u_comment, hdr->d_name, \"\", (int) sizeof(*d));\n\n p_reclen = &hdr->d_reclen;\n\n {\n register char *p = (char *) hdr;\n register char *q = aligned4(p + sizeof(*hdr) + u_namlen + 1);\n *p_reclen = (uint16_t) (q - p);\n hdr = (struct zzip_dir_hdr *) q;\n }\n } /*for */\n\n if (USE_MMAP && fd_map)\n {\n HINT3(\"unmap *%p len=%li\", fd_map, (long) (zz_rootsize + zz_fd_gap));\n _zzip_munmap(io->fd.sys, fd_map, zz_rootsize + zz_fd_gap);\n }\n\n if (p_reclen)\n {\n *p_reclen = 0; /* mark end of list */\n\n if (hdr_return)\n *hdr_return = hdr0;\n } /* else zero (sane) entries */\n# ifndef ZZIP_ALLOW_MODULO_ENTRIES\n return (entries != zz_entries ? ZZIP_CORRUPTED : 0);\n# else\n return ((entries & (unsigned)0xFFFF) != zz_entries ? ZZIP_CORRUPTED : 0);\n# endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'check rootseek after correction #41'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static ssize_t ocfs2_direct_IO(struct kiocb *iocb, struct iov_iter *iter)\n{\n\tstruct file *file = iocb->ki_filp;\n\tstruct inode *inode = file->f_mapping->host;\n\tstruct ocfs2_super *osb = OCFS2_SB(inode->i_sb);\n\tget_block_t *get_block;\n\n\t/*\n\t * Fallback to buffered I/O if we see an inode without\n\t * extents.\n\t */\n\tif (OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL)\n\t\treturn 0;\n\n\t/* Fallback to buffered I/O if we do not support append dio. */\n\tif (iocb->ki_pos + iter->count > i_size_read(inode) &&\n\t !ocfs2_supports_append_dio(osb))\n\t\treturn 0;\n\n\tif (iov_iter_rw(iter) == READ)\n\t\tget_block = ocfs2_get_block;\n\telse\n\t\tget_block = ocfs2_dio_get_block;\n\n\treturn __blockdev_direct_IO(iocb, inode, inode->i_sb->s_bdev,\n\t\t\t\t iter, get_block,\n\t\t\t\t ocfs2_dio_end_io, NULL, 0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'ocfs2: ip_alloc_sem should be taken in ocfs2_get_block()\n\nip_alloc_sem should be taken in ocfs2_get_block() when reading file in\nDIRECT mode to prevent concurrent access to extent tree with\nocfs2_dio_end_io_write(), which may cause BUGON in the following\nsituation:\n\nread file 'A' end_io of writing file 'A'\nvfs_read\n __vfs_read\n ocfs2_file_read_iter\n generic_file_read_iter\n ocfs2_direct_IO\n __blockdev_direct_IO\n do_blockdev_direct_IO\n do_direct_IO\n get_more_blocks\n ocfs2_get_block\n ocfs2_extent_map_get_blocks\n ocfs2_get_clusters\n ocfs2_get_clusters_nocache()\n ocfs2_search_extent_list\n return the index of record which\n contains the v_cluster, that is\n v_cluster > rec[i]->e_cpos.\n ocfs2_dio_end_io\n ocfs2_dio_end_io_write\n down_write(&oi->ip_alloc_sem);\n ocfs2_mark_extent_written\n ocfs2_change_extent_flag\n ocfs2_split_extent\n ...\n --> modify the rec[i]->e_cpos, resulting\n in v_cluster < rec[i]->e_cpos.\n BUG_ON(v_cluster < le32_to_cpu(rec->e_cpos))\n\n[alex.chen@huawei.com: v3]\n Link: http://lkml.kernel.org/r/59EF3614.6050008@huawei.com\nLink: http://lkml.kernel.org/r/59EF3614.6050008@huawei.com\nFixes: c15471f79506 (\"ocfs2: fix sparse file & data ordering issue in direct io\")\nSigned-off-by: Alex Chen \nReviewed-by: Jun Piao \nReviewed-by: Joseph Qi \nReviewed-by: Gang He \nAcked-by: Changwei Ge \nCc: Mark Fasheh \nCc: Joel Becker \nCc: Junxiao Bi \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void sas_revalidate_domain(struct work_struct *work)\n{\n\tint res = 0;\n\tstruct sas_discovery_event *ev = to_sas_discovery_event(work);\n\tstruct asd_sas_port *port = ev->port;\n\tstruct sas_ha_struct *ha = port->ha;\n\tstruct domain_device *ddev = port->port_dev;\n\n\t/* prevent revalidation from finding sata links in recovery */\n\tmutex_lock(&ha->disco_mutex);\n\tif (test_bit(SAS_HA_ATA_EH_ACTIVE, &ha->state)) {\n\t\tSAS_DPRINTK(\"REVALIDATION DEFERRED on port %d, pid:%d\\n\",\n\t\t\t port->id, task_pid_nr(current));\n\t\tgoto out;\n\t}\n\n\tclear_bit(DISCE_REVALIDATE_DOMAIN, &port->disc.pending);\n\n\tSAS_DPRINTK(\"REVALIDATING DOMAIN on port %d, pid:%d\\n\", port->id,\n\t\t task_pid_nr(current));\n\n\tif (ddev && (ddev->dev_type == SAS_FANOUT_EXPANDER_DEVICE ||\n\t\t ddev->dev_type == SAS_EDGE_EXPANDER_DEVICE))\n\t\tres = sas_ex_revalidate_domain(ddev);\n\n\tSAS_DPRINTK(\"done REVALIDATING DOMAIN on port %d, pid:%d, res 0x%x\\n\",\n\t\t port->id, task_pid_nr(current), res);\n out:\n\tmutex_unlock(&ha->disco_mutex);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284'], 'message': 'scsi: libsas: direct call probe and destruct\n\nIn commit 87c8331fcf72 (\"[SCSI] libsas: prevent domain rediscovery\ncompeting with ata error handling\") introduced disco mutex to prevent\nrediscovery competing with ata error handling and put the whole\nrevalidation in the mutex. But the rphy add/remove needs to wait for the\nerror handling which also grabs the disco mutex. This may leads to dead\nlock.So the probe and destruct event were introduce to do the rphy\nadd/remove asynchronously and out of the lock.\n\nThe asynchronously processed workers makes the whole discovery process\nnot atomic, the other events may interrupt the process. For example,\nif a loss of signal event inserted before the probe event, the\nsas_deform_port() is called and the port will be deleted.\n\nAnd sas_port_delete() may run before the destruct event, but the\nport-x:x is the top parent of end device or expander. This leads to\na kernel WARNING such as:\n\n[ 82.042979] sysfs group 'power' not found for kobject 'phy-1:0:22'\n[ 82.042983] ------------[ cut here ]------------\n[ 82.042986] WARNING: CPU: 54 PID: 1714 at fs/sysfs/group.c:237\nsysfs_remove_group+0x94/0xa0\n[ 82.043059] Call trace:\n[ 82.043082] [] sysfs_remove_group+0x94/0xa0\n[ 82.043085] [] dpm_sysfs_remove+0x60/0x70\n[ 82.043086] [] device_del+0x138/0x308\n[ 82.043089] [] sas_phy_delete+0x38/0x60\n[ 82.043091] [] do_sas_phy_delete+0x6c/0x80\n[ 82.043093] [] device_for_each_child+0x58/0xa0\n[ 82.043095] [] sas_remove_children+0x40/0x50\n[ 82.043100] [] sas_destruct_devices+0x64/0xa0\n[ 82.043102] [] process_one_work+0x1fc/0x4b0\n[ 82.043104] [] worker_thread+0x50/0x490\n[ 82.043105] [] kthread+0xfc/0x128\n[ 82.043107] [] ret_from_fork+0x10/0x50\n\nMake probe and destruct a direct call in the disco and revalidate function,\nbut put them outside the lock. The whole discovery or revalidate won't\nbe interrupted by other events. And the DISCE_PROBE and DISCE_DESTRUCT\nevent are deleted as a result of the direct call.\n\nIntroduce a new list to destruct the sas_port and put the port delete after\nthe destruct. This makes sure the right order of destroying the sysfs\nkobject and fix the warning above.\n\nIn sas_ex_revalidate_domain() have a loop to find all broadcasted\ndevice, and sometimes we have a chance to find the same expander twice.\nBecause the sas_port will be deleted at the end of the whole revalidate\nprocess, sas_port with the same name cannot be added before this.\nOtherwise the sysfs will complain of creating duplicate filename. Since\nthe LLDD will send broadcast for every device change, we can only\nprocess one expander's revalidation.\n\n[mkp: kbuild test robot warning]\n\nSigned-off-by: Jason Yan \nCC: John Garry \nCC: Johannes Thumshirn \nCC: Ewan Milne \nCC: Christoph Hellwig \nCC: Tomas Henzl \nCC: Dan Williams \nReviewed-by: Hannes Reinecke \nSigned-off-by: Martin K. Petersen '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Token *tokenize(char *line)\n{\n char c, *p = line;\n enum pp_token_type type;\n Token *list = NULL;\n Token *t, **tail = &list;\n\n while (*line) {\n p = line;\n if (*p == '%') {\n p++;\n if (*p == '+' && !nasm_isdigit(p[1])) {\n p++;\n type = TOK_PASTE;\n } else if (nasm_isdigit(*p) ||\n ((*p == '-' || *p == '+') && nasm_isdigit(p[1]))) {\n do {\n p++;\n }\n while (nasm_isdigit(*p));\n type = TOK_PREPROC_ID;\n } else if (*p == '{') {\n p++;\n while (*p) {\n if (*p == '}')\n break;\n p[-1] = *p;\n p++;\n }\n if (*p != '}')\n nasm_error(ERR_WARNING | ERR_PASS1,\n\t\t\t \"unterminated %%{ construct\");\n p[-1] = '\\0';\n if (*p)\n p++;\n type = TOK_PREPROC_ID;\n } else if (*p == '[') {\n int lvl = 1;\n line += 2; /* Skip the leading %[ */\n p++;\n while (lvl && (c = *p++)) {\n switch (c) {\n case ']':\n lvl--;\n break;\n case '%':\n if (*p == '[')\n lvl++;\n break;\n case '\\'':\n case '\\\"':\n case '`':\n p = nasm_skip_string(p - 1) + 1;\n break;\n default:\n break;\n }\n }\n p--;\n if (*p)\n *p++ = '\\0';\n if (lvl)\n nasm_error(ERR_NONFATAL|ERR_PASS1,\n\t\t\t \"unterminated %%[ construct\");\n type = TOK_INDIRECT;\n } else if (*p == '?') {\n type = TOK_PREPROC_Q; /* %? */\n p++;\n if (*p == '?') {\n type = TOK_PREPROC_QQ; /* %?? */\n p++;\n }\n } else if (*p == '!') {\n type = TOK_PREPROC_ID;\n p++;\n if (isidchar(*p)) {\n do {\n p++;\n }\n while (isidchar(*p));\n } else if (*p == '\\'' || *p == '\\\"' || *p == '`') {\n p = nasm_skip_string(p);\n if (*p)\n p++;\n else\n nasm_error(ERR_NONFATAL|ERR_PASS1,\n\t\t\t\t \"unterminated %%! string\");\n } else {\n /* %! without string or identifier */\n type = TOK_OTHER; /* Legacy behavior... */\n }\n } else if (isidchar(*p) ||\n ((*p == '!' || *p == '%' || *p == '$') &&\n isidchar(p[1]))) {\n do {\n p++;\n }\n while (isidchar(*p));\n type = TOK_PREPROC_ID;\n } else {\n type = TOK_OTHER;\n if (*p == '%')\n p++;\n }\n } else if (isidstart(*p) || (*p == '$' && isidstart(p[1]))) {\n type = TOK_ID;\n p++;\n while (*p && isidchar(*p))\n p++;\n } else if (*p == '\\'' || *p == '\"' || *p == '`') {\n /*\n * A string token.\n */\n type = TOK_STRING;\n p = nasm_skip_string(p);\n\n if (*p) {\n p++;\n } else {\n nasm_error(ERR_WARNING|ERR_PASS1, \"unterminated string\");\n /* Handling unterminated strings by UNV */\n /* type = -1; */\n }\n } else if (p[0] == '$' && p[1] == '$') {\n type = TOK_OTHER; /* TOKEN_BASE */\n p += 2;\n } else if (isnumstart(*p)) {\n bool is_hex = false;\n bool is_float = false;\n bool has_e = false;\n char c, *r;\n\n /*\n * A numeric token.\n */\n\n if (*p == '$') {\n p++;\n is_hex = true;\n }\n\n for (;;) {\n c = *p++;\n\n if (!is_hex && (c == 'e' || c == 'E')) {\n has_e = true;\n if (*p == '+' || *p == '-') {\n /*\n * e can only be followed by +/- if it is either a\n * prefixed hex number or a floating-point number\n */\n p++;\n is_float = true;\n }\n } else if (c == 'H' || c == 'h' || c == 'X' || c == 'x') {\n is_hex = true;\n } else if (c == 'P' || c == 'p') {\n is_float = true;\n if (*p == '+' || *p == '-')\n p++;\n } else if (isnumchar(c))\n ; /* just advance */\n else if (c == '.') {\n /*\n * we need to deal with consequences of the legacy\n * parser, like \"1.nolist\" being two tokens\n * (TOK_NUMBER, TOK_ID) here; at least give it\n * a shot for now. In the future, we probably need\n * a flex-based scanner with proper pattern matching\n * to do it as well as it can be done. Nothing in\n * the world is going to help the person who wants\n * 0x123.p16 interpreted as two tokens, though.\n */\n r = p;\n while (*r == '_')\n r++;\n\n if (nasm_isdigit(*r) || (is_hex && nasm_isxdigit(*r)) ||\n (!is_hex && (*r == 'e' || *r == 'E')) ||\n (*r == 'p' || *r == 'P')) {\n p = r;\n is_float = true;\n } else\n break; /* Terminate the token */\n } else\n break;\n }\n p--; /* Point to first character beyond number */\n\n if (p == line+1 && *line == '$') {\n type = TOK_OTHER; /* TOKEN_HERE */\n } else {\n if (has_e && !is_hex) {\n /* 1e13 is floating-point, but 1e13h is not */\n is_float = true;\n }\n\n type = is_float ? TOK_FLOAT : TOK_NUMBER;\n }\n } else if (nasm_isspace(*p)) {\n type = TOK_WHITESPACE;\n p = nasm_skip_spaces(p);\n /*\n * Whitespace just before end-of-line is discarded by\n * pretending it's a comment; whitespace just before a\n * comment gets lumped into the comment.\n */\n if (!*p || *p == ';') {\n type = TOK_COMMENT;\n while (*p)\n p++;\n }\n } else if (*p == ';') {\n type = TOK_COMMENT;\n while (*p)\n p++;\n } else {\n /*\n * Anything else is an operator of some kind. We check\n * for all the double-character operators (>>, <<, //,\n * %%, <=, >=, ==, !=, <>, &&, ||, ^^), but anything\n * else is a single-character operator.\n */\n type = TOK_OTHER;\n if ((p[0] == '>' && p[1] == '>') ||\n (p[0] == '<' && p[1] == '<') ||\n (p[0] == '/' && p[1] == '/') ||\n (p[0] == '<' && p[1] == '=') ||\n (p[0] == '>' && p[1] == '=') ||\n (p[0] == '=' && p[1] == '=') ||\n (p[0] == '!' && p[1] == '=') ||\n (p[0] == '<' && p[1] == '>') ||\n (p[0] == '&' && p[1] == '&') ||\n (p[0] == '|' && p[1] == '|') ||\n (p[0] == '^' && p[1] == '^')) {\n p++;\n }\n p++;\n }\n\n /* Handling unterminated string by UNV */\n /*if (type == -1)\n {\n *tail = t = new_Token(NULL, TOK_STRING, line, p-line+1);\n t->text[p-line] = *line;\n tail = &t->next;\n }\n else */\n if (type != TOK_COMMENT) {\n *tail = t = new_Token(NULL, type, line, p - line);\n tail = &t->next;\n }\n line = p;\n }\n return list;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'preproc: Don't access offsting byte on unterminated strings\n\nhttps://bugzilla.nasm.us/show_bug.cgi?id=3392446\n\nSigned-off-by: Cyrill Gorcunov '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void LogOpenCLBuildFailure(MagickCLDevice device,const char *kernel,\n ExceptionInfo *exception)\n{\n char\n filename[MagickPathExtent],\n *log;\n\n size_t\n log_size;\n\n (void) FormatLocaleString(filename,MagickPathExtent,\"%s%s%s\",\n GetOpenCLCacheDirectory(),DirectorySeparator,\"magick_badcl.cl\");\n\n (void) remove_utf8(filename);\n (void) BlobToFile(filename,kernel,strlen(kernel),exception);\n\n openCL_library->clGetProgramBuildInfo(device->program,device->deviceID,\n CL_PROGRAM_BUILD_LOG,0,NULL,&log_size);\n log=(char*)AcquireMagickMemory(log_size);\n openCL_library->clGetProgramBuildInfo(device->program,device->deviceID,\n CL_PROGRAM_BUILD_LOG,log_size,log,&log_size);\n\n (void) FormatLocaleString(filename,MagickPathExtent,\"%s%s%s\",\n GetOpenCLCacheDirectory(),DirectorySeparator,\"magick_badcl.log\");\n\n (void) remove_utf8(filename);\n (void) BlobToFile(filename,log,log_size,exception);\n log=(char*)RelinquishMagickMemory(log);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/793'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: dir_initialize(int argc, VALUE *argv, VALUE dir)\n{\n struct dir_data *dp;\n rb_encoding *fsenc;\n VALUE dirname, opt, orig;\n static ID keyword_ids[1];\n const char *path;\n\n if (!keyword_ids[0]) {\n\tkeyword_ids[0] = rb_id_encoding();\n }\n\n fsenc = rb_filesystem_encoding();\n\n rb_scan_args(argc, argv, \"1:\", &dirname, &opt);\n\n if (!NIL_P(opt)) {\n\tVALUE enc;\n\trb_get_kwargs(opt, keyword_ids, 0, 1, &enc);\n\tif (enc != Qundef && !NIL_P(enc)) {\n\t fsenc = rb_to_encoding(enc);\n\t}\n }\n\n GlobPathValue(dirname, FALSE);\n orig = rb_str_dup_frozen(dirname);\n dirname = rb_str_encode_ospath(dirname);\n dirname = rb_str_dup_frozen(dirname);\n\n TypedData_Get_Struct(dir, struct dir_data, &dir_data_type, dp);\n if (dp->dir) closedir(dp->dir);\n dp->dir = NULL;\n RB_OBJ_WRITE(dir, &dp->path, Qnil);\n dp->enc = fsenc;\n path = RSTRING_PTR(dirname);\n dp->dir = opendir_without_gvl(path);\n if (dp->dir == NULL) {\n\tint e = errno;\n\tif (rb_gc_for_fd(e)) {\n\t dp->dir = opendir_without_gvl(path);\n\t}\n#ifdef HAVE_GETATTRLIST\n\telse if (e == EIO) {\n\t u_int32_t attrbuf[1];\n\t struct attrlist al = {ATTR_BIT_MAP_COUNT, 0};\n\t if (getattrlist(path, &al, attrbuf, sizeof(attrbuf), FSOPT_NOFOLLOW) == 0) {\n\t\tdp->dir = opendir_without_gvl(path);\n\t }\n\t}\n#endif\n\tif (dp->dir == NULL) {\n\t RB_GC_GUARD(dirname);\n\t rb_syserr_fail_path(e, orig);\n\t}\n }\n RB_OBJ_WRITE(dir, &dp->path, orig);\n\n return dir;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-22'], 'message': 'dir.c: check NUL bytes\n\n* dir.c (GlobPathValue): should be used in rb_push_glob only.\n other methods should use FilePathValue.\n https://hackerone.com/reports/302338\n\n* dir.c (rb_push_glob): expand GlobPathValue\n\ngit-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@62989 b2dd03c8-39d4-4d8f-98ff-823fe69b080e'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: do_ed_script (char const *inname, char const *outname,\n\t bool *outname_needs_removal, FILE *ofp)\n{\n static char const editor_program[] = EDITOR_PROGRAM;\n\n file_offset beginning_of_this_line;\n FILE *pipefp = 0;\n size_t chars_read;\n\n if (! dry_run && ! skip_rest_of_patch) {\n\tint exclusive = *outname_needs_removal ? 0 : O_EXCL;\n\tif (inerrno != ENOENT)\n\t {\n\t *outname_needs_removal = true;\n\t copy_file (inname, outname, 0, exclusive, instat.st_mode, true);\n\t }\n\tsprintf (buf, \"%s %s%s\", editor_program,\n\t\t verbosity == VERBOSE ? \"\" : \"- \",\n\t\t outname);\n\tfflush (stdout);\n\tpipefp = popen(buf, binary_transput ? \"wb\" : \"w\");\n\tif (!pipefp)\n\t pfatal (\"Can't open pipe to %s\", quotearg (buf));\n }\n for (;;) {\n\tchar ed_command_letter;\n\tbeginning_of_this_line = file_tell (pfp);\n\tchars_read = get_line ();\n\tif (! chars_read) {\n\t next_intuit_at(beginning_of_this_line,p_input_line);\n\t break;\n\t}\n\ted_command_letter = get_ed_command_letter (buf);\n\tif (ed_command_letter) {\n\t if (pipefp)\n\t\tif (! fwrite (buf, sizeof *buf, chars_read, pipefp))\n\t\t write_fatal ();\n\t if (ed_command_letter != 'd' && ed_command_letter != 's') {\n\t p_pass_comments_through = true;\n\t\twhile ((chars_read = get_line ()) != 0) {\n\t\t if (pipefp)\n\t\t\tif (! fwrite (buf, sizeof *buf, chars_read, pipefp))\n\t\t\t write_fatal ();\n\t\t if (chars_read == 2 && strEQ (buf, \".\\n\"))\n\t\t\tbreak;\n\t\t}\n\t\tp_pass_comments_through = false;\n\t }\n\t}\n\telse {\n\t next_intuit_at(beginning_of_this_line,p_input_line);\n\t break;\n\t}\n }\n if (!pipefp)\n return;\n if (fwrite (\"w\\nq\\n\", sizeof (char), (size_t) 4, pipefp) == 0\n\t|| fflush (pipefp) != 0)\n write_fatal ();\n if (pclose (pipefp) != 0)\n fatal (\"%s FAILED\", editor_program);\n\n if (ofp)\n {\n\tFILE *ifp = fopen (outname, binary_transput ? \"rb\" : \"r\");\n\tint c;\n\tif (!ifp)\n\t pfatal (\"can't open '%s'\", outname);\n\twhile ((c = getc (ifp)) != EOF)\n\t if (putc (c, ofp) == EOF)\n\t write_fatal ();\n\tif (ferror (ifp) || fclose (ifp) != 0)\n\t read_fatal ();\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fix arbitrary command execution in ed-style patches (CVE-2018-1000156)\n\n* src/pch.c (do_ed_script): Write ed script to a temporary file instead\nof piping it to ed: this will cause ed to abort on invalid commands\ninstead of rejecting them and carrying on.\n* tests/ed-style: New test case.\n* tests/Makefile.am (TESTS): Add test case.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: pk_transaction_authorize_actions_finished_cb (GObject *source_object,\n\t\t\t\t\t GAsyncResult *res,\n\t\t\t\t\t struct AuthorizeActionsData *data)\n{\n\tconst gchar *action_id = NULL;\n\tPkTransactionPrivate *priv = data->transaction->priv;\n\tg_autoptr(GError) error = NULL;\n\tg_autoptr(PolkitAuthorizationResult) result = NULL;\n\tg_assert (data->actions && data->actions->len > 0);\n\n\t/* get the first action */\n\taction_id = g_ptr_array_index (data->actions, 0);\n\n\t/* finish the call */\n\tresult = polkit_authority_check_authorization_finish (priv->authority, res, &error);\n\n\t/* failed because the request was cancelled */\n\tif (g_cancellable_is_cancelled (priv->cancellable)) {\n\t\t/* emit an ::StatusChanged, ::ErrorCode() and then ::Finished() */\n\t\tpriv->waiting_for_auth = FALSE;\n\t\tpk_transaction_status_changed_emit (data->transaction, PK_STATUS_ENUM_FINISHED);\n\t\tpk_transaction_error_code_emit (data->transaction, PK_ERROR_ENUM_NOT_AUTHORIZED,\n\t\t\t\t\t\t\"The authentication was cancelled due to a timeout.\");\n\t\tpk_transaction_finished_emit (data->transaction, PK_EXIT_ENUM_FAILED, 0);\n\t\tgoto out;\n\t}\n\n\t/* failed, maybe polkit is messed up? */\n\tif (result == NULL) {\n\t\tg_autofree gchar *message = NULL;\n\t\tpriv->waiting_for_auth = FALSE;\n\t\tg_warning (\"failed to check for auth: %s\", error->message);\n\n\t\t/* emit an ::StatusChanged, ::ErrorCode() and then ::Finished() */\n\t\tpk_transaction_status_changed_emit (data->transaction, PK_STATUS_ENUM_FINISHED);\n\t\tmessage = g_strdup_printf (\"Failed to check for authentication: %s\", error->message);\n\t\tpk_transaction_error_code_emit (data->transaction,\n\t\t\t\t\t\tPK_ERROR_ENUM_NOT_AUTHORIZED,\n\t\t\t\t\t\tmessage);\n\t\tpk_transaction_finished_emit (data->transaction, PK_EXIT_ENUM_FAILED, 0);\n\t\tgoto out;\n\t}\n\n\t/* did not auth */\n\tif (!polkit_authorization_result_get_is_authorized (result)) {\n\t\tif (g_strcmp0 (action_id, \"org.freedesktop.packagekit.package-install\") == 0 &&\n\t\t\t pk_bitfield_contain (priv->cached_transaction_flags,\n\t\t\t\t\t\t PK_TRANSACTION_FLAG_ENUM_ALLOW_REINSTALL)) {\n\t\t\tg_debug (\"allowing just reinstallation\");\n\t\t\tpk_bitfield_add (priv->cached_transaction_flags,\n\t\t\t\t\t PK_TRANSACTION_FLAG_ENUM_JUST_REINSTALL);\n\t\t} else {\n\t\t\tpriv->waiting_for_auth = FALSE;\n\t\t\t/* emit an ::StatusChanged, ::ErrorCode() and then ::Finished() */\n\t\t\tpk_transaction_status_changed_emit (data->transaction, PK_STATUS_ENUM_FINISHED);\n\t\t\tpk_transaction_error_code_emit (data->transaction, PK_ERROR_ENUM_NOT_AUTHORIZED,\n\t\t\t\t\t\t\t\"Failed to obtain authentication.\");\n\t\t\tpk_transaction_finished_emit (data->transaction, PK_EXIT_ENUM_FAILED, 0);\n\n\t\t\tsyslog (LOG_AUTH | LOG_NOTICE,\n\t\t\t\t\"uid %i failed to obtain auth\",\n\t\t\t\tpriv->uid);\n\t\t\tgoto out;\n\t\t}\n\t}\n\n\tif (data->actions->len <= 1) {\n\t\t/* authentication finished successfully */\n\t\tpriv->waiting_for_auth = FALSE;\n\t\tpk_transaction_set_state (data->transaction, PK_TRANSACTION_STATE_READY);\n\t\t/* log success too */\n\t\tsyslog (LOG_AUTH | LOG_INFO,\n\t\t\t\"uid %i obtained auth for %s\",\n\t\t\tpriv->uid, action_id);\n\t} else {\n\t\t/* process the rest of actions */\n\t\tg_ptr_array_remove_index (data->actions, 0);\n\t\tpk_transaction_authorize_actions (data->transaction, data->role, data->actions);\n\t}\n\nout:\n\tg_ptr_array_unref (data->actions);\n\tg_free (data);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-287'], 'message': 'Do not set JUST_REINSTALL on any kind of auth failure\n\nIf we try to continue the auth queue when it has been cancelled (or failed)\nthen we fall upon the obscure JUST_REINSTALL transaction flag which only the\nDNF backend actually verifies.\n\nMany thanks to Matthias Gerstner for spotting the problem.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: QPDFObjectHandle::parseInternal(PointerHolder input,\n std::string const& object_description,\n QPDFTokenizer& tokenizer, bool& empty,\n StringDecrypter* decrypter, QPDF* context,\n bool content_stream)\n{\n // This method must take care not to resolve any objects. Don't\n // check the type of any object without first ensuring that it is\n // a direct object. Otherwise, doing so may have the side effect\n // of reading the object and changing the file pointer.\n\n empty = false;\n\n QPDFObjectHandle object;\n\n std::vector > olist_stack;\n olist_stack.push_back(std::vector());\n std::vector state_stack;\n state_stack.push_back(st_top);\n std::vector offset_stack;\n qpdf_offset_t offset = input->tell();\n offset_stack.push_back(offset);\n bool done = false;\n while (! done)\n {\n std::vector& olist = olist_stack.back();\n parser_state_e state = state_stack.back();\n offset = offset_stack.back();\n\n\tobject = QPDFObjectHandle();\n\n\tQPDFTokenizer::Token token =\n tokenizer.readToken(input, object_description, true);\n\n\tswitch (token.getType())\n\t{\n case QPDFTokenizer::tt_eof:\n if (! content_stream)\n {\n QTC::TC(\"qpdf\", \"QPDFObjectHandle eof in parseInternal\");\n warn(context,\n QPDFExc(qpdf_e_damaged_pdf, input->getName(),\n object_description,\n input->getLastOffset(),\n \"unexpected EOF\"));\n }\n state = st_eof;\n break;\n\n case QPDFTokenizer::tt_bad:\n\t QTC::TC(\"qpdf\", \"QPDFObjectHandle bad token in parse\");\n warn(context,\n QPDFExc(qpdf_e_damaged_pdf, input->getName(),\n object_description,\n input->getLastOffset(),\n token.getErrorMessage()));\n object = newNull();\n\t break;\n\n\t case QPDFTokenizer::tt_brace_open:\n\t case QPDFTokenizer::tt_brace_close:\n\t QTC::TC(\"qpdf\", \"QPDFObjectHandle bad brace\");\n warn(context,\n QPDFExc(qpdf_e_damaged_pdf, input->getName(),\n object_description,\n input->getLastOffset(),\n \"treating unexpected brace token as null\"));\n object = newNull();\n\t break;\n\n\t case QPDFTokenizer::tt_array_close:\n\t if (state == st_array)\n\t {\n state = st_stop;\n\t }\n\t else\n\t {\n\t\tQTC::TC(\"qpdf\", \"QPDFObjectHandle bad array close\");\n warn(context,\n QPDFExc(qpdf_e_damaged_pdf, input->getName(),\n object_description,\n input->getLastOffset(),\n \"treating unexpected array close token as null\"));\n object = newNull();\n\t }\n\t break;\n\n\t case QPDFTokenizer::tt_dict_close:\n\t if (state == st_dictionary)\n\t {\n state = st_stop;\n\t }\n\t else\n\t {\n\t\tQTC::TC(\"qpdf\", \"QPDFObjectHandle bad dictionary close\");\n warn(context,\n QPDFExc(qpdf_e_damaged_pdf, input->getName(),\n object_description,\n input->getLastOffset(),\n \"unexpected dictionary close token\"));\n object = newNull();\n\t }\n\t break;\n\n\t case QPDFTokenizer::tt_array_open:\n\t case QPDFTokenizer::tt_dict_open:\n olist_stack.push_back(std::vector());\n state = st_start;\n offset_stack.push_back(input->tell());\n state_stack.push_back(\n (token.getType() == QPDFTokenizer::tt_array_open) ?\n st_array : st_dictionary);\n\t break;\n\n\t case QPDFTokenizer::tt_bool:\n\t object = newBool((token.getValue() == \"true\"));\n\t break;\n\n\t case QPDFTokenizer::tt_null:\n\t object = newNull();\n\t break;\n\n\t case QPDFTokenizer::tt_integer:\n\t object = newInteger(QUtil::string_to_ll(token.getValue().c_str()));\n\t break;\n\n\t case QPDFTokenizer::tt_real:\n\t object = newReal(token.getValue());\n\t break;\n\n\t case QPDFTokenizer::tt_name:\n\t object = newName(token.getValue());\n\t break;\n\n\t case QPDFTokenizer::tt_word:\n\t {\n\t\tstd::string const& value = token.getValue();\n if (content_stream)\n {\n object = QPDFObjectHandle::newOperator(value);\n }\n\t\telse if ((value == \"R\") && (state != st_top) &&\n (olist.size() >= 2) &&\n (! olist.at(olist.size() - 1).isIndirect()) &&\n (olist.at(olist.size() - 1).isInteger()) &&\n (! olist.at(olist.size() - 2).isIndirect()) &&\n (olist.at(olist.size() - 2).isInteger()))\n\t\t{\n if (context == 0)\n {\n QTC::TC(\"qpdf\", \"QPDFObjectHandle indirect without context\");\n throw std::logic_error(\n \"QPDFObjectHandle::parse called without context\"\n \" on an object with indirect references\");\n }\n\t\t // Try to resolve indirect objects\n\t\t object = newIndirect(\n\t\t\tcontext,\n\t\t\tolist.at(olist.size() - 2).getIntValue(),\n\t\t\tolist.at(olist.size() - 1).getIntValue());\n\t\t olist.pop_back();\n\t\t olist.pop_back();\n\t\t}\n\t\telse if ((value == \"endobj\") && (state == st_top))\n\t\t{\n\t\t // We just saw endobj without having read\n\t\t // anything. Treat this as a null and do not move\n\t\t // the input source's offset.\n\t\t object = newNull();\n\t\t input->seek(input->getLastOffset(), SEEK_SET);\n empty = true;\n\t\t}\n\t\telse\n\t\t{\n QTC::TC(\"qpdf\", \"QPDFObjectHandle treat word as string\");\n warn(context,\n QPDFExc(qpdf_e_damaged_pdf, input->getName(),\n object_description,\n input->getLastOffset(),\n \"unknown token while reading object;\"\n \" treating as string\"));\n object = newString(value);\n\t\t}\n\t }\n\t break;\n\n\t case QPDFTokenizer::tt_string:\n\t {\n\t\tstd::string val = token.getValue();\n if (decrypter)\n {\n decrypter->decryptString(val);\n }\n\t\tobject = QPDFObjectHandle::newString(val);\n\t }\n\n\t break;\n\n\t default:\n warn(context,\n QPDFExc(qpdf_e_damaged_pdf, input->getName(),\n object_description,\n input->getLastOffset(),\n \"treating unknown token type as null while \"\n \"reading object\"));\n object = newNull();\n\t break;\n\t}\n\n if ((! object.isInitialized()) &&\n (! ((state == st_start) ||\n (state == st_stop) ||\n (state == st_eof))))\n {\n throw std::logic_error(\n \"QPDFObjectHandle::parseInternal: \"\n \"unexpected uninitialized object\");\n object = newNull();\n }\n\n switch (state)\n {\n case st_eof:\n if (state_stack.size() > 1)\n {\n warn(context,\n QPDFExc(qpdf_e_damaged_pdf, input->getName(),\n object_description,\n input->getLastOffset(),\n \"parse error while reading object\"));\n }\n done = true;\n // In content stream mode, leave object uninitialized to\n // indicate EOF\n if (! content_stream)\n {\n object = newNull();\n }\n break;\n\n case st_dictionary:\n case st_array:\n setObjectDescriptionFromInput(\n object, context, object_description, input,\n input->getLastOffset());\n olist.push_back(object);\n break;\n\n case st_top:\n done = true;\n break;\n\n case st_start:\n break;\n\n case st_stop:\n if ((state_stack.size() < 2) || (olist_stack.size() < 2))\n {\n throw std::logic_error(\n \"QPDFObjectHandle::parseInternal: st_stop encountered\"\n \" with insufficient elements in stack\");\n }\n parser_state_e old_state = state_stack.back();\n state_stack.pop_back();\n if (old_state == st_array)\n {\n object = newArray(olist);\n setObjectDescriptionFromInput(\n object, context, object_description, input, offset);\n }\n else if (old_state == st_dictionary)\n {\n // Convert list to map. Alternating elements are keys.\n // Attempt to recover more or less gracefully from\n // invalid dictionaries.\n std::set names;\n for (std::vector::iterator iter =\n olist.begin();\n iter != olist.end(); ++iter)\n {\n if ((! (*iter).isIndirect()) && (*iter).isName())\n {\n names.insert((*iter).getName());\n }\n }\n\n std::map dict;\n int next_fake_key = 1;\n for (unsigned int i = 0; i < olist.size(); ++i)\n {\n QPDFObjectHandle key_obj = olist.at(i);\n QPDFObjectHandle val;\n if (key_obj.isIndirect() || (! key_obj.isName()))\n {\n bool found_fake = false;\n std::string candidate;\n while (! found_fake)\n {\n candidate =\n \"/QPDFFake\" +\n QUtil::int_to_string(next_fake_key++);\n found_fake = (names.count(candidate) == 0);\n QTC::TC(\"qpdf\", \"QPDFObjectHandle found fake\",\n (found_fake ? 0 : 1));\n }\n warn(context,\n QPDFExc(\n qpdf_e_damaged_pdf,\n input->getName(), object_description, offset,\n \"expected dictionary key but found\"\n \" non-name object; inserting key \" +\n candidate));\n val = key_obj;\n key_obj = newName(candidate);\n }\n else if (i + 1 >= olist.size())\n {\n QTC::TC(\"qpdf\", \"QPDFObjectHandle no val for last key\");\n warn(context,\n QPDFExc(\n qpdf_e_damaged_pdf,\n input->getName(), object_description, offset,\n \"dictionary ended prematurely; \"\n \"using null as value for last key\"));\n val = newNull();\n setObjectDescriptionFromInput(\n val, context, object_description, input, offset);\n }\n else\n {\n val = olist.at(++i);\n }\n dict[key_obj.getName()] = val;\n }\n object = newDictionary(dict);\n setObjectDescriptionFromInput(\n object, context, object_description, input, offset);\n }\n olist_stack.pop_back();\n offset_stack.pop_back();\n if (state_stack.back() == st_top)\n {\n done = true;\n }\n else\n {\n olist_stack.back().push_back(object);\n }\n }\n }\n\n setObjectDescriptionFromInput(\n object, context, object_description, input, offset);\n return object;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-674'], 'message': 'Limit depth of nesting in direct objects (fixes #202)\n\nThis fixes CVE-2018-9918.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info,\n ExceptionInfo *exception)\n{\n char\n page_geometry[MaxTextExtent];\n\n Image\n *image;\n\n MagickBooleanType\n logging;\n\n volatile int\n first_mng_object,\n object_id,\n term_chunk_found,\n skip_to_iend;\n\n volatile ssize_t\n image_count=0;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n offset;\n\n MngBox\n default_fb,\n fb,\n previous_fb;\n\n#if defined(MNG_INSERT_LAYERS)\n PixelPacket\n mng_background_color;\n#endif\n\n register unsigned char\n *p;\n\n register ssize_t\n i;\n\n size_t\n count;\n\n ssize_t\n loop_level;\n\n volatile short\n skipping_loop;\n\n#if defined(MNG_INSERT_LAYERS)\n unsigned int\n mandatory_back=0;\n#endif\n\n volatile unsigned int\n#ifdef MNG_OBJECT_BUFFERS\n mng_background_object=0,\n#endif\n mng_type=0; /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */\n\n size_t\n default_frame_timeout,\n frame_timeout,\n#if defined(MNG_INSERT_LAYERS)\n image_height,\n image_width,\n#endif\n length;\n\n /* These delays are all measured in image ticks_per_second,\n * not in MNG ticks_per_second\n */\n volatile size_t\n default_frame_delay,\n final_delay,\n final_image_delay,\n frame_delay,\n#if defined(MNG_INSERT_LAYERS)\n insert_layers,\n#endif\n mng_iterations=1,\n simplicity=0,\n subframe_height=0,\n subframe_width=0;\n\n previous_fb.top=0;\n previous_fb.bottom=0;\n previous_fb.left=0;\n previous_fb.right=0;\n default_fb.top=0;\n default_fb.bottom=0;\n default_fb.left=0;\n default_fb.right=0;\n\n logging=LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Enter ReadOneMNGImage()\");\n\n image=mng_info->image;\n\n if (LocaleCompare(image_info->magick,\"MNG\") == 0)\n {\n char\n magic_number[MaxTextExtent];\n\n /* Verify MNG signature. */\n count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number);\n if (memcmp(magic_number,\"\\212MNG\\r\\n\\032\\n\",8) != 0)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n\n /* Initialize some nonzero members of the MngInfo structure. */\n for (i=0; i < MNG_MAX_OBJECTS; i++)\n {\n mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX;\n mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX;\n }\n mng_info->exists[0]=MagickTrue;\n }\n\n skipping_loop=(-1);\n first_mng_object=MagickTrue;\n mng_type=0;\n#if defined(MNG_INSERT_LAYERS)\n insert_layers=MagickFalse; /* should be False when converting or mogrifying */\n#endif\n default_frame_delay=0;\n default_frame_timeout=0;\n frame_delay=0;\n final_delay=1;\n mng_info->ticks_per_second=1UL*image->ticks_per_second;\n object_id=0;\n skip_to_iend=MagickFalse;\n term_chunk_found=MagickFalse;\n mng_info->framing_mode=1;\n#if defined(MNG_INSERT_LAYERS)\n mandatory_back=MagickFalse;\n#endif\n#if defined(MNG_INSERT_LAYERS)\n mng_background_color=image->background_color;\n#endif\n default_fb=mng_info->frame;\n previous_fb=mng_info->frame;\n do\n {\n char\n type[MaxTextExtent];\n\n if (LocaleCompare(image_info->magick,\"MNG\") == 0)\n {\n unsigned char\n *chunk;\n\n /*\n Read a new chunk.\n */\n type[0]='\\0';\n (void) ConcatenateMagickString(type,\"errr\",MaxTextExtent);\n length=(size_t) ReadBlobMSBLong(image);\n count=(size_t) ReadBlob(image,4,(unsigned char *) type);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Reading MNG chunk type %c%c%c%c, length: %.20g\",\n type[0],type[1],type[2],type[3],(double) length);\n\n if (length > PNG_UINT_31_MAX)\n {\n status=MagickFalse;\n break;\n }\n\n if (count == 0)\n ThrowReaderException(CorruptImageError,\"CorruptImage\");\n\n p=NULL;\n chunk=(unsigned char *) NULL;\n\n if (length != 0)\n {\n if (length > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\n \"InsufficientImageDataInFile\");\n chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk));\n\n if (chunk == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n\n for (i=0; i < (ssize_t) length; i++)\n {\n int\n c;\n\n c=ReadBlobByte(image);\n if (c == EOF)\n {\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n ThrowReaderException(CorruptImageError,\n \"InsufficientImageDataInFile\");\n }\n chunk[i]=(unsigned char) c;\n }\n\n p=chunk;\n }\n\n (void) ReadBlobMSBLong(image); /* read crc word */\n\n#if !defined(JNG_SUPPORTED)\n if (memcmp(type,mng_JHDR,4) == 0)\n {\n skip_to_iend=MagickTrue;\n\n if (mng_info->jhdr_warning == 0)\n (void) ThrowMagickException(&image->exception,GetMagickModule(),\n CoderError,\"JNGCompressNotSupported\",\"`%s'\",image->filename);\n\n mng_info->jhdr_warning++;\n }\n#endif\n if (memcmp(type,mng_DHDR,4) == 0)\n {\n skip_to_iend=MagickTrue;\n\n if (mng_info->dhdr_warning == 0)\n (void) ThrowMagickException(&image->exception,GetMagickModule(),\n CoderError,\"DeltaPNGNotSupported\",\"`%s'\",image->filename);\n\n mng_info->dhdr_warning++;\n }\n if (memcmp(type,mng_MEND,4) == 0)\n {\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n break;\n }\n\n if (skip_to_iend)\n {\n if (memcmp(type,mng_IEND,4) == 0)\n skip_to_iend=MagickFalse;\n\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Skip to IEND.\");\n\n continue;\n }\n\n if (memcmp(type,mng_MHDR,4) == 0)\n {\n if (length != 28)\n {\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n ThrowReaderException(CorruptImageError,\"CorruptImage\");\n }\n\n mng_info->mng_width=(unsigned long)mng_get_long(p);\n mng_info->mng_height=(unsigned long)mng_get_long(&p[4]);\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" MNG width: %.20g\",(double) mng_info->mng_width);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" MNG height: %.20g\",(double) mng_info->mng_height);\n }\n\n p+=8;\n mng_info->ticks_per_second=(size_t) mng_get_long(p);\n\n if (mng_info->ticks_per_second == 0)\n default_frame_delay=0;\n\n else\n default_frame_delay=1UL*image->ticks_per_second/\n mng_info->ticks_per_second;\n\n frame_delay=default_frame_delay;\n simplicity=0;\n\n /* Skip nominal layer count, frame count, and play time */\n p+=16;\n simplicity=(size_t) mng_get_long(p);\n\n mng_type=1; /* Full MNG */\n\n if ((simplicity != 0) && ((simplicity | 11) == 11))\n mng_type=2; /* LC */\n\n if ((simplicity != 0) && ((simplicity | 9) == 9))\n mng_type=3; /* VLC */\n\n#if defined(MNG_INSERT_LAYERS)\n if (mng_type != 3)\n insert_layers=MagickTrue;\n#endif\n if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)\n {\n /* Allocate next image structure. */\n AcquireNextImage(image_info,image);\n\n if (GetNextImageInList(image) == (Image *) NULL)\n return(DestroyImageList(image));\n\n image=SyncNextImageInList(image);\n mng_info->image=image;\n }\n\n if ((mng_info->mng_width > 65535L) ||\n (mng_info->mng_height > 65535L))\n {\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n ThrowReaderException(ImageError,\"WidthOrHeightExceedsLimit\");\n }\n\n (void) FormatLocaleString(page_geometry,MaxTextExtent,\n \"%.20gx%.20g+0+0\",(double) mng_info->mng_width,(double)\n mng_info->mng_height);\n\n mng_info->frame.left=0;\n mng_info->frame.right=(ssize_t) mng_info->mng_width;\n mng_info->frame.top=0;\n mng_info->frame.bottom=(ssize_t) mng_info->mng_height;\n mng_info->clip=default_fb=previous_fb=mng_info->frame;\n\n for (i=0; i < MNG_MAX_OBJECTS; i++)\n mng_info->object_clip[i]=mng_info->frame;\n\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n continue;\n }\n\n if (memcmp(type,mng_TERM,4) == 0)\n {\n int\n repeat=0;\n\n if (length != 0)\n repeat=p[0];\n\n if (repeat == 3 && length > 8)\n {\n final_delay=(png_uint_32) mng_get_long(&p[2]);\n mng_iterations=(png_uint_32) mng_get_long(&p[6]);\n\n if (mng_iterations == PNG_UINT_31_MAX)\n mng_iterations=0;\n\n image->iterations=mng_iterations;\n term_chunk_found=MagickTrue;\n }\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" repeat=%d, final_delay=%.20g, iterations=%.20g\",\n repeat,(double) final_delay, (double) image->iterations);\n }\n\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n continue;\n }\n if (memcmp(type,mng_DEFI,4) == 0)\n {\n if (mng_type == 3)\n {\n (void) ThrowMagickException(&image->exception,GetMagickModule(),\n CoderError,\"DEFI chunk found in MNG-VLC datastream\",\"`%s'\",\n image->filename);\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n continue;\n }\n\n if (length < 2)\n {\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n ThrowReaderException(CorruptImageError,\"CorruptImage\");\n }\n\n object_id=((unsigned int) p[0] << 8) | (unsigned int) p[1];\n\n if (mng_type == 2 && object_id != 0)\n (void) ThrowMagickException(&image->exception,\n GetMagickModule(),\n CoderError,\"Nonzero object_id in MNG-LC datastream\",\n \"`%s'\", image->filename);\n\n if (object_id > MNG_MAX_OBJECTS)\n {\n /*\n Instead of using a warning we should allocate a larger\n MngInfo structure and continue.\n */\n (void) ThrowMagickException(&image->exception,\n GetMagickModule(), CoderError,\n \"object id too large\",\"`%s'\",image->filename);\n object_id=MNG_MAX_OBJECTS;\n }\n\n if (mng_info->exists[object_id])\n if (mng_info->frozen[object_id])\n {\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n (void) ThrowMagickException(&image->exception,\n GetMagickModule(),CoderError,\n \"DEFI cannot redefine a frozen MNG object\",\"`%s'\",\n image->filename);\n continue;\n }\n\n mng_info->exists[object_id]=MagickTrue;\n\n if (length > 2)\n mng_info->invisible[object_id]=p[2];\n\n /*\n Extract object offset info.\n */\n if (length > 11)\n {\n mng_info->x_off[object_id]=(ssize_t) mng_get_long(&p[4]);\n mng_info->y_off[object_id]=(ssize_t) mng_get_long(&p[8]);\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" x_off[%d]: %.20g, y_off[%d]: %.20g\",\n object_id,(double) mng_info->x_off[object_id],\n object_id,(double) mng_info->y_off[object_id]);\n }\n }\n\n /*\n Extract object clipping info.\n */\n\n if (length > 27)\n mng_info->object_clip[object_id]=\n mng_read_box(mng_info->frame,0, &p[12]);\n\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n continue;\n }\n if (memcmp(type,mng_bKGD,4) == 0)\n {\n mng_info->have_global_bkgd=MagickFalse;\n\n if (length > 5)\n {\n mng_info->mng_global_bkgd.red=\n ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1]));\n\n mng_info->mng_global_bkgd.green=\n ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3]));\n\n mng_info->mng_global_bkgd.blue=\n ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5]));\n\n mng_info->have_global_bkgd=MagickTrue;\n }\n\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n continue;\n }\n if (memcmp(type,mng_BACK,4) == 0)\n {\n#if defined(MNG_INSERT_LAYERS)\n if (length > 6)\n mandatory_back=p[6];\n\n else\n mandatory_back=0;\n\n if (mandatory_back && length > 5)\n {\n mng_background_color.red=\n ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1]));\n\n mng_background_color.green=\n ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3]));\n\n mng_background_color.blue=\n ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5]));\n\n mng_background_color.opacity=OpaqueOpacity;\n }\n\n#ifdef MNG_OBJECT_BUFFERS\n if (length > 8)\n mng_background_object=(p[7] << 8) | p[8];\n#endif\n#endif\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n continue;\n }\n\n if (memcmp(type,mng_PLTE,4) == 0)\n {\n /* Read global PLTE. */\n\n if (length && (length < 769))\n {\n if (mng_info->global_plte == (png_colorp) NULL)\n mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256,\n sizeof(*mng_info->global_plte));\n\n if (mng_info->global_plte == (png_colorp) NULL)\n {\n mng_info->global_plte_length=0;\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n mng_info=MngInfoFreeStruct(mng_info);\n ThrowReaderException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n\n for (i=0; i < (ssize_t) (length/3); i++)\n {\n mng_info->global_plte[i].red=p[3*i];\n mng_info->global_plte[i].green=p[3*i+1];\n mng_info->global_plte[i].blue=p[3*i+2];\n }\n\n mng_info->global_plte_length=(unsigned int) (length/3);\n }\n#ifdef MNG_LOOSE\n for ( ; i < 256; i++)\n {\n mng_info->global_plte[i].red=i;\n mng_info->global_plte[i].green=i;\n mng_info->global_plte[i].blue=i;\n }\n\n if (length != 0)\n mng_info->global_plte_length=256;\n#endif\n else\n mng_info->global_plte_length=0;\n\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n continue;\n }\n\n if (memcmp(type,mng_tRNS,4) == 0)\n {\n /* read global tRNS */\n\n if (length > 0 && length < 257)\n for (i=0; i < (ssize_t) length; i++)\n mng_info->global_trns[i]=p[i];\n\n#ifdef MNG_LOOSE\n for ( ; i < 256; i++)\n mng_info->global_trns[i]=255;\n#endif\n mng_info->global_trns_length=(unsigned int) length;\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n continue;\n }\n if (memcmp(type,mng_gAMA,4) == 0)\n {\n if (length == 4)\n {\n ssize_t\n igamma;\n\n igamma=mng_get_long(p);\n mng_info->global_gamma=((float) igamma)*0.00001;\n mng_info->have_global_gama=MagickTrue;\n }\n\n else\n mng_info->have_global_gama=MagickFalse;\n\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n continue;\n }\n\n if (memcmp(type,mng_cHRM,4) == 0)\n {\n /* Read global cHRM */\n\n if (length == 32)\n {\n mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p);\n mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]);\n mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]);\n mng_info->global_chrm.red_primary.y=0.00001*\n mng_get_long(&p[12]);\n mng_info->global_chrm.green_primary.x=0.00001*\n mng_get_long(&p[16]);\n mng_info->global_chrm.green_primary.y=0.00001*\n mng_get_long(&p[20]);\n mng_info->global_chrm.blue_primary.x=0.00001*\n mng_get_long(&p[24]);\n mng_info->global_chrm.blue_primary.y=0.00001*\n mng_get_long(&p[28]);\n mng_info->have_global_chrm=MagickTrue;\n }\n else\n mng_info->have_global_chrm=MagickFalse;\n\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n continue;\n }\n\n if (memcmp(type,mng_sRGB,4) == 0)\n {\n /*\n Read global sRGB.\n */\n if (length != 0)\n {\n mng_info->global_srgb_intent=\n Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]);\n mng_info->have_global_srgb=MagickTrue;\n }\n else\n mng_info->have_global_srgb=MagickFalse;\n\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n continue;\n }\n\n if (memcmp(type,mng_iCCP,4) == 0)\n {\n /* To do: */\n\n /*\n Read global iCCP.\n */\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n continue;\n }\n\n if (memcmp(type,mng_FRAM,4) == 0)\n {\n if (mng_type == 3)\n (void) ThrowMagickException(&image->exception,GetMagickModule(),\n CoderError,\"FRAM chunk found in MNG-VLC datastream\",\"`%s'\",\n image->filename);\n\n if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4))\n image->delay=frame_delay;\n\n frame_delay=default_frame_delay;\n frame_timeout=default_frame_timeout;\n fb=default_fb;\n\n if (length > 0)\n if (p[0])\n mng_info->framing_mode=p[0];\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Framing_mode=%d\",mng_info->framing_mode);\n\n if (length > 6)\n {\n /* Note the delay and frame clipping boundaries. */\n\n p++; /* framing mode */\n\n while (((p-chunk) < (long) length) && *p)\n p++; /* frame name */\n\n p++; /* frame name terminator */\n\n if ((p-chunk) < (ssize_t) (length-4))\n {\n int\n change_delay,\n change_timeout,\n change_clipping;\n\n change_delay=(*p++);\n change_timeout=(*p++);\n change_clipping=(*p++);\n p++; /* change_sync */\n\n if (change_delay && ((p-chunk) < (ssize_t) (length-4)))\n {\n frame_delay=1UL*image->ticks_per_second*\n mng_get_long(p);\n\n if (mng_info->ticks_per_second != 0)\n frame_delay/=mng_info->ticks_per_second;\n\n else\n frame_delay=PNG_UINT_31_MAX;\n\n if (change_delay == 2)\n default_frame_delay=frame_delay;\n\n p+=4;\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Framing_delay=%.20g\",(double) frame_delay);\n }\n\n if (change_timeout && ((p-chunk) < (ssize_t) (length-4)))\n {\n frame_timeout=1UL*image->ticks_per_second*\n mng_get_long(p);\n\n if (mng_info->ticks_per_second != 0)\n frame_timeout/=mng_info->ticks_per_second;\n\n else\n frame_timeout=PNG_UINT_31_MAX;\n\n if (change_timeout == 2)\n default_frame_timeout=frame_timeout;\n\n p+=4;\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Framing_timeout=%.20g\",(double) frame_timeout);\n }\n\n if (change_clipping && ((p-chunk) < (ssize_t) (length-16)))\n {\n fb=mng_read_box(previous_fb,(char) p[0],&p[1]);\n p+=16;\n previous_fb=fb;\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g\",\n (double) fb.left,(double) fb.right,(double) fb.top,\n (double) fb.bottom);\n\n if (change_clipping == 2)\n default_fb=fb;\n }\n }\n }\n mng_info->clip=fb;\n mng_info->clip=mng_minimum_box(fb,mng_info->frame);\n\n subframe_width=(size_t) (mng_info->clip.right\n -mng_info->clip.left);\n\n subframe_height=(size_t) (mng_info->clip.bottom\n -mng_info->clip.top);\n /*\n Insert a background layer behind the frame if framing_mode is 4.\n */\n#if defined(MNG_INSERT_LAYERS)\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" subframe_width=%.20g, subframe_height=%.20g\",(double)\n subframe_width,(double) subframe_height);\n\n if (insert_layers && (mng_info->framing_mode == 4) &&\n (subframe_width) && (subframe_height))\n {\n /* Allocate next image structure. */\n if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)\n {\n AcquireNextImage(image_info,image);\n\n if (GetNextImageInList(image) == (Image *) NULL)\n return(DestroyImageList(image));\n\n image=SyncNextImageInList(image);\n }\n\n mng_info->image=image;\n\n if (term_chunk_found)\n {\n image->start_loop=MagickTrue;\n image->iterations=mng_iterations;\n term_chunk_found=MagickFalse;\n }\n\n else\n image->start_loop=MagickFalse;\n\n image->columns=subframe_width;\n image->rows=subframe_height;\n image->page.width=subframe_width;\n image->page.height=subframe_height;\n image->page.x=mng_info->clip.left;\n image->page.y=mng_info->clip.top;\n image->background_color=mng_background_color;\n image->matte=MagickFalse;\n image->delay=0;\n (void) SetImageBackgroundColor(image);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\",\n (double) mng_info->clip.left,(double) mng_info->clip.right,\n (double) mng_info->clip.top,(double) mng_info->clip.bottom);\n }\n#endif\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n continue;\n }\n if (memcmp(type,mng_CLIP,4) == 0)\n {\n unsigned int\n first_object,\n last_object;\n\n /*\n Read CLIP.\n */\n if (length > 3)\n {\n first_object=(p[0] << 8) | p[1];\n last_object=(p[2] << 8) | p[3];\n p+=4;\n\n for (i=(int) first_object; i <= (int) last_object; i++)\n {\n if ((i < 0) || (i >= MNG_MAX_OBJECTS))\n continue;\n if (mng_info->exists[i] && !mng_info->frozen[i])\n {\n MngBox\n box;\n\n box=mng_info->object_clip[i];\n if ((p-chunk) < (ssize_t) (length-17))\n mng_info->object_clip[i]=\n mng_read_box(box,(char) p[0],&p[1]);\n }\n }\n\n }\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n continue;\n }\n if (memcmp(type,mng_SAVE,4) == 0)\n {\n for (i=1; i < MNG_MAX_OBJECTS; i++)\n if (mng_info->exists[i])\n {\n mng_info->frozen[i]=MagickTrue;\n#ifdef MNG_OBJECT_BUFFERS\n if (mng_info->ob[i] != (MngBuffer *) NULL)\n mng_info->ob[i]->frozen=MagickTrue;\n#endif\n }\n\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n continue;\n }\n\n if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0))\n {\n /* Read DISC or SEEK. */\n\n if ((length == 0) || !memcmp(type,mng_SEEK,4))\n {\n for (i=1; i < MNG_MAX_OBJECTS; i++)\n MngInfoDiscardObject(mng_info,i);\n }\n\n else\n {\n register ssize_t\n j;\n\n for (j=1; j < (ssize_t) length; j+=2)\n {\n i=p[j-1] << 8 | p[j];\n MngInfoDiscardObject(mng_info,i);\n }\n }\n\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n continue;\n }\n\n if (memcmp(type,mng_MOVE,4) == 0)\n {\n size_t\n first_object,\n last_object;\n\n /* read MOVE */\n\n if (length > 3)\n {\n first_object=(p[0] << 8) | p[1];\n last_object=(p[2] << 8) | p[3];\n p+=4;\n\n for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++)\n {\n if ((i < 0) || (i >= MNG_MAX_OBJECTS))\n continue;\n if (mng_info->exists[i] && !mng_info->frozen[i] &&\n (p-chunk) < (ssize_t) (length-8))\n {\n MngPair\n new_pair;\n\n MngPair\n old_pair;\n\n old_pair.a=mng_info->x_off[i];\n old_pair.b=mng_info->y_off[i];\n new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]);\n mng_info->x_off[i]=new_pair.a;\n mng_info->y_off[i]=new_pair.b;\n }\n }\n }\n\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n continue;\n }\n\n if (memcmp(type,mng_LOOP,4) == 0)\n {\n ssize_t loop_iters=1;\n if (length > 4)\n {\n loop_level=chunk[0];\n mng_info->loop_active[loop_level]=1; /* mark loop active */\n\n /* Record starting point. */\n loop_iters=mng_get_long(&chunk[1]);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" LOOP level %.20g has %.20g iterations \",\n (double) loop_level, (double) loop_iters);\n\n if (loop_iters == 0)\n skipping_loop=loop_level;\n\n else\n {\n mng_info->loop_jump[loop_level]=TellBlob(image);\n mng_info->loop_count[loop_level]=loop_iters;\n }\n\n mng_info->loop_iteration[loop_level]=0;\n }\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n continue;\n }\n\n if (memcmp(type,mng_ENDL,4) == 0)\n {\n if (length > 0)\n {\n loop_level=chunk[0];\n\n if (skipping_loop > 0)\n {\n if (skipping_loop == loop_level)\n {\n /*\n Found end of zero-iteration loop.\n */\n skipping_loop=(-1);\n mng_info->loop_active[loop_level]=0;\n }\n }\n\n else\n {\n if (mng_info->loop_active[loop_level] == 1)\n {\n mng_info->loop_count[loop_level]--;\n mng_info->loop_iteration[loop_level]++;\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" ENDL: LOOP level %.20g has %.20g remaining iters \",\n (double) loop_level,(double)\n mng_info->loop_count[loop_level]);\n\n if (mng_info->loop_count[loop_level] != 0)\n {\n offset=SeekBlob(image,\n mng_info->loop_jump[loop_level], SEEK_SET);\n\n if (offset < 0)\n {\n chunk=(unsigned char *) RelinquishMagickMemory(\n chunk);\n ThrowReaderException(CorruptImageError,\n \"ImproperImageHeader\");\n }\n }\n\n else\n {\n short\n last_level;\n\n /*\n Finished loop.\n */\n mng_info->loop_active[loop_level]=0;\n last_level=(-1);\n for (i=0; i < loop_level; i++)\n if (mng_info->loop_active[i] == 1)\n last_level=(short) i;\n loop_level=last_level;\n }\n }\n }\n }\n\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n continue;\n }\n\n if (memcmp(type,mng_CLON,4) == 0)\n {\n if (mng_info->clon_warning == 0)\n (void) ThrowMagickException(&image->exception,GetMagickModule(),\n CoderError,\"CLON is not implemented yet\",\"`%s'\",\n image->filename);\n\n mng_info->clon_warning++;\n }\n\n if (memcmp(type,mng_MAGN,4) == 0)\n {\n png_uint_16\n magn_first,\n magn_last,\n magn_mb,\n magn_ml,\n magn_mr,\n magn_mt,\n magn_mx,\n magn_my,\n magn_methx,\n magn_methy;\n\n if (length > 1)\n magn_first=(p[0] << 8) | p[1];\n\n else\n magn_first=0;\n\n if (length > 3)\n magn_last=(p[2] << 8) | p[3];\n\n else\n magn_last=magn_first;\n#ifndef MNG_OBJECT_BUFFERS\n if (magn_first || magn_last)\n if (mng_info->magn_warning == 0)\n {\n (void) ThrowMagickException(&image->exception,\n GetMagickModule(),CoderError,\n \"MAGN is not implemented yet for nonzero objects\",\n \"`%s'\",image->filename);\n\n mng_info->magn_warning++;\n }\n#endif\n if (length > 4)\n magn_methx=p[4];\n\n else\n magn_methx=0;\n\n if (length > 6)\n magn_mx=(p[5] << 8) | p[6];\n\n else\n magn_mx=1;\n\n if (magn_mx == 0)\n magn_mx=1;\n\n if (length > 8)\n magn_my=(p[7] << 8) | p[8];\n\n else\n magn_my=magn_mx;\n\n if (magn_my == 0)\n magn_my=1;\n\n if (length > 10)\n magn_ml=(p[9] << 8) | p[10];\n\n else\n magn_ml=magn_mx;\n\n if (magn_ml == 0)\n magn_ml=1;\n\n if (length > 12)\n magn_mr=(p[11] << 8) | p[12];\n\n else\n magn_mr=magn_mx;\n\n if (magn_mr == 0)\n magn_mr=1;\n\n if (length > 14)\n magn_mt=(p[13] << 8) | p[14];\n\n else\n magn_mt=magn_my;\n\n if (magn_mt == 0)\n magn_mt=1;\n\n if (length > 16)\n magn_mb=(p[15] << 8) | p[16];\n\n else\n magn_mb=magn_my;\n\n if (magn_mb == 0)\n magn_mb=1;\n\n if (length > 17)\n magn_methy=p[17];\n\n else\n magn_methy=magn_methx;\n\n\n if (magn_methx > 5 || magn_methy > 5)\n if (mng_info->magn_warning == 0)\n {\n (void) ThrowMagickException(&image->exception,\n GetMagickModule(),CoderError,\n \"Unknown MAGN method in MNG datastream\",\"`%s'\",\n image->filename);\n\n mng_info->magn_warning++;\n }\n#ifdef MNG_OBJECT_BUFFERS\n /* Magnify existing objects in the range magn_first to magn_last */\n#endif\n if (magn_first == 0 || magn_last == 0)\n {\n /* Save the magnification factors for object 0 */\n mng_info->magn_mb=magn_mb;\n mng_info->magn_ml=magn_ml;\n mng_info->magn_mr=magn_mr;\n mng_info->magn_mt=magn_mt;\n mng_info->magn_mx=magn_mx;\n mng_info->magn_my=magn_my;\n mng_info->magn_methx=magn_methx;\n mng_info->magn_methy=magn_methy;\n }\n }\n\n if (memcmp(type,mng_PAST,4) == 0)\n {\n if (mng_info->past_warning == 0)\n (void) ThrowMagickException(&image->exception,GetMagickModule(),\n CoderError,\"PAST is not implemented yet\",\"`%s'\",\n image->filename);\n\n mng_info->past_warning++;\n }\n\n if (memcmp(type,mng_SHOW,4) == 0)\n {\n if (mng_info->show_warning == 0)\n (void) ThrowMagickException(&image->exception,GetMagickModule(),\n CoderError,\"SHOW is not implemented yet\",\"`%s'\",\n image->filename);\n\n mng_info->show_warning++;\n }\n\n if (memcmp(type,mng_sBIT,4) == 0)\n {\n if (length < 4)\n mng_info->have_global_sbit=MagickFalse;\n\n else\n {\n mng_info->global_sbit.gray=p[0];\n mng_info->global_sbit.red=p[0];\n mng_info->global_sbit.green=p[1];\n mng_info->global_sbit.blue=p[2];\n mng_info->global_sbit.alpha=p[3];\n mng_info->have_global_sbit=MagickTrue;\n }\n }\n if (memcmp(type,mng_pHYs,4) == 0)\n {\n if (length > 8)\n {\n mng_info->global_x_pixels_per_unit=\n (size_t) mng_get_long(p);\n mng_info->global_y_pixels_per_unit=\n (size_t) mng_get_long(&p[4]);\n mng_info->global_phys_unit_type=p[8];\n mng_info->have_global_phys=MagickTrue;\n }\n\n else\n mng_info->have_global_phys=MagickFalse;\n }\n if (memcmp(type,mng_pHYg,4) == 0)\n {\n if (mng_info->phyg_warning == 0)\n (void) ThrowMagickException(&image->exception,GetMagickModule(),\n CoderError,\"pHYg is not implemented.\",\"`%s'\",image->filename);\n\n mng_info->phyg_warning++;\n }\n if (memcmp(type,mng_BASI,4) == 0)\n {\n skip_to_iend=MagickTrue;\n\n if (mng_info->basi_warning == 0)\n (void) ThrowMagickException(&image->exception,GetMagickModule(),\n CoderError,\"BASI is not implemented yet\",\"`%s'\",\n image->filename);\n\n mng_info->basi_warning++;\n#ifdef MNG_BASI_SUPPORTED\n if (length > 11)\n {\n basi_width=(unsigned long) mng_get_long(p);\n basi_width=(unsigned long) mng_get_long(&p[4]);\n basi_color_type=p[8];\n basi_compression_method=p[9];\n basi_filter_type=p[10];\n basi_interlace_method=p[11];\n }\n if (length > 13)\n basi_red=(png_uint_32) p[12] << 8) & png_uint_32) p[13];\n\n else\n basi_red=0;\n\n if (length > 15)\n basi_green=(png_uint_32) p[14] << 8) & png_uint_32) p[15];\n\n else\n basi_green=0;\n\n if (length > 17)\n basi_blue=(png_uint_32) p[16] << 8) & png_uint_32) p[17];\n\n else\n basi_blue=0;\n\n if (length > 19)\n basi_alpha=(png_uint_32) p[18] << 8) & png_uint_32) p[19];\n\n else\n {\n if (basi_sample_depth == 16)\n basi_alpha=65535L;\n else\n basi_alpha=255;\n }\n\n if (length > 20)\n basi_viewable=p[20];\n\n else\n basi_viewable=0;\n\n#endif\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n continue;\n }\n\n if (memcmp(type,mng_IHDR,4)\n#if defined(JNG_SUPPORTED)\n && memcmp(type,mng_JHDR,4)\n#endif\n )\n {\n /* Not an IHDR or JHDR chunk */\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n continue;\n }\n/* Process IHDR */\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Processing %c%c%c%c chunk\",type[0],type[1],type[2],type[3]);\n\n mng_info->exists[object_id]=MagickTrue;\n mng_info->viewable[object_id]=MagickTrue;\n\n if (mng_info->invisible[object_id])\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Skipping invisible object\");\n\n skip_to_iend=MagickTrue;\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n continue;\n }\n#if defined(MNG_INSERT_LAYERS)\n if (length < 8)\n {\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n\n image_width=(size_t) mng_get_long(p);\n image_height=(size_t) mng_get_long(&p[4]);\n#endif\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n /*\n Insert a transparent background layer behind the entire animation\n if it is not full screen.\n */\n#if defined(MNG_INSERT_LAYERS)\n if (insert_layers && mng_type && first_mng_object)\n {\n if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) ||\n (image_width < mng_info->mng_width) ||\n (mng_info->clip.right < (ssize_t) mng_info->mng_width) ||\n (image_height < mng_info->mng_height) ||\n (mng_info->clip.bottom < (ssize_t) mng_info->mng_height))\n {\n if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)\n {\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image);\n\n if (GetNextImageInList(image) == (Image *) NULL)\n return(DestroyImageList(image));\n\n image=SyncNextImageInList(image);\n }\n mng_info->image=image;\n\n if (term_chunk_found)\n {\n image->start_loop=MagickTrue;\n image->iterations=mng_iterations;\n term_chunk_found=MagickFalse;\n }\n\n else\n image->start_loop=MagickFalse;\n\n /* Make a background rectangle. */\n\n image->delay=0;\n image->columns=mng_info->mng_width;\n image->rows=mng_info->mng_height;\n image->page.width=mng_info->mng_width;\n image->page.height=mng_info->mng_height;\n image->page.x=0;\n image->page.y=0;\n image->background_color=mng_background_color;\n (void) SetImageBackgroundColor(image);\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Inserted transparent background layer, W=%.20g, H=%.20g\",\n (double) mng_info->mng_width,(double) mng_info->mng_height);\n }\n }\n /*\n Insert a background layer behind the upcoming image if\n framing_mode is 3, and we haven't already inserted one.\n */\n if (insert_layers && (mng_info->framing_mode == 3) &&\n (subframe_width) && (subframe_height) && (simplicity == 0 ||\n (simplicity & 0x08)))\n {\n if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)\n {\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image);\n\n if (GetNextImageInList(image) == (Image *) NULL)\n return(DestroyImageList(image));\n\n image=SyncNextImageInList(image);\n }\n\n mng_info->image=image;\n\n if (term_chunk_found)\n {\n image->start_loop=MagickTrue;\n image->iterations=mng_iterations;\n term_chunk_found=MagickFalse;\n }\n\n else\n image->start_loop=MagickFalse;\n\n image->delay=0;\n image->columns=subframe_width;\n image->rows=subframe_height;\n image->page.width=subframe_width;\n image->page.height=subframe_height;\n image->page.x=mng_info->clip.left;\n image->page.y=mng_info->clip.top;\n image->background_color=mng_background_color;\n image->matte=MagickFalse;\n (void) SetImageBackgroundColor(image);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\",\n (double) mng_info->clip.left,(double) mng_info->clip.right,\n (double) mng_info->clip.top,(double) mng_info->clip.bottom);\n }\n#endif /* MNG_INSERT_LAYERS */\n first_mng_object=MagickFalse;\n\n if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)\n {\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image);\n\n if (GetNextImageInList(image) == (Image *) NULL)\n return(DestroyImageList(image));\n\n image=SyncNextImageInList(image);\n }\n mng_info->image=image;\n status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n GetBlobSize(image));\n\n if (status == MagickFalse)\n break;\n\n if (term_chunk_found)\n {\n image->start_loop=MagickTrue;\n term_chunk_found=MagickFalse;\n }\n\n else\n image->start_loop=MagickFalse;\n\n if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3)\n {\n image->delay=frame_delay;\n frame_delay=default_frame_delay;\n }\n\n else\n image->delay=0;\n\n image->page.width=mng_info->mng_width;\n image->page.height=mng_info->mng_height;\n image->page.x=mng_info->x_off[object_id];\n image->page.y=mng_info->y_off[object_id];\n image->iterations=mng_iterations;\n\n /*\n Seek back to the beginning of the IHDR or JHDR chunk's length field.\n */\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Seeking back to beginning of %c%c%c%c chunk\",type[0],type[1],\n type[2],type[3]);\n\n offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR);\n\n if (offset < 0)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n\n mng_info->image=image;\n mng_info->mng_type=mng_type;\n mng_info->object_id=object_id;\n\n if (memcmp(type,mng_IHDR,4) == 0)\n image=ReadOnePNGImage(mng_info,image_info,exception);\n\n#if defined(JNG_SUPPORTED)\n else\n image=ReadOneJNGImage(mng_info,image_info,exception);\n#endif\n\n if (image == (Image *) NULL)\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"exit ReadJNGImage() with error\");\n\n return((Image *) NULL);\n }\n\n if (image->columns == 0 || image->rows == 0)\n {\n (void) CloseBlob(image);\n return(DestroyImageList(image));\n }\n\n mng_info->image=image;\n\n if (mng_type)\n {\n MngBox\n crop_box;\n\n if (mng_info->magn_methx || mng_info->magn_methy)\n {\n png_uint_32\n magnified_height,\n magnified_width;\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Processing MNG MAGN chunk\");\n\n if (mng_info->magn_methx == 1)\n {\n magnified_width=mng_info->magn_ml;\n\n if (image->columns > 1)\n magnified_width += mng_info->magn_mr;\n\n if (image->columns > 2)\n magnified_width += (png_uint_32)\n ((image->columns-2)*(mng_info->magn_mx));\n }\n\n else\n {\n magnified_width=(png_uint_32) image->columns;\n\n if (image->columns > 1)\n magnified_width += mng_info->magn_ml-1;\n\n if (image->columns > 2)\n magnified_width += mng_info->magn_mr-1;\n\n if (image->columns > 3)\n magnified_width += (png_uint_32)\n ((image->columns-3)*(mng_info->magn_mx-1));\n }\n\n if (mng_info->magn_methy == 1)\n {\n magnified_height=mng_info->magn_mt;\n\n if (image->rows > 1)\n magnified_height += mng_info->magn_mb;\n\n if (image->rows > 2)\n magnified_height += (png_uint_32)\n ((image->rows-2)*(mng_info->magn_my));\n }\n\n else\n {\n magnified_height=(png_uint_32) image->rows;\n\n if (image->rows > 1)\n magnified_height += mng_info->magn_mt-1;\n\n if (image->rows > 2)\n magnified_height += mng_info->magn_mb-1;\n\n if (image->rows > 3)\n magnified_height += (png_uint_32)\n ((image->rows-3)*(mng_info->magn_my-1));\n }\n\n if (magnified_height > image->rows ||\n magnified_width > image->columns)\n {\n Image\n *large_image;\n\n int\n yy;\n\n ssize_t\n m,\n y;\n\n register ssize_t\n x;\n\n register PixelPacket\n *n,\n *q;\n\n PixelPacket\n *next,\n *prev;\n\n png_uint_16\n magn_methx,\n magn_methy;\n\n /* Allocate next image structure. */\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Allocate magnified image\");\n\n AcquireNextImage(image_info,image);\n\n if (GetNextImageInList(image) == (Image *) NULL)\n return(DestroyImageList(image));\n\n large_image=SyncNextImageInList(image);\n\n large_image->columns=magnified_width;\n large_image->rows=magnified_height;\n\n magn_methx=mng_info->magn_methx;\n magn_methy=mng_info->magn_methy;\n\n#if (MAGICKCORE_QUANTUM_DEPTH > 16)\n#define QM unsigned short\n if (magn_methx != 1 || magn_methy != 1)\n {\n /*\n Scale pixels to unsigned shorts to prevent\n overflow of intermediate values of interpolations\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=GetAuthenticPixels(image,0,y,image->columns,1,\n exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=(ssize_t) image->columns-1; x >= 0; x--)\n {\n SetPixelRed(q,ScaleQuantumToShort(\n GetPixelRed(q)));\n SetPixelGreen(q,ScaleQuantumToShort(\n GetPixelGreen(q)));\n SetPixelBlue(q,ScaleQuantumToShort(\n GetPixelBlue(q)));\n SetPixelOpacity(q,ScaleQuantumToShort(\n GetPixelOpacity(q)));\n q++;\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n }\n#else\n#define QM Quantum\n#endif\n\n if (image->matte != MagickFalse)\n (void) SetImageBackgroundColor(large_image);\n\n else\n {\n large_image->background_color.opacity=OpaqueOpacity;\n (void) SetImageBackgroundColor(large_image);\n\n if (magn_methx == 4)\n magn_methx=2;\n\n if (magn_methx == 5)\n magn_methx=3;\n\n if (magn_methy == 4)\n magn_methy=2;\n\n if (magn_methy == 5)\n magn_methy=3;\n }\n\n /* magnify the rows into the right side of the large image */\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Magnify the rows to %.20g\",(double) large_image->rows);\n m=(ssize_t) mng_info->magn_mt;\n yy=0;\n length=(size_t) image->columns;\n next=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*next));\n prev=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*prev));\n\n if ((prev == (PixelPacket *) NULL) ||\n (next == (PixelPacket *) NULL))\n {\n if (prev != (PixelPacket *) NULL)\n prev=(PixelPacket *) RelinquishMagickMemory(prev);\n if (next != (PixelPacket *) NULL)\n next=(PixelPacket *) RelinquishMagickMemory(next);\n image=DestroyImageList(image);\n ThrowReaderException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n\n n=GetAuthenticPixels(image,0,0,image->columns,1,exception);\n (void) memcpy(next,n,length);\n\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n if (y == 0)\n m=(ssize_t) mng_info->magn_mt;\n\n else if (magn_methy > 1 && y == (ssize_t) image->rows-2)\n m=(ssize_t) mng_info->magn_mb;\n\n else if (magn_methy <= 1 && y == (ssize_t) image->rows-1)\n m=(ssize_t) mng_info->magn_mb;\n\n else if (magn_methy > 1 && y == (ssize_t) image->rows-1)\n m=1;\n\n else\n m=(ssize_t) mng_info->magn_my;\n\n n=prev;\n prev=next;\n next=n;\n\n if (y < (ssize_t) image->rows-1)\n {\n n=GetAuthenticPixels(image,0,y+1,image->columns,1,\n exception);\n (void) memcpy(next,n,length);\n }\n\n for (i=0; i < m; i++, yy++)\n {\n register PixelPacket\n *pixels;\n\n assert(yy < (ssize_t) large_image->rows);\n pixels=prev;\n n=next;\n q=GetAuthenticPixels(large_image,0,yy,large_image->columns,\n 1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n q+=(large_image->columns-image->columns);\n\n for (x=(ssize_t) image->columns-1; x >= 0; x--)\n {\n /* To do: get color as function of indexes[x] */\n /*\n if (image->storage_class == PseudoClass)\n {\n }\n */\n\n if (magn_methy <= 1)\n {\n /* replicate previous */\n SetPixelRGBO(q,(pixels));\n }\n\n else if (magn_methy == 2 || magn_methy == 4)\n {\n if (i == 0)\n {\n SetPixelRGBO(q,(pixels));\n }\n\n else\n {\n /* Interpolate */\n SetPixelRed(q,\n ((QM) (((ssize_t)\n (2*i*(GetPixelRed(n)\n -GetPixelRed(pixels)+m))/\n ((ssize_t) (m*2))\n +GetPixelRed(pixels)))));\n SetPixelGreen(q,\n ((QM) (((ssize_t)\n (2*i*(GetPixelGreen(n)\n -GetPixelGreen(pixels)+m))/\n ((ssize_t) (m*2))\n +GetPixelGreen(pixels)))));\n SetPixelBlue(q,\n ((QM) (((ssize_t)\n (2*i*(GetPixelBlue(n)\n -GetPixelBlue(pixels)+m))/\n ((ssize_t) (m*2))\n +GetPixelBlue(pixels)))));\n\n if (image->matte != MagickFalse)\n SetPixelOpacity(q,\n ((QM) (((ssize_t)\n (2*i*(GetPixelOpacity(n)\n -GetPixelOpacity(pixels)+m))\n /((ssize_t) (m*2))+\n GetPixelOpacity(pixels)))));\n }\n\n if (magn_methy == 4)\n {\n /* Replicate nearest */\n if (i <= ((m+1) << 1))\n SetPixelOpacity(q,\n (*pixels).opacity+0);\n else\n SetPixelOpacity(q,\n (*n).opacity+0);\n }\n }\n\n else /* if (magn_methy == 3 || magn_methy == 5) */\n {\n /* Replicate nearest */\n if (i <= ((m+1) << 1))\n {\n SetPixelRGBO(q,(pixels));\n }\n\n else\n {\n SetPixelRGBO(q,(n));\n }\n\n if (magn_methy == 5)\n {\n SetPixelOpacity(q,\n (QM) (((ssize_t) (2*i*\n (GetPixelOpacity(n)\n -GetPixelOpacity(pixels))\n +m))/((ssize_t) (m*2))\n +GetPixelOpacity(pixels)));\n }\n }\n n++;\n q++;\n pixels++;\n } /* x */\n\n if (SyncAuthenticPixels(large_image,exception) == 0)\n break;\n\n } /* i */\n } /* y */\n\n prev=(PixelPacket *) RelinquishMagickMemory(prev);\n next=(PixelPacket *) RelinquishMagickMemory(next);\n\n length=image->columns;\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Delete original image\");\n\n DeleteImageFromList(&image);\n\n image=large_image;\n\n mng_info->image=image;\n\n /* magnify the columns */\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Magnify the columns to %.20g\",(double) image->columns);\n\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register PixelPacket\n *pixels;\n\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n pixels=q+(image->columns-length);\n n=pixels+1;\n\n for (x=(ssize_t) (image->columns-length);\n x < (ssize_t) image->columns; x++)\n {\n /* To do: Rewrite using Get/Set***PixelComponent() */\n\n if (x == (ssize_t) (image->columns-length))\n m=(ssize_t) mng_info->magn_ml;\n\n else if (magn_methx > 1 && x == (ssize_t) image->columns-2)\n m=(ssize_t) mng_info->magn_mr;\n\n else if (magn_methx <= 1 && x == (ssize_t) image->columns-1)\n m=(ssize_t) mng_info->magn_mr;\n\n else if (magn_methx > 1 && x == (ssize_t) image->columns-1)\n m=1;\n\n else\n m=(ssize_t) mng_info->magn_mx;\n\n for (i=0; i < m; i++)\n {\n if (magn_methx <= 1)\n {\n /* replicate previous */\n SetPixelRGBO(q,(pixels));\n }\n\n else if (magn_methx == 2 || magn_methx == 4)\n {\n if (i == 0)\n {\n SetPixelRGBO(q,(pixels));\n }\n\n /* To do: Rewrite using Get/Set***PixelComponent() */\n else\n {\n /* Interpolate */\n SetPixelRed(q,\n (QM) ((2*i*(\n GetPixelRed(n)\n -GetPixelRed(pixels))+m)\n /((ssize_t) (m*2))+\n GetPixelRed(pixels)));\n\n SetPixelGreen(q,\n (QM) ((2*i*(\n GetPixelGreen(n)\n -GetPixelGreen(pixels))+m)\n /((ssize_t) (m*2))+\n GetPixelGreen(pixels)));\n\n SetPixelBlue(q,\n (QM) ((2*i*(\n GetPixelBlue(n)\n -GetPixelBlue(pixels))+m)\n /((ssize_t) (m*2))+\n GetPixelBlue(pixels)));\n if (image->matte != MagickFalse)\n SetPixelOpacity(q,\n (QM) ((2*i*(\n GetPixelOpacity(n)\n -GetPixelOpacity(pixels))+m)\n /((ssize_t) (m*2))+\n GetPixelOpacity(pixels)));\n }\n\n if (magn_methx == 4)\n {\n /* Replicate nearest */\n if (i <= ((m+1) << 1))\n {\n SetPixelOpacity(q,\n GetPixelOpacity(pixels)+0);\n }\n else\n {\n SetPixelOpacity(q,\n GetPixelOpacity(n)+0);\n }\n }\n }\n\n else /* if (magn_methx == 3 || magn_methx == 5) */\n {\n /* Replicate nearest */\n if (i <= ((m+1) << 1))\n {\n SetPixelRGBO(q,(pixels));\n }\n\n else\n {\n SetPixelRGBO(q,(n));\n }\n\n if (magn_methx == 5)\n {\n /* Interpolate */\n SetPixelOpacity(q,\n (QM) ((2*i*( GetPixelOpacity(n)\n -GetPixelOpacity(pixels))+m)/\n ((ssize_t) (m*2))\n +GetPixelOpacity(pixels)));\n }\n }\n q++;\n }\n n++;\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n#if (MAGICKCORE_QUANTUM_DEPTH > 16)\n if (magn_methx != 1 || magn_methy != 1)\n {\n /*\n Rescale pixels to Quantum\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n\n for (x=(ssize_t) image->columns-1; x >= 0; x--)\n {\n SetPixelRed(q,ScaleShortToQuantum(\n GetPixelRed(q)));\n SetPixelGreen(q,ScaleShortToQuantum(\n GetPixelGreen(q)));\n SetPixelBlue(q,ScaleShortToQuantum(\n GetPixelBlue(q)));\n SetPixelOpacity(q,ScaleShortToQuantum(\n GetPixelOpacity(q)));\n q++;\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n }\n#endif\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Finished MAGN processing\");\n }\n }\n\n /*\n Crop_box is with respect to the upper left corner of the MNG.\n */\n crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id];\n crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id];\n crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id];\n crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id];\n crop_box=mng_minimum_box(crop_box,mng_info->clip);\n crop_box=mng_minimum_box(crop_box,mng_info->frame);\n crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]);\n if ((crop_box.left != (mng_info->image_box.left\n +mng_info->x_off[object_id])) ||\n (crop_box.right != (mng_info->image_box.right\n +mng_info->x_off[object_id])) ||\n (crop_box.top != (mng_info->image_box.top\n +mng_info->y_off[object_id])) ||\n (crop_box.bottom != (mng_info->image_box.bottom\n +mng_info->y_off[object_id])))\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Crop the PNG image\");\n\n if ((crop_box.left < crop_box.right) &&\n (crop_box.top < crop_box.bottom))\n {\n Image\n *im;\n\n RectangleInfo\n crop_info;\n\n /*\n Crop_info is with respect to the upper left corner of\n the image.\n */\n crop_info.x=(crop_box.left-mng_info->x_off[object_id]);\n crop_info.y=(crop_box.top-mng_info->y_off[object_id]);\n crop_info.width=(size_t) (crop_box.right-crop_box.left);\n crop_info.height=(size_t) (crop_box.bottom-crop_box.top);\n image->page.width=image->columns;\n image->page.height=image->rows;\n image->page.x=0;\n image->page.y=0;\n im=CropImage(image,&crop_info,exception);\n\n if (im != (Image *) NULL)\n {\n image->columns=im->columns;\n image->rows=im->rows;\n im=DestroyImage(im);\n image->page.width=image->columns;\n image->page.height=image->rows;\n image->page.x=crop_box.left;\n image->page.y=crop_box.top;\n }\n }\n\n else\n {\n /*\n No pixels in crop area. The MNG spec still requires\n a layer, though, so make a single transparent pixel in\n the top left corner.\n */\n image->columns=1;\n image->rows=1;\n image->colors=2;\n (void) SetImageBackgroundColor(image);\n image->page.width=1;\n image->page.height=1;\n image->page.x=0;\n image->page.y=0;\n }\n }\n#ifndef PNG_READ_EMPTY_PLTE_SUPPORTED\n image=mng_info->image;\n#endif\n }\n\n#if (MAGICKCORE_QUANTUM_DEPTH > 16)\n /* PNG does not handle depths greater than 16 so reduce it even\n * if lossy, and promote any depths > 8 to 16.\n */\n if (image->depth > 16)\n image->depth=16;\n#endif\n\n#if (MAGICKCORE_QUANTUM_DEPTH > 8)\n if (image->depth > 8)\n {\n /* To do: fill low byte properly */\n image->depth=16;\n }\n\n if (LosslessReduceDepthOK(image) != MagickFalse)\n image->depth = 8;\n#endif\n\n GetImageException(image,exception);\n\n if (image_info->number_scenes != 0)\n {\n if (mng_info->scenes_found >\n (ssize_t) (image_info->first_scene+image_info->number_scenes))\n break;\n }\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Finished reading image datastream.\");\n\n } while (LocaleCompare(image_info->magick,\"MNG\") == 0);\n\n (void) CloseBlob(image);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Finished reading all image datastreams.\");\n\n#if defined(MNG_INSERT_LAYERS)\n if (insert_layers && !mng_info->image_found && (mng_info->mng_width) &&\n (mng_info->mng_height))\n {\n /*\n Insert a background layer if nothing else was found.\n */\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" No images found. Inserting a background layer.\");\n\n if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)\n {\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Allocation failed, returning NULL.\");\n\n return(DestroyImageList(image));\n }\n image=SyncNextImageInList(image);\n }\n image->columns=mng_info->mng_width;\n image->rows=mng_info->mng_height;\n image->page.width=mng_info->mng_width;\n image->page.height=mng_info->mng_height;\n image->page.x=0;\n image->page.y=0;\n image->background_color=mng_background_color;\n image->matte=MagickFalse;\n\n if (image_info->ping == MagickFalse)\n (void) SetImageBackgroundColor(image);\n\n mng_info->image_found++;\n }\n#endif\n image->iterations=mng_iterations;\n\n if (mng_iterations == 1)\n image->start_loop=MagickTrue;\n\n while (GetPreviousImageInList(image) != (Image *) NULL)\n {\n image_count++;\n if (image_count > 10*mng_info->image_found)\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" No beginning\");\n\n (void) ThrowMagickException(&image->exception,GetMagickModule(),\n CoderError,\"Linked list is corrupted, beginning of list not found\",\n \"`%s'\",image_info->filename);\n\n return(DestroyImageList(image));\n }\n\n image=GetPreviousImageInList(image);\n\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Corrupt list\");\n\n (void) ThrowMagickException(&image->exception,GetMagickModule(),\n CoderError,\"Linked list is corrupted; next_image is NULL\",\"`%s'\",\n image_info->filename);\n }\n }\n\n if (mng_info->ticks_per_second && mng_info->image_found > 1 &&\n GetNextImageInList(image) ==\n (Image *) NULL)\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" First image null\");\n\n (void) ThrowMagickException(&image->exception,GetMagickModule(),\n CoderError,\"image->next for first image is NULL but shouldn't be.\",\n \"`%s'\",image_info->filename);\n }\n\n if (mng_info->image_found == 0)\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" No visible images found.\");\n\n (void) ThrowMagickException(&image->exception,GetMagickModule(),\n CoderError,\"No visible images in file\",\"`%s'\",image_info->filename);\n\n return(DestroyImageList(image));\n }\n\n if (mng_info->ticks_per_second)\n final_delay=1UL*MagickMax(image->ticks_per_second,1L)*\n final_delay/mng_info->ticks_per_second;\n\n else\n image->start_loop=MagickTrue;\n\n /* Find final nonzero image delay */\n final_image_delay=0;\n\n while (GetNextImageInList(image) != (Image *) NULL)\n {\n if (image->delay)\n final_image_delay=image->delay;\n\n image=GetNextImageInList(image);\n }\n\n if (final_delay < final_image_delay)\n final_delay=final_image_delay;\n\n image->delay=final_delay;\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image->delay=%.20g, final_delay=%.20g\",(double) image->delay,\n (double) final_delay);\n\n if (logging != MagickFalse)\n {\n int\n scene;\n\n scene=0;\n image=GetFirstImageInList(image);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Before coalesce:\");\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" scene 0 delay=%.20g\",(double) image->delay);\n\n while (GetNextImageInList(image) != (Image *) NULL)\n {\n image=GetNextImageInList(image);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" scene %.20g delay=%.20g\",(double) scene++,(double) image->delay);\n }\n }\n\n image=GetFirstImageInList(image);\n#ifdef MNG_COALESCE_LAYERS\n if (insert_layers)\n {\n Image\n *next_image,\n *next;\n\n size_t\n scene;\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Coalesce Images\");\n\n scene=image->scene;\n next_image=CoalesceImages(image,&image->exception);\n\n if (next_image == (Image *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n\n image=DestroyImageList(image);\n image=next_image;\n\n for (next=image; next != (Image *) NULL; next=next_image)\n {\n next->page.width=mng_info->mng_width;\n next->page.height=mng_info->mng_height;\n next->page.x=0;\n next->page.y=0;\n next->scene=scene++;\n next_image=GetNextImageInList(next);\n\n if (next_image == (Image *) NULL)\n break;\n\n if (next->delay == 0)\n {\n scene--;\n next_image->previous=GetPreviousImageInList(next);\n if (GetPreviousImageInList(next) == (Image *) NULL)\n image=next_image;\n else\n next->previous->next=next_image;\n next=DestroyImage(next);\n }\n }\n }\n#endif\n\n while (GetNextImageInList(image) != (Image *) NULL)\n image=GetNextImageInList(image);\n\n image->dispose=BackgroundDispose;\n\n if (logging != MagickFalse)\n {\n int\n scene;\n\n scene=0;\n image=GetFirstImageInList(image);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" After coalesce:\");\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" scene 0 delay=%.20g dispose=%.20g\",(double) image->delay,\n (double) image->dispose);\n\n while (GetNextImageInList(image) != (Image *) NULL)\n {\n image=GetNextImageInList(image);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" scene %.20g delay=%.20g dispose=%.20g\",(double) scene++,\n (double) image->delay,(double) image->dispose);\n }\n }\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" exit ReadOneJNGImage();\");\n\n return(image);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': 'Fixed infinite loop (#1095).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ParseRiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config)\n{\n int is_rf64 = !strncmp (fourcc, \"RF64\", 4), got_ds64 = 0;\n int64_t total_samples = 0, infilesize;\n RiffChunkHeader riff_chunk_header;\n ChunkHeader chunk_header;\n WaveHeader WaveHeader;\n DS64Chunk ds64_chunk;\n uint32_t bcount;\n\n CLEAR (WaveHeader);\n CLEAR (ds64_chunk);\n infilesize = DoGetFileSize (infile);\n\n if (!is_rf64 && infilesize >= 4294967296LL && !(config->qmode & QMODE_IGNORE_LENGTH)) {\n error_line (\"can't handle .WAV files larger than 4 GB (non-standard)!\");\n return WAVPACK_SOFT_ERROR;\n }\n\n memcpy (&riff_chunk_header, fourcc, 4);\n\n if ((!DoReadFile (infile, ((char *) &riff_chunk_header) + 4, sizeof (RiffChunkHeader) - 4, &bcount) ||\n bcount != sizeof (RiffChunkHeader) - 4 || strncmp (riff_chunk_header.formType, \"WAVE\", 4))) {\n error_line (\"%s is not a valid .WAV file!\", infilename);\n return WAVPACK_SOFT_ERROR;\n }\n else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&\n !WavpackAddWrapper (wpc, &riff_chunk_header, sizeof (RiffChunkHeader))) {\n error_line (\"%s\", WavpackGetErrorMessage (wpc));\n return WAVPACK_SOFT_ERROR;\n }\n\n // loop through all elements of the RIFF wav header\n // (until the data chuck) and copy them to the output file\n\n while (1) {\n if (!DoReadFile (infile, &chunk_header, sizeof (ChunkHeader), &bcount) ||\n bcount != sizeof (ChunkHeader)) {\n error_line (\"%s is not a valid .WAV file!\", infilename);\n return WAVPACK_SOFT_ERROR;\n }\n else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&\n !WavpackAddWrapper (wpc, &chunk_header, sizeof (ChunkHeader))) {\n error_line (\"%s\", WavpackGetErrorMessage (wpc));\n return WAVPACK_SOFT_ERROR;\n }\n\n WavpackLittleEndianToNative (&chunk_header, ChunkHeaderFormat);\n\n if (!strncmp (chunk_header.ckID, \"ds64\", 4)) {\n if (chunk_header.ckSize < sizeof (DS64Chunk) ||\n !DoReadFile (infile, &ds64_chunk, sizeof (DS64Chunk), &bcount) ||\n bcount != sizeof (DS64Chunk)) {\n error_line (\"%s is not a valid .WAV file!\", infilename);\n return WAVPACK_SOFT_ERROR;\n }\n else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&\n !WavpackAddWrapper (wpc, &ds64_chunk, sizeof (DS64Chunk))) {\n error_line (\"%s\", WavpackGetErrorMessage (wpc));\n return WAVPACK_SOFT_ERROR;\n }\n\n got_ds64 = 1;\n WavpackLittleEndianToNative (&ds64_chunk, DS64ChunkFormat);\n\n if (debug_logging_mode)\n error_line (\"DS64: riffSize = %lld, dataSize = %lld, sampleCount = %lld, table_length = %d\",\n (long long) ds64_chunk.riffSize64, (long long) ds64_chunk.dataSize64,\n (long long) ds64_chunk.sampleCount64, ds64_chunk.tableLength);\n\n if (ds64_chunk.tableLength * sizeof (CS64Chunk) != chunk_header.ckSize - sizeof (DS64Chunk)) {\n error_line (\"%s is not a valid .WAV file!\", infilename);\n return WAVPACK_SOFT_ERROR;\n }\n\n while (ds64_chunk.tableLength--) {\n CS64Chunk cs64_chunk;\n if (!DoReadFile (infile, &cs64_chunk, sizeof (CS64Chunk), &bcount) ||\n bcount != sizeof (CS64Chunk) ||\n (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&\n !WavpackAddWrapper (wpc, &cs64_chunk, sizeof (CS64Chunk)))) {\n error_line (\"%s\", WavpackGetErrorMessage (wpc));\n return WAVPACK_SOFT_ERROR;\n }\n }\n }\n else if (!strncmp (chunk_header.ckID, \"fmt \", 4)) { // if it's the format chunk, we want to get some info out of there and\n int supported = TRUE, format; // make sure it's a .wav file we can handle\n\n if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) ||\n !DoReadFile (infile, &WaveHeader, chunk_header.ckSize, &bcount) ||\n bcount != chunk_header.ckSize) {\n error_line (\"%s is not a valid .WAV file!\", infilename);\n return WAVPACK_SOFT_ERROR;\n }\n else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&\n !WavpackAddWrapper (wpc, &WaveHeader, chunk_header.ckSize)) {\n error_line (\"%s\", WavpackGetErrorMessage (wpc));\n return WAVPACK_SOFT_ERROR;\n }\n\n WavpackLittleEndianToNative (&WaveHeader, WaveHeaderFormat);\n\n if (debug_logging_mode) {\n error_line (\"format tag size = %d\", chunk_header.ckSize);\n error_line (\"FormatTag = %x, NumChannels = %d, BitsPerSample = %d\",\n WaveHeader.FormatTag, WaveHeader.NumChannels, WaveHeader.BitsPerSample);\n error_line (\"BlockAlign = %d, SampleRate = %d, BytesPerSecond = %d\",\n WaveHeader.BlockAlign, WaveHeader.SampleRate, WaveHeader.BytesPerSecond);\n\n if (chunk_header.ckSize > 16)\n error_line (\"cbSize = %d, ValidBitsPerSample = %d\", WaveHeader.cbSize,\n WaveHeader.ValidBitsPerSample);\n\n if (chunk_header.ckSize > 20)\n error_line (\"ChannelMask = %x, SubFormat = %d\",\n WaveHeader.ChannelMask, WaveHeader.SubFormat);\n }\n\n if (chunk_header.ckSize > 16 && WaveHeader.cbSize == 2)\n config->qmode |= QMODE_ADOBE_MODE;\n\n format = (WaveHeader.FormatTag == 0xfffe && chunk_header.ckSize == 40) ?\n WaveHeader.SubFormat : WaveHeader.FormatTag;\n\n config->bits_per_sample = (chunk_header.ckSize == 40 && WaveHeader.ValidBitsPerSample) ?\n WaveHeader.ValidBitsPerSample : WaveHeader.BitsPerSample;\n\n if (format != 1 && format != 3)\n supported = FALSE;\n\n if (format == 3 && config->bits_per_sample != 32)\n supported = FALSE;\n\n if (!WaveHeader.NumChannels || WaveHeader.NumChannels > 256 ||\n WaveHeader.BlockAlign / WaveHeader.NumChannels < (config->bits_per_sample + 7) / 8 ||\n WaveHeader.BlockAlign / WaveHeader.NumChannels > 4 ||\n WaveHeader.BlockAlign % WaveHeader.NumChannels)\n supported = FALSE;\n\n if (config->bits_per_sample < 1 || config->bits_per_sample > 32)\n supported = FALSE;\n\n if (!supported) {\n error_line (\"%s is an unsupported .WAV format!\", infilename);\n return WAVPACK_SOFT_ERROR;\n }\n\n if (chunk_header.ckSize < 40) {\n if (!config->channel_mask && !(config->qmode & QMODE_CHANS_UNASSIGNED)) {\n if (WaveHeader.NumChannels <= 2)\n config->channel_mask = 0x5 - WaveHeader.NumChannels;\n else if (WaveHeader.NumChannels <= 18)\n config->channel_mask = (1 << WaveHeader.NumChannels) - 1;\n else\n config->channel_mask = 0x3ffff;\n }\n }\n else if (WaveHeader.ChannelMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) {\n error_line (\"this WAV file already has channel order information!\");\n return WAVPACK_SOFT_ERROR;\n }\n else if (WaveHeader.ChannelMask)\n config->channel_mask = WaveHeader.ChannelMask;\n\n if (format == 3)\n config->float_norm_exp = 127;\n else if ((config->qmode & QMODE_ADOBE_MODE) &&\n WaveHeader.BlockAlign / WaveHeader.NumChannels == 4) {\n if (WaveHeader.BitsPerSample == 24)\n config->float_norm_exp = 127 + 23;\n else if (WaveHeader.BitsPerSample == 32)\n config->float_norm_exp = 127 + 15;\n }\n\n if (debug_logging_mode) {\n if (config->float_norm_exp == 127)\n error_line (\"data format: normalized 32-bit floating point\");\n else if (config->float_norm_exp)\n error_line (\"data format: 32-bit floating point (Audition %d:%d float type 1)\",\n config->float_norm_exp - 126, 150 - config->float_norm_exp);\n else\n error_line (\"data format: %d-bit integers stored in %d byte(s)\",\n config->bits_per_sample, WaveHeader.BlockAlign / WaveHeader.NumChannels);\n }\n }\n else if (!strncmp (chunk_header.ckID, \"data\", 4)) { // on the data chunk, get size and exit loop\n\n int64_t data_chunk_size = (got_ds64 && chunk_header.ckSize == (uint32_t) -1) ?\n ds64_chunk.dataSize64 : chunk_header.ckSize;\n\n\n if (!WaveHeader.NumChannels || (is_rf64 && !got_ds64)) { // make sure we saw \"fmt\" and \"ds64\" chunks (if required)\n error_line (\"%s is not a valid .WAV file!\", infilename);\n return WAVPACK_SOFT_ERROR;\n }\n\n if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && infilesize - data_chunk_size > 16777216) {\n error_line (\"this .WAV file has over 16 MB of extra RIFF data, probably is corrupt!\");\n return WAVPACK_SOFT_ERROR;\n }\n\n if (config->qmode & QMODE_IGNORE_LENGTH) {\n if (infilesize && DoGetFilePosition (infile) != -1)\n total_samples = (infilesize - DoGetFilePosition (infile)) / WaveHeader.BlockAlign;\n else\n total_samples = -1;\n }\n else {\n total_samples = data_chunk_size / WaveHeader.BlockAlign;\n\n if (got_ds64 && total_samples != ds64_chunk.sampleCount64) {\n error_line (\"%s is not a valid .WAV file!\", infilename);\n return WAVPACK_SOFT_ERROR;\n }\n\n if (!total_samples) {\n error_line (\"this .WAV file has no audio samples, probably is corrupt!\");\n return WAVPACK_SOFT_ERROR;\n }\n\n if (total_samples > MAX_WAVPACK_SAMPLES) {\n error_line (\"%s has too many samples for WavPack!\", infilename);\n return WAVPACK_SOFT_ERROR;\n }\n }\n\n config->bytes_per_sample = WaveHeader.BlockAlign / WaveHeader.NumChannels;\n config->num_channels = WaveHeader.NumChannels;\n config->sample_rate = WaveHeader.SampleRate;\n break;\n }\n else { // just copy unknown chunks to output file\n\n int bytes_to_copy = (chunk_header.ckSize + 1) & ~1L;\n char *buff = malloc (bytes_to_copy);\n\n if (debug_logging_mode)\n error_line (\"extra unknown chunk \\\"%c%c%c%c\\\" of %d bytes\",\n chunk_header.ckID [0], chunk_header.ckID [1], chunk_header.ckID [2],\n chunk_header.ckID [3], chunk_header.ckSize);\n\n if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) ||\n bcount != bytes_to_copy ||\n (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&\n !WavpackAddWrapper (wpc, buff, bytes_to_copy))) {\n error_line (\"%s\", WavpackGetErrorMessage (wpc));\n free (buff);\n return WAVPACK_SOFT_ERROR;\n }\n\n free (buff);\n }\n }\n\n if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) {\n error_line (\"%s: %s\", infilename, WavpackGetErrorMessage (wpc));\n return WAVPACK_SOFT_ERROR;\n }\n\n return WAVPACK_NO_ERROR;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'issue #33, sanitize size of unknown chunks before malloc()'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int CephxServiceHandler::handle_request(bufferlist::iterator& indata, bufferlist& result_bl, uint64_t& global_id, AuthCapsInfo& caps, uint64_t *auid)\n{\n int ret = 0;\n\n struct CephXRequestHeader cephx_header;\n ::decode(cephx_header, indata);\n\n\n switch (cephx_header.request_type) {\n case CEPHX_GET_AUTH_SESSION_KEY:\n {\n ldout(cct, 10) << \"handle_request get_auth_session_key for \" << entity_name << dendl;\n\n CephXAuthenticate req;\n ::decode(req, indata);\n\n CryptoKey secret;\n if (!key_server->get_secret(entity_name, secret)) {\n ldout(cct, 0) << \"couldn't find entity name: \" << entity_name << dendl;\n\tret = -EPERM;\n\tbreak;\n }\n\n if (!server_challenge) {\n\tret = -EPERM;\n\tbreak;\n } \n\n uint64_t expected_key;\n std::string error;\n cephx_calc_client_server_challenge(cct, secret, server_challenge,\n\t\t\t\t\t req.client_challenge, &expected_key, error);\n if (!error.empty()) {\n\tldout(cct, 0) << \" cephx_calc_client_server_challenge error: \" << error << dendl;\n\tret = -EPERM;\n\tbreak;\n }\n\n ldout(cct, 20) << \" checking key: req.key=\" << hex << req.key\n\t << \" expected_key=\" << expected_key << dec << dendl;\n if (req.key != expected_key) {\n ldout(cct, 0) << \" unexpected key: req.key=\" << hex << req.key\n\t\t<< \" expected_key=\" << expected_key << dec << dendl;\n ret = -EPERM;\n\tbreak;\n }\n\n CryptoKey session_key;\n CephXSessionAuthInfo info;\n bool should_enc_ticket = false;\n\n EntityAuth eauth;\n if (! key_server->get_auth(entity_name, eauth)) {\n\tret = -EPERM;\n\tbreak;\n }\n CephXServiceTicketInfo old_ticket_info;\n\n if (cephx_decode_ticket(cct, key_server, CEPH_ENTITY_TYPE_AUTH,\n\t\t\t req.old_ticket, old_ticket_info)) {\n global_id = old_ticket_info.ticket.global_id;\n ldout(cct, 10) << \"decoded old_ticket with global_id=\" << global_id << dendl;\n should_enc_ticket = true;\n }\n\n info.ticket.init_timestamps(ceph_clock_now(), cct->_conf->auth_mon_ticket_ttl);\n info.ticket.name = entity_name;\n info.ticket.global_id = global_id;\n info.ticket.auid = eauth.auid;\n info.validity += cct->_conf->auth_mon_ticket_ttl;\n\n if (auid) *auid = eauth.auid;\n\n key_server->generate_secret(session_key);\n\n info.session_key = session_key;\n info.service_id = CEPH_ENTITY_TYPE_AUTH;\n if (!key_server->get_service_secret(CEPH_ENTITY_TYPE_AUTH, info.service_secret, info.secret_id)) {\n ldout(cct, 0) << \" could not get service secret for auth subsystem\" << dendl;\n ret = -EIO;\n break;\n }\n\n vector info_vec;\n info_vec.push_back(info);\n\n build_cephx_response_header(cephx_header.request_type, 0, result_bl);\n if (!cephx_build_service_ticket_reply(cct, eauth.key, info_vec, should_enc_ticket,\n\t\t\t\t\t old_ticket_info.session_key, result_bl)) {\n\tret = -EIO;\n }\n\n if (!key_server->get_service_caps(entity_name, CEPH_ENTITY_TYPE_MON, caps)) {\n ldout(cct, 0) << \" could not get mon caps for \" << entity_name << dendl;\n ret = -EACCES;\n } else {\n char *caps_str = caps.caps.c_str();\n if (!caps_str || !caps_str[0]) {\n ldout(cct,0) << \"mon caps null for \" << entity_name << dendl;\n ret = -EACCES;\n }\n }\n }\n break;\n\n case CEPHX_GET_PRINCIPAL_SESSION_KEY:\n {\n ldout(cct, 10) << \"handle_request get_principal_session_key\" << dendl;\n\n bufferlist tmp_bl;\n CephXServiceTicketInfo auth_ticket_info;\n if (!cephx_verify_authorizer(cct, key_server, indata, auth_ticket_info, tmp_bl)) {\n ret = -EPERM;\n\tbreak;\n }\n\n CephXServiceTicketRequest ticket_req;\n ::decode(ticket_req, indata);\n ldout(cct, 10) << \" ticket_req.keys = \" << ticket_req.keys << dendl;\n\n ret = 0;\n vector info_vec;\n int found_services = 0;\n int service_err = 0;\n for (uint32_t service_id = 1; service_id <= ticket_req.keys;\n\t service_id <<= 1) {\n if (ticket_req.keys & service_id) {\n\t ldout(cct, 10) << \" adding key for service \"\n\t\t\t << ceph_entity_type_name(service_id) << dendl;\n CephXSessionAuthInfo info;\n int r = key_server->build_session_auth_info(service_id,\n\t\t\t\t\t\t auth_ticket_info, info);\n\t // tolerate missing MGR rotating key for the purposes of upgrades.\n if (r < 0) {\n\t ldout(cct, 10) << \" missing key for service \"\n\t\t\t << ceph_entity_type_name(service_id) << dendl;\n\t service_err = r;\n\t continue;\n\t }\n info.validity += cct->_conf->auth_service_ticket_ttl;\n info_vec.push_back(info);\n\t ++found_services;\n }\n }\n if (!found_services && service_err) {\n\tldout(cct, 10) << __func__ << \" did not find any service keys\" << dendl;\n\tret = service_err;\n }\n CryptoKey no_key;\n build_cephx_response_header(cephx_header.request_type, ret, result_bl);\n cephx_build_service_ticket_reply(cct, auth_ticket_info.session_key, info_vec, false, no_key, result_bl);\n }\n break;\n\n case CEPHX_GET_ROTATING_KEY:\n {\n ldout(cct, 10) << \"handle_request getting rotating secret for \" << entity_name << dendl;\n build_cephx_response_header(cephx_header.request_type, 0, result_bl);\n if (!key_server->get_rotating_encrypted(entity_name, result_bl)) {\n ret = -EPERM;\n break;\n }\n }\n break;\n\n default:\n ldout(cct, 10) << \"handle_request unknown op \" << cephx_header.request_type << dendl;\n return -EINVAL;\n }\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'auth/cephx: add authorizer challenge\n\nAllow the accepting side of a connection to reject an initial authorizer\nwith a random challenge. The connecting side then has to respond with an\nupdated authorizer proving they are able to decrypt the service's challenge\nand that the new authorizer was produced for this specific connection\ninstance.\n\nThe accepting side requires this challenge and response unconditionally\nif the client side advertises they have the feature bit. Servers wishing\nto require this improved level of authentication simply have to require\nthe appropriate feature.\n\nSigned-off-by: Sage Weil \n(cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b)\n\n# Conflicts:\n#\tsrc/auth/Auth.h\n#\tsrc/auth/cephx/CephxProtocol.cc\n#\tsrc/auth/cephx/CephxProtocol.h\n#\tsrc/auth/none/AuthNoneProtocol.h\n#\tsrc/msg/Dispatcher.h\n#\tsrc/msg/async/AsyncConnection.cc\n\n- const_iterator\n- ::decode vs decode\n- AsyncConnection ctor arg noise\n- get_random_bytes(), not cct->random()'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool CephxAuthorizeHandler::verify_authorizer(CephContext *cct, KeyStore *keys,\n\t\t\t\t\t bufferlist& authorizer_data, bufferlist& authorizer_reply,\n EntityName& entity_name, uint64_t& global_id, AuthCapsInfo& caps_info, CryptoKey& session_key, uint64_t *auid)\n{\n bufferlist::iterator iter = authorizer_data.begin();\n\n if (!authorizer_data.length()) {\n ldout(cct, 1) << \"verify authorizer, authorizer_data.length()=0\" << dendl;\n return false;\n }\n\n CephXServiceTicketInfo auth_ticket_info;\n\n bool isvalid = cephx_verify_authorizer(cct, keys, iter, auth_ticket_info, authorizer_reply);\n\n if (isvalid) {\n caps_info = auth_ticket_info.ticket.caps;\n entity_name = auth_ticket_info.ticket.name;\n global_id = auth_ticket_info.ticket.global_id;\n session_key = auth_ticket_info.session_key;\n if (auid) *auid = auth_ticket_info.ticket.auid;\n }\n\n return isvalid;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'auth/cephx: add authorizer challenge\n\nAllow the accepting side of a connection to reject an initial authorizer\nwith a random challenge. The connecting side then has to respond with an\nupdated authorizer proving they are able to decrypt the service's challenge\nand that the new authorizer was produced for this specific connection\ninstance.\n\nThe accepting side requires this challenge and response unconditionally\nif the client side advertises they have the feature bit. Servers wishing\nto require this improved level of authentication simply have to require\nthe appropriate feature.\n\nSigned-off-by: Sage Weil \n(cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b)\n\n# Conflicts:\n#\tsrc/auth/Auth.h\n#\tsrc/auth/cephx/CephxProtocol.cc\n#\tsrc/auth/cephx/CephxProtocol.h\n#\tsrc/auth/none/AuthNoneProtocol.h\n#\tsrc/msg/Dispatcher.h\n#\tsrc/msg/async/AsyncConnection.cc\n\n- const_iterator\n- ::decode vs decode\n- AsyncConnection ctor arg noise\n- get_random_bytes(), not cct->random()'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int Pipe::accept()\n{\n ldout(msgr->cct,10) << \"accept\" << dendl;\n assert(pipe_lock.is_locked());\n assert(state == STATE_ACCEPTING);\n\n pipe_lock.Unlock();\n\n // vars\n bufferlist addrs;\n entity_addr_t socket_addr;\n socklen_t len;\n int r;\n char banner[strlen(CEPH_BANNER)+1];\n bufferlist addrbl;\n ceph_msg_connect connect;\n ceph_msg_connect_reply reply;\n Pipe *existing = 0;\n bufferptr bp;\n bufferlist authorizer, authorizer_reply;\n bool authorizer_valid;\n uint64_t feat_missing;\n bool replaced = false;\n // this variable denotes if the connection attempt from peer is a hard \n // reset or not, it is true if there is an existing connection and the\n // connection sequence from peer is equal to zero\n bool is_reset_from_peer = false;\n CryptoKey session_key;\n int removed; // single-use down below\n\n // this should roughly mirror pseudocode at\n // http://ceph.com/wiki/Messaging_protocol\n int reply_tag = 0;\n uint64_t existing_seq = -1;\n\n // used for reading in the remote acked seq on connect\n uint64_t newly_acked_seq = 0;\n\n recv_reset();\n\n set_socket_options();\n\n // announce myself.\n r = tcp_write(CEPH_BANNER, strlen(CEPH_BANNER));\n if (r < 0) {\n ldout(msgr->cct,10) << \"accept couldn't write banner\" << dendl;\n goto fail_unlocked;\n }\n\n // and my addr\n ::encode(msgr->my_inst.addr, addrs, 0); // legacy\n\n port = msgr->my_inst.addr.get_port();\n\n // and peer's socket addr (they might not know their ip)\n sockaddr_storage ss;\n len = sizeof(ss);\n r = ::getpeername(sd, (sockaddr*)&ss, &len);\n if (r < 0) {\n ldout(msgr->cct,0) << \"accept failed to getpeername \" << cpp_strerror(errno) << dendl;\n goto fail_unlocked;\n }\n socket_addr.set_sockaddr((sockaddr*)&ss);\n ::encode(socket_addr, addrs, 0); // legacy\n\n r = tcp_write(addrs.c_str(), addrs.length());\n if (r < 0) {\n ldout(msgr->cct,10) << \"accept couldn't write my+peer addr\" << dendl;\n goto fail_unlocked;\n }\n\n ldout(msgr->cct,1) << \"accept sd=\" << sd << \" \" << socket_addr << dendl;\n \n // identify peer\n if (tcp_read(banner, strlen(CEPH_BANNER)) < 0) {\n ldout(msgr->cct,10) << \"accept couldn't read banner\" << dendl;\n goto fail_unlocked;\n }\n if (memcmp(banner, CEPH_BANNER, strlen(CEPH_BANNER))) {\n banner[strlen(CEPH_BANNER)] = 0;\n ldout(msgr->cct,1) << \"accept peer sent bad banner '\" << banner << \"' (should be '\" << CEPH_BANNER << \"')\" << dendl;\n goto fail_unlocked;\n }\n {\n bufferptr tp(sizeof(ceph_entity_addr));\n addrbl.push_back(std::move(tp));\n }\n if (tcp_read(addrbl.c_str(), addrbl.length()) < 0) {\n ldout(msgr->cct,10) << \"accept couldn't read peer_addr\" << dendl;\n goto fail_unlocked;\n }\n {\n bufferlist::iterator ti = addrbl.begin();\n ::decode(peer_addr, ti);\n }\n\n ldout(msgr->cct,10) << \"accept peer addr is \" << peer_addr << dendl;\n if (peer_addr.is_blank_ip()) {\n // peer apparently doesn't know what ip they have; figure it out for them.\n int port = peer_addr.get_port();\n peer_addr.u = socket_addr.u;\n peer_addr.set_port(port);\n ldout(msgr->cct,0) << \"accept peer addr is really \" << peer_addr\n\t << \" (socket is \" << socket_addr << \")\" << dendl;\n }\n set_peer_addr(peer_addr); // so that connection_state gets set up\n \n while (1) {\n if (tcp_read((char*)&connect, sizeof(connect)) < 0) {\n ldout(msgr->cct,10) << \"accept couldn't read connect\" << dendl;\n goto fail_unlocked;\n }\n\n authorizer.clear();\n if (connect.authorizer_len) {\n bp = buffer::create(connect.authorizer_len);\n if (tcp_read(bp.c_str(), connect.authorizer_len) < 0) {\n ldout(msgr->cct,10) << \"accept couldn't read connect authorizer\" << dendl;\n goto fail_unlocked;\n }\n authorizer.push_back(std::move(bp));\n authorizer_reply.clear();\n }\n\n ldout(msgr->cct,20) << \"accept got peer connect_seq \" << connect.connect_seq\n\t << \" global_seq \" << connect.global_seq\n\t << dendl;\n \n msgr->lock.Lock(); // FIXME\n pipe_lock.Lock();\n if (msgr->dispatch_queue.stop)\n goto shutting_down;\n if (state != STATE_ACCEPTING) {\n goto shutting_down;\n }\n\n // note peer's type, flags\n set_peer_type(connect.host_type);\n policy = msgr->get_policy(connect.host_type);\n ldout(msgr->cct,10) << \"accept of host_type \" << connect.host_type\n\t\t\t<< \", policy.lossy=\" << policy.lossy\n\t\t\t<< \" policy.server=\" << policy.server\n\t\t\t<< \" policy.standby=\" << policy.standby\n\t\t\t<< \" policy.resetcheck=\" << policy.resetcheck\n\t\t\t<< dendl;\n\n memset(&reply, 0, sizeof(reply));\n reply.protocol_version = msgr->get_proto_version(peer_type, false);\n msgr->lock.Unlock();\n\n // mismatch?\n ldout(msgr->cct,10) << \"accept my proto \" << reply.protocol_version\n\t << \", their proto \" << connect.protocol_version << dendl;\n if (connect.protocol_version != reply.protocol_version) {\n reply.tag = CEPH_MSGR_TAG_BADPROTOVER;\n goto reply;\n }\n\n // require signatures for cephx?\n if (connect.authorizer_protocol == CEPH_AUTH_CEPHX) {\n if (peer_type == CEPH_ENTITY_TYPE_OSD ||\n\t peer_type == CEPH_ENTITY_TYPE_MDS ||\n\t peer_type == CEPH_ENTITY_TYPE_MGR) {\n\tif (msgr->cct->_conf->cephx_require_signatures ||\n\t msgr->cct->_conf->cephx_cluster_require_signatures) {\n\t ldout(msgr->cct,10) << \"using cephx, requiring MSG_AUTH feature bit for cluster\" << dendl;\n\t policy.features_required |= CEPH_FEATURE_MSG_AUTH;\n\t}\n\tif (msgr->cct->_conf->cephx_require_version >= 2 ||\n\t msgr->cct->_conf->cephx_cluster_require_version >= 2) {\n\t ldout(msgr->cct,10) << \"using cephx, requiring cephx v2 feature bit for cluster\" << dendl;\n\t policy.features_required |= CEPH_FEATUREMASK_CEPHX_V2;\n\t}\n } else {\n\tif (msgr->cct->_conf->cephx_require_signatures ||\n\t msgr->cct->_conf->cephx_service_require_signatures) {\n\t ldout(msgr->cct,10) << \"using cephx, requiring MSG_AUTH feature bit for service\" << dendl;\n\t policy.features_required |= CEPH_FEATURE_MSG_AUTH;\n\t}\n\tif (msgr->cct->_conf->cephx_require_version >= 2 ||\n\t msgr->cct->_conf->cephx_service_require_version >= 2) {\n\t ldout(msgr->cct,10) << \"using cephx, requiring cephx v2 feature bit for cluster\" << dendl;\n\t policy.features_required |= CEPH_FEATUREMASK_CEPHX_V2;\n\t}\n }\n }\n\n feat_missing = policy.features_required & ~(uint64_t)connect.features;\n if (feat_missing) {\n ldout(msgr->cct,1) << \"peer missing required features \" << std::hex << feat_missing << std::dec << dendl;\n reply.tag = CEPH_MSGR_TAG_FEATURES;\n goto reply;\n }\n \n // Check the authorizer. If not good, bail out.\n\n pipe_lock.Unlock();\n\n if (!msgr->verify_authorizer(connection_state.get(), peer_type, connect.authorizer_protocol, authorizer,\n\t\t\t\t authorizer_reply, authorizer_valid, session_key) ||\n\t!authorizer_valid) {\n ldout(msgr->cct,0) << \"accept: got bad authorizer\" << dendl;\n pipe_lock.Lock();\n if (state != STATE_ACCEPTING)\n\tgoto shutting_down_msgr_unlocked;\n reply.tag = CEPH_MSGR_TAG_BADAUTHORIZER;\n session_security.reset();\n goto reply;\n } \n\n // We've verified the authorizer for this pipe, so set up the session security structure. PLR\n\n ldout(msgr->cct,10) << \"accept: setting up session_security.\" << dendl;\n\n retry_existing_lookup:\n msgr->lock.Lock();\n pipe_lock.Lock();\n if (msgr->dispatch_queue.stop)\n goto shutting_down;\n if (state != STATE_ACCEPTING)\n goto shutting_down;\n \n // existing?\n existing = msgr->_lookup_pipe(peer_addr);\n if (existing) {\n existing->pipe_lock.Lock(true); // skip lockdep check (we are locking a second Pipe here)\n if (existing->reader_dispatching) {\n\t/** we need to wait, or we can deadlock if downstream\n\t * fast_dispatchers are (naughtily!) waiting on resources\n\t * held by somebody trying to make use of the SimpleMessenger lock.\n\t * So drop locks, wait, and retry. It just looks like a slow network\n\t * to everybody else.\n\t *\n\t * We take a ref to existing here since it might get reaped before we\n\t * wake up (see bug #15870). We can be confident that it lived until\n\t * locked it since we held the msgr lock from _lookup_pipe through to\n\t * locking existing->lock and checking reader_dispatching.\n\t */\n\texisting->get();\n\tpipe_lock.Unlock();\n\tmsgr->lock.Unlock();\n\texisting->notify_on_dispatch_done = true;\n\twhile (existing->reader_dispatching)\n\t existing->cond.Wait(existing->pipe_lock);\n\texisting->pipe_lock.Unlock();\n\texisting->put();\n\texisting = nullptr;\n\tgoto retry_existing_lookup;\n }\n\n if (connect.global_seq < existing->peer_global_seq) {\n\tldout(msgr->cct,10) << \"accept existing \" << existing << \".gseq \" << existing->peer_global_seq\n\t\t << \" > \" << connect.global_seq << \", RETRY_GLOBAL\" << dendl;\n\treply.tag = CEPH_MSGR_TAG_RETRY_GLOBAL;\n\treply.global_seq = existing->peer_global_seq; // so we can send it below..\n\texisting->pipe_lock.Unlock();\n\tmsgr->lock.Unlock();\n\tgoto reply;\n } else {\n\tldout(msgr->cct,10) << \"accept existing \" << existing << \".gseq \" << existing->peer_global_seq\n\t\t << \" <= \" << connect.global_seq << \", looks ok\" << dendl;\n }\n \n if (existing->policy.lossy) {\n\tldout(msgr->cct,0) << \"accept replacing existing (lossy) channel (new one lossy=\"\n\t << policy.lossy << \")\" << dendl;\n\texisting->was_session_reset();\n\tgoto replace;\n }\n\n ldout(msgr->cct,0) << \"accept connect_seq \" << connect.connect_seq\n\t\t\t << \" vs existing \" << existing->connect_seq\n\t\t\t << \" state \" << existing->get_state_name() << dendl;\n\n if (connect.connect_seq == 0 && existing->connect_seq > 0) {\n\tldout(msgr->cct,0) << \"accept peer reset, then tried to connect to us, replacing\" << dendl;\n // this is a hard reset from peer\n is_reset_from_peer = true;\n\tif (policy.resetcheck)\n\t existing->was_session_reset(); // this resets out_queue, msg_ and connect_seq #'s\n\tgoto replace;\n }\n\n if (connect.connect_seq < existing->connect_seq) {\n\t// old attempt, or we sent READY but they didn't get it.\n\tldout(msgr->cct,10) << \"accept existing \" << existing << \".cseq \" << existing->connect_seq\n\t\t\t << \" > \" << connect.connect_seq << \", RETRY_SESSION\" << dendl;\n\tgoto retry_session;\n }\n\n if (connect.connect_seq == existing->connect_seq) {\n\t// if the existing connection successfully opened, and/or\n\t// subsequently went to standby, then the peer should bump\n\t// their connect_seq and retry: this is not a connection race\n\t// we need to resolve here.\n\tif (existing->state == STATE_OPEN ||\n\t existing->state == STATE_STANDBY) {\n\t ldout(msgr->cct,10) << \"accept connection race, existing \" << existing\n\t\t\t << \".cseq \" << existing->connect_seq\n\t\t\t << \" == \" << connect.connect_seq\n\t\t\t << \", OPEN|STANDBY, RETRY_SESSION\" << dendl;\n\t goto retry_session;\n\t}\n\n\t// connection race?\n\tif (peer_addr < msgr->my_inst.addr ||\n\t existing->policy.server) {\n\t // incoming wins\n\t ldout(msgr->cct,10) << \"accept connection race, existing \" << existing << \".cseq \" << existing->connect_seq\n\t\t << \" == \" << connect.connect_seq << \", or we are server, replacing my attempt\" << dendl;\n\t if (!(existing->state == STATE_CONNECTING ||\n\t\texisting->state == STATE_WAIT))\n\t lderr(msgr->cct) << \"accept race bad state, would replace, existing=\"\n\t\t\t << existing->get_state_name()\n\t\t\t << \" \" << existing << \".cseq=\" << existing->connect_seq\n\t\t\t << \" == \" << connect.connect_seq\n\t\t\t << dendl;\n\t assert(existing->state == STATE_CONNECTING ||\n\t\t existing->state == STATE_WAIT);\n\t goto replace;\n\t} else {\n\t // our existing outgoing wins\n\t ldout(msgr->cct,10) << \"accept connection race, existing \" << existing << \".cseq \" << existing->connect_seq\n\t\t << \" == \" << connect.connect_seq << \", sending WAIT\" << dendl;\n\t assert(peer_addr > msgr->my_inst.addr);\n\t if (!(existing->state == STATE_CONNECTING))\n\t lderr(msgr->cct) << \"accept race bad state, would send wait, existing=\"\n\t\t\t << existing->get_state_name()\n\t\t\t << \" \" << existing << \".cseq=\" << existing->connect_seq\n\t\t\t << \" == \" << connect.connect_seq\n\t\t\t << dendl;\n\t assert(existing->state == STATE_CONNECTING);\n\t // make sure our outgoing connection will follow through\n\t existing->_send_keepalive();\n\t reply.tag = CEPH_MSGR_TAG_WAIT;\n\t existing->pipe_lock.Unlock();\n\t msgr->lock.Unlock();\n\t goto reply;\n\t}\n }\n\n assert(connect.connect_seq > existing->connect_seq);\n assert(connect.global_seq >= existing->peer_global_seq);\n if (policy.resetcheck && // RESETSESSION only used by servers; peers do not reset each other\n\t existing->connect_seq == 0) {\n\tldout(msgr->cct,0) << \"accept we reset (peer sent cseq \" << connect.connect_seq \n\t\t << \", \" << existing << \".cseq = \" << existing->connect_seq\n\t\t << \"), sending RESETSESSION\" << dendl;\n\treply.tag = CEPH_MSGR_TAG_RESETSESSION;\n\tmsgr->lock.Unlock();\n\texisting->pipe_lock.Unlock();\n\tgoto reply;\n }\n\n // reconnect\n ldout(msgr->cct,10) << \"accept peer sent cseq \" << connect.connect_seq\n\t << \" > \" << existing->connect_seq << dendl;\n goto replace;\n } // existing\n else if (connect.connect_seq > 0) {\n // we reset, and they are opening a new session\n ldout(msgr->cct,0) << \"accept we reset (peer sent cseq \" << connect.connect_seq << \"), sending RESETSESSION\" << dendl;\n msgr->lock.Unlock();\n reply.tag = CEPH_MSGR_TAG_RESETSESSION;\n goto reply;\n } else {\n // new session\n ldout(msgr->cct,10) << \"accept new session\" << dendl;\n existing = NULL;\n goto open;\n }\n ceph_abort();\n\n retry_session:\n assert(existing->pipe_lock.is_locked());\n assert(pipe_lock.is_locked());\n reply.tag = CEPH_MSGR_TAG_RETRY_SESSION;\n reply.connect_seq = existing->connect_seq + 1;\n existing->pipe_lock.Unlock();\n msgr->lock.Unlock();\n goto reply; \n\n reply:\n assert(pipe_lock.is_locked());\n reply.features = ((uint64_t)connect.features & policy.features_supported) | policy.features_required;\n reply.authorizer_len = authorizer_reply.length();\n pipe_lock.Unlock();\n r = tcp_write((char*)&reply, sizeof(reply));\n if (r < 0)\n goto fail_unlocked;\n if (reply.authorizer_len) {\n r = tcp_write(authorizer_reply.c_str(), authorizer_reply.length());\n if (r < 0)\n\tgoto fail_unlocked;\n }\n }\n \n replace:\n assert(existing->pipe_lock.is_locked());\n assert(pipe_lock.is_locked());\n // if it is a hard reset from peer, we don't need a round-trip to negotiate in/out sequence\n if ((connect.features & CEPH_FEATURE_RECONNECT_SEQ) && !is_reset_from_peer) {\n reply_tag = CEPH_MSGR_TAG_SEQ;\n existing_seq = existing->in_seq;\n }\n ldout(msgr->cct,10) << \"accept replacing \" << existing << dendl;\n existing->stop();\n existing->unregister_pipe();\n replaced = true;\n\n if (existing->policy.lossy) {\n // disconnect from the Connection\n assert(existing->connection_state);\n if (existing->connection_state->clear_pipe(existing))\n msgr->dispatch_queue.queue_reset(existing->connection_state.get());\n } else {\n // queue a reset on the new connection, which we're dumping for the old\n msgr->dispatch_queue.queue_reset(connection_state.get());\n\n // drop my Connection, and take a ref to the existing one. do not\n // clear existing->connection_state, since read_message and\n // write_message both dereference it without pipe_lock.\n connection_state = existing->connection_state;\n\n // make existing Connection reference us\n connection_state->reset_pipe(this);\n\n if (existing->delay_thread) {\n existing->delay_thread->steal_for_pipe(this);\n delay_thread = existing->delay_thread;\n existing->delay_thread = NULL;\n delay_thread->flush();\n }\n\n // steal incoming queue\n uint64_t replaced_conn_id = conn_id;\n conn_id = existing->conn_id;\n existing->conn_id = replaced_conn_id;\n\n // reset the in_seq if this is a hard reset from peer,\n // otherwise we respect our original connection's value\n in_seq = is_reset_from_peer ? 0 : existing->in_seq;\n in_seq_acked = in_seq;\n\n // steal outgoing queue and out_seq\n existing->requeue_sent();\n out_seq = existing->out_seq;\n ldout(msgr->cct,10) << \"accept re-queuing on out_seq \" << out_seq << \" in_seq \" << in_seq << dendl;\n for (map >::iterator p = existing->out_q.begin();\n p != existing->out_q.end();\n ++p)\n out_q[p->first].splice(out_q[p->first].begin(), p->second);\n }\n existing->stop_and_wait();\n existing->pipe_lock.Unlock();\n\n open:\n // open\n assert(pipe_lock.is_locked());\n connect_seq = connect.connect_seq + 1;\n peer_global_seq = connect.global_seq;\n assert(state == STATE_ACCEPTING);\n state = STATE_OPEN;\n ldout(msgr->cct,10) << \"accept success, connect_seq = \" << connect_seq << \", sending READY\" << dendl;\n\n // send READY reply\n reply.tag = (reply_tag ? reply_tag : CEPH_MSGR_TAG_READY);\n reply.features = policy.features_supported;\n reply.global_seq = msgr->get_global_seq();\n reply.connect_seq = connect_seq;\n reply.flags = 0;\n reply.authorizer_len = authorizer_reply.length();\n if (policy.lossy)\n reply.flags = reply.flags | CEPH_MSG_CONNECT_LOSSY;\n\n connection_state->set_features((uint64_t)reply.features & (uint64_t)connect.features);\n ldout(msgr->cct,10) << \"accept features \" << connection_state->get_features() << dendl;\n\n session_security.reset(\n get_auth_session_handler(msgr->cct,\n\t\t\t connect.authorizer_protocol,\n\t\t\t session_key,\n\t\t\t connection_state->get_features()));\n\n // notify\n msgr->dispatch_queue.queue_accept(connection_state.get());\n msgr->ms_deliver_handle_fast_accept(connection_state.get());\n\n // ok!\n if (msgr->dispatch_queue.stop)\n goto shutting_down;\n removed = msgr->accepting_pipes.erase(this);\n assert(removed == 1);\n register_pipe();\n msgr->lock.Unlock();\n pipe_lock.Unlock();\n\n r = tcp_write((char*)&reply, sizeof(reply));\n if (r < 0) {\n goto fail_registered;\n }\n\n if (reply.authorizer_len) {\n r = tcp_write(authorizer_reply.c_str(), authorizer_reply.length());\n if (r < 0) {\n goto fail_registered;\n }\n }\n\n if (reply_tag == CEPH_MSGR_TAG_SEQ) {\n if (tcp_write((char*)&existing_seq, sizeof(existing_seq)) < 0) {\n ldout(msgr->cct,2) << \"accept write error on in_seq\" << dendl;\n goto fail_registered;\n }\n if (tcp_read((char*)&newly_acked_seq, sizeof(newly_acked_seq)) < 0) {\n ldout(msgr->cct,2) << \"accept read error on newly_acked_seq\" << dendl;\n goto fail_registered;\n }\n }\n\n pipe_lock.Lock();\n discard_requeued_up_to(newly_acked_seq);\n if (state != STATE_CLOSED) {\n ldout(msgr->cct,10) << \"accept starting writer, state \" << get_state_name() << dendl;\n start_writer();\n }\n ldout(msgr->cct,20) << \"accept done\" << dendl;\n\n maybe_start_delay_thread();\n\n return 0; // success.\n\n fail_registered:\n ldout(msgr->cct, 10) << \"accept fault after register\" << dendl;\n\n if (msgr->cct->_conf->ms_inject_internal_delays) {\n ldout(msgr->cct, 10) << \" sleep for \" << msgr->cct->_conf->ms_inject_internal_delays << dendl;\n utime_t t;\n t.set_from_double(msgr->cct->_conf->ms_inject_internal_delays);\n t.sleep();\n }\n\n fail_unlocked:\n pipe_lock.Lock();\n if (state != STATE_CLOSED) {\n bool queued = is_queued();\n ldout(msgr->cct, 10) << \" queued = \" << (int)queued << dendl;\n if (queued) {\n state = policy.server ? STATE_STANDBY : STATE_CONNECTING;\n } else if (replaced) {\n state = STATE_STANDBY;\n } else {\n state = STATE_CLOSED;\n state_closed = true;\n }\n fault();\n if (queued || replaced)\n start_writer();\n }\n return -1;\n\n shutting_down:\n msgr->lock.Unlock();\n shutting_down_msgr_unlocked:\n assert(pipe_lock.is_locked());\n\n if (msgr->cct->_conf->ms_inject_internal_delays) {\n ldout(msgr->cct, 10) << \" sleep for \" << msgr->cct->_conf->ms_inject_internal_delays << dendl;\n utime_t t;\n t.set_from_double(msgr->cct->_conf->ms_inject_internal_delays);\n t.sleep();\n }\n\n state = STATE_CLOSED;\n state_closed = true;\n fault();\n return -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'auth/cephx: add authorizer challenge\n\nAllow the accepting side of a connection to reject an initial authorizer\nwith a random challenge. The connecting side then has to respond with an\nupdated authorizer proving they are able to decrypt the service's challenge\nand that the new authorizer was produced for this specific connection\ninstance.\n\nThe accepting side requires this challenge and response unconditionally\nif the client side advertises they have the feature bit. Servers wishing\nto require this improved level of authentication simply have to require\nthe appropriate feature.\n\nSigned-off-by: Sage Weil \n(cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b)\n\n# Conflicts:\n#\tsrc/auth/Auth.h\n#\tsrc/auth/cephx/CephxProtocol.cc\n#\tsrc/auth/cephx/CephxProtocol.h\n#\tsrc/auth/none/AuthNoneProtocol.h\n#\tsrc/msg/Dispatcher.h\n#\tsrc/msg/async/AsyncConnection.cc\n\n- const_iterator\n- ::decode vs decode\n- AsyncConnection ctor arg noise\n- get_random_bytes(), not cct->random()'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void addECSOption(char* packet, const size_t& packetSize, uint16_t* len, const ComboAddress& remote, int stamp)\n{\n string EDNSRR;\n struct dnsheader* dh = (struct dnsheader*) packet;\n\n EDNSSubnetOpts eso;\n if(stamp < 0)\n eso.source = Netmask(remote);\n else {\n ComboAddress stamped(remote);\n *((char*)&stamped.sin4.sin_addr.s_addr)=stamp;\n eso.source = Netmask(stamped);\n }\n string optRData=makeEDNSSubnetOptsString(eso);\n string record;\n generateEDNSOption(EDNSOptionCode::ECS, optRData, record);\n generateOptRR(record, EDNSRR);\n\n\n uint16_t arcount = ntohs(dh->arcount);\n /* does it fit in the existing buffer? */\n if (packetSize - *len > EDNSRR.size()) {\n arcount++;\n dh->arcount = htons(arcount);\n memcpy(packet + *len, EDNSRR.c_str(), EDNSRR.size());\n *len += EDNSRR.size();\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'dnsreplay: Bail out on a too small outgoing buffer'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ldb_kv_search(struct ldb_kv_context *ctx)\n{\n\tstruct ldb_context *ldb;\n\tstruct ldb_module *module = ctx->module;\n\tstruct ldb_request *req = ctx->req;\n\tvoid *data = ldb_module_get_private(module);\n\tstruct ldb_kv_private *ldb_kv =\n\t talloc_get_type(data, struct ldb_kv_private);\n\tint ret;\n\n\tldb = ldb_module_get_ctx(module);\n\n\tldb_request_set_state(req, LDB_ASYNC_PENDING);\n\n\tif (ldb_kv->kv_ops->lock_read(module) != 0) {\n\t\treturn LDB_ERR_OPERATIONS_ERROR;\n\t}\n\n\tif (ldb_kv_cache_load(module) != 0) {\n\t\tldb_kv->kv_ops->unlock_read(module);\n\t\treturn LDB_ERR_OPERATIONS_ERROR;\n\t}\n\n\tif (req->op.search.tree == NULL) {\n\t\tldb_kv->kv_ops->unlock_read(module);\n\t\treturn LDB_ERR_OPERATIONS_ERROR;\n\t}\n\n\tctx->tree = req->op.search.tree;\n\tctx->scope = req->op.search.scope;\n\tctx->base = req->op.search.base;\n\tctx->attrs = req->op.search.attrs;\n\n\tif ((req->op.search.base == NULL) || (ldb_dn_is_null(req->op.search.base) == true)) {\n\n\t\t/* Check what we should do with a NULL dn */\n\t\tswitch (req->op.search.scope) {\n\t\tcase LDB_SCOPE_BASE:\n\t\t\tldb_asprintf_errstring(ldb,\n\t\t\t\t\t \"NULL Base DN invalid for a base search\");\n\t\t\tret = LDB_ERR_INVALID_DN_SYNTAX;\n\t\t\tbreak;\n\t\tcase LDB_SCOPE_ONELEVEL:\n\t\t\tldb_asprintf_errstring(ldb,\n\t\t\t\t\t \"NULL Base DN invalid for a one-level search\");\n\t\t\tret = LDB_ERR_INVALID_DN_SYNTAX;\n\t\t\tbreak;\n\t\tcase LDB_SCOPE_SUBTREE:\n\t\tdefault:\n\t\t\t/* We accept subtree searches from a NULL base DN, ie over the whole DB */\n\t\t\tret = LDB_SUCCESS;\n\t\t}\n\t} else if (ldb_dn_is_valid(req->op.search.base) == false) {\n\n\t\t/* We don't want invalid base DNs here */\n\t\tldb_asprintf_errstring(ldb,\n\t\t\t\t \"Invalid Base DN: %s\",\n\t\t\t\t ldb_dn_get_linearized(req->op.search.base));\n\t\tret = LDB_ERR_INVALID_DN_SYNTAX;\n\n\t} else if (req->op.search.scope == LDB_SCOPE_BASE) {\n\n\t\t/*\n\t\t * If we are LDB_SCOPE_BASE, do just one search and\n\t\t * return early. This is critical to ensure we do not\n\t\t * go into the index code for special DNs, as that\n\t\t * will try to look up an index record for a special\n\t\t * record (which doesn't exist).\n\t\t */\n\t\tret = ldb_kv_search_and_return_base(ldb_kv, ctx);\n\n\t\tldb_kv->kv_ops->unlock_read(module);\n\n\t\treturn ret;\n\n\t} else if (ldb_kv->check_base) {\n\t\t/*\n\t\t * This database has been marked as\n\t\t * 'checkBaseOnSearch', so do a spot check of the base\n\t\t * dn. Also optimise the subsequent filter by filling\n\t\t * in the ctx->base to be exactly case correct\n\t\t */\n\t\tret = ldb_kv_search_base(\n\t\t module, ctx, req->op.search.base, &ctx->base);\n\n\t\tif (ret == LDB_ERR_NO_SUCH_OBJECT) {\n\t\t\tldb_asprintf_errstring(ldb,\n\t\t\t\t\t \"No such Base DN: %s\",\n\t\t\t\t\t ldb_dn_get_linearized(req->op.search.base));\n\t\t}\n\n\t} else {\n\t\t/* If we are not checking the base DN life is easy */\n\t\tret = LDB_SUCCESS;\n\t}\n\n\tif (ret == LDB_SUCCESS) {\n\t\tuint32_t match_count = 0;\n\n\t\tret = ldb_kv_search_indexed(ctx, &match_count);\n\t\tif (ret == LDB_ERR_NO_SUCH_OBJECT) {\n\t\t\t/* Not in the index, therefore OK! */\n\t\t\tret = LDB_SUCCESS;\n\n\t\t}\n\t\t/* Check if we got just a normal error.\n\t\t * In that case proceed to a full search unless we got a\n\t\t * callback error */\n\t\tif (!ctx->request_terminated && ret != LDB_SUCCESS) {\n\t\t\t/* Not indexed, so we need to do a full scan */\n\t\t\tif (ldb_kv->warn_unindexed ||\n\t\t\t ldb_kv->disable_full_db_scan) {\n\t\t\t\t/* useful for debugging when slow performance\n\t\t\t\t * is caused by unindexed searches */\n\t\t\t\tchar *expression = ldb_filter_from_tree(ctx, ctx->tree);\n\t\t\t\tldb_debug(ldb, LDB_DEBUG_ERROR, \"ldb FULL SEARCH: %s SCOPE: %s DN: %s\",\n\t\t\t\t\t\t\texpression,\n\t\t\t\t\t\t\treq->op.search.scope==LDB_SCOPE_BASE?\"base\":\n\t\t\t\t\t\t\treq->op.search.scope==LDB_SCOPE_ONELEVEL?\"one\":\n\t\t\t\t\t\t\treq->op.search.scope==LDB_SCOPE_SUBTREE?\"sub\":\"UNKNOWN\",\n\t\t\t\t\t\t\tldb_dn_get_linearized(req->op.search.base));\n\n\t\t\t\ttalloc_free(expression);\n\t\t\t}\n\n\t\t\tif (match_count != 0) {\n\t\t\t\t/* the indexing code gave an error\n\t\t\t\t * after having returned at least one\n\t\t\t\t * entry. This means the indexes are\n\t\t\t\t * corrupt or a database record is\n\t\t\t\t * corrupt. We cannot continue with a\n\t\t\t\t * full search or we may return\n\t\t\t\t * duplicate entries\n\t\t\t\t */\n\t\t\t\tldb_kv->kv_ops->unlock_read(module);\n\t\t\t\treturn LDB_ERR_OPERATIONS_ERROR;\n\t\t\t}\n\n\t\t\tif (ldb_kv->disable_full_db_scan) {\n\t\t\t\tldb_set_errstring(ldb,\n\t\t\t\t\t\t \"ldb FULL SEARCH disabled\");\n\t\t\t\tldb_kv->kv_ops->unlock_read(module);\n\t\t\t\treturn LDB_ERR_INAPPROPRIATE_MATCHING;\n\t\t\t}\n\n\t\t\tret = ldb_kv_search_full(ctx);\n\t\t\tif (ret != LDB_SUCCESS) {\n\t\t\t\tldb_set_errstring(ldb, \"Indexed and full searches both failed!\\n\");\n\t\t\t}\n\t\t}\n\t}\n\n\tldb_kv->kv_ops->unlock_read(module);\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'CVE-2018-1140 ldb_tdb: Check for DN validity in add, rename and search\n\nThis ensures we fail with a good error code before an eventual ldb_dn_get_casefold() which\nwould otherwise fail.\n\nSigned-off-by: Andrew Bartlett \nReviewed-by: Douglas Bagnall \nBUG: https://bugzilla.samba.org/show_bug.cgi?id=13374'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool PackLinuxElf32::canPack()\n{\n union {\n unsigned char buf[sizeof(Elf32_Ehdr) + 14*sizeof(Elf32_Phdr)];\n //struct { Elf32_Ehdr ehdr; Elf32_Phdr phdr; } e;\n } u;\n COMPILE_TIME_ASSERT(sizeof(u.buf) <= 512)\n\n fi->seek(0, SEEK_SET);\n fi->readx(u.buf, sizeof(u.buf));\n fi->seek(0, SEEK_SET);\n Elf32_Ehdr const *const ehdr = (Elf32_Ehdr *) u.buf;\n\n // now check the ELF header\n if (checkEhdr(ehdr) != 0)\n return false;\n\n // additional requirements for linux/elf386\n if (get_te16(&ehdr->e_ehsize) != sizeof(*ehdr)) {\n throwCantPack(\"invalid Ehdr e_ehsize; try '--force-execve'\");\n return false;\n }\n if (e_phoff != sizeof(*ehdr)) {// Phdrs not contiguous with Ehdr\n throwCantPack(\"non-contiguous Ehdr/Phdr; try '--force-execve'\");\n return false;\n }\n\n unsigned char osabi0 = u.buf[Elf32_Ehdr::EI_OSABI];\n // The first PT_LOAD32 must cover the beginning of the file (0==p_offset).\n Elf32_Phdr const *phdr = phdri;\n note_size = 0;\n for (unsigned j=0; j < e_phnum; ++phdr, ++j) {\n if (j >= 14) {\n throwCantPack(\"too many ElfXX_Phdr; try '--force-execve'\");\n return false;\n }\n unsigned const p_type = get_te32(&phdr->p_type);\n unsigned const p_offset = get_te32(&phdr->p_offset);\n if (1!=exetype && PT_LOAD32 == p_type) { // 1st PT_LOAD\n exetype = 1;\n load_va = get_te32(&phdr->p_vaddr); // class data member\n\n // Cast on next line is to avoid a compiler bug (incorrect complaint) in\n // Microsoft (R) C/C++ Optimizing Compiler Version 19.00.24215.1 for x64\n // error C4319: '~': zero extending 'unsigned int' to 'upx_uint64_t' of greater size\n unsigned const off = ~page_mask & (unsigned)load_va;\n\n if (off && off == p_offset) { // specific hint\n throwCantPack(\"Go-language PT_LOAD: try hemfix.c, or try '--force-execve'\");\n // Fixing it inside upx fails because packExtent() reads original file.\n return false;\n }\n if (0 != p_offset) { // 1st PT_LOAD must cover Ehdr and Phdr\n throwCantPack(\"first PT_LOAD.p_offset != 0; try '--force-execve'\");\n return false;\n }\n hatch_off = ~3u & (3+ get_te32(&phdr->p_memsz));\n }\n if (PT_NOTE32 == p_type) {\n unsigned const x = get_te32(&phdr->p_memsz);\n if ( sizeof(elfout.notes) < x // beware overflow of note_size\n || (sizeof(elfout.notes) < (note_size += x)) ) {\n throwCantPack(\"PT_NOTEs too big; try '--force-execve'\");\n return false;\n }\n if (osabi_note && Elf32_Ehdr::ELFOSABI_NONE==osabi0) { // Still seems to be generic.\n struct {\n struct Elf32_Nhdr nhdr;\n char name[8];\n unsigned body;\n } note;\n memset(¬e, 0, sizeof(note));\n fi->seek(p_offset, SEEK_SET);\n fi->readx(¬e, sizeof(note));\n fi->seek(0, SEEK_SET);\n if (4==get_te32(¬e.nhdr.descsz)\n && 1==get_te32(¬e.nhdr.type)\n // && 0==note.end\n && (1+ strlen(osabi_note))==get_te32(¬e.nhdr.namesz)\n && 0==strcmp(osabi_note, (char const *)¬e.name[0])\n ) {\n osabi0 = ei_osabi; // Specified by PT_NOTE.\n }\n }\n }\n }\n if (Elf32_Ehdr::ELFOSABI_NONE ==osabi0\n || Elf32_Ehdr::ELFOSABI_LINUX==osabi0) { // No EI_OSBAI, no PT_NOTE.\n unsigned const arm_eabi = 0xff000000u & get_te32(&ehdr->e_flags);\n if (Elf32_Ehdr::EM_ARM==e_machine\n && (EF_ARM_EABI_VER5==arm_eabi\n || EF_ARM_EABI_VER4==arm_eabi ) ) {\n // armel-eabi armeb-eabi ARM Linux EABI version 4 is a mess.\n ei_osabi = osabi0 = Elf32_Ehdr::ELFOSABI_LINUX;\n }\n else {\n osabi0 = opt->o_unix.osabi0; // Possibly specified by command-line.\n }\n }\n if (osabi0!=ei_osabi) {\n return false;\n }\n\n // We want to compress position-independent executable (gcc -pie)\n // main programs, but compressing a shared library must be avoided\n // because the result is no longer usable. In theory, there is no way\n // to tell them apart: both are just ET_DYN. Also in theory,\n // neither the presence nor the absence of any particular symbol name\n // can be used to tell them apart; there are counterexamples.\n // However, we will use the following heuristic suggested by\n // Peter S. Mazinger September 2005:\n // If a ET_DYN has __libc_start_main as a global undefined symbol,\n // then the file is a position-independent executable main program\n // (that depends on libc.so.6) and is eligible to be compressed.\n // Otherwise (no __libc_start_main as global undefined): skip it.\n // Also allow __uClibc_main and __uClibc_start_main .\n\n if (Elf32_Ehdr::ET_DYN==get_te16(&ehdr->e_type)) {\n // The DT_SYMTAB has no designated length. Read the whole file.\n alloc_file_image(file_image, file_size);\n fi->seek(0, SEEK_SET);\n fi->readx(file_image, file_size);\n memcpy(&ehdri, ehdr, sizeof(Elf32_Ehdr));\n phdri= (Elf32_Phdr *)((size_t)e_phoff + file_image); // do not free() !!\n shdri= (Elf32_Shdr *)((size_t)e_shoff + file_image); // do not free() !!\n\n sec_strndx = &shdri[get_te16(&ehdr->e_shstrndx)];\n shstrtab = (char const *)(get_te32(&sec_strndx->sh_offset) + file_image);\n sec_dynsym = elf_find_section_type(Elf32_Shdr::SHT_DYNSYM);\n if (sec_dynsym)\n sec_dynstr = get_te32(&sec_dynsym->sh_link) + shdri;\n\n if (Elf32_Shdr::SHT_STRTAB != get_te32(&sec_strndx->sh_type)\n || 0!=strcmp((char const *)\".shstrtab\",\n &shstrtab[get_te32(&sec_strndx->sh_name)]) ) {\n throwCantPack(\"bad e_shstrndx\");\n }\n\n phdr= phdri;\n for (int j= e_phnum; --j>=0; ++phdr)\n if (Elf32_Phdr::PT_DYNAMIC==get_te32(&phdr->p_type)) {\n dynseg= (Elf32_Dyn const *)(check_pt_dynamic(phdr) + file_image);\n invert_pt_dynamic(dynseg);\n break;\n }\n // elf_find_dynamic() returns 0 if 0==dynseg.\n dynstr= (char const *)elf_find_dynamic(Elf32_Dyn::DT_STRTAB);\n dynsym= (Elf32_Sym const *)elf_find_dynamic(Elf32_Dyn::DT_SYMTAB);\n\n if (opt->o_unix.force_pie\n || Elf32_Dyn::DF_1_PIE & elf_unsigned_dynamic(Elf32_Dyn::DT_FLAGS_1)\n || calls_crt1((Elf32_Rel const *)elf_find_dynamic(Elf32_Dyn::DT_REL),\n (int)elf_unsigned_dynamic(Elf32_Dyn::DT_RELSZ))\n || calls_crt1((Elf32_Rel const *)elf_find_dynamic(Elf32_Dyn::DT_JMPREL),\n (int)elf_unsigned_dynamic(Elf32_Dyn::DT_PLTRELSZ))) {\n is_pie = true;\n goto proceed; // calls C library init for main program\n }\n\n // Heuristic HACK for shared libraries (compare Darwin (MacOS) Dylib.)\n // If there is an existing DT_INIT, and if everything that the dynamic\n // linker ld-linux needs to perform relocations before calling DT_INIT\n // resides below the first SHT_EXECINSTR Section in one PT_LOAD, then\n // compress from the first executable Section to the end of that PT_LOAD.\n // We must not alter anything that ld-linux might touch before it calls\n // the DT_INIT function.\n //\n // Obviously this hack requires that the linker script put pieces\n // into good positions when building the original shared library,\n // and also requires ld-linux to behave.\n\n // Apparently glibc-2.13.90 insists on 0==e_ident[EI_PAD..15],\n // so compressing shared libraries may be doomed anyway.\n // 2011-06-01: stub.shlib-init.S works around by installing hatch\n // at end of .text.\n\n if (/*jni_onload_sym ||*/ elf_find_dynamic(upx_dt_init)) {\n if (this->e_machine!=Elf32_Ehdr::EM_386\n && this->e_machine!=Elf32_Ehdr::EM_MIPS\n && this->e_machine!=Elf32_Ehdr::EM_ARM)\n goto abandon; // need stub: EM_PPC\n if (elf_has_dynamic(Elf32_Dyn::DT_TEXTREL)) {\n throwCantPack(\"DT_TEXTREL found; re-compile with -fPIC\");\n goto abandon;\n }\n Elf32_Shdr const *shdr = shdri;\n xct_va = ~0u;\n if (e_shnum) {\n for (int j= e_shnum; --j>=0; ++shdr) {\n unsigned const sh_type = get_te32(&shdr->sh_type);\n if (Elf32_Shdr::SHF_EXECINSTR & get_te32(&shdr->sh_flags)) {\n xct_va = umin(xct_va, get_te32(&shdr->sh_addr));\n }\n // Hook the first slot of DT_PREINIT_ARRAY or DT_INIT_ARRAY.\n if (( Elf32_Dyn::DT_PREINIT_ARRAY==upx_dt_init\n && Elf32_Shdr::SHT_PREINIT_ARRAY==sh_type)\n || ( Elf32_Dyn::DT_INIT_ARRAY ==upx_dt_init\n && Elf32_Shdr::SHT_INIT_ARRAY ==sh_type) ) {\n user_init_off = get_te32(&shdr->sh_offset);\n user_init_va = get_te32(&file_image[user_init_off]);\n }\n // By default /usr/bin/ld leaves 4 extra DT_NULL to support pre-linking.\n // Take one as a last resort.\n if ((Elf32_Dyn::DT_INIT==upx_dt_init || !upx_dt_init)\n && Elf32_Shdr::SHT_DYNAMIC == sh_type) {\n unsigned const n = get_te32(&shdr->sh_size) / sizeof(Elf32_Dyn);\n Elf32_Dyn *dynp = (Elf32_Dyn *)&file_image[get_te32(&shdr->sh_offset)];\n for (; Elf32_Dyn::DT_NULL != dynp->d_tag; ++dynp) {\n if (upx_dt_init == get_te32(&dynp->d_tag)) {\n break; // re-found DT_INIT\n }\n }\n if ((1+ dynp) < (n+ dynseg)) { // not the terminator, so take it\n user_init_va = get_te32(&dynp->d_val); // 0 if (0==upx_dt_init)\n set_te32(&dynp->d_tag, upx_dt_init = Elf32_Dyn::DT_INIT);\n user_init_off = (char const *)&dynp->d_val - (char const *)&file_image[0];\n }\n }\n }\n }\n else { // no Sections; use heuristics\n unsigned const strsz = elf_unsigned_dynamic(Elf32_Dyn::DT_STRSZ);\n unsigned const strtab = elf_unsigned_dynamic(Elf32_Dyn::DT_STRTAB);\n unsigned const relsz = elf_unsigned_dynamic(Elf32_Dyn::DT_RELSZ);\n unsigned const rel = elf_unsigned_dynamic(Elf32_Dyn::DT_REL);\n unsigned const init = elf_unsigned_dynamic(upx_dt_init);\n if ((init == (relsz + rel ) && rel == (strsz + strtab))\n || (init == (strsz + strtab) && strtab == (relsz + rel ))\n ) {\n xct_va = init;\n user_init_va = init;\n user_init_off = elf_get_offset_from_address(init);\n }\n }\n // Rely on 0==elf_unsigned_dynamic(tag) if no such tag.\n unsigned const va_gash = elf_unsigned_dynamic(Elf32_Dyn::DT_GNU_HASH);\n unsigned const va_hash = elf_unsigned_dynamic(Elf32_Dyn::DT_HASH);\n if (xct_va < va_gash || (0==va_gash && xct_va < va_hash)\n || xct_va < elf_unsigned_dynamic(Elf32_Dyn::DT_STRTAB)\n || xct_va < elf_unsigned_dynamic(Elf32_Dyn::DT_SYMTAB)\n || xct_va < elf_unsigned_dynamic(Elf32_Dyn::DT_REL)\n || xct_va < elf_unsigned_dynamic(Elf32_Dyn::DT_RELA)\n || xct_va < elf_unsigned_dynamic(Elf32_Dyn::DT_JMPREL)\n || xct_va < elf_unsigned_dynamic(Elf32_Dyn::DT_VERDEF)\n || xct_va < elf_unsigned_dynamic(Elf32_Dyn::DT_VERSYM)\n || xct_va < elf_unsigned_dynamic(Elf32_Dyn::DT_VERNEEDED) ) {\n throwCantPack(\"DT_ tag above stub\");\n goto abandon;\n }\n if (!opt->o_unix.android_shlib) {\n phdr = phdri;\n for (unsigned j= 0; j < e_phnum; ++phdr, ++j) {\n unsigned const vaddr = get_te32(&phdr->p_vaddr);\n if (PT_NOTE32 == get_te32(&phdr->p_type)\n && xct_va < vaddr) {\n char buf[40]; snprintf(buf, sizeof(buf),\n \"PT_NOTE %#x above stub\", vaddr);\n throwCantPack(buf);\n goto abandon;\n }\n }\n }\n xct_off = elf_get_offset_from_address(xct_va);\n if (opt->debug.debug_level) {\n fprintf(stderr, \"shlib canPack: xct_va=%#lx xct_off=%lx\\n\",\n (long)xct_va, (long)xct_off);\n }\n goto proceed; // But proper packing depends on checking xct_va.\n }\n else\n throwCantPack(\"need DT_INIT; try \\\"void _init(void){}\\\"\");\nabandon:\n return false;\nproceed: ;\n }\n // XXX Theoretically the following test should be first,\n // but PackUnix::canPack() wants 0!=exetype ?\n if (!super::canPack())\n return false;\n assert(exetype == 1);\n exetype = 0;\n\n // set options\n opt->o_unix.blocksize = blocksize = file_size;\n return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'More checking of PT_DYNAMIC and its contents.\n\nhttps://github.com/upx/upx/issues/206\n\tmodified: p_lx_elf.cpp'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int compat_get_timex(struct timex *txc, const struct compat_timex __user *utp)\n{\n\tstruct compat_timex tx32;\n\n\tif (copy_from_user(&tx32, utp, sizeof(struct compat_timex)))\n\t\treturn -EFAULT;\n\n\ttxc->modes = tx32.modes;\n\ttxc->offset = tx32.offset;\n\ttxc->freq = tx32.freq;\n\ttxc->maxerror = tx32.maxerror;\n\ttxc->esterror = tx32.esterror;\n\ttxc->status = tx32.status;\n\ttxc->constant = tx32.constant;\n\ttxc->precision = tx32.precision;\n\ttxc->tolerance = tx32.tolerance;\n\ttxc->time.tv_sec = tx32.time.tv_sec;\n\ttxc->time.tv_usec = tx32.time.tv_usec;\n\ttxc->tick = tx32.tick;\n\ttxc->ppsfreq = tx32.ppsfreq;\n\ttxc->jitter = tx32.jitter;\n\ttxc->shift = tx32.shift;\n\ttxc->stabil = tx32.stabil;\n\ttxc->jitcnt = tx32.jitcnt;\n\ttxc->calcnt = tx32.calcnt;\n\ttxc->errcnt = tx32.errcnt;\n\ttxc->stbcnt = tx32.stbcnt;\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'compat: fix 4-byte infoleak via uninitialized struct field\n\nCommit 3a4d44b61625 (\"ntp: Move adjtimex related compat syscalls to\nnative counterparts\") removed the memset() in compat_get_timex(). Since\nthen, the compat adjtimex syscall can invoke do_adjtimex() with an\nuninitialized ->tai.\n\nIf do_adjtimex() doesn't write to ->tai (e.g. because the arguments are\ninvalid), compat_put_timex() then copies the uninitialized ->tai field\nto userspace.\n\nFix it by adding the memset() back.\n\nFixes: 3a4d44b61625 (\"ntp: Move adjtimex related compat syscalls to native counterparts\")\nSigned-off-by: Jann Horn \nAcked-by: Kees Cook \nAcked-by: Al Viro \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: _rpc_batch_job(slurm_msg_t *msg, bool new_msg)\n{\n\tbatch_job_launch_msg_t *req = (batch_job_launch_msg_t *)msg->data;\n\tbool first_job_run;\n\tint rc = SLURM_SUCCESS;\n\tbool\t replied = false, revoked;\n\tslurm_addr_t *cli = &msg->orig_addr;\n\n\tif (new_msg) {\n\t\tuid_t req_uid = g_slurm_auth_get_uid(msg->auth_cred,\n\t\t\t\t\t\t conf->auth_info);\n\t\tif (!_slurm_authorized_user(req_uid)) {\n\t\t\terror(\"Security violation, batch launch RPC from uid %d\",\n\t\t\t req_uid);\n\t\t\trc = ESLURM_USER_ID_MISSING; /* or bad in this case */\n\t\t\tgoto done;\n\t\t}\n\t}\n\n\tif (_launch_job_test(req->job_id)) {\n\t\terror(\"Job %u already running, do not launch second copy\",\n\t\t req->job_id);\n\t\trc = ESLURM_DUPLICATE_JOB_ID;\t/* job already running */\n\t\t_launch_job_fail(req->job_id, rc);\n\t\tgoto done;\n\t}\n\n\tslurm_cred_handle_reissue(conf->vctx, req->cred);\n\tif (slurm_cred_revoked(conf->vctx, req->cred)) {\n\t\terror(\"Job %u already killed, do not launch batch job\",\n\t\t req->job_id);\n\t\trc = ESLURMD_CREDENTIAL_REVOKED;\t/* job already ran */\n\t\tgoto done;\n\t}\n\n\ttask_g_slurmd_batch_request(req->job_id, req);\t/* determine task affinity */\n\n\tslurm_mutex_lock(&prolog_mutex);\n\tfirst_job_run = !slurm_cred_jobid_cached(conf->vctx, req->job_id);\n\n\t/* BlueGene prolog waits for partition boot and is very slow.\n\t * On any system we might need to load environment variables\n\t * for Moab (see --get-user-env), which could also be slow.\n\t * Just reply now and send a separate kill job request if the\n\t * prolog or launch fail. */\n\treplied = true;\n\tif (new_msg && (slurm_send_rc_msg(msg, rc) < 1)) {\n\t\t/* The slurmctld is no longer waiting for a reply.\n\t\t * This typically indicates that the slurmd was\n\t\t * blocked from memory and/or CPUs and the slurmctld\n\t\t * has requeued the batch job request. */\n\t\terror(\"Could not confirm batch launch for job %u, \"\n\t\t \"aborting request\", req->job_id);\n\t\trc = SLURM_COMMUNICATIONS_SEND_ERROR;\n\t\tslurm_mutex_unlock(&prolog_mutex);\n\t\tgoto done;\n\t}\n\n\t/*\n\t * Insert jobid into credential context to denote that\n\t * we've now \"seen\" an instance of the job\n\t */\n\tif (first_job_run) {\n\t\tjob_env_t job_env;\n\t\tslurm_cred_insert_jobid(conf->vctx, req->job_id);\n\t\t_add_job_running_prolog(req->job_id);\n\t\tslurm_mutex_unlock(&prolog_mutex);\n\n\t\tmemset(&job_env, 0, sizeof(job_env_t));\n\n\t\tjob_env.jobid = req->job_id;\n\t\tjob_env.step_id = req->step_id;\n\t\tjob_env.node_list = req->nodes;\n\t\tjob_env.partition = req->partition;\n\t\tjob_env.spank_job_env = req->spank_job_env;\n\t\tjob_env.spank_job_env_size = req->spank_job_env_size;\n\t\tjob_env.uid = req->uid;\n\t\tjob_env.user_name = req->user_name;\n\t\t/*\n\t \t * Run job prolog on this node\n\t \t */\n#if defined(HAVE_BG)\n\t\tselect_g_select_jobinfo_get(req->select_jobinfo,\n\t\t\t\t\t SELECT_JOBDATA_BLOCK_ID,\n\t\t\t\t\t &job_env.resv_id);\n#elif defined(HAVE_ALPS_CRAY)\n\t\tjob_env.resv_id = select_g_select_jobinfo_xstrdup(\n\t\t\treq->select_jobinfo, SELECT_PRINT_RESV_ID);\n#endif\n\t\tif (container_g_create(req->job_id))\n\t\t\terror(\"container_g_create(%u): %m\", req->job_id);\n\t\trc = _run_prolog(&job_env, req->cred);\n\t\txfree(job_env.resv_id);\n\t\tif (rc) {\n\t\t\tint term_sig, exit_status;\n\t\t\tif (WIFSIGNALED(rc)) {\n\t\t\t\texit_status = 0;\n\t\t\t\tterm_sig = WTERMSIG(rc);\n\t\t\t} else {\n\t\t\t\texit_status = WEXITSTATUS(rc);\n\t\t\t\tterm_sig = 0;\n\t\t\t}\n\t\t\terror(\"[job %u] prolog failed status=%d:%d\",\n\t\t\t req->job_id, exit_status, term_sig);\n\t\t\t_prolog_error(req, rc);\n\t\t\trc = ESLURMD_PROLOG_FAILED;\n\t\t\tgoto done;\n\t\t}\n\t} else {\n\t\tslurm_mutex_unlock(&prolog_mutex);\n\t\t_wait_for_job_running_prolog(req->job_id);\n\t}\n\n\tif (_get_user_env(req) < 0) {\n\t\tbool requeue = _requeue_setup_env_fail();\n\t\tif (requeue) {\n\t\t\trc = ESLURMD_SETUP_ENVIRONMENT_ERROR;\n\t\t\tgoto done;\n\t\t}\n\t}\n\t_set_batch_job_limits(msg);\n\n\t/* Since job could have been killed while the prolog was\n\t * running (especially on BlueGene, which can take minutes\n\t * for partition booting). Test if the credential has since\n\t * been revoked and exit as needed. */\n\tif (slurm_cred_revoked(conf->vctx, req->cred)) {\n\t\tinfo(\"Job %u already killed, do not launch batch job\",\n\t\t req->job_id);\n\t\trc = ESLURMD_CREDENTIAL_REVOKED; /* job already ran */\n\t\tgoto done;\n\t}\n\n\tslurm_mutex_lock(&launch_mutex);\n\tif (req->step_id == SLURM_BATCH_SCRIPT)\n\t\tinfo(\"Launching batch job %u for UID %d\",\n\t\t req->job_id, req->uid);\n\telse\n\t\tinfo(\"Launching batch job %u.%u for UID %d\",\n\t\t req->job_id, req->step_id, req->uid);\n\n\tdebug3(\"_rpc_batch_job: call to _forkexec_slurmstepd\");\n\trc = _forkexec_slurmstepd(LAUNCH_BATCH_JOB, (void *)req, cli, NULL,\n\t\t\t\t (hostset_t)NULL, SLURM_PROTOCOL_VERSION);\n\tdebug3(\"_rpc_batch_job: return from _forkexec_slurmstepd: %d\", rc);\n\n\tslurm_mutex_unlock(&launch_mutex);\n\t_launch_complete_add(req->job_id);\n\n\t/* On a busy system, slurmstepd may take a while to respond,\n\t * if the job was cancelled in the interim, run through the\n\t * abort logic below. */\n\trevoked = slurm_cred_revoked(conf->vctx, req->cred);\n\tif (revoked)\n\t\t_launch_complete_rm(req->job_id);\n\tif (revoked && _is_batch_job_finished(req->job_id)) {\n\t\t/* If configured with select/serial and the batch job already\n\t\t * completed, consider the job sucessfully launched and do\n\t\t * not repeat termination logic below, which in the worst case\n\t\t * just slows things down with another message. */\n\t\trevoked = false;\n\t}\n\tif (revoked) {\n\t\tinfo(\"Job %u killed while launch was in progress\",\n\t\t req->job_id);\n\t\tsleep(1);\t/* give slurmstepd time to create\n\t\t\t\t * the communication socket */\n\t\t_terminate_all_steps(req->job_id, true);\n\t\trc = ESLURMD_CREDENTIAL_REVOKED;\n\t\tgoto done;\n\t}\n\ndone:\n\tif (!replied) {\n\t\tif (new_msg && (slurm_send_rc_msg(msg, rc) < 1)) {\n\t\t\t/* The slurmctld is no longer waiting for a reply.\n\t\t\t * This typically indicates that the slurmd was\n\t\t\t * blocked from memory and/or CPUs and the slurmctld\n\t\t\t * has requeued the batch job request. */\n\t\t\terror(\"Could not confirm batch launch for job %u, \"\n\t\t\t \"aborting request\", req->job_id);\n\t\t\trc = SLURM_COMMUNICATIONS_SEND_ERROR;\n\t\t} else {\n\t\t\t/* No need to initiate separate reply below */\n\t\t\trc = SLURM_SUCCESS;\n\t\t}\n\t}\n\tif (rc != SLURM_SUCCESS) {\n\t\t/* prolog or job launch failure,\n\t\t * tell slurmctld that the job failed */\n\t\tif (req->step_id == SLURM_BATCH_SCRIPT)\n\t\t\t_launch_job_fail(req->job_id, rc);\n\t\telse\n\t\t\t_abort_step(req->job_id, req->step_id);\n\t}\n\n\t/*\n\t * If job prolog failed or we could not reply,\n\t * initiate message to slurmctld with current state\n\t */\n\tif ((rc == ESLURMD_PROLOG_FAILED)\n\t || (rc == SLURM_COMMUNICATIONS_SEND_ERROR)\n\t || (rc == ESLURMD_SETUP_ENVIRONMENT_ERROR)) {\n\t\tsend_registration_msg(rc, false);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Validate gid and user_name values provided to slurmd up front.\n\nDo not defer until later, and do not potentially miss out on proper\nvalidation of the user_name field which can lead to improper authentication\nhandling.\n\nCVE-2018-10995.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static ssize_t match_busid_show(struct device_driver *drv, char *buf)\n{\n\tint i;\n\tchar *out = buf;\n\n\tspin_lock(&busid_table_lock);\n\tfor (i = 0; i < MAX_BUSID; i++)\n\t\tif (busid_table[i].name[0])\n\t\t\tout += sprintf(out, \"%s \", busid_table[i].name);\n\tspin_unlock(&busid_table_lock);\n\tout += sprintf(out, \"\\n\");\n\n\treturn out - buf;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'usbip: usbip_host: fix NULL-ptr deref and use-after-free errors\n\nusbip_host updates device status without holding lock from stub probe,\ndisconnect and rebind code paths. When multiple requests to import a\ndevice are received, these unprotected code paths step all over each\nother and drive fails with NULL-ptr deref and use-after-free errors.\n\nThe driver uses a table lock to protect the busid array for adding and\ndeleting busids to the table. However, the probe, disconnect and rebind\npaths get the busid table entry and update the status without holding\nthe busid table lock. Add a new finer grain lock to protect the busid\nentry. This new lock will be held to search and update the busid entry\nfields from get_busid_idx(), add_match_busid() and del_match_busid().\n\nmatch_busid_show() does the same to access the busid entry fields.\n\nget_busid_priv() changed to return the pointer to the busid entry holding\nthe busid lock. stub_probe(), stub_disconnect() and stub_device_rebind()\ncall put_busid_priv() to release the busid lock before returning. This\nchanges fixes the unprotected code paths eliminating the race conditions\nin updating the busid entries.\n\nReported-by: Jakub Jirasek\nSigned-off-by: Shuah Khan (Samsung OSG) \nCc: stable \nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void put_busid_priv(struct bus_id_priv *bid)\n{\n\tspin_unlock(&bid->busid_lock);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'usbip: usbip_host: fix bad unlock balance during stub_probe()\n\nstub_probe() calls put_busid_priv() in an error path when device isn't\nfound in the busid_table. Fix it by making put_busid_priv() safe to be\ncalled with null struct bus_id_priv pointer.\n\nThis problem happens when \"usbip bind\" is run without loading usbip_host\ndriver and then running modprobe. The first failed bind attempt unbinds\nthe device from the original driver and when usbip_host is modprobed,\nstub_probe() runs and doesn't find the device in its busid table and calls\nput_busid_priv(0 with null bus_id_priv pointer.\n\nusbip-host 3-10.2: 3-10.2 is not in match_busid table... skip!\n\n[ 367.359679] =====================================\n[ 367.359681] WARNING: bad unlock balance detected!\n[ 367.359683] 4.17.0-rc4+ #5 Not tainted\n[ 367.359685] -------------------------------------\n[ 367.359688] modprobe/2768 is trying to release lock (\n[ 367.359689]\n==================================================================\n[ 367.359696] BUG: KASAN: null-ptr-deref in print_unlock_imbalance_bug+0x99/0x110\n[ 367.359699] Read of size 8 at addr 0000000000000058 by task modprobe/2768\n\n[ 367.359705] CPU: 4 PID: 2768 Comm: modprobe Not tainted 4.17.0-rc4+ #5\n\nFixes: 22076557b07c (\"usbip: usbip_host: fix NULL-ptr deref and use-after-free errors\") in usb-linus\nSigned-off-by: Shuah Khan (Samsung OSG) \nCc: stable \nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: Statement_Ptr Expand::operator()(Definition_Ptr d)\n {\n Env* env = environment();\n Definition_Obj dd = SASS_MEMORY_COPY(d);\n env->local_frame()[d->name() +\n (d->type() == Definition::MIXIN ? \"[m]\" : \"[f]\")] = dd;\n\n if (d->type() == Definition::FUNCTION && (\n Prelexer::calc_fn_call(d->name().c_str()) ||\n d->name() == \"element\" ||\n d->name() == \"expression\" ||\n d->name() == \"url\"\n )) {\n deprecated(\n \"Naming a function \\\"\" + d->name() + \"\\\" is disallowed and will be an error in future versions of Sass.\",\n \"This name conflicts with an existing CSS function with special parse rules.\",\n false, d->pstate()\n );\n }\n\n // set the static link so we can have lexical scoping\n dd->environment(env);\n return 0;\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fix segfault on empty custom properties\n\nOriginally reported in sass/sassc#225\n\nFixes sass/sassc#225\nSpec sass/sass-spec#1249'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static size_t optsize (lua_State *L, char opt, const char **fmt) {\n switch (opt) {\n case 'B': case 'b': return sizeof(char);\n case 'H': case 'h': return sizeof(short);\n case 'L': case 'l': return sizeof(long);\n case 'T': return sizeof(size_t);\n case 'f': return sizeof(float);\n case 'd': return sizeof(double);\n case 'x': return 1;\n case 'c': return getnum(L, fmt, 1);\n case 'i': case 'I': {\n int sz = getnum(L, fmt, sizeof(int));\n if (sz > MAXINTSIZE)\n luaL_error(L, \"integral size %d is larger than limit of %d\",\n sz, MAXINTSIZE);\n return sz;\n }\n default: return 0; /* other cases do not need alignment */\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190', 'CWE-787'], 'message': 'Security: update Lua struct package for security.\n\nDuring an auditing Apple found that the \"struct\" Lua package\nwe ship with Redis (http://www.inf.puc-rio.br/~roberto/struct/) contains\na security problem. A bound-checking statement fails because of integer\noverflow. The bug exists since we initially integrated this package with\nLua, when scripting was introduced, so every version of Redis with\nEVAL/EVALSHA capabilities exposed is affected.\n\nInstead of just fixing the bug, the library was updated to the latest\nversion shipped by the author.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void sock_release(struct socket *sock)\n{\n\tif (sock->ops) {\n\t\tstruct module *owner = sock->ops->owner;\n\n\t\tsock->ops->release(sock);\n\t\tsock->ops = NULL;\n\t\tmodule_put(owner);\n\t}\n\n\tif (rcu_dereference_protected(sock->wq, 1)->fasync_list)\n\t\tpr_err(\"%s: fasync list not empty!\\n\", __func__);\n\n\tif (!sock->file) {\n\t\tiput(SOCK_INODE(sock));\n\t\treturn;\n\t}\n\tsock->file = NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'socket: close race condition between sock_close() and sockfs_setattr()\n\nfchownat() doesn't even hold refcnt of fd until it figures out\nfd is really needed (otherwise is ignored) and releases it after\nit resolves the path. This means sock_close() could race with\nsockfs_setattr(), which leads to a NULL pointer dereference\nsince typically we set sock->sk to NULL in ->release().\n\nAs pointed out by Al, this is unique to sockfs. So we can fix this\nin socket layer by acquiring inode_lock in sock_close() and\nchecking against NULL in sockfs_setattr().\n\nsock_release() is called in many places, only the sock_close()\npath matters here. And fortunately, this should not affect normal\nsock_close() as it is only called when the last fd refcnt is gone.\nIt only affects sock_close() with a parallel sockfs_setattr() in\nprogress, which is not common.\n\nFixes: 86741ec25462 (\"net: core: Add a UID field to struct sock.\")\nReported-by: shankarapailoor \nCc: Tetsuo Handa \nCc: Lorenzo Colitti \nCc: Al Viro \nSigned-off-by: Cong Wang \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n BMPInfo\n bmp_info;\n\n Image\n *image;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n offset,\n start_position;\n\n MemoryInfo\n *pixel_info;\n\n Quantum\n index;\n\n register Quantum\n *q;\n\n register ssize_t\n i,\n x;\n\n register unsigned char\n *p;\n\n size_t\n bit,\n bytes_per_line,\n length;\n\n ssize_t\n count,\n y;\n\n unsigned char\n magick[12],\n *pixels;\n\n unsigned int\n blue,\n green,\n offset_bits,\n red;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Determine if this a BMP file.\n */\n (void) memset(&bmp_info,0,sizeof(bmp_info));\n bmp_info.ba_offset=0;\n start_position=0;\n offset_bits=0;\n count=ReadBlob(image,2,magick);\n if (count != 2)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n do\n {\n PixelInfo\n quantum_bits;\n\n PixelPacket\n shift;\n\n /*\n Verify BMP identifier.\n */\n if (bmp_info.ba_offset == 0)\n start_position=TellBlob(image)-2;\n bmp_info.ba_offset=0;\n while (LocaleNCompare((char *) magick,\"BA\",2) == 0)\n {\n bmp_info.file_size=ReadBlobLSBLong(image);\n bmp_info.ba_offset=ReadBlobLSBLong(image);\n bmp_info.offset_bits=ReadBlobLSBLong(image);\n count=ReadBlob(image,2,magick);\n if (count != 2)\n break;\n }\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Magick: %c%c\",\n magick[0],magick[1]);\n if ((count != 2) || ((LocaleNCompare((char *) magick,\"BM\",2) != 0) &&\n (LocaleNCompare((char *) magick,\"CI\",2) != 0)))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n bmp_info.file_size=ReadBlobLSBLong(image);\n (void) ReadBlobLSBLong(image);\n bmp_info.offset_bits=ReadBlobLSBLong(image);\n bmp_info.size=ReadBlobLSBLong(image);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" BMP size: %u\",\n bmp_info.size);\n if (bmp_info.size == 12)\n {\n /*\n OS/2 BMP image file.\n */\n (void) CopyMagickString(image->magick,\"BMP2\",MagickPathExtent);\n bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image));\n bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image));\n bmp_info.planes=ReadBlobLSBShort(image);\n bmp_info.bits_per_pixel=ReadBlobLSBShort(image);\n bmp_info.x_pixels=0;\n bmp_info.y_pixels=0;\n bmp_info.number_colors=0;\n bmp_info.compression=BI_RGB;\n bmp_info.image_size=0;\n bmp_info.alpha_mask=0;\n if (image->debug != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Format: OS/2 Bitmap\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Geometry: %.20gx%.20g\",(double) bmp_info.width,(double)\n bmp_info.height);\n }\n }\n else\n {\n /*\n Microsoft Windows BMP image file.\n */\n if (bmp_info.size < 40)\n ThrowReaderException(CorruptImageError,\"NonOS2HeaderSizeError\");\n bmp_info.width=(ssize_t) ReadBlobLSBSignedLong(image);\n bmp_info.height=(ssize_t) ReadBlobLSBSignedLong(image);\n bmp_info.planes=ReadBlobLSBShort(image);\n bmp_info.bits_per_pixel=ReadBlobLSBShort(image);\n bmp_info.compression=ReadBlobLSBLong(image);\n bmp_info.image_size=ReadBlobLSBLong(image);\n bmp_info.x_pixels=ReadBlobLSBLong(image);\n bmp_info.y_pixels=ReadBlobLSBLong(image);\n bmp_info.number_colors=ReadBlobLSBLong(image);\n bmp_info.colors_important=ReadBlobLSBLong(image);\n if (image->debug != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Format: MS Windows bitmap\");\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Geometry: %.20gx%.20g\",(double) bmp_info.width,(double)\n bmp_info.height);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Bits per pixel: %.20g\",(double) bmp_info.bits_per_pixel);\n switch (bmp_info.compression)\n {\n case BI_RGB:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_RGB\");\n break;\n }\n case BI_RLE4:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_RLE4\");\n break;\n }\n case BI_RLE8:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_RLE8\");\n break;\n }\n case BI_BITFIELDS:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_BITFIELDS\");\n break;\n }\n case BI_PNG:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_PNG\");\n break;\n }\n case BI_JPEG:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: BI_JPEG\");\n break;\n }\n default:\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Compression: UNKNOWN (%u)\",bmp_info.compression);\n }\n }\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Number of colors: %u\",bmp_info.number_colors);\n }\n bmp_info.red_mask=ReadBlobLSBLong(image);\n bmp_info.green_mask=ReadBlobLSBLong(image);\n bmp_info.blue_mask=ReadBlobLSBLong(image);\n if (bmp_info.size > 40)\n {\n double\n gamma;\n\n /*\n Read color management information.\n */\n bmp_info.alpha_mask=ReadBlobLSBLong(image);\n bmp_info.colorspace=ReadBlobLSBSignedLong(image);\n /*\n Decode 2^30 fixed point formatted CIE primaries.\n */\n# define BMP_DENOM ((double) 0x40000000)\n bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;\n\n gamma=bmp_info.red_primary.x+bmp_info.red_primary.y+\n bmp_info.red_primary.z;\n gamma=PerceptibleReciprocal(gamma);\n bmp_info.red_primary.x*=gamma;\n bmp_info.red_primary.y*=gamma;\n image->chromaticity.red_primary.x=bmp_info.red_primary.x;\n image->chromaticity.red_primary.y=bmp_info.red_primary.y;\n\n gamma=bmp_info.green_primary.x+bmp_info.green_primary.y+\n bmp_info.green_primary.z;\n gamma=PerceptibleReciprocal(gamma);\n bmp_info.green_primary.x*=gamma;\n bmp_info.green_primary.y*=gamma;\n image->chromaticity.green_primary.x=bmp_info.green_primary.x;\n image->chromaticity.green_primary.y=bmp_info.green_primary.y;\n\n gamma=bmp_info.blue_primary.x+bmp_info.blue_primary.y+\n bmp_info.blue_primary.z;\n gamma=PerceptibleReciprocal(gamma);\n bmp_info.blue_primary.x*=gamma;\n bmp_info.blue_primary.y*=gamma;\n image->chromaticity.blue_primary.x=bmp_info.blue_primary.x;\n image->chromaticity.blue_primary.y=bmp_info.blue_primary.y;\n\n /*\n Decode 16^16 fixed point formatted gamma_scales.\n */\n bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000;\n bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000;\n bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000;\n /*\n Compute a single gamma from the BMP 3-channel gamma.\n */\n image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+\n bmp_info.gamma_scale.z)/3.0;\n }\n else\n (void) CopyMagickString(image->magick,\"BMP3\",MagickPathExtent);\n\n if (bmp_info.size > 108)\n {\n size_t\n intent;\n\n /*\n Read BMP Version 5 color management information.\n */\n intent=ReadBlobLSBLong(image);\n switch ((int) intent)\n {\n case LCS_GM_BUSINESS:\n {\n image->rendering_intent=SaturationIntent;\n break;\n }\n case LCS_GM_GRAPHICS:\n {\n image->rendering_intent=RelativeIntent;\n break;\n }\n case LCS_GM_IMAGES:\n {\n image->rendering_intent=PerceptualIntent;\n break;\n }\n case LCS_GM_ABS_COLORIMETRIC:\n {\n image->rendering_intent=AbsoluteIntent;\n break;\n }\n }\n (void) ReadBlobLSBLong(image); /* Profile data */\n (void) ReadBlobLSBLong(image); /* Profile size */\n (void) ReadBlobLSBLong(image); /* Reserved byte */\n }\n }\n if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image))\n (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,\n \"LengthAndFilesizeDoNotMatch\",\"`%s'\",image->filename);\n else\n if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image))\n (void) ThrowMagickException(exception,GetMagickModule(),\n CorruptImageWarning,\"LengthAndFilesizeDoNotMatch\",\"`%s'\",\n image->filename);\n if (bmp_info.width <= 0)\n ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\");\n if (bmp_info.height == 0)\n ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\");\n if (bmp_info.planes != 1)\n ThrowReaderException(CorruptImageError,\"StaticPlanesValueNotEqualToOne\");\n if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) &&\n (bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) &&\n (bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32))\n ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n if (bmp_info.bits_per_pixel < 16 &&\n bmp_info.number_colors > (1U << bmp_info.bits_per_pixel))\n ThrowReaderException(CorruptImageError,\"UnrecognizedNumberOfColors\");\n if ((bmp_info.compression == 1) && (bmp_info.bits_per_pixel != 8))\n ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4))\n ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16))\n ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\");\n switch (bmp_info.compression)\n {\n case BI_RGB:\n image->compression=NoCompression;\n break;\n case BI_RLE8:\n case BI_RLE4:\n image->compression=RLECompression;\n break;\n case BI_BITFIELDS:\n break;\n case BI_JPEG:\n ThrowReaderException(CoderError,\"JPEGCompressNotSupported\");\n case BI_PNG:\n ThrowReaderException(CoderError,\"PNGCompressNotSupported\");\n default:\n ThrowReaderException(CorruptImageError,\"UnrecognizedImageCompression\");\n }\n image->columns=(size_t) MagickAbsoluteValue(bmp_info.width);\n image->rows=(size_t) MagickAbsoluteValue(bmp_info.height);\n image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8;\n image->alpha_trait=((bmp_info.alpha_mask != 0) &&\n (bmp_info.compression == BI_BITFIELDS)) ? BlendPixelTrait :\n UndefinedPixelTrait;\n if (bmp_info.bits_per_pixel < 16)\n {\n size_t\n one;\n\n image->storage_class=PseudoClass;\n image->colors=bmp_info.number_colors;\n one=1;\n if (image->colors == 0)\n image->colors=one << bmp_info.bits_per_pixel;\n }\n image->resolution.x=(double) bmp_info.x_pixels/100.0;\n image->resolution.y=(double) bmp_info.y_pixels/100.0;\n image->units=PixelsPerCentimeterResolution;\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n if (image->storage_class == PseudoClass)\n {\n unsigned char\n *bmp_colormap;\n\n size_t\n packet_size;\n\n /*\n Read BMP raster colormap.\n */\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Reading colormap of %.20g colors\",(double) image->colors);\n if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t)\n image->colors,4*sizeof(*bmp_colormap));\n if (bmp_colormap == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n if ((bmp_info.size == 12) || (bmp_info.size == 64))\n packet_size=3;\n else\n packet_size=4;\n offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET);\n if (offset < 0)\n {\n bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n count=ReadBlob(image,packet_size*image->colors,bmp_colormap);\n if (count != (ssize_t) (packet_size*image->colors))\n {\n bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);\n ThrowReaderException(CorruptImageError,\n \"InsufficientImageDataInFile\");\n }\n p=bmp_colormap;\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(*p++);\n image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(*p++);\n image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(*p++);\n if (packet_size == 4)\n p++;\n }\n bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);\n }\n /*\n Read image data.\n */\n if (bmp_info.offset_bits == offset_bits)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n offset_bits=bmp_info.offset_bits;\n offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET);\n if (offset < 0)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (bmp_info.compression == BI_RLE4)\n bmp_info.bits_per_pixel<<=1;\n bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32);\n length=(size_t) bytes_per_line*image->rows;\n if (((MagickSizeType) length/8) > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n if ((bmp_info.compression == BI_RGB) ||\n (bmp_info.compression == BI_BITFIELDS))\n {\n pixel_info=AcquireVirtualMemory((size_t) image->rows,\n MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Reading pixels (%.20g bytes)\",(double) length);\n count=ReadBlob(image,length,pixels);\n if (count != (ssize_t) length)\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\n \"InsufficientImageDataInFile\");\n }\n }\n else\n {\n /*\n Convert run-length encoded raster pixels.\n */\n pixel_info=AcquireVirtualMemory((size_t) image->rows,\n MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n status=DecodeImage(image,bmp_info.compression,pixels,\n image->columns*image->rows);\n if (status == MagickFalse)\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\n \"UnableToRunlengthDecodeImage\");\n }\n }\n /*\n Convert BMP raster image to pixel packets.\n */\n if (bmp_info.compression == BI_RGB)\n {\n /*\n We should ignore the alpha value in BMP3 files but there have been\n reports about 32 bit files with alpha. We do a quick check to see if\n the alpha channel contains a value that is not zero (default value).\n If we find a non zero value we asume the program that wrote the file\n wants to use the alpha channel.\n */\n if ((image->alpha_trait == UndefinedPixelTrait) && (bmp_info.size == 40) &&\n (bmp_info.bits_per_pixel == 32))\n {\n bytes_per_line=4*(image->columns);\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (*(p+3) != 0)\n {\n image->alpha_trait=BlendPixelTrait;\n y=-1;\n break;\n }\n p+=4;\n }\n }\n }\n bmp_info.alpha_mask=image->alpha_trait != UndefinedPixelTrait ?\n 0xff000000U : 0U;\n bmp_info.red_mask=0x00ff0000U;\n bmp_info.green_mask=0x0000ff00U;\n bmp_info.blue_mask=0x000000ffU;\n if (bmp_info.bits_per_pixel == 16)\n {\n /*\n RGB555.\n */\n bmp_info.red_mask=0x00007c00U;\n bmp_info.green_mask=0x000003e0U;\n bmp_info.blue_mask=0x0000001fU;\n }\n }\n (void) memset(&shift,0,sizeof(shift));\n (void) memset(&quantum_bits,0,sizeof(quantum_bits));\n if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32))\n {\n register unsigned int\n sample;\n\n /*\n Get shift and quantum bits info from bitfield masks.\n */\n if (bmp_info.red_mask != 0)\n while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0)\n {\n shift.red++;\n if (shift.red >= 32U)\n break;\n }\n if (bmp_info.green_mask != 0)\n while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0)\n {\n shift.green++;\n if (shift.green >= 32U)\n break;\n }\n if (bmp_info.blue_mask != 0)\n while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0)\n {\n shift.blue++;\n if (shift.blue >= 32U)\n break;\n }\n if (bmp_info.alpha_mask != 0)\n while (((bmp_info.alpha_mask << shift.alpha) & 0x80000000UL) == 0)\n {\n shift.alpha++;\n if (shift.alpha >= 32U)\n break;\n }\n sample=shift.red;\n while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0)\n {\n sample++;\n if (sample >= 32U)\n break;\n }\n quantum_bits.red=(MagickRealType) (sample-shift.red);\n sample=shift.green;\n while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0)\n {\n sample++;\n if (sample >= 32U)\n break;\n }\n quantum_bits.green=(MagickRealType) (sample-shift.green);\n sample=shift.blue;\n while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0)\n {\n sample++;\n if (sample >= 32U)\n break;\n }\n quantum_bits.blue=(MagickRealType) (sample-shift.blue);\n sample=shift.alpha;\n while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0)\n {\n sample++;\n if (sample >= 32U)\n break;\n }\n quantum_bits.alpha=(MagickRealType) (sample-shift.alpha);\n }\n switch (bmp_info.bits_per_pixel)\n {\n case 1:\n {\n /*\n Convert bitmap scanline.\n */\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < ((ssize_t) image->columns-7); x+=8)\n {\n for (bit=0; bit < 8; bit++)\n {\n index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);\n SetPixelIndex(image,index,q);\n q+=GetPixelChannels(image);\n }\n p++;\n }\n if ((image->columns % 8) != 0)\n {\n for (bit=0; bit < (image->columns % 8); bit++)\n {\n index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);\n SetPixelIndex(image,index,q);\n q+=GetPixelChannels(image);\n }\n p++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n (void) SyncImage(image,exception);\n break;\n }\n case 4:\n {\n /*\n Convert PseudoColor scanline.\n */\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < ((ssize_t) image->columns-1); x+=2)\n {\n ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0x0f),&index,\n exception);\n SetPixelIndex(image,index,q);\n q+=GetPixelChannels(image);\n ValidateColormapValue(image,(ssize_t) (*p & 0x0f),&index,exception);\n SetPixelIndex(image,index,q);\n q+=GetPixelChannels(image);\n p++;\n }\n if ((image->columns % 2) != 0)\n {\n ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0xf),&index,\n exception);\n SetPixelIndex(image,index,q);\n q+=GetPixelChannels(image);\n p++;\n x++;\n }\n if (x < (ssize_t) image->columns)\n break;\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n (void) SyncImage(image,exception);\n break;\n }\n case 8:\n {\n /*\n Convert PseudoColor scanline.\n */\n if ((bmp_info.compression == BI_RLE8) ||\n (bmp_info.compression == BI_RLE4))\n bytes_per_line=image->columns;\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=(ssize_t) image->columns; x != 0; --x)\n {\n ValidateColormapValue(image,(ssize_t) *p++,&index,exception);\n SetPixelIndex(image,index,q);\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n offset=(MagickOffsetType) (image->rows-y-1);\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n (void) SyncImage(image,exception);\n break;\n }\n case 16:\n {\n unsigned int\n alpha,\n pixel;\n\n /*\n Convert bitfield encoded 16-bit PseudoColor scanline.\n */\n if ((bmp_info.compression != BI_RGB) &&\n (bmp_info.compression != BI_BITFIELDS))\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\n \"UnrecognizedImageCompression\");\n }\n bytes_per_line=2*(image->columns+image->columns % 2);\n image->storage_class=DirectClass;\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=(unsigned int) (*p++);\n pixel|=(*p++) << 8;\n red=((pixel & bmp_info.red_mask) << shift.red) >> 16;\n if (quantum_bits.red == 5)\n red|=((red & 0xe000) >> 5);\n if (quantum_bits.red <= 8)\n red|=((red & 0xff00) >> 8);\n green=((pixel & bmp_info.green_mask) << shift.green) >> 16;\n if (quantum_bits.green == 5)\n green|=((green & 0xe000) >> 5);\n if (quantum_bits.green == 6)\n green|=((green & 0xc000) >> 6);\n if (quantum_bits.green <= 8)\n green|=((green & 0xff00) >> 8);\n blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16;\n if (quantum_bits.blue == 5)\n blue|=((blue & 0xe000) >> 5);\n if (quantum_bits.blue <= 8)\n blue|=((blue & 0xff00) >> 8);\n SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q);\n SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q);\n SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q);\n SetPixelAlpha(image,OpaqueAlpha,q);\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16;\n if (quantum_bits.alpha <= 8)\n alpha|=((alpha & 0xff00) >> 8);\n SetPixelAlpha(image,ScaleShortToQuantum(\n (unsigned short) alpha),q);\n }\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n offset=(MagickOffsetType) (image->rows-y-1);\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case 24:\n {\n /*\n Convert DirectColor scanline.\n */\n bytes_per_line=4*((image->columns*24+31)/32);\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelBlue(image,ScaleCharToQuantum(*p++),q);\n SetPixelGreen(image,ScaleCharToQuantum(*p++),q);\n SetPixelRed(image,ScaleCharToQuantum(*p++),q);\n SetPixelAlpha(image,OpaqueAlpha,q);\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n offset=(MagickOffsetType) (image->rows-y-1);\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case 32:\n {\n /*\n Convert bitfield encoded DirectColor scanline.\n */\n if ((bmp_info.compression != BI_RGB) &&\n (bmp_info.compression != BI_BITFIELDS))\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\n \"UnrecognizedImageCompression\");\n }\n bytes_per_line=4*(image->columns);\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n unsigned int\n alpha,\n pixel;\n\n p=pixels+(image->rows-y-1)*bytes_per_line;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=(unsigned int) (*p++);\n pixel|=((unsigned int) *p++ << 8);\n pixel|=((unsigned int) *p++ << 16);\n pixel|=((unsigned int) *p++ << 24);\n red=((pixel & bmp_info.red_mask) << shift.red) >> 16;\n if (quantum_bits.red == 8)\n red|=(red >> 8);\n green=((pixel & bmp_info.green_mask) << shift.green) >> 16;\n if (quantum_bits.green == 8)\n green|=(green >> 8);\n blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16;\n if (quantum_bits.blue == 8)\n blue|=(blue >> 8);\n SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q);\n SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q);\n SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q);\n SetPixelAlpha(image,OpaqueAlpha,q);\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16;\n if (quantum_bits.alpha == 8)\n alpha|=(alpha >> 8);\n SetPixelAlpha(image,ScaleShortToQuantum(\n (unsigned short) alpha),q);\n }\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n offset=(MagickOffsetType) (image->rows-y-1);\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n (image->rows-y),image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n default:\n {\n pixel_info=RelinquishVirtualMemory(pixel_info);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n }\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (y > 0)\n break;\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n if (bmp_info.height < 0)\n {\n Image\n *flipped_image;\n\n /*\n Correct image orientation.\n */\n flipped_image=FlipImage(image,exception);\n if (flipped_image != (Image *) NULL)\n {\n DuplicateBlob(flipped_image,image);\n ReplaceImageInList(&image, flipped_image);\n image=flipped_image;\n }\n }\n /*\n Proceed to next image.\n */\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n *magick='\\0';\n if (bmp_info.ba_offset != 0)\n {\n offset=SeekBlob(image,(MagickOffsetType) bmp_info.ba_offset,SEEK_SET);\n if (offset < 0)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n count=ReadBlob(image,2,magick);\n if ((count == 2) && (IsBMP(magick,2) != MagickFalse))\n {\n /*\n Acquire next image structure.\n */\n AcquireNextImage(image_info,image,exception);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n GetBlobSize(image));\n if (status == MagickFalse)\n break;\n }\n } while (IsBMP(magick,2) != MagickFalse);\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1177'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int nested_vmx_check_permission(struct kvm_vcpu *vcpu)\n{\n\tif (!to_vmx(vcpu)->nested.vmxon) {\n\t\tkvm_queue_exception(vcpu, UD_VECTOR);\n\t\treturn 0;\n\t}\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284'], 'message': 'kvm: nVMX: Enforce cpl=0 for VMX instructions\n\nVMX instructions executed inside a L1 VM will always trigger a VM exit\neven when executed with cpl 3. This means we must perform the\nprivilege check in software.\n\nFixes: 70f3aac964ae(\"kvm: nVMX: Remove superfluous VMX instruction fault checks\")\nCc: stable@vger.kernel.org\nSigned-off-by: Felix Wilhelm \nSigned-off-by: Paolo Bonzini '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void RemoteFsDevice::load()\n{\n if (RemoteFsDevice::constSambaAvahiProtocol==details.url.scheme()) {\n // Start Avahi listener...\n Avahi::self();\n QUrlQuery q(details.url);\n if (q.hasQueryItem(constServiceNameQuery)) {\n details.serviceName=q.queryItemValue(constServiceNameQuery);\n }\n\n if (!details.serviceName.isEmpty()) {\n AvahiService *srv=Avahi::self()->getService(details.serviceName);\n if (!srv || srv->getHost().isEmpty()) {\n sub=tr(\"Not Available\");\n } else {\n sub=tr(\"Available\");\n }\n }\n connect(Avahi::self(), SIGNAL(serviceAdded(QString)), SLOT(serviceAdded(QString)));\n connect(Avahi::self(), SIGNAL(serviceRemoved(QString)), SLOT(serviceRemoved(QString)));\n }\n\n if (isConnected()) {\n setAudioFolder();\n readOpts(settingsFileName(), opts, true);\n rescan(false); // Read from cache if we have it!\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-22'], 'message': 'Remove internal Samba shre mounting code, this had some privilege escalation issues, and is not well tested'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ~Mounter() { } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-22'], 'message': 'Remove internal Samba shre mounting code, this had some privilege escalation issues, and is not well tested'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void Avahi::addService(int, int, const QString &name, const QString &type, const QString &domain, uint)\n{\n if (isLocalDomain(domain) && !services.contains(name)) {\n AvahiService *srv=new AvahiService(name, type, domain);\n services.insert(name, srv);\n connect(srv, SIGNAL(serviceResolved(QString)), this, SIGNAL(serviceAdded(QString)));\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-22'], 'message': 'Remove internal Samba shre mounting code, this had some privilege escalation issues, and is not well tested'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void Mounter::startTimer()\n{\n if (!timer) {\n timer=new QTimer(this);\n connect(timer, SIGNAL(timeout()), SLOT(timeout()));\n }\n timer->start(30000);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-22'], 'message': 'Remove internal Samba shre mounting code, this had some privilege escalation issues, and is not well tested'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ext4_read_inode_bitmap(struct super_block *sb, ext4_group_t block_group)\n{\n\tstruct ext4_group_desc *desc;\n\tstruct ext4_sb_info *sbi = EXT4_SB(sb);\n\tstruct buffer_head *bh = NULL;\n\text4_fsblk_t bitmap_blk;\n\tint err;\n\n\tdesc = ext4_get_group_desc(sb, block_group, NULL);\n\tif (!desc)\n\t\treturn ERR_PTR(-EFSCORRUPTED);\n\n\tbitmap_blk = ext4_inode_bitmap(sb, desc);\n\tif ((bitmap_blk <= le32_to_cpu(sbi->s_es->s_first_data_block)) ||\n\t (bitmap_blk >= ext4_blocks_count(sbi->s_es))) {\n\t\text4_error(sb, \"Invalid inode bitmap blk %llu in \"\n\t\t\t \"block_group %u\", bitmap_blk, block_group);\n\t\text4_mark_group_bitmap_corrupted(sb, block_group,\n\t\t\t\t\tEXT4_GROUP_INFO_IBITMAP_CORRUPT);\n\t\treturn ERR_PTR(-EFSCORRUPTED);\n\t}\n\tbh = sb_getblk(sb, bitmap_blk);\n\tif (unlikely(!bh)) {\n\t\text4_error(sb, \"Cannot read inode bitmap - \"\n\t\t\t \"block_group = %u, inode_bitmap = %llu\",\n\t\t\t block_group, bitmap_blk);\n\t\treturn ERR_PTR(-ENOMEM);\n\t}\n\tif (bitmap_uptodate(bh))\n\t\tgoto verify;\n\n\tlock_buffer(bh);\n\tif (bitmap_uptodate(bh)) {\n\t\tunlock_buffer(bh);\n\t\tgoto verify;\n\t}\n\n\text4_lock_group(sb, block_group);\n\tif (desc->bg_flags & cpu_to_le16(EXT4_BG_INODE_UNINIT)) {\n\t\tmemset(bh->b_data, 0, (EXT4_INODES_PER_GROUP(sb) + 7) / 8);\n\t\text4_mark_bitmap_end(EXT4_INODES_PER_GROUP(sb),\n\t\t\t\t sb->s_blocksize * 8, bh->b_data);\n\t\tset_bitmap_uptodate(bh);\n\t\tset_buffer_uptodate(bh);\n\t\tset_buffer_verified(bh);\n\t\text4_unlock_group(sb, block_group);\n\t\tunlock_buffer(bh);\n\t\treturn bh;\n\t}\n\text4_unlock_group(sb, block_group);\n\n\tif (buffer_uptodate(bh)) {\n\t\t/*\n\t\t * if not uninit if bh is uptodate,\n\t\t * bitmap is also uptodate\n\t\t */\n\t\tset_bitmap_uptodate(bh);\n\t\tunlock_buffer(bh);\n\t\tgoto verify;\n\t}\n\t/*\n\t * submit the buffer_head for reading\n\t */\n\ttrace_ext4_load_inode_bitmap(sb, block_group);\n\tbh->b_end_io = ext4_end_bitmap_read;\n\tget_bh(bh);\n\tsubmit_bh(REQ_OP_READ, REQ_META | REQ_PRIO, bh);\n\twait_on_buffer(bh);\n\tif (!buffer_uptodate(bh)) {\n\t\tput_bh(bh);\n\t\text4_error(sb, \"Cannot read inode bitmap - \"\n\t\t\t \"block_group = %u, inode_bitmap = %llu\",\n\t\t\t block_group, bitmap_blk);\n\t\text4_mark_group_bitmap_corrupted(sb, block_group,\n\t\t\t\tEXT4_GROUP_INFO_IBITMAP_CORRUPT);\n\t\treturn ERR_PTR(-EIO);\n\t}\n\nverify:\n\terr = ext4_validate_inode_bitmap(sb, desc, block_group, bh);\n\tif (err)\n\t\tgoto out;\n\treturn bh;\nout:\n\tput_bh(bh);\n\treturn ERR_PTR(err);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'ext4: only look at the bg_flags field if it is valid\n\nThe bg_flags field in the block group descripts is only valid if the\nuninit_bg or metadata_csum feature is enabled. We were not\nconsistently looking at this field; fix this.\n\nAlso block group #0 must never have uninitialized allocation bitmaps,\nor need to be zeroed, since that's where the root inode, and other\nspecial inodes are set up. Check for these conditions and mark the\nfile system as corrupted if they are detected.\n\nThis addresses CVE-2018-10876.\n\nhttps://bugzilla.kernel.org/show_bug.cgi?id=199403\n\nSigned-off-by: Theodore Ts'o \nCc: stable@kernel.org'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: __ext4_xattr_check_block(struct inode *inode, struct buffer_head *bh,\n\t\t\t const char *function, unsigned int line)\n{\n\tint error = -EFSCORRUPTED;\n\n\tif (buffer_verified(bh))\n\t\treturn 0;\n\n\tif (BHDR(bh)->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC) ||\n\t BHDR(bh)->h_blocks != cpu_to_le32(1))\n\t\tgoto errout;\n\terror = -EFSBADCRC;\n\tif (!ext4_xattr_block_csum_verify(inode, bh))\n\t\tgoto errout;\n\terror = ext4_xattr_check_entries(BFIRST(bh), bh->b_data + bh->b_size,\n\t\t\t\t\t bh->b_data);\nerrout:\n\tif (error)\n\t\t__ext4_error_inode(inode, function, line, 0,\n\t\t\t\t \"corrupted xattr block %llu\",\n\t\t\t\t (unsigned long long) bh->b_blocknr);\n\telse\n\t\tset_buffer_verified(bh);\n\treturn error;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'ext4: always verify the magic number in xattr blocks\n\nIf there an inode points to a block which is also some other type of\nmetadata block (such as a block allocation bitmap), the\nbuffer_verified flag can be set when it was validated as that other\nmetadata block type; however, it would make a really terrible external\nattribute block. The reason why we use the verified flag is to avoid\nconstantly reverifying the block. However, it doesn't take much\noverhead to make sure the magic number of the xattr block is correct,\nand this will avoid potential crashes.\n\nThis addresses CVE-2018-10879.\n\nhttps://bugzilla.kernel.org/show_bug.cgi?id=200001\n\nSigned-off-by: Theodore Ts'o \nReviewed-by: Andreas Dilger \nCc: stable@kernel.org'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int alarm_timer_nsleep(const clockid_t which_clock, int flags,\n\t\t\t const struct timespec64 *tsreq)\n{\n\tenum alarmtimer_type type = clock2alarm(which_clock);\n\tstruct restart_block *restart = ¤t->restart_block;\n\tstruct alarm alarm;\n\tktime_t exp;\n\tint ret = 0;\n\n\tif (!alarmtimer_get_rtcdev())\n\t\treturn -ENOTSUPP;\n\n\tif (flags & ~TIMER_ABSTIME)\n\t\treturn -EINVAL;\n\n\tif (!capable(CAP_WAKE_ALARM))\n\t\treturn -EPERM;\n\n\talarm_init_on_stack(&alarm, type, alarmtimer_nsleep_wakeup);\n\n\texp = timespec64_to_ktime(*tsreq);\n\t/* Convert (if necessary) to absolute time */\n\tif (flags != TIMER_ABSTIME) {\n\t\tktime_t now = alarm_bases[type].gettime();\n\t\texp = ktime_add(now, exp);\n\t}\n\n\tret = alarmtimer_do_nsleep(&alarm, exp, type);\n\tif (ret != -ERESTART_RESTARTBLOCK)\n\t\treturn ret;\n\n\t/* abs timers don't set remaining time or restart */\n\tif (flags == TIMER_ABSTIME)\n\t\treturn -ERESTARTNOHAND;\n\n\trestart->fn = alarm_timer_nsleep_restart;\n\trestart->nanosleep.clockid = type;\n\trestart->nanosleep.expires = exp;\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'alarmtimer: Prevent overflow for relative nanosleep\n\nAir Icy reported:\n\n UBSAN: Undefined behaviour in kernel/time/alarmtimer.c:811:7\n signed integer overflow:\n 1529859276030040771 + 9223372036854775807 cannot be represented in type 'long long int'\n Call Trace:\n alarm_timer_nsleep+0x44c/0x510 kernel/time/alarmtimer.c:811\n __do_sys_clock_nanosleep kernel/time/posix-timers.c:1235 [inline]\n __se_sys_clock_nanosleep kernel/time/posix-timers.c:1213 [inline]\n __x64_sys_clock_nanosleep+0x326/0x4e0 kernel/time/posix-timers.c:1213\n do_syscall_64+0xb8/0x3a0 arch/x86/entry/common.c:290\n\nalarm_timer_nsleep() uses ktime_add() to add the current time and the\nrelative expiry value. ktime_add() has no sanity checks so the addition\ncan overflow when the relative timeout is large enough.\n\nUse ktime_add_safe() which has the necessary sanity checks in place and\nlimits the result to the valid range.\n\nFixes: 9a7adcf5c6de (\"timers: Posix interface for alarm-timers\")\nReported-by: Team OWL337 \nSigned-off-by: Thomas Gleixner \nCc: John Stultz \nLink: https://lkml.kernel.org/r/alpine.DEB.2.21.1807020926360.1595@nanos.tec.linutronix.de'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *XMagickCommand(Display *display,XResourceInfo *resource_info,\n XWindows *windows,const CommandType command_type,Image **image,\n MagickStatusType *state)\n{\n Image\n *nexus;\n\n MagickBooleanType\n proceed;\n\n MagickStatusType\n status;\n\n XTextProperty\n window_name;\n\n /*\n Process user command.\n */\n nexus=NewImageList();\n switch (command_type)\n {\n case OpenCommand:\n {\n char\n **filelist;\n\n ExceptionInfo\n *exception;\n\n Image\n *images,\n *next;\n\n ImageInfo\n *read_info;\n\n int\n number_files;\n\n register int\n i;\n\n static char\n filenames[MaxTextExtent] = \"*\";\n\n if (resource_info->immutable != MagickFalse)\n break;\n /*\n Request file name from user.\n */\n XFileBrowserWidget(display,windows,\"Animate\",filenames);\n if (*filenames == '\\0')\n return((Image *) NULL);\n /*\n Expand the filenames.\n */\n filelist=(char **) AcquireMagickMemory(sizeof(char *));\n if (filelist == (char **) NULL)\n {\n ThrowXWindowException(ResourceLimitError,\"MemoryAllocationFailed\",\n filenames);\n return((Image *) NULL);\n }\n number_files=1;\n filelist[0]=filenames;\n status=ExpandFilenames(&number_files,&filelist);\n if ((status == MagickFalse) || (number_files == 0))\n {\n if (number_files == 0)\n {\n ThrowXWindowException(ImageError,\"NoImagesWereLoaded\",filenames);\n return((Image *) NULL);\n }\n ThrowXWindowException(ResourceLimitError,\"MemoryAllocationFailed\",\n filenames);\n return((Image *) NULL);\n }\n read_info=CloneImageInfo(resource_info->image_info);\n exception=AcquireExceptionInfo();\n images=NewImageList();\n XSetCursorState(display,windows,MagickTrue);\n XCheckRefreshWindows(display,windows);\n for (i=0; i < number_files; i++)\n {\n (void) CopyMagickString(read_info->filename,filelist[i],MaxTextExtent);\n filelist[i]=DestroyString(filelist[i]);\n *read_info->magick='\\0';\n next=ReadImage(read_info,exception);\n CatchException(exception);\n if (next != (Image *) NULL)\n AppendImageToList(&images,next);\n if (number_files <= 5)\n continue;\n proceed=SetImageProgress(images,LoadImageTag,i,(MagickSizeType)\n number_files);\n if (proceed == MagickFalse)\n break;\n }\n filelist=(char **) RelinquishMagickMemory(filelist);\n exception=DestroyExceptionInfo(exception);\n read_info=DestroyImageInfo(read_info);\n if (images == (Image *) NULL)\n {\n XSetCursorState(display,windows,MagickFalse);\n ThrowXWindowException(ImageError,\"NoImagesWereLoaded\",filenames);\n return((Image *) NULL);\n }\n nexus=GetFirstImageInList(images);\n *state|=ExitState;\n break;\n }\n case PlayCommand:\n {\n char\n basename[MaxTextExtent];\n\n int\n status;\n\n /*\n Window name is the base of the filename.\n */\n *state|=PlayAnimationState;\n *state&=(~AutoReverseAnimationState);\n GetPathComponent((*image)->magick_filename,BasePath,basename);\n (void) FormatLocaleString(windows->image.name,MaxTextExtent,\n \"%s: %s\",MagickPackageName,basename);\n if (resource_info->title != (char *) NULL)\n {\n char\n *title;\n\n title=InterpretImageProperties(resource_info->image_info,*image,\n resource_info->title);\n (void) CopyMagickString(windows->image.name,title,MaxTextExtent);\n title=DestroyString(title);\n }\n status=XStringListToTextProperty(&windows->image.name,1,&window_name);\n if (status == 0)\n break;\n XSetWMName(display,windows->image.id,&window_name);\n (void) XFree((void *) window_name.value);\n break;\n }\n case StepCommand:\n case StepBackwardCommand:\n case StepForwardCommand:\n {\n *state|=StepAnimationState;\n *state&=(~PlayAnimationState);\n if (command_type == StepBackwardCommand)\n *state&=(~ForwardAnimationState);\n if (command_type == StepForwardCommand)\n *state|=ForwardAnimationState;\n if (resource_info->title != (char *) NULL)\n break;\n break;\n }\n case RepeatCommand:\n {\n *state|=RepeatAnimationState;\n *state&=(~AutoReverseAnimationState);\n *state|=PlayAnimationState;\n break;\n }\n case AutoReverseCommand:\n {\n *state|=AutoReverseAnimationState;\n *state&=(~RepeatAnimationState);\n *state|=PlayAnimationState;\n break;\n }\n case SaveCommand:\n {\n /*\n Save image.\n */\n status=XSaveImage(display,resource_info,windows,*image);\n if (status == MagickFalse)\n {\n char\n message[MaxTextExtent];\n\n (void) FormatLocaleString(message,MaxTextExtent,\"%s:%s\",\n (*image)->exception.reason != (char *) NULL ?\n (*image)->exception.reason : \"\",\n (*image)->exception.description != (char *) NULL ?\n (*image)->exception.description : \"\");\n XNoticeWidget(display,windows,\"Unable to save file:\",message);\n break;\n }\n break;\n }\n case SlowerCommand:\n {\n resource_info->delay++;\n break;\n }\n case FasterCommand:\n {\n if (resource_info->delay == 0)\n break;\n resource_info->delay--;\n break;\n }\n case ForwardCommand:\n {\n *state=ForwardAnimationState;\n *state&=(~AutoReverseAnimationState);\n break;\n }\n case ReverseCommand:\n {\n *state&=(~ForwardAnimationState);\n *state&=(~AutoReverseAnimationState);\n break;\n }\n case InfoCommand:\n {\n XDisplayImageInfo(display,resource_info,windows,(Image *) NULL,*image);\n break;\n }\n case HelpCommand:\n {\n /*\n User requested help.\n */\n XTextViewWidget(display,resource_info,windows,MagickFalse,\n \"Help Viewer - Animate\",AnimateHelp);\n break;\n }\n case BrowseDocumentationCommand:\n {\n Atom\n mozilla_atom;\n\n Window\n mozilla_window,\n root_window;\n\n /*\n Browse the ImageMagick documentation.\n */\n root_window=XRootWindow(display,XDefaultScreen(display));\n mozilla_atom=XInternAtom(display,\"_MOZILLA_VERSION\",MagickFalse);\n mozilla_window=XWindowByProperty(display,root_window,mozilla_atom);\n if (mozilla_window != (Window) NULL)\n {\n char\n command[MaxTextExtent],\n *url;\n\n /*\n Display documentation using Netscape remote control.\n */\n url=GetMagickHomeURL();\n (void) FormatLocaleString(command,MaxTextExtent,\n \"openurl(%s,new-tab)\",url);\n url=DestroyString(url);\n mozilla_atom=XInternAtom(display,\"_MOZILLA_COMMAND\",MagickFalse);\n (void) XChangeProperty(display,mozilla_window,mozilla_atom,\n XA_STRING,8,PropModeReplace,(unsigned char *) command,\n (int) strlen(command));\n XSetCursorState(display,windows,MagickFalse);\n break;\n }\n XSetCursorState(display,windows,MagickTrue);\n XCheckRefreshWindows(display,windows);\n status=InvokeDelegate(resource_info->image_info,*image,\"browse\",\n (char *) NULL,&(*image)->exception);\n if (status == MagickFalse)\n XNoticeWidget(display,windows,\"Unable to browse documentation\",\n (char *) NULL);\n XDelay(display,1500);\n XSetCursorState(display,windows,MagickFalse);\n break;\n }\n case VersionCommand:\n {\n XNoticeWidget(display,windows,GetMagickVersion((size_t *) NULL),\n GetMagickCopyright());\n break;\n }\n case QuitCommand:\n {\n /*\n exit program\n */\n if (resource_info->confirm_exit == MagickFalse)\n XClientMessage(display,windows->image.id,windows->im_protocols,\n windows->im_exit,CurrentTime);\n else\n {\n int\n status;\n\n /*\n Confirm program exit.\n */\n status=XConfirmWidget(display,windows,\"Do you really want to exit\",\n resource_info->client_name);\n if (status != 0)\n XClientMessage(display,windows->image.id,windows->im_protocols,\n windows->im_exit,CurrentTime);\n }\n break;\n }\n default:\n break;\n }\n return(nexus);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-772'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1195'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void SoundTouch::setChannels(uint numChannels)\r\n{\r\n /*if (numChannels != 1 && numChannels != 2) \r\n {\r\n //ST_THROW_RT_ERROR(\"Illegal number of channels\");\r\n return;\r\n }*/\r\n channels = numChannels;\r\n pRateTransposer->setChannels((int)numChannels);\r\n pTDStretch->setChannels((int)numChannels);\r\n}\r ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617'], 'message': 'Replaced illegal-number-of-channel assertions with run-time exception'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int pop_fetch_message (CONTEXT* ctx, MESSAGE* msg, int msgno)\n{\n int ret;\n void *uidl;\n char buf[LONG_STRING];\n char path[_POSIX_PATH_MAX];\n progress_t progressbar;\n POP_DATA *pop_data = (POP_DATA *)ctx->data;\n POP_CACHE *cache;\n HEADER *h = ctx->hdrs[msgno];\n unsigned short bcache = 1;\n\n /* see if we already have the message in body cache */\n if ((msg->fp = mutt_bcache_get (pop_data->bcache, h->data)))\n return 0;\n\n /*\n * see if we already have the message in our cache in\n * case $message_cachedir is unset\n */\n cache = &pop_data->cache[h->index % POP_CACHE_LEN];\n\n if (cache->path)\n {\n if (cache->index == h->index)\n {\n /* yes, so just return a pointer to the message */\n msg->fp = fopen (cache->path, \"r\");\n if (msg->fp)\n\treturn 0;\n \n mutt_perror (cache->path);\n mutt_sleep (2);\n return -1;\n }\n else\n {\n /* clear the previous entry */\n unlink (cache->path);\n FREE (&cache->path);\n }\n }\n\n FOREVER\n {\n if (pop_reconnect (ctx) < 0)\n return -1;\n\n /* verify that massage index is correct */\n if (h->refno < 0)\n {\n mutt_error _(\"The message index is incorrect. Try reopening the mailbox.\");\n mutt_sleep (2);\n return -1;\n }\n\n mutt_progress_init (&progressbar, _(\"Fetching message...\"),\n\t\t\tMUTT_PROGRESS_SIZE, NetInc, h->content->length + h->content->offset - 1);\n\n /* see if we can put in body cache; use our cache as fallback */\n if (!(msg->fp = mutt_bcache_put (pop_data->bcache, h->data, 1)))\n {\n /* no */\n bcache = 0;\n mutt_mktemp (path, sizeof (path));\n if (!(msg->fp = safe_fopen (path, \"w+\")))\n {\n\tmutt_perror (path);\n\tmutt_sleep (2);\n\treturn -1;\n }\n }\n\n snprintf (buf, sizeof (buf), \"RETR %d\\r\\n\", h->refno);\n\n ret = pop_fetch_data (pop_data, buf, &progressbar, fetch_message, msg->fp);\n if (ret == 0)\n break;\n\n safe_fclose (&msg->fp);\n\n /* if RETR failed (e.g. connection closed), be sure to remove either\n * the file in bcache or from POP's own cache since the next iteration\n * of the loop will re-attempt to put() the message */\n if (!bcache)\n unlink (path);\n\n if (ret == -2)\n {\n mutt_error (\"%s\", pop_data->err_msg);\n mutt_sleep (2);\n return -1;\n }\n\n if (ret == -3)\n {\n mutt_error _(\"Can't write message to temporary file!\");\n mutt_sleep (2);\n return -1;\n }\n }\n\n /* Update the header information. Previously, we only downloaded a\n * portion of the headers, those required for the main display.\n */\n if (bcache)\n mutt_bcache_commit (pop_data->bcache, h->data);\n else\n {\n cache->index = h->index;\n cache->path = safe_strdup (path);\n }\n rewind (msg->fp);\n uidl = h->data;\n\n /* we replace envelop, key in subj_hash has to be updated as well */\n if (ctx->subj_hash && h->env->real_subj)\n hash_delete (ctx->subj_hash, h->env->real_subj, h, NULL);\n mutt_label_hash_remove (ctx, h);\n mutt_free_envelope (&h->env);\n h->env = mutt_read_rfc822_header (msg->fp, h, 0, 0);\n if (ctx->subj_hash && h->env->real_subj)\n hash_insert (ctx->subj_hash, h->env->real_subj, h);\n mutt_label_hash_add (ctx, h);\n\n h->data = uidl;\n h->lines = 0;\n fgets (buf, sizeof (buf), msg->fp);\n while (!feof (msg->fp))\n {\n ctx->hdrs[msgno]->lines++;\n fgets (buf, sizeof (buf), msg->fp);\n }\n\n h->content->length = ftello (msg->fp) - h->content->offset;\n\n /* This needs to be done in case this is a multipart message */\n if (!WithCrypto)\n h->security = crypt_query (h->content);\n\n mutt_clear_error();\n rewind (msg->fp);\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Sanitize POP bcache paths.\n\nProtect against bcache directory path traversal for UID values.\n\nThanks for Jeriko One for the bug report and patch, which this commit\nis based upon.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void imap_quote_string(char *dest, size_t dlen, const char *src)\n{\n static const char quote[] = \"\\\"\\\\\";\n char *pt = dest;\n const char *s = src;\n\n *pt++ = '\"';\n /* save room for trailing quote-char */\n dlen -= 2;\n\n for (; *s && dlen; s++)\n {\n if (strchr(quote, *s))\n {\n dlen -= 2;\n if (dlen == 0)\n break;\n *pt++ = '\\\\';\n *pt++ = *s;\n }\n else\n {\n *pt++ = *s;\n dlen--;\n }\n }\n *pt++ = '\"';\n *pt = '\\0';\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-78', 'CWE-77'], 'message': 'quote imap strings more carefully\n\nCo-authored-by: JerikoOne '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: imap_auth_res_t imap_auth_cram_md5 (IMAP_DATA* idata, const char* method)\n{\n char ibuf[LONG_STRING*2], obuf[LONG_STRING];\n unsigned char hmac_response[MD5_DIGEST_LEN];\n int len;\n int rc;\n\n if (!mutt_bit_isset (idata->capabilities, ACRAM_MD5))\n return IMAP_AUTH_UNAVAIL;\n\n mutt_message _(\"Authenticating (CRAM-MD5)...\");\n\n /* get auth info */\n if (mutt_account_getlogin (&idata->conn->account))\n return IMAP_AUTH_FAILURE;\n if (mutt_account_getpass (&idata->conn->account))\n return IMAP_AUTH_FAILURE;\n\n imap_cmd_start (idata, \"AUTHENTICATE CRAM-MD5\");\n\n /* From RFC 2195:\n * The data encoded in the first ready response contains a presumptively\n * arbitrary string of random digits, a timestamp, and the fully-qualified\n * primary host name of the server. The syntax of the unencoded form must\n * correspond to that of an RFC 822 'msg-id' [RFC822] as described in [POP3].\n */\n do\n rc = imap_cmd_step (idata);\n while (rc == IMAP_CMD_CONTINUE);\n \n if (rc != IMAP_CMD_RESPOND)\n {\n dprint (1, (debugfile, \"Invalid response from server: %s\\n\", ibuf));\n goto bail;\n }\n\n if ((len = mutt_from_base64 (obuf, idata->buf + 2)) == -1)\n {\n dprint (1, (debugfile, \"Error decoding base64 response.\\n\"));\n goto bail;\n }\n\n obuf[len] = '\\0';\n dprint (2, (debugfile, \"CRAM challenge: %s\\n\", obuf));\n\n /* The client makes note of the data and then responds with a string\n * consisting of the user name, a space, and a 'digest'. The latter is\n * computed by applying the keyed MD5 algorithm from [KEYED-MD5] where the\n * key is a shared secret and the digested text is the timestamp (including\n * angle-brackets).\n * \n * Note: The user name shouldn't be quoted. Since the digest can't contain\n * spaces, there is no ambiguity. Some servers get this wrong, we'll work\n * around them when the bug report comes in. Until then, we'll remain\n * blissfully RFC-compliant.\n */\n hmac_md5 (idata->conn->account.pass, obuf, hmac_response);\n /* dubious optimisation I saw elsewhere: make the whole string in one call */\n snprintf (obuf, sizeof (obuf),\n \"%s %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\",\n idata->conn->account.user,\n hmac_response[0], hmac_response[1], hmac_response[2], hmac_response[3],\n hmac_response[4], hmac_response[5], hmac_response[6], hmac_response[7],\n hmac_response[8], hmac_response[9], hmac_response[10], hmac_response[11],\n hmac_response[12], hmac_response[13], hmac_response[14], hmac_response[15]);\n dprint(2, (debugfile, \"CRAM response: %s\\n\", obuf));\n\n /* XXX - ibuf must be long enough to store the base64 encoding of obuf, \n * plus the additional debris\n */\n \n mutt_to_base64 ((unsigned char*) ibuf, (unsigned char*) obuf, strlen (obuf),\n\t\t sizeof (ibuf) - 2);\n safe_strcat (ibuf, sizeof (ibuf), \"\\r\\n\");\n mutt_socket_write (idata->conn, ibuf);\n\n do\n rc = imap_cmd_step (idata);\n while (rc == IMAP_CMD_CONTINUE);\n\n if (rc != IMAP_CMD_OK)\n {\n dprint (1, (debugfile, \"Error receiving server response.\\n\"));\n goto bail;\n }\n\n if (imap_code (idata->buf))\n return IMAP_AUTH_SUCCESS;\n\n bail:\n mutt_error _(\"CRAM-MD5 authentication failed.\");\n mutt_sleep (2);\n return IMAP_AUTH_FAILURE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'Check outbuf length in mutt_from_base64()\n\nThe obuf can be overflowed in auth_cram.c, and possibly auth_gss.c.\n\nThanks to Jeriko One for the bug report.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static apr_status_t run_watchdog(int state, void *baton, apr_pool_t *ptemp)\n{\n md_watchdog *wd = baton;\n apr_status_t rv = APR_SUCCESS;\n md_job_t *job;\n apr_time_t next_run, now;\n int restart = 0;\n int i;\n \n switch (state) {\n case AP_WATCHDOG_STATE_STARTING:\n ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, wd->s, APLOGNO(10054)\n \"md watchdog start, auto drive %d mds\", wd->jobs->nelts);\n assert(wd->reg);\n \n for (i = 0; i < wd->jobs->nelts; ++i) {\n job = APR_ARRAY_IDX(wd->jobs, i, md_job_t *);\n load_job_props(wd->reg, job, ptemp);\n }\n break;\n case AP_WATCHDOG_STATE_RUNNING:\n \n wd->next_change = 0;\n ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, wd->s, APLOGNO(10055)\n \"md watchdog run, auto drive %d mds\", wd->jobs->nelts);\n \n /* normally, we'd like to run at least twice a day */\n next_run = apr_time_now() + apr_time_from_sec(MD_SECS_PER_DAY / 2);\n\n /* Check on all the jobs we have */\n for (i = 0; i < wd->jobs->nelts; ++i) {\n job = APR_ARRAY_IDX(wd->jobs, i, md_job_t *);\n \n rv = check_job(wd, job, ptemp);\n\n if (job->need_restart && !job->restart_processed) {\n restart = 1;\n }\n if (job->next_check && job->next_check < next_run) {\n next_run = job->next_check;\n }\n }\n\n now = apr_time_now();\n if (APLOGdebug(wd->s)) {\n ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, wd->s, APLOGNO(10107)\n \"next run in %s\", md_print_duration(ptemp, next_run - now));\n }\n wd_set_interval(wd->watchdog, next_run - now, wd, run_watchdog);\n break;\n \n case AP_WATCHDOG_STATE_STOPPING:\n ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, wd->s, APLOGNO(10058)\n \"md watchdog stopping\");\n break;\n }\n\n if (restart) {\n const char *action, *names = \"\";\n int n;\n \n for (i = 0, n = 0; i < wd->jobs->nelts; ++i) {\n job = APR_ARRAY_IDX(wd->jobs, i, md_job_t *);\n if (job->need_restart && !job->restart_processed) {\n names = apr_psprintf(ptemp, \"%s%s%s\", names, n? \" \" : \"\", job->md->name);\n ++n;\n }\n }\n\n if (n > 0) {\n int notified = 1;\n\n /* Run notify command for ready MDs (if configured) and persist that\n * we have done so. This process might be reaped after n requests or die\n * of another cause. The one taking over the watchdog need to notify again.\n */\n if (wd->mc->notify_cmd) {\n const char * const *argv;\n const char *cmdline;\n int exit_code;\n \n cmdline = apr_psprintf(ptemp, \"%s %s\", wd->mc->notify_cmd, names); \n apr_tokenize_to_argv(cmdline, (char***)&argv, ptemp);\n if (APR_SUCCESS == (rv = md_util_exec(ptemp, argv[0], argv, &exit_code))) {\n ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, wd->s, APLOGNO(10108) \n \"notify command '%s' returned %d\", \n wd->mc->notify_cmd, exit_code);\n }\n else {\n ap_log_error(APLOG_MARK, APLOG_ERR, rv, wd->s, APLOGNO(10109) \n \"executing configured MDNotifyCmd %s\", wd->mc->notify_cmd);\n notified = 0;\n } \n }\n \n if (notified) {\n /* persist the jobs that were notified */\n for (i = 0, n = 0; i < wd->jobs->nelts; ++i) {\n job = APR_ARRAY_IDX(wd->jobs, i, md_job_t *);\n if (job->need_restart && !job->restart_processed) {\n job->restart_processed = 1;\n save_job_props(wd->reg, job, ptemp);\n }\n }\n }\n \n /* FIXME: the server needs to start gracefully to take the new certificate in.\n * This poses a variety of problems to solve satisfactory for everyone:\n * - I myself, have no implementation for Windows \n * - on *NIX, child processes run with less privileges, preventing\n * the signal based restart trigger to work\n * - admins want better control of timing windows for restarts, e.g.\n * during less busy hours/days.\n */\n rv = md_server_graceful(ptemp, wd->s);\n if (APR_ENOTIMPL == rv) {\n /* self-graceful restart not supported in this setup */\n action = \" and changes will be activated on next (graceful) server restart.\";\n }\n else {\n action = \" and server has been asked to restart now.\";\n }\n ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, wd->s, APLOGNO(10059) \n \"The Managed Domain%s %s %s been setup%s\",\n (n > 1)? \"s\" : \"\", names, (n > 1)? \"have\" : \"has\", action);\n }\n }\n \n return APR_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'v1.1.12, notifycmd improvements'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int WavInFile::readHeaderBlock()\r\n{\r\n char label[5];\r\n string sLabel;\r\n\r\n // lead label string\r\n if (fread(label, 1, 4, fptr) !=4) return -1;\r\n label[4] = 0;\r\n\r\n if (isAlphaStr(label) == 0) return -1; // not a valid label\r\n\r\n // Decode blocks according to their label\r\n if (strcmp(label, fmtStr) == 0)\r\n {\r\n int nLen, nDump;\r\n\r\n // 'fmt ' block \r\n memcpy(header.format.fmt, fmtStr, 4);\r\n\r\n // read length of the format field\r\n if (fread(&nLen, sizeof(int), 1, fptr) != 1) return -1;\r\n // swap byte order if necessary\r\n _swap32(nLen);\r\n\r\n // verify that header length isn't smaller than expected\r\n if (nLen < sizeof(header.format) - 8) return -1;\r\n\r\n header.format.format_len = nLen;\r\n\r\n // calculate how much length differs from expected\r\n nDump = nLen - ((int)sizeof(header.format) - 8);\r\n\r\n // if format_len is larger than expected, read only as much data as we've space for\r\n if (nDump > 0)\r\n {\r\n nLen = sizeof(header.format) - 8;\r\n }\r\n\r\n // read data\r\n if (fread(&(header.format.fixed), nLen, 1, fptr) != 1) return -1;\r\n\r\n // swap byte order if necessary\r\n _swap16((short &)header.format.fixed); // short int fixed;\r\n _swap16((short &)header.format.channel_number); // short int channel_number;\r\n _swap32((int &)header.format.sample_rate); // int sample_rate;\r\n _swap32((int &)header.format.byte_rate); // int byte_rate;\r\n _swap16((short &)header.format.byte_per_sample); // short int byte_per_sample;\r\n _swap16((short &)header.format.bits_per_sample); // short int bits_per_sample;\r\n\r\n // if format_len is larger than expected, skip the extra data\r\n if (nDump > 0)\r\n {\r\n fseek(fptr, nDump, SEEK_CUR);\r\n }\r\n\r\n return 0;\r\n }\r\n else if (strcmp(label, factStr) == 0)\r\n {\r\n int nLen, nDump;\r\n\r\n // 'fact' block \r\n memcpy(header.fact.fact_field, factStr, 4);\r\n\r\n // read length of the fact field\r\n if (fread(&nLen, sizeof(int), 1, fptr) != 1) return -1;\r\n // swap byte order if necessary\r\n _swap32(nLen); // int fact_len;\r\n\r\n // verify that fact length isn't smaller than expected\r\n if (nLen < sizeof(header.fact) - 8) return -1;\r\n\r\n header.fact.fact_len = nLen;\r\n\r\n // calculate how much length differs from expected\r\n nDump = nLen - ((int)sizeof(header.fact) - 8);\r\n\r\n // if format_len is larger than expected, read only as much data as we've space for\r\n if (nDump > 0)\r\n {\r\n nLen = sizeof(header.fact) - 8;\r\n }\r\n\r\n // read data\r\n if (fread(&(header.fact.fact_sample_len), nLen, 1, fptr) != 1) return -1;\r\n\r\n // swap byte order if necessary\r\n _swap32((int &)header.fact.fact_sample_len); // int sample_length;\r\n\r\n // if fact_len is larger than expected, skip the extra data\r\n if (nDump > 0)\r\n {\r\n fseek(fptr, nDump, SEEK_CUR);\r\n }\r\n\r\n return 0;\r\n }\r\n else if (strcmp(label, dataStr) == 0)\r\n {\r\n // 'data' block\r\n memcpy(header.data.data_field, dataStr, 4);\r\n if (fread(&(header.data.data_len), sizeof(uint), 1, fptr) != 1) return -1;\r\n\r\n // swap byte order if necessary\r\n _swap32((int &)header.data.data_len);\r\n\r\n return 1;\r\n }\r\n else\r\n {\r\n uint len, i;\r\n uint temp;\r\n // unknown block\r\n\r\n // read length\r\n if (fread(&len, sizeof(len), 1, fptr) != 1) return -1;\r\n // scan through the block\r\n for (i = 0; i < len; i ++)\r\n {\r\n if (fread(&temp, 1, 1, fptr) != 1) return -1;\r\n if (feof(fptr)) return -1; // unexpected eof\r\n }\r\n }\r\n return 0;\r\n}\r ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fixed WavFile header/fact not-too-small check'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static ssize_t parse8BIM(Image *ifile, Image *ofile)\n{\n char\n brkused,\n quoted,\n *line,\n *token,\n *newstr,\n *name;\n\n int\n state,\n next;\n\n unsigned char\n dataset;\n\n unsigned int\n recnum;\n\n int\n inputlen = MaxTextExtent;\n\n MagickOffsetType\n savedpos,\n currentpos;\n\n ssize_t\n savedolen = 0L,\n outputlen = 0L;\n\n TokenInfo\n *token_info;\n\n dataset = 0;\n recnum = 0;\n line = (char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*line));\n if (line == (char *) NULL)\n return(-1);\n newstr = name = token = (char *) NULL;\n savedpos = 0;\n token_info=AcquireTokenInfo();\n while (super_fgets(&line,&inputlen,ifile)!=NULL)\n {\n state=0;\n next=0;\n\n token=(char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*token));\n if (token == (char *) NULL)\n break;\n newstr=(char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*newstr));\n if (newstr == (char *) NULL)\n break;\n while (Tokenizer(token_info,0,token,(size_t) inputlen,line,\"\",\"=\",\"\\\"\",0,\n &brkused,&next,"ed)==0)\n {\n if (state == 0)\n {\n int\n state,\n next;\n\n char\n brkused,\n quoted;\n\n state=0;\n next=0;\n while (Tokenizer(token_info,0,newstr,(size_t) inputlen,token,\"\",\"#\",\n \"\", 0,&brkused,&next,"ed)==0)\n {\n switch (state)\n {\n case 0:\n if (strcmp(newstr,\"8BIM\")==0)\n dataset = 255;\n else\n dataset = (unsigned char) StringToLong(newstr);\n break;\n case 1:\n recnum = (unsigned int) StringToUnsignedLong(newstr);\n break;\n case 2:\n name=(char *) AcquireQuantumMemory(strlen(newstr)+MaxTextExtent,\n sizeof(*name));\n if (name)\n (void) strcpy(name,newstr);\n break;\n }\n state++;\n }\n }\n else\n if (state == 1)\n {\n int\n next;\n\n ssize_t\n len;\n\n char\n brkused,\n quoted;\n\n next=0;\n len = (ssize_t) strlen(token);\n while (Tokenizer(token_info,0,newstr,(size_t) inputlen,token,\"\",\"&\",\n \"\",0,&brkused,&next,"ed)==0)\n {\n if (brkused && next > 0)\n {\n size_t\n codes_length;\n\n char\n *s = &token[next-1];\n\n codes_length=convertHTMLcodes(s, strlen(s));\n if ((ssize_t) codes_length > len)\n len=0;\n else\n len-=codes_length;\n }\n }\n\n if (dataset == 255)\n {\n unsigned char\n nlen = 0;\n\n int\n i;\n\n if (savedolen > 0)\n {\n MagickOffsetType\n offset;\n\n ssize_t diff = outputlen - savedolen;\n currentpos = TellBlob(ofile);\n if (currentpos < 0)\n return(-1);\n offset=SeekBlob(ofile,savedpos,SEEK_SET);\n if (offset < 0)\n return(-1);\n (void) WriteBlobMSBLong(ofile,(unsigned int) diff);\n offset=SeekBlob(ofile,currentpos,SEEK_SET);\n if (offset < 0)\n return(-1);\n savedolen = 0L;\n }\n if (outputlen & 1)\n {\n (void) WriteBlobByte(ofile,0x00);\n outputlen++;\n }\n (void) WriteBlobString(ofile,\"8BIM\");\n (void) WriteBlobMSBShort(ofile,(unsigned short) recnum);\n outputlen += 6;\n if (name)\n nlen = (unsigned char) strlen(name);\n (void) WriteBlobByte(ofile,nlen);\n outputlen++;\n for (i=0; i 0)\n (void) WriteBlobByte(ofile,(unsigned char) token[next++]);\n\n if (outputlen & 1)\n {\n (void) WriteBlobByte(ofile,0x00);\n outputlen++;\n }\n }\n else\n {\n /* patch in a fake length for now and fix it later */\n savedpos = TellBlob(ofile);\n if (savedpos < 0)\n return(-1);\n (void) WriteBlobMSBLong(ofile,0xFFFFFFFFU);\n outputlen += 4;\n savedolen = outputlen;\n }\n }\n else\n {\n if (len <= 0x7FFF)\n {\n (void) WriteBlobByte(ofile,0x1c);\n (void) WriteBlobByte(ofile,(unsigned char) dataset);\n (void) WriteBlobByte(ofile,(unsigned char) (recnum & 0xff));\n (void) WriteBlobMSBShort(ofile,(unsigned short) len);\n outputlen += 5;\n next=0;\n outputlen += len;\n while (len-- > 0)\n (void) WriteBlobByte(ofile,(unsigned char) token[next++]);\n }\n }\n }\n state++;\n }\n if (token != (char *) NULL)\n token=DestroyString(token);\n if (newstr != (char *) NULL)\n newstr=DestroyString(newstr);\n if (name != (char *) NULL)\n name=DestroyString(name);\n }\n token_info=DestroyTokenInfo(token_info);\n if (token != (char *) NULL)\n token=DestroyString(token);\n if (newstr != (char *) NULL)\n newstr=DestroyString(newstr);\n if (name != (char *) NULL)\n name=DestroyString(name);\n line=DestroyString(line);\n if (savedolen > 0)\n {\n MagickOffsetType\n offset;\n\n ssize_t diff = outputlen - savedolen;\n\n currentpos = TellBlob(ofile);\n if (currentpos < 0)\n return(-1);\n offset=SeekBlob(ofile,savedpos,SEEK_SET);\n if (offset < 0)\n return(-1);\n (void) WriteBlobMSBLong(ofile,(unsigned int) diff);\n offset=SeekBlob(ofile,currentpos,SEEK_SET);\n if (offset < 0)\n return(-1);\n savedolen = 0L;\n }\n return(outputlen);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-772'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1190'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static struct pid *good_sigevent(sigevent_t * event)\n{\n\tstruct task_struct *rtn = current->group_leader;\n\n\tif ((event->sigev_notify & SIGEV_THREAD_ID ) &&\n\t\t(!(rtn = find_task_by_vpid(event->sigev_notify_thread_id)) ||\n\t\t !same_thread_group(rtn, current) ||\n\t\t (event->sigev_notify & ~SIGEV_THREAD_ID) != SIGEV_SIGNAL))\n\t\treturn NULL;\n\n\tif (((event->sigev_notify & ~SIGEV_THREAD_ID) != SIGEV_NONE) &&\n\t ((event->sigev_signo <= 0) || (event->sigev_signo > SIGRTMAX)))\n\t\treturn NULL;\n\n\treturn task_pid(rtn);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'posix-timer: Properly check sigevent->sigev_notify\n\ntimer_create() specifies via sigevent->sigev_notify the signal delivery for\nthe new timer. The valid modes are SIGEV_NONE, SIGEV_SIGNAL, SIGEV_THREAD\nand (SIGEV_SIGNAL | SIGEV_THREAD_ID).\n\nThe sanity check in good_sigevent() is only checking the valid combination\nfor the SIGEV_THREAD_ID bit, i.e. SIGEV_SIGNAL, but if SIGEV_THREAD_ID is\nnot set it accepts any random value.\n\nThis has no real effects on the posix timer and signal delivery code, but\nit affects show_timer() which handles the output of /proc/$PID/timers. That\nfunction uses a string array to pretty print sigev_notify. The access to\nthat array has no bound checks, so random sigev_notify cause access beyond\nthe array bounds.\n\nAdd proper checks for the valid notify modes and remove the SIGEV_THREAD_ID\nmasking from various code pathes as SIGEV_NONE can never be set in\ncombination with SIGEV_THREAD_ID.\n\nReported-by: Eric Biggers \nReported-by: Dmitry Vyukov \nReported-by: Alexey Dobriyan \nSigned-off-by: Thomas Gleixner \nCc: John Stultz \nCc: stable@vger.kernel.org'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: kernel_ptr(void)\n{\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'printk: hash addresses printed with %p\n\nCurrently there exist approximately 14 000 places in the kernel where\naddresses are being printed using an unadorned %p. This potentially\nleaks sensitive information regarding the Kernel layout in memory. Many\nof these calls are stale, instead of fixing every call lets hash the\naddress by default before printing. This will of course break some\nusers, forcing code printing needed addresses to be updated.\n\nCode that _really_ needs the address will soon be able to use the new\nprintk specifier %px to print the address.\n\nFor what it's worth, usage of unadorned %p can be broken down as\nfollows (thanks to Joe Perches).\n\n$ git grep -E '%p[^A-Za-z0-9]' | cut -f1 -d\"/\" | sort | uniq -c\n 1084 arch\n 20 block\n 10 crypto\n 32 Documentation\n 8121 drivers\n 1221 fs\n 143 include\n 101 kernel\n 69 lib\n 100 mm\n 1510 net\n 40 samples\n 7 scripts\n 11 security\n 166 sound\n 152 tools\n 2 virt\n\nAdd function ptr_to_id() to map an address to a 32 bit unique\nidentifier. Hash any unadorned usage of specifier %p and any malformed\nspecifiers.\n\nSigned-off-by: Tobin C. Harding '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: BGD_DECLARE(void *) gdImageBmpPtr(gdImagePtr im, int *size, int compression)\n{\n\tvoid *rv;\n\tgdIOCtx *out = gdNewDynamicCtx(2048, NULL);\n\tif (out == NULL) return NULL;\n\tgdImageBmpCtx(im, out, compression);\n\trv = gdDPExtractData(out, size);\n\tout->gd_free(out);\n\treturn rv;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'bmp: check return value in gdImageBmpPtr\n\nCloses #447.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: lex(struct scanner *s, union lvalue *val)\n{\nskip_more_whitespace_and_comments:\n /* Skip spaces. */\n while (is_space(peek(s)))\n if (next(s) == '\\n')\n return TOK_END_OF_LINE;\n\n /* Skip comments. */\n if (chr(s, '#')) {\n skip_to_eol(s);\n goto skip_more_whitespace_and_comments;\n }\n\n /* See if we're done. */\n if (eof(s)) return TOK_END_OF_FILE;\n\n /* New token. */\n s->token_line = s->line;\n s->token_column = s->column;\n s->buf_pos = 0;\n\n /* LHS Keysym. */\n if (chr(s, '<')) {\n while (peek(s) != '>' && !eol(s))\n buf_append(s, next(s));\n if (!chr(s, '>')) {\n scanner_err(s, \"unterminated keysym literal\");\n return TOK_ERROR;\n }\n if (!buf_append(s, '\\0')) {\n scanner_err(s, \"keysym literal is too long\");\n return TOK_ERROR;\n }\n val->string.str = s->buf;\n val->string.len = s->buf_pos;\n return TOK_LHS_KEYSYM;\n }\n\n /* Colon. */\n if (chr(s, ':'))\n return TOK_COLON;\n if (chr(s, '!'))\n return TOK_BANG;\n if (chr(s, '~'))\n return TOK_TILDE;\n\n /* String literal. */\n if (chr(s, '\\\"')) {\n while (!eof(s) && !eol(s) && peek(s) != '\\\"') {\n if (chr(s, '\\\\')) {\n uint8_t o;\n if (chr(s, '\\\\')) {\n buf_append(s, '\\\\');\n }\n else if (chr(s, '\"')) {\n buf_append(s, '\"');\n }\n else if (chr(s, 'x') || chr(s, 'X')) {\n if (hex(s, &o))\n buf_append(s, (char) o);\n else\n scanner_warn(s, \"illegal hexadecimal escape sequence in string literal\");\n }\n else if (oct(s, &o)) {\n buf_append(s, (char) o);\n }\n else {\n scanner_warn(s, \"unknown escape sequence (%c) in string literal\", peek(s));\n /* Ignore. */\n }\n } else {\n buf_append(s, next(s));\n }\n }\n if (!chr(s, '\\\"')) {\n scanner_err(s, \"unterminated string literal\");\n return TOK_ERROR;\n }\n if (!buf_append(s, '\\0')) {\n scanner_err(s, \"string literal is too long\");\n return TOK_ERROR;\n }\n if (!is_valid_utf8(s->buf, s->buf_pos - 1)) {\n scanner_err(s, \"string literal is not a valid UTF-8 string\");\n return TOK_ERROR;\n }\n val->string.str = s->buf;\n val->string.len = s->buf_pos;\n return TOK_STRING;\n }\n\n /* Identifier or include. */\n if (is_alpha(peek(s)) || peek(s) == '_') {\n s->buf_pos = 0;\n while (is_alnum(peek(s)) || peek(s) == '_')\n buf_append(s, next(s));\n if (!buf_append(s, '\\0')) {\n scanner_err(s, \"identifier is too long\");\n return TOK_ERROR;\n }\n\n if (streq(s->buf, \"include\"))\n return TOK_INCLUDE;\n\n val->string.str = s->buf;\n val->string.len = s->buf_pos;\n return TOK_IDENT;\n }\n\n /* Discard rest of line. */\n skip_to_eol(s);\n\n scanner_err(s, \"unrecognized token\");\n return TOK_ERROR;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': 'compose: fix infinite loop in parser on some inputs\n\nThe parser would enter an infinite loop if an unterminated keysym\nliteral occurs at EOF.\n\nFound with the afl fuzzer.\n\nSigned-off-by: Ran Benita '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static char *InterpretDelegateProperties(ImageInfo *image_info,\n Image *image,const char *embed_text,ExceptionInfo *exception)\n{\n#define ExtendInterpretText(string_length) \\\nDisableMSCWarning(4127) \\\n{ \\\n size_t length=(string_length); \\\n if ((size_t) (q-interpret_text+length+1) >= extent) \\\n { \\\n extent+=length; \\\n interpret_text=(char *) ResizeQuantumMemory(interpret_text,extent+ \\\n MaxTextExtent,sizeof(*interpret_text)); \\\n if (interpret_text == (char *) NULL) \\\n return((char *) NULL); \\\n q=interpret_text+strlen(interpret_text); \\\n } \\\n} \\\nRestoreMSCWarning\n\n#define AppendKeyValue2Text(key,value)\\\nDisableMSCWarning(4127) \\\n{ \\\n size_t length=strlen(key)+strlen(value)+2; \\\n if ((size_t) (q-interpret_text+length+1) >= extent) \\\n { \\\n extent+=length; \\\n interpret_text=(char *) ResizeQuantumMemory(interpret_text,extent+ \\\n MaxTextExtent,sizeof(*interpret_text)); \\\n if (interpret_text == (char *) NULL) \\\n return((char *) NULL); \\\n q=interpret_text+strlen(interpret_text); \\\n } \\\n q+=FormatLocaleString(q,extent,\"%s=%s\\n\",(key),(value)); \\\n} \\\nRestoreMSCWarning\n\n#define AppendString2Text(string) \\\nDisableMSCWarning(4127) \\\n{ \\\n size_t length=strlen((string)); \\\n if ((size_t) (q-interpret_text+length+1) >= extent) \\\n { \\\n extent+=length; \\\n interpret_text=(char *) ResizeQuantumMemory(interpret_text,extent+ \\\n MaxTextExtent,sizeof(*interpret_text)); \\\n if (interpret_text == (char *) NULL) \\\n return((char *) NULL); \\\n q=interpret_text+strlen(interpret_text); \\\n } \\\n (void) CopyMagickString(q,(string),extent); \\\n q+=length; \\\n} \\\nRestoreMSCWarning\n\n char\n *interpret_text,\n *string;\n\n register char\n *q; /* current position in interpret_text */\n\n register const char\n *p; /* position in embed_text string being expanded */\n\n size_t\n extent; /* allocated length of interpret_text */\n\n MagickBooleanType\n number;\n\n assert(image == NULL || image->signature == MagickCoreSignature);\n assert(image_info == NULL || image_info->signature == MagickCoreSignature);\n if ((image != (Image *) NULL) && (image->debug != MagickFalse))\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n else\n if ((image_info != (ImageInfo *) NULL) && (image_info->debug != MagickFalse))\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\"no-image\");\n if (embed_text == (const char *) NULL)\n return(ConstantString(\"\"));\n p=embed_text;\n while ((isspace((int) ((unsigned char) *p)) != 0) && (*p != '\\0'))\n p++;\n if (*p == '\\0')\n return(ConstantString(\"\"));\n /*\n Translate any embedded format characters.\n */\n interpret_text=AcquireString(embed_text); /* new string with extra space */\n extent=MagickPathExtent; /* allocated space in string */\n number=MagickFalse; /* is last char a number? */\n for (q=interpret_text; *p!='\\0';\n number=isdigit((int) ((unsigned char) *p)) ? MagickTrue : MagickFalse,p++)\n {\n /*\n Interpret escape characters (e.g. Filename: %M).\n */\n *q='\\0';\n ExtendInterpretText(MagickPathExtent);\n switch (*p)\n {\n case '\\\\':\n {\n switch (*(p+1))\n {\n case '\\0':\n continue;\n case 'r': /* convert to RETURN */\n {\n *q++='\\r';\n p++;\n continue;\n }\n case 'n': /* convert to NEWLINE */\n {\n *q++='\\n';\n p++;\n continue;\n }\n case '\\n': /* EOL removal UNIX,MacOSX */\n {\n p++;\n continue;\n }\n case '\\r': /* EOL removal DOS,Windows */\n {\n p++;\n if (*p == '\\n') /* return-newline EOL */\n p++;\n continue;\n }\n default:\n {\n p++;\n *q++=(*p);\n }\n }\n continue;\n }\n case '&':\n {\n if (LocaleNCompare(\"<\",p,4) == 0)\n {\n *q++='<';\n p+=3;\n }\n else\n if (LocaleNCompare(\">\",p,4) == 0)\n {\n *q++='>';\n p+=3;\n }\n else\n if (LocaleNCompare(\"&\",p,5) == 0)\n {\n *q++='&';\n p+=4;\n }\n else\n *q++=(*p);\n continue;\n }\n case '%':\n break; /* continue to next set of handlers */\n default:\n {\n *q++=(*p); /* any thing else is 'as normal' */\n continue;\n }\n }\n p++; /* advance beyond the percent */\n /*\n Doubled Percent - or percent at end of string.\n */\n if ((*p == '\\0') || (*p == '\\'') || (*p == '\"'))\n p--;\n if (*p == '%')\n {\n *q++='%';\n continue;\n }\n /*\n Single letter escapes %c.\n */\n if (number != MagickFalse)\n {\n /*\n But only if not preceeded by a number!\n */\n *q++='%'; /* do NOT substitute the percent */\n p--; /* back up one */\n continue;\n }\n string=GetMagickPropertyLetter(image_info,image,*p, exception);\n if (string != (char *) NULL)\n {\n AppendString2Text(string);\n string=DestroyString(string);\n continue;\n }\n (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning,\n \"UnknownImageProperty\",\"\\\"%%%c\\\"\",*p);\n }\n *q='\\0';\n return(interpret_text);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1225'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadOneJNGImage(MngInfo *mng_info,\n const ImageInfo *image_info, ExceptionInfo *exception)\n{\n Image\n *alpha_image,\n *color_image,\n *image,\n *jng_image;\n\n ImageInfo\n *alpha_image_info,\n *color_image_info;\n\n MagickBooleanType\n logging;\n\n int\n unique_filenames;\n\n ssize_t\n y;\n\n MagickBooleanType\n status;\n\n png_uint_32\n jng_height,\n jng_width;\n\n png_byte\n jng_color_type,\n jng_image_sample_depth,\n jng_image_compression_method,\n jng_image_interlace_method,\n jng_alpha_sample_depth,\n jng_alpha_compression_method,\n jng_alpha_filter_method,\n jng_alpha_interlace_method;\n\n register const PixelPacket\n *s;\n\n register ssize_t\n i,\n x;\n\n register PixelPacket\n *q;\n\n register unsigned char\n *p;\n\n unsigned int\n read_JSEP,\n reading_idat;\n\n size_t\n length;\n\n jng_alpha_compression_method=0;\n jng_alpha_sample_depth=8;\n jng_color_type=0;\n jng_height=0;\n jng_width=0;\n alpha_image=(Image *) NULL;\n color_image=(Image *) NULL;\n alpha_image_info=(ImageInfo *) NULL;\n color_image_info=(ImageInfo *) NULL;\n unique_filenames=0;\n\n logging=LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Enter ReadOneJNGImage()\");\n\n image=mng_info->image;\n\n if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)\n {\n /*\n Allocate next image structure.\n */\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" AcquireNextImage()\");\n\n AcquireNextImage(image_info,image);\n\n if (GetNextImageInList(image) == (Image *) NULL)\n return(DestroyImageList(image));\n\n image=SyncNextImageInList(image);\n }\n mng_info->image=image;\n\n /*\n Signature bytes have already been read.\n */\n\n read_JSEP=MagickFalse;\n reading_idat=MagickFalse;\n for (;;)\n {\n char\n type[MaxTextExtent];\n\n unsigned char\n *chunk;\n\n unsigned int\n count;\n\n /*\n Read a new JNG chunk.\n */\n status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n 2*GetBlobSize(image));\n\n if (status == MagickFalse)\n break;\n\n type[0]='\\0';\n (void) ConcatenateMagickString(type,\"errr\",MaxTextExtent);\n length=(size_t) ReadBlobMSBLong(image);\n count=(unsigned int) ReadBlob(image,4,(unsigned char *) type);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Reading JNG chunk type %c%c%c%c, length: %.20g\",\n type[0],type[1],type[2],type[3],(double) length);\n\n if (length > PNG_UINT_31_MAX || count == 0)\n {\n DestroyJNG(NULL,&color_image,&color_image_info,\n &alpha_image,&alpha_image_info);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n\n if (length > GetBlobSize(image))\n {\n DestroyJNG(NULL,&color_image,&color_image_info,\n &alpha_image,&alpha_image_info);\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n }\n p=NULL;\n chunk=(unsigned char *) NULL;\n\n if (length != 0)\n {\n chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk));\n\n if (chunk == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n\n for (i=0; i < (ssize_t) length; i++)\n {\n int\n c;\n\n c=ReadBlobByte(image);\n if (c == EOF)\n break;\n chunk[i]=(unsigned char) c;\n }\n for ( ; i < (ssize_t) length; i++)\n chunk[i]='\\0';\n\n p=chunk;\n }\n\n (void) ReadBlobMSBLong(image); /* read crc word */\n\n if (memcmp(type,mng_JHDR,4) == 0)\n {\n if (length == 16)\n {\n jng_width=(png_uint_32)mng_get_long(p);\n jng_height=(png_uint_32)mng_get_long(&p[4]);\n if ((jng_width == 0) || (jng_height == 0))\n {\n DestroyJNG(chunk,&color_image,&color_image_info,\n &alpha_image,&alpha_image_info);\n\n ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\");\n }\n jng_color_type=p[8];\n jng_image_sample_depth=p[9];\n jng_image_compression_method=p[10];\n jng_image_interlace_method=p[11];\n\n image->interlace=jng_image_interlace_method != 0 ? PNGInterlace :\n NoInterlace;\n\n jng_alpha_sample_depth=p[12];\n jng_alpha_compression_method=p[13];\n jng_alpha_filter_method=p[14];\n jng_alpha_interlace_method=p[15];\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" jng_width: %16lu, jng_height: %16lu\\n\"\n \" jng_color_type: %16d, jng_image_sample_depth: %3d\\n\"\n \" jng_image_compression_method:%3d\",\n (unsigned long) jng_width, (unsigned long) jng_height,\n jng_color_type, jng_image_sample_depth,\n jng_image_compression_method);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" jng_image_interlace_method: %3d\"\n \" jng_alpha_sample_depth: %3d\",\n jng_image_interlace_method,\n jng_alpha_sample_depth);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" jng_alpha_compression_method:%3d\\n\"\n \" jng_alpha_filter_method: %3d\\n\"\n \" jng_alpha_interlace_method: %3d\",\n jng_alpha_compression_method,\n jng_alpha_filter_method,\n jng_alpha_interlace_method);\n }\n }\n\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n if (jng_width > 65535 || jng_height > 65535 ||\n (long) jng_width > GetMagickResourceLimit(WidthResource) ||\n (long) jng_height > GetMagickResourceLimit(HeightResource))\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" JNG width or height too large: (%lu x %lu)\",\n (long) jng_width, (long) jng_height);\n DestroyJNG(chunk,&color_image,&color_image_info,\n &alpha_image,&alpha_image_info);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n\n continue;\n }\n\n\n if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) &&\n ((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) ||\n (memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0)))\n {\n /*\n o create color_image\n o open color_blob, attached to color_image\n o if (color type has alpha)\n open alpha_blob, attached to alpha_image\n */\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Creating color_blob.\");\n\n color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo));\n\n if (color_image_info == (ImageInfo *) NULL)\n {\n DestroyJNG(chunk,&color_image,&color_image_info,\n &alpha_image,&alpha_image_info);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n\n GetImageInfo(color_image_info);\n color_image=AcquireImage(color_image_info);\n if (color_image == (Image *) NULL)\n {\n DestroyJNG(chunk,&color_image,&color_image_info,\n &alpha_image,&alpha_image_info);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n\n (void) AcquireUniqueFilename(color_image->filename);\n unique_filenames++;\n status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode,\n exception);\n\n if (status == MagickFalse)\n {\n DestroyJNG(chunk,&color_image,&color_image_info,\n &alpha_image,&alpha_image_info);\n return(DestroyImageList(image));\n }\n\n if ((image_info->ping == MagickFalse) && (jng_color_type >= 12))\n {\n alpha_image_info=(ImageInfo *)\n AcquireMagickMemory(sizeof(ImageInfo));\n\n if (alpha_image_info == (ImageInfo *) NULL)\n {\n DestroyJNG(chunk,&color_image,&color_image_info,\n &alpha_image,&alpha_image_info);\n ThrowReaderException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n\n GetImageInfo(alpha_image_info);\n alpha_image=AcquireImage(alpha_image_info);\n\n if (alpha_image == (Image *) NULL)\n {\n DestroyJNG(chunk,&color_image,&color_image_info,\n &alpha_image,&alpha_image_info);\n ThrowReaderException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Creating alpha_blob.\");\n\n (void) AcquireUniqueFilename(alpha_image->filename);\n unique_filenames++;\n status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode,\n exception);\n\n if (status == MagickFalse)\n {\n alpha_image=DestroyImage(alpha_image);\n alpha_image_info=DestroyImageInfo(alpha_image_info);\n color_image=DestroyImage(color_image);\n return(DestroyImageList(image));\n }\n\n if (jng_alpha_compression_method == 0)\n {\n unsigned char\n data[18];\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing IHDR chunk to alpha_blob.\");\n\n (void) WriteBlob(alpha_image,8,(const unsigned char *)\n \"\\211PNG\\r\\n\\032\\n\");\n\n (void) WriteBlobMSBULong(alpha_image,13L);\n PNGType(data,mng_IHDR);\n LogPNGChunk(logging,mng_IHDR,13L);\n PNGLong(data+4,jng_width);\n PNGLong(data+8,jng_height);\n data[12]=jng_alpha_sample_depth;\n data[13]=0; /* color_type gray */\n data[14]=0; /* compression method 0 */\n data[15]=0; /* filter_method 0 */\n data[16]=0; /* interlace_method 0 */\n (void) WriteBlob(alpha_image,17,data);\n (void) WriteBlobMSBULong(alpha_image,crc32(0,data,17));\n }\n }\n reading_idat=MagickTrue;\n }\n\n if (memcmp(type,mng_JDAT,4) == 0)\n {\n /* Copy chunk to color_image->blob */\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Copying JDAT chunk data to color_blob.\");\n\n if ((length != 0) && (color_image != (Image *) NULL))\n (void) WriteBlob(color_image,length,chunk);\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n continue;\n }\n\n if (memcmp(type,mng_IDAT,4) == 0)\n {\n png_byte\n data[5];\n\n /* Copy IDAT header and chunk data to alpha_image->blob */\n\n if (alpha_image != NULL && image_info->ping == MagickFalse)\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Copying IDAT chunk data to alpha_blob.\");\n\n (void) WriteBlobMSBULong(alpha_image,(size_t) length);\n PNGType(data,mng_IDAT);\n LogPNGChunk(logging,mng_IDAT,length);\n (void) WriteBlob(alpha_image,4,data);\n (void) WriteBlob(alpha_image,length,chunk);\n (void) WriteBlobMSBULong(alpha_image,\n crc32(crc32(0,data,4),chunk,(uInt) length));\n }\n\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n continue;\n }\n\n if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0))\n {\n /* Copy chunk data to alpha_image->blob */\n\n if ((alpha_image != NULL) && (image_info->ping == MagickFalse) &&\n (length != 0))\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Copying JDAA chunk data to alpha_blob.\");\n\n (void) WriteBlob(alpha_image,length,chunk);\n }\n\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n continue;\n }\n\n if (memcmp(type,mng_JSEP,4) == 0)\n {\n read_JSEP=MagickTrue;\n\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n continue;\n }\n\n if (memcmp(type,mng_bKGD,4) == 0)\n {\n if (length == 2)\n {\n image->background_color.red=ScaleCharToQuantum(p[1]);\n image->background_color.green=image->background_color.red;\n image->background_color.blue=image->background_color.red;\n }\n\n if (length == 6)\n {\n image->background_color.red=ScaleCharToQuantum(p[1]);\n image->background_color.green=ScaleCharToQuantum(p[3]);\n image->background_color.blue=ScaleCharToQuantum(p[5]);\n }\n\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n continue;\n }\n\n if (memcmp(type,mng_gAMA,4) == 0)\n {\n if (length == 4)\n image->gamma=((float) mng_get_long(p))*0.00001;\n\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n continue;\n }\n\n if (memcmp(type,mng_cHRM,4) == 0)\n {\n if (length == 32)\n {\n image->chromaticity.white_point.x=0.00001*mng_get_long(p);\n image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]);\n image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]);\n image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]);\n image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]);\n image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]);\n image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]);\n image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]);\n }\n\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n continue;\n }\n\n if (memcmp(type,mng_sRGB,4) == 0)\n {\n if (length == 1)\n {\n image->rendering_intent=\n Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]);\n image->gamma=1.000f/2.200f;\n image->chromaticity.red_primary.x=0.6400f;\n image->chromaticity.red_primary.y=0.3300f;\n image->chromaticity.green_primary.x=0.3000f;\n image->chromaticity.green_primary.y=0.6000f;\n image->chromaticity.blue_primary.x=0.1500f;\n image->chromaticity.blue_primary.y=0.0600f;\n image->chromaticity.white_point.x=0.3127f;\n image->chromaticity.white_point.y=0.3290f;\n }\n\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n continue;\n }\n\n if (memcmp(type,mng_oFFs,4) == 0)\n {\n if (length > 8)\n {\n image->page.x=(ssize_t) mng_get_long(p);\n image->page.y=(ssize_t) mng_get_long(&p[4]);\n\n if ((int) p[8] != 0)\n {\n image->page.x/=10000;\n image->page.y/=10000;\n }\n }\n\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n continue;\n }\n\n if (memcmp(type,mng_pHYs,4) == 0)\n {\n if (length > 8)\n {\n image->x_resolution=(double) mng_get_long(p);\n image->y_resolution=(double) mng_get_long(&p[4]);\n if ((int) p[8] == PNG_RESOLUTION_METER)\n {\n image->units=PixelsPerCentimeterResolution;\n image->x_resolution=image->x_resolution/100.0f;\n image->y_resolution=image->y_resolution/100.0f;\n }\n }\n\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n continue;\n }\n\n#if 0\n if (memcmp(type,mng_iCCP,4) == 0)\n {\n /* To do: */\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n continue;\n }\n#endif\n\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n if (memcmp(type,mng_IEND,4))\n continue;\n\n break;\n }\n\n\n /* IEND found */\n\n /*\n Finish up reading image data:\n\n o read main image from color_blob.\n\n o close color_blob.\n\n o if (color_type has alpha)\n if alpha_encoding is PNG\n read secondary image from alpha_blob via ReadPNG\n if alpha_encoding is JPEG\n read secondary image from alpha_blob via ReadJPEG\n\n o close alpha_blob.\n\n o copy intensity of secondary image into\n opacity samples of main image.\n\n o destroy the secondary image.\n */\n\n if (color_image_info == (ImageInfo *) NULL)\n {\n assert(color_image == (Image *) NULL);\n assert(alpha_image == (Image *) NULL);\n if (color_image != (Image *) NULL)\n color_image=DestroyImage(color_image);\n return(DestroyImageList(image));\n }\n\n if (color_image == (Image *) NULL)\n {\n assert(alpha_image == (Image *) NULL);\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n }\n\n (void) SeekBlob(color_image,0,SEEK_SET);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Reading jng_image from color_blob.\");\n\n assert(color_image_info != (ImageInfo *) NULL);\n (void) FormatLocaleString(color_image_info->filename,MaxTextExtent,\"jpeg:%s\",\n color_image->filename);\n\n color_image_info->ping=MagickFalse; /* To do: avoid this */\n jng_image=ReadImage(color_image_info,exception);\n\n (void) RelinquishUniqueFileResource(color_image->filename);\n unique_filenames--;\n color_image=DestroyImage(color_image);\n color_image_info=DestroyImageInfo(color_image_info);\n\n if (jng_image == (Image *) NULL)\n {\n DestroyJNG(NULL,NULL,NULL,&alpha_image,&alpha_image_info);\n return(DestroyImageList(image));\n }\n\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Copying jng_image pixels to main image.\");\n image->columns=jng_width;\n image->rows=jng_height;\n length=image->columns*sizeof(PixelPacket);\n\n status=SetImageExtent(image,image->columns,image->rows);\n if (status == MagickFalse)\n {\n jng_image=DestroyImageList(jng_image);\n DestroyJNG(NULL,&color_image,&color_image_info,&alpha_image,\n &alpha_image_info);\n return(DestroyImageList(image));\n }\n if ((image->columns != jng_image->columns) ||\n (image->rows != jng_image->rows))\n {\n jng_image=DestroyImageList(jng_image);\n DestroyJNG(NULL,&color_image,&color_image_info,&alpha_image,\n &alpha_image_info);\n return(DestroyImageList(image));\n }\n\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n s=GetVirtualPixels(jng_image,0,y,image->columns,1,exception);\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n if ((s == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))\n break;\n (void) memcpy(q,s,length);\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n\n jng_image=DestroyImage(jng_image);\n\n if ((image_info->ping == MagickFalse) && (jng_color_type >= 12))\n {\n if (jng_alpha_compression_method == 0)\n {\n png_byte\n data[5];\n (void) WriteBlobMSBULong(alpha_image,0x00000000L);\n PNGType(data,mng_IEND);\n LogPNGChunk(logging,mng_IEND,0L);\n (void) WriteBlob(alpha_image,4,data);\n (void) WriteBlobMSBULong(alpha_image,crc32(0,data,4));\n }\n\n (void) SeekBlob(alpha_image,0,SEEK_SET);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Reading opacity from alpha_blob.\");\n\n (void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent,\n \"%s\",alpha_image->filename);\n\n jng_image=ReadImage(alpha_image_info,exception);\n\n if (jng_image != (Image *) NULL)\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception);\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n if ((s == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))\n break;\n\n if (image->matte != MagickFalse)\n for (x=(ssize_t) image->columns; x != 0; x--,q++,s++)\n SetPixelOpacity(q,QuantumRange-GetPixelRed(s));\n\n else\n for (x=(ssize_t) image->columns; x != 0; x--,q++,s++)\n {\n SetPixelAlpha(q,GetPixelRed(s));\n if (GetPixelOpacity(q) != OpaqueOpacity)\n image->matte=MagickTrue;\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n (void) RelinquishUniqueFileResource(alpha_image->filename);\n unique_filenames--;\n alpha_image=DestroyImage(alpha_image);\n alpha_image_info=DestroyImageInfo(alpha_image_info);\n if (jng_image != (Image *) NULL)\n jng_image=DestroyImage(jng_image);\n }\n\n /* Read the JNG image. */\n\n if (mng_info->mng_type == 0)\n {\n mng_info->mng_width=jng_width;\n mng_info->mng_height=jng_height;\n }\n\n if (image->page.width == 0 && image->page.height == 0)\n {\n image->page.width=jng_width;\n image->page.height=jng_height;\n }\n\n if (image->page.x == 0 && image->page.y == 0)\n {\n image->page.x=mng_info->x_off[mng_info->object_id];\n image->page.y=mng_info->y_off[mng_info->object_id];\n }\n\n else\n {\n image->page.y=mng_info->y_off[mng_info->object_id];\n }\n\n mng_info->image_found++;\n status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image),\n 2*GetBlobSize(image));\n\n if (status == MagickFalse)\n return(DestroyImageList(image));\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" exit ReadOneJNGImage(); unique_filenames=%d\",unique_filenames);\n\n return(image);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-772'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1201'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadCALSImage(const ImageInfo *image_info,\n ExceptionInfo *exception)\n{\n char\n filename[MaxTextExtent],\n header[129],\n message[MaxTextExtent];\n\n FILE\n *file;\n\n Image\n *image;\n\n ImageInfo\n *read_info;\n\n int\n c,\n unique_file;\n\n MagickBooleanType\n status;\n\n register ssize_t\n i;\n\n unsigned long\n density,\n direction,\n height,\n orientation,\n pel_path,\n type,\n width;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Read CALS header.\n */\n (void) memset(header,0,sizeof(header));\n density=0;\n direction=0;\n orientation=1;\n pel_path=0;\n type=1;\n width=0;\n height=0;\n for (i=0; i < 16; i++)\n {\n if (ReadBlob(image,128,(unsigned char *) header) != 128)\n break;\n switch (*header)\n {\n case 'R':\n case 'r':\n {\n if (LocaleNCompare(header,\"rdensty:\",8) == 0)\n {\n (void) sscanf(header+8,\"%lu\",&density);\n break;\n }\n if (LocaleNCompare(header,\"rpelcnt:\",8) == 0)\n {\n (void) sscanf(header+8,\"%lu,%lu\",&width,&height);\n break;\n }\n if (LocaleNCompare(header,\"rorient:\",8) == 0)\n {\n (void) sscanf(header+8,\"%lu,%lu\",&pel_path,&direction);\n if (pel_path == 90)\n orientation=5;\n else\n if (pel_path == 180)\n orientation=3;\n else\n if (pel_path == 270)\n orientation=7;\n if (direction == 90)\n orientation++;\n break;\n }\n if (LocaleNCompare(header,\"rtype:\",6) == 0)\n {\n (void) sscanf(header+6,\"%lu\",&type);\n break;\n }\n break;\n }\n }\n }\n /*\n Read CALS pixels.\n */\n file=(FILE *) NULL;\n unique_file=AcquireUniqueFileResource(filename);\n if (unique_file != -1)\n file=fdopen(unique_file,\"wb\");\n if ((unique_file == -1) || (file == (FILE *) NULL))\n ThrowImageException(FileOpenError,\"UnableToCreateTemporaryFile\");\n while ((c=ReadBlobByte(image)) != EOF)\n (void) fputc(c,file);\n (void) fclose(file);\n (void) CloseBlob(image);\n image=DestroyImage(image);\n read_info=CloneImageInfo(image_info);\n SetImageInfoBlob(read_info,(void *) NULL,0);\n (void) FormatLocaleString(read_info->filename,MaxTextExtent,\"group4:%s\",\n filename);\n (void) FormatLocaleString(message,MaxTextExtent,\"%lux%lu\",width,height);\n read_info->size=ConstantString(message);\n (void) FormatLocaleString(message,MaxTextExtent,\"%lu\",density);\n read_info->density=ConstantString(message);\n read_info->orientation=(OrientationType) orientation;\n image=ReadImage(read_info,exception);\n if (image != (Image *) NULL)\n {\n (void) CopyMagickString(image->filename,image_info->filename,\n MaxTextExtent);\n (void) CopyMagickString(image->magick_filename,image_info->filename,\n MaxTextExtent);\n (void) CopyMagickString(image->magick,\"CALS\",MaxTextExtent);\n }\n read_info=DestroyImageInfo(read_info);\n (void) RelinquishUniqueFileResource(filename);\n return(image);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-252'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1199'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: test_bson_validate (void)\n{\n char filename[64];\n size_t offset;\n bson_t *b;\n int i;\n bson_error_t error;\n\n for (i = 1; i <= 38; i++) {\n bson_snprintf (filename, sizeof filename, \"test%u.bson\", i);\n b = get_bson (filename);\n BSON_ASSERT (bson_validate (b, BSON_VALIDATE_NONE, &offset));\n bson_destroy (b);\n }\n\n b = get_bson (\"codewscope.bson\");\n BSON_ASSERT (bson_validate (b, BSON_VALIDATE_NONE, &offset));\n bson_destroy (b);\n\n b = get_bson (\"empty_key.bson\");\n BSON_ASSERT (bson_validate (b,\n BSON_VALIDATE_NONE | BSON_VALIDATE_UTF8 |\n BSON_VALIDATE_DOLLAR_KEYS |\n BSON_VALIDATE_DOT_KEYS,\n &offset));\n bson_destroy (b);\n\n#define VALIDATE_TEST(_filename, _flags, _offset, _flag, _msg) \\\n b = get_bson (_filename); \\\n BSON_ASSERT (!bson_validate (b, _flags, &offset)); \\\n ASSERT_CMPSIZE_T (offset, ==, (size_t) _offset); \\\n BSON_ASSERT (!bson_validate_with_error (b, _flags, &error)); \\\n ASSERT_ERROR_CONTAINS (error, BSON_ERROR_INVALID, _flag, _msg); \\\n bson_destroy (b)\n\n VALIDATE_TEST (\"overflow2.bson\",\n BSON_VALIDATE_NONE,\n 9,\n BSON_VALIDATE_NONE,\n \"corrupt BSON\");\n VALIDATE_TEST (\"trailingnull.bson\",\n BSON_VALIDATE_NONE,\n 14,\n BSON_VALIDATE_NONE,\n \"corrupt BSON\");\n VALIDATE_TEST (\"dollarquery.bson\",\n BSON_VALIDATE_DOLLAR_KEYS | BSON_VALIDATE_DOT_KEYS,\n 4,\n BSON_VALIDATE_DOLLAR_KEYS,\n \"keys cannot begin with \\\"$\\\": \\\"$query\\\"\");\n VALIDATE_TEST (\"dotquery.bson\",\n BSON_VALIDATE_DOLLAR_KEYS | BSON_VALIDATE_DOT_KEYS,\n 4,\n BSON_VALIDATE_DOT_KEYS,\n \"keys cannot contain \\\".\\\": \\\"abc.def\\\"\");\n VALIDATE_TEST (\"overflow3.bson\",\n BSON_VALIDATE_NONE,\n 9,\n BSON_VALIDATE_NONE,\n \"corrupt BSON\");\n /* same outcome as above, despite different flags */\n VALIDATE_TEST (\"overflow3.bson\",\n BSON_VALIDATE_UTF8,\n 9,\n BSON_VALIDATE_NONE,\n \"corrupt BSON\");\n VALIDATE_TEST (\"overflow4.bson\",\n BSON_VALIDATE_NONE,\n 9,\n BSON_VALIDATE_NONE,\n \"corrupt BSON\");\n VALIDATE_TEST (\"empty_key.bson\",\n BSON_VALIDATE_EMPTY_KEYS,\n 4,\n BSON_VALIDATE_EMPTY_KEYS,\n \"empty key\");\n VALIDATE_TEST (\n \"test40.bson\", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, \"corrupt BSON\");\n VALIDATE_TEST (\n \"test41.bson\", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, \"corrupt BSON\");\n VALIDATE_TEST (\n \"test42.bson\", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, \"corrupt BSON\");\n VALIDATE_TEST (\n \"test43.bson\", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, \"corrupt BSON\");\n VALIDATE_TEST (\n \"test44.bson\", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, \"corrupt BSON\");\n VALIDATE_TEST (\n \"test45.bson\", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, \"corrupt BSON\");\n VALIDATE_TEST (\n \"test46.bson\", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, \"corrupt BSON\");\n VALIDATE_TEST (\n \"test47.bson\", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, \"corrupt BSON\");\n VALIDATE_TEST (\n \"test48.bson\", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, \"corrupt BSON\");\n VALIDATE_TEST (\n \"test49.bson\", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, \"corrupt BSON\");\n VALIDATE_TEST (\"test50.bson\",\n BSON_VALIDATE_NONE,\n 10,\n BSON_VALIDATE_NONE,\n \"corrupt code-with-scope\");\n VALIDATE_TEST (\"test51.bson\",\n BSON_VALIDATE_NONE,\n 10,\n BSON_VALIDATE_NONE,\n \"corrupt code-with-scope\");\n VALIDATE_TEST (\n \"test52.bson\", BSON_VALIDATE_NONE, 9, BSON_VALIDATE_NONE, \"corrupt BSON\");\n VALIDATE_TEST (\n \"test53.bson\", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, \"corrupt BSON\");\n VALIDATE_TEST (\"test54.bson\",\n BSON_VALIDATE_NONE,\n 12,\n BSON_VALIDATE_NONE,\n \"corrupt BSON\");\n\n /* DBRef validation */\n b = BCON_NEW (\"my_dbref\",\n \"{\",\n \"$ref\",\n BCON_UTF8 (\"collection\"),\n \"$id\",\n BCON_INT32 (1),\n \"}\");\n BSON_ASSERT (bson_validate_with_error (b, BSON_VALIDATE_NONE, &error));\n BSON_ASSERT (\n bson_validate_with_error (b, BSON_VALIDATE_DOLLAR_KEYS, &error));\n bson_destroy (b);\n\n /* needs \"$ref\" before \"$id\" */\n b = BCON_NEW (\"my_dbref\", \"{\", \"$id\", BCON_INT32 (1), \"}\");\n BSON_ASSERT (bson_validate_with_error (b, BSON_VALIDATE_NONE, &error));\n BSON_ASSERT (\n !bson_validate_with_error (b, BSON_VALIDATE_DOLLAR_KEYS, &error));\n ASSERT_ERROR_CONTAINS (error,\n BSON_ERROR_INVALID,\n BSON_VALIDATE_DOLLAR_KEYS,\n \"keys cannot begin with \\\"$\\\": \\\"$id\\\"\");\n bson_destroy (b);\n\n /* two $refs */\n b = BCON_NEW (\"my_dbref\",\n \"{\",\n \"$ref\",\n BCON_UTF8 (\"collection\"),\n \"$ref\",\n BCON_UTF8 (\"collection\"),\n \"}\");\n BSON_ASSERT (bson_validate_with_error (b, BSON_VALIDATE_NONE, &error));\n BSON_ASSERT (\n !bson_validate_with_error (b, BSON_VALIDATE_DOLLAR_KEYS, &error));\n ASSERT_ERROR_CONTAINS (error,\n BSON_ERROR_INVALID,\n BSON_VALIDATE_DOLLAR_KEYS,\n \"keys cannot begin with \\\"$\\\": \\\"$ref\\\"\");\n bson_destroy (b);\n\n /* must not contain invalid key like \"extra\" */\n b = BCON_NEW (\"my_dbref\",\n \"{\",\n \"$ref\",\n BCON_UTF8 (\"collection\"),\n \"extra\",\n BCON_INT32 (2),\n \"$id\",\n BCON_INT32 (1),\n \"}\");\n BSON_ASSERT (bson_validate_with_error (b, BSON_VALIDATE_NONE, &error));\n BSON_ASSERT (\n !bson_validate_with_error (b, BSON_VALIDATE_DOLLAR_KEYS, &error));\n ASSERT_ERROR_CONTAINS (error,\n BSON_ERROR_INVALID,\n BSON_VALIDATE_DOLLAR_KEYS,\n \"invalid key within DBRef subdocument: \\\"extra\\\"\");\n bson_destroy (b);\n\n#undef VALIDATE_TEST\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix for CVE-2018-16790 -- Verify bounds before binary length read.\n\nAs reported here: https://jira.mongodb.org/browse/CDRIVER-2819,\na heap overread occurs due a failure to correctly verify data\nbounds.\n\nIn the original check, len - o returns the data left including the\nsizeof(l) we just read. Instead, the comparison should check\nagainst the data left NOT including the binary int32, i.e. just\nsubtype (byte*) instead of int32 subtype (byte*).\n\nAdded in test for corrupted BSON example.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: epass2003_sm_unwrap_apdu(struct sc_card *card, struct sc_apdu *sm, struct sc_apdu *plain)\n{\n\tint r;\n\tsize_t len = 0;\n\tepass2003_exdata *exdata = NULL;\n\n\tif (!card->drv_data) \n\t\treturn SC_ERROR_INVALID_ARGUMENTS;\n\n\texdata = (epass2003_exdata *)card->drv_data;\n\n\tLOG_FUNC_CALLED(card->ctx);\n\n\tr = sc_check_sw(card, sm->sw1, sm->sw2);\n\tif (r == SC_SUCCESS) {\n\t\tif (exdata->sm) {\n\t\t\tif (0 != decrypt_response(card, sm->resp, sm->resplen, plain->resp, &len))\n\t\t\t\treturn SC_ERROR_CARD_CMD_FAILED;\n\t\t}\n\t\telse {\n\t\t\tmemcpy(plain->resp, sm->resp, sm->resplen);\n\t\t\tlen = sm->resplen;\n\t\t}\n\t}\n\n\tplain->resplen = len;\n\tplain->sw1 = sm->sw1;\n\tplain->sw2 = sm->sw2;\n\n\tsc_log(card->ctx,\n\t \"unwrapped APDU: resplen %\"SC_FORMAT_LEN_SIZE_T\"u, SW %02X%02X\",\n\t plain->resplen, plain->sw1, plain->sw2);\n\tLOG_FUNC_RETURN(card->ctx, SC_SUCCESS);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415', 'CWE-119'], 'message': 'fixed out of bounds writes\n\nThanks to Eric Sesterhenn from X41 D-SEC GmbH\nfor reporting the problems.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial)\n{\n\tcac_private_data_t * priv = CAC_DATA(card);\n\n\tSC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL);\n if (card->serialnr.len) {\n *serial = card->serialnr;\n SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);\n }\n\tif (priv->cac_id_len) {\n\t\tserial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR);\n\t\tmemcpy(serial->value, priv->cac_id, priv->cac_id_len);\n\t\tSC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);\n\t}\n\tSC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_NOT_FOUND);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415', 'CWE-119'], 'message': 'fixed out of bounds writes\n\nThanks to Eric Sesterhenn from X41 D-SEC GmbH\nfor reporting the problems.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig)\n\t{\n\ttcp::TCP_ApplicationAnalyzer::DeliverStream(length, line, orig);\n\n\tif ( starttls )\n\t\t{\n\t\tForwardStream(length, line, orig);\n\t\treturn;\n\t\t}\n\n\t// check line size\n\tif ( length > 512 )\n\t\t{\n\t\tWeird(\"irc_line_size_exceeded\");\n\t\treturn;\n\t\t}\n\n\tstring myline = string((const char*) line, length);\n\tSkipLeadingWhitespace(myline);\n\n\tif ( myline.length() < 3 )\n\t\t{\n\t\tWeird(\"irc_line_too_short\");\n\t\treturn;\n\t\t}\n\n\t// Check for prefix.\n\tstring prefix = \"\";\n\tif ( myline[0] == ':' )\n\t\t{ // find end of prefix and extract it\n\t\tauto pos = myline.find(' ');\n\t\tif ( pos == string::npos )\n\t\t\t{\n\t\t\tWeird(\"irc_invalid_line\");\n\t\t\treturn;\n\t\t\t}\n\n\t\tprefix = myline.substr(1, pos - 1);\n\t\tmyline = myline.substr(pos + 1); // remove prefix from line\n\t\tSkipLeadingWhitespace(myline);\n\t\t}\n\n\tif ( orig )\n\t\tProtocolConfirmation();\n\n\tint code = 0;\n\tstring command = \"\";\n\n\t// Check if line is long enough to include status code or command.\n\t// (shortest command with optional params is \"WHO\")\n\tif ( myline.length() < 3 )\n\t\t{\n\t\tWeird(\"irc_invalid_line\");\n\t\tProtocolViolation(\"line too short\");\n\t\treturn;\n\t\t}\n\n\t// Check if this is a server reply.\n\tif ( isdigit(myline[0]) )\n\t\t{\n\t\tif ( isdigit(myline[1]) && isdigit(myline[2]) &&\n\t\t myline[3] == ' ')\n\t\t\t{\n\t\t\tcode = (myline[0] - '0') * 100 +\n\t\t\t\t(myline[1] - '0') * 10 + (myline[2] - '0');\n\t\t\tmyline = myline.substr(4);\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tWeird(\"irc_invalid_reply_number\");\n\t\t\tProtocolViolation(\"invalid reply number\");\n\t\t\treturn;\n\t\t\t}\n\t\t}\n\telse\n\t\t{ // get command\n\t\tauto pos = myline.find(' ');\n\t\t// Not all commands require parameters\n\t\tif ( pos == string::npos )\n\t\t\tpos = myline.length();\n\n\t\tcommand = myline.substr(0, pos);\n\t\tfor ( unsigned int i = 0; i < command.size(); ++i )\n\t\t\tcommand[i] = toupper(command[i]);\n\n\t\t// Adjust for the no-parameter case\n\t\tif ( pos == myline.length() )\n\t\t\tpos--;\n\n\t\tmyline = myline.substr(pos + 1);\n\t\tSkipLeadingWhitespace(myline);\n\t\t}\n\n\t// Extract parameters.\n\tstring params = myline;\n\n\t// special case\n\tif ( command == \"STARTTLS\" )\n\t\treturn;\n\n\t// Check for Server2Server - connections with ZIP enabled.\n\tif ( orig && orig_status == WAIT_FOR_REGISTRATION )\n\t\t{\n\t\tif ( command == \"PASS\" )\n\t\t\t{\n\t\t\tvector p = SplitWords(params,' ');\n\t\t\tif ( p.size() > 3 &&\n\t\t\t (p[3].find('Z')<=p[3].size() ||\n\t\t\t p[3].find('z')<=p[3].size()) )\n\t\t\t\torig_zip_status = ACCEPT_ZIP;\n\t\t\telse\n\t\t\t orig_zip_status = NO_ZIP;\n\t\t\t}\n\n\t\t// We do not check if SERVER command is successful, since\n\t\t// the connection will be terminated by the server if\n\t\t// authentication fails.\n\t\t//\n\t\t// (### This seems not quite prudent to me - VP)\n\t\tif ( command == \"SERVER\" && prefix == \"\")\n\t\t\t{\n\t\t\torig_status = REGISTERED;\n\t\t\t}\n\t\t}\n\n\tif ( ! orig && resp_status == WAIT_FOR_REGISTRATION )\n\t\t{\n\t\tif ( command == \"PASS\" )\n\t\t\t{\n\t\t\tvector p = SplitWords(params,' ');\n\t\t\tif ( p.size() > 3 &&\n\t\t\t (p[3].find('Z')<=p[3].size() ||\n\t\t\t p[3].find('z')<=p[3].size()) )\n\t\t\t resp_zip_status = ACCEPT_ZIP;\n\t\t\telse\n\t\t\t resp_zip_status = NO_ZIP;\n\n\t\t\t}\n\n\t\t// Again, don't bother checking whether SERVER command\n\t\t// is successful.\n\t\tif ( command == \"SERVER\" && prefix == \"\")\n\t\t\tresp_status = REGISTERED;\n\t\t}\n\n\t// Analyze server reply messages.\n\tif ( code > 0 )\n\t\t{\n\t\tswitch ( code ) {\n\t\t/*\n\t\tcase 1: // RPL_WELCOME\n\t\tcase 2: // RPL_YOURHOST\n\t\tcase 3: // RPL_CREATED\n\t\tcase 4: // RPL_MYINFO\n\t\tcase 5: // RPL_BOUNCE\n\t\tcase 252: // number of ops online\n\t\tcase 253: // number of unknown connections\n\t\tcase 265: // RPL_LOCALUSERS\n\t\tcase 312: // whois server reply\n\t\tcase 315: // end of who list\n\t\tcase 317: // whois idle reply\n\t\tcase 318: // end of whois list\n\t\tcase 366: // end of names list\n\t\tcase 372: // RPL_MOTD\n\t\tcase 375: // RPL_MOTDSTART\n\t\tcase 376: // RPL_ENDOFMOTD\n\t\tcase 331: // RPL_NOTOPIC\n\t\t\tbreak;\n\t\t*/\n\n\t\t// Count of users, services and servers in whole network.\n\t\tcase 251:\n\t\t\tif ( ! irc_network_info )\n\t\t\t\tbreak;\n\n\t\t\t{\n\t\t\tvector parts = SplitWords(params, ' ');\n\t\t\tint users = 0;\n\t\t\tint services = 0;\n\t\t\tint servers = 0;\n\n\t\t\tfor ( unsigned int i = 1; i < parts.size(); ++i )\n\t\t\t\t{\n\t\t\t\tif ( parts[i] == \"users\" )\n\t\t\t\t\tusers = atoi(parts[i-1].c_str());\n\t\t\t\telse if ( parts[i] == \"services\" )\n\t\t\t\t\tservices = atoi(parts[i-1].c_str());\n\t\t\t\telse if ( parts[i] == \"servers\" )\n\t\t\t\t\tservers = atoi(parts[i-1].c_str());\n\t\t\t\t// else ###\n\t\t\t\t}\n\n\t\t\tval_list* vl = new val_list;\n\t\t\tvl->append(BuildConnVal());\n\t\t\tvl->append(new Val(orig, TYPE_BOOL));\n\t\t\tvl->append(new Val(users, TYPE_INT));\n\t\t\tvl->append(new Val(services, TYPE_INT));\n\t\t\tvl->append(new Val(servers, TYPE_INT));\n\n\t\t\tConnectionEvent(irc_network_info, vl);\n\t\t\t}\n\t\t\tbreak;\n\n\t\t// List of users in a channel (names command).\n\t\tcase 353:\n\t\t\tif ( ! irc_names_info )\n\t\t\t\tbreak;\n\n\t\t\t{\n\t\t\tvector parts = SplitWords(params, ' ');\n\n\t\t\t// Remove nick name.\n\t\t\tparts.erase(parts.begin());\n\t\t\tif ( parts.size() < 2 )\n\t\t\t\t{\n\t\t\t\tWeird(\"irc_invalid_names_line\");\n\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\tstring type = parts[0];\n\t\t\tstring channel = parts[1];\n\n\t\t\t// Remove type and channel.\n\t\t\tparts.erase(parts.begin());\n\t\t\tparts.erase(parts.begin());\n\n\t\t\tif ( parts.size() > 0 && parts[0][0] == ':' )\n\t\t\t\tparts[0] = parts[0].substr(1);\n\n\t\t\tval_list* vl = new val_list;\n\t\t\tvl->append(BuildConnVal());\n\t\t\tvl->append(new Val(orig, TYPE_BOOL));\n\t\t\tvl->append(new StringVal(type.c_str()));\n\t\t\tvl->append(new StringVal(channel.c_str()));\n\n\t\t\tTableVal* set = new TableVal(string_set);\n\t\t\tfor ( unsigned int i = 0; i < parts.size(); ++i )\n\t\t\t\t{\n\t\t\t\tif ( parts[i][0] == '@' )\n\t\t\t\t\tparts[i] = parts[i].substr(1);\n\t\t\t\tVal* idx = new StringVal(parts[i].c_str());\n\t\t\t\tset->Assign(idx, 0);\n\t\t\t\tUnref(idx);\n\t\t\t\t}\n\t\t\tvl->append(set);\n\n\t\t\tConnectionEvent(irc_names_info, vl);\n\t\t\t}\n\t\t\tbreak;\n\n\t\t// Count of users and services on this server.\n\t\tcase 255:\n\t\t\tif ( ! irc_server_info )\n\t\t\t\tbreak;\n\n\t\t\t{\n\t\t\tvector parts = SplitWords(params, ' ');\n\t\t\tint users = 0;\n\t\t\tint services = 0;\n\t\t\tint servers = 0;\n\n\t\t\tfor ( unsigned int i = 1; i < parts.size(); ++i )\n\t\t\t\t{\n\t\t\t\tif ( parts[i] == \"users,\" )\n\t\t\t\t\tusers = atoi(parts[i-1].c_str());\n\t\t\t\telse if ( parts[i] == \"clients\" )\n\t\t\t\t\tusers = atoi(parts[i-1].c_str());\n\t\t\t\telse if ( parts[i] == \"services\" )\n\t\t\t\t\tservices = atoi(parts[i-1].c_str());\n\t\t\t\telse if ( parts[i] == \"servers\" )\n\t\t\t\t\tservers = atoi(parts[i-1].c_str());\n\t\t\t\t// else ###\n\t\t\t\t}\n\n\t\t\tval_list* vl = new val_list;\n\t\t\tvl->append(BuildConnVal());\n\t\t\tvl->append(new Val(orig, TYPE_BOOL));\n\t\t\tvl->append(new Val(users, TYPE_INT));\n\t\t\tvl->append(new Val(services, TYPE_INT));\n\t\t\tvl->append(new Val(servers, TYPE_INT));\n\n\t\t\tConnectionEvent(irc_server_info, vl);\n\t\t\t}\n\t\t\tbreak;\n\n\t\t// Count of channels.\n\t\tcase 254:\n\t\t\tif ( ! irc_channel_info )\n\t\t\t\tbreak;\n\n\t\t\t{\n\t\t\tvector parts = SplitWords(params, ' ');\n\t\t\tint channels = 0;\n\t\t\tfor ( unsigned int i = 1; i < parts.size(); ++i )\n\t\t\t\tif ( parts[i] == \":channels\" )\n\t\t\t\t\tchannels = atoi(parts[i - 1].c_str());\n\n\t\t\tval_list* vl = new val_list;\n\t\t\tvl->append(BuildConnVal());\n\t\t\tvl->append(new Val(orig, TYPE_BOOL));\n\t\t\tvl->append(new Val(channels, TYPE_INT));\n\n\t\t\tConnectionEvent(irc_channel_info, vl);\n\t\t\t}\n\t\t\tbreak;\n\n\t\t// RPL_GLOBALUSERS\n\t\tcase 266:\n\t\t\t{\n\t\t\t// FIXME: We should really streamline all this\n\t\t\t// parsing code ...\n\t\t\tif ( ! irc_global_users )\n\t\t\t\tbreak;\n\n\t\t\tconst char* prefix = params.c_str();\n\n\t\t\tconst char* eop = strchr(prefix, ' ');\n\t\t\tif ( ! eop )\n\t\t\t\t{\n\t\t\t\tWeird(\"invalid_irc_global_users_reply\");\n\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\tconst char *msg = strchr(++eop, ':');\n\t\t\tif ( ! msg )\n\t\t\t\t{\n\t\t\t\tWeird(\"invalid_irc_global_users_reply\");\n\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\tval_list* vl = new val_list;\n\t\t\tvl->append(BuildConnVal());\n\t\t\tvl->append(new Val(orig, TYPE_BOOL));\n\t\t\tvl->append(new StringVal(eop - prefix, prefix));\n\t\t\tvl->append(new StringVal(++msg));\n\t\t\tConnectionEvent(irc_global_users, vl);\n\t\t\tbreak;\n\t\t\t}\n\n\t\t// WHOIS user reply line.\n\t\tcase 311:\n\t\t\tif ( ! irc_whois_user_line )\n\t\t\t\tbreak;\n\n\t\t\t{\n\t\t\tvector parts = SplitWords(params, ' ');\n\n\t\t\tif ( parts.size() > 1 )\n\t\t\t\tparts.erase(parts.begin());\n\t\t\tif ( parts.size() < 5 )\n\t\t\t\t{\n\t\t\t\tWeird(\"irc_invalid_whois_user_line\");\n\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\tval_list* vl = new val_list;\n\t\t\tvl->append(BuildConnVal());\n\t\t\tvl->append(new Val(orig, TYPE_BOOL));\n\t\t\tvl->append(new StringVal(parts[0].c_str()));\n\t\t\tvl->append(new StringVal(parts[1].c_str()));\n\t\t\tvl->append(new StringVal(parts[2].c_str()));\n\n\t\t\tparts.erase(parts.begin(), parts.begin() + 4);\n\n\t\t\tstring real_name = parts[0];\n\t\t\tfor ( unsigned int i = 1; i < parts.size(); ++i )\n\t\t\t\treal_name = real_name + \" \" + parts[i];\n\n\t\t\tif ( real_name[0] == ':' )\n\t\t\t\treal_name = real_name.substr(1);\n\n\t\t\tvl->append(new StringVal(real_name.c_str()));\n\n\t\t\tConnectionEvent(irc_whois_user_line, vl);\n\t\t\t}\n\t\t\tbreak;\n\n\t\t// WHOIS operator reply line.\n\t\tcase 313:\n\t\t\tif ( ! irc_whois_operator_line )\n\t\t\t\tbreak;\n\n\t\t\t{\n\t\t\tvector parts = SplitWords(params, ' ');\n\n\t\t\tif ( parts.size() > 1 )\n\t\t\t\tparts.erase(parts.begin());\n\n\t\t\tif ( parts.size() < 2 )\n\t\t\t\t{\n\t\t\t\tWeird(\"irc_invalid_whois_operator_line\");\n\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\tval_list* vl = new val_list;\n\t\t\tvl->append(BuildConnVal());\n\t\t\tvl->append(new Val(orig, TYPE_BOOL));\n\t\t\tvl->append(new StringVal(parts[0].c_str()));\n\n\t\t\tConnectionEvent(irc_whois_operator_line, vl);\n\t\t\t}\n\t\t\tbreak;\n\n\t\t// WHOIS channel reply.\n\t\tcase 319:\n\t\t\tif ( ! irc_whois_channel_line )\n\t\t\t\tbreak;\n\n\t\t\t{\n\t\t\tvector parts = SplitWords(params, ' ');\n\n\t\t\t// Remove nick name.\n\t\t\tparts.erase(parts.begin());\n\t\t\tif ( parts.size() < 2 )\n\t\t\t\t{\n\t\t\t\tWeird(\"irc_invalid_whois_channel_line\");\n\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\tstring nick = parts[0];\n\t\t\tparts.erase(parts.begin());\n\n\t\t\tif ( parts.size() > 0 && parts[0][0] == ':' )\n\t\t\t\tparts[0] = parts[0].substr(1);\n\n\t\t\tval_list* vl = new val_list;\n\t\t\tvl->append(BuildConnVal());\n\t\t\tvl->append(new Val(orig, TYPE_BOOL));\n\t\t\tvl->append(new StringVal(nick.c_str()));\n\t\t\tTableVal* set = new TableVal(string_set);\n\t\t\tfor ( unsigned int i = 0; i < parts.size(); ++i )\n\t\t\t\t{\n\t\t\t\tVal* idx = new StringVal(parts[i].c_str());\n\t\t\t\tset->Assign(idx, 0);\n\t\t\t\tUnref(idx);\n\t\t\t\t}\n\n\t\t\tvl->append(set);\n\n\t\t\tConnectionEvent(irc_whois_channel_line, vl);\n\t\t\t}\n\t\t\tbreak;\n\n\t\t// RPL_TOPIC reply.\n\t\tcase 332:\n\t\t\t{\n\t\t\tif ( ! irc_channel_topic )\n\t\t\t\tbreak;\n\n\t\t\tvector parts = SplitWords(params, ' ');\n\t\t\tif ( parts.size() < 4 )\n\t\t\t\t{\n\t\t\t\tWeird(\"irc_invalid_topic_reply\");\n\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\tunsigned int pos = params.find(':');\n\t\t\tif ( pos < params.size() )\n\t\t\t\t{\n\t\t\t\tstring topic = params.substr(pos + 1);\n\t\t\t\tval_list* vl = new val_list;\n\n\t\t\t\tvl->append(BuildConnVal());\n\t\t\t\tvl->append(new Val(orig, TYPE_BOOL));\n\t\t\t\tvl->append(new StringVal(parts[1].c_str()));\n\n\t\t\t\tconst char* t = topic.c_str();\n\t\t\t\tif ( *t == ':' )\n\t\t\t\t\t++t;\n\n\t\t\t\tvl->append(new StringVal(t));\n\n\t\t\t\tConnectionEvent(irc_channel_topic, vl);\n\t\t\t\t}\n\t\t\telse\n\t\t\t\t{\n\t\t\t\tWeird(\"irc_invalid_topic_reply\");\n\t\t\t\treturn;\n\t\t\t\t}\n\t\t\tbreak;\n\t\t\t}\n\n\t\t// WHO reply line.\n\t\tcase 352:\n\t\t\tif ( ! irc_who_line )\n\t\t\t\tbreak;\n\n\t\t\t{\n\t\t\tvector parts = SplitWords(params, ' ');\n\t\t\tif ( parts.size() < 9 )\n\t\t\t\t{\n\t\t\t\tWeird(\"irc_invalid_who_line\");\n\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\tval_list* vl = new val_list;\n\t\t\tvl->append(BuildConnVal());\n\t\t\tvl->append(new Val(orig, TYPE_BOOL));\n\t\t\tvl->append(new StringVal(parts[0].c_str()));\n\t\t\tvl->append(new StringVal(parts[1].c_str()));\n\t\t\tif ( parts[2][0] == '~' )\n\t\t\t\tparts[2] = parts[2].substr(1);\n\t\t\tvl->append(new StringVal(parts[2].c_str()));\n\t\t\tvl->append(new StringVal(parts[3].c_str()));\n\t\t\tvl->append(new StringVal(parts[4].c_str()));\n\t\t\tvl->append(new StringVal(parts[5].c_str()));\n\t\t\tvl->append(new StringVal(parts[6].c_str()));\n\t\t\tif ( parts[7][0] == ':' )\n\t\t\t\tparts[7] = parts[7].substr(1);\n\t\t\tvl->append(new Val(atoi(parts[7].c_str()), TYPE_INT));\n\t\t\tvl->append(new StringVal(parts[8].c_str()));\n\n\t\t\tConnectionEvent(irc_who_line, vl);\n\t\t\t}\n\t\t\tbreak;\n\n\t\t// Invalid nick name.\n\t\tcase 431:\n\t\tcase 432:\n\t\tcase 433:\n\t\tcase 436:\n\t\t\tif ( irc_invalid_nick )\n\t\t\t\t{\n\t\t\t\tval_list* vl = new val_list;\n\t\t\t\tvl->append(BuildConnVal());\n\t\t\t\tvl->append(new Val(orig, TYPE_BOOL));\n\t\t\t\tConnectionEvent(irc_invalid_nick, vl);\n\t\t\t\t}\n\t\t\tbreak;\n\n\t\t// Operator responses.\n\t\tcase 381: // User is operator\n\t\tcase 491: // user is not operator\n\t\t\tif ( irc_oper_response )\n\t\t\t\t{\n\t\t\t\tval_list* vl = new val_list;\n\t\t\t\tvl->append(BuildConnVal());\n\t\t\t\tvl->append(new Val(orig, TYPE_BOOL));\n\t\t\t\tvl->append(new Val(code == 381, TYPE_BOOL));\n\t\t\t\tConnectionEvent(irc_oper_response, vl);\n\t\t\t\t}\n\t\t\tbreak;\n\n\t\tcase 670:\n\t\t\t// StartTLS success reply to StartTLS\n\t\t\tStartTLS();\n\t\t\tbreak;\n\n\t\t// All other server replies.\n\t\tdefault:\n\t\t\tval_list* vl = new val_list;\n\t\t\tvl->append(BuildConnVal());\n\t\t\tvl->append(new Val(orig, TYPE_BOOL));\n\t\t\tvl->append(new StringVal(prefix.c_str()));\n\t\t\tvl->append(new Val(code, TYPE_COUNT));\n\t\t\tvl->append(new StringVal(params.c_str()));\n\n\t\t\tConnectionEvent(irc_reply, vl);\n\t\t\tbreak;\n\t\t}\n\t\treturn;\n\t\t}\n\n\t// Check if command is valid.\n\tif ( command.size() > 20 )\n\t\t{\n\t\tWeird(\"irc_invalid_command\");\n\t\tif ( ++invalid_msg_count > invalid_msg_max_count )\n\t\t\t{\n\t\t\tWeird(\"irc_too_many_invalid\");\n\t\t\tProtocolViolation(\"too many long lines\");\n\t\t\treturn;\n\t\t\t}\n\t\treturn;\n\t\t}\n\n\telse if ( ( irc_privmsg_message || irc_dcc_message ) && command == \"PRIVMSG\")\n\t\t{\n\t\tunsigned int pos = params.find(' ');\n\t\tif ( pos >= params.size() )\n\t\t\t{\n\t\t\tWeird(\"irc_invalid_privmsg_message_format\");\n\t\t\treturn;\n\t\t\t}\n\n\t\tstring target = params.substr(0, pos);\n\t\tstring message = params.substr(pos + 1);\n\t\tSkipLeadingWhitespace(message);\n\n\t\tif ( message.size() > 0 && message[0] == ':' )\n\t\t\tmessage = message.substr(1);\n\t\tif ( message.size() > 0 && message[0] == 1 )\n\t\t\tmessage = message.substr(1); // DCC\n\n\t\t// Check for DCC messages.\n\t\tif ( message.size() > 3 && message.substr(0, 3) == \"DCC\" )\n\t\t\t{\n\t\t\tif ( message.size() > 0 &&\n\t\t\t message[message.size() - 1] == 1 )\n\t\t\t\tmessage = message.substr(0, message.size() - 1);\n\n\t\t\tvector parts = SplitWords(message, ' ');\n\t\t\tif ( parts.size() < 5 || parts.size() > 6 )\n\t\t\t\t{\n\t\t\t\t// Turbo DCC extension appends a \"T\" at the end of handshake.\n\t\t\t\tif ( ! (parts.size() == 7 && parts[6] == \"T\") )\n\t\t\t\t\t{\n\t\t\t\t\tWeird(\"irc_invalid_dcc_message_format\");\n\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t// Calculate IP address.\n\t\t\tuint32 raw_ip = 0;\n\t\t\tfor ( unsigned int i = 0; i < parts[3].size(); ++i )\n\t\t\t\t{\n\t\t\t\tstring s = parts[3].substr(i, 1);\n\t\t\t\traw_ip = (10 * raw_ip) + atoi(s.c_str());\n\t\t\t\t}\n\n\t\t\tval_list* vl = new val_list;\n\t\t\tvl->append(BuildConnVal());\n\t\t\tvl->append(new Val(orig, TYPE_BOOL));\n\t\t\tvl->append(new StringVal(prefix.c_str()));\n\t\t\tvl->append(new StringVal(target.c_str()));\n\t\t\tvl->append(new StringVal(parts[1].c_str()));\n\t\t\tvl->append(new StringVal(parts[2].c_str()));\n\t\t\tvl->append(new AddrVal(htonl(raw_ip)));\n\t\t\tvl->append(new Val(atoi(parts[4].c_str()), TYPE_COUNT));\n\t\t\tif ( parts.size() >= 6 )\n\t\t\t\tvl->append(new Val(atoi(parts[5].c_str()),\n\t\t\t\t\t\t\tTYPE_COUNT));\n\t\t\telse\n\t\t\t\tvl->append(new Val(0, TYPE_COUNT));\n\n\t\t\tConnectionEvent(irc_dcc_message, vl);\n\t\t\t}\n\n\t\telse\n\t\t\t{\n\t\t\tval_list* vl = new val_list;\n\t\t\tvl->append(BuildConnVal());\n\t\t\tvl->append(new Val(orig, TYPE_BOOL));\n\t\t\tvl->append(new StringVal(prefix.c_str()));\n\t\t\tvl->append(new StringVal(target.c_str()));\n\t\t\tvl->append(new StringVal(message.c_str()));\n\n\t\t\tConnectionEvent(irc_privmsg_message, vl);\n\t\t\t}\n\t\t}\n\n\telse if ( irc_notice_message && command == \"NOTICE\" )\n\t\t{\n\t\tunsigned int pos = params.find(' ');\n\t\tif ( pos >= params.size() )\n\t\t\t{\n\t\t\tWeird(\"irc_invalid_notice_message_format\");\n\t\t\treturn;\n\t\t\t}\n\n\t\tstring target = params.substr(0, pos);\n\t\tstring message = params.substr(pos + 1);\n\t\tSkipLeadingWhitespace(message);\n\t\tif ( message[0] == ':' )\n\t\t\tmessage = message.substr(1);\n\n\t\tval_list* vl = new val_list;\n\t\tvl->append(BuildConnVal());\n\t\tvl->append(new Val(orig, TYPE_BOOL));\n\t\tvl->append(new StringVal(prefix.c_str()));\n\t\tvl->append(new StringVal(target.c_str()));\n\t\tvl->append(new StringVal(message.c_str()));\n\n\t\tConnectionEvent(irc_notice_message, vl);\n\t\t}\n\n\telse if ( irc_squery_message && command == \"SQUERY\" )\n\t\t{\n\t\tunsigned int pos = params.find(' ');\n\t\tif ( pos >= params.size() )\n\t\t\t{\n\t\t\tWeird(\"irc_invalid_squery_message_format\");\n\t\t\treturn;\n\t\t\t}\n\n\t\tstring target = params.substr(0, pos);\n\t\tstring message = params.substr(pos + 1);\n\t\tSkipLeadingWhitespace(message);\n\t\tif ( message[0] == ':' )\n\t\t\tmessage = message.substr(1);\n\n\t\tval_list* vl = new val_list;\n\t\tvl->append(BuildConnVal());\n\t\tvl->append(new Val(orig, TYPE_BOOL));\n\t\tvl->append(new StringVal(prefix.c_str()));\n\t\tvl->append(new StringVal(target.c_str()));\n\t\tvl->append(new StringVal(message.c_str()));\n\n\t\tConnectionEvent(irc_squery_message, vl);\n\t\t}\n\n\telse if ( irc_user_message && command == \"USER\" )\n\t\t{\n\t\t// extract username and real name\n\t\tvector parts = SplitWords(params, ' ');\n\t\tval_list* vl = new val_list;\n\t\tvl->append(BuildConnVal());\n\t\tvl->append(new Val(orig, TYPE_BOOL));\n\n\t\tif ( parts.size() > 0 )\n\t\t\tvl->append(new StringVal(parts[0].c_str()));\n\t\telse vl->append(new StringVal(\"\"));\n\n\t\tif ( parts.size() > 1 )\n\t\t\tvl->append(new StringVal(parts[1].c_str()));\n\t\telse vl->append(new StringVal(\"\"));\n\n\t\tif ( parts.size() > 2 )\n\t\t\tvl->append(new StringVal(parts[2].c_str()));\n\t\telse vl->append(new StringVal(\"\"));\n\n\t\tstring realname;\n\t\tfor ( unsigned int i = 3; i < parts.size(); i++ )\n\t\t\t{\n\t\t\trealname += parts[i];\n\t\t\tif ( i > 3 )\n\t\t\t\trealname += \" \";\n\t\t\t}\n\n\t\tconst char* name = realname.c_str();\n\t\tvl->append(new StringVal(*name == ':' ? name + 1 : name));\n\n\t\tConnectionEvent(irc_user_message, vl);\n\t\t}\n\n\telse if ( irc_oper_message && command == \"OPER\" )\n\t\t{\n\t\t// extract username and password\n\t\tvector parts = SplitWords(params, ' ');\n\t\tif ( parts.size() == 2 )\n\t\t\t{\n\t\t\tval_list* vl = new val_list;\n\t\t\tvl->append(BuildConnVal());\n\t\t\tvl->append(new Val(orig, TYPE_BOOL));\n\t\t\tvl->append(new StringVal(parts[0].c_str()));\n\t\t\tvl->append(new StringVal(parts[1].c_str()));\n\n\t\t\tConnectionEvent(irc_oper_message, vl);\n\t\t\t}\n\n\t\telse\n\t\t\tWeird(\"irc_invalid_oper_message_format\");\n\t\t}\n\n\telse if ( irc_kick_message && command == \"KICK\" )\n\t\t{\n\t\t// Extract channels, users and comment.\n\t\tvector parts = SplitWords(params, ' ');\n\t\tif ( parts.size() <= 1 )\n\t\t\t{\n\t\t\tWeird(\"irc_invalid_kick_message_format\");\n\t\t\treturn;\n\t\t\t}\n\n\t\tval_list* vl = new val_list;\n\t\tvl->append(BuildConnVal());\n\t\tvl->append(new Val(orig, TYPE_BOOL));\n\t\tvl->append(new StringVal(prefix.c_str()));\n\t\tvl->append(new StringVal(parts[0].c_str()));\n\t\tvl->append(new StringVal(parts[1].c_str()));\n\t\tif ( parts.size() > 2 )\n\t\t\t{\n\t\t\tstring comment = parts[2];\n\t\t\tfor ( unsigned int i = 3; i < parts.size(); ++i )\n\t\t\t\tcomment += \" \" + parts[i];\n\n\t\t\tif ( comment[0] == ':' )\n\t\t\t\tcomment = comment.substr(1);\n\n\t\t\tvl->append(new StringVal(comment.c_str()));\n\t\t\t}\n\t\telse\n\t\t\tvl->append(new StringVal(\"\"));\n\n\t\tConnectionEvent(irc_kick_message, vl);\n\t\t}\n\n\telse if ( irc_join_message && command == \"JOIN\" )\n\t\t{\n\t\tif ( params[0] == ':' )\n\t\t\tparams = params.substr(1);\n\n\t\tvector parts = SplitWords(params, ' ');\n\n\t\tif ( parts.size() < 1 )\n\t\t\t{\n\t\t\tWeird(\"irc_invalid_join_line\");\n\t\t\treturn;\n\t\t\t}\n\n\t\tstring nickname = \"\";\n\t\tif ( prefix.size() > 0 )\n\t\t\t{\n\t\t\tunsigned int pos = prefix.find('!');\n\t\t\tif ( pos < prefix.size() )\n\t\t\t\tnickname = prefix.substr(0, pos);\n\t\t\t}\n\n\t\tval_list* vl = new val_list;\n\t\tvl->append(BuildConnVal());\n\t\tvl->append(new Val(orig, TYPE_BOOL));\n\n\t\tTableVal* list = new TableVal(irc_join_list);\n\t\tvector channels = SplitWords(parts[0], ',');\n\t\tvector passwords;\n\n\t\tif ( parts.size() > 1 )\n\t\t\tpasswords = SplitWords(parts[1], ',');\n\n\t\tstring empty_string = \"\";\n\t\tfor ( unsigned int i = 0; i < channels.size(); ++i )\n\t\t\t{\n\t\t\tRecordVal* info = new RecordVal(irc_join_info);\n\t\t\tinfo->Assign(0, new StringVal(nickname.c_str()));\n\t\t\tinfo->Assign(1, new StringVal(channels[i].c_str()));\n\t\t\tif ( i < passwords.size() )\n\t\t\t\tinfo->Assign(2, new StringVal(passwords[i].c_str()));\n\t\t\telse\n\t\t\t\tinfo->Assign(2, new StringVal(empty_string.c_str()));\n\t\t\t// User mode.\n\t\t\tinfo->Assign(3, new StringVal(empty_string.c_str()));\n\t\t\tlist->Assign(info, 0);\n\t\t\tUnref(info);\n\t\t\t}\n\n\t\tvl->append(list);\n\n\t\tConnectionEvent(irc_join_message, vl);\n\t\t}\n\n\telse if ( irc_join_message && command == \"NJOIN\" )\n\t\t{\n\t\tvector parts = SplitWords(params, ' ');\n\t\tif ( parts.size() != 2 )\n\t\t\t{\n\t\t\tWeird(\"irc_invalid_njoin_line\");\n\t\t\treturn;\n\t\t\t}\n\n\t\tstring channel = parts[0];\n\t\tif ( parts[1][0] == ':' )\n\t\t\tparts[1] = parts[1].substr(1);\n\n\t\tvector users = SplitWords(parts[1], ',');\n\n\t\tval_list* vl = new val_list;\n\t\tvl->append(BuildConnVal());\n\t\tvl->append(new Val(orig, TYPE_BOOL));\n\n\t\tTableVal* list = new TableVal(irc_join_list);\n\t\tstring empty_string = \"\";\n\n\t\tfor ( unsigned int i = 0; i < users.size(); ++i )\n\t\t\t{\n\t\t\tRecordVal* info = new RecordVal(irc_join_info);\n\t\t\tstring nick = users[i];\n\t\t\tstring mode = \"none\";\n\n\t\t\tif ( nick[0] == '@' )\n\t\t\t\t{\n\t\t\t\tif ( nick[1] == '@' )\n\t\t\t\t\t{\n\t\t\t\t\tnick = nick.substr(2);\n\t\t\t\t\tmode = \"creator\";\n\t\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\tnick = nick.substr(1);\n\t\t\t\t\tmode = \"operator\";\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\telse if ( nick[0] == '+' )\n\t\t\t\t{\n\t\t\t\tnick = nick.substr(1);\n\t\t\t\tmode = \"voice\";\n\t\t\t\t}\n\n\t\t\tinfo->Assign(0, new StringVal(nick.c_str()));\n\t\t\tinfo->Assign(1, new StringVal(channel.c_str()));\n\t\t\t// Password:\n\t\t\tinfo->Assign(2, new StringVal(empty_string.c_str()));\n\t\t\t// User mode:\n\t\t\tinfo->Assign(3, new StringVal(mode.c_str()));\n\t\t\tlist->Assign(info, 0);\n\t\t\tUnref(info);\n\t\t\t}\n\n\t\tvl->append(list);\n\n\t\tConnectionEvent(irc_join_message, vl);\n\t\t}\n\n\telse if ( irc_part_message && command == \"PART\" )\n\t\t{\n\t\tstring channels = params;\n\t\tstring message = \"\";\n\t\tunsigned int pos = params.find(' ');\n\n\t\tif ( pos < params.size() )\n\t\t\t{\n\t\t\tchannels = params.substr(0, pos);\n\t\t\tif ( params.size() > pos + 1 )\n\t\t\t\t{\n\t\t\t\tmessage = params.substr(pos + 1);\n\t\t\t\tSkipLeadingWhitespace(message);\n\t\t\t\t}\n\t\t\tif ( message[0] == ':' )\n\t\t\t\tmessage = message.substr(1);\n\t\t\t}\n\n\t\tstring nick = prefix;\n\t\tpos = nick.find('!');\n\t\tif ( pos < nick.size() )\n\t\t\tnick = nick.substr(0, pos);\n\n\t\tvector channelList = SplitWords(channels, ',');\n\t\tTableVal* set = new TableVal(string_set);\n\n\t\tfor ( unsigned int i = 0; i < channelList.size(); ++i )\n\t\t\t{\n\t\t\tVal* idx = new StringVal(channelList[i].c_str());\n\t\t\tset->Assign(idx, 0);\n\t\t\tUnref(idx);\n\t\t\t}\n\n\t\tval_list* vl = new val_list;\n\t\tvl->append(BuildConnVal());\n\t\tvl->append(new Val(orig, TYPE_BOOL));\n\t\tvl->append(new StringVal(nick.c_str()));\n\t\tvl->append(set);\n\t\tvl->append(new StringVal(message.c_str()));\n\n\t\tConnectionEvent(irc_part_message, vl);\n\t\t}\n\n\telse if ( irc_quit_message && command == \"QUIT\" )\n\t\t{\n\t\tstring message = params;\n\t\tif ( message[0] == ':' )\n\t\t\tmessage = message.substr(1);\n\n\t\tstring nickname = \"\";\n\t\tif ( prefix.size() > 0 )\n\t\t\t{\n\t\t\tunsigned int pos = prefix.find('!');\n\t\t\tif ( pos < prefix.size() )\n\t\t\t\tnickname = prefix.substr(0, pos);\n\t\t\t}\n\n\t\tval_list* vl = new val_list;\n\t\tvl->append(BuildConnVal());\n\t\tvl->append(new Val(orig, TYPE_BOOL));\n\t\tvl->append(new StringVal(nickname.c_str()));\n\t\tvl->append(new StringVal(message.c_str()));\n\n\t\tConnectionEvent(irc_quit_message, vl);\n\t\t}\n\n\telse if ( irc_nick_message && command == \"NICK\" )\n\t\t{\n\t\tstring nick = params;\n\t\tif ( nick[0] == ':' )\n\t\t\tnick = nick.substr(1);\n\n\t\tval_list* vl = new val_list;\n\t\tvl->append(BuildConnVal());\n\t\tvl->append(new Val(orig, TYPE_BOOL));\n\t\tvl->append(new StringVal(prefix.c_str()));\n\t\tvl->append(new StringVal(nick.c_str()));\n\n\t\tConnectionEvent(irc_nick_message, vl);\n\t\t}\n\n\telse if ( irc_who_message && command == \"WHO\" )\n\t\t{\n\t\tvector parts = SplitWords(params, ' ');\n\t\tif ( parts.size() > 2 )\n\t\t\t{\n\t\t\tWeird(\"irc_invalid_who_message_format\");\n\t\t\treturn;\n\t\t\t}\n\n\t\tbool oper = false;\n\t\tif ( parts.size() == 2 && parts[1] == \"o\" )\n\t\t\toper = true;\n\n\t\t// Remove \":\" from mask.\n\t\tif ( parts.size() > 0 && parts[0].size() > 0 && parts[0][0] == ':' )\n\t\t\tparts[0] = parts[0].substr(1);\n\n\t\tval_list* vl = new val_list;\n\t\tvl->append(BuildConnVal());\n\t\tvl->append(new Val(orig, TYPE_BOOL));\n\t\tif ( parts.size() > 0 )\n\t\t\tvl->append(new StringVal(parts[0].c_str()));\n\t\telse\n\t\t\tvl->append(new StringVal(\"\"));\n\t\tvl->append(new Val(oper, TYPE_BOOL));\n\n\t\tConnectionEvent(irc_who_message, vl);\n\t\t}\n\n\telse if ( irc_whois_message && command == \"WHOIS\" )\n\t\t{\n\t\tvector parts = SplitWords(params, ' ');\n\t\tif ( parts.size() < 1 || parts.size() > 2 )\n\t\t\t{\n\t\t\tWeird(\"irc_invalid_whois_message_format\");\n\t\t\treturn;\n\t\t\t}\n\n\t\tstring server = \"\";\n\t\tstring users = \"\";\n\n\t\tif ( parts.size() == 2 )\n\t\t\t{\n\t\t\tserver = parts[0];\n\t\t\tusers = parts[1];\n\t\t\t}\n\t\telse\n\t\t\tusers = parts[0];\n\n\t\tval_list* vl = new val_list;\n\t\tvl->append(BuildConnVal());\n\t\tvl->append(new Val(orig, TYPE_BOOL));\n\t\tvl->append(new StringVal(server.c_str()));\n\t\tvl->append(new StringVal(users.c_str()));\n\n\t\tConnectionEvent(irc_whois_message, vl);\n\t\t}\n\n\telse if ( irc_error_message && command == \"ERROR\" )\n\t\t{\n\t\tval_list* vl = new val_list;\n\t\tvl->append(BuildConnVal());\n\t\tvl->append(new Val(orig, TYPE_BOOL));\n\t\tvl->append(new StringVal(prefix.c_str()));\n\t\tif ( params[0] == ':' )\n\t\t\tparams = params.substr(1);\n\t\tvl->append(new StringVal(params.c_str()));\n\n\t\tConnectionEvent(irc_error_message, vl);\n\t\t}\n\n\telse if ( irc_invite_message && command == \"INVITE\" )\n\t\t{\n\t\tvector parts = SplitWords(params, ' ');\n\t\tif ( parts.size() == 2 )\n\t\t\t{ // remove \":\" from channel\n\t\t\tif ( parts[1].size() > 0 && parts[1][0] == ':' )\n\t\t\t\tparts[1] = parts[1].substr(1);\n\n\t\t\tval_list* vl = new val_list;\n\t\t\tvl->append(BuildConnVal());\n\t\t\tvl->append(new Val(orig, TYPE_BOOL));\n\t\t\tvl->append(new StringVal(prefix.c_str()));\n\t\t\tvl->append(new StringVal(parts[0].c_str()));\n\t\t\tvl->append(new StringVal(parts[1].c_str()));\n\n\t\t\tConnectionEvent(irc_invite_message, vl);\n\t\t\t}\n\t\telse\n\t\t\tWeird(\"irc_invalid_invite_message_format\");\n\t\t}\n\n\telse if ( irc_mode_message && command == \"MODE\" )\n\t\t{\n\t\tif ( params.size() > 0 )\n\t\t\t{\n\t\t\tval_list* vl = new val_list;\n\t\t\tvl->append(BuildConnVal());\n\t\t\tvl->append(new Val(orig, TYPE_BOOL));\n\t\t\tvl->append(new StringVal(prefix.c_str()));\n\t\t\tvl->append(new StringVal(params.c_str()));\n\n\t\t\tConnectionEvent(irc_mode_message, vl);\n\t\t\t}\n\n\t\telse\n\t\t\tWeird(\"irc_invalid_mode_message_format\");\n\t\t}\n\n\telse if ( irc_password_message && command == \"PASS\" )\n\t\t{\n\t\tval_list* vl = new val_list;\n\t\tvl->append(BuildConnVal());\n\t\tvl->append(new Val(orig, TYPE_BOOL));\n\t\tvl->append(new StringVal(params.c_str()));\n\t\tConnectionEvent(irc_password_message, vl);\n\t\t}\n\n\telse if ( irc_squit_message && command == \"SQUIT\" )\n\t\t{\n\t\tstring server = params;\n\t\tstring message = \"\";\n\n\t\tunsigned int pos = params.find(' ');\n\t\tif ( pos < params.size() )\n\t\t\t{\n\t\t\tserver = params.substr(0, pos);\n\t\t\tmessage = params.substr(pos + 1);\n\t\t\tSkipLeadingWhitespace(message);\n\t\t\tif ( message[0] == ':' )\n\t\t\t\tmessage = message.substr(1);\n\t\t\t}\n\n\t\tval_list* vl = new val_list;\n\t\tvl->append(BuildConnVal());\n\t\tvl->append(new Val(orig, TYPE_BOOL));\n\t\tvl->append(new StringVal(prefix.c_str()));\n\t\tvl->append(new StringVal(server.c_str()));\n\t\tvl->append(new StringVal(message.c_str()));\n\n\t\tConnectionEvent(irc_squit_message, vl);\n\t\t}\n\n\n\telse if ( orig )\n\t\t{\n\t\tif ( irc_request )\n\t\t\t{\n\t\t\tval_list* vl = new val_list;\n\t\t\tvl->append(BuildConnVal());\n\t\t\tvl->append(new Val(orig, TYPE_BOOL));\n\t\t\tvl->append(new StringVal(prefix.c_str()));\n\t\t\tvl->append(new StringVal(command.c_str()));\n\t\t\tvl->append(new StringVal(params.c_str()));\n\n\t\t\tConnectionEvent(irc_request, vl);\n\t\t\t}\n\t\t}\n\n\telse\n\t\t{\n\t\tif ( irc_message )\n\t\t\t{\n\t\t\tval_list* vl = new val_list;\n\t\t\tvl->append(BuildConnVal());\n\t\t\tvl->append(new Val(orig, TYPE_BOOL));\n\t\t\tvl->append(new StringVal(prefix.c_str()));\n\t\t\tvl->append(new StringVal(command.c_str()));\n\t\t\tvl->append(new StringVal(params.c_str()));\n\n\t\t\tConnectionEvent(irc_message, vl);\n\t\t\t}\n\t\t}\n\n\tif ( orig_status == REGISTERED && resp_status == REGISTERED &&\n\t orig_zip_status == ACCEPT_ZIP && resp_zip_status == ACCEPT_ZIP )\n\t\t{\n\t\torig_zip_status = ZIP_LOADED;\n\t\tresp_zip_status = ZIP_LOADED;\n\t\tAddSupportAnalyzer(new zip::ZIP_Analyzer(Conn(), true));\n\t\tAddSupportAnalyzer(new zip::ZIP_Analyzer(Conn(), false));\n\t\t}\n\n\treturn;\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fix IRC names command parsing'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void WavOutFile::write(const float *buffer, int numElems)\r\n{\r\n int numBytes;\r\n int bytesPerSample;\r\n\r\n if (numElems == 0) return;\r\n\r\n bytesPerSample = header.format.bits_per_sample / 8;\r\n numBytes = numElems * bytesPerSample;\r\n int confBufBytes = (numBytes + 3) & -4; // round up to nearest multiple of four to avoid overflow with 24bit-value assignment\r\n void *temp = getConvBuffer(confBufBytes);\r\n\r\n switch (bytesPerSample)\r\n {\r\n case 1:\r\n {\r\n unsigned char *temp2 = (unsigned char *)temp;\r\n for (int i = 0; i < numElems; i ++)\r\n {\r\n temp2[i] = (unsigned char)saturate(buffer[i] * 128.0f + 128.0f, 0.0f, 255.0f);\r\n }\r\n break;\r\n }\r\n\r\n case 2:\r\n {\r\n short *temp2 = (short *)temp;\r\n for (int i = 0; i < numElems; i ++)\r\n {\r\n short value = (short)saturate(buffer[i] * 32768.0f, -32768.0f, 32767.0f);\r\n temp2[i] = _swap16(value);\r\n }\r\n break;\r\n }\r\n\r\n case 3:\r\n {\r\n char *temp2 = (char *)temp;\r\n for (int i = 0; i < numElems; i ++)\r\n {\r\n int value = saturate(buffer[i] * 8388608.0f, -8388608.0f, 8388607.0f);\r\n *((int*)temp2) = _swap32(value);\r\n temp2 += 3;\r\n }\r\n break;\r\n }\r\n\r\n case 4:\r\n {\r\n int *temp2 = (int *)temp;\r\n for (int i = 0; i < numElems; i ++)\r\n {\r\n int value = saturate(buffer[i] * 2147483648.0f, -2147483648.0f, 2147483647.0f);\r\n temp2[i] = _swap32(value);\r\n }\r\n break;\r\n }\r\n\r\n default:\r\n assert(false);\r\n }\r\n\r\n int res = (int)fwrite(temp, 1, numBytes, fptr);\r\n\r\n if (res != numBytes) \r\n {\r\n ST_THROW_RT_ERROR(\"Error while writing to a wav file.\");\r\n }\r\n bytesWritten += numBytes;\r\n}\r ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'New take on CVE-2018-17097 i.e. avoiding writing beyond end of buffer in case of 24-bit samples'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ovl_permission(struct inode *inode, int mask)\n{\n\tstruct ovl_entry *oe = inode->i_private;\n\tbool is_upper;\n\tstruct dentry *realdentry = ovl_entry_real(oe, &is_upper);\n\tstruct inode *realinode;\n\tint err;\n\n\tif (ovl_is_default_permissions(inode)) {\n\t\tstruct kstat stat;\n\t\tstruct path realpath = { .dentry = realdentry };\n\n\t\tif (mask & MAY_NOT_BLOCK)\n\t\t\treturn -ECHILD;\n\n\t\trealpath.mnt = ovl_entry_mnt_real(oe, inode, is_upper);\n\n\t\terr = vfs_getattr(&realpath, &stat);\n\t\tif (err)\n\t\t\treturn err;\n\n\t\tif ((stat.mode ^ inode->i_mode) & S_IFMT)\n\t\t\treturn -ESTALE;\n\n\t\tinode->i_mode = stat.mode;\n\t\tinode->i_uid = stat.uid;\n\t\tinode->i_gid = stat.gid;\n\n\t\treturn generic_permission(inode, mask);\n\t}\n\n\t/* Careful in RCU walk mode */\n\trealinode = d_inode_rcu(realdentry);\n\tif (!realinode) {\n\t\tWARN_ON(!(mask & MAY_NOT_BLOCK));\n\t\treturn -ENOENT;\n\t}\n\n\tif (mask & MAY_WRITE) {\n\t\tumode_t mode = realinode->i_mode;\n\n\t\t/*\n\t\t * Writes will always be redirected to upper layer, so\n\t\t * ignore lower layer being read-only.\n\t\t *\n\t\t * If the overlay itself is read-only then proceed\n\t\t * with the permission check, don't return EROFS.\n\t\t * This will only happen if this is the lower layer of\n\t\t * another overlayfs.\n\t\t *\n\t\t * If upper fs becomes read-only after the overlay was\n\t\t * constructed return EROFS to prevent modification of\n\t\t * upper layer.\n\t\t */\n\t\tif (is_upper && !IS_RDONLY(inode) && IS_RDONLY(realinode) &&\n\t\t (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode)))\n\t\t\treturn -EROFS;\n\t}\n\n\treturn __inode_permission(realinode, mask);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-863'], 'message': 'ovl: modify ovl_permission() to do checks on two inodes\n\nRight now ovl_permission() calls __inode_permission(realinode), to do\npermission checks on real inode and no checks are done on overlay inode.\n\nModify it to do checks both on overlay inode as well as underlying inode.\nChecks on overlay inode will be done with the creds of calling task while\nchecks on underlying inode will be done with the creds of mounter.\n\nSigned-off-by: Vivek Goyal \nSigned-off-by: Miklos Szeredi '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: matchCurrentInput(\n\t\tconst InString *input, int pos, const widechar *passInstructions, int passIC) {\n\tint k;\n\tint kk = pos;\n\tfor (k = passIC + 2; k < passIC + 2 + passInstructions[passIC + 1]; k++)\n\t\tif (input->chars[kk] == ENDSEGMENT || passInstructions[k] != input->chars[kk++])\n\t\t\treturn 0;\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix a buffer overflow\n\nFixes #635\n\nThanks to HongxuChen for reporting it'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int clone_submodule(const char *path, const char *gitdir, const char *url,\n\t\t\t const char *depth, struct string_list *reference,\n\t\t\t int quiet, int progress)\n{\n\tstruct child_process cp = CHILD_PROCESS_INIT;\n\n\targv_array_push(&cp.args, \"clone\");\n\targv_array_push(&cp.args, \"--no-checkout\");\n\tif (quiet)\n\t\targv_array_push(&cp.args, \"--quiet\");\n\tif (progress)\n\t\targv_array_push(&cp.args, \"--progress\");\n\tif (depth && *depth)\n\t\targv_array_pushl(&cp.args, \"--depth\", depth, NULL);\n\tif (reference->nr) {\n\t\tstruct string_list_item *item;\n\t\tfor_each_string_list_item(item, reference)\n\t\t\targv_array_pushl(&cp.args, \"--reference\",\n\t\t\t\t\t item->string, NULL);\n\t}\n\tif (gitdir && *gitdir)\n\t\targv_array_pushl(&cp.args, \"--separate-git-dir\", gitdir, NULL);\n\n\targv_array_push(&cp.args, url);\n\targv_array_push(&cp.args, path);\n\n\tcp.git_cmd = 1;\n\tprepare_submodule_repo_env(&cp.env_array);\n\tcp.no_stdin = 1;\n\n\treturn run_command(&cp);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-88'], 'message': 'submodule--helper: use \"--\" to signal end of clone options\n\nWhen we clone a submodule, we call \"git clone $url $path\".\nBut there's nothing to say that those components can't begin\nwith a dash themselves, confusing git-clone into thinking\nthey're options. Let's pass \"--\" to make it clear what we\nexpect.\n\nThere's no test here, because it's actually quite hard to\nmake these names work, even with \"git clone\" parsing them\ncorrectly. And we're going to restrict these cases even\nfurther in future commits. So we'll leave off testing until\nthen; this is just the minimal fix to prevent us from doing\nsomething stupid with a badly formed entry.\n\nReported-by: joernchen \nSigned-off-by: Jeff King \nSigned-off-by: Junio C Hamano '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: mon_rwxa_t MonCapGrant::get_allowed(CephContext *cct,\n\t\t\t\t int daemon_type,\n\t\t\t\t EntityName name,\n\t\t\t\t const std::string& s, const std::string& c,\n\t\t\t\t const map& c_args) const\n{\n if (profile.length()) {\n expand_profile(daemon_type, name);\n mon_rwxa_t a;\n for (list::const_iterator p = profile_grants.begin();\n\t p != profile_grants.end(); ++p)\n a = a | p->get_allowed(cct, daemon_type, name, s, c, c_args);\n return a;\n }\n if (service.length()) {\n if (service != s)\n return 0;\n return allow;\n }\n if (command.length()) {\n if (command != c)\n return 0;\n for (map::const_iterator p = command_args.begin(); p != command_args.end(); ++p) {\n map::const_iterator q = c_args.find(p->first);\n // argument must be present if a constraint exists\n if (q == c_args.end())\n\treturn 0;\n switch (p->second.match_type) {\n case StringConstraint::MATCH_TYPE_EQUAL:\n\tif (p->second.value != q->second)\n\t return 0;\n break;\n case StringConstraint::MATCH_TYPE_PREFIX:\n\tif (q->second.find(p->second.value) != 0)\n\t return 0;\n break;\n case StringConstraint::MATCH_TYPE_REGEX:\n try {\n\t std::regex pattern(\n p->second.value, std::regex::extended);\n if (!std::regex_match(q->second, pattern))\n\t return 0;\n } catch(const std::regex_error&) {\n\t return 0;\n\t}\n break;\n default:\n break;\n }\n }\n return MON_CAP_ALL;\n }\n return allow;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-285'], 'message': 'mon/config-key: limit caps allowed to access the store\n\nHenceforth, we'll require explicit `allow` caps for commands, or for the\nconfig-key service. Blanket caps are no longer allowed for the\nconfig-key service, except for 'allow *'.\n\n(for luminous and mimic, we're also ensuring MonCap's parser is able to\nunderstand forward slashes '/' when parsing prefixes)\n\nSigned-off-by: Joao Eduardo Luis \n(cherry picked from commit 5fff611041c5afeaf3c8eb09e4de0cc919d69237)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static bool manager_check_idle(void *userdata) {\n Manager *m = userdata;\n Link *link;\n Iterator i;\n\n assert(m);\n\n HASHMAP_FOREACH(link, m->links, i) {\n /* we are not woken on udev activity, so let's just wait for the\n * pending udev event */\n if (link->state == LINK_STATE_PENDING)\n return false;\n\n if (!link->network)\n continue;\n\n /* we are not woken on netork activity, so let's stay around */\n if (link_lldp_enabled(link) ||\n link_ipv4ll_enabled(link) ||\n link_dhcp4_server_enabled(link) ||\n link_dhcp4_enabled(link) ||\n link_dhcp6_enabled(link))\n return false;\n }\n\n return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'networkd: IPv6 router discovery - follow IPv6AcceptRouterAdvertisemnt=\n\nThe previous behavior:\nWhen DHCPv6 was enabled, router discover was performed first, and then DHCPv6 was\nenabled only if the relevant flags were passed in the Router Advertisement message.\nMoreover, router discovery was performed even if AcceptRouterAdvertisements=false,\nmoreover, even if router advertisements were accepted (by the kernel) the flags\nindicating that DHCPv6 should be performed were ignored.\n\nNew behavior:\nIf RouterAdvertisements are accepted, and either no routers are found, or an\nadvertisement is received indicating DHCPv6 should be performed, the DHCPv6\nclient is started. Moreover, the DHCP option now truly enables the DHCPv6\nclient regardless of router discovery (though it will probably not be\nvery useful to get a lease withotu any routes, this seems the more consistent\napproach).\n\nThe recommended default setting should be to set DHCP=ipv4 and to leave\nIPv6AcceptRouterAdvertisements unset.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: execstack2_continue(i_ctx_t *i_ctx_p)\n{\n os_ptr op = osp;\n\n return do_execstack(i_ctx_p, op->value.boolval, op - 1);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Bug 699927: don't include operator arrays in execstack output\n\nWhen we transfer the contents of the execution stack into the array, take the\nextra step of replacing any operator arrays on the stack with the operator\nthat reference them.\n\nThis prevents the contents of Postscript defined, internal only operators (those\ncreated with .makeoperator) being exposed via execstack (and thus, via error\nhandling).\n\nThis necessitates a change in the resource remapping 'resource', which contains\na procedure which relies on the contents of the operators arrays being present.\nAs we already had internal-only variants of countexecstack and execstack\n(.countexecstack and .execstack) - using those, and leaving thier operation\nincluding the operator arrays means the procedure continues to work correctly.\n\nBoth .countexecstack and .execstack are undefined after initialization.\n\nAlso, when we store the execstack (or part thereof) for an execstackoverflow\nerror, make the same oparray/operator substitution as above for execstack.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void voutf(struct GlobalConfig *config,\n const char *prefix,\n const char *fmt,\n va_list ap)\n{\n size_t width = (79 - strlen(prefix));\n if(!config->mute) {\n size_t len;\n char *ptr;\n char print_buffer[256];\n\n len = vsnprintf(print_buffer, sizeof(print_buffer), fmt, ap);\n\n ptr = print_buffer;\n while(len > 0) {\n fputs(prefix, config->errors);\n\n if(len > width) {\n size_t cut = width-1;\n\n while(!ISSPACE(ptr[cut]) && cut) {\n cut--;\n }\n if(0 == cut)\n /* not a single cutting position was found, just cut it at the\n max text width then! */\n cut = width-1;\n\n (void)fwrite(ptr, cut + 1, 1, config->errors);\n fputs(\"\\n\", config->errors);\n ptr += cut + 1; /* skip the space too */\n len -= cut;\n }\n else {\n fputs(ptr, config->errors);\n len = 0;\n }\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'curl: support >256 bytes warning messsages\n\nBug: #2174'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int RGWListBucketMultiparts_ObjStore::get_params()\n{\n delimiter = s->info.args.get(\"delimiter\");\n prefix = s->info.args.get(\"prefix\");\n string str = s->info.args.get(\"max-uploads\");\n op_ret = parse_value_and_bound(str, &max_uploads, 0, g_conf()->rgw_max_listing_results, default_max);\n if (op_ret < 0) {\n return op_ret;\n }\n\n string key_marker = s->info.args.get(\"key-marker\");\n string upload_id_marker = s->info.args.get(\"upload-id-marker\");\n if (!key_marker.empty())\n marker.init(key_marker, upload_id_marker);\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-770'], 'message': 'rgw: fix issues with 'enforce bounds' patch\n\nThe patch to enforce bounds on max-keys/max-uploads/max-parts had a few\nissues that would prevent us from compiling it. Instead of changing the\ncode provided by the submitter, we're addressing them in a separate\ncommit to maintain the DCO.\n\nSigned-off-by: Joao Eduardo Luis \nSigned-off-by: Abhishek Lekshmanan \n(cherry picked from commit 29bc434a6a81a2e5c5b8cfc4c8d5c82ca5bf538a)\nmimic specific fixes:\nAs the largeish change from master g_conf() isn't in mimic yet, use the g_conf\nglobal structure, also make rgw_op use the value from req_info ceph context as\nwe do for all the requests'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int ras_putdatastd(jas_stream_t *out, ras_hdr_t *hdr, jas_image_t *image, int numcmpts, int *cmpts)\n{\n\tint rowsize;\n\tint pad;\n\tunsigned int z;\n\tint nz;\n\tint c;\n\tint x;\n\tint y;\n\tint v;\n\tjas_matrix_t *data[3];\n\tint i;\n\n\tassert(numcmpts <= 3);\n\n\tfor (i = 0; i < 3; ++i) {\n\t\tdata[i] = 0;\n\t}\n\n\tfor (i = 0; i < numcmpts; ++i) {\n\t\tif (!(data[i] = jas_matrix_create(jas_image_height(image),\n\t\t jas_image_width(image)))) {\n\t\t\tgoto error;\n\t\t}\n\t}\n\n\trowsize = RAS_ROWSIZE(hdr);\n\tpad = rowsize - (hdr->width * hdr->depth + 7) / 8;\n\n\thdr->length = hdr->height * rowsize;\n\n\tfor (y = 0; y < hdr->height; y++) {\n\t\tfor (i = 0; i < numcmpts; ++i) {\n\t\t\tif (jas_image_readcmpt(image, cmpts[i], 0, y,\n\t\t\t\t\tjas_image_width(image), 1, data[i])) {\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t}\n\t\tz = 0;\n\t\tnz = 0;\n\t\tfor (x = 0; x < hdr->width; x++) {\n\t\t\tz <<= hdr->depth;\n\t\t\tif (RAS_ISRGB(hdr)) {\n\t\t\t\tv = RAS_RED((jas_matrix_getv(data[0], x))) |\n\t\t\t\t RAS_GREEN((jas_matrix_getv(data[1], x))) |\n\t\t\t\t RAS_BLUE((jas_matrix_getv(data[2], x)));\n\t\t\t} else {\n\t\t\t\tv = (jas_matrix_getv(data[0], x));\n\t\t\t}\n\t\t\tz |= v & RAS_ONES(hdr->depth);\n\t\t\tnz += hdr->depth;\n\t\t\twhile (nz >= 8) {\n\t\t\t\tc = (z >> (nz - 8)) & 0xff;\n\t\t\t\tif (jas_stream_putc(out, c) == EOF) {\n\t\t\t\t\tgoto error;\n\t\t\t\t}\n\t\t\t\tnz -= 8;\n\t\t\t\tz &= RAS_ONES(nz);\n\t\t\t}\n\t\t}\n\t\tif (nz > 0) {\n\t\t\tc = (z >> (8 - nz)) & RAS_ONES(nz);\n\t\t\tif (jas_stream_putc(out, c) == EOF) {\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t}\n\t\tif (pad % 2) {\n\t\t\tif (jas_stream_putc(out, 0) == EOF) {\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (i = 0; i < numcmpts; ++i) {\n\t\tjas_matrix_destroy(data[i]);\n\t\tdata[i] = 0;\n\t}\n\n\treturn 0;\n\nerror:\n\tfor (i = 0; i < numcmpts; ++i) {\n\t\tif (data[i]) {\n\t\t\tjas_matrix_destroy(data[i]);\n\t\t}\n\t}\n\treturn -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'ras_enc: check components for RGB, fixes NULL pointer dereference\n\nFixes CVE-2018-18873\n\nCloses https://github.com/jasper-maint/jasper/issues/15\nCloses https://github.com/mdadams/jasper/issues/184'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: Perl_my_setenv(pTHX_ const char *nam, const char *val)\n{\n dVAR;\n#ifdef __amigaos4__\n amigaos4_obtain_environ(__FUNCTION__);\n#endif\n#ifdef USE_ITHREADS\n /* only parent thread can modify process environment */\n if (PL_curinterp == aTHX)\n#endif\n {\n#ifndef PERL_USE_SAFE_PUTENV\n if (!PL_use_safe_putenv) {\n /* most putenv()s leak, so we manipulate environ directly */\n I32 i;\n const I32 len = strlen(nam);\n int nlen, vlen;\n\n /* where does it go? */\n for (i = 0; environ[i]; i++) {\n if (strnEQ(environ[i],nam,len) && environ[i][len] == '=')\n break;\n }\n\n if (environ == PL_origenviron) { /* need we copy environment? */\n I32 j;\n I32 max;\n char **tmpenv;\n\n max = i;\n while (environ[max])\n max++;\n tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));\n for (j=0; j \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-703', 'CWE-787'], 'message': 'Perl_my_setenv(); handle integer wrap\n\nRT #133204\n\nWean this function off int/I32 and onto UV/Size_t.\nAlso, replace all malloc-ish calls with a wrapper that does\noverflow checks,\n\nIn particular, it was doing (nlen + vlen + 2) which could wrap when\nthe combined length of the environment variable name and value\nexceeded around 0x7fffffff.\n\nThe wrapper check function is probably overkill, but belt and braces...\n\nNB this function has several variant parts, #ifdef'ed by platform\ntype; I have blindly changed the parts that aren't compiled under linux.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: amstar_estimate(\n application_argument_t *argument)\n{\n GPtrArray *argv_ptr;\n char *cmd = NULL;\n int nullfd;\n int pipefd;\n FILE *dumpout = NULL;\n off_t size = -1;\n char line[32768];\n char *errmsg = NULL;\n char *qerrmsg;\n char *qdisk = NULL;\n amwait_t wait_status;\n int starpid;\n amregex_t *rp;\n times_t start_time;\n int level = 0;\n GSList *levels = NULL;\n\n if (!argument->level) {\n\tfprintf(stderr, \"ERROR No level argument\\n\");\n\terror(_(\"No level argument\"));\n }\n if (!argument->dle.disk) {\n\tfprintf(stderr, \"ERROR No disk argument\\n\");\n\terror(_(\"No disk argument\"));\n }\n if (!argument->dle.device) {\n\tfprintf(stderr, \"ERROR No device argument\\n\");\n\terror(_(\"No device argument\"));\n }\n\n if (argument->dle.include_list &&\n\targument->dle.include_list->nb_element >= 0) {\n\tfprintf(stderr, \"ERROR include-list not supported for backup\\n\");\n }\n\n if (check_device(argument) == 0) {\n\treturn;\n }\n\n if (argument->calcsize) {\n\tchar *dirname;\n\tchar *calcsize = g_strjoin(NULL, amlibexecdir, \"/\", \"calcsize\", NULL);\n\tif (!check_exec_for_suid(calcsize, FALSE)) {\n\t errmsg = g_strdup_printf(\"'%s' binary is not secure\", calcsize);\n\t goto common_error;\n\t return;\n\t}\n\n\tif (star_directory) {\n\t dirname = star_directory;\n\t} else {\n\t dirname = argument->dle.device;\n\t}\n\trun_calcsize(argument->config, \"STAR\", argument->dle.disk, dirname,\n\t\t argument->level, NULL, NULL);\n\treturn;\n }\n\n qdisk = quote_string(argument->dle.disk);\n if (!star_path) {\n\terrmsg = g_strdup(_(\"STAR-PATH not defined\"));\n\tgoto common_error;\n }\n if (!check_exec_for_suid(star_path, FALSE)) {\n\terrmsg = g_strdup_printf(\"'%s' binary is not secure\", star_path);\n\tgoto common_error;\n }\n cmd = g_strdup(star_path);\n\n start_time = curclock();\n\n qdisk = quote_string(argument->dle.disk);\n for (levels = argument->level; levels != NULL; levels = levels->next) {\n\tlevel = GPOINTER_TO_INT(levels->data);\n\targv_ptr = amstar_build_argv(argument, level, CMD_ESTIMATE, NULL);\n\n\tif ((nullfd = open(\"/dev/null\", O_RDWR)) == -1) {\n\t errmsg = g_strdup_printf(_(\"Cannot access /dev/null : %s\"),\n\t\t\t\tstrerror(errno));\n\t goto common_error;\n\t}\n\n\tstarpid = pipespawnv(cmd, STDERR_PIPE, 1,\n\t\t\t &nullfd, &nullfd, &pipefd,\n\t\t\t (char **)argv_ptr->pdata);\n\n\tdumpout = fdopen(pipefd,\"r\");\n\tif (!dumpout) {\n\t errmsg = g_strdup_printf(_(\"Can't fdopen: %s\"), strerror(errno));\n\t aclose(nullfd);\n\t goto common_error;\n\t}\n\n\tsize = (off_t)-1;\n\twhile (size < 0 && (fgets(line, sizeof(line), dumpout)) != NULL) {\n\t if (strlen(line) > 0 && line[strlen(line)-1] == '\\n') {\n\t\t/* remove trailling \\n */\n\t\tline[strlen(line)-1] = '\\0';\n\t }\n\t if (line[0] == '\\0')\n\t\tcontinue;\n\t dbprintf(\"%s\\n\", line);\n\t /* check for size match */\n\t /*@ignore@*/\n\t for(rp = re_table; rp->regex != NULL; rp++) {\n\t\tif(match(rp->regex, line)) {\n\t\t if (rp->typ == DMP_SIZE) {\n\t\t\tsize = ((the_num(line, rp->field)*rp->scale+1023.0)/1024.0);\n\t\t\tif(size < 0.0)\n\t\t\t size = 1.0; /* found on NeXT -- sigh */\n\t\t }\n\t\t break;\n\t\t}\n\t }\n\t /*@end@*/\n\t}\n\n\twhile ((fgets(line, sizeof(line), dumpout)) != NULL) {\n\t dbprintf(\"%s\", line);\n\t}\n\n\tdbprintf(\".....\\n\");\n\tdbprintf(_(\"estimate time for %s level %d: %s\\n\"),\n\t\t qdisk,\n\t\t level,\n\t\t walltime_str(timessub(curclock(), start_time)));\n\tif(size == (off_t)-1) {\n\t errmsg = g_strdup_printf(_(\"no size line match in %s output\"),\n\t\t\t\tcmd);\n\t dbprintf(_(\"%s for %s\\n\"), errmsg, qdisk);\n\t dbprintf(\".....\\n\");\n\t qerrmsg = quote_string(errmsg);\n\t fprintf(stdout, \"ERROR %s\\n\", qerrmsg);\n\t amfree(errmsg);\n\t amfree(qerrmsg);\n\t} else if(size == (off_t)0 && argument->level == 0) {\n\t dbprintf(_(\"possible %s problem -- is \\\"%s\\\" really empty?\\n\"),\n\t\t cmd, argument->dle.disk);\n\t dbprintf(\".....\\n\");\n\t}\n\tdbprintf(_(\"estimate size for %s level %d: %lld KB\\n\"),\n\t\t qdisk,\n\t\t level,\n\t\t (long long)size);\n\n\t(void)kill(-starpid, SIGTERM);\n\n\tdbprintf(_(\"waiting for %s \\\"%s\\\" child\\n\"), cmd, qdisk);\n\twaitpid(starpid, &wait_status, 0);\n\tif (WIFSIGNALED(wait_status)) {\n\t amfree(errmsg);\n\t errmsg = g_strdup_printf(_(\"%s terminated with signal %d: see %s\"),\n\t\t\t\tcmd, WTERMSIG(wait_status), dbfn());\n\t dbprintf(_(\"%s for %s\\n\"), errmsg, qdisk);\n\t dbprintf(\".....\\n\");\n\t qerrmsg = quote_string(errmsg);\n\t fprintf(stdout, \"ERROR %s\\n\", qerrmsg);\n\t amfree(errmsg);\n\t amfree(qerrmsg);\n\t} else if (WIFEXITED(wait_status)) {\n\t if (WEXITSTATUS(wait_status) != 0) {\n\t\tamfree(errmsg);\n\t\terrmsg = g_strdup_printf(_(\"%s exited with status %d: see %s\"),\n\t\t\t\t cmd, WEXITSTATUS(wait_status), dbfn());\n\t\tdbprintf(_(\"%s for %s\\n\"), errmsg, qdisk);\n\t\tdbprintf(\".....\\n\");\n\t\tqerrmsg = quote_string(errmsg);\n\t\tfprintf(stdout, \"ERROR %s\\n\", qerrmsg);\n\t\tamfree(errmsg);\n\t\tamfree(qerrmsg);\n\t } else {\n\t\t/* Normal exit */\n\t }\n\t} else {\n\t amfree(errmsg);\n\t errmsg = g_strdup_printf(_(\"%s got bad exit: see %s\"), cmd, dbfn());\n\t dbprintf(_(\"%s for %s\\n\"), errmsg, qdisk);\n\t dbprintf(\".....\\n\");\n\t qerrmsg = quote_string(errmsg);\n\t fprintf(stdout, \"ERROR %s\\n\", qerrmsg);\n\t amfree(errmsg);\n\t amfree(qerrmsg);\n\t}\n\tdbprintf(_(\"after %s %s wait\\n\"), cmd, qdisk);\n\n\tg_ptr_array_free_full(argv_ptr);\n\n\taclose(nullfd);\n\tafclose(dumpout);\n\n\tfprintf(stdout, \"%d %lld 1\\n\", level, (long long)size);\n }\n amfree(qdisk);\n amfree(cmd);\n return;\n\ncommon_error:\n dbprintf(\"%s\\n\", errmsg);\n qerrmsg = quote_string(errmsg);\n amfree(qdisk);\n dbprintf(\"%s\", errmsg);\n fprintf(stdout, \"ERROR %s\\n\", qerrmsg);\n amfree(errmsg);\n amfree(qerrmsg);\n amfree(cmd);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-77'], 'message': '* application-src/ambsdtar.c, application-src/amgtar.c,\n application-src/amstar.c: Filter option from COMMAND-OPTIONS\n* common-src/ammessage.c: Add message.\n\n\ngit-svn-id: https://svn.code.sf.net/p/amanda/code/amanda/trunk@6483 a8d146d6-cc15-0410-8900-af154a0219e0'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static GPtrArray *amstar_build_argv(\n application_argument_t *argument,\n int level,\n int command,\n FILE *mesgstream)\n{\n char *dirname;\n char *fsname;\n char levelstr[NUM_STR_SIZE+7];\n GPtrArray *argv_ptr = g_ptr_array_new();\n char *s;\n char *tardumpfile;\n GSList *copt;\n\n if (star_directory) {\n\tdirname = star_directory;\n } else {\n\tdirname = argument->dle.device;\n }\n fsname = vstralloc(\"fs-name=\", dirname, NULL);\n for (s = fsname; *s != '\\0'; s++) {\n\tif (iscntrl((int)*s))\n\t *s = '-';\n }\n snprintf(levelstr, SIZEOF(levelstr), \"-level=%d\", level);\n\n if (star_dle_tardumps) {\n\tchar *sdisk = sanitise_filename(argument->dle.disk);\n\ttardumpfile = vstralloc(star_tardumps, sdisk, NULL);\n\tamfree(sdisk);\n } else {\n\ttardumpfile = stralloc(star_tardumps);\n }\n\n g_ptr_array_add(argv_ptr, stralloc(star_path));\n\n g_ptr_array_add(argv_ptr, stralloc(\"-c\"));\n g_ptr_array_add(argv_ptr, stralloc(\"-f\"));\n if (command == CMD_ESTIMATE) {\n\tg_ptr_array_add(argv_ptr, stralloc(\"/dev/null\"));\n } else {\n\tg_ptr_array_add(argv_ptr, stralloc(\"-\"));\n }\n g_ptr_array_add(argv_ptr, stralloc(\"-C\"));\n\n#if defined(__CYGWIN__)\n {\n\tchar tmppath[PATH_MAX];\n\n\tcygwin_conv_to_full_posix_path(dirname, tmppath);\n\tg_ptr_array_add(argv_ptr, stralloc(tmppath));\n }\n#else\n g_ptr_array_add(argv_ptr, stralloc(dirname));\n#endif\n g_ptr_array_add(argv_ptr, stralloc(fsname));\n if (star_onefilesystem)\n\tg_ptr_array_add(argv_ptr, stralloc(\"-xdev\"));\n g_ptr_array_add(argv_ptr, stralloc(\"-link-dirs\"));\n g_ptr_array_add(argv_ptr, stralloc(levelstr));\n g_ptr_array_add(argv_ptr, stralloc2(\"tardumps=\", tardumpfile));\n if (command == CMD_BACKUP)\n\tg_ptr_array_add(argv_ptr, stralloc(\"-wtardumps\"));\n\n g_ptr_array_add(argv_ptr, stralloc(\"-xattr\"));\n if (star_acl)\n\tg_ptr_array_add(argv_ptr, stralloc(\"-acl\"));\n g_ptr_array_add(argv_ptr, stralloc(\"H=exustar\"));\n g_ptr_array_add(argv_ptr, stralloc(\"errctl=WARN|SAMEFILE|DIFF|GROW|SHRINK|SPECIALFILE|GETXATTR|BADACL *\"));\n if (star_sparse)\n\tg_ptr_array_add(argv_ptr, stralloc(\"-sparse\"));\n g_ptr_array_add(argv_ptr, stralloc(\"-dodesc\"));\n\n if (command == CMD_BACKUP && argument->dle.create_index)\n\tg_ptr_array_add(argv_ptr, stralloc(\"-v\"));\n\n if (((argument->dle.include_file &&\n\t argument->dle.include_file->nb_element >= 1) ||\n\t (argument->dle.include_list &&\n\t argument->dle.include_list->nb_element >= 1)) &&\n\t((argument->dle.exclude_file &&\n\t argument->dle.exclude_file->nb_element >= 1) ||\n\t (argument->dle.exclude_list &&\n\t argument->dle.exclude_list->nb_element >= 1))) {\n\n\tif (mesgstream && command == CMD_BACKUP) {\n\t fprintf(mesgstream, \"? include and exclude specified, disabling exclude\\n\");\n\t}\n\tfree_sl(argument->dle.exclude_file);\n\targument->dle.exclude_file = NULL;\n\tfree_sl(argument->dle.exclude_list);\n\targument->dle.exclude_list = NULL;\n }\n\n if ((argument->dle.exclude_file &&\n\t argument->dle.exclude_file->nb_element >= 1) ||\n\t(argument->dle.exclude_list &&\n\t argument->dle.exclude_list->nb_element >= 1)) {\n\tg_ptr_array_add(argv_ptr, stralloc(\"-match-tree\"));\n\tg_ptr_array_add(argv_ptr, stralloc(\"-not\"));\n }\n if (argument->dle.exclude_file &&\n\targument->dle.exclude_file->nb_element >= 1) {\n\tsle_t *excl;\n\tfor (excl = argument->dle.exclude_file->first; excl != NULL;\n\t excl = excl->next) {\n\t char *ex;\n\t if (strcmp(excl->name, \"./\") == 0) {\n\t\tex = g_strdup_printf(\"pat=%s\", excl->name+2);\n\t } else {\n\t\tex = g_strdup_printf(\"pat=%s\", excl->name);\n\t }\n\t g_ptr_array_add(argv_ptr, ex);\n\t}\n }\n if (argument->dle.exclude_list &&\n\targument->dle.exclude_list->nb_element >= 1) {\n\tsle_t *excl;\n\tfor (excl = argument->dle.exclude_list->first; excl != NULL;\n\t excl = excl->next) {\n\t char *exclname = fixup_relative(excl->name, argument->dle.device);\n\t FILE *exclude;\n\t char *aexc;\n\t if ((exclude = fopen(exclname, \"r\")) != NULL) {\n\t\twhile ((aexc = agets(exclude)) != NULL) {\n\t\t if (aexc[0] != '\\0') {\n\t\t\tchar *ex;\n\t\t\tif (strcmp(aexc, \"./\") == 0) {\n\t\t\t ex = g_strdup_printf(\"pat=%s\", aexc+2);\n\t\t\t} else {\n\t\t\t ex = g_strdup_printf(\"pat=%s\", aexc);\n\t\t\t}\n\t\t\tg_ptr_array_add(argv_ptr, ex);\n\t\t }\n\t\t amfree(aexc);\n\t\t}\n\t\tfclose(exclude);\n\t }\n\t amfree(exclname);\n\t}\n }\n\n if (argument->dle.include_file &&\n\targument->dle.include_file->nb_element >= 1) {\n\tsle_t *excl;\n\tfor (excl = argument->dle.include_file->first; excl != NULL;\n\t excl = excl->next) {\n\t char *ex;\n\t if (g_str_equal(excl->name, \"./\")) {\n\t\tex = g_strdup_printf(\"pat=%s\", excl->name+2);\n\t } else {\n\t\tex = g_strdup_printf(\"pat=%s\", excl->name);\n\t }\n\t g_ptr_array_add(argv_ptr, ex);\n\t}\n }\n if (argument->dle.include_list &&\n\targument->dle.include_list->nb_element >= 1) {\n\tsle_t *excl;\n\tfor (excl = argument->dle.include_list->first; excl != NULL;\n\t excl = excl->next) {\n\t char *exclname = fixup_relative(excl->name, argument->dle.device);\n\t FILE *include;\n\t char *aexc;\n\t if ((include = fopen(exclname, \"r\")) != NULL) {\n\t\twhile ((aexc = agets(include)) != NULL) {\n\t\t if (aexc[0] != '\\0') {\n\t\t\tchar *ex;\n\t\t\tif (g_str_equal(aexc, \"./\")) {\n\t\t\t ex = g_strdup_printf(\"pat=%s\", aexc+2);\n\t\t\t} else {\n\t\t\t ex = g_strdup_printf(\"pat=%s\", aexc);\n\t\t\t}\n\t\t\tg_ptr_array_add(argv_ptr, ex);\n\t\t }\n\t\t amfree(aexc);\n\t\t}\n\t\tfclose(include);\n\t }\n\t amfree(exclname);\n\t}\n }\n\n /* It is best to place command_options at the and of command line.\n * For example '-find' option requires that it is the last option used.\n * See: http://cdrecord.berlios.de/private/man/star/star.1.html\n */\n for (copt = argument->command_options; copt != NULL; copt = copt->next) {\n\tg_ptr_array_add(argv_ptr, stralloc((char *)copt->data));\n }\n\n g_ptr_array_add(argv_ptr, stralloc(\".\"));\n\n g_ptr_array_add(argv_ptr, NULL);\n\n amfree(tardumpfile);\n amfree(fsname);\n\n return(argv_ptr);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': '* Add a /etc/amanda-security.conf file\n\n\ngit-svn-id: https://svn.code.sf.net/p/amanda/code/amanda/branches/3_3@6486 a8d146d6-cc15-0410-8900-af154a0219e0'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: amgtar_estimate(\n application_argument_t *argument)\n{\n char *incrname = NULL;\n GPtrArray *argv_ptr;\n char *cmd = NULL;\n int nullfd = -1;\n int pipefd = -1;\n FILE *dumpout = NULL;\n off_t size = -1;\n char line[32768];\n char *errmsg = NULL;\n char *qerrmsg = NULL;\n char *qdisk;\n amwait_t wait_status;\n int tarpid;\n amregex_t *rp;\n times_t start_time;\n int level;\n GSList *levels;\n char *file_exclude;\n char *file_include;\n char *option;\n\n if (!argument->level) {\n fprintf(stderr, \"ERROR No level argument\\n\");\n error(_(\"No level argument\"));\n }\n if (!argument->dle.disk) {\n fprintf(stderr, \"ERROR No disk argument\\n\");\n error(_(\"No disk argument\"));\n }\n if (!argument->dle.device) {\n fprintf(stderr, \"ERROR No device argument\\n\");\n error(_(\"No device argument\"));\n }\n\n qdisk = quote_string(argument->dle.disk);\n\n if ((option = validate_command_options(argument))) {\n\tfprintf(stderr, \"ERROR Invalid '%s' COMMAND-OPTIONS\\n\", option);\n\terror(\"Invalid '%s' COMMAND-OPTIONS\", option);\n }\n\n if (argument->calcsize) {\n\tchar *dirname;\n\tint nb_exclude;\n\tint nb_include;\n\tchar *calcsize = g_strjoin(NULL, amlibexecdir, \"/\", \"calcsize\", NULL);\n\n\tif (!check_exec_for_suid(calcsize, FALSE)) {\n\t errmsg = g_strdup_printf(\"'%s' binary is not secure\", calcsize);\n\t g_free(calcsize);\n\t goto common_error;\n\t}\n\tg_free(calcsize);\n\n\tif (gnutar_directory) {\n\t dirname = gnutar_directory;\n\t} else {\n\t dirname = argument->dle.device;\n\t}\n\n\tamgtar_build_exinclude(&argument->dle, 1,\n\t\t\t &nb_exclude, &file_exclude,\n\t\t\t &nb_include, &file_include);\n\n\trun_calcsize(argument->config, \"GNUTAR\", argument->dle.disk, dirname,\n\t\t argument->level, file_exclude, file_include);\n\n\tif (argument->verbose == 0) {\n\t if (file_exclude)\n\t\tunlink(file_exclude);\n\t if (file_include)\n\t\tunlink(file_include);\n }\n\treturn;\n }\n\n if (!gnutar_path) {\n\terrmsg = vstrallocf(_(\"GNUTAR-PATH not defined\"));\n\tgoto common_error;\n }\n\n if (!check_exec_for_suid(gnutar_path, FALSE)) {\n\terrmsg = g_strdup_printf(\"'%s' binary is not secure\", gnutar_path);\n\tgoto common_error;\n }\n\n if (!gnutar_listdir) {\n\terrmsg = vstrallocf(_(\"GNUTAR-LISTDIR not defined\"));\n\tgoto common_error;\n }\n\n for (levels = argument->level; levels != NULL; levels = levels->next) {\n\tlevel = GPOINTER_TO_INT(levels->data);\n\tincrname = amgtar_get_incrname(argument, level, stdout, CMD_ESTIMATE);\n\tcmd = stralloc(gnutar_path);\n\targv_ptr = amgtar_build_argv(argument, incrname, &file_exclude,\n\t\t\t\t &file_include, CMD_ESTIMATE);\n\n\tstart_time = curclock();\n\n\tif ((nullfd = open(\"/dev/null\", O_RDWR)) == -1) {\n\t errmsg = vstrallocf(_(\"Cannot access /dev/null : %s\"),\n\t\t\t\tstrerror(errno));\n\t goto common_exit;\n\t}\n\n\ttarpid = pipespawnv(cmd, STDERR_PIPE, 1,\n\t\t\t &nullfd, &nullfd, &pipefd,\n\t\t\t (char **)argv_ptr->pdata);\n\n\tdumpout = fdopen(pipefd,\"r\");\n\tif (!dumpout) {\n\t error(_(\"Can't fdopen: %s\"), strerror(errno));\n\t /*NOTREACHED*/\n\t}\n\n\tsize = (off_t)-1;\n\twhile (size < 0 && (fgets(line, sizeof(line), dumpout) != NULL)) {\n\t if (line[strlen(line)-1] == '\\n') /* remove trailling \\n */\n\t\tline[strlen(line)-1] = '\\0';\n\t if (line[0] == '\\0')\n\t\tcontinue;\n\t dbprintf(\"%s\\n\", line);\n\t /* check for size match */\n\t /*@ignore@*/\n\t for(rp = re_table; rp->regex != NULL; rp++) {\n\t\tif(match(rp->regex, line)) {\n\t\t if (rp->typ == DMP_SIZE) {\n\t\t\tsize = ((the_num(line, rp->field)*rp->scale+1023.0)/1024.0);\n\t\t\tif(size < 0.0)\n\t\t\t size = 1.0; /* found on NeXT -- sigh */\n\t\t }\n\t\t break;\n\t\t}\n\t }\n\t /*@end@*/\n\t}\n\n\twhile (fgets(line, sizeof(line), dumpout) != NULL) {\n\t dbprintf(\"%s\", line);\n\t}\n\n\tdbprintf(\".....\\n\");\n\tdbprintf(_(\"estimate time for %s level %d: %s\\n\"),\n\t\t qdisk,\n\t\t level,\n\t\t walltime_str(timessub(curclock(), start_time)));\n\tif(size == (off_t)-1) {\n\t errmsg = vstrallocf(_(\"no size line match in %s output\"), cmd);\n\t dbprintf(_(\"%s for %s\\n\"), errmsg, qdisk);\n\t dbprintf(\".....\\n\");\n\t} else if(size == (off_t)0 && argument->level == 0) {\n\t dbprintf(_(\"possible %s problem -- is \\\"%s\\\" really empty?\\n\"),\n\t\t cmd, argument->dle.disk);\n\t dbprintf(\".....\\n\");\n\t}\n\tdbprintf(_(\"estimate size for %s level %d: %lld KB\\n\"),\n\t\t qdisk,\n\t\t level,\n\t\t (long long)size);\n\n\tkill(-tarpid, SIGTERM);\n\n\tdbprintf(_(\"waiting for %s \\\"%s\\\" child\\n\"), cmd, qdisk);\n\twaitpid(tarpid, &wait_status, 0);\n\tif (WIFSIGNALED(wait_status)) {\n\t errmsg = vstrallocf(_(\"%s terminated with signal %d: see %s\"),\n\t\t\t\tcmd, WTERMSIG(wait_status), dbfn());\n\t} else if (WIFEXITED(wait_status)) {\n\t if (exit_value[WEXITSTATUS(wait_status)] == 1) {\n\t\terrmsg = vstrallocf(_(\"%s exited with status %d: see %s\"),\n\t\t\t\t cmd, WEXITSTATUS(wait_status), dbfn());\n\t } else {\n\t\t/* Normal exit */\n\t }\n\t} else {\n\t errmsg = vstrallocf(_(\"%s got bad exit: see %s\"),\n\t\t\t\tcmd, dbfn());\n\t}\n\tdbprintf(_(\"after %s %s wait\\n\"), cmd, qdisk);\n\ncommon_exit:\n\tif (errmsg) {\n\t dbprintf(\"%s\", errmsg);\n\t fprintf(stdout, \"ERROR %s\\n\", errmsg);\n\t}\n\n\tif (incrname) {\n\t unlink(incrname);\n\t}\n\n\tif (argument->verbose == 0) {\n\t if (file_exclude)\n\t\tunlink(file_exclude);\n\t if (file_include)\n\t\tunlink(file_include);\n }\n\n\tg_ptr_array_free_full(argv_ptr);\n\tamfree(cmd);\n\n\taclose(nullfd);\n\tafclose(dumpout);\n\n\tfprintf(stdout, \"%d %lld 1\\n\", level, (long long)size);\n }\n amfree(qdisk);\n return;\n\ncommon_error:\n qerrmsg = quote_string(errmsg);\n amfree(qdisk);\n dbprintf(\"%s\", errmsg);\n fprintf(stdout, \"ERROR %s\\n\", qerrmsg);\n amfree(errmsg);\n amfree(qerrmsg);\n return;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': '* Add a /etc/amanda-security.conf file\n\n\ngit-svn-id: https://svn.code.sf.net/p/amanda/code/amanda/branches/3_3@6486 a8d146d6-cc15-0410-8900-af154a0219e0'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: _poppler_attachment_new (FileSpec *emb_file)\n{\n PopplerAttachment *attachment;\n PopplerAttachmentPrivate *priv;\n EmbFile *embFile;\n\n g_assert (emb_file != nullptr);\n\n attachment = (PopplerAttachment *) g_object_new (POPPLER_TYPE_ATTACHMENT, nullptr);\n priv = POPPLER_ATTACHMENT_GET_PRIVATE (attachment);\n\n if (emb_file->getFileName ())\n attachment->name = _poppler_goo_string_to_utf8 (emb_file->getFileName ());\n if (emb_file->getDescription ())\n attachment->description = _poppler_goo_string_to_utf8 (emb_file->getDescription ());\n\n embFile = emb_file->getEmbeddedFile();\n attachment->size = embFile->size ();\n\n if (embFile->createDate ())\n _poppler_convert_pdf_date_to_gtime (embFile->createDate (), (time_t *)&attachment->ctime);\n if (embFile->modDate ())\n _poppler_convert_pdf_date_to_gtime (embFile->modDate (), (time_t *)&attachment->mtime);\n\n if (embFile->checksum () && embFile->checksum ()->getLength () > 0)\n attachment->checksum = g_string_new_len (embFile->checksum ()->getCString (),\n embFile->checksum ()->getLength ());\n priv->obj_stream = embFile->streamObject()->copy();\n\n return attachment;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fix crash on missing embedded file\n\nCheck whether an embedded file is actually present in the PDF\nand show warning in that case.\n\nhttps://bugs.freedesktop.org/show_bug.cgi?id=106137\nhttps://gitlab.freedesktop.org/poppler/poppler/issues/236'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: write_stacktrace(const char *file_name, const char *str)\n{\n\tint fd;\n\tvoid *buffer[100];\n\tint nptrs;\n\tint i;\n\tchar **strs;\n\n\tnptrs = backtrace(buffer, 100);\n\tif (file_name) {\n\t\tfd = open(file_name, O_WRONLY | O_APPEND | O_CREAT, 0644);\n\t\tif (str)\n\t\t\tdprintf(fd, \"%s\\n\", str);\n\t\tbacktrace_symbols_fd(buffer, nptrs, fd);\n\t\tif (write(fd, \"\\n\", 1) != 1) {\n\t\t\t/* We don't care, but this stops a warning on Ubuntu */\n\t\t}\n\t\tclose(fd);\n\t} else {\n\t\tif (str)\n\t\t\tlog_message(LOG_INFO, \"%s\", str);\n\t\tstrs = backtrace_symbols(buffer, nptrs);\n\t\tif (strs == NULL) {\n\t\t\tlog_message(LOG_INFO, \"Unable to get stack backtrace\");\n\t\t\treturn;\n\t\t}\n\n\t\t/* We don't need the call to this function, or the first two entries on the stack */\n\t\tfor (i = 1; i < nptrs - 2; i++)\n\t\t\tlog_message(LOG_INFO, \" %s\", strs[i]);\n\t\tfree(strs);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'When opening files for write, ensure they aren't symbolic links\n\nIssue #1048 identified that if, for example, a non privileged user\ncreated a symbolic link from /etc/keepalvied.data to /etc/passwd,\nwriting to /etc/keepalived.data (which could be invoked via DBus)\nwould cause /etc/passwd to be overwritten.\n\nThis commit stops keepalived writing to pathnames where the ultimate\ncomponent is a symbolic link, by setting O_NOFOLLOW whenever opening\na file for writing.\n\nThis might break some setups, where, for example, /etc/keepalived.data\nwas a symbolic link to /home/fred/keepalived.data. If this was the case,\ninstead create a symbolic link from /home/fred/keepalived.data to\n/tmp/keepalived.data, so that the file is still accessible via\n/home/fred/keepalived.data.\n\nThere doesn't appear to be a way around this backward incompatibility,\nsince even checking if the pathname is a symbolic link prior to opening\nfor writing would create a race condition.\n\nSigned-off-by: Quentin Armitage '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: keepalived_main(int argc, char **argv)\n{\n\tbool report_stopped = true;\n\tstruct utsname uname_buf;\n\tchar *end;\n\n\t/* Ensure time_now is set. We then don't have to check anywhere\n\t * else if it is set. */\n\tset_time_now();\n\n\t/* Save command line options in case need to log them later */\n\tsave_cmd_line_options(argc, argv);\n\n\t/* Init debugging level */\n\tdebug = 0;\n\n\t/* We are the parent process */\n#ifndef _DEBUG_\n\tprog_type = PROG_TYPE_PARENT;\n#endif\n\n\t/* Initialise daemon_mode */\n#ifdef _WITH_VRRP_\n\t__set_bit(DAEMON_VRRP, &daemon_mode);\n#endif\n#ifdef _WITH_LVS_\n\t__set_bit(DAEMON_CHECKERS, &daemon_mode);\n#endif\n#ifdef _WITH_BFD_\n\t__set_bit(DAEMON_BFD, &daemon_mode);\n#endif\n\n\t/* Open log with default settings so we can log initially */\n\topenlog(PACKAGE_NAME, LOG_PID, log_facility);\n\n#ifdef _MEM_CHECK_\n\tmem_log_init(PACKAGE_NAME, \"Parent process\");\n#endif\n\n\t/* Some functionality depends on kernel version, so get the version here */\n\tif (uname(&uname_buf))\n\t\tlog_message(LOG_INFO, \"Unable to get uname() information - error %d\", errno);\n\telse {\n\t\tos_major = (unsigned)strtoul(uname_buf.release, &end, 10);\n\t\tif (*end != '.')\n\t\t\tos_major = 0;\n\t\telse {\n\t\t\tos_minor = (unsigned)strtoul(end + 1, &end, 10);\n\t\t\tif (*end != '.')\n\t\t\t\tos_major = 0;\n\t\t\telse {\n\t\t\t\tif (!isdigit(end[1]))\n\t\t\t\t\tos_major = 0;\n\t\t\t\telse\n\t\t\t\t\tos_release = (unsigned)strtoul(end + 1, &end, 10);\n\t\t\t}\n\t\t}\n\t\tif (!os_major)\n\t\t\tlog_message(LOG_INFO, \"Unable to parse kernel version %s\", uname_buf.release);\n\n\t\t/* config_id defaults to hostname */\n\t\tif (!config_id) {\n\t\t\tend = strchrnul(uname_buf.nodename, '.');\n\t\t\tconfig_id = MALLOC((size_t)(end - uname_buf.nodename) + 1);\n\t\t\tstrncpy(config_id, uname_buf.nodename, (size_t)(end - uname_buf.nodename));\n\t\t\tconfig_id[end - uname_buf.nodename] = '\\0';\n\t\t}\n\t}\n\n\t/*\n\t * Parse command line and set debug level.\n\t * bits 0..7 reserved by main.c\n\t */\n\tif (parse_cmdline(argc, argv)) {\n\t\tcloselog();\n\t\tif (!__test_bit(NO_SYSLOG_BIT, &debug))\n\t\t\topenlog(PACKAGE_NAME, LOG_PID | ((__test_bit(LOG_CONSOLE_BIT, &debug)) ? LOG_CONS : 0) , log_facility);\n\t}\n\n\tif (__test_bit(LOG_CONSOLE_BIT, &debug))\n\t\tenable_console_log();\n\n#ifdef GIT_COMMIT\n\tlog_message(LOG_INFO, \"Starting %s, git commit %s\", version_string, GIT_COMMIT);\n#else\n\tlog_message(LOG_INFO, \"Starting %s\", version_string);\n#endif\n\n\t/* Handle any core file requirements */\n\tcore_dump_init();\n\n\tif (os_major) {\n\t\tif (KERNEL_VERSION(os_major, os_minor, os_release) < LINUX_VERSION_CODE) {\n\t\t\t/* keepalived was build for a later kernel version */\n\t\t\tlog_message(LOG_INFO, \"WARNING - keepalived was build for newer Linux %d.%d.%d, running on %s %s %s\",\n\t\t\t\t\t(LINUX_VERSION_CODE >> 16) & 0xff,\n\t\t\t\t\t(LINUX_VERSION_CODE >> 8) & 0xff,\n\t\t\t\t\t(LINUX_VERSION_CODE ) & 0xff,\n\t\t\t\t\tuname_buf.sysname, uname_buf.release, uname_buf.version);\n\t\t} else {\n\t\t\t/* keepalived was build for a later kernel version */\n\t\t\tlog_message(LOG_INFO, \"Running on %s %s %s (built for Linux %d.%d.%d)\",\n\t\t\t\t\tuname_buf.sysname, uname_buf.release, uname_buf.version,\n\t\t\t\t\t(LINUX_VERSION_CODE >> 16) & 0xff,\n\t\t\t\t\t(LINUX_VERSION_CODE >> 8) & 0xff,\n\t\t\t\t\t(LINUX_VERSION_CODE ) & 0xff);\n\t\t}\n\t}\n\n#ifndef _DEBUG_\n\tlog_command_line(0);\n#endif\n\n\t/* Check we can read the configuration file(s).\n\t NOTE: the working directory will be / if we\n\t forked, but will be the current working directory\n\t when keepalived was run if we haven't forked.\n\t This means that if any config file names are not\n\t absolute file names, the behaviour will be different\n\t depending on whether we forked or not. */\n\tif (!check_conf_file(conf_file)) {\n\t\tif (__test_bit(CONFIG_TEST_BIT, &debug))\n\t\t\tconfig_test_exit();\n\n\t\tgoto end;\n\t}\n\n\tglobal_data = alloc_global_data();\n\n\tread_config_file();\n\n\tinit_global_data(global_data, NULL);\n\n#if HAVE_DECL_CLONE_NEWNET\n\tif (override_namespace) {\n\t\tif (global_data->network_namespace) {\n\t\t\tlog_message(LOG_INFO, \"Overriding config net_namespace '%s' with command line namespace '%s'\", global_data->network_namespace, override_namespace);\n\t\t\tFREE(global_data->network_namespace);\n\t\t}\n\t\tglobal_data->network_namespace = override_namespace;\n\t\toverride_namespace = NULL;\n\t}\n#endif\n\n\tif (!__test_bit(CONFIG_TEST_BIT, &debug) &&\n\t (global_data->instance_name\n#if HAVE_DECL_CLONE_NEWNET\n\t || global_data->network_namespace\n#endif\n\t\t\t\t\t )) {\n\t\tif ((syslog_ident = make_syslog_ident(PACKAGE_NAME))) {\n\t\t\tlog_message(LOG_INFO, \"Changing syslog ident to %s\", syslog_ident);\n\t\t\tcloselog();\n\t\t\topenlog(syslog_ident, LOG_PID | ((__test_bit(LOG_CONSOLE_BIT, &debug)) ? LOG_CONS : 0), log_facility);\n\t\t}\n\t\telse\n\t\t\tlog_message(LOG_INFO, \"Unable to change syslog ident\");\n\n\t\tuse_pid_dir = true;\n\n\t\topen_log_file(log_file_name,\n\t\t\t\tNULL,\n#if HAVE_DECL_CLONE_NEWNET\n\t\t\t\tglobal_data->network_namespace,\n#else\n\t\t\t\tNULL,\n#endif\n\t\t\t\tglobal_data->instance_name);\n\t}\n\n\t/* Initialise pointer to child finding function */\n\tset_child_finder_name(find_keepalived_child_name);\n\n\tif (!__test_bit(CONFIG_TEST_BIT, &debug)) {\n\t\tif (use_pid_dir) {\n\t\t\t/* Create the directory for pid files */\n\t\t\tcreate_pid_dir();\n\t\t}\n\t}\n\n#if HAVE_DECL_CLONE_NEWNET\n\tif (global_data->network_namespace) {\n\t\tif (global_data->network_namespace && !set_namespaces(global_data->network_namespace)) {\n\t\t\tlog_message(LOG_ERR, \"Unable to set network namespace %s - exiting\", global_data->network_namespace);\n\t\t\tgoto end;\n\t\t}\n\t}\n#endif\n\n\tif (!__test_bit(CONFIG_TEST_BIT, &debug)) {\n\t\tif (global_data->instance_name) {\n\t\t\tif (!main_pidfile && (main_pidfile = make_pidfile_name(KEEPALIVED_PID_DIR KEEPALIVED_PID_FILE, global_data->instance_name, PID_EXTENSION)))\n\t\t\t\tfree_main_pidfile = true;\n#ifdef _WITH_LVS_\n\t\t\tif (!checkers_pidfile && (checkers_pidfile = make_pidfile_name(KEEPALIVED_PID_DIR CHECKERS_PID_FILE, global_data->instance_name, PID_EXTENSION)))\n\t\t\t\tfree_checkers_pidfile = true;\n#endif\n#ifdef _WITH_VRRP_\n\t\t\tif (!vrrp_pidfile && (vrrp_pidfile = make_pidfile_name(KEEPALIVED_PID_DIR VRRP_PID_FILE, global_data->instance_name, PID_EXTENSION)))\n\t\t\t\tfree_vrrp_pidfile = true;\n#endif\n#ifdef _WITH_BFD_\n\t\t\tif (!bfd_pidfile && (bfd_pidfile = make_pidfile_name(KEEPALIVED_PID_DIR VRRP_PID_FILE, global_data->instance_name, PID_EXTENSION)))\n\t\t\t\tfree_bfd_pidfile = true;\n#endif\n\t\t}\n\n\t\tif (use_pid_dir) {\n\t\t\tif (!main_pidfile)\n\t\t\t\tmain_pidfile = KEEPALIVED_PID_DIR KEEPALIVED_PID_FILE PID_EXTENSION;\n#ifdef _WITH_LVS_\n\t\t\tif (!checkers_pidfile)\n\t\t\t\tcheckers_pidfile = KEEPALIVED_PID_DIR CHECKERS_PID_FILE PID_EXTENSION;\n#endif\n#ifdef _WITH_VRRP_\n\t\t\tif (!vrrp_pidfile)\n\t\t\t\tvrrp_pidfile = KEEPALIVED_PID_DIR VRRP_PID_FILE PID_EXTENSION;\n#endif\n#ifdef _WITH_BFD_\n\t\t\tif (!bfd_pidfile)\n\t\t\t\tbfd_pidfile = KEEPALIVED_PID_DIR BFD_PID_FILE PID_EXTENSION;\n#endif\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (!main_pidfile)\n\t\t\t\tmain_pidfile = PID_DIR KEEPALIVED_PID_FILE PID_EXTENSION;\n#ifdef _WITH_LVS_\n\t\t\tif (!checkers_pidfile)\n\t\t\t\tcheckers_pidfile = PID_DIR CHECKERS_PID_FILE PID_EXTENSION;\n#endif\n#ifdef _WITH_VRRP_\n\t\t\tif (!vrrp_pidfile)\n\t\t\t\tvrrp_pidfile = PID_DIR VRRP_PID_FILE PID_EXTENSION;\n#endif\n#ifdef _WITH_BFD_\n\t\t\tif (!bfd_pidfile)\n\t\t\t\tbfd_pidfile = PID_DIR BFD_PID_FILE PID_EXTENSION;\n#endif\n\t\t}\n\n\t\t/* Check if keepalived is already running */\n\t\tif (keepalived_running(daemon_mode)) {\n\t\t\tlog_message(LOG_INFO, \"daemon is already running\");\n\t\t\treport_stopped = false;\n\t\t\tgoto end;\n\t\t}\n\t}\n\n\t/* daemonize process */\n\tif (!__test_bit(DONT_FORK_BIT, &debug) &&\n\t xdaemon(false, false, true) > 0) {\n\t\tcloselog();\n\t\tFREE_PTR(config_id);\n\t\tFREE_PTR(orig_core_dump_pattern);\n\t\tclose_std_fd();\n\t\texit(0);\n\t}\n\n\t/* Set file creation mask */\n\tumask(0);\n\n#ifdef _MEM_CHECK_\n\tenable_mem_log_termination();\n#endif\n\n\tif (__test_bit(CONFIG_TEST_BIT, &debug)) {\n\t\tvalidate_config();\n\n\t\tconfig_test_exit();\n\t}\n\n\t/* write the father's pidfile */\n\tif (!pidfile_write(main_pidfile, getpid()))\n\t\tgoto end;\n\n\t/* Create the master thread */\n\tmaster = thread_make_master();\n\n\t/* Signal handling initialization */\n\tsignal_init();\n\n\t/* Init daemon */\n\tif (!start_keepalived())\n\t\tlog_message(LOG_INFO, \"Warning - keepalived has no configuration to run\");\n\n\tinitialise_debug_options();\n\n#ifdef THREAD_DUMP\n\tregister_parent_thread_addresses();\n#endif\n\n\t/* Launch the scheduling I/O multiplexer */\n\tlaunch_thread_scheduler(master);\n\n\t/* Finish daemon process */\n\tstop_keepalived();\n\n#ifdef THREAD_DUMP\n\tderegister_thread_addresses();\n#endif\n\n\t/*\n\t * Reached when terminate signal catched.\n\t * finally return from system\n\t */\nend:\n\tif (report_stopped) {\n#ifdef GIT_COMMIT\n\t\tlog_message(LOG_INFO, \"Stopped %s, git commit %s\", version_string, GIT_COMMIT);\n#else\n\t\tlog_message(LOG_INFO, \"Stopped %s\", version_string);\n#endif\n\t}\n\n#if HAVE_DECL_CLONE_NEWNET\n\tif (global_data && global_data->network_namespace)\n\t\tclear_namespaces();\n#endif\n\n\tif (use_pid_dir)\n\t\tremove_pid_dir();\n\n\t/* Restore original core_pattern if necessary */\n\tif (orig_core_dump_pattern)\n\t\tupdate_core_dump_pattern(orig_core_dump_pattern);\n\n\tfree_parent_mallocs_startup(false);\n\tfree_parent_mallocs_exit();\n\tfree_global_data(global_data);\n\n\tcloselog();\n\n#ifndef _MEM_CHECK_LOG_\n\tFREE_PTR(syslog_ident);\n#else\n\tif (syslog_ident)\n\t\tfree(syslog_ident);\n#endif\n\tclose_std_fd();\n\n\texit(KEEPALIVED_EXIT_OK);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Add command line and configuration option to set umask\n\nIssue #1048 identified that files created by keepalived are created\nwith mode 0666. This commit changes the default to 0644, and also\nallows the umask to be specified in the configuration or as a command\nline option.\n\nSigned-off-by: Quentin Armitage '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: vlog_message(const int facility, const char* format, va_list args)\n{\n#if !HAVE_VSYSLOG\n\tchar buf[MAX_LOG_MSG+1];\n\n\tvsnprintf(buf, sizeof(buf), format, args);\n#endif\n\n\t/* Don't write syslog if testing configuration */\n\tif (__test_bit(CONFIG_TEST_BIT, &debug))\n\t\treturn;\n\n\tif (log_file || (__test_bit(DONT_FORK_BIT, &debug) && log_console)) {\n#if HAVE_VSYSLOG\n\t\tva_list args1;\n\t\tchar buf[2 * MAX_LOG_MSG + 1];\n\n\t\tva_copy(args1, args);\n\t\tvsnprintf(buf, sizeof(buf), format, args1);\n\t\tva_end(args1);\n#endif\n\n\t\t/* timestamp setup */\n\t\ttime_t t = time(NULL);\n\t\tstruct tm tm;\n\t\tlocaltime_r(&t, &tm);\n\t\tchar timestamp[64];\n\t\tstrftime(timestamp, sizeof(timestamp), \"%c\", &tm);\n\n\t\tif (log_console && __test_bit(DONT_FORK_BIT, &debug))\n\t\t\tfprintf(stderr, \"%s: %s\\n\", timestamp, buf);\n\t\tif (log_file) {\n\t\t\tfprintf(log_file, \"%s: %s\\n\", timestamp, buf);\n\t\t\tif (always_flush_log_file)\n\t\t\t\tfflush(log_file);\n\t\t}\n\t}\n\n\tif (!__test_bit(NO_SYSLOG_BIT, &debug))\n#if HAVE_VSYSLOG\n\t\tvsyslog(facility, format, args);\n#else\n\t\tsyslog(facility, \"%s\", buf);\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Disable fopen_safe() append mode by default\n\nIf a non privileged user creates /tmp/keepalived.log and has it open\nfor read (e.g. tail -f), then even though keepalived will change the\nowner to root and remove all read/write permissions from non owners,\nthe application which already has the file open will be able to read\nthe added log entries.\n\nAccordingly, opening a file in append mode is disabled by default, and\nonly enabled if --enable-smtp-alert-debug or --enable-log-file (which\nare debugging options and unset by default) are enabled.\n\nThis should further alleviate security concerns related to CVE-2018-19046.\n\nSigned-off-by: Quentin Armitage '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: stop_bfd(int status)\n{\n\tstruct rusage usage;\n\n\tif (__test_bit(CONFIG_TEST_BIT, &debug))\n\t\treturn;\n\n\t/* Stop daemon */\n\tpidfile_rm(bfd_pidfile);\n\n\t/* Clean data */\n\tfree_global_data(global_data);\n\tbfd_dispatcher_release(bfd_data);\n\tfree_bfd_data(bfd_data);\n\tfree_bfd_buffer();\n\tthread_destroy_master(master);\n\tfree_parent_mallocs_exit();\n\n\t/*\n\t * Reached when terminate signal catched.\n\t * finally return to parent process.\n\t */\n\tif (__test_bit(LOG_DETAIL_BIT, &debug)) {\n\t\tgetrusage(RUSAGE_SELF, &usage);\n\t\tlog_message(LOG_INFO, \"Stopped - used %ld.%6.6ld user time, %ld.%6.6ld system time\", usage.ru_utime.tv_sec, usage.ru_utime.tv_usec, usage.ru_stime.tv_sec, usage.ru_stime.tv_usec);\n\t}\n\telse\n\t\tlog_message(LOG_INFO, \"Stopped\");\n\n\tif (log_file_name)\n\t\tclose_log_file();\n\tcloselog();\n\n#ifndef _MEM_CHECK_LOG_\n\tFREE_PTR(bfd_syslog_ident);\n#else\n\tif (bfd_syslog_ident)\n\t\tfree(bfd_syslog_ident);\n#endif\n\tclose_std_fd();\n\n\texit(status);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Disable fopen_safe() append mode by default\n\nIf a non privileged user creates /tmp/keepalived.log and has it open\nfor read (e.g. tail -f), then even though keepalived will change the\nowner to root and remove all read/write permissions from non owners,\nthe application which already has the file open will be able to read\nthe added log entries.\n\nAccordingly, opening a file in append mode is disabled by default, and\nonly enabled if --enable-smtp-alert-debug or --enable-log-file (which\nare debugging options and unset by default) are enabled.\n\nThis should further alleviate security concerns related to CVE-2018-19046.\n\nSigned-off-by: Quentin Armitage '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: w64_read_header\t(SF_PRIVATE *psf, int *blockalign, int *framesperblock)\n{\tWAVLIKE_PRIVATE *wpriv ;\n\tWAV_FMT \t*wav_fmt ;\n\tint\t\t\tdword = 0, marker, format = 0 ;\n\tsf_count_t\tchunk_size, bytesread = 0 ;\n\tint\t\t\tparsestage = 0, error, done = 0 ;\n\n\tif ((wpriv = psf->container_data) == NULL)\n\t\treturn SFE_INTERNAL ;\n\twav_fmt = &wpriv->wav_fmt ;\n\n\t/* Set position to start of file to begin reading header. */\n\tpsf_binheader_readf (psf, \"p\", 0) ;\n\n\twhile (! done)\n\t{\t/* Each new chunk must start on an 8 byte boundary, so jump if needed. */\n\t\tif (psf->header.indx & 0x7)\n\t\t\tpsf_binheader_readf (psf, \"j\", 8 - (psf->header.indx & 0x7)) ;\n\n\t\t/* Generate hash of 16 byte marker. */\n\t\tmarker = chunk_size = 0 ;\n\t\tbytesread = psf_binheader_readf (psf, \"eh8\", &marker, &chunk_size) ;\n\t\tif (bytesread == 0)\n\t\t\tbreak ;\n\t\tswitch (marker)\n\t\t{\tcase riff_HASH16 :\n\t\t\t\t\tif (parsestage)\n\t\t\t\t\t\treturn SFE_W64_NO_RIFF ;\n\n\t\t\t\t\tif (psf->filelength != chunk_size)\n\t\t\t\t\t\tpsf_log_printf (psf, \"riff : %D (should be %D)\\n\", chunk_size, psf->filelength) ;\n\t\t\t\t\telse\n\t\t\t\t\t\tpsf_log_printf (psf, \"riff : %D\\n\", chunk_size) ;\n\n\t\t\t\t\tparsestage |= HAVE_riff ;\n\n\t\t\t\t\tbytesread += psf_binheader_readf (psf, \"h\", &marker) ;\n\t\t\t\t\tif (marker == wave_HASH16)\n\t\t\t\t\t{ \tif ((parsestage & HAVE_riff) != HAVE_riff)\n\t\t\t\t\t\t\treturn SFE_W64_NO_WAVE ;\n\t\t\t\t\t\tpsf_log_printf (psf, \"wave\\n\") ;\n\t\t\t\t\t\tparsestage |= HAVE_wave ;\n\t\t\t\t\t} ;\n\t\t\t\t\tchunk_size = 0 ;\n\t\t\t\t\tbreak ;\n\n\t\t\tcase ACID_HASH16:\n\t\t\t\t\tpsf_log_printf (psf, \"Looks like an ACID file. Exiting.\\n\") ;\n\t\t\t\t\treturn SFE_UNIMPLEMENTED ;\n\n\t\t\tcase fmt_HASH16 :\n\t\t\t\t\tif ((parsestage & (HAVE_riff | HAVE_wave)) != (HAVE_riff | HAVE_wave))\n\t\t\t\t\t\treturn SFE_WAV_NO_FMT ;\n\n\t\t\t\t\tpsf_log_printf (psf, \" fmt : %D\\n\", chunk_size) ;\n\n\t\t\t\t\t/* size of 16 byte marker and 8 byte chunk_size value. */\n\t\t\t\t\tchunk_size -= 24 ;\n\n\t\t\t\t\tif ((error = wavlike_read_fmt_chunk (psf, (int) chunk_size)))\n\t\t\t\t\t\treturn error ;\n\n\t\t\t\t\tif (chunk_size % 8)\n\t\t\t\t\t\tpsf_binheader_readf (psf, \"j\", 8 - (chunk_size % 8)) ;\n\n\t\t\t\t\tformat\t\t= wav_fmt->format ;\n\t\t\t\t\tparsestage |= HAVE_fmt ;\n\t\t\t\t\tchunk_size = 0 ;\n\t\t\t\t\tbreak ;\n\n\t\t\tcase fact_HASH16:\n\t\t\t\t\t{\tsf_count_t frames ;\n\n\t\t\t\t\t\tpsf_binheader_readf (psf, \"e8\", &frames) ;\n\t\t\t\t\t\tpsf_log_printf (psf, \"fact : %D\\n frames : %D\\n\",\n\t\t\t\t\t\t\t\t\t\tchunk_size, frames) ;\n\t\t\t\t\t\t} ;\n\t\t\t\t\tchunk_size = 0 ;\n\t\t\t\t\tbreak ;\n\n\n\t\t\tcase data_HASH16 :\n\t\t\t\t\tif ((parsestage & (HAVE_riff | HAVE_wave | HAVE_fmt)) != (HAVE_riff | HAVE_wave | HAVE_fmt))\n\t\t\t\t\t\treturn SFE_W64_NO_DATA ;\n\n\t\t\t\t\tpsf->dataoffset = psf_ftell (psf) ;\n\t\t\t\t\tpsf->datalength = SF_MIN (chunk_size - 24, psf->filelength - psf->dataoffset) ;\n\n\t\t\t\t\tif (chunk_size % 8)\n\t\t\t\t\t\tchunk_size += 8 - (chunk_size % 8) ;\n\n\t\t\t\t\tpsf_log_printf (psf, \"data : %D\\n\", chunk_size) ;\n\n\t\t\t\t\tparsestage |= HAVE_data ;\n\n\t\t\t\t\tif (! psf->sf.seekable)\n\t\t\t\t\t\tbreak ;\n\n\t\t\t\t\t/* Seek past data and continue reading header. */\n\t\t\t\t\tpsf_fseek (psf, chunk_size, SEEK_CUR) ;\n\t\t\t\t\tchunk_size = 0 ;\n\t\t\t\t\tbreak ;\n\n\t\t\tcase levl_HASH16 :\n\t\t\t\t\tpsf_log_printf (psf, \"levl : %D\\n\", chunk_size) ;\n\t\t\t\t\tchunk_size -= 24 ;\n\t\t\t\t\tbreak ;\n\n\t\t\tcase list_HASH16 :\n\t\t\t\t\tpsf_log_printf (psf, \"list : %D\\n\", chunk_size) ;\n\t\t\t\t\tchunk_size -= 24 ;\n\t\t\t\t\tbreak ;\n\n\t\t\tcase junk_HASH16 :\n\t\t\t\t\tpsf_log_printf (psf, \"junk : %D\\n\", chunk_size) ;\n\t\t\t\t\tchunk_size -= 24 ;\n\t\t\t\t\tbreak ;\n\n\t\t\tcase bext_HASH16 :\n\t\t\t\t\tpsf_log_printf (psf, \"bext : %D\\n\", chunk_size) ;\n\t\t\t\t\tchunk_size -= 24 ;\n\t\t\t\t\tbreak ;\n\n\t\t\tcase MARKER_HASH16 :\n\t\t\t\t\tpsf_log_printf (psf, \"marker : %D\\n\", chunk_size) ;\n\t\t\t\t\tchunk_size -= 24 ;\n\t\t\t\t\tbreak ;\n\n\t\t\tcase SUMLIST_HASH16 :\n\t\t\t\t\tpsf_log_printf (psf, \"summary list : %D\\n\", chunk_size) ;\n\t\t\t\t\tchunk_size -= 24 ;\n\t\t\t\t\tbreak ;\n\n\t\t\tdefault :\n\t\t\t\t\tpsf_log_printf (psf, \"*** Unknown chunk marker (%X) at position %D with length %D. Exiting parser.\\n\", marker, psf_ftell (psf) - 8, chunk_size) ;\n\t\t\t\t\tdone = SF_TRUE ;\n\t\t\t\t\tbreak ;\n\t\t\t} ;\t/* switch (dword) */\n\n\t\tif (chunk_size >= psf->filelength)\n\t\t{\tpsf_log_printf (psf, \"*** Chunk size %u > file length %D. Exiting parser.\\n\", chunk_size, psf->filelength) ;\n\t\t\tbreak ;\n\t\t\t} ;\n\n\t\tif (psf->sf.seekable == 0 && (parsestage & HAVE_data))\n\t\t\tbreak ;\n\n\t\tif (psf_ftell (psf) >= (psf->filelength - (2 * SIGNED_SIZEOF (dword))))\n\t\t\tbreak ;\n\n\t\tif (chunk_size > 0 && chunk_size < 0xffff0000)\n\t\t{\tdword = chunk_size ;\n\t\t\tpsf_binheader_readf (psf, \"j\", dword - 24) ;\n\t\t\t} ;\n\t\t} ; /* while (1) */\n\n\tif (psf->dataoffset <= 0)\n\t\treturn SFE_W64_NO_DATA ;\n\n\tif (psf->sf.channels < 1)\n\t\treturn SFE_CHANNEL_COUNT_ZERO ;\n\n\tif (psf->sf.channels >= SF_MAX_CHANNELS)\n\t\treturn SFE_CHANNEL_COUNT ;\n\n\tpsf->endian = SF_ENDIAN_LITTLE ;\t\t/* All W64 files are little endian. */\n\n\tif (psf_ftell (psf) != psf->dataoffset)\n\t\tpsf_fseek (psf, psf->dataoffset, SEEK_SET) ;\n\n\tif (psf->blockwidth)\n\t{\tif (psf->filelength - psf->dataoffset < psf->datalength)\n\t\t\tpsf->sf.frames = (psf->filelength - psf->dataoffset) / psf->blockwidth ;\n\t\telse\n\t\t\tpsf->sf.frames = psf->datalength / psf->blockwidth ;\n\t\t} ;\n\n\tswitch (format)\n\t{\tcase WAVE_FORMAT_PCM :\n\t\tcase WAVE_FORMAT_EXTENSIBLE :\n\t\t\t\t\t/* extensible might be FLOAT, MULAW, etc as well! */\n\t\t\t\t\tpsf->sf.format = SF_FORMAT_W64 | u_bitwidth_to_subformat (psf->bytewidth * 8) ;\n\t\t\t\t\tbreak ;\n\n\t\tcase WAVE_FORMAT_MULAW :\n\t\t\t\t\tpsf->sf.format = (SF_FORMAT_W64 | SF_FORMAT_ULAW) ;\n\t\t\t\t\tbreak ;\n\n\t\tcase WAVE_FORMAT_ALAW :\n\t\t\t\t\tpsf->sf.format = (SF_FORMAT_W64 | SF_FORMAT_ALAW) ;\n\t\t\t\t\tbreak ;\n\n\t\tcase WAVE_FORMAT_MS_ADPCM :\n\t\t\t\t\tpsf->sf.format = (SF_FORMAT_W64 | SF_FORMAT_MS_ADPCM) ;\n\t\t\t\t\t*blockalign = wav_fmt->msadpcm.blockalign ;\n\t\t\t\t\t*framesperblock = wav_fmt->msadpcm.samplesperblock ;\n\t\t\t\t\tbreak ;\n\n\t\tcase WAVE_FORMAT_IMA_ADPCM :\n\t\t\t\t\tpsf->sf.format = (SF_FORMAT_W64 | SF_FORMAT_IMA_ADPCM) ;\n\t\t\t\t\t*blockalign = wav_fmt->ima.blockalign ;\n\t\t\t\t\t*framesperblock = wav_fmt->ima.samplesperblock ;\n\t\t\t\t\tbreak ;\n\n\t\tcase WAVE_FORMAT_GSM610 :\n\t\t\t\t\tpsf->sf.format = (SF_FORMAT_W64 | SF_FORMAT_GSM610) ;\n\t\t\t\t\tbreak ;\n\n\t\tcase WAVE_FORMAT_IEEE_FLOAT :\n\t\t\t\t\tpsf->sf.format = SF_FORMAT_W64 ;\n\t\t\t\t\tpsf->sf.format |= (psf->bytewidth == 8) ? SF_FORMAT_DOUBLE : SF_FORMAT_FLOAT ;\n\t\t\t\t\tbreak ;\n\n\t\tdefault : return SFE_UNIMPLEMENTED ;\n\t\t} ;\n\n\treturn 0 ;\n} /* w64_read_header */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fix max channel count bug\n\nThe code was allowing files to be written with a channel count of exactly\n`SF_MAX_CHANNELS` but was failing to read some file formats with the same\nchannel count.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int read_next_sample(int ifd, int action, int curr, char *file, int *rtype, int tab,\n\t\t struct file_magic *file_magic, struct file_activity *file_actlst,\n\t\t struct tm *rectime, struct tm *loctime, int oneof)\n{\n\tint rc;\n\tchar rec_hdr_tmp[MAX_RECORD_HEADER_SIZE];\n\n\t/* Read current record */\n\tif ((rc = read_record_hdr(ifd, rec_hdr_tmp, &record_hdr[curr], &file_hdr,\n\t\t\t arch_64, endian_mismatch, oneof)) != 0)\n\t\t/* End of sa file */\n\t\treturn rc;\n\n\t*rtype = record_hdr[curr].record_type;\n\n\tif (*rtype == R_COMMENT) {\n\t\tif (action & IGNORE_COMMENT) {\n\t\t\t/* Ignore COMMENT record */\n\t\t\tif (lseek(ifd, MAX_COMMENT_LEN, SEEK_CUR) < MAX_COMMENT_LEN) {\n\t\t\t\tperror(\"lseek\");\n\t\t\t\tif (oneof == UEOF_CONT)\n\t\t\t\t\treturn 2;\n\t\t\t\tclose(ifd);\n\t\t\t\texit(2);\n\t\t\t}\n\t\t\tif (action & SET_TIMESTAMPS) {\n\t\t\t\tsa_get_record_timestamp_struct(flags, &record_hdr[curr],\n\t\t\t\t\t\t\t rectime, loctime);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t/* Display COMMENT record */\n\t\t\tprint_special_record(&record_hdr[curr], flags, &tm_start, &tm_end,\n\t\t\t\t\t *rtype, ifd, rectime, loctime, file, tab,\n\t\t\t\t\t file_magic, &file_hdr, act, fmt[f_position],\n\t\t\t\t\t endian_mismatch, arch_64);\n\t\t}\n\t}\n\telse if (*rtype == R_RESTART) {\n\t\tif (action & IGNORE_RESTART) {\n\t\t\t/*\n\t\t\t * Ignore RESTART record (don't display it)\n\t\t\t * but anyway we have to read the CPU number that follows it\n\t\t\t * (unless we don't want to do it now).\n\t\t\t */\n\t\t\tif (!(action & DONT_READ_CPU_NR)) {\n\t\t\t\tfile_hdr.sa_cpu_nr = read_nr_value(ifd, file, file_magic,\n\t\t\t\t\t\t\t\t endian_mismatch, arch_64, TRUE);\n\t\t\t}\n\t\t\tif (action & SET_TIMESTAMPS) {\n\t\t\t\tsa_get_record_timestamp_struct(flags, &record_hdr[curr],\n\t\t\t\t\t\t\t rectime, loctime);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t/* Display RESTART record */\n\t\t\tprint_special_record(&record_hdr[curr], flags, &tm_start, &tm_end,\n\t\t\t\t\t *rtype, ifd, rectime, loctime, file, tab,\n\t\t\t\t\t file_magic, &file_hdr, act, fmt[f_position],\n\t\t\t\t\t endian_mismatch, arch_64);\n\t\t}\n\t}\n\telse {\n\t\t/*\n\t\t * OK: Previous record was not a special one.\n\t\t * So read now the extra fields.\n\t\t */\n\t\tif (read_file_stat_bunch(act, curr, ifd, file_hdr.sa_act_nr, file_actlst,\n\t\t\t\t\t endian_mismatch, arch_64, file, file_magic, oneof) > 0)\n\t\t\treturn 2;\n\t\tsa_get_record_timestamp_struct(flags, &record_hdr[curr], rectime, loctime);\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix #196 and #199: Out of bound reads security issues\n\nCheck args before calling memmove() and memset() in remap_struct()\nfunction to avoid out of bound reads which would possibly lead to\nunknown code execution and/or sadf command crash.\n\nSigned-off-by: Sebastien GODARD '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static char* set_iovec_field_free(struct iovec *iovec, size_t *n_iovec, const char *field, char *value) {\n char *x;\n\n x = set_iovec_field(iovec, n_iovec, field, value);\n free(value);\n return x;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-770'], 'message': 'journald: do not store the iovec entry for process commandline on stack\n\nThis fixes a crash where we would read the commandline, whose length is under\ncontrol of the sending program, and then crash when trying to create a stack\nallocation for it.\n\nCVE-2018-16864\nhttps://bugzilla.redhat.com/show_bug.cgi?id=1653855\n\nThe message actually doesn't get written to disk, because\njournal_file_append_entry() returns -E2BIG.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int main(void) {\n test_syslog_parse_identifier(\"pidu[111]: xxx\", \"pidu\", \"111\", 11);\n test_syslog_parse_identifier(\"pidu: xxx\", \"pidu\", NULL, 6);\n test_syslog_parse_identifier(\"pidu: xxx\", \"pidu\", NULL, 7);\n test_syslog_parse_identifier(\"pidu xxx\", NULL, NULL, 0);\n test_syslog_parse_identifier(\":\", \"\", NULL, 1);\n test_syslog_parse_identifier(\": \", \"\", NULL, 3);\n test_syslog_parse_identifier(\"pidu:\", \"pidu\", NULL, 5);\n test_syslog_parse_identifier(\"pidu: \", \"pidu\", NULL, 6);\n test_syslog_parse_identifier(\"pidu : \", NULL, NULL, 0);\n\n test_syslog_parse_priority(\"<>\", 0, 0);\n test_syslog_parse_priority(\"<>aaa\", 0, 0);\n test_syslog_parse_priority(\"\", 0, 0);\n test_syslog_parse_priority(\"aaa\", 0, 0);\n test_syslog_parse_priority(\" \", 0, 0);\n test_syslog_parse_priority(\" aaa\", 0, 0);\n /* TODO: add test cases of valid priorities */\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'journal: do not remove multiple spaces after identifier in syslog message\n\nSingle space is used as separator.\nC.f. discussions in #156.\n\nFixes #9839 introduced by a6aadf4ae0bae185dc4c414d492a4a781c80ffe5.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: sub_font_params(gs_memory_t *mem, const ref *op, gs_matrix *pmat, gs_matrix *pomat, ref *pfname)\n{\n ref *pmatrix, *pfontname, *pfontstyle, *porigfont, *pfontinfo;\n\n if (dict_find_string(op, \"FontMatrix\", &pmatrix) <= 0 ||\n read_matrix(mem, pmatrix, pmat) < 0\n )\n return_error(gs_error_invalidfont);\n if (dict_find_string(op, \"OrigFont\", &porigfont) <= 0)\n porigfont = NULL;\n if (pomat!= NULL) {\n if (porigfont == NULL ||\n dict_find_string(porigfont, \"FontMatrix\", &pmatrix) <= 0 ||\n read_matrix(mem, pmatrix, pomat) < 0\n )\n memset(pomat, 0, sizeof(*pomat));\n }\n /* Use the FontInfo/OrigFontName key preferrentially (created by MS PSCRIPT driver) */\n if ((dict_find_string((porigfont != NULL ? porigfont : op), \"FontInfo\", &pfontinfo) > 0) &&\n r_has_type(pfontinfo, t_dictionary) &&\n (dict_find_string(pfontinfo, \"OrigFontName\", &pfontname) > 0)) {\n if ((dict_find_string(pfontinfo, \"OrigFontStyle\", &pfontstyle) > 0) &&\n r_size(pfontstyle) > 0) {\n const byte *tmpStr1 = pfontname->value.const_bytes;\n const byte *tmpStr2 = pfontstyle->value.const_bytes;\n int fssize1 = r_size(pfontname), fssize2 = r_size(pfontstyle), fssize = fssize1 + fssize2 + 1;\n byte *sfname = gs_alloc_string(mem, fssize, \"sub_font_params\");\n\n if (sfname == NULL)\n return_error(gs_error_VMerror);\n memcpy(sfname, tmpStr1, fssize1);\n sfname[fssize1]=',' ;\n memcpy(sfname + fssize1 + 1, tmpStr2, fssize2);\n make_string(pfname, a_readonly, fssize, sfname);\n } else\n get_font_name(mem, pfname, pfontname);\n } else if (dict_find_string((porigfont != NULL ? porigfont : op), \".Alias\", &pfontname) > 0) {\n /* If we emulate the font, we want the requested name rather than a substitute. */\n get_font_name(mem, pfname, pfontname);\n } else if (dict_find_string((porigfont != NULL ? porigfont : op), \"FontName\", &pfontname) > 0) {\n get_font_name(mem, pfname, pfontname);\n } else\n make_empty_string(pfname, a_readonly);\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-704'], 'message': 'PS interpreter - add some type checking\n\nThese were 'probably' safe anyway, since they mostly treat the objects\nas integers without checking, which at least can't result in a crash.\n\nNevertheless, we ought to check.\n\nThe return from comparedictkeys could be wrong if one of the keys had\na value which was not an array, it could incorrectly decide the two\nwere in fact the same.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: zcrd1_params(os_ptr op, gs_cie_render * pcrd,\n ref_cie_render_procs * pcprocs, gs_memory_t * mem)\n{\n int code;\n int ignore;\n gx_color_lookup_table *const prtl = &pcrd->RenderTable.lookup;\n ref *pRT;\n\n if ((code = dict_int_param(op, \"ColorRenderingType\", 1, 1, 0, &ignore)) < 0)\n return code;\n if ((code = zcrd1_proc_params(mem, op, pcprocs)) < 0)\n return code;\n\n if ((code = dict_matrix3_param(mem, op, \"MatrixLMN\", &pcrd->MatrixLMN)) < 0)\n return code;\n if ((code = dict_range3_param(mem, op, \"RangeLMN\", &pcrd->RangeLMN)) < 0)\n return code;\n if ((code = dict_matrix3_param(mem, op, \"MatrixABC\", &pcrd->MatrixABC)) < 0)\n return code;\n if ((code = dict_range3_param(mem, op, \"RangeABC\", &pcrd->RangeABC)) < 0)\n return code;\n if ((code = cie_points_param(mem, op, &pcrd->points)) < 0)\n return code;\n if ((code = dict_matrix3_param(mem, op, \"MatrixPQR\", &pcrd->MatrixPQR)) < 0)\n return code;\n if ((code = dict_range3_param(mem,op, \"RangePQR\", &pcrd->RangePQR)) < 0)\n return code;\n\n if (dict_find_string(op, \"RenderTable\", &pRT) > 0) {\n const ref *prte = pRT->value.const_refs;\n\n /* Finish unpacking and checking the RenderTable parameter. */\n check_type_only(prte[4], t_integer);\n if (!(prte[4].value.intval == 3 || prte[4].value.intval == 4))\n return_error(gs_error_rangecheck);\n prtl->n = 3;\n prtl->m = prte[4].value.intval;\n if (r_size(pRT) != prtl->m + 5)\n return_error(gs_error_rangecheck);\n code = cie_table_param(pRT, prtl, mem);\n if (code < 0)\n return code;\n } else {\n prtl->table = 0;\n }\n pcrd->EncodeLMN = Encode_default;\n pcrd->EncodeABC = Encode_default;\n pcrd->TransformPQR = TransformPQR_default;\n pcrd->RenderTable.T = RenderTableT_default;\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-704'], 'message': 'PS interpreter - add some type checking\n\nThese were 'probably' safe anyway, since they mostly treat the objects\nas integers without checking, which at least can't result in a crash.\n\nNevertheless, we ought to check.\n\nThe return from comparedictkeys could be wrong if one of the keys had\na value which was not an array, it could incorrectly decide the two\nwere in fact the same.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int usb_audio_probe(struct usb_interface *intf,\n\t\t\t const struct usb_device_id *usb_id)\n{\n\tstruct usb_device *dev = interface_to_usbdev(intf);\n\tconst struct snd_usb_audio_quirk *quirk =\n\t\t(const struct snd_usb_audio_quirk *)usb_id->driver_info;\n\tstruct snd_usb_audio *chip;\n\tint i, err;\n\tstruct usb_host_interface *alts;\n\tint ifnum;\n\tu32 id;\n\n\talts = &intf->altsetting[0];\n\tifnum = get_iface_desc(alts)->bInterfaceNumber;\n\tid = USB_ID(le16_to_cpu(dev->descriptor.idVendor),\n\t\t le16_to_cpu(dev->descriptor.idProduct));\n\tif (get_alias_id(dev, &id))\n\t\tquirk = get_alias_quirk(dev, id);\n\tif (quirk && quirk->ifnum >= 0 && ifnum != quirk->ifnum)\n\t\treturn -ENXIO;\n\n\terr = snd_usb_apply_boot_quirk(dev, intf, quirk, id);\n\tif (err < 0)\n\t\treturn err;\n\n\t/*\n\t * found a config. now register to ALSA\n\t */\n\n\t/* check whether it's already registered */\n\tchip = NULL;\n\tmutex_lock(®ister_mutex);\n\tfor (i = 0; i < SNDRV_CARDS; i++) {\n\t\tif (usb_chip[i] && usb_chip[i]->dev == dev) {\n\t\t\tif (atomic_read(&usb_chip[i]->shutdown)) {\n\t\t\t\tdev_err(&dev->dev, \"USB device is in the shutdown state, cannot create a card instance\\n\");\n\t\t\t\terr = -EIO;\n\t\t\t\tgoto __error;\n\t\t\t}\n\t\t\tchip = usb_chip[i];\n\t\t\tatomic_inc(&chip->active); /* avoid autopm */\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (! chip) {\n\t\t/* it's a fresh one.\n\t\t * now look for an empty slot and create a new card instance\n\t\t */\n\t\tfor (i = 0; i < SNDRV_CARDS; i++)\n\t\t\tif (!usb_chip[i] &&\n\t\t\t (vid[i] == -1 || vid[i] == USB_ID_VENDOR(id)) &&\n\t\t\t (pid[i] == -1 || pid[i] == USB_ID_PRODUCT(id))) {\n\t\t\t\tif (enable[i]) {\n\t\t\t\t\terr = snd_usb_audio_create(intf, dev, i, quirk,\n\t\t\t\t\t\t\t\t id, &chip);\n\t\t\t\t\tif (err < 0)\n\t\t\t\t\t\tgoto __error;\n\t\t\t\t\tchip->pm_intf = intf;\n\t\t\t\t\tbreak;\n\t\t\t\t} else if (vid[i] != -1 || pid[i] != -1) {\n\t\t\t\t\tdev_info(&dev->dev,\n\t\t\t\t\t\t \"device (%04x:%04x) is disabled\\n\",\n\t\t\t\t\t\t USB_ID_VENDOR(id),\n\t\t\t\t\t\t USB_ID_PRODUCT(id));\n\t\t\t\t\terr = -ENOENT;\n\t\t\t\t\tgoto __error;\n\t\t\t\t}\n\t\t\t}\n\t\tif (!chip) {\n\t\t\tdev_err(&dev->dev, \"no available usb audio device\\n\");\n\t\t\terr = -ENODEV;\n\t\t\tgoto __error;\n\t\t}\n\t}\n\tdev_set_drvdata(&dev->dev, chip);\n\n\t/*\n\t * For devices with more than one control interface, we assume the\n\t * first contains the audio controls. We might need a more specific\n\t * check here in the future.\n\t */\n\tif (!chip->ctrl_intf)\n\t\tchip->ctrl_intf = alts;\n\n\tchip->txfr_quirk = 0;\n\terr = 1; /* continue */\n\tif (quirk && quirk->ifnum != QUIRK_NO_INTERFACE) {\n\t\t/* need some special handlings */\n\t\terr = snd_usb_create_quirk(chip, intf, &usb_audio_driver, quirk);\n\t\tif (err < 0)\n\t\t\tgoto __error;\n\t}\n\n\tif (err > 0) {\n\t\t/* create normal USB audio interfaces */\n\t\terr = snd_usb_create_streams(chip, ifnum);\n\t\tif (err < 0)\n\t\t\tgoto __error;\n\t\terr = snd_usb_create_mixer(chip, ifnum, ignore_ctl_error);\n\t\tif (err < 0)\n\t\t\tgoto __error;\n\t}\n\n\t/* we are allowed to call snd_card_register() many times */\n\terr = snd_card_register(chip->card);\n\tif (err < 0)\n\t\tgoto __error;\n\n\tusb_chip[chip->index] = chip;\n\tchip->num_interfaces++;\n\tusb_set_intfdata(intf, chip);\n\tatomic_dec(&chip->active);\n\tmutex_unlock(®ister_mutex);\n\treturn 0;\n\n __error:\n\tif (chip) {\n\t\tif (!chip->num_interfaces)\n\t\t\tsnd_card_free(chip->card);\n\t\tatomic_dec(&chip->active);\n\t}\n\tmutex_unlock(®ister_mutex);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'ALSA: usb-audio: Fix UAF decrement if card has no live interfaces in card.c\n\nIf a USB sound card reports 0 interfaces, an error condition is triggered\nand the function usb_audio_probe errors out. In the error path, there was a\nuse-after-free vulnerability where the memory object of the card was first\nfreed, followed by a decrement of the number of active chips. Moving the\ndecrement above the atomic_dec fixes the UAF.\n\n[ The original problem was introduced in 3.1 kernel, while it was\n developed in a different form. The Fixes tag below indicates the\n original commit but it doesn't mean that the patch is applicable\n cleanly. -- tiwai ]\n\nFixes: 362e4e49abe5 (\"ALSA: usb-audio - clear chip->probing on error exit\")\nReported-by: Hui Peng \nReported-by: Mathias Payer \nSigned-off-by: Hui Peng \nSigned-off-by: Mathias Payer \nCc: \nSigned-off-by: Takashi Iwai '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int crypto_report_comp(struct sk_buff *skb, struct crypto_alg *alg)\n{\n\tstruct crypto_report_comp rcomp;\n\n\tstrlcpy(rcomp.type, \"compression\", sizeof(rcomp.type));\n\tif (nla_put(skb, CRYPTOCFGA_REPORT_COMPRESS,\n\t\t sizeof(struct crypto_report_comp), &rcomp))\n\t\tgoto nla_put_failure;\n\treturn 0;\n\nnla_put_failure:\n\treturn -EMSGSIZE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'crypto: user - fix leaking uninitialized memory to userspace\n\nAll bytes of the NETLINK_CRYPTO report structures must be initialized,\nsince they are copied to userspace. The change from strncpy() to\nstrlcpy() broke this. As a minimal fix, change it back.\n\nFixes: 4473710df1f8 (\"crypto: user - Prepare for CRYPTO_MAX_ALG_NAME expansion\")\nCc: # v4.12+\nSigned-off-by: Eric Biggers \nSigned-off-by: Herbert Xu '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: wav_read_smpl_chunk (SF_PRIVATE *psf, uint32_t chunklen)\n{\tchar buffer [512] ;\n\tuint32_t thisread, bytesread = 0, dword, sampler_data, loop_count ;\n\tuint32_t note, pitch, start, end, type = -1, count ;\n\tint j, k ;\n\n\tchunklen += (chunklen & 1) ;\n\n\tbytesread += psf_binheader_readf (psf, \"4\", &dword) ;\n\tpsf_log_printf (psf, \" Manufacturer : %X\\n\", dword) ;\n\n\tbytesread += psf_binheader_readf (psf, \"4\", &dword) ;\n\tpsf_log_printf (psf, \" Product : %u\\n\", dword) ;\n\n\tbytesread += psf_binheader_readf (psf, \"4\", &dword) ;\n\tpsf_log_printf (psf, \" Period : %u nsec\\n\", dword) ;\n\n\tbytesread += psf_binheader_readf (psf, \"4\", ¬e) ;\n\tpsf_log_printf (psf, \" Midi Note : %u\\n\", note) ;\n\n\tbytesread += psf_binheader_readf (psf, \"4\", &pitch) ;\n\tif (pitch != 0)\n\t{\tsnprintf (buffer, sizeof (buffer), \"%f\",\n\t\t\t\t\t(1.0 * 0x80000000) / ((uint32_t) pitch)) ;\n\t\tpsf_log_printf (psf, \" Pitch Fract. : %s\\n\", buffer) ;\n\t\t}\n\telse\n\t\tpsf_log_printf (psf, \" Pitch Fract. : 0\\n\") ;\n\n\tbytesread += psf_binheader_readf (psf, \"4\", &dword) ;\n\tpsf_log_printf (psf, \" SMPTE Format : %u\\n\", dword) ;\n\n\tbytesread += psf_binheader_readf (psf, \"4\", &dword) ;\n\tsnprintf (buffer, sizeof (buffer), \"%02d:%02d:%02d %02d\",\n\t\t\t\t(dword >> 24) & 0x7F, (dword >> 16) & 0x7F, (dword >> 8) & 0x7F, dword & 0x7F) ;\n\tpsf_log_printf (psf, \" SMPTE Offset : %s\\n\", buffer) ;\n\n\tbytesread += psf_binheader_readf (psf, \"4\", &loop_count) ;\n\tpsf_log_printf (psf, \" Loop Count : %u\\n\", loop_count) ;\n\n\tif (loop_count == 0 && chunklen == bytesread)\n\t\treturn 0 ;\n\n\t/* Sampler Data holds the number of data bytes after the CUE chunks which\n\t** is not actually CUE data. Display value after CUE data.\n\t*/\n\tbytesread += psf_binheader_readf (psf, \"4\", &sampler_data) ;\n\n\tif ((psf->instrument = psf_instrument_alloc ()) == NULL)\n\t\treturn SFE_MALLOC_FAILED ;\n\n\tpsf->instrument->loop_count = loop_count ;\n\n\tfor (j = 0 ; loop_count > 0 && chunklen - bytesread >= 24 ; j ++)\n\t{\tif ((thisread = psf_binheader_readf (psf, \"4\", &dword)) == 0)\n\t\t\tbreak ;\n\t\tbytesread += thisread ;\n\t\tpsf_log_printf (psf, \" Cue ID : %2u\", dword) ;\n\n\t\tbytesread += psf_binheader_readf (psf, \"4\", &type) ;\n\t\tpsf_log_printf (psf, \" Type : %2u\", type) ;\n\n\t\tbytesread += psf_binheader_readf (psf, \"4\", &start) ;\n\t\tpsf_log_printf (psf, \" Start : %5u\", start) ;\n\n\t\tbytesread += psf_binheader_readf (psf, \"4\", &end) ;\n\t\tpsf_log_printf (psf, \" End : %5u\", end) ;\n\n\t\tbytesread += psf_binheader_readf (psf, \"4\", &dword) ;\n\t\tpsf_log_printf (psf, \" Fraction : %5u\", dword) ;\n\n\t\tbytesread += psf_binheader_readf (psf, \"4\", &count) ;\n\t\tpsf_log_printf (psf, \" Count : %5u\\n\", count) ;\n\n\t\tif (j < ARRAY_LEN (psf->instrument->loops))\n\t\t{\tpsf->instrument->loops [j].start = start ;\n\t\t\tpsf->instrument->loops [j].end = end + 1 ;\n\t\t\tpsf->instrument->loops [j].count = count ;\n\n\t\t\tswitch (type)\n\t\t\t{\tcase 0 :\n\t\t\t\t\tpsf->instrument->loops [j].mode = SF_LOOP_FORWARD ;\n\t\t\t\t\tbreak ;\n\t\t\t\tcase 1 :\n\t\t\t\t\tpsf->instrument->loops [j].mode = SF_LOOP_ALTERNATING ;\n\t\t\t\t\tbreak ;\n\t\t\t\tcase 2 :\n\t\t\t\t\tpsf->instrument->loops [j].mode = SF_LOOP_BACKWARD ;\n\t\t\t\t\tbreak ;\n\t\t\t\tdefault:\n\t\t\t\t\tpsf->instrument->loops [j].mode = SF_LOOP_NONE ;\n\t\t\t\t\tbreak ;\n\t\t\t\t} ;\n\t\t\t} ;\n\n\t\tloop_count -- ;\n\t\t} ;\n\n\tif (chunklen - bytesread == 0)\n\t{\tif (sampler_data != 0)\n\t\t\tpsf_log_printf (psf, \" Sampler Data : %u (should be 0)\\n\", sampler_data) ;\n\t\telse\n\t\t\tpsf_log_printf (psf, \" Sampler Data : %u\\n\", sampler_data) ;\n\t\t}\n\telse\n\t{\tif (sampler_data != chunklen - bytesread)\n\t\t{\tpsf_log_printf (psf, \" Sampler Data : %u (should have been %u)\\n\", sampler_data, chunklen - bytesread) ;\n\t\t\tsampler_data = chunklen - bytesread ;\n\t\t\t}\n\t\telse\n\t\t\tpsf_log_printf (psf, \" Sampler Data : %u\\n\", sampler_data) ;\n\n\t\tpsf_log_printf (psf, \" \") ;\n\t\tfor (k = 0 ; k < (int) sampler_data ; k++)\n\t\t{\tchar ch ;\n\n\t\t\tif (k > 0 && (k % 20) == 0)\n\t\t\t\tpsf_log_printf (psf, \"\\n \") ;\n\n\t\t\tif ((thisread = psf_binheader_readf (psf, \"1\", &ch)) == 0)\n\t\t\t\tbreak ;\n\t\t\tbytesread += thisread ;\n\t\t\tpsf_log_printf (psf, \"%02X \", ch & 0xFF) ;\n\t\t\t} ;\n\n\t\tpsf_log_printf (psf, \"\\n\") ;\n\t\t} ;\n\n\tpsf->instrument->basenote = note ;\n\tpsf->instrument->detune = (int8_t)(pitch / (0x40000000 / 25.0) + 0.5) ;\n\tpsf->instrument->gain = 1 ;\n\tpsf->instrument->velocity_lo = psf->instrument->key_lo = 0 ;\n\tpsf->instrument->velocity_hi = psf->instrument->key_hi = 127 ;\n\n\treturn 0 ;\n} /* wav_read_smpl_chunk */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'src/wav.c: Fix heap read overflow\n\nThis is CVE-2018-19758.\n\nCloses: https://github.com/erikd/libsndfile/issues/435'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: rfbHandleAuthResult(rfbClient* client)\n{\n uint32_t authResult=0, reasonLen=0;\n char *reason=NULL;\n\n if (!ReadFromRFBServer(client, (char *)&authResult, 4)) return FALSE;\n\n authResult = rfbClientSwap32IfLE(authResult);\n\n switch (authResult) {\n case rfbVncAuthOK:\n rfbClientLog(\"VNC authentication succeeded\\n\");\n return TRUE;\n break;\n case rfbVncAuthFailed:\n if (client->major==3 && client->minor>7)\n {\n /* we have an error following */\n if (!ReadFromRFBServer(client, (char *)&reasonLen, 4)) return FALSE;\n reasonLen = rfbClientSwap32IfLE(reasonLen);\n reason = malloc(reasonLen+1);\n if (!ReadFromRFBServer(client, reason, reasonLen)) { free(reason); return FALSE; }\n reason[reasonLen]=0;\n rfbClientLog(\"VNC connection failed: %s\\n\",reason);\n free(reason);\n return FALSE;\n }\n rfbClientLog(\"VNC authentication failed\\n\");\n return FALSE;\n case rfbVncAuthTooMany:\n rfbClientLog(\"VNC authentication failed - too many tries\\n\");\n return FALSE;\n }\n\n rfbClientLog(\"Unknown VNC authentication result: %d\\n\",\n (int)authResult);\n return FALSE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'LibVNCClient: fix three possible heap buffer overflows\n\nAn attacker could feed `0xffffffff`, causing a `malloc(0)` for the\nbuffers which are subsequently written to.\n\nCloses #247'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: HandleUltraZipBPP (rfbClient* client, int rx, int ry, int rw, int rh)\n{\n rfbZlibHeader hdr;\n int i=0;\n int toRead=0;\n int inflateResult=0;\n unsigned char *ptr=NULL;\n lzo_uint uncompressedBytes = ry + (rw * 65535);\n unsigned int numCacheRects = rx;\n\n if (!ReadFromRFBServer(client, (char *)&hdr, sz_rfbZlibHeader))\n return FALSE;\n\n toRead = rfbClientSwap32IfLE(hdr.nBytes);\n\n if (toRead==0) return TRUE;\n\n if (uncompressedBytes==0)\n {\n rfbClientLog(\"ultrazip error: rectangle has 0 uncomressed bytes (%dy + (%dw * 65535)) (%d rectangles)\\n\", ry, rw, rx); \n return FALSE;\n }\n\n /* First make sure we have a large enough raw buffer to hold the\n * decompressed data. In practice, with a fixed BPP, fixed frame\n * buffer size and the first update containing the entire frame\n * buffer, this buffer allocation should only happen once, on the\n * first update.\n */\n if ( client->raw_buffer_size < (int)(uncompressedBytes + 500)) {\n if ( client->raw_buffer != NULL ) {\n free( client->raw_buffer );\n }\n client->raw_buffer_size = uncompressedBytes + 500;\n /* buffer needs to be aligned on 4-byte boundaries */\n if ((client->raw_buffer_size % 4)!=0)\n client->raw_buffer_size += (4-(client->raw_buffer_size % 4));\n client->raw_buffer = (char*) malloc( client->raw_buffer_size );\n }\n\n \n /* allocate enough space to store the incoming compressed packet */\n if ( client->ultra_buffer_size < toRead ) {\n if ( client->ultra_buffer != NULL ) {\n free( client->ultra_buffer );\n }\n client->ultra_buffer_size = toRead;\n client->ultra_buffer = (char*) malloc( client->ultra_buffer_size );\n }\n\n /* Fill the buffer, obtaining data from the server. */\n if (!ReadFromRFBServer(client, client->ultra_buffer, toRead))\n return FALSE;\n\n /* uncompress the data */\n uncompressedBytes = client->raw_buffer_size;\n inflateResult = lzo1x_decompress_safe(\n (lzo_byte *)client->ultra_buffer, toRead,\n (lzo_byte *)client->raw_buffer, &uncompressedBytes, NULL);\n if ( inflateResult != LZO_E_OK ) \n {\n rfbClientLog(\"ultra decompress returned error: %d\\n\",\n inflateResult);\n return FALSE;\n }\n \n /* Put the uncompressed contents of the update on the screen. */\n ptr = (unsigned char *)client->raw_buffer;\n for (i=0; iGotBitmap(client, (unsigned char *)ptr, sx, sy, sw, sh);\n ptr += ((sw * sh) * (BPP / 8));\n }\n } \n\n return TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'LibVNCClient: make sure Ultra decoding cannot dereference a null pointer\n\nCloses #254'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void CLASS parse_exif (int base)\n{\n unsigned kodak, entries, tag, type, len, save, c;\n double expo,ape;\n\n kodak = !strncmp(make,\"EASTMAN\",7) && tiff_nifds < 3;\n entries = get2();\n if(!strncmp(make,\"Hasselblad\",10) && (tiff_nifds > 3) && (entries > 512)) return;\n#ifdef LIBRAW_LIBRARY_BUILD\n INT64 fsize = ifp->size();\n#endif\n while (entries--) {\n tiff_get (base, &tag, &type, &len, &save);\n\n#ifdef LIBRAW_LIBRARY_BUILD\n INT64 savepos = ftell(ifp);\n if(len > 8 && savepos + len > fsize*2) continue;\n if(callbacks.exif_cb)\n {\n callbacks.exif_cb(callbacks.exifparser_data,tag,type,len,order,ifp);\n fseek(ifp,savepos,SEEK_SET);\n }\n#endif\n switch (tag) {\n#ifdef LIBRAW_LIBRARY_BUILD\n case 0xa405:\t\t// FocalLengthIn35mmFormat\n imgdata.lens.FocalLengthIn35mmFormat = get2();\n break;\n case 0xa431:\t\t// BodySerialNumber\n stmread(imgdata.shootinginfo.BodySerial, len, ifp);\n break;\n case 0xa432:\t\t// LensInfo, 42034dec, Lens Specification per EXIF standard\n imgdata.lens.MinFocal = getreal(type);\n imgdata.lens.MaxFocal = getreal(type);\n imgdata.lens.MaxAp4MinFocal = getreal(type);\n imgdata.lens.MaxAp4MaxFocal = getreal(type);\n break;\n case 0xa435:\t\t// LensSerialNumber\n stmread(imgdata.lens.LensSerial, len, ifp);\n break;\n case 0xc630:\t\t// DNG LensInfo, Lens Specification per EXIF standard\n imgdata.lens.dng.MinFocal = getreal(type);\n imgdata.lens.dng.MaxFocal = getreal(type);\n imgdata.lens.dng.MaxAp4MinFocal = getreal(type);\n imgdata.lens.dng.MaxAp4MaxFocal = getreal(type);\n break;\n case 0xa433:\t\t// LensMake\n stmread(imgdata.lens.LensMake, len, ifp);\n break;\n case 0xa434:\t\t// LensModel\n stmread(imgdata.lens.Lens, len, ifp);\n if (!strncmp(imgdata.lens.Lens, \"----\", 4))\n imgdata.lens.Lens[0] = 0;\n break;\n case 0x9205:\n imgdata.lens.EXIF_MaxAp = libraw_powf64(2.0f, (getreal(type) / 2.0f));\n break;\n#endif\n case 33434: tiff_ifd[tiff_nifds-1].t_shutter =\n\t\t shutter = getreal(type);\t\tbreak;\n case 33437: aperture = getreal(type);\t\tbreak; // 0x829d FNumber\n case 34855: iso_speed = get2();\t\t\tbreak;\n case 34866:\n if (iso_speed == 0xffff && (!strncasecmp(make, \"SONY\",4) || !strncasecmp(make, \"CANON\",5)))\n iso_speed = getreal(type);\n break;\n case 36867:\n case 36868: get_timestamp(0);\t\t\tbreak;\n case 37377: if ((expo = -getreal(type)) < 128 && shutter == 0.)\n\t\t tiff_ifd[tiff_nifds-1].t_shutter =\n\t\t\tshutter = libraw_powf64(2.0, expo);\n\t\tbreak;\n case 37378: // 0x9202 ApertureValue\n if ((fabs(ape = getreal(type))<256.0) && (!aperture))\n aperture = libraw_powf64(2.0, ape/2);\n break;\n case 37385: flash_used = getreal(type); break;\n case 37386: focal_len = getreal(type);\t\tbreak;\n case 37500: \t // tag 0x927c\n#ifdef LIBRAW_LIBRARY_BUILD\n if (((make[0] == '\\0') && (!strncmp(model, \"ov5647\",6))) ||\n ((!strncmp(make, \"RaspberryPi\",11)) && (!strncmp(model, \"RP_OV5647\",9))) ||\n ((!strncmp(make, \"RaspberryPi\",11)) && (!strncmp(model, \"RP_imx219\",9)))) {\n char mn_text[512];\n char* pos;\n char ccms[512];\n ushort l;\n float num;\n\n fgets(mn_text, len, ifp);\n pos = strstr(mn_text, \"gain_r=\");\n if (pos) cam_mul[0] = atof(pos+7);\n pos = strstr(mn_text, \"gain_b=\");\n if (pos) cam_mul[2] = atof(pos+7);\n if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f)) cam_mul[1] = cam_mul[3] = 1.0f;\n else cam_mul[0] = cam_mul[2] = 0.0f;\n\n pos = strstr(mn_text, \"ccm=\") + 4;\n l = strstr(pos, \" \") - pos;\n memcpy (ccms, pos, l);\n ccms[l] = '\\0';\n\n pos = strtok (ccms, \",\");\n for (l=0; l<4; l++) {\n num = 0.0;\n for (c=0; c<3; c++) {\n imgdata.color.ccm[l][c] = (float)atoi(pos);\n num += imgdata.color.ccm[l][c];\n pos = strtok (NULL, \",\");\n }\n if (num > 0.01) FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num;\n }\n }\n else\n#endif\n parse_makernote (base, 0);\n break;\n case 40962: if (kodak) raw_width = get4();\tbreak;\n case 40963: if (kodak) raw_height = get4();\tbreak;\n case 41730:\n\tif (get4() == 0x20002)\n\t for (exif_cfa=c=0; c < 8; c+=2)\n\t exif_cfa |= fgetc(ifp) * 0x01010101 << c;\n }\n fseek (ifp, save, SEEK_SET);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'Secunia 81800#1: samsumg_load_raw\n\nSecunia 81800#2: find_green\n\nSecunia 81800#3: rollei_load_raw\n\nremove_trailing_spaces: isspace() does not works right with signed non-latin chars\n\nSecunia 81800#5/6: nikon_coolscan_load_raw\n\nSecunia 81800#4: rollei_load_raw'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: defaults (void)\n{\n char *tmp;\n\n /* Most of the default values are 0 (and 0.0, NULL, and false).\n Just reset everything, and fill in the non-zero values. Note\n that initializing pointers to NULL this way is technically\n illegal, but porting Wget to a machine where NULL is not all-zero\n bit pattern will be the least of the implementors' worries. */\n xzero (opt);\n\n#ifdef HAVE_METALINK\n opt.metalink_index = -1;\n#endif\n\n opt.cookies = true;\n opt.verbose = -1;\n opt.ntry = 20;\n opt.reclevel = 5;\n opt.add_hostdir = true;\n opt.netrc = true;\n opt.ftp_glob = true;\n opt.htmlify = true;\n opt.http_keep_alive = true;\n opt.use_proxy = true;\n opt.convert_file_only = false;\n tmp = getenv (\"no_proxy\");\n if (tmp)\n opt.no_proxy = sepstring (tmp);\n opt.prefer_family = prefer_none;\n opt.allow_cache = true;\n opt.if_modified_since = true;\n\n opt.read_timeout = 900;\n opt.use_robots = true;\n\n opt.remove_listing = true;\n\n opt.dot_bytes = 1024;\n opt.dot_spacing = 10;\n opt.dots_in_line = 50;\n\n opt.dns_cache = true;\n opt.ftp_pasv = true;\n /* 2014-09-07 Darshit Shah \n * opt.retr_symlinks is set to true by default. Creating symbolic links on the\n * local filesystem pose a security threat by malicious FTP Servers that\n * server a specially crafted .listing file akin to this:\n *\n * lrwxrwxrwx 1 root root 33 Dec 25 2012 JoCxl6d8rFU -> /\n * drwxrwxr-x 15 1024 106 4096 Aug 28 02:02 JoCxl6d8rFU\n *\n * A .listing file in this fashion makes Wget susceptiple to a symlink attack\n * wherein the attacker is able to create arbitrary files, directories and\n * symbolic links on the target system and even set permissions.\n *\n * Hence, by default Wget attempts to retrieve the pointed-to files and does\n * not create the symbolic links locally.\n */\n opt.retr_symlinks = true;\n\n#ifdef HAVE_SSL\n opt.check_cert = CHECK_CERT_ON;\n opt.ftps_resume_ssl = true;\n opt.ftps_fallback_to_ftp = false;\n opt.ftps_implicit = false;\n opt.ftps_clear_data_connection = false;\n#endif\n\n#ifdef HAVE_LIBZ\n opt.compression = compression_none;\n#endif\n\n /* The default for file name restriction defaults to the OS type. */\n#if defined(WINDOWS) || defined(MSDOS) || defined(__CYGWIN__)\n opt.restrict_files_os = restrict_windows;\n#elif defined(__VMS)\n opt.restrict_files_os = restrict_vms;\n#else\n opt.restrict_files_os = restrict_unix;\n#endif\n opt.restrict_files_ctrl = true;\n opt.restrict_files_nonascii = false;\n opt.restrict_files_case = restrict_no_case_restriction;\n\n opt.regex_type = regex_type_posix;\n\n opt.max_redirect = 20;\n\n opt.waitretry = 10;\n\n#ifdef ENABLE_IRI\n opt.enable_iri = true;\n#else\n opt.enable_iri = false;\n#endif\n opt.locale = NULL;\n opt.encoding_remote = NULL;\n\n opt.useservertimestamps = true;\n opt.show_all_dns_entries = false;\n\n opt.warc_maxsize = 0; /* 1024 * 1024 * 1024; */\n#ifdef HAVE_LIBZ\n opt.warc_compression_enabled = true;\n#else\n opt.warc_compression_enabled = false;\n#endif\n opt.warc_digests_enabled = true;\n opt.warc_cdx_enabled = false;\n opt.warc_cdx_dedup_filename = NULL;\n opt.warc_tempdir = NULL;\n opt.warc_keep_log = true;\n\n /* Use a negative value to mark the absence of --start-pos option */\n opt.start_pos = -1;\n opt.show_progress = -1;\n opt.noscroll = false;\n\n#ifdef HAVE_HSTS\n /* HSTS is enabled by default */\n opt.hsts = true;\n#endif\n\n#ifdef ENABLE_XATTR\n opt.enable_xattr = true;\n#else\n opt.enable_xattr = false;\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Don't use extended attributes (--xattr) by default\n\n* src/init.c (defaults): Set enable_xattr to false by default\n* src/main.c (print_help): Reverse option logic of --xattr\n* doc/wget.texi: Add description for --xattr\n\nUsers may not be aware that the origin URL and Referer are saved\nincluding credentials, and possibly access tokens within\nthe urls.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int ipddp_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)\n{\n struct ipddp_route __user *rt = ifr->ifr_data;\n struct ipddp_route rcp, rcp2, *rp;\n\n if(!capable(CAP_NET_ADMIN))\n return -EPERM;\n\n\tif(copy_from_user(&rcp, rt, sizeof(rcp)))\n\t\treturn -EFAULT;\n\n switch(cmd)\n {\n\t\tcase SIOCADDIPDDPRT:\n return ipddp_create(&rcp);\n\n case SIOCFINDIPDDPRT:\n\t\t\tspin_lock_bh(&ipddp_route_lock);\n\t\t\trp = __ipddp_find_route(&rcp);\n\t\t\tif (rp)\n\t\t\t\tmemcpy(&rcp2, rp, sizeof(rcp2));\n\t\t\tspin_unlock_bh(&ipddp_route_lock);\n\n\t\t\tif (rp) {\n\t\t\t\tif (copy_to_user(rt, &rcp2,\n\t\t\t\t\t\t sizeof(struct ipddp_route)))\n\t\t\t\t\treturn -EFAULT;\n\t\t\t\treturn 0;\n\t\t\t} else\n\t\t\t\treturn -ENOENT;\n\n case SIOCDELIPDDPRT:\n return ipddp_delete(&rcp);\n\n default:\n return -EINVAL;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'net/appletalk: fix minor pointer leak to userspace in SIOCFINDIPDDPRT\n\nFields ->dev and ->next of struct ipddp_route may be copied to\nuserspace on the SIOCFINDIPDDPRT ioctl. This is only accessible\nto CAP_NET_ADMIN though. Let's manually copy the relevant fields\ninstead of using memcpy().\n\nBugLink: http://blog.infosectcbr.com.au/2018/09/linux-kernel-infoleaks.html\nCc: Jann Horn \nSigned-off-by: Willy Tarreau \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: send_request (ctrl_t ctrl, const char *request, const char *hostportstr,\n const char *httphost, unsigned int httpflags,\n gpg_error_t (*post_cb)(void *, http_t), void *post_cb_value,\n estream_t *r_fp, unsigned int *r_http_status)\n{\n gpg_error_t err;\n http_session_t session = NULL;\n http_t http = NULL;\n int redirects_left = MAX_REDIRECTS;\n estream_t fp = NULL;\n char *request_buffer = NULL;\n parsed_uri_t uri = NULL;\n int is_onion;\n\n *r_fp = NULL;\n\n err = http_parse_uri (&uri, request, 0);\n if (err)\n goto leave;\n is_onion = uri->onion;\n\n err = http_session_new (&session, httphost,\n ((ctrl->http_no_crl? HTTP_FLAG_NO_CRL : 0)\n | HTTP_FLAG_TRUST_DEF),\n gnupg_http_tls_verify_cb, ctrl);\n if (err)\n goto leave;\n http_session_set_log_cb (session, cert_log_cb);\n http_session_set_timeout (session, ctrl->timeout);\n\n once_more:\n err = http_open (&http,\n post_cb? HTTP_REQ_POST : HTTP_REQ_GET,\n request,\n httphost,\n /* fixme: AUTH */ NULL,\n (httpflags\n |(opt.honor_http_proxy? HTTP_FLAG_TRY_PROXY:0)\n |(dirmngr_use_tor ()? HTTP_FLAG_FORCE_TOR:0)\n |(opt.disable_ipv4? HTTP_FLAG_IGNORE_IPv4 : 0)\n |(opt.disable_ipv6? HTTP_FLAG_IGNORE_IPv6 : 0)),\n ctrl->http_proxy,\n session,\n NULL,\n /*FIXME curl->srvtag*/NULL);\n if (!err)\n {\n fp = http_get_write_ptr (http);\n /* Avoid caches to get the most recent copy of the key. We set\n both the Pragma and Cache-Control versions of the header, so\n we're good with both HTTP 1.0 and 1.1. */\n es_fputs (\"Pragma: no-cache\\r\\n\"\n \"Cache-Control: no-cache\\r\\n\", fp);\n if (post_cb)\n err = post_cb (post_cb_value, http);\n if (!err)\n {\n http_start_data (http);\n if (es_ferror (fp))\n err = gpg_error_from_syserror ();\n }\n }\n if (err)\n {\n /* Fixme: After a redirection we show the old host name. */\n log_error (_(\"error connecting to '%s': %s\\n\"),\n hostportstr, gpg_strerror (err));\n goto leave;\n }\n\n /* Wait for the response. */\n dirmngr_tick (ctrl);\n err = http_wait_response (http);\n if (err)\n {\n log_error (_(\"error reading HTTP response for '%s': %s\\n\"),\n hostportstr, gpg_strerror (err));\n goto leave;\n }\n\n if (http_get_tls_info (http, NULL))\n {\n /* Update the httpflags so that a redirect won't fallback to an\n unencrypted connection. */\n httpflags |= HTTP_FLAG_FORCE_TLS;\n }\n\n if (r_http_status)\n *r_http_status = http_get_status_code (http);\n\n switch (http_get_status_code (http))\n {\n case 200:\n err = 0;\n break; /* Success. */\n\n case 301:\n case 302:\n case 307:\n {\n const char *s = http_get_header (http, \"Location\");\n\n log_info (_(\"URL '%s' redirected to '%s' (%u)\\n\"),\n request, s?s:\"[none]\", http_get_status_code (http));\n if (s && *s && redirects_left-- )\n {\n if (is_onion)\n {\n /* Make sure that an onion address only redirects to\n * another onion address. */\n http_release_parsed_uri (uri);\n uri = NULL;\n err = http_parse_uri (&uri, s, 0);\n if (err)\n goto leave;\n\n if (! uri->onion)\n {\n err = gpg_error (GPG_ERR_FORBIDDEN);\n goto leave;\n }\n }\n\n xfree (request_buffer);\n request_buffer = xtrystrdup (s);\n if (request_buffer)\n {\n request = request_buffer;\n http_close (http, 0);\n http = NULL;\n goto once_more;\n }\n err = gpg_error_from_syserror ();\n }\n else\n err = gpg_error (GPG_ERR_NO_DATA);\n log_error (_(\"too many redirections\\n\"));\n }\n goto leave;\n\n case 501:\n err = gpg_error (GPG_ERR_NOT_IMPLEMENTED);\n goto leave;\n\n default:\n log_error (_(\"error accessing '%s': http status %u\\n\"),\n request, http_get_status_code (http));\n err = gpg_error (GPG_ERR_NO_DATA);\n goto leave;\n }\n\n /* FIXME: We should register a permanent redirection and whether a\n host has ever used TLS so that future calls will always use\n TLS. */\n\n fp = http_get_read_ptr (http);\n if (!fp)\n {\n err = gpg_error (GPG_ERR_BUG);\n goto leave;\n }\n\n /* Return the read stream and close the HTTP context. */\n *r_fp = fp;\n http_close (http, 1);\n http = NULL;\n\n leave:\n http_close (http, 0);\n http_session_release (session);\n xfree (request_buffer);\n http_release_parsed_uri (uri);\n return err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-352'], 'message': 'dirmngr: Avoid possible CSRF attacks via http redirects.\n\n* dirmngr/http.h (parsed_uri_s): Add fields off_host and off_path.\n(http_redir_info_t): New.\n* dirmngr/http.c (do_parse_uri): Set new fields.\n(same_host_p): New.\n(http_prepare_redirect): New.\n* dirmngr/t-http-basic.c: New test.\n* dirmngr/ks-engine-hkp.c (send_request): Use http_prepare_redirect\ninstead of the open code.\n* dirmngr/ks-engine-http.c (ks_http_fetch): Ditto.\n--\n\nWith this change a http query will not follow a redirect unless the\nLocation header gives the same host. If the host is different only\nthe host and port is taken from the Location header and the original\npath and query parts are kept.\n\nSigned-off-by: Werner Koch \n(cherry picked from commit fa1b1eaa4241ff3f0634c8bdf8591cbc7c464144)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: _pickle_UnpicklerMemoProxy_copy_impl(UnpicklerMemoProxyObject *self)\n/*[clinic end generated code: output=e12af7e9bc1e4c77 input=97769247ce032c1d]*/\n{\n Py_ssize_t i;\n PyObject *new_memo = PyDict_New();\n if (new_memo == NULL)\n return NULL;\n\n for (i = 0; i < self->unpickler->memo_size; i++) {\n int status;\n PyObject *key, *value;\n\n value = self->unpickler->memo[i];\n if (value == NULL)\n continue;\n\n key = PyLong_FromSsize_t(i);\n if (key == NULL)\n goto error;\n status = PyDict_SetItem(new_memo, key, value);\n Py_DECREF(key);\n if (status < 0)\n goto error;\n }\n return new_memo;\n\nerror:\n Py_DECREF(new_memo);\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190', 'CWE-369'], 'message': 'closes bpo-34656: Avoid relying on signed overflow in _pickle memos. (GH-9261)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int jpc_dec_decodepkt(jpc_dec_t *dec, jas_stream_t *pkthdrstream, jas_stream_t *in, int compno, int rlvlno,\n int prcno, int lyrno)\n{\n\tjpc_bitstream_t *inb;\n\tjpc_dec_tcomp_t *tcomp;\n\tjpc_dec_rlvl_t *rlvl;\n\tjpc_dec_band_t *band;\n\tjpc_dec_cblk_t *cblk;\n\tint n;\n\tint m;\n\tint i;\n\tjpc_tagtreenode_t *leaf;\n\tint included;\n\tint ret;\n\tint numnewpasses;\n\tjpc_dec_seg_t *seg;\n\tint len;\n\tint present;\n\tint savenumnewpasses;\n\tint mycounter;\n\tjpc_ms_t *ms;\n\tjpc_dec_tile_t *tile;\n\tjpc_dec_ccp_t *ccp;\n\tjpc_dec_cp_t *cp;\n\tint bandno;\n\tjpc_dec_prc_t *prc;\n\tint usedcblkcnt;\n\tint cblkno;\n\tuint_fast32_t bodylen;\n\tbool discard;\n\tint passno;\n\tint maxpasses;\n\tint hdrlen;\n\tint hdroffstart;\n\tint hdroffend;\n\n\t/* Avoid compiler warning about possible use of uninitialized\n\t variable. */\n\tbodylen = 0;\n\n\tdiscard = (lyrno >= dec->maxlyrs);\n\n\ttile = dec->curtile;\n\tcp = tile->cp;\n\tccp = &cp->ccps[compno];\n\n\t/*\n\t * Decode the packet header.\n\t */\n\n\t/* Decode the SOP marker segment if present. */\n\tif (cp->csty & JPC_COD_SOP) {\n\t\tif (jpc_dec_lookahead(in) == JPC_MS_SOP) {\n\t\t\tif (!(ms = jpc_getms(in, dec->cstate))) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tif (jpc_ms_gettype(ms) != JPC_MS_SOP) {\n\t\t\t\tjpc_ms_destroy(ms);\n\t\t\t\tjas_eprintf(\"missing SOP marker segment\\n\");\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tjpc_ms_destroy(ms);\n\t\t}\n\t}\n\nhdroffstart = jas_stream_getrwcount(pkthdrstream);\n\n\tif (!(inb = jpc_bitstream_sopen(pkthdrstream, \"r\"))) {\n\t\treturn -1;\n\t}\n\n\tif ((present = jpc_bitstream_getbit(inb)) < 0) {\n\t\treturn 1;\n\t}\n\tJAS_DBGLOG(10, (\"\\n\", present));\n\tJAS_DBGLOG(10, (\"present=%d \", present));\n\n\t/* Is the packet non-empty? */\n\tif (present) {\n\t\t/* The packet is non-empty. */\n\t\ttcomp = &tile->tcomps[compno];\n\t\trlvl = &tcomp->rlvls[rlvlno];\n\t\tbodylen = 0;\n\t\tfor (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;\n\t\t ++bandno, ++band) {\n\t\t\tif (!band->data) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tprc = &band->prcs[prcno];\n\t\t\tif (!prc->cblks) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tusedcblkcnt = 0;\n\t\t\tfor (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;\n\t\t\t ++cblkno, ++cblk) {\n\t\t\t\t++usedcblkcnt;\n\t\t\t\tif (!cblk->numpasses) {\n\t\t\t\t\tleaf = jpc_tagtree_getleaf(prc->incltagtree, usedcblkcnt - 1);\n\t\t\t\t\tif ((included = jpc_tagtree_decode(prc->incltagtree, leaf, lyrno + 1, inb)) < 0) {\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif ((included = jpc_bitstream_getbit(inb)) < 0) {\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tJAS_DBGLOG(10, (\"\\n\"));\n\t\t\t\tJAS_DBGLOG(10, (\"included=%d \", included));\n\t\t\t\tif (!included) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!cblk->numpasses) {\n\t\t\t\t\ti = 1;\n\t\t\t\t\tleaf = jpc_tagtree_getleaf(prc->numimsbstagtree, usedcblkcnt - 1);\n\t\t\t\t\tfor (;;) {\n\t\t\t\t\t\tif ((ret = jpc_tagtree_decode(prc->numimsbstagtree, leaf, i, inb)) < 0) {\n\t\t\t\t\t\t\treturn -1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (ret) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t++i;\n\t\t\t\t\t}\n\t\t\t\t\tcblk->numimsbs = i - 1;\n\t\t\t\t\tcblk->firstpassno = cblk->numimsbs * 3;\n\t\t\t\t}\n\t\t\t\tif ((numnewpasses = jpc_getnumnewpasses(inb)) < 0) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\tJAS_DBGLOG(10, (\"numnewpasses=%d \", numnewpasses));\n\t\t\t\tseg = cblk->curseg;\n\t\t\t\tsavenumnewpasses = numnewpasses;\n\t\t\t\tmycounter = 0;\n\t\t\t\tif (numnewpasses > 0) {\n\t\t\t\t\tif ((m = jpc_getcommacode(inb)) < 0) {\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\t}\n\t\t\t\t\tcblk->numlenbits += m;\n\t\t\t\t\tJAS_DBGLOG(10, (\"increment=%d \", m));\n\t\t\t\t\twhile (numnewpasses > 0) {\n\t\t\t\t\t\tpassno = cblk->firstpassno + cblk->numpasses + mycounter;\n\t/* XXX - the maxpasses is not set precisely but this doesn't matter... */\n\t\t\t\t\t\tmaxpasses = JPC_SEGPASSCNT(passno, cblk->firstpassno, 10000, (ccp->cblkctx & JPC_COX_LAZY) != 0, (ccp->cblkctx & JPC_COX_TERMALL) != 0);\n\t\t\t\t\t\tif (!discard && !seg) {\n\t\t\t\t\t\t\tif (!(seg = jpc_seg_alloc())) {\n\t\t\t\t\t\t\t\treturn -1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tjpc_seglist_insert(&cblk->segs, cblk->segs.tail, seg);\n\t\t\t\t\t\t\tif (!cblk->curseg) {\n\t\t\t\t\t\t\t\tcblk->curseg = seg;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tseg->passno = passno;\n\t\t\t\t\t\t\tseg->type = JPC_SEGTYPE(seg->passno, cblk->firstpassno, (ccp->cblkctx & JPC_COX_LAZY) != 0);\n\t\t\t\t\t\t\tseg->maxpasses = maxpasses;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tn = JAS_MIN(numnewpasses, maxpasses);\n\t\t\t\t\t\tmycounter += n;\n\t\t\t\t\t\tnumnewpasses -= n;\n\t\t\t\t\t\tif ((len = jpc_bitstream_getbits(inb, cblk->numlenbits + jpc_floorlog2(n))) < 0) {\n\t\t\t\t\t\t\treturn -1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tJAS_DBGLOG(10, (\"len=%d \", len));\n\t\t\t\t\t\tif (!discard) {\n\t\t\t\t\t\t\tseg->lyrno = lyrno;\n\t\t\t\t\t\t\tseg->numpasses += n;\n\t\t\t\t\t\t\tseg->cnt = len;\n\t\t\t\t\t\t\tseg = seg->next;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbodylen += len;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcblk->numpasses += savenumnewpasses;\n\t\t\t}\n\t\t}\n\n\t\tjpc_bitstream_inalign(inb, 0, 0);\n\n\t} else {\n\t\tif (jpc_bitstream_inalign(inb, 0x7f, 0)) {\n\t\t\tjas_eprintf(\"alignment failed\\n\");\n\t\t\treturn -1;\n\t\t}\n\t}\n\tjpc_bitstream_close(inb);\n\n\thdroffend = jas_stream_getrwcount(pkthdrstream);\n\thdrlen = hdroffend - hdroffstart;\n\tif (jas_getdbglevel() >= 5) {\n\t\tjas_eprintf(\"hdrlen=%lu bodylen=%lu \\n\", (unsigned long) hdrlen,\n\t\t (unsigned long) bodylen);\n\t}\n\n\tif (cp->csty & JPC_COD_EPH) {\n\t\tif (jpc_dec_lookahead(pkthdrstream) == JPC_MS_EPH) {\n\t\t\tif (!(ms = jpc_getms(pkthdrstream, dec->cstate))) {\n\t\t\t\tjas_eprintf(\"cannot get (EPH) marker segment\\n\");\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tif (jpc_ms_gettype(ms) != JPC_MS_EPH) {\n\t\t\t\tjpc_ms_destroy(ms);\n\t\t\t\tjas_eprintf(\"missing EPH marker segment\\n\");\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tjpc_ms_destroy(ms);\n\t\t}\n\t}\n\n\t/* decode the packet body. */\n\n\tif (jas_getdbglevel() >= 1) {\n\t\tjas_eprintf(\"packet body offset=%06ld\\n\", (long) jas_stream_getrwcount(in));\n\t}\n\n\tif (!discard) {\n\t\ttcomp = &tile->tcomps[compno];\n\t\trlvl = &tcomp->rlvls[rlvlno];\n\t\tfor (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;\n\t\t ++bandno, ++band) {\n\t\t\tif (!band->data) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tprc = &band->prcs[prcno];\n\t\t\tif (!prc->cblks) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;\n\t\t\t ++cblkno, ++cblk) {\n\t\t\t\tseg = cblk->curseg;\n\t\t\t\twhile (seg) {\n\t\t\t\t\tif (!seg->stream) {\n\t\t\t\t\t\tif (!(seg->stream = jas_stream_memopen(0, 0))) {\n\t\t\t\t\t\t\treturn -1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n#if 0\njas_eprintf(\"lyrno=%02d, compno=%02d, lvlno=%02d, prcno=%02d, bandno=%02d, cblkno=%02d, passno=%02d numpasses=%02d cnt=%d numbps=%d, numimsbs=%d\\n\", lyrno, compno, rlvlno, prcno, band - rlvl->bands, cblk - prc->cblks, seg->passno, seg->numpasses, seg->cnt, band->numbps, cblk->numimsbs);\n#endif\n\t\t\t\t\tif (seg->cnt > 0) {\n\t\t\t\t\t\tif (jpc_getdata(in, seg->stream, seg->cnt) < 0) {\n\t\t\t\t\t\t\treturn -1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tseg->cnt = 0;\n\t\t\t\t\t}\n\t\t\t\t\tif (seg->numpasses >= seg->maxpasses) {\n\t\t\t\t\t\tcblk->curseg = seg->next;\n\t\t\t\t\t}\n\t\t\t\t\tseg = seg->next;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif (jas_stream_gobble(in, bodylen) != JAS_CAST(int, bodylen)) {\n\t\t\treturn -1;\n\t\t}\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-772'], 'message': 'jpc_t2dec: fix various memory leaks in jpc_dec_decodepkt()\n\nFixes CVE-2018-20622\n\nCloses https://github.com/jasper-maint/jasper/issues/12\nCloses https://github.com/mdadams/jasper/issues/193'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: return_enc_padata(krb5_context context, krb5_data *req_pkt,\n krb5_kdc_req *request, krb5_keyblock *reply_key,\n krb5_db_entry *server, krb5_enc_kdc_rep_part *reply_encpart,\n krb5_boolean is_referral)\n{\n krb5_error_code code = 0;\n /* This should be initialized and only used for Win2K compat and other\n * specific standardized uses such as FAST negotiation. */\n assert(reply_encpart->enc_padata == NULL);\n if (is_referral) {\n code = return_referral_enc_padata(context, reply_encpart, server);\n if (code)\n return code;\n }\n code = kdc_handle_protected_negotiation(context, req_pkt, request, reply_key,\n &reply_encpart->enc_padata);\n if (code)\n goto cleanup;\n /*Add potentially other enc_padata providers*/\ncleanup:\n return code;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617'], 'message': 'Remove incorrect KDC assertion\n\nThe assertion in return_enc_padata() is reachable because\nkdc_make_s4u2self_rep() may have previously added encrypted padata.\nIt is no longer necessary because the code uses add_pa_data_element()\ninstead of allocating a new list.\n\nCVE-2018-20217:\n\nIn MIT krb5 1.8 or later, an authenticated user who can obtain a TGT\nusing an older encryption type (DES, DES3, or RC4) can cause an\nassertion failure in the KDC by sending an S4U2Self request.\n\n[ghudson@mit.edu: rewrote commit message with CVE description]\n\nticket: 8767 (new)\ntags: pullup\ntarget_version: 1.17\ntarget_version: 1.16-next\ntarget_version: 1.15-next'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int hso_probe(struct usb_interface *interface,\n\t\t const struct usb_device_id *id)\n{\n\tint mux, i, if_num, port_spec;\n\tunsigned char port_mask;\n\tstruct hso_device *hso_dev = NULL;\n\tstruct hso_shared_int *shared_int;\n\tstruct hso_device *tmp_dev = NULL;\n\n\tif (interface->cur_altsetting->desc.bInterfaceClass != 0xFF) {\n\t\tdev_err(&interface->dev, \"Not our interface\\n\");\n\t\treturn -ENODEV;\n\t}\n\n\tif_num = interface->cur_altsetting->desc.bInterfaceNumber;\n\n\t/* Get the interface/port specification from either driver_info or from\n\t * the device itself */\n\tif (id->driver_info)\n\t\tport_spec = ((u32 *)(id->driver_info))[if_num];\n\telse\n\t\tport_spec = hso_get_config_data(interface);\n\n\t/* Check if we need to switch to alt interfaces prior to port\n\t * configuration */\n\tif (interface->num_altsetting > 1)\n\t\tusb_set_interface(interface_to_usbdev(interface), if_num, 1);\n\tinterface->needs_remote_wakeup = 1;\n\n\t/* Allocate new hso device(s) */\n\tswitch (port_spec & HSO_INTF_MASK) {\n\tcase HSO_INTF_MUX:\n\t\tif ((port_spec & HSO_PORT_MASK) == HSO_PORT_NETWORK) {\n\t\t\t/* Create the network device */\n\t\t\tif (!disable_net) {\n\t\t\t\thso_dev = hso_create_net_device(interface,\n\t\t\t\t\t\t\t\tport_spec);\n\t\t\t\tif (!hso_dev)\n\t\t\t\t\tgoto exit;\n\t\t\t\ttmp_dev = hso_dev;\n\t\t\t}\n\t\t}\n\n\t\tif (hso_get_mux_ports(interface, &port_mask))\n\t\t\t/* TODO: de-allocate everything */\n\t\t\tgoto exit;\n\n\t\tshared_int = hso_create_shared_int(interface);\n\t\tif (!shared_int)\n\t\t\tgoto exit;\n\n\t\tfor (i = 1, mux = 0; i < 0x100; i = i << 1, mux++) {\n\t\t\tif (port_mask & i) {\n\t\t\t\thso_dev = hso_create_mux_serial_device(\n\t\t\t\t\t\tinterface, i, shared_int);\n\t\t\t\tif (!hso_dev)\n\t\t\t\t\tgoto exit;\n\t\t\t}\n\t\t}\n\n\t\tif (tmp_dev)\n\t\t\thso_dev = tmp_dev;\n\t\tbreak;\n\n\tcase HSO_INTF_BULK:\n\t\t/* It's a regular bulk interface */\n\t\tif ((port_spec & HSO_PORT_MASK) == HSO_PORT_NETWORK) {\n\t\t\tif (!disable_net)\n\t\t\t\thso_dev =\n\t\t\t\t hso_create_net_device(interface, port_spec);\n\t\t} else {\n\t\t\thso_dev =\n\t\t\t hso_create_bulk_serial_device(interface, port_spec);\n\t\t}\n\t\tif (!hso_dev)\n\t\t\tgoto exit;\n\t\tbreak;\n\tdefault:\n\t\tgoto exit;\n\t}\n\n\t/* save our data pointer in this device */\n\tusb_set_intfdata(interface, hso_dev);\n\n\t/* done */\n\treturn 0;\nexit:\n\thso_free_interface(interface);\n\treturn -ENODEV;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'USB: hso: Fix OOB memory access in hso_probe/hso_get_config_data\n\nThe function hso_probe reads if_num from the USB device (as an u8) and uses\nit without a length check to index an array, resulting in an OOB memory read\nin hso_probe or hso_get_config_data.\n\nAdd a length check for both locations and updated hso_probe to bail on\nerror.\n\nThis issue has been assigned CVE-2018-19985.\n\nReported-by: Hui Peng \nReported-by: Mathias Payer \nSigned-off-by: Hui Peng \nSigned-off-by: Mathias Payer \nReviewed-by: Sebastian Andrzej Siewior \nSigned-off-by: Greg Kroah-Hartman \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: uint8_t* FAST_FUNC udhcp_get_option32(struct dhcp_packet *packet, int code)\n{\n\tuint8_t *r = udhcp_get_option(packet, code);\n\tif (r) {\n\t\tif (r[-1] != 4)\n\t\t\tr = NULL;\n\t}\n\treturn r;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'udhcpc: when decoding DHCP_SUBNET, ensure it is 4 bytes long\n\nfunction old new delta\nudhcp_run_script 795 801 +6\n\nSigned-off-by: Denys Vlasenko '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: long strnlen_user(const char __user *str, long count)\n{\n\tunsigned long max_addr, src_addr;\n\n\tif (unlikely(count <= 0))\n\t\treturn 0;\n\n\tmax_addr = user_addr_max();\n\tsrc_addr = (unsigned long)str;\n\tif (likely(src_addr < max_addr)) {\n\t\tunsigned long max = max_addr - src_addr;\n\t\tlong retval;\n\n\t\tuser_access_begin();\n\t\tretval = do_strnlen_user(str, count, max);\n\t\tuser_access_end();\n\t\treturn retval;\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'make 'user_access_begin()' do 'access_ok()'\n\nOriginally, the rule used to be that you'd have to do access_ok()\nseparately, and then user_access_begin() before actually doing the\ndirect (optimized) user access.\n\nBut experience has shown that people then decide not to do access_ok()\nat all, and instead rely on it being implied by other operations or\nsimilar. Which makes it very hard to verify that the access has\nactually been range-checked.\n\nIf you use the unsafe direct user accesses, hardware features (either\nSMAP - Supervisor Mode Access Protection - on x86, or PAN - Privileged\nAccess Never - on ARM) do force you to use user_access_begin(). But\nnothing really forces the range check.\n\nBy putting the range check into user_access_begin(), we actually force\npeople to do the right thing (tm), and the range check vill be visible\nnear the actual accesses. We have way too long a history of people\ntrying to avoid them.\n\nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: sec_recv(uint8 * rdpver)\n{\n\tuint32 sec_flags;\n\tuint16 channel;\n\tSTREAM s;\n\n\twhile ((s = mcs_recv(&channel, rdpver)) != NULL)\n\t{\n\t\tif (rdpver != NULL)\n\t\t{\n\t\t\tif (*rdpver != 3)\n\t\t\t{\n\t\t\t\tif (*rdpver & 0x80)\n\t\t\t\t{\n\t\t\t\t\tin_uint8s(s, 8);\t/* signature */\n\t\t\t\t\tsec_decrypt(s->p, s->end - s->p);\n\t\t\t\t}\n\t\t\t\treturn s;\n\t\t\t}\n\t\t}\n\t\tif (g_encryption || (!g_licence_issued && !g_licence_error_result))\n\t\t{\n\t\t\tin_uint32_le(s, sec_flags);\n\n\t\t\tif (g_encryption)\n\t\t\t{\n\t\t\t\tif (sec_flags & SEC_ENCRYPT)\n\t\t\t\t{\n\t\t\t\t\tin_uint8s(s, 8);\t/* signature */\n\t\t\t\t\tsec_decrypt(s->p, s->end - s->p);\n\t\t\t\t}\n\n\t\t\t\tif (sec_flags & SEC_LICENCE_NEG)\n\t\t\t\t{\n\t\t\t\t\tlicence_process(s);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (sec_flags & 0x0400)\t/* SEC_REDIRECT_ENCRYPT */\n\t\t\t\t{\n\t\t\t\t\tuint8 swapbyte;\n\n\t\t\t\t\tin_uint8s(s, 8);\t/* signature */\n\t\t\t\t\tsec_decrypt(s->p, s->end - s->p);\n\n\t\t\t\t\t/* Check for a redirect packet, starts with 00 04 */\n\t\t\t\t\tif (s->p[0] == 0 && s->p[1] == 4)\n\t\t\t\t\t{\n\t\t\t\t\t\t/* for some reason the PDU and the length seem to be swapped.\n\t\t\t\t\t\t This isn't good, but we're going to do a byte for byte\n\t\t\t\t\t\t swap. So the first foure value appear as: 00 04 XX YY,\n\t\t\t\t\t\t where XX YY is the little endian length. We're going to\n\t\t\t\t\t\t use 04 00 as the PDU type, so after our swap this will look\n\t\t\t\t\t\t like: XX YY 04 00 */\n\t\t\t\t\t\tswapbyte = s->p[0];\n\t\t\t\t\t\ts->p[0] = s->p[2];\n\t\t\t\t\t\ts->p[2] = swapbyte;\n\n\t\t\t\t\t\tswapbyte = s->p[1];\n\t\t\t\t\t\ts->p[1] = s->p[3];\n\t\t\t\t\t\ts->p[3] = swapbyte;\n\n\t\t\t\t\t\tswapbyte = s->p[2];\n\t\t\t\t\t\ts->p[2] = s->p[3];\n\t\t\t\t\t\ts->p[3] = swapbyte;\n\t\t\t\t\t}\n#ifdef WITH_DEBUG\n\t\t\t\t\t/* warning! this debug statement will show passwords in the clear! */\n\t\t\t\t\thexdump(s->p, s->end - s->p);\n#endif\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif ((sec_flags & 0xffff) == SEC_LICENCE_NEG)\n\t\t\t\t{\n\t\t\t\t\tlicence_process(s);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\ts->p -= 4;\n\t\t\t}\n\t\t}\n\n\t\tif (channel != MCS_GLOBAL_CHANNEL)\n\t\t{\n\t\t\tchannel_process(s, channel);\n\t\t\tif (rdpver != NULL)\n\t\t\t\t*rdpver = 0xff;\n\t\t\treturn s;\n\t\t}\n\n\t\treturn s;\n\t}\n\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n* Add rdp_protocol_error function that is used in several fixes\n* Refactor of process_bitmap_updates\n* Fix possible integer overflow in s_check_rem() on 32bit arch\n* Fix memory corruption in process_bitmap_data - CVE-2018-8794\n* Fix remote code execution in process_bitmap_data - CVE-2018-8795\n* Fix remote code execution in process_plane - CVE-2018-8797\n* Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n* Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n* Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n* Fix Denial of Service in sec_recv - CVE-2018-20176\n* Fix minor information leak in rdpdr_process - CVE-2018-8791\n* Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n* Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n* Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n* Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n* Fix Denial of Service in process_secondary_order - CVE-2018-8799\n* Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n* Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n* Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n* Fix Denial of Service in process_demand_active - CVE-2018-20178\n* Fix remote code execution in lspci_process - CVE-2018-20179\n* Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n* Fix remote code execution in seamless_process - CVE-2018-20181\n* Fix remote code execution in seamless_process_line - CVE-2018-20182'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void change_port_settings(struct tty_struct *tty,\n\t\tstruct edgeport_port *edge_port, struct ktermios *old_termios)\n{\n\tstruct device *dev = &edge_port->port->dev;\n\tstruct ump_uart_config *config;\n\tint baud;\n\tunsigned cflag;\n\tint status;\n\tint port_number = edge_port->port->port_number;\n\n\tconfig = kmalloc (sizeof (*config), GFP_KERNEL);\n\tif (!config) {\n\t\ttty->termios = *old_termios;\n\t\treturn;\n\t}\n\n\tcflag = tty->termios.c_cflag;\n\n\tconfig->wFlags = 0;\n\n\t/* These flags must be set */\n\tconfig->wFlags |= UMP_MASK_UART_FLAGS_RECEIVE_MS_INT;\n\tconfig->wFlags |= UMP_MASK_UART_FLAGS_AUTO_START_ON_ERR;\n\tconfig->bUartMode = (__u8)(edge_port->bUartMode);\n\n\tswitch (cflag & CSIZE) {\n\tcase CS5:\n\t\t config->bDataBits = UMP_UART_CHAR5BITS;\n\t\t dev_dbg(dev, \"%s - data bits = 5\\n\", __func__);\n\t\t break;\n\tcase CS6:\n\t\t config->bDataBits = UMP_UART_CHAR6BITS;\n\t\t dev_dbg(dev, \"%s - data bits = 6\\n\", __func__);\n\t\t break;\n\tcase CS7:\n\t\t config->bDataBits = UMP_UART_CHAR7BITS;\n\t\t dev_dbg(dev, \"%s - data bits = 7\\n\", __func__);\n\t\t break;\n\tdefault:\n\tcase CS8:\n\t\t config->bDataBits = UMP_UART_CHAR8BITS;\n\t\t dev_dbg(dev, \"%s - data bits = 8\\n\", __func__);\n\t\t\t break;\n\t}\n\n\tif (cflag & PARENB) {\n\t\tif (cflag & PARODD) {\n\t\t\tconfig->wFlags |= UMP_MASK_UART_FLAGS_PARITY;\n\t\t\tconfig->bParity = UMP_UART_ODDPARITY;\n\t\t\tdev_dbg(dev, \"%s - parity = odd\\n\", __func__);\n\t\t} else {\n\t\t\tconfig->wFlags |= UMP_MASK_UART_FLAGS_PARITY;\n\t\t\tconfig->bParity = UMP_UART_EVENPARITY;\n\t\t\tdev_dbg(dev, \"%s - parity = even\\n\", __func__);\n\t\t}\n\t} else {\n\t\tconfig->bParity = UMP_UART_NOPARITY;\n\t\tdev_dbg(dev, \"%s - parity = none\\n\", __func__);\n\t}\n\n\tif (cflag & CSTOPB) {\n\t\tconfig->bStopBits = UMP_UART_STOPBIT2;\n\t\tdev_dbg(dev, \"%s - stop bits = 2\\n\", __func__);\n\t} else {\n\t\tconfig->bStopBits = UMP_UART_STOPBIT1;\n\t\tdev_dbg(dev, \"%s - stop bits = 1\\n\", __func__);\n\t}\n\n\t/* figure out the flow control settings */\n\tif (cflag & CRTSCTS) {\n\t\tconfig->wFlags |= UMP_MASK_UART_FLAGS_OUT_X_CTS_FLOW;\n\t\tconfig->wFlags |= UMP_MASK_UART_FLAGS_RTS_FLOW;\n\t\tdev_dbg(dev, \"%s - RTS/CTS is enabled\\n\", __func__);\n\t} else {\n\t\tdev_dbg(dev, \"%s - RTS/CTS is disabled\\n\", __func__);\n\t\trestart_read(edge_port);\n\t}\n\n\t/*\n\t * if we are implementing XON/XOFF, set the start and stop\n\t * character in the device\n\t */\n\tconfig->cXon = START_CHAR(tty);\n\tconfig->cXoff = STOP_CHAR(tty);\n\n\t/* if we are implementing INBOUND XON/XOFF */\n\tif (I_IXOFF(tty)) {\n\t\tconfig->wFlags |= UMP_MASK_UART_FLAGS_IN_X;\n\t\tdev_dbg(dev, \"%s - INBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x\\n\",\n\t\t\t__func__, config->cXon, config->cXoff);\n\t} else\n\t\tdev_dbg(dev, \"%s - INBOUND XON/XOFF is disabled\\n\", __func__);\n\n\t/* if we are implementing OUTBOUND XON/XOFF */\n\tif (I_IXON(tty)) {\n\t\tconfig->wFlags |= UMP_MASK_UART_FLAGS_OUT_X;\n\t\tdev_dbg(dev, \"%s - OUTBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x\\n\",\n\t\t\t__func__, config->cXon, config->cXoff);\n\t} else\n\t\tdev_dbg(dev, \"%s - OUTBOUND XON/XOFF is disabled\\n\", __func__);\n\n\ttty->termios.c_cflag &= ~CMSPAR;\n\n\t/* Round the baud rate */\n\tbaud = tty_get_baud_rate(tty);\n\tif (!baud) {\n\t\t/* pick a default, any default... */\n\t\tbaud = 9600;\n\t} else\n\t\ttty_encode_baud_rate(tty, baud, baud);\n\n\tedge_port->baud_rate = baud;\n\tconfig->wBaudRate = (__u16)((461550L + baud/2) / baud);\n\n\t/* FIXME: Recompute actual baud from divisor here */\n\n\tdev_dbg(dev, \"%s - baud rate = %d, wBaudRate = %d\\n\", __func__, baud, config->wBaudRate);\n\n\tdev_dbg(dev, \"wBaudRate: %d\\n\", (int)(461550L / config->wBaudRate));\n\tdev_dbg(dev, \"wFlags: 0x%x\\n\", config->wFlags);\n\tdev_dbg(dev, \"bDataBits: %d\\n\", config->bDataBits);\n\tdev_dbg(dev, \"bParity: %d\\n\", config->bParity);\n\tdev_dbg(dev, \"bStopBits: %d\\n\", config->bStopBits);\n\tdev_dbg(dev, \"cXon: %d\\n\", config->cXon);\n\tdev_dbg(dev, \"cXoff: %d\\n\", config->cXoff);\n\tdev_dbg(dev, \"bUartMode: %d\\n\", config->bUartMode);\n\n\t/* move the word values into big endian mode */\n\tcpu_to_be16s(&config->wFlags);\n\tcpu_to_be16s(&config->wBaudRate);\n\n\tstatus = send_cmd(edge_port->port->serial->dev, UMPC_SET_CONFIG,\n\t\t\t\t(__u8)(UMPM_UART1_PORT + port_number),\n\t\t\t\t0, (__u8 *)config, sizeof(*config));\n\tif (status)\n\t\tdev_dbg(dev, \"%s - error %d when trying to write config to device\\n\",\n\t\t\t__func__, status);\n\tkfree(config);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-369'], 'message': 'USB: serial: io_ti: fix div-by-zero in set_termios\n\nFix a division-by-zero in set_termios when debugging is enabled and a\nhigh-enough speed has been requested so that the divisor value becomes\nzero.\n\nInstead of just fixing the offending debug statement, cap the baud rate\nat the base as a zero divisor value also appears to crash the firmware.\n\nFixes: 1da177e4c3f4 (\"Linux-2.6.12-rc2\")\nCc: stable # 2.6.12\nReviewed-by: Greg Kroah-Hartman \nSigned-off-by: Johan Hovold '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void nsc_rle_decompress_data(NSC_CONTEXT* context)\n{\n\tUINT16 i;\n\tBYTE* rle;\n\tUINT32 planeSize;\n\tUINT32 originalSize;\n\trle = context->Planes;\n\n\tfor (i = 0; i < 4; i++)\n\t{\n\t\toriginalSize = context->OrgByteCount[i];\n\t\tplaneSize = context->PlaneByteCount[i];\n\n\t\tif (planeSize == 0)\n\t\t\tFillMemory(context->priv->PlaneBuffers[i], originalSize, 0xFF);\n\t\telse if (planeSize < originalSize)\n\t\t\tnsc_rle_decode(rle, context->priv->PlaneBuffers[i], originalSize);\n\t\telse\n\t\t\tCopyMemory(context->priv->PlaneBuffers[i], rle, originalSize);\n\n\t\trle += planeSize;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-787'], 'message': 'Fixed CVE-2018-8788\n\nThanks to Eyal Itkin from Check Point Software Technologies.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ntlm_read_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields)\n{\n\tif (fields->Len > 0)\n\t{\n\t\tif ((fields->BufferOffset + fields->Len) > Stream_Length(s))\n\t\t\treturn -1;\n\n\t\tfields->Buffer = (PBYTE) malloc(fields->Len);\n\n\t\tif (!fields->Buffer)\n\t\t\treturn -1;\n\n\t\tStream_SetPosition(s, fields->BufferOffset);\n\t\tStream_Read(s, fields->Buffer, fields->Len);\n\t}\n\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-125'], 'message': 'Fixed CVE-2018-8789\n\nThanks to Eyal Itkin from Check Point Software Technologies.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: BGD_DECLARE(void) gdImageWBMPCtx(gdImagePtr image, int fg, gdIOCtx *out)\n{\n\tint x, y, pos;\n\tWbmp *wbmp;\n\n\t/* create the WBMP */\n\tif((wbmp = createwbmp(gdImageSX(image), gdImageSY(image), WBMP_WHITE)) == NULL) {\n\t\tgd_error(\"Could not create WBMP\\n\");\n\t\treturn;\n\t}\n\n\t/* fill up the WBMP structure */\n\tpos = 0;\n\tfor(y = 0; y < gdImageSY(image); y++) {\n\t\tfor(x = 0; x < gdImageSX(image); x++) {\n\t\t\tif(gdImageGetPixel(image, x, y) == fg) {\n\t\t\t\twbmp->bitmap[pos] = WBMP_BLACK;\n\t\t\t}\n\t\t\tpos++;\n\t\t}\n\t}\n\n\t/* write the WBMP to a gd file descriptor */\n\tif(writewbmp(wbmp, &gd_putout, out)) {\n\t\tgd_error(\"Could not save WBMP\\n\");\n\t}\n\n\t/* des submitted this bugfix: gdFree the memory. */\n\tfreewbmp(wbmp);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'Fix #492: Potential double-free in gdImage*Ptr()\n\nWhenever `gdImage*Ptr()` calls `gdImage*Ctx()` and the latter fails, we\nmust not call `gdDPExtractData()`; otherwise a double-free would\nhappen. Since `gdImage*Ctx()` are void functions, and we can't change\nthat for BC reasons, we're introducing static helpers which are used\ninternally.\n\nWe're adding a regression test for `gdImageJpegPtr()`, but not for\n`gdImageGifPtr()` and `gdImageWbmpPtr()` since we don't know how to\ntrigger failure of the respective `gdImage*Ctx()` calls.\n\nThis potential security issue has been reported by Solmaz Salimi (aka.\nRooney).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: char *rfbProcessFileTransferReadBuffer(rfbClientPtr cl, uint32_t length)\n{\n char *buffer=NULL;\n int n=0;\n\n FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN(\"\", cl, NULL);\n /*\n rfbLog(\"rfbProcessFileTransferReadBuffer(%dlen)\\n\", length);\n */\n if (length>0) {\n buffer=malloc((uint64_t)length+1);\n if (buffer!=NULL) {\n if ((n = rfbReadExact(cl, (char *)buffer, length)) <= 0) {\n if (n != 0)\n rfbLogPerror(\"rfbProcessFileTransferReadBuffer: read\");\n rfbCloseClient(cl);\n /* NOTE: don't forget to free(buffer) if you return early! */\n if (buffer!=NULL) free(buffer);\n return NULL;\n }\n /* Null Terminate */\n buffer[length]=0;\n }\n }\n return buffer;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Error out in rfbProcessFileTransferReadBuffer if length can not be allocated\n\nre #273'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int ldb_wildcard_compare(struct ldb_context *ldb,\n\t\t\t\tconst struct ldb_parse_tree *tree,\n\t\t\t\tconst struct ldb_val value, bool *matched)\n{\n\tconst struct ldb_schema_attribute *a;\n\tstruct ldb_val val;\n\tstruct ldb_val cnk;\n\tstruct ldb_val *chunk;\n\tuint8_t *save_p = NULL;\n\tunsigned int c = 0;\n\n\ta = ldb_schema_attribute_by_name(ldb, tree->u.substring.attr);\n\tif (!a) {\n\t\treturn LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;\n\t}\n\n\tif (tree->u.substring.chunks == NULL) {\n\t\t*matched = false;\n\t\treturn LDB_SUCCESS;\n\t}\n\n\tif (a->syntax->canonicalise_fn(ldb, ldb, &value, &val) != 0) {\n\t\treturn LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;\n\t}\n\n\tsave_p = val.data;\n\tcnk.data = NULL;\n\n\tif ( ! tree->u.substring.start_with_wildcard ) {\n\n\t\tchunk = tree->u.substring.chunks[c];\n\t\tif (a->syntax->canonicalise_fn(ldb, ldb, chunk, &cnk) != 0) goto mismatch;\n\n\t\t/* This deals with wildcard prefix searches on binary attributes (eg objectGUID) */\n\t\tif (cnk.length > val.length) {\n\t\t\tgoto mismatch;\n\t\t}\n\t\t/*\n\t\t * Empty strings are returned as length 0. Ensure\n\t\t * we can cope with this.\n\t\t */\n\t\tif (cnk.length == 0) {\n\t\t\tgoto mismatch;\n\t\t}\n\n\t\tif (memcmp((char *)val.data, (char *)cnk.data, cnk.length) != 0) goto mismatch;\n\t\tval.length -= cnk.length;\n\t\tval.data += cnk.length;\n\t\tc++;\n\t\ttalloc_free(cnk.data);\n\t\tcnk.data = NULL;\n\t}\n\n\twhile (tree->u.substring.chunks[c]) {\n\t\tuint8_t *p;\n\n\t\tchunk = tree->u.substring.chunks[c];\n\t\tif(a->syntax->canonicalise_fn(ldb, ldb, chunk, &cnk) != 0) goto mismatch;\n\n\t\t/*\n\t\t * Empty strings are returned as length 0. Ensure\n\t\t * we can cope with this.\n\t\t */\n\t\tif (cnk.length == 0) {\n\t\t\tgoto mismatch;\n\t\t}\n\t\t/*\n\t\t * Values might be binary blobs. Don't use string\n\t\t * search, but memory search instead.\n\t\t */\n\t\tp = memmem((const void *)val.data,val.length,\n\t\t\t (const void *)cnk.data, cnk.length);\n\t\tif (p == NULL) goto mismatch;\n\n\t\t/*\n\t\t * At this point we know cnk.length <= val.length as\n\t\t * otherwise there could be no match\n\t\t */\n\n\t\tif ( (! tree->u.substring.chunks[c + 1]) && (! tree->u.substring.end_with_wildcard) ) {\n\t\t\tuint8_t *g;\n\t\t\tuint8_t *end = val.data + val.length;\n\t\t\tdo { /* greedy */\n\n\t\t\t\t/*\n\t\t\t\t * haystack is a valid pointer in val\n\t\t\t\t * because the memmem() can only\n\t\t\t\t * succeed if the needle (cnk.length)\n\t\t\t\t * is <= haystacklen\n\t\t\t\t *\n\t\t\t\t * p will be a pointer at least\n\t\t\t\t * cnk.length from the end of haystack\n\t\t\t\t */\n\t\t\t\tuint8_t *haystack\n\t\t\t\t\t= p + cnk.length;\n\t\t\t\tsize_t haystacklen\n\t\t\t\t\t= end - (haystack);\n\n\t\t\t\tg = memmem(haystack,\n\t\t\t\t\t haystacklen,\n\t\t\t\t\t(const uint8_t *)cnk.data,\n\t\t\t\t\tcnk.length);\n\t\t\t\tif (g) p = g;\n\t\t\t} while(g);\n\t\t}\n\t\tval.length = val.length - (p - (uint8_t *)(val.data)) - cnk.length;\n\t\tval.data = (uint8_t *)(p + cnk.length);\n\t\tc++;\n\t\ttalloc_free(cnk.data);\n\t\tcnk.data = NULL;\n\t}\n\n\t/* last chunk may not have reached end of string */\n\tif ( (! tree->u.substring.end_with_wildcard) && (*(val.data) != 0) ) goto mismatch;\n\ttalloc_free(save_p);\n\t*matched = true;\n\treturn LDB_SUCCESS;\n\nmismatch:\n\t*matched = false;\n\ttalloc_free(save_p);\n\ttalloc_free(cnk.data);\n\treturn LDB_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'CVE-2019-3824 ldb: Improve code style and layout in wildcard processing\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=13773\n\nSigned-off-by: Andrew Bartlett \nReviewed-by: Gary Lockyer '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int copy_verifier_state(struct bpf_verifier_state *dst_state,\n\t\t\t const struct bpf_verifier_state *src)\n{\n\tstruct bpf_func_state *dst;\n\tint i, err;\n\n\t/* if dst has more stack frames then src frame, free them */\n\tfor (i = src->curframe + 1; i <= dst_state->curframe; i++) {\n\t\tfree_func_state(dst_state->frame[i]);\n\t\tdst_state->frame[i] = NULL;\n\t}\n\tdst_state->curframe = src->curframe;\n\tfor (i = 0; i <= src->curframe; i++) {\n\t\tdst = dst_state->frame[i];\n\t\tif (!dst) {\n\t\t\tdst = kzalloc(sizeof(*dst), GFP_KERNEL);\n\t\t\tif (!dst)\n\t\t\t\treturn -ENOMEM;\n\t\t\tdst_state->frame[i] = dst;\n\t\t}\n\t\terr = copy_func_state(dst, src->frame[i]);\n\t\tif (err)\n\t\t\treturn err;\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'bpf: prevent out of bounds speculation on pointer arithmetic\n\nJann reported that the original commit back in b2157399cc98\n(\"bpf: prevent out-of-bounds speculation\") was not sufficient\nto stop CPU from speculating out of bounds memory access:\nWhile b2157399cc98 only focussed on masking array map access\nfor unprivileged users for tail calls and data access such\nthat the user provided index gets sanitized from BPF program\nand syscall side, there is still a more generic form affected\nfrom BPF programs that applies to most maps that hold user\ndata in relation to dynamic map access when dealing with\nunknown scalars or \"slow\" known scalars as access offset, for\nexample:\n\n - Load a map value pointer into R6\n - Load an index into R7\n - Do a slow computation (e.g. with a memory dependency) that\n loads a limit into R8 (e.g. load the limit from a map for\n high latency, then mask it to make the verifier happy)\n - Exit if R7 >= R8 (mispredicted branch)\n - Load R0 = R6[R7]\n - Load R0 = R6[R0]\n\nFor unknown scalars there are two options in the BPF verifier\nwhere we could derive knowledge from in order to guarantee\nsafe access to the memory: i) While /<=/>= variants won't\nallow to derive any lower or upper bounds from the unknown\nscalar where it would be safe to add it to the map value\npointer, it is possible through ==/!= test however. ii) another\noption is to transform the unknown scalar into a known scalar,\nfor example, through ALU ops combination such as R &= \nfollowed by R |= or any similar combination where the\noriginal information from the unknown scalar would be destroyed\nentirely leaving R with a constant. The initial slow load still\nprecedes the latter ALU ops on that register, so the CPU\nexecutes speculatively from that point. Once we have the known\nscalar, any compare operation would work then. A third option\nonly involving registers with known scalars could be crafted\nas described in [0] where a CPU port (e.g. Slow Int unit)\nwould be filled with many dependent computations such that\nthe subsequent condition depending on its outcome has to wait\nfor evaluation on its execution port and thereby executing\nspeculatively if the speculated code can be scheduled on a\ndifferent execution port, or any other form of mistraining\nas described in [1], for example. Given this is not limited\nto only unknown scalars, not only map but also stack access\nis affected since both is accessible for unprivileged users\nand could potentially be used for out of bounds access under\nspeculation.\n\nIn order to prevent any of these cases, the verifier is now\nsanitizing pointer arithmetic on the offset such that any\nout of bounds speculation would be masked in a way where the\npointer arithmetic result in the destination register will\nstay unchanged, meaning offset masked into zero similar as\nin array_index_nospec() case. With regards to implementation,\nthere are three options that were considered: i) new insn\nfor sanitation, ii) push/pop insn and sanitation as inlined\nBPF, iii) reuse of ax register and sanitation as inlined BPF.\n\nOption i) has the downside that we end up using from reserved\nbits in the opcode space, but also that we would require\neach JIT to emit masking as native arch opcodes meaning\nmitigation would have slow adoption till everyone implements\nit eventually which is counter-productive. Option ii) and iii)\nhave both in common that a temporary register is needed in\norder to implement the sanitation as inlined BPF since we\nare not allowed to modify the source register. While a push /\npop insn in ii) would be useful to have in any case, it\nrequires once again that every JIT needs to implement it\nfirst. While possible, amount of changes needed would also\nbe unsuitable for a -stable patch. Therefore, the path which\nhas fewer changes, less BPF instructions for the mitigation\nand does not require anything to be changed in the JITs is\noption iii) which this work is pursuing. The ax register is\nalready mapped to a register in all JITs (modulo arm32 where\nit's mapped to stack as various other BPF registers there)\nand used in constant blinding for JITs-only so far. It can\nbe reused for verifier rewrites under certain constraints.\nThe interpreter's tmp \"register\" has therefore been remapped\ninto extending the register set with hidden ax register and\nreusing that for a number of instructions that needed the\nprior temporary variable internally (e.g. div, mod). This\nallows for zero increase in stack space usage in the interpreter,\nand enables (restricted) generic use in rewrites otherwise as\nlong as such a patchlet does not make use of these instructions.\nThe sanitation mask is dynamic and relative to the offset the\nmap value or stack pointer currently holds.\n\nThere are various cases that need to be taken under consideration\nfor the masking, e.g. such operation could look as follows:\nptr += val or val += ptr or ptr -= val. Thus, the value to be\nsanitized could reside either in source or in destination\nregister, and the limit is different depending on whether\nthe ALU op is addition or subtraction and depending on the\ncurrent known and bounded offset. The limit is derived as\nfollows: limit := max_value_size - (smin_value + off). For\nsubtraction: limit := umax_value + off. This holds because\nwe do not allow any pointer arithmetic that would\ntemporarily go out of bounds or would have an unknown\nvalue with mixed signed bounds where it is unclear at\nverification time whether the actual runtime value would\nbe either negative or positive. For example, we have a\nderived map pointer value with constant offset and bounded\none, so limit based on smin_value works because the verifier\nrequires that statically analyzed arithmetic on the pointer\nmust be in bounds, and thus it checks if resulting\nsmin_value + off and umax_value + off is still within map\nvalue bounds at time of arithmetic in addition to time of\naccess. Similarly, for the case of stack access we derive\nthe limit as follows: MAX_BPF_STACK + off for subtraction\nand -off for the case of addition where off := ptr_reg->off +\nptr_reg->var_off.value. Subtraction is a special case for\nthe masking which can be in form of ptr += -val, ptr -= -val,\nor ptr -= val. In the first two cases where we know that\nthe value is negative, we need to temporarily negate the\nvalue in order to do the sanitation on a positive value\nwhere we later swap the ALU op, and restore original source\nregister if the value was in source.\n\nThe sanitation of pointer arithmetic alone is still not fully\nsufficient as is, since a scenario like the following could\nhappen ...\n\n PTR += 0x1000 (e.g. K-based imm)\n PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON\n PTR += 0x1000\n PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON\n [...]\n\n... which under speculation could end up as ...\n\n PTR += 0x1000\n PTR -= 0 [ truncated by mitigation ]\n PTR += 0x1000\n PTR -= 0 [ truncated by mitigation ]\n [...]\n\n... and therefore still access out of bounds. To prevent such\ncase, the verifier is also analyzing safety for potential out\nof bounds access under speculative execution. Meaning, it is\nalso simulating pointer access under truncation. We therefore\n\"branch off\" and push the current verification state after the\nALU operation with known 0 to the verification stack for later\nanalysis. Given the current path analysis succeeded it is\nlikely that the one under speculation can be pruned. In any\ncase, it is also subject to existing complexity limits and\ntherefore anything beyond this point will be rejected. In\nterms of pruning, it needs to be ensured that the verification\nstate from speculative execution simulation must never prune\na non-speculative execution path, therefore, we mark verifier\nstate accordingly at the time of push_stack(). If verifier\ndetects out of bounds access under speculative execution from\none of the possible paths that includes a truncation, it will\nreject such program.\n\nGiven we mask every reg-based pointer arithmetic for\nunprivileged programs, we've been looking into how it could\naffect real-world programs in terms of size increase. As the\nmajority of programs are targeted for privileged-only use\ncase, we've unconditionally enabled masking (with its alu\nrestrictions on top of it) for privileged programs for the\nsake of testing in order to check i) whether they get rejected\nin its current form, and ii) by how much the number of\ninstructions and size will increase. We've tested this by\nusing Katran, Cilium and test_l4lb from the kernel selftests.\nFor Katran we've evaluated balancer_kern.o, Cilium bpf_lxc.o\nand an older test object bpf_lxc_opt_-DUNKNOWN.o and l4lb\nwe've used test_l4lb.o as well as test_l4lb_noinline.o. We\nfound that none of the programs got rejected by the verifier\nwith this change, and that impact is rather minimal to none.\nbalancer_kern.o had 13,904 bytes (1,738 insns) xlated and\n7,797 bytes JITed before and after the change. Most complex\nprogram in bpf_lxc.o had 30,544 bytes (3,817 insns) xlated\nand 18,538 bytes JITed before and after and none of the other\ntail call programs in bpf_lxc.o had any changes either. For\nthe older bpf_lxc_opt_-DUNKNOWN.o object we found a small\nincrease from 20,616 bytes (2,576 insns) and 12,536 bytes JITed\nbefore to 20,664 bytes (2,582 insns) and 12,558 bytes JITed\nafter the change. Other programs from that object file had\nsimilar small increase. Both test_l4lb.o had no change and\nremained at 6,544 bytes (817 insns) xlated and 3,401 bytes\nJITed and for test_l4lb_noinline.o constant at 5,080 bytes\n(634 insns) xlated and 3,313 bytes JITed. This can be explained\nin that LLVM typically optimizes stack based pointer arithmetic\nby using K-based operations and that use of dynamic map access\nis not overly frequent. However, in future we may decide to\noptimize the algorithm further under known guarantees from\nbranch and value speculation. Latter seems also unclear in\nterms of prediction heuristics that today's CPUs apply as well\nas whether there could be collisions in e.g. the predictor's\nValue History/Pattern Table for triggering out of bounds access,\nthus masking is performed unconditionally at this point but could\nbe subject to relaxation later on. We were generally also\nbrainstorming various other approaches for mitigation, but the\nblocker was always lack of available registers at runtime and/or\noverhead for runtime tracking of limits belonging to a specific\npointer. Thus, we found this to be minimally intrusive under\ngiven constraints.\n\nWith that in place, a simple example with sanitized access on\nunprivileged load at post-verification time looks as follows:\n\n # bpftool prog dump xlated id 282\n [...]\n 28: (79) r1 = *(u64 *)(r7 +0)\n 29: (79) r2 = *(u64 *)(r7 +8)\n 30: (57) r1 &= 15\n 31: (79) r3 = *(u64 *)(r0 +4608)\n 32: (57) r3 &= 1\n 33: (47) r3 |= 1\n 34: (2d) if r2 > r3 goto pc+19\n 35: (b4) (u32) r11 = (u32) 20479 |\n 36: (1f) r11 -= r2 | Dynamic sanitation for pointer\n 37: (4f) r11 |= r2 | arithmetic with registers\n 38: (87) r11 = -r11 | containing bounded or known\n 39: (c7) r11 s>>= 63 | scalars in order to prevent\n 40: (5f) r11 &= r2 | out of bounds speculation.\n 41: (0f) r4 += r11 |\n 42: (71) r4 = *(u8 *)(r4 +0)\n 43: (6f) r4 <<= r1\n [...]\n\nFor the case where the scalar sits in the destination register\nas opposed to the source register, the following code is emitted\nfor the above example:\n\n [...]\n 16: (b4) (u32) r11 = (u32) 20479\n 17: (1f) r11 -= r2\n 18: (4f) r11 |= r2\n 19: (87) r11 = -r11\n 20: (c7) r11 s>>= 63\n 21: (5f) r2 &= r11\n 22: (0f) r2 += r0\n 23: (61) r0 = *(u32 *)(r2 +0)\n [...]\n\nJIT blinding example with non-conflicting use of r10:\n\n [...]\n d5:\tje 0x0000000000000106 _\n d7:\tmov 0x0(%rax),%edi |\n da:\tmov $0xf153246,%r10d | Index load from map value and\n e0:\txor $0xf153259,%r10 | (const blinded) mask with 0x1f.\n e7:\tand %r10,%rdi |_\n ea:\tmov $0x2f,%r10d |\n f0:\tsub %rdi,%r10 | Sanitized addition. Both use r10\n f3:\tor %rdi,%r10 | but do not interfere with each\n f6:\tneg %r10 | other. (Neither do these instructions\n f9:\tsar $0x3f,%r10 | interfere with the use of ax as temp\n fd:\tand %r10,%rdi | in interpreter.)\n 100:\tadd %rax,%rdi |_\n 103:\tmov 0x0(%rdi),%eax\n [...]\n\nTested that it fixes Jann's reproducer, and also checked that test_verifier\nand test_progs suite with interpreter, JIT and JIT with hardening enabled\non x86-64 and arm64 runs successfully.\n\n [0] Speculose: Analyzing the Security Implications of Speculative\n Execution in CPUs, Giorgi Maisuradze and Christian Rossow,\n https://arxiv.org/pdf/1801.04084.pdf\n\n [1] A Systematic Evaluation of Transient Execution Attacks and\n Defenses, Claudio Canella, Jo Van Bulck, Michael Schwarz,\n Moritz Lipp, Benjamin von Berg, Philipp Ortner, Frank Piessens,\n Dmitry Evtyushkin, Daniel Gruss,\n https://arxiv.org/pdf/1811.05441.pdf\n\nFixes: b2157399cc98 (\"bpf: prevent out-of-bounds speculation\")\nReported-by: Jann Horn \nSigned-off-by: Daniel Borkmann \nAcked-by: Alexei Starovoitov \nSigned-off-by: Alexei Starovoitov '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: empe_inlinepgp_encrypted_parse (EMailParserExtension *extension,\n EMailParser *parser,\n CamelMimePart *part,\n GString *part_id,\n GCancellable *cancellable,\n GQueue *out_mail_parts)\n{\n\tCamelCipherContext *cipher;\n\tCamelCipherValidity *valid;\n\tCamelMimePart *opart;\n\tCamelDataWrapper *dw;\n\tgchar *mime_type;\n\tgint len;\n\tGQueue work_queue = G_QUEUE_INIT;\n\tGList *head, *link;\n\tGError *local_error = NULL;\n\n\tif (g_cancellable_is_cancelled (cancellable))\n\t\treturn FALSE;\n\n\tcipher = camel_gpg_context_new (e_mail_parser_get_session (parser));\n\n\topart = camel_mime_part_new ();\n\n\t/* Decrypt the message */\n\tvalid = camel_cipher_context_decrypt_sync (\n\t\tcipher, part, opart, cancellable, &local_error);\n\n\tif (local_error != NULL) {\n\t\te_mail_parser_error (\n\t\t\tparser, out_mail_parts,\n\t\t\t_(\"Could not parse PGP message: %s\"),\n\t\t\tlocal_error->message);\n\t\tg_error_free (local_error);\n\n\t\te_mail_parser_parse_part_as (\n\t\t\tparser,\n\t\t\tpart, part_id,\n\t\t\t\"application/vnd.evolution.source\",\n\t\t\tcancellable, out_mail_parts);\n\n\t\tg_object_unref (cipher);\n\t\tg_object_unref (opart);\n\n\t\treturn TRUE;\n\t}\n\n\tdw = camel_medium_get_content ((CamelMedium *) opart);\n\tmime_type = camel_data_wrapper_get_mime_type (dw);\n\n\t/* this ensures to show the 'opart' as inlined, if possible */\n\tif (mime_type && g_ascii_strcasecmp (mime_type, \"application/octet-stream\") == 0) {\n\t\tconst gchar *snoop;\n\n\t\tsnoop = e_mail_part_snoop_type (opart);\n\n\t\tif (snoop != NULL) {\n\t\t\tcamel_data_wrapper_set_mime_type (dw, snoop);\n\n\t\t\t/* Set the MIME type on the 'opart' itself as well.\n\t\t\t * If it's \"text/plain\", then we want the TextPlain\n\t\t\t * parser extension to treat it as \"text/plain\" and\n\t\t\t * NOT wrap it as an attachment. */\n\t\t\tcamel_data_wrapper_set_mime_type (\n\t\t\t\tCAMEL_DATA_WRAPPER (opart), snoop);\n\t\t}\n\t}\n\n\te_mail_part_preserve_charset_in_content_type (part, opart);\n\tg_free (mime_type);\n\n\t/* Pass it off to the real formatter */\n\tlen = part_id->len;\n\tg_string_append (part_id, \".inlinepgp_encrypted\");\n\n\tmime_type = camel_data_wrapper_get_mime_type (dw);\n\n\tg_warn_if_fail (e_mail_parser_parse_part_as (\n\t\tparser, opart, part_id, mime_type,\n\t\tcancellable, &work_queue));\n\n\tg_free (mime_type);\n\n\tg_string_truncate (part_id, len);\n\n\thead = g_queue_peek_head_link (&work_queue);\n\n\tfor (link = head; link != NULL; link = g_list_next (link)) {\n\t\tEMailPart *mail_part = link->data;\n\n\t\te_mail_part_update_validity (\n\t\t\tmail_part, valid,\n\t\t\tE_MAIL_PART_VALIDITY_ENCRYPTED |\n\t\t\tE_MAIL_PART_VALIDITY_PGP);\n\t}\n\n\te_queue_transfer (&work_queue, out_mail_parts);\n\n\t/* Add a widget with details about the encryption, but only when\n\t * the encrypted isn't itself secured, in that case it has created\n\t * the button itself */\n\tif (!e_mail_part_is_secured (opart)) {\n\t\tEMailPart *mail_part;\n\n\t\tg_string_append (part_id, \".inlinepgp_encrypted.button\");\n\n\t\te_mail_parser_parse_part_as (\n\t\t\tparser, part, part_id,\n\t\t\t\"application/vnd.evolution.secure-button\",\n\t\t\tcancellable, &work_queue);\n\n\t\tmail_part = g_queue_peek_head (&work_queue);\n\t\tif (mail_part != NULL)\n\t\t\te_mail_part_update_validity (\n\t\t\t\tmail_part, valid,\n\t\t\t\tE_MAIL_PART_VALIDITY_ENCRYPTED |\n\t\t\t\tE_MAIL_PART_VALIDITY_PGP);\n\n\t\te_queue_transfer (&work_queue, out_mail_parts);\n\n\t\tg_string_truncate (part_id, len);\n\t}\n\n\t/* Clean Up */\n\tcamel_cipher_validity_free (valid);\n\tg_object_unref (opart);\n\tg_object_unref (cipher);\n\n\treturn TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-347'], 'message': 'eds-I#3 - [GPG] Mails that are not encrypted look encrypted\n\nRelated to https://gitlab.gnome.org/GNOME/evolution-data-server/issues/3'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ews_response_cb (SoupSession *session,\n SoupMessage *msg,\n gpointer data)\n{\n\tEwsNode *enode = (EwsNode *) data;\n\tESoapResponse *response;\n\tESoapParameter *param;\n\tconst gchar *persistent_auth;\n\tgint log_level;\n\tgint wait_ms = 0;\n\n\tpersistent_auth = soup_message_headers_get_one (msg->response_headers, \"Persistent-Auth\");\n\tif (persistent_auth && g_ascii_strcasecmp (persistent_auth, \"false\") == 0) {\n\t\tSoupSessionFeature *feature;\n\n\t\tfeature = soup_session_get_feature (session, SOUP_TYPE_AUTH_MANAGER);\n\t\tif (feature) {\n\t\t\tsoup_auth_manager_clear_cached_credentials (SOUP_AUTH_MANAGER (feature));\n\t\t}\n\t}\n\n\tif (g_cancellable_is_cancelled (enode->cancellable))\n\t\tgoto exit;\n\n\tif (ews_connection_credentials_failed (enode->cnc, msg, enode->simple)) {\n\t\tgoto exit;\n\t} else if (msg->status_code == SOUP_STATUS_UNAUTHORIZED) {\n\t\tif (msg->response_headers) {\n\t\t\tconst gchar *diagnostics;\n\n\t\t\tdiagnostics = soup_message_headers_get_list (msg->response_headers, \"X-MS-DIAGNOSTICS\");\n\t\t\tif (diagnostics && strstr (diagnostics, \"invalid_grant\")) {\n\t\t\t\tg_simple_async_result_set_error (\n\t\t\t\t\tenode->simple,\n\t\t\t\t\tEWS_CONNECTION_ERROR,\n\t\t\t\t\tEWS_CONNECTION_ERROR_ACCESSDENIED,\n\t\t\t\t\t\"%s\", diagnostics);\n\t\t\t\tgoto exit;\n\t\t\t} else if (diagnostics && *diagnostics) {\n\t\t\t\tg_simple_async_result_set_error (\n\t\t\t\t\tenode->simple,\n\t\t\t\t\tEWS_CONNECTION_ERROR,\n\t\t\t\t\tEWS_CONNECTION_ERROR_AUTHENTICATION_FAILED,\n\t\t\t\t\t\"%s\", diagnostics);\n\t\t\t\tgoto exit;\n\t\t\t}\n\t\t}\n\n\t\tg_simple_async_result_set_error (\n\t\t\tenode->simple,\n\t\t\tEWS_CONNECTION_ERROR,\n\t\t\tEWS_CONNECTION_ERROR_AUTHENTICATION_FAILED,\n\t\t\t_(\"Authentication failed\"));\n\t\tgoto exit;\n\t} else if (msg->status_code == SOUP_STATUS_CANT_RESOLVE ||\n\t\t msg->status_code == SOUP_STATUS_CANT_RESOLVE_PROXY ||\n\t\t msg->status_code == SOUP_STATUS_CANT_CONNECT ||\n\t\t msg->status_code == SOUP_STATUS_CANT_CONNECT_PROXY ||\n\t\t msg->status_code == SOUP_STATUS_IO_ERROR) {\n\t\tg_simple_async_result_set_error (\n\t\t\tenode->simple,\n\t\t\tEWS_CONNECTION_ERROR,\n\t\t\tEWS_CONNECTION_ERROR_UNAVAILABLE,\n\t\t\t\"%s\", msg->reason_phrase);\n\t\tgoto exit;\n\t}\n\n\tresponse = e_soap_message_parse_response ((ESoapMessage *) msg);\n\n\tif (response == NULL) {\n\t\tg_simple_async_result_set_error (\n\t\t\tenode->simple,\n\t\t\tEWS_CONNECTION_ERROR,\n\t\t\tEWS_CONNECTION_ERROR_NORESPONSE,\n\t\t\t_(\"No response: %s\"), msg->reason_phrase);\n\t\tgoto exit;\n\t}\n\n\t/* TODO: The stdout can be replaced with Evolution's\n\t * Logging framework also */\n\n\tlog_level = e_ews_debug_get_log_level ();\n\tif (log_level >= 1 && log_level < 3) {\n\t\t/* This will dump only the headers, since we stole the body.\n\t\t * And only if EWS_DEBUG=1, since higher levels will have dumped\n\t\t * it directly from libsoup anyway. */\n\t\te_ews_debug_dump_raw_soup_response (msg);\n\t\t/* And this will dump the body... */\n\t\te_soap_response_dump_response (response, stdout);\n\t}\n\n\tparam = e_soap_response_get_first_parameter_by_name (response, \"detail\", NULL);\n\tif (param)\n\t\tparam = e_soap_parameter_get_first_child_by_name (param, \"ResponseCode\");\n\tif (param) {\n\t\tgchar *value;\n\n\t\tvalue = e_soap_parameter_get_string_value (param);\n\t\tif (value && ews_get_error_code (value) == EWS_CONNECTION_ERROR_SERVERBUSY) {\n\t\t\tparam = e_soap_response_get_first_parameter_by_name (response, \"detail\", NULL);\n\t\t\tif (param)\n\t\t\t\tparam = e_soap_parameter_get_first_child_by_name (param, \"MessageXml\");\n\t\t\tif (param) {\n\t\t\t\tparam = e_soap_parameter_get_first_child_by_name (param, \"Value\");\n\t\t\t\tif (param) {\n\t\t\t\t\tg_free (value);\n\n\t\t\t\t\tvalue = e_soap_parameter_get_property (param, \"Name\");\n\t\t\t\t\tif (g_strcmp0 (value, \"BackOffMilliseconds\") == 0) {\n\t\t\t\t\t\twait_ms = e_soap_parameter_get_int_value (param);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tg_free (value);\n\t}\n\n\tif (wait_ms > 0 && e_ews_connection_get_backoff_enabled (enode->cnc)) {\n\t\tGCancellable *cancellable = enode->cancellable;\n\t\tEFlag *flag;\n\n\t\tif (cancellable)\n\t\t\tg_object_ref (cancellable);\n\t\tg_object_ref (msg);\n\n\t\tflag = e_flag_new ();\n\t\twhile (wait_ms > 0 && !g_cancellable_is_cancelled (cancellable) && msg->status_code != SOUP_STATUS_CANCELLED) {\n\t\t\tgint64 now = g_get_monotonic_time ();\n\t\t\tgint left_minutes, left_seconds;\n\n\t\t\tleft_minutes = wait_ms / 60000;\n\t\t\tleft_seconds = (wait_ms / 1000) % 60;\n\n\t\t\tif (left_minutes > 0) {\n\t\t\t\tcamel_operation_push_message (cancellable,\n\t\t\t\t\tg_dngettext (GETTEXT_PACKAGE,\n\t\t\t\t\t\t\"Exchange server is busy, waiting to retry (%d:%02d minute)\",\n\t\t\t\t\t\t\"Exchange server is busy, waiting to retry (%d:%02d minutes)\", left_minutes),\n\t\t\t\t\tleft_minutes, left_seconds);\n\t\t\t} else {\n\t\t\t\tcamel_operation_push_message (cancellable,\n\t\t\t\t\tg_dngettext (GETTEXT_PACKAGE,\n\t\t\t\t\t\t\"Exchange server is busy, waiting to retry (%d second)\",\n\t\t\t\t\t\t\"Exchange server is busy, waiting to retry (%d seconds)\", left_seconds),\n\t\t\t\t\tleft_seconds);\n\t\t\t}\n\n\t\t\te_flag_wait_until (flag, now + (G_TIME_SPAN_MILLISECOND * (wait_ms > 1000 ? 1000 : wait_ms)));\n\n\t\t\tnow = g_get_monotonic_time () - now;\n\t\t\tnow = now / G_TIME_SPAN_MILLISECOND;\n\n\t\t\tif (now >= wait_ms)\n\t\t\t\twait_ms = 0;\n\t\t\twait_ms -= now;\n\n\t\t\tcamel_operation_pop_message (cancellable);\n\t\t}\n\n\t\te_flag_free (flag);\n\n\t\tg_object_unref (response);\n\n\t\tif (g_cancellable_is_cancelled (cancellable) ||\n\t\t msg->status_code == SOUP_STATUS_CANCELLED) {\n\t\t\tg_clear_object (&cancellable);\n\t\t\tg_object_unref (msg);\n\t\t} else {\n\t\t\tEwsNode *new_node;\n\n\t\t\tnew_node = ews_node_new ();\n\t\t\tnew_node->msg = E_SOAP_MESSAGE (msg); /* takes ownership */\n\t\t\tnew_node->pri = enode->pri;\n\t\t\tnew_node->cb = enode->cb;\n\t\t\tnew_node->cnc = enode->cnc;\n\t\t\tnew_node->simple = enode->simple;\n\n\t\t\tenode->simple = NULL;\n\n\t\t\tQUEUE_LOCK (enode->cnc);\n\t\t\tenode->cnc->priv->jobs = g_slist_prepend (enode->cnc->priv->jobs, new_node);\n\t\t\tQUEUE_UNLOCK (enode->cnc);\n\n\t\t\tif (cancellable) {\n\t\t\t\tnew_node->cancellable = g_object_ref (cancellable);\n\t\t\t\tnew_node->cancel_handler_id = g_cancellable_connect (\n\t\t\t\t\tcancellable, G_CALLBACK (ews_cancel_request), new_node, NULL);\n\t\t\t}\n\n\t\t\tg_clear_object (&cancellable);\n\t\t}\n\n\t\tgoto exit;\n\t}\n\n\tif (enode->cb != NULL)\n\t\tenode->cb (response, enode->simple);\n\n\tg_object_unref (response);\n\nexit:\n\tif (enode->simple)\n\t\tg_simple_async_result_complete_in_idle (enode->simple);\n\n\tews_active_job_done (enode->cnc, enode);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-295'], 'message': 'I#27 - SSL Certificates are not validated\n\nThis depends on https://gitlab.gnome.org/GNOME/evolution-data-server/commit/6672b8236139bd6ef41ecb915f4c72e2a052dba5 too.\n\nCloses https://gitlab.gnome.org/GNOME/evolution-ews/issues/27'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: e_ews_autodiscover_ws_url_finish (CamelEwsSettings *settings,\n GAsyncResult *result,\n GError **error)\n{\n\tGSimpleAsyncResult *simple;\n\tstruct _autodiscover_data *ad;\n\n\tg_return_val_if_fail (\n\t\tg_simple_async_result_is_valid (\n\t\tresult, G_OBJECT (settings),\n\t\te_ews_autodiscover_ws_url), FALSE);\n\n\tsimple = G_SIMPLE_ASYNC_RESULT (result);\n\tad = g_simple_async_result_get_op_res_gpointer (simple);\n\n\tif (g_simple_async_result_propagate_error (simple, error))\n\t\treturn FALSE;\n\n\tg_warn_if_fail (ad->as_url != NULL);\n\tg_warn_if_fail (ad->oab_url != NULL);\n\n\tcamel_ews_settings_set_hosturl (settings, ad->as_url);\n\n\tif (!has_suffix_icmp (ad->oab_url, \"oab.xml\")) {\n\t\tgchar *tmp;\n\n\t\tif (g_str_has_suffix (ad->oab_url, \"/\"))\n\t\t\ttmp = g_strconcat (ad->oab_url, \"oab.xml\", NULL);\n\t\telse\n\t\t\ttmp = g_strconcat (ad->oab_url, \"/\", \"oab.xml\", NULL);\n\n\t\tcamel_ews_settings_set_oaburl (settings, tmp);\n\t\tg_free (tmp);\n\t} else {\n\t\tcamel_ews_settings_set_oaburl (settings, ad->oab_url);\n\t}\n\n\treturn TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-295'], 'message': 'I#27 - SSL Certificates are not validated\n\nThis depends on https://gitlab.gnome.org/GNOME/evolution-data-server/commit/6672b8236139bd6ef41ecb915f4c72e2a052dba5 too.\n\nCloses https://gitlab.gnome.org/GNOME/evolution-ews/issues/27'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: e_ews_config_utils_open_connection_for (ESource *source,\n CamelEwsSettings *ews_settings,\n\t\t\t\t\tconst gchar *connect_url,\n\t\t\t\t\tEEwsConfigUtilTryCredentialsFunc try_credentials_func,\n\t\t\t\t\tgpointer user_data,\n GCancellable *cancellable,\n GError **perror)\n{\n\tEEwsConnection *conn = NULL;\n\tCamelNetworkSettings *network_settings;\n\tGError *local_error = NULL;\n\n\tg_return_val_if_fail (source != NULL, NULL);\n\tg_return_val_if_fail (ews_settings != NULL, NULL);\n\n\tnetwork_settings = CAMEL_NETWORK_SETTINGS (ews_settings);\n\n\t/* use the one from mailer, if there, otherwise open new */\n\tconn = e_ews_connection_find (\n\t\tconnect_url && *connect_url ? connect_url : camel_ews_settings_get_hosturl (ews_settings),\n\t\tcamel_network_settings_get_user (network_settings));\n\tif (conn) {\n\t\tif (try_credentials_func &&\n\t\t try_credentials_func (conn, NULL, user_data, cancellable, perror) != E_SOURCE_AUTHENTICATION_ACCEPTED) {\n\t\t\tg_clear_object (&conn);\n\t\t}\n\t\treturn conn;\n\t}\n\n\twhile (!conn && !g_cancellable_is_cancelled (cancellable) && !local_error) {\n\t\tif (e_ews_connection_utils_get_without_password (ews_settings)) {\n\t\t\tESourceAuthenticationResult result;\n\t\t\tgchar *hosturl;\n\n\t\t\thosturl = camel_ews_settings_dup_hosturl (ews_settings);\n\t\t\tconn = e_ews_connection_new (source, connect_url && *connect_url ? connect_url : hosturl, ews_settings);\n\t\t\tg_free (hosturl);\n\n\t\t\te_ews_connection_update_credentials (conn, NULL);\n\n\t\t\tif (try_credentials_func)\n\t\t\t\tresult = try_credentials_func (conn, NULL, user_data, cancellable, &local_error);\n\t\t\telse\n\t\t\t\tresult = e_ews_connection_try_credentials_sync (conn, NULL, cancellable, &local_error);\n\n\t\t\tif (result != E_SOURCE_AUTHENTICATION_ACCEPTED) {\n\t\t\t\tg_clear_object (&conn);\n\t\t\t\tif (result != E_SOURCE_AUTHENTICATION_REJECTED || local_error)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (!conn) {\n\t\t\tEShell *shell;\n\t\t\tTryCredentialsData data;\n\n\t\t\te_ews_connection_utils_force_off_ntlm_auth_check ();\n\t\t\tg_clear_error (&local_error);\n\n\t\t\tshell = e_shell_get_default ();\n\n\t\t\tdata.ews_settings = g_object_ref (ews_settings);\n\t\t\tdata.connect_url = connect_url && *connect_url ? connect_url : NULL;\n\t\t\tdata.try_credentials_func = try_credentials_func;\n\t\t\tdata.user_data = user_data;\n\t\t\tdata.conn = NULL;\n\n\t\t\te_credentials_prompter_loop_prompt_sync (e_shell_get_credentials_prompter (shell),\n\t\t\t\tsource, E_CREDENTIALS_PROMPTER_PROMPT_FLAG_ALLOW_SOURCE_SAVE,\n\t\t\t\tews_config_utils_try_credentials_sync, &data, cancellable, &local_error);\n\n\t\t\tif (data.conn)\n\t\t\t\tconn = g_object_ref (data.conn);\n\n\t\t\tg_clear_object (&data.ews_settings);\n\t\t\tg_clear_object (&data.conn);\n\t\t}\n\t}\n\n\tif (local_error)\n\t\tg_propagate_error (perror, local_error);\n\n\treturn conn;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-295'], 'message': 'I#27 - SSL Certificates are not validated\n\nThis depends on https://gitlab.gnome.org/GNOME/evolution-data-server/commit/6672b8236139bd6ef41ecb915f4c72e2a052dba5 too.\n\nCloses https://gitlab.gnome.org/GNOME/evolution-ews/issues/27'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ns_xfr_start(ns_client_t *client, dns_rdatatype_t reqtype) {\n\tisc_result_t result;\n\tdns_name_t *question_name;\n\tdns_rdataset_t *question_rdataset;\n\tdns_zone_t *zone = NULL, *raw = NULL, *mayberaw;\n\tdns_db_t *db = NULL;\n\tdns_dbversion_t *ver = NULL;\n\tdns_rdataclass_t question_class;\n\trrstream_t *soa_stream = NULL;\n\trrstream_t *data_stream = NULL;\n\trrstream_t *stream = NULL;\n\tdns_difftuple_t *current_soa_tuple = NULL;\n\tdns_name_t *soa_name;\n\tdns_rdataset_t *soa_rdataset;\n\tdns_rdata_t soa_rdata = DNS_RDATA_INIT;\n\tbool have_soa = false;\n\tconst char *mnemonic = NULL;\n\tisc_mem_t *mctx = client->mctx;\n\tdns_message_t *request = client->message;\n\txfrout_ctx_t *xfr = NULL;\n\tisc_quota_t *quota = NULL;\n\tdns_transfer_format_t format = client->view->transfer_format;\n\tisc_netaddr_t na;\n\tdns_peer_t *peer = NULL;\n\tisc_buffer_t *tsigbuf = NULL;\n\tchar *journalfile;\n\tchar msg[NS_CLIENT_ACLMSGSIZE(\"zone transfer\")];\n\tchar keyname[DNS_NAME_FORMATSIZE];\n\tbool is_poll = false;\n\tbool is_dlz = false;\n\tbool is_ixfr = false;\n\tuint32_t begin_serial = 0, current_serial;\n\n\tswitch (reqtype) {\n\tcase dns_rdatatype_axfr:\n\t\tmnemonic = \"AXFR\";\n\t\tbreak;\n\tcase dns_rdatatype_ixfr:\n\t\tmnemonic = \"IXFR\";\n\t\tbreak;\n\tdefault:\n\t\tINSIST(0);\n\t\tISC_UNREACHABLE();\n\t}\n\n\tns_client_log(client,\n\t\t DNS_LOGCATEGORY_XFER_OUT, NS_LOGMODULE_XFER_OUT,\n\t\t ISC_LOG_DEBUG(6), \"%s request\", mnemonic);\n\t/*\n\t * Apply quota.\n\t */\n\tresult = isc_quota_attach(&ns_g_server->xfroutquota, "a);\n\tif (result != ISC_R_SUCCESS) {\n\t\tisc_log_write(XFROUT_COMMON_LOGARGS, ISC_LOG_WARNING,\n\t\t\t \"%s request denied: %s\", mnemonic,\n\t\t\t isc_result_totext(result));\n\t\tgoto failure;\n\t}\n\n\t/*\n\t * Interpret the question section.\n\t */\n\tresult = dns_message_firstname(request, DNS_SECTION_QUESTION);\n\tINSIST(result == ISC_R_SUCCESS);\n\n\t/*\n\t * The question section must contain exactly one question, and\n\t * it must be for AXFR/IXFR as appropriate.\n\t */\n\tquestion_name = NULL;\n\tdns_message_currentname(request, DNS_SECTION_QUESTION, &question_name);\n\tquestion_rdataset = ISC_LIST_HEAD(question_name->list);\n\tquestion_class = question_rdataset->rdclass;\n\tINSIST(question_rdataset->type == reqtype);\n\tif (ISC_LIST_NEXT(question_rdataset, link) != NULL)\n\t\tFAILC(DNS_R_FORMERR, \"multiple questions\");\n\tresult = dns_message_nextname(request, DNS_SECTION_QUESTION);\n\tif (result != ISC_R_NOMORE)\n\t\tFAILC(DNS_R_FORMERR, \"multiple questions\");\n\n\tresult = dns_zt_find(client->view->zonetable, question_name, 0, NULL,\n\t\t\t &zone);\n\n\tif (result != ISC_R_SUCCESS) {\n\t\t/*\n\t\t * Normal zone table does not have a match.\n\t\t * Try the DLZ database\n\t\t */\n\t\t// Temporary: only searching the first DLZ database\n\t\tif (! ISC_LIST_EMPTY(client->view->dlz_searched)) {\n\t\t\tresult = dns_dlzallowzonexfr(client->view,\n\t\t\t\t\t\t question_name,\n\t\t\t\t\t\t &client->peeraddr,\n\t\t\t\t\t\t &db);\n\n\t\t\tif (result == ISC_R_NOPERM) {\n\t\t\t\tchar _buf1[DNS_NAME_FORMATSIZE];\n\t\t\t\tchar _buf2[DNS_RDATACLASS_FORMATSIZE];\n\n\t\t\t\tresult = DNS_R_REFUSED;\n\t\t\t\tdns_name_format(question_name, _buf1,\n\t\t\t\t\t\tsizeof(_buf1));\n\t\t\t\tdns_rdataclass_format(question_class,\n\t\t\t\t\t\t _buf2, sizeof(_buf2));\n\t\t\t\tns_client_log(client, DNS_LOGCATEGORY_SECURITY,\n\t\t\t\t\t NS_LOGMODULE_XFER_OUT,\n\t\t\t\t\t ISC_LOG_ERROR,\n\t\t\t\t\t \"zone transfer '%s/%s' denied\",\n\t\t\t\t\t _buf1, _buf2);\n\t\t\t\tgoto failure;\n\t\t\t}\n\t\t\tif (result != ISC_R_SUCCESS)\n\t\t\t\tFAILQ(DNS_R_NOTAUTH, \"non-authoritative zone\",\n\t\t\t\t question_name, question_class);\n\t\t\tis_dlz = true;\n\t\t} else {\n\t\t\t/*\n\t\t\t * not DLZ and not in normal zone table, we are\n\t\t\t * not authoritative\n\t\t\t */\n\t\t\tFAILQ(DNS_R_NOTAUTH, \"non-authoritative zone\",\n\t\t\t question_name, question_class);\n\t\t}\n\t} else {\n\t\t/* zone table has a match */\n\t\tswitch(dns_zone_gettype(zone)) {\n\t\t\t/* Master and slave zones are OK for transfer. */\n\t\t\tcase dns_zone_master:\n\t\t\tcase dns_zone_slave:\n\t\t\tcase dns_zone_dlz:\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tFAILQ(DNS_R_NOTAUTH, \"non-authoritative zone\",\n\t\t\t\t question_name, question_class);\n\t\t\t}\n\t\tCHECK(dns_zone_getdb(zone, &db));\n\t\tdns_db_currentversion(db, &ver);\n\t}\n\n\txfrout_log1(client, question_name, question_class, ISC_LOG_DEBUG(6),\n\t\t \"%s question section OK\", mnemonic);\n\n\t/*\n\t * Check the authority section. Look for a SOA record with\n\t * the same name and class as the question.\n\t */\n\tfor (result = dns_message_firstname(request, DNS_SECTION_AUTHORITY);\n\t result == ISC_R_SUCCESS;\n\t result = dns_message_nextname(request, DNS_SECTION_AUTHORITY))\n\t{\n\t\tsoa_name = NULL;\n\t\tdns_message_currentname(request, DNS_SECTION_AUTHORITY,\n\t\t\t\t\t&soa_name);\n\n\t\t/*\n\t\t * Ignore data whose owner name is not the zone apex.\n\t\t */\n\t\tif (! dns_name_equal(soa_name, question_name))\n\t\t\tcontinue;\n\n\t\tfor (soa_rdataset = ISC_LIST_HEAD(soa_name->list);\n\t\t soa_rdataset != NULL;\n\t\t soa_rdataset = ISC_LIST_NEXT(soa_rdataset, link))\n\t\t{\n\t\t\t/*\n\t\t\t * Ignore non-SOA data.\n\t\t\t */\n\t\t\tif (soa_rdataset->type != dns_rdatatype_soa)\n\t\t\t\tcontinue;\n\t\t\tif (soa_rdataset->rdclass != question_class)\n\t\t\t\tcontinue;\n\n\t\t\tCHECK(dns_rdataset_first(soa_rdataset));\n\t\t\tdns_rdataset_current(soa_rdataset, &soa_rdata);\n\t\t\tresult = dns_rdataset_next(soa_rdataset);\n\t\t\tif (result == ISC_R_SUCCESS)\n\t\t\t\tFAILC(DNS_R_FORMERR,\n\t\t\t\t \"IXFR authority section \"\n\t\t\t\t \"has multiple SOAs\");\n\t\t\thave_soa = true;\n\t\t\tgoto got_soa;\n\t\t}\n\t}\n got_soa:\n\tif (result != ISC_R_NOMORE)\n\t\tCHECK(result);\n\n\txfrout_log1(client, question_name, question_class, ISC_LOG_DEBUG(6),\n\t\t \"%s authority section OK\", mnemonic);\n\n\t/*\n\t * If not a DLZ zone, decide whether to allow this transfer.\n\t */\n\tif (!is_dlz) {\n\t\tns_client_aclmsg(\"zone transfer\", question_name, reqtype,\n\t\t\t\t client->view->rdclass, msg, sizeof(msg));\n\t\tCHECK(ns_client_checkacl(client, NULL, msg,\n\t\t\t\t\t dns_zone_getxfracl(zone),\n\t\t\t\t\t true, ISC_LOG_ERROR));\n\t}\n\n\t/*\n\t * AXFR over UDP is not possible.\n\t */\n\tif (reqtype == dns_rdatatype_axfr &&\n\t (client->attributes & NS_CLIENTATTR_TCP) == 0)\n\t\tFAILC(DNS_R_FORMERR, \"attempted AXFR over UDP\");\n\n\t/*\n\t * Look up the requesting server in the peer table.\n\t */\n\tisc_netaddr_fromsockaddr(&na, &client->peeraddr);\n\t(void)dns_peerlist_peerbyaddr(client->view->peers, &na, &peer);\n\n\t/*\n\t * Decide on the transfer format (one-answer or many-answers).\n\t */\n\tif (peer != NULL)\n\t\t(void)dns_peer_gettransferformat(peer, &format);\n\n\t/*\n\t * Get a dynamically allocated copy of the current SOA.\n\t */\n\tif (is_dlz)\n\t\tdns_db_currentversion(db, &ver);\n\n\tCHECK(dns_db_createsoatuple(db, ver, mctx, DNS_DIFFOP_EXISTS,\n\t\t\t\t ¤t_soa_tuple));\n\n\tcurrent_serial = dns_soa_getserial(¤t_soa_tuple->rdata);\n\tif (reqtype == dns_rdatatype_ixfr) {\n\t\tbool provide_ixfr;\n\n\t\t/*\n\t\t * Outgoing IXFR may have been disabled for this peer\n\t\t * or globally.\n\t\t */\n\t\tprovide_ixfr = client->view->provideixfr;\n\t\tif (peer != NULL)\n\t\t\t(void) dns_peer_getprovideixfr(peer, &provide_ixfr);\n\t\tif (provide_ixfr == false)\n\t\t\tgoto axfr_fallback;\n\n\t\tif (! have_soa)\n\t\t\tFAILC(DNS_R_FORMERR,\n\t\t\t \"IXFR request missing SOA\");\n\n\t\tbegin_serial = dns_soa_getserial(&soa_rdata);\n\n\t\t/*\n\t\t * RFC1995 says \"If an IXFR query with the same or\n\t\t * newer version number than that of the server\n\t\t * is received, it is replied to with a single SOA\n\t\t * record of the server's current version, just as\n\t\t * in AXFR\". The claim about AXFR is incorrect,\n\t\t * but other than that, we do as the RFC says.\n\t\t *\n\t\t * Sending a single SOA record is also how we refuse\n\t\t * IXFR over UDP (currently, we always do).\n\t\t */\n\t\tif (DNS_SERIAL_GE(begin_serial, current_serial) ||\n\t\t (client->attributes & NS_CLIENTATTR_TCP) == 0)\n\t\t{\n\t\t\tCHECK(soa_rrstream_create(mctx, db, ver, &stream));\n\t\t\tis_poll = true;\n\t\t\tgoto have_stream;\n\t\t}\n\t\tjournalfile = is_dlz ? NULL : dns_zone_getjournal(zone);\n\t\tif (journalfile != NULL)\n\t\t\tresult = ixfr_rrstream_create(mctx,\n\t\t\t\t\t\t journalfile,\n\t\t\t\t\t\t begin_serial,\n\t\t\t\t\t\t current_serial,\n\t\t\t\t\t\t &data_stream);\n\t\telse\n\t\t\tresult = ISC_R_NOTFOUND;\n\t\tif (result == ISC_R_NOTFOUND ||\n\t\t result == ISC_R_RANGE) {\n\t\t\txfrout_log1(client, question_name, question_class,\n\t\t\t\t ISC_LOG_DEBUG(4),\n\t\t\t\t \"IXFR version not in journal, \"\n\t\t\t\t \"falling back to AXFR\");\n\t\t\tmnemonic = \"AXFR-style IXFR\";\n\t\t\tgoto axfr_fallback;\n\t\t}\n\t\tCHECK(result);\n\t\tis_ixfr = true;\n\t} else {\n\taxfr_fallback:\n\t\tCHECK(axfr_rrstream_create(mctx, db, ver, &data_stream));\n\t}\n\n\t/*\n\t * Bracket the data stream with SOAs.\n\t */\n\tCHECK(soa_rrstream_create(mctx, db, ver, &soa_stream));\n\tCHECK(compound_rrstream_create(mctx, &soa_stream, &data_stream,\n\t\t\t\t &stream));\n\tsoa_stream = NULL;\n\tdata_stream = NULL;\n\n have_stream:\n\tCHECK(dns_message_getquerytsig(request, mctx, &tsigbuf));\n\t/*\n\t * Create the xfrout context object. This transfers the ownership\n\t * of \"stream\", \"db\", \"ver\", and \"quota\" to the xfrout context object.\n\t */\n\n\n\n\tif (is_dlz)\n\t\tCHECK(xfrout_ctx_create(mctx, client, request->id,\n\t\t\t\t\tquestion_name, reqtype, question_class,\n\t\t\t\t\tzone, db, ver, quota, stream,\n\t\t\t\t\tdns_message_gettsigkey(request),\n\t\t\t\t\ttsigbuf,\n\t\t\t\t\trequest->verified_sig,\n\t\t\t\t\t3600,\n\t\t\t\t\t3600,\n\t\t\t\t\t(format == dns_many_answers) ?\n\t\t\t\t\ttrue : false,\n\t\t\t\t\t&xfr));\n\telse\n\t\tCHECK(xfrout_ctx_create(mctx, client, request->id,\n\t\t\t\t\tquestion_name, reqtype, question_class,\n\t\t\t\t\tzone, db, ver, quota, stream,\n\t\t\t\t\tdns_message_gettsigkey(request),\n\t\t\t\t\ttsigbuf,\n\t\t\t\t\trequest->verified_sig,\n\t\t\t\t\tdns_zone_getmaxxfrout(zone),\n\t\t\t\t\tdns_zone_getidleout(zone),\n\t\t\t\t\t(format == dns_many_answers) ?\n\t\t\t\t\ttrue : false,\n\t\t\t\t\t&xfr));\n\n\txfr->mnemonic = mnemonic;\n\tstream = NULL;\n\tquota = NULL;\n\n\tCHECK(xfr->stream->methods->first(xfr->stream));\n\n\tif (xfr->tsigkey != NULL)\n\t\tdns_name_format(&xfr->tsigkey->name, keyname, sizeof(keyname));\n\telse\n\t\tkeyname[0] = '\\0';\n\tif (is_poll)\n\t\txfrout_log1(client, question_name, question_class,\n\t\t\t ISC_LOG_DEBUG(1), \"IXFR poll up to date%s%s\",\n\t\t\t (xfr->tsigkey != NULL) ? \": TSIG \" : \"\", keyname);\n\telse if (is_ixfr)\n\t\txfrout_log1(client, question_name, question_class,\n\t\t\t ISC_LOG_INFO, \"%s started%s%s (serial %u -> %u)\",\n\t\t\t mnemonic, (xfr->tsigkey != NULL) ? \": TSIG \" : \"\",\n\t\t\t keyname, begin_serial, current_serial);\n\telse\n\t\txfrout_log1(client, question_name, question_class,\n\t\t\t ISC_LOG_INFO, \"%s started%s%s (serial %u)\",\n\t\t\t mnemonic, (xfr->tsigkey != NULL) ? \": TSIG \" : \"\",\n\t\t\t keyname, current_serial);\n\n\n\tif (zone != NULL) {\n\t\tdns_zone_getraw(zone, &raw);\n\t\tmayberaw = (raw != NULL) ? raw : zone;\n\t\tif ((client->attributes & NS_CLIENTATTR_WANTEXPIRE) != 0 &&\n\t\t dns_zone_gettype(mayberaw) == dns_zone_slave) {\n\t\t\tisc_time_t expiretime;\n\t\t\tuint32_t secs;\n\t\t\tdns_zone_getexpiretime(zone, &expiretime);\n\t\t\tsecs = isc_time_seconds(&expiretime);\n\t\t\tif (secs >= client->now && result == ISC_R_SUCCESS) {\n\t\t\t\tclient->attributes |= NS_CLIENTATTR_HAVEEXPIRE;\n\t\t\t\tclient->expire = secs - client->now;\n\t\t\t}\n\t\t}\n\t\tif (raw != NULL)\n\t\t\tdns_zone_detach(&raw);\n\t}\n\n\t/*\n\t * Hand the context over to sendstream(). Set xfr to NULL;\n\t * sendstream() is responsible for either passing the\n\t * context on to a later event handler or destroying it.\n\t */\n\tsendstream(xfr);\n\txfr = NULL;\n\n\tresult = ISC_R_SUCCESS;\n\n failure:\n\tif (result == DNS_R_REFUSED)\n\t\tinc_stats(zone, dns_nsstatscounter_xfrrej);\n\tif (quota != NULL)\n\t\tisc_quota_detach("a);\n\tif (current_soa_tuple != NULL)\n\t\tdns_difftuple_free(¤t_soa_tuple);\n\tif (stream != NULL)\n\t\tstream->methods->destroy(&stream);\n\tif (soa_stream != NULL)\n\t\tsoa_stream->methods->destroy(&soa_stream);\n\tif (data_stream != NULL)\n\t\tdata_stream->methods->destroy(&data_stream);\n\tif (ver != NULL)\n\t\tdns_db_closeversion(db, &ver, false);\n\tif (db != NULL)\n\t\tdns_db_detach(&db);\n\tif (zone != NULL)\n\t\tdns_zone_detach(&zone);\n\t/* XXX kludge */\n\tif (xfr != NULL) {\n\t\txfrout_fail(xfr, result, \"setting up zone transfer\");\n\t} else if (result != ISC_R_SUCCESS) {\n\t\tns_client_log(client, DNS_LOGCATEGORY_XFER_OUT,\n\t\t\t NS_LOGMODULE_XFER_OUT,\n\t\t\t ISC_LOG_DEBUG(3), \"zone transfer setup failed\");\n\t\tns_client_error(client, result);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-732'], 'message': 'denied axfr requests were not effective for writable DLZ zones\n\n(cherry picked from commit d9077cd0038e59726e1956de18b4b7872038a283)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static VTermState *vterm_state_new(VTerm *vt)\n{\n VTermState *state = vterm_allocator_malloc(vt, sizeof(VTermState));\n\n state->vt = vt;\n\n state->rows = vt->rows;\n state->cols = vt->cols;\n\n state->mouse_col = 0;\n state->mouse_row = 0;\n state->mouse_buttons = 0;\n\n state->mouse_protocol = MOUSE_X10;\n\n state->callbacks = NULL;\n state->cbdata = NULL;\n\n vterm_state_newpen(state);\n\n state->bold_is_highbright = 0;\n\n return state;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'patch 8.1.0633: crash when out of memory while opening a terminal window\n\nProblem: Crash when out of memory while opening a terminal window.\nSolution: Handle out-of-memory more gracefully.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: VTerm *vterm_new_with_allocator(int rows, int cols, VTermAllocatorFunctions *funcs, void *allocdata)\n{\n /* Need to bootstrap using the allocator function directly */\n VTerm *vt = (*funcs->malloc)(sizeof(VTerm), allocdata);\n\n vt->allocator = funcs;\n vt->allocdata = allocdata;\n\n vt->rows = rows;\n vt->cols = cols;\n\n vt->parser.state = NORMAL;\n\n vt->parser.callbacks = NULL;\n vt->parser.cbdata = NULL;\n\n vt->parser.strbuffer_len = 500; /* should be able to hold an OSC string */\n vt->parser.strbuffer_cur = 0;\n vt->parser.strbuffer = vterm_allocator_malloc(vt, vt->parser.strbuffer_len);\n\n vt->outbuffer_len = 200;\n vt->outbuffer_cur = 0;\n vt->outbuffer = vterm_allocator_malloc(vt, vt->outbuffer_len);\n\n return vt;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'patch 8.1.0633: crash when out of memory while opening a terminal window\n\nProblem: Crash when out of memory while opening a terminal window.\nSolution: Handle out-of-memory more gracefully.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static bool context_has_no_new_privileges(const ExecContext *c) {\n assert(c);\n\n if (c->no_new_privileges)\n return true;\n\n if (have_effective_cap(CAP_SYS_ADMIN)) /* if we are privileged, we don't need NNP */\n return false;\n\n /* We need NNP if we have any form of seccomp and are unprivileged */\n return context_has_address_families(c) ||\n c->memory_deny_write_execute ||\n c->restrict_realtime ||\n exec_context_restrict_namespaces_set(c) ||\n c->protect_kernel_tunables ||\n c->protect_kernel_modules ||\n c->private_devices ||\n context_has_syscall_filters(c) ||\n !set_isempty(c->syscall_archs) ||\n c->lock_personality ||\n c->protect_hostname;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-269'], 'message': 'core: expose SUID/SGID restriction as new unit setting RestrictSUIDSGID='" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: compile_string_node(Node* node, regex_t* reg)\n{\n int r, len, prev_len, slen, ambig;\n OnigEncoding enc = reg->enc;\n UChar *p, *prev, *end;\n StrNode* sn;\n\n sn = NSTR(node);\n if (sn->end <= sn->s)\n return 0;\n\n end = sn->end;\n ambig = NSTRING_IS_AMBIG(node);\n\n p = prev = sn->s;\n prev_len = enclen(enc, p);\n p += prev_len;\n slen = 1;\n\n for (; p < end; ) {\n len = enclen(enc, p);\n if (len == prev_len) {\n slen++;\n }\n else {\n r = add_compile_string(prev, prev_len, slen, reg, ambig);\n if (r) return r;\n\n prev = p;\n slen = 1;\n prev_len = len;\n }\n\n p += len;\n }\n return add_compile_string(prev, prev_len, slen, reg, ambig);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #77371 (heap buffer overflow in mb regex functions - compile_string_node)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: jio_snprintf(char * str, int n, const char * format, ...)\n{\n\tva_list args;\n\tint result;\n\n\tTrc_SC_snprintf_Entry();\n\n\tva_start(args, format);\n#if defined(WIN32) && !defined(WIN32_IBMC)\n\tresult = _vsnprintf( str, n, format, args );\n#else\n\tresult = vsprintf( str, format, args );\n#endif\n\tva_end(args);\n\n\tTrc_SC_snprintf_Exit(result);\n\n\treturn result;\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Clean up jio_snprintf and jio_vfprintf\n\nFixes https://bugs.eclipse.org/bugs/show_bug.cgi?id=543659\n\nSigned-off-by: Peter Bain '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static gboolean DecodeHeader(unsigned char *BFH, unsigned char *BIH,\n struct bmp_progressive_state *State,\n GError **error)\n{\n\tgint clrUsed;\n\n\t/* First check for the two first bytes content. A sane\n\t BMP file must start with bytes 0x42 0x4D. */\n\tif (*BFH != 0x42 || *(BFH + 1) != 0x4D) {\n\t\tg_set_error_literal (error,\n GDK_PIXBUF_ERROR,\n GDK_PIXBUF_ERROR_CORRUPT_IMAGE,\n _(\"BMP image has bogus header data\"));\n\t\tState->read_state = READ_STATE_ERROR;\n\t\treturn FALSE;\n\t}\n\n /* FIXME this is totally unrobust against bogus image data. */\n\tif (State->BufferSize < lsb_32 (&BIH[0]) + 14) {\n\t\tState->BufferSize = lsb_32 (&BIH[0]) + 14;\n\t\tif (!grow_buffer (State, error))\n\t\t\treturn FALSE;\n\t\treturn TRUE;\n\t}\n\n#if DUMPBIH\n\tDumpBIH(BIH);\n#endif \n\n\tState->Header.size = lsb_32 (&BIH[0]);\n\tif (State->Header.size == 124) {\n /* BMP v5 */\n\t\tState->Header.width = lsb_32 (&BIH[4]);\n\t\tState->Header.height = lsb_32 (&BIH[8]);\n\t\tState->Header.depth = lsb_16 (&BIH[14]);\n\t\tState->Compressed = lsb_32 (&BIH[16]);\n\t} else if (State->Header.size == 108) {\n /* BMP v4 */\n\t\tState->Header.width = lsb_32 (&BIH[4]);\n\t\tState->Header.height = lsb_32 (&BIH[8]);\n\t\tState->Header.depth = lsb_16 (&BIH[14]);\n\t\tState->Compressed = lsb_32 (&BIH[16]);\n\t} else if (State->Header.size == 64) {\n /* BMP OS/2 v2 */\n\t\tState->Header.width = lsb_32 (&BIH[4]);\n\t\tState->Header.height = lsb_32 (&BIH[8]);\n\t\tState->Header.depth = lsb_16 (&BIH[14]);\n\t\tState->Compressed = lsb_32 (&BIH[16]);\n\t} else if (State->Header.size == 40) {\n /* BMP v3 */ \n\t\tState->Header.width = lsb_32 (&BIH[4]);\n\t\tState->Header.height = lsb_32 (&BIH[8]);\n\t\tState->Header.depth = lsb_16 (&BIH[14]);\n\t\tState->Compressed = lsb_32 (&BIH[16]);\n\t} else if (State->Header.size == 12) {\n /* BMP OS/2 */\n\t\tState->Header.width = lsb_16 (&BIH[4]);\n\t\tState->Header.height = lsb_16 (&BIH[6]);\n\t\tState->Header.depth = lsb_16 (&BIH[10]);\n\t\tState->Compressed = BI_RGB;\n\t} else {\n\t\tg_set_error_literal (error,\n GDK_PIXBUF_ERROR,\n GDK_PIXBUF_ERROR_CORRUPT_IMAGE,\n _(\"BMP image has unsupported header size\"));\n\t\tState->read_state = READ_STATE_ERROR;\n\t\treturn FALSE;\n\t}\n\n if (State->Header.depth > 32)\n {\n\t\tg_set_error_literal (error,\n GDK_PIXBUF_ERROR,\n GDK_PIXBUF_ERROR_CORRUPT_IMAGE,\n _(\"BMP image has unsupported depth\"));\n\t\tState->read_state = READ_STATE_ERROR;\n }\n\n\tif (State->Header.size == 12)\n\t\tclrUsed = 1 << State->Header.depth;\n\telse\n\t\tclrUsed = (int) (BIH[35] << 24) + (BIH[34] << 16) + (BIH[33] << 8) + (BIH[32]);\n\n\tif (clrUsed != 0)\n\t\tState->Header.n_colors = clrUsed;\n\telse\n State->Header.n_colors = (1 << State->Header.depth);\n\n\tState->Type = State->Header.depth;\t/* This may be less trivial someday */\n\n\t/* Negative heights indicates bottom-down pixelorder */\n\tif (State->Header.height < 0) {\n\t\tState->Header.height = -State->Header.height;\n\t\tState->Header.Negative = 1;\n\t}\n\n\tif (State->Header.Negative && \n\t (State->Compressed != BI_RGB && State->Compressed != BI_BITFIELDS))\n\t{\n\t\tg_set_error_literal (error,\n GDK_PIXBUF_ERROR,\n GDK_PIXBUF_ERROR_CORRUPT_IMAGE,\n _(\"Topdown BMP images cannot be compressed\"));\n\t\tState->read_state = READ_STATE_ERROR;\n\t\treturn FALSE;\n\t}\n\n\tif (State->Header.width <= 0 || State->Header.height == 0 ||\n\t (State->Compressed == BI_RLE4 && State->Type != 4) ||\n\t (State->Compressed == BI_RLE8 && State->Type != 8)\t ||\n\t (State->Compressed == BI_BITFIELDS && !(State->Type == 16 || State->Type == 32)) ||\n\t (State->Compressed > BI_BITFIELDS)) {\n\t\tg_set_error_literal (error,\n GDK_PIXBUF_ERROR,\n GDK_PIXBUF_ERROR_CORRUPT_IMAGE,\n _(\"BMP image has bogus header data\"));\n\t\tState->read_state = READ_STATE_ERROR;\n\t\treturn FALSE;\n\t}\n\n\tif (State->Type == 32)\n\t\tState->LineWidth = State->Header.width * 4;\n\telse if (State->Type == 24)\n\t\tState->LineWidth = State->Header.width * 3;\n\telse if (State->Type == 16)\n\t\tState->LineWidth = State->Header.width * 2;\n\telse if (State->Type == 8)\n\t\tState->LineWidth = State->Header.width * 1;\n\telse if (State->Type == 4)\n\t\tState->LineWidth = (State->Header.width + 1) / 2;\n\telse if (State->Type == 1) {\n\t\tState->LineWidth = State->Header.width / 8;\n\t\tif ((State->Header.width & 7) != 0)\n\t\t\tState->LineWidth++;\n\t} else {\n\t\tg_set_error_literal (error,\n GDK_PIXBUF_ERROR,\n GDK_PIXBUF_ERROR_CORRUPT_IMAGE,\n _(\"BMP image has bogus header data\"));\n\t\tState->read_state = READ_STATE_ERROR;\n\t\treturn FALSE;\n\t}\n\n\t/* Pad to a 32 bit boundary */\n\tif (((State->LineWidth % 4) > 0)\n\t && (State->Compressed == BI_RGB || State->Compressed == BI_BITFIELDS))\n\t\tState->LineWidth = (State->LineWidth / 4) * 4 + 4;\n\n\tif (State->pixbuf == NULL) {\n\t\tif (State->size_func) {\n\t\t\tgint width = State->Header.width;\n\t\t\tgint height = State->Header.height;\n\n\t\t\t(*State->size_func) (&width, &height, State->user_data);\n\t\t\tif (width == 0 || height == 0) {\n\t\t\t\tState->read_state = READ_STATE_DONE;\n\t\t\t\tState->BufferSize = 0;\n\t\t\t\treturn TRUE;\n\t\t\t}\n\t\t}\n\n\t\tif (State->Type == 32 || \n\t\t State->Compressed == BI_RLE4 || \n\t\t State->Compressed == BI_RLE8)\n\t\t\tState->pixbuf =\n\t\t\t\tgdk_pixbuf_new(GDK_COLORSPACE_RGB, TRUE, 8,\n\t\t\t\t\t (gint) State->Header.width,\n\t\t\t\t\t (gint) State->Header.height);\n\t\telse\n\t\t\tState->pixbuf =\n\t\t\t\tgdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8,\n\t\t\t\t\t (gint) State->Header.width,\n\t\t\t\t\t (gint) State->Header.height);\n\t\t\n\t\tif (State->pixbuf == NULL) {\n\t\t\tg_set_error_literal (error,\n GDK_PIXBUF_ERROR,\n GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,\n _(\"Not enough memory to load bitmap image\"));\n\t\t\tState->read_state = READ_STATE_ERROR;\n\t\t\treturn FALSE;\n\t\t\t}\n\t\t\n\t\tif (State->prepared_func != NULL)\n\t\t\t/* Notify the client that we are ready to go */\n\t\t\t(*State->prepared_func) (State->pixbuf, NULL, State->user_data);\n\t\t\n\t\t/* make all pixels initially transparent */\n\t\tif (State->Compressed == BI_RLE4 || State->Compressed == BI_RLE8) {\n\t\t\tmemset (State->pixbuf->pixels, 0, State->pixbuf->rowstride * State->Header.height);\n\t\t\tState->compr.p = State->pixbuf->pixels \n\t\t\t\t+ State->pixbuf->rowstride * (State->Header.height- 1);\n\t\t}\n\t}\n\t\n\tState->BufferDone = 0;\n\tif (State->Type <= 8) {\n gint samples;\n\n\t\tState->read_state = READ_STATE_PALETTE;\n\n\t\t/* Allocate enough to hold the palette */\n\t samples = (State->Header.size == 12 ? 3 : 4);\n\t\tState->BufferSize = State->Header.n_colors * samples;\n\n\t\t/* Skip over everything between the palette and the data.\n\t\t This protects us against a malicious BFH[10] value.\n */\n\t\tState->BufferPadding = (lsb_32 (&BFH[10]) - 14 - State->Header.size) - State->BufferSize;\n\n\t} else if (State->Compressed == BI_RGB) {\n\t\tif (State->BufferSize < lsb_32 (&BFH[10]))\n\t\t{\n\t\t\t/* skip over padding between headers and image data */\n\t\t\tState->read_state = READ_STATE_HEADERS;\n\t\t\tState->BufferDone = State->BufferSize;\n\t\t\tState->BufferSize = lsb_32 (&BFH[10]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tState->read_state = READ_STATE_DATA;\n\t\t\tState->BufferSize = State->LineWidth;\n\t\t}\n\t} else if (State->Compressed == BI_BITFIELDS) {\n if (State->Header.size == 108 || State->Header.size == 124) \n {\n\t\t\t/* v4 and v5 have the bitmasks in the header */\n\t\t\tif (!decode_bitmasks (&BIH[40], State, error)) {\n\t\t\t State->read_state = READ_STATE_ERROR;\n\t\t\t return FALSE;\n }\n }\n else \n {\n\t\t State->read_state = READ_STATE_BITMASKS;\n\t\t State->BufferSize = 12;\n }\n\t} else {\n\t\tg_set_error_literal (error,\n GDK_PIXBUF_ERROR,\n GDK_PIXBUF_ERROR_CORRUPT_IMAGE,\n _(\"BMP image has bogus header data\"));\n\t\tState->read_state = READ_STATE_ERROR;\n\t\treturn FALSE;\n\t}\n\n\tif (!grow_buffer (State, error)) \n\t\treturn FALSE;\n\n return TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'bmp: Reject impossible palette size\n\nbmp headers contain separate fields for the number of colors,\nand the bit depth. Catch the impossible n_colors > 1 << depth\nand error early, before it causes a out-of-bounds memory\naccess when decoding the colormap.\n\nhttps://bugzilla.gnome.org/show_bug.cgi?id=758991'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: * Elliptic Curve Key Exchange\n */\n\nstatic int curve25519_sha256(LIBSSH2_SESSION *session, unsigned char *data,\n size_t data_len, unsigned char public_key[LIBSSH2_ED25519_KEY_LEN],\n unsigned char private_key[LIBSSH2_ED25519_KEY_LEN],\n kmdhgGPshakex_state_t *exchange_state)\n{\n int ret = 0;\n int rc;\n int public_key_len = LIBSSH2_ED25519_KEY_LEN;\n\n if(data_len < 5) {\n return _libssh2_error(session, LIBSSH2_ERROR_HOSTKEY_INIT,\n \"Data is too short\");\n }\n\n if(exchange_state->state == libssh2_NB_state_idle) {\n\n /* Setup initial values */\n exchange_state->k = _libssh2_bn_init();\n\n exchange_state->state = libssh2_NB_state_created;\n }\n\n if( exchange_state->state == libssh2_NB_state_created) {\n /* parse INIT reply data */\n\n /*host key K_S*/\n unsigned char *s = data + 1; //advance past packet type\n unsigned char *server_public_key;\n size_t server_public_key_len;\n size_t host_sig_len;\n\n session->server_hostkey_len = _libssh2_ntohu32((const unsigned char*)s);\n s += 4;\n\n session->server_hostkey = LIBSSH2_ALLOC(session, session->server_hostkey_len);\n if(!session->server_hostkey) {\n ret = _libssh2_error(session, LIBSSH2_ERROR_ALLOC,\n \"Unable to allocate memory for a copy \"\n \"of the host key\");\n goto clean_exit;\n }\n\n memcpy(session->server_hostkey, s, session->server_hostkey_len);\n s += session->server_hostkey_len;\n\n#if LIBSSH2_MD5\n {\n libssh2_md5_ctx fingerprint_ctx;\n\n if(libssh2_md5_init(&fingerprint_ctx)) {\n libssh2_md5_update(fingerprint_ctx, session->server_hostkey,\n session->server_hostkey_len);\n libssh2_md5_final(fingerprint_ctx, session->server_hostkey_md5);\n session->server_hostkey_md5_valid = TRUE;\n }\n else {\n session->server_hostkey_md5_valid = FALSE;\n }\n }\n#ifdef LIBSSH2DEBUG\n {\n char fingerprint[50], *fprint = fingerprint;\n int i;\n for(i = 0; i < 16; i++, fprint += 3) {\n snprintf(fprint, 4, \"%02x:\", session->server_hostkey_md5[i]);\n }\n *(--fprint) = '\\0';\n _libssh2_debug(session, LIBSSH2_TRACE_KEX,\n \"Server's MD5 Fingerprint: %s\", fingerprint);\n }\n#endif /* LIBSSH2DEBUG */\n#endif /* ! LIBSSH2_MD5 */\n\n {\n libssh2_sha1_ctx fingerprint_ctx;\n\n if(libssh2_sha1_init(&fingerprint_ctx)) {\n libssh2_sha1_update(fingerprint_ctx, session->server_hostkey,\n session->server_hostkey_len);\n libssh2_sha1_final(fingerprint_ctx, session->server_hostkey_sha1);\n session->server_hostkey_sha1_valid = TRUE;\n }\n else {\n session->server_hostkey_sha1_valid = FALSE;\n }\n }\n#ifdef LIBSSH2DEBUG\n {\n char fingerprint[64], *fprint = fingerprint;\n int i;\n\n for(i = 0; i < 20; i++, fprint += 3) {\n snprintf(fprint, 4, \"%02x:\", session->server_hostkey_sha1[i]);\n }\n *(--fprint) = '\\0';\n _libssh2_debug(session, LIBSSH2_TRACE_KEX,\n \"Server's SHA1 Fingerprint: %s\", fingerprint);\n }\n#endif /* LIBSSH2DEBUG */\n\n /* SHA256 */\n {\n libssh2_sha256_ctx fingerprint_ctx;\n\n if(libssh2_sha256_init(&fingerprint_ctx)) {\n libssh2_sha256_update(fingerprint_ctx, session->server_hostkey,\n session->server_hostkey_len);\n libssh2_sha256_final(fingerprint_ctx, session->server_hostkey_sha256);\n session->server_hostkey_sha256_valid = TRUE;\n }\n else {\n session->server_hostkey_sha256_valid = FALSE;\n }\n }\n#ifdef LIBSSH2DEBUG\n {\n char *base64Fingerprint = NULL;\n _libssh2_base64_encode(session, (const char*)session->server_hostkey_sha256, SHA256_DIGEST_LENGTH, &base64Fingerprint);\n if( base64Fingerprint != NULL) {\n _libssh2_debug(session, LIBSSH2_TRACE_KEX,\n \"Server's SHA256 Fingerprint: %s\", base64Fingerprint);\n LIBSSH2_FREE(session, base64Fingerprint);\n }\n }\n#endif /* LIBSSH2DEBUG */\n\n if(session->hostkey->init(session, session->server_hostkey,\n session->server_hostkey_len,\n &session->server_hostkey_abstract)) {\n ret = _libssh2_error(session, LIBSSH2_ERROR_HOSTKEY_INIT,\n \"Unable to initialize hostkey importer\");\n goto clean_exit;\n }\n\n /* server public key Q_S */\n server_public_key_len = _libssh2_ntohu32((const unsigned char*)s);\n s += 4;\n\n if( server_public_key_len != LIBSSH2_ED25519_KEY_LEN) {\n ret = _libssh2_error(session, LIBSSH2_ERROR_HOSTKEY_INIT,\n \"Unexpected curve25519 server public key length\");\n goto clean_exit;\n }\n\n server_public_key = s;\n s += server_public_key_len;\n\n /* server signature */\n host_sig_len = _libssh2_ntohu32((const unsigned char*)s);\n s += 4;\n\n exchange_state->h_sig = s;\n exchange_state->h_sig_len = host_sig_len;\n s += host_sig_len;\n\n // Compute the shared secret K\n rc = _libssh2_curve25519_gen_k(&exchange_state->k, private_key, server_public_key);\n if( rc != 0) {\n ret = _libssh2_error(session, LIBSSH2_ERROR_KEX_FAILURE,\n \"Unable to create ECDH shared secret\");\n goto clean_exit;\n }\n\n exchange_state->k_value_len = _libssh2_bn_bytes(exchange_state->k) + 5;\n if(_libssh2_bn_bits(exchange_state->k) % 8) {\n // don't need leading 00\n exchange_state->k_value_len--;\n }\n exchange_state->k_value =\n LIBSSH2_ALLOC(session, exchange_state->k_value_len);\n if(!exchange_state->k_value) {\n ret = _libssh2_error(session, LIBSSH2_ERROR_ALLOC,\n \"Unable to allocate buffer for K\");\n goto clean_exit;\n }\n _libssh2_htonu32(exchange_state->k_value,\n exchange_state->k_value_len - 4);\n if(_libssh2_bn_bits(exchange_state->k) % 8) {\n _libssh2_bn_to_bin(exchange_state->k, exchange_state->k_value + 4);\n } else {\n exchange_state->k_value[4] = 0;\n _libssh2_bn_to_bin(exchange_state->k, exchange_state->k_value + 5);\n }\n\n // verify hash\n LIBSSH2_KEX_METHOD_EC_SHA_HASH_CREATE_VERIFY(256);\n\n if( rc != 0) {\n ret = _libssh2_error(session, LIBSSH2_ERROR_HOSTKEY_SIGN,\n \"Unable to verify hostkey signature\");\n goto clean_exit;\n }\n\n exchange_state->c = SSH_MSG_NEWKEYS;\n exchange_state->state = libssh2_NB_state_sent;\n }\n\n if(exchange_state->state == libssh2_NB_state_sent) {\n rc = _libssh2_transport_send(session, &exchange_state->c, 1, NULL, 0);\n if(rc == LIBSSH2_ERROR_EAGAIN) {\n return rc;\n } else if(rc) {\n ret = _libssh2_error(session, rc, \"Unable to send NEWKEYS message\");\n goto clean_exit;\n }\n\n exchange_state->state = libssh2_NB_state_sent2;\n }\n\n if(exchange_state->state == libssh2_NB_state_sent2) {\n rc = _libssh2_packet_require(session, SSH_MSG_NEWKEYS,\n &exchange_state->tmp,\n &exchange_state->tmp_len, 0, NULL, 0,\n &exchange_state->req_state);\n if(rc == LIBSSH2_ERROR_EAGAIN) {\n return rc;\n } else if(rc) {\n ret = _libssh2_error(session, rc, \"Timed out waiting for NEWKEYS\");\n goto clean_exit;\n }\n\n // The first key exchange has been performed, switch to active crypt/comp/mac mode\n session->state |= LIBSSH2_STATE_NEWKEYS;\n _libssh2_debug(session, LIBSSH2_TRACE_KEX, \"Received NEWKEYS message\");\n\n // This will actually end up being just packet_type(1) for this packet type anyway\n LIBSSH2_FREE(session, exchange_state->tmp);\n\n if(!session->session_id) {\n\n size_t digest_length = SHA256_DIGEST_LENGTH;\n session->session_id = LIBSSH2_ALLOC(session, digest_length);\n if(!session->session_id) {\n ret = _libssh2_error(session, LIBSSH2_ERROR_ALLOC,\n \"Unable to allocate buffer for SHA digest\");\n goto clean_exit;\n }\n memcpy(session->session_id, exchange_state->h_sig_comp,\n digest_length);\n session->session_id_len = digest_length;\n _libssh2_debug(session, LIBSSH2_TRACE_KEX, \"session_id calculated\");\n }\n\n // Cleanup any existing cipher\n if(session->local.crypt->dtor) {\n session->local.crypt->dtor(session,\n &session->local.crypt_abstract);\n }\n\n // Calculate IV/Secret/Key for each direction\n if(session->local.crypt->init) {\n unsigned char *iv = NULL, *secret = NULL;\n int free_iv = 0, free_secret = 0;\n\n LIBSSH2_KEX_METHOD_SHA_VALUE_HASH(256, iv,\n session->local.crypt->\n iv_len, \"A\");\n if(!iv) {\n ret = -1;\n goto clean_exit;\n }\n\n LIBSSH2_KEX_METHOD_SHA_VALUE_HASH(256, secret,\n session->local.crypt->\n secret_len, \"C\");\n\n if(!secret) {\n LIBSSH2_FREE(session, iv);\n ret = LIBSSH2_ERROR_KEX_FAILURE;\n goto clean_exit;\n }\n if(session->local.crypt->\n init(session, session->local.crypt, iv, &free_iv, secret,\n &free_secret, 1, &session->local.crypt_abstract)) {\n LIBSSH2_FREE(session, iv);\n LIBSSH2_FREE(session, secret);\n ret = LIBSSH2_ERROR_KEX_FAILURE;\n goto clean_exit;\n }\n\n if(free_iv) {\n _libssh2_explicit_zero(iv, session->local.crypt->iv_len);\n LIBSSH2_FREE(session, iv);\n }\n\n if(free_secret) {\n _libssh2_explicit_zero(secret, session->local.crypt->secret_len);\n LIBSSH2_FREE(session, secret);\n }\n }\n _libssh2_debug(session, LIBSSH2_TRACE_KEX,\n \"Client to Server IV and Key calculated\");\n\n if(session->remote.crypt->dtor) {\n // Cleanup any existing cipher\n session->remote.crypt->dtor(session,\n &session->remote.crypt_abstract);\n }\n\n if(session->remote.crypt->init) {\n unsigned char *iv = NULL, *secret = NULL;\n int free_iv = 0, free_secret = 0;\n\n LIBSSH2_KEX_METHOD_SHA_VALUE_HASH(256, iv,\n session->remote.crypt->\n iv_len, \"B\");\n\n if(!iv) {\n ret = LIBSSH2_ERROR_KEX_FAILURE;\n goto clean_exit;\n }\n LIBSSH2_KEX_METHOD_SHA_VALUE_HASH(256, secret,\n session->remote.crypt->\n secret_len, \"D\");\n\n if(!secret) {\n LIBSSH2_FREE(session, iv);\n ret = LIBSSH2_ERROR_KEX_FAILURE;\n goto clean_exit;\n }\n if(session->remote.crypt->\n init(session, session->remote.crypt, iv, &free_iv, secret,\n &free_secret, 0, &session->remote.crypt_abstract)) {\n LIBSSH2_FREE(session, iv);\n LIBSSH2_FREE(session, secret);\n ret = LIBSSH2_ERROR_KEX_FAILURE;\n goto clean_exit;\n }\n\n if(free_iv) {\n _libssh2_explicit_zero(iv, session->remote.crypt->iv_len);\n LIBSSH2_FREE(session, iv);\n }\n\n if(free_secret) {\n _libssh2_explicit_zero(secret, session->remote.crypt->secret_len);\n LIBSSH2_FREE(session, secret);\n }\n }\n _libssh2_debug(session, LIBSSH2_TRACE_KEX,\n \"Server to Client IV and Key calculated\");\n\n if(session->local.mac->dtor) {\n session->local.mac->dtor(session, &session->local.mac_abstract);\n }\n\n if(session->local.mac->init) {\n unsigned char *key = NULL;\n int free_key = 0;\n\n LIBSSH2_KEX_METHOD_SHA_VALUE_HASH(256, key,\n session->local.mac->\n key_len, \"E\");\n\n if(!key) {\n ret = LIBSSH2_ERROR_KEX_FAILURE;\n goto clean_exit;\n }\n session->local.mac->init(session, key, &free_key,\n &session->local.mac_abstract);\n\n if(free_key) {\n _libssh2_explicit_zero(key, session->local.mac->key_len);\n LIBSSH2_FREE(session, key);\n }\n }\n _libssh2_debug(session, LIBSSH2_TRACE_KEX,\n \"Client to Server HMAC Key calculated\");\n\n if(session->remote.mac->dtor) {\n session->remote.mac->dtor(session, &session->remote.mac_abstract);\n }\n\n if(session->remote.mac->init) {\n unsigned char *key = NULL;\n int free_key = 0;\n\n LIBSSH2_KEX_METHOD_SHA_VALUE_HASH(256, key,\n session->remote.mac->\n key_len, \"F\");\n\n if(!key) {\n ret = LIBSSH2_ERROR_KEX_FAILURE;\n goto clean_exit;\n }\n session->remote.mac->init(session, key, &free_key,\n &session->remote.mac_abstract);\n\n if(free_key) {\n _libssh2_explicit_zero(key, session->remote.mac->key_len);\n LIBSSH2_FREE(session, key);\n }\n }\n _libssh2_debug(session, LIBSSH2_TRACE_KEX,\n \"Server to Client HMAC Key calculated\");\n\n // Initialize compression for each direction\n\n // Cleanup any existing compression\n if(session->local.comp && session->local.comp->dtor) {\n session->local.comp->dtor(session, 1,\n &session->local.comp_abstract);\n }\n\n if(session->local.comp && session->local.comp->init) {\n if(session->local.comp->init(session, 1,\n &session->local.comp_abstract)) {\n ret = LIBSSH2_ERROR_KEX_FAILURE;\n goto clean_exit;\n }\n }\n _libssh2_debug(session, LIBSSH2_TRACE_KEX,\n \"Client to Server compression initialized\");\n\n if(session->remote.comp && session->remote.comp->dtor) {\n session->remote.comp->dtor(session, 0,\n &session->remote.comp_abstract);\n }\n\n if(session->remote.comp && session->remote.comp->init) {\n if(session->remote.comp->init(session, 0,\n &session->remote.comp_abstract)) {\n ret = LIBSSH2_ERROR_KEX_FAILURE;\n goto clean_exit;\n }\n }\n _libssh2_debug(session, LIBSSH2_TRACE_KEX,\n \"Server to Client compression initialized\");\n }\n\nclean_exit:\n _libssh2_bn_free(exchange_state->k);\n exchange_state->k = NULL;\n\n if(exchange_state->k_value) {\n LIBSSH2_FREE(session, exchange_state->k_value);\n exchange_state->k_value = NULL;\n }\n\n exchange_state->state = libssh2_NB_state_idle; ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Security fixes (#315)\n\n* Bounds checks\r\n\r\nFixes for CVEs\r\nhttps://www.libssh2.org/CVE-2019-3863.html\r\nhttps://www.libssh2.org/CVE-2019-3856.html\r\n\r\n* Packet length bounds check\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3855.html\r\n\r\n* Response length check\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3859.html\r\n\r\n* Bounds check\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3857.html\r\n\r\n* Bounds checking\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3859.html\r\n\r\nand additional data validation\r\n\r\n* Check bounds before reading into buffers\r\n\r\n* Bounds checking\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3859.html\r\n\r\n* declare SIZE_MAX and UINT_MAX if needed'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: _libssh2_channel_packet_data_len(LIBSSH2_CHANNEL * channel, int stream_id)\n{\n LIBSSH2_SESSION *session = channel->session;\n LIBSSH2_PACKET *read_packet;\n uint32_t read_local_id;\n\n read_packet = _libssh2_list_first(&session->packets);\n if(read_packet == NULL)\n return 0;\n\n while(read_packet) {\n read_local_id = _libssh2_ntohu32(read_packet->data + 1);\n\n /*\n * Either we asked for a specific extended data stream\n * (and data was available),\n * or the standard stream (and data was available),\n * or the standard stream with extended_data_merge\n * enabled and data was available\n */\n if((stream_id\n && (read_packet->data[0] == SSH_MSG_CHANNEL_EXTENDED_DATA)\n && (channel->local.id == read_local_id)\n && (stream_id == (int) _libssh2_ntohu32(read_packet->data + 5)))\n ||\n (!stream_id\n && (read_packet->data[0] == SSH_MSG_CHANNEL_DATA)\n && (channel->local.id == read_local_id))\n ||\n (!stream_id\n && (read_packet->data[0] == SSH_MSG_CHANNEL_EXTENDED_DATA)\n && (channel->local.id == read_local_id)\n && (channel->remote.extended_data_ignore_mode\n == LIBSSH2_CHANNEL_EXTENDED_DATA_MERGE))) {\n return (read_packet->data_len - read_packet->data_head);\n }\n read_packet = _libssh2_list_next(&read_packet->node);\n }\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Security fixes (#315)\n\n* Bounds checks\r\n\r\nFixes for CVEs\r\nhttps://www.libssh2.org/CVE-2019-3863.html\r\nhttps://www.libssh2.org/CVE-2019-3856.html\r\n\r\n* Packet length bounds check\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3855.html\r\n\r\n* Response length check\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3859.html\r\n\r\n* Bounds check\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3857.html\r\n\r\n* Bounds checking\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3859.html\r\n\r\nand additional data validation\r\n\r\n* Check bounds before reading into buffers\r\n\r\n* Bounds checking\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3859.html\r\n\r\n* declare SIZE_MAX and UINT_MAX if needed'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: * Diffie Hellman Key Exchange, Group Agnostic\n */\nstatic int diffie_hellman_sha1(LIBSSH2_SESSION *session,\n _libssh2_bn *g,\n _libssh2_bn *p,\n int group_order,\n unsigned char packet_type_init,\n unsigned char packet_type_reply,\n unsigned char *midhash,\n unsigned long midhash_len,\n kmdhgGPshakex_state_t *exchange_state)\n{\n int ret = 0;\n int rc;\n libssh2_sha1_ctx exchange_hash_ctx;\n\n if(exchange_state->state == libssh2_NB_state_idle) {\n /* Setup initial values */\n exchange_state->e_packet = NULL;\n exchange_state->s_packet = NULL;\n exchange_state->k_value = NULL;\n exchange_state->ctx = _libssh2_bn_ctx_new();\n libssh2_dh_init(&exchange_state->x);\n exchange_state->e = _libssh2_bn_init(); /* g^x mod p */\n exchange_state->f = _libssh2_bn_init_from_bin(); /* g^(Random from server) mod p */\n exchange_state->k = _libssh2_bn_init(); /* The shared secret: f^x mod p */\n\n /* Zero the whole thing out */\n memset(&exchange_state->req_state, 0, sizeof(packet_require_state_t));\n\n /* Generate x and e */\n rc = libssh2_dh_key_pair(&exchange_state->x, exchange_state->e, g, p,\n group_order, exchange_state->ctx);\n if(rc)\n goto clean_exit;\n\n /* Send KEX init */\n /* packet_type(1) + String Length(4) + leading 0(1) */\n exchange_state->e_packet_len =\n _libssh2_bn_bytes(exchange_state->e) + 6;\n if(_libssh2_bn_bits(exchange_state->e) % 8) {\n /* Leading 00 not needed */\n exchange_state->e_packet_len--;\n }\n\n exchange_state->e_packet =\n LIBSSH2_ALLOC(session, exchange_state->e_packet_len);\n if(!exchange_state->e_packet) {\n ret = _libssh2_error(session, LIBSSH2_ERROR_ALLOC,\n \"Out of memory error\");\n goto clean_exit;\n }\n exchange_state->e_packet[0] = packet_type_init;\n _libssh2_htonu32(exchange_state->e_packet + 1,\n exchange_state->e_packet_len - 5);\n if(_libssh2_bn_bits(exchange_state->e) % 8) {\n _libssh2_bn_to_bin(exchange_state->e,\n exchange_state->e_packet + 5);\n }\n else {\n exchange_state->e_packet[5] = 0;\n _libssh2_bn_to_bin(exchange_state->e,\n exchange_state->e_packet + 6);\n }\n\n _libssh2_debug(session, LIBSSH2_TRACE_KEX, \"Sending KEX packet %d\",\n (int) packet_type_init);\n exchange_state->state = libssh2_NB_state_created;\n }\n\n if(exchange_state->state == libssh2_NB_state_created) {\n rc = _libssh2_transport_send(session, exchange_state->e_packet,\n exchange_state->e_packet_len,\n NULL, 0);\n if(rc == LIBSSH2_ERROR_EAGAIN) {\n return rc;\n }\n else if(rc) {\n ret = _libssh2_error(session, rc,\n \"Unable to send KEX init message\");\n goto clean_exit;\n }\n exchange_state->state = libssh2_NB_state_sent;\n }\n\n if(exchange_state->state == libssh2_NB_state_sent) {\n if(session->burn_optimistic_kexinit) {\n /* The first KEX packet to come along will be the guess initially\n * sent by the server. That guess turned out to be wrong so we\n * need to silently ignore it */\n int burn_type;\n\n _libssh2_debug(session, LIBSSH2_TRACE_KEX,\n \"Waiting for badly guessed KEX packet (to be ignored)\");\n burn_type =\n _libssh2_packet_burn(session, &exchange_state->burn_state);\n if(burn_type == LIBSSH2_ERROR_EAGAIN) {\n return burn_type;\n }\n else if(burn_type <= 0) {\n /* Failed to receive a packet */\n ret = burn_type;\n goto clean_exit;\n }\n session->burn_optimistic_kexinit = 0;\n\n _libssh2_debug(session, LIBSSH2_TRACE_KEX,\n \"Burnt packet of type: %02x\",\n (unsigned int) burn_type);\n }\n\n exchange_state->state = libssh2_NB_state_sent1;\n }\n\n if(exchange_state->state == libssh2_NB_state_sent1) {\n /* Wait for KEX reply */\n rc = _libssh2_packet_require(session, packet_type_reply,\n &exchange_state->s_packet,\n &exchange_state->s_packet_len, 0, NULL,\n 0, &exchange_state->req_state);\n if(rc == LIBSSH2_ERROR_EAGAIN) {\n return rc;\n }\n if(rc) {\n ret = _libssh2_error(session, LIBSSH2_ERROR_TIMEOUT,\n \"Timed out waiting for KEX reply\");\n goto clean_exit;\n }\n\n /* Parse KEXDH_REPLY */\n exchange_state->s = exchange_state->s_packet + 1;\n\n session->server_hostkey_len = _libssh2_ntohu32(exchange_state->s);\n exchange_state->s += 4;\n\n if(session->server_hostkey)\n LIBSSH2_FREE(session, session->server_hostkey);\n\n session->server_hostkey =\n LIBSSH2_ALLOC(session, session->server_hostkey_len);\n if(!session->server_hostkey) {\n ret = _libssh2_error(session, LIBSSH2_ERROR_ALLOC,\n \"Unable to allocate memory for a copy \"\n \"of the host key\");\n goto clean_exit;\n }\n memcpy(session->server_hostkey, exchange_state->s,\n session->server_hostkey_len);\n exchange_state->s += session->server_hostkey_len;\n\n#if LIBSSH2_MD5\n {\n libssh2_md5_ctx fingerprint_ctx;\n\n if(libssh2_md5_init(&fingerprint_ctx)) {\n libssh2_md5_update(fingerprint_ctx, session->server_hostkey,\n session->server_hostkey_len);\n libssh2_md5_final(fingerprint_ctx,\n session->server_hostkey_md5);\n session->server_hostkey_md5_valid = TRUE;\n }\n else {\n session->server_hostkey_md5_valid = FALSE;\n }\n }\n#ifdef LIBSSH2DEBUG\n {\n char fingerprint[50], *fprint = fingerprint;\n int i;\n for(i = 0; i < 16; i++, fprint += 3) {\n snprintf(fprint, 4, \"%02x:\", session->server_hostkey_md5[i]);\n }\n *(--fprint) = '\\0';\n _libssh2_debug(session, LIBSSH2_TRACE_KEX,\n \"Server's MD5 Fingerprint: %s\", fingerprint);\n }\n#endif /* LIBSSH2DEBUG */\n#endif /* ! LIBSSH2_MD5 */\n\n {\n libssh2_sha1_ctx fingerprint_ctx;\n\n if(libssh2_sha1_init(&fingerprint_ctx)) {\n libssh2_sha1_update(fingerprint_ctx, session->server_hostkey,\n session->server_hostkey_len);\n libssh2_sha1_final(fingerprint_ctx,\n session->server_hostkey_sha1);\n session->server_hostkey_sha1_valid = TRUE;\n }\n else {\n session->server_hostkey_sha1_valid = FALSE;\n }\n }\n#ifdef LIBSSH2DEBUG\n {\n char fingerprint[64], *fprint = fingerprint;\n int i;\n\n for(i = 0; i < 20; i++, fprint += 3) {\n snprintf(fprint, 4, \"%02x:\", session->server_hostkey_sha1[i]);\n }\n *(--fprint) = '\\0';\n _libssh2_debug(session, LIBSSH2_TRACE_KEX,\n \"Server's SHA1 Fingerprint: %s\", fingerprint);\n }\n#endif /* LIBSSH2DEBUG */\n\n {\n libssh2_sha256_ctx fingerprint_ctx;\n\n if(libssh2_sha256_init(&fingerprint_ctx)) {\n libssh2_sha256_update(fingerprint_ctx, session->server_hostkey,\n session->server_hostkey_len);\n libssh2_sha256_final(fingerprint_ctx,\n session->server_hostkey_sha256);\n session->server_hostkey_sha256_valid = TRUE;\n }\n else {\n session->server_hostkey_sha256_valid = FALSE;\n }\n }\n#ifdef LIBSSH2DEBUG\n {\n char *base64Fingerprint = NULL;\n _libssh2_base64_encode(session, (const char *)session->server_hostkey_sha256,\n SHA256_DIGEST_LENGTH, &base64Fingerprint);\n if(base64Fingerprint != NULL) {\n _libssh2_debug(session, LIBSSH2_TRACE_KEX,\n \"Server's SHA256 Fingerprint: %s\", base64Fingerprint);\n LIBSSH2_FREE(session, base64Fingerprint);\n }\n }\n#endif /* LIBSSH2DEBUG */\n\n\n if(session->hostkey->init(session, session->server_hostkey,\n session->server_hostkey_len,\n &session->server_hostkey_abstract)) {\n ret = _libssh2_error(session, LIBSSH2_ERROR_HOSTKEY_INIT,\n \"Unable to initialize hostkey importer\");\n goto clean_exit;\n }\n\n exchange_state->f_value_len = _libssh2_ntohu32(exchange_state->s);\n exchange_state->s += 4;\n exchange_state->f_value = exchange_state->s;\n exchange_state->s += exchange_state->f_value_len;\n _libssh2_bn_from_bin(exchange_state->f, exchange_state->f_value_len,\n exchange_state->f_value);\n\n exchange_state->h_sig_len = _libssh2_ntohu32(exchange_state->s);\n exchange_state->s += 4;\n exchange_state->h_sig = exchange_state->s;\n\n /* Compute the shared secret */\n libssh2_dh_secret(&exchange_state->x, exchange_state->k,\n exchange_state->f, p, exchange_state->ctx);\n exchange_state->k_value_len = _libssh2_bn_bytes(exchange_state->k) + 5;\n if(_libssh2_bn_bits(exchange_state->k) % 8) {\n /* don't need leading 00 */\n exchange_state->k_value_len--;\n }\n exchange_state->k_value =\n LIBSSH2_ALLOC(session, exchange_state->k_value_len);\n if(!exchange_state->k_value) {\n ret = _libssh2_error(session, LIBSSH2_ERROR_ALLOC,\n \"Unable to allocate buffer for K\");\n goto clean_exit;\n }\n _libssh2_htonu32(exchange_state->k_value,\n exchange_state->k_value_len - 4);\n if(_libssh2_bn_bits(exchange_state->k) % 8) {\n _libssh2_bn_to_bin(exchange_state->k, exchange_state->k_value + 4);\n }\n else {\n exchange_state->k_value[4] = 0;\n _libssh2_bn_to_bin(exchange_state->k, exchange_state->k_value + 5);\n }\n\n exchange_state->exchange_hash = (void *)&exchange_hash_ctx;\n libssh2_sha1_init(&exchange_hash_ctx);\n\n if(session->local.banner) {\n _libssh2_htonu32(exchange_state->h_sig_comp,\n strlen((char *) session->local.banner) - 2);\n libssh2_sha1_update(exchange_hash_ctx,\n exchange_state->h_sig_comp, 4);\n libssh2_sha1_update(exchange_hash_ctx,\n session->local.banner,\n strlen((char *) session->local.banner) - 2);\n }\n else {\n _libssh2_htonu32(exchange_state->h_sig_comp,\n sizeof(LIBSSH2_SSH_DEFAULT_BANNER) - 1);\n libssh2_sha1_update(exchange_hash_ctx,\n exchange_state->h_sig_comp, 4);\n libssh2_sha1_update(exchange_hash_ctx,\n (const unsigned char *)LIBSSH2_SSH_DEFAULT_BANNER,\n sizeof(LIBSSH2_SSH_DEFAULT_BANNER) - 1);\n }\n\n _libssh2_htonu32(exchange_state->h_sig_comp,\n strlen((char *) session->remote.banner));\n libssh2_sha1_update(exchange_hash_ctx,\n exchange_state->h_sig_comp, 4);\n libssh2_sha1_update(exchange_hash_ctx,\n session->remote.banner,\n strlen((char *) session->remote.banner));\n\n _libssh2_htonu32(exchange_state->h_sig_comp,\n session->local.kexinit_len);\n libssh2_sha1_update(exchange_hash_ctx,\n exchange_state->h_sig_comp, 4);\n libssh2_sha1_update(exchange_hash_ctx,\n session->local.kexinit,\n session->local.kexinit_len);\n\n _libssh2_htonu32(exchange_state->h_sig_comp,\n session->remote.kexinit_len);\n libssh2_sha1_update(exchange_hash_ctx,\n exchange_state->h_sig_comp, 4);\n libssh2_sha1_update(exchange_hash_ctx,\n session->remote.kexinit,\n session->remote.kexinit_len);\n\n _libssh2_htonu32(exchange_state->h_sig_comp,\n session->server_hostkey_len);\n libssh2_sha1_update(exchange_hash_ctx,\n exchange_state->h_sig_comp, 4);\n libssh2_sha1_update(exchange_hash_ctx,\n session->server_hostkey,\n session->server_hostkey_len);\n\n if(packet_type_init == SSH_MSG_KEX_DH_GEX_INIT) {\n /* diffie-hellman-group-exchange hashes additional fields */\n#ifdef LIBSSH2_DH_GEX_NEW\n _libssh2_htonu32(exchange_state->h_sig_comp,\n LIBSSH2_DH_GEX_MINGROUP);\n _libssh2_htonu32(exchange_state->h_sig_comp + 4,\n LIBSSH2_DH_GEX_OPTGROUP);\n _libssh2_htonu32(exchange_state->h_sig_comp + 8,\n LIBSSH2_DH_GEX_MAXGROUP);\n libssh2_sha1_update(exchange_hash_ctx,\n exchange_state->h_sig_comp, 12);\n#else\n _libssh2_htonu32(exchange_state->h_sig_comp,\n LIBSSH2_DH_GEX_OPTGROUP);\n libssh2_sha1_update(exchange_hash_ctx,\n exchange_state->h_sig_comp, 4);\n#endif\n }\n\n if(midhash) {\n libssh2_sha1_update(exchange_hash_ctx, midhash,\n midhash_len);\n }\n\n libssh2_sha1_update(exchange_hash_ctx,\n exchange_state->e_packet + 1,\n exchange_state->e_packet_len - 1);\n\n _libssh2_htonu32(exchange_state->h_sig_comp,\n exchange_state->f_value_len);\n libssh2_sha1_update(exchange_hash_ctx,\n exchange_state->h_sig_comp, 4);\n libssh2_sha1_update(exchange_hash_ctx,\n exchange_state->f_value,\n exchange_state->f_value_len);\n\n libssh2_sha1_update(exchange_hash_ctx,\n exchange_state->k_value,\n exchange_state->k_value_len);\n\n libssh2_sha1_final(exchange_hash_ctx,\n exchange_state->h_sig_comp);\n\n if(session->hostkey->\n sig_verify(session, exchange_state->h_sig,\n exchange_state->h_sig_len, exchange_state->h_sig_comp,\n 20, &session->server_hostkey_abstract)) {\n ret = _libssh2_error(session, LIBSSH2_ERROR_HOSTKEY_SIGN,\n \"Unable to verify hostkey signature\");\n goto clean_exit;\n }\n\n _libssh2_debug(session, LIBSSH2_TRACE_KEX, \"Sending NEWKEYS message\");\n exchange_state->c = SSH_MSG_NEWKEYS;\n\n exchange_state->state = libssh2_NB_state_sent2;\n }\n\n if(exchange_state->state == libssh2_NB_state_sent2) {\n rc = _libssh2_transport_send(session, &exchange_state->c, 1, NULL, 0);\n if(rc == LIBSSH2_ERROR_EAGAIN) {\n return rc;\n }\n else if(rc) {\n ret = _libssh2_error(session, rc, \"Unable to send NEWKEYS message\");\n goto clean_exit;\n }\n\n exchange_state->state = libssh2_NB_state_sent3;\n }\n\n if(exchange_state->state == libssh2_NB_state_sent3) {\n rc = _libssh2_packet_require(session, SSH_MSG_NEWKEYS,\n &exchange_state->tmp,\n &exchange_state->tmp_len, 0, NULL, 0,\n &exchange_state->req_state);\n if(rc == LIBSSH2_ERROR_EAGAIN) {\n return rc;\n }\n else if(rc) {\n ret = _libssh2_error(session, rc, \"Timed out waiting for NEWKEYS\");\n goto clean_exit;\n }\n /* The first key exchange has been performed,\n switch to active crypt/comp/mac mode */\n session->state |= LIBSSH2_STATE_NEWKEYS;\n _libssh2_debug(session, LIBSSH2_TRACE_KEX, \"Received NEWKEYS message\");\n\n /* This will actually end up being just packet_type(1)\n for this packet type anyway */\n LIBSSH2_FREE(session, exchange_state->tmp);\n\n if(!session->session_id) {\n session->session_id = LIBSSH2_ALLOC(session, SHA_DIGEST_LENGTH);\n if(!session->session_id) {\n ret = _libssh2_error(session, LIBSSH2_ERROR_ALLOC,\n \"Unable to allocate buffer for SHA digest\");\n goto clean_exit;\n }\n memcpy(session->session_id, exchange_state->h_sig_comp,\n SHA_DIGEST_LENGTH);\n session->session_id_len = SHA_DIGEST_LENGTH;\n _libssh2_debug(session, LIBSSH2_TRACE_KEX, \"session_id calculated\");\n }\n\n /* Cleanup any existing cipher */\n if(session->local.crypt->dtor) {\n session->local.crypt->dtor(session,\n &session->local.crypt_abstract);\n }\n\n /* Calculate IV/Secret/Key for each direction */\n if(session->local.crypt->init) {\n unsigned char *iv = NULL, *secret = NULL;\n int free_iv = 0, free_secret = 0;\n\n LIBSSH2_KEX_METHOD_DIFFIE_HELLMAN_SHA1_HASH(iv,\n session->local.crypt->\n iv_len,\n (const unsigned char *)\"A\");\n if(!iv) {\n ret = -1;\n goto clean_exit;\n }\n LIBSSH2_KEX_METHOD_DIFFIE_HELLMAN_SHA1_HASH(secret,\n session->local.crypt->\n secret_len,\n (const unsigned char *)\"C\");\n if(!secret) {\n LIBSSH2_FREE(session, iv);\n ret = LIBSSH2_ERROR_KEX_FAILURE;\n goto clean_exit;\n }\n if(session->local.crypt->\n init(session, session->local.crypt, iv, &free_iv, secret,\n &free_secret, 1, &session->local.crypt_abstract)) {\n LIBSSH2_FREE(session, iv);\n LIBSSH2_FREE(session, secret);\n ret = LIBSSH2_ERROR_KEX_FAILURE;\n goto clean_exit;\n }\n\n if(free_iv) {\n _libssh2_explicit_zero(iv, session->local.crypt->iv_len);\n LIBSSH2_FREE(session, iv);\n }\n\n if(free_secret) {\n _libssh2_explicit_zero(secret, session->local.crypt->secret_len);\n LIBSSH2_FREE(session, secret);\n }\n }\n _libssh2_debug(session, LIBSSH2_TRACE_KEX,\n \"Client to Server IV and Key calculated\");\n\n if(session->remote.crypt->dtor) {\n /* Cleanup any existing cipher */\n session->remote.crypt->dtor(session,\n &session->remote.crypt_abstract);\n }\n\n if(session->remote.crypt->init) {\n unsigned char *iv = NULL, *secret = NULL;\n int free_iv = 0, free_secret = 0;\n\n LIBSSH2_KEX_METHOD_DIFFIE_HELLMAN_SHA1_HASH(iv,\n session->remote.crypt->\n iv_len,\n (const unsigned char *)\"B\");\n if(!iv) {\n ret = LIBSSH2_ERROR_KEX_FAILURE;\n goto clean_exit;\n }\n LIBSSH2_KEX_METHOD_DIFFIE_HELLMAN_SHA1_HASH(secret,\n session->remote.crypt->\n secret_len,\n (const unsigned char *)\"D\");\n if(!secret) {\n LIBSSH2_FREE(session, iv);\n ret = LIBSSH2_ERROR_KEX_FAILURE;\n goto clean_exit;\n }\n if(session->remote.crypt->\n init(session, session->remote.crypt, iv, &free_iv, secret,\n &free_secret, 0, &session->remote.crypt_abstract)) {\n LIBSSH2_FREE(session, iv);\n LIBSSH2_FREE(session, secret);\n ret = LIBSSH2_ERROR_KEX_FAILURE;\n goto clean_exit;\n }\n\n if(free_iv) {\n _libssh2_explicit_zero(iv, session->remote.crypt->iv_len);\n LIBSSH2_FREE(session, iv);\n }\n\n if(free_secret) {\n _libssh2_explicit_zero(secret, session->remote.crypt->secret_len);\n LIBSSH2_FREE(session, secret);\n }\n }\n _libssh2_debug(session, LIBSSH2_TRACE_KEX,\n \"Server to Client IV and Key calculated\");\n\n if(session->local.mac->dtor) {\n session->local.mac->dtor(session, &session->local.mac_abstract);\n }\n\n if(session->local.mac->init) {\n unsigned char *key = NULL;\n int free_key = 0;\n\n LIBSSH2_KEX_METHOD_DIFFIE_HELLMAN_SHA1_HASH(key,\n session->local.mac->\n key_len,\n (const unsigned char *)\"E\");\n if(!key) {\n ret = LIBSSH2_ERROR_KEX_FAILURE;\n goto clean_exit;\n }\n session->local.mac->init(session, key, &free_key,\n &session->local.mac_abstract);\n\n if(free_key) {\n _libssh2_explicit_zero(key, session->local.mac->key_len);\n LIBSSH2_FREE(session, key);\n }\n }\n _libssh2_debug(session, LIBSSH2_TRACE_KEX,\n \"Client to Server HMAC Key calculated\");\n\n if(session->remote.mac->dtor) {\n session->remote.mac->dtor(session, &session->remote.mac_abstract);\n }\n\n if(session->remote.mac->init) {\n unsigned char *key = NULL;\n int free_key = 0;\n\n LIBSSH2_KEX_METHOD_DIFFIE_HELLMAN_SHA1_HASH(key,\n session->remote.mac->\n key_len,\n (const unsigned char *)\"F\");\n if(!key) {\n ret = LIBSSH2_ERROR_KEX_FAILURE;\n goto clean_exit;\n }\n session->remote.mac->init(session, key, &free_key,\n &session->remote.mac_abstract);\n\n if(free_key) {\n _libssh2_explicit_zero(key, session->remote.mac->key_len);\n LIBSSH2_FREE(session, key);\n }\n }\n _libssh2_debug(session, LIBSSH2_TRACE_KEX,\n \"Server to Client HMAC Key calculated\");\n\n /* Initialize compression for each direction */\n\n /* Cleanup any existing compression */\n if(session->local.comp && session->local.comp->dtor) {\n session->local.comp->dtor(session, 1,\n &session->local.comp_abstract);\n }\n\n if(session->local.comp && session->local.comp->init) {\n if(session->local.comp->init(session, 1,\n &session->local.comp_abstract)) {\n ret = LIBSSH2_ERROR_KEX_FAILURE;\n goto clean_exit;\n }\n }\n _libssh2_debug(session, LIBSSH2_TRACE_KEX,\n \"Client to Server compression initialized\");\n\n if(session->remote.comp && session->remote.comp->dtor) {\n session->remote.comp->dtor(session, 0,\n &session->remote.comp_abstract);\n }\n\n if(session->remote.comp && session->remote.comp->init) {\n if(session->remote.comp->init(session, 0,\n &session->remote.comp_abstract)) {\n ret = LIBSSH2_ERROR_KEX_FAILURE;\n goto clean_exit;\n }\n }\n _libssh2_debug(session, LIBSSH2_TRACE_KEX,\n \"Server to Client compression initialized\");\n\n }\n\n clean_exit:\n libssh2_dh_dtor(&exchange_state->x);\n _libssh2_bn_free(exchange_state->e);\n exchange_state->e = NULL;\n _libssh2_bn_free(exchange_state->f);\n exchange_state->f = NULL;\n _libssh2_bn_free(exchange_state->k);\n exchange_state->k = NULL;\n _libssh2_bn_ctx_free(exchange_state->ctx);\n exchange_state->ctx = NULL;\n\n if(exchange_state->e_packet) {\n LIBSSH2_FREE(session, exchange_state->e_packet);\n exchange_state->e_packet = NULL;\n }\n\n if(exchange_state->s_packet) {\n LIBSSH2_FREE(session, exchange_state->s_packet);\n exchange_state->s_packet = NULL;\n }\n\n if(exchange_state->k_value) {\n LIBSSH2_FREE(session, exchange_state->k_value);\n exchange_state->k_value = NULL;\n }\n\n exchange_state->state = libssh2_NB_state_idle;\n ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Security fixes (#315)\n\n* Bounds checks\r\n\r\nFixes for CVEs\r\nhttps://www.libssh2.org/CVE-2019-3863.html\r\nhttps://www.libssh2.org/CVE-2019-3856.html\r\n\r\n* Packet length bounds check\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3855.html\r\n\r\n* Response length check\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3859.html\r\n\r\n* Bounds check\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3857.html\r\n\r\n* Bounds checking\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3859.html\r\n\r\nand additional data validation\r\n\r\n* Check bounds before reading into buffers\r\n\r\n* Bounds checking\r\n\r\nCVE\r\nhttps://www.libssh2.org/CVE-2019-3859.html\r\n\r\n* declare SIZE_MAX and UINT_MAX if needed'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: entry *load_entry(FILE * file, void (*error_func) (), struct passwd *pw,\n\tchar **envp) {\n\t/* this function reads one crontab entry -- the next -- from a file.\n\t * it skips any leading blank lines, ignores comments, and returns\n\t * NULL if for any reason the entry can't be read and parsed.\n\t *\n\t * the entry is also parsed here.\n\t *\n\t * syntax:\n\t * user crontab:\n\t * minutes hours doms months dows cmd\\n\n\t * system crontab (/etc/crontab):\n\t * minutes hours doms months dows USERNAME cmd\\n\n\t */\n\n\tecode_e ecode = e_none;\n\tentry *e;\n\tint ch;\n\tchar cmd[MAX_COMMAND];\n\tchar envstr[MAX_ENVSTR];\n\tchar **tenvp;\n\tchar *p;\n\tstruct passwd temppw;\n\n\tDebug(DPARS, (\"load_entry()...about to eat comments\\n\"));\n\n\tskip_comments(file);\n\n\tch = get_char(file);\n\tif (ch == EOF)\n\t\treturn (NULL);\n\n\t/* ch is now the first useful character of a useful line.\n\t * it may be an @special or it may be the first character\n\t * of a list of minutes.\n\t */\n\n\te = (entry *) calloc(sizeof (entry), sizeof (char));\n\n\t/* check for '-' as a first character, this option will disable \n\t* writing a syslog message about command getting executed\n\t*/\n\tif (ch == '-') {\n\t/* if we are editing system crontab or user uid is 0 (root) \n\t* we are allowed to disable logging \n\t*/\n\t\tif (pw == NULL || pw->pw_uid == 0)\n\t\t\te->flags |= DONT_LOG;\n\t\telse {\n\t\t\tlog_it(\"CRON\", getpid(), \"ERROR\", \"Only privileged user can disable logging\", 0);\n\t\t\tecode = e_option;\n\t\t\tgoto eof;\n\t\t}\n\t\tch = get_char(file);\n\t\tif (ch == EOF) {\n\t\t\tfree(e);\n\t\t\treturn NULL;\n\t\t}\n\t}\n\n\tif (ch == '@') {\n\t\t/* all of these should be flagged and load-limited; i.e.,\n\t\t * instead of @hourly meaning \"0 * * * *\" it should mean\n\t\t * \"close to the front of every hour but not 'til the\n\t\t * system load is low\". Problems are: how do you know\n\t\t * what \"low\" means? (save me from /etc/cron.conf!) and:\n\t\t * how to guarantee low variance (how low is low?), which\n\t\t * means how to we run roughly every hour -- seems like\n\t\t * we need to keep a history or let the first hour set\n\t\t * the schedule, which means we aren't load-limited\n\t\t * anymore. too much for my overloaded brain. (vix, jan90)\n\t\t * HINT\n\t\t */\n\t\tch = get_string(cmd, MAX_COMMAND, file, \" \\t\\n\");\n\t\tif (!strcmp(\"reboot\", cmd)) {\n\t\t\te->flags |= WHEN_REBOOT;\n\t\t}\n\t\telse if (!strcmp(\"yearly\", cmd) || !strcmp(\"annually\", cmd)) {\n\t\t\tbit_set(e->minute, 0);\n\t\t\tbit_set(e->hour, 0);\n\t\t\tbit_set(e->dom, 0);\n\t\t\tbit_set(e->month, 0);\n\t\t\tbit_nset(e->dow, 0, LAST_DOW - FIRST_DOW);\n\t\t\te->flags |= DOW_STAR;\n\t\t}\n\t\telse if (!strcmp(\"monthly\", cmd)) {\n\t\t\tbit_set(e->minute, 0);\n\t\t\tbit_set(e->hour, 0);\n\t\t\tbit_set(e->dom, 0);\n\t\t\tbit_nset(e->month, 0, LAST_MONTH - FIRST_MONTH);\n\t\t\tbit_nset(e->dow, 0, LAST_DOW - FIRST_DOW);\n\t\t\te->flags |= DOW_STAR;\n\t\t}\n\t\telse if (!strcmp(\"weekly\", cmd)) {\n\t\t\tbit_set(e->minute, 0);\n\t\t\tbit_set(e->hour, 0);\n\t\t\tbit_nset(e->dom, 0, LAST_DOM - FIRST_DOM);\n\t\t\tbit_nset(e->month, 0, LAST_MONTH - FIRST_MONTH);\n\t\t\tbit_set(e->dow, 0);\n\t\t\te->flags |= DOW_STAR;\n\t\t}\n\t\telse if (!strcmp(\"daily\", cmd) || !strcmp(\"midnight\", cmd)) {\n\t\t\tbit_set(e->minute, 0);\n\t\t\tbit_set(e->hour, 0);\n\t\t\tbit_nset(e->dom, 0, LAST_DOM - FIRST_DOM);\n\t\t\tbit_nset(e->month, 0, LAST_MONTH - FIRST_MONTH);\n\t\t\tbit_nset(e->dow, 0, LAST_DOW - FIRST_DOW);\n\t\t}\n\t\telse if (!strcmp(\"hourly\", cmd)) {\n\t\t\tbit_set(e->minute, 0);\n\t\t\tbit_nset(e->hour, 0, LAST_HOUR - FIRST_HOUR);\n\t\t\tbit_nset(e->dom, 0, LAST_DOM - FIRST_DOM);\n\t\t\tbit_nset(e->month, 0, LAST_MONTH - FIRST_MONTH);\n\t\t\tbit_nset(e->dow, 0, LAST_DOW - FIRST_DOW);\n\t\t\te->flags |= HR_STAR;\n\t\t}\n\t\telse {\n\t\t\tecode = e_timespec;\n\t\t\tgoto eof;\n\t\t}\n\t\t/* Advance past whitespace between shortcut and\n\t\t * username/command.\n\t\t */\n\t\tSkip_Blanks(ch, file);\n\t\tif (ch == EOF || ch == '\\n') {\n\t\t\tecode = e_cmd;\n\t\t\tgoto eof;\n\t\t}\n\t}\n\telse {\n\t\tDebug(DPARS, (\"load_entry()...about to parse numerics\\n\"));\n\n\t\tif (ch == '*')\n\t\t\te->flags |= MIN_STAR;\n\t\tch = get_list(e->minute, FIRST_MINUTE, LAST_MINUTE, PPC_NULL, ch, file);\n\t\tif (ch == EOF) {\n\t\t\tecode = e_minute;\n\t\t\tgoto eof;\n\t\t}\n\n\t\t/* hours\n\t\t */\n\n\t\tif (ch == '*')\n\t\t\te->flags |= HR_STAR;\n\t\tch = get_list(e->hour, FIRST_HOUR, LAST_HOUR, PPC_NULL, ch, file);\n\t\tif (ch == EOF) {\n\t\t\tecode = e_hour;\n\t\t\tgoto eof;\n\t\t}\n\n\t\t/* DOM (days of month)\n\t\t */\n\n\t\tif (ch == '*')\n\t\t\te->flags |= DOM_STAR;\n\t\tch = get_list(e->dom, FIRST_DOM, LAST_DOM, PPC_NULL, ch, file);\n\t\tif (ch == EOF) {\n\t\t\tecode = e_dom;\n\t\t\tgoto eof;\n\t\t}\n\n\t\t/* month\n\t\t */\n\n\t\tch = get_list(e->month, FIRST_MONTH, LAST_MONTH, MonthNames, ch, file);\n\t\tif (ch == EOF) {\n\t\t\tecode = e_month;\n\t\t\tgoto eof;\n\t\t}\n\n\t\t/* DOW (days of week)\n\t\t */\n\n\t\tif (ch == '*')\n\t\t\te->flags |= DOW_STAR;\n\t\tch = get_list(e->dow, FIRST_DOW, LAST_DOW, DowNames, ch, file);\n\t\tif (ch == EOF) {\n\t\t\tecode = e_dow;\n\t\t\tgoto eof;\n\t\t}\n\t}\n\n\t/* make sundays equivalent */\n\tif (bit_test(e->dow, 0) || bit_test(e->dow, 7)) {\n\t\tbit_set(e->dow, 0);\n\t\tbit_set(e->dow, 7);\n\t}\n\n\t/* check for permature EOL and catch a common typo */\n\tif (ch == '\\n' || ch == '*') {\n\t\tecode = e_cmd;\n\t\tgoto eof;\n\t}\n\n\t/* ch is the first character of a command, or a username */\n\tunget_char(ch, file);\n\n\tif (!pw) {\n\t\tchar *username = cmd;\t/* temp buffer */\n\n\t\tDebug(DPARS, (\"load_entry()...about to parse username\\n\"));\n\t\tch = get_string(username, MAX_COMMAND, file, \" \\t\\n\");\n\n\t\tDebug(DPARS, (\"load_entry()...got %s\\n\", username));\n\t\tif (ch == EOF || ch == '\\n' || ch == '*') {\n\t\t\tecode = e_cmd;\n\t\t\tgoto eof;\n\t\t}\n\n\t\tpw = getpwnam(username);\n\t\tif (pw == NULL) {\n\t\t\tDebug(DPARS, (\"load_entry()...unknown user entry\\n\"));\n\t\t\tmemset(&temppw, 0, sizeof (temppw));\n\t\t\ttemppw.pw_name = username;\n\t\t\ttemppw.pw_passwd = \"\";\n\t\t\tpw = &temppw;\n\t\t} else {\n\t\t\tDebug(DPARS, (\"load_entry()...uid %ld, gid %ld\\n\",\n\t\t\t\t(long) pw->pw_uid, (long) pw->pw_gid));\n\t\t}\n\t}\n\n\tif ((e->pwd = pw_dup(pw)) == NULL) {\n\t\tecode = e_memory;\n\t\tgoto eof;\n\t}\n\tmemset(e->pwd->pw_passwd, 0, strlen(e->pwd->pw_passwd));\n\n\tp = env_get(\"RANDOM_DELAY\", envp);\n\tif (p) {\n\t\tchar *endptr;\n\t\tlong val;\n\n\t\terrno = 0; /* To distinguish success/failure after call */\n\t\tval = strtol(p, &endptr, 10);\n\t\tif (errno != 0 || val < 0 || val > 24*60) {\n\t\t\tlog_it(\"CRON\", getpid(), \"ERROR\", \"bad value of RANDOM_DELAY\", 0);\n\t\t} else {\n\t\t\te->delay = (int)((double)val * RandomScale);\n\t\t}\n\t}\n\n\t/* copy and fix up environment. some variables are just defaults and\n\t * others are overrides.\n\t */\n\tif ((e->envp = env_copy(envp)) == NULL) {\n\t\tecode = e_memory;\n\t\tgoto eof;\n\t}\n\tif (!env_get(\"SHELL\", e->envp)) {\n\t\tif (glue_strings(envstr, sizeof envstr, \"SHELL\", _PATH_BSHELL, '=')) {\n\t\t\tif ((tenvp = env_set(e->envp, envstr)) == NULL) {\n\t\t\t\tecode = e_memory;\n\t\t\t\tgoto eof;\n\t\t\t}\n\t\t\te->envp = tenvp;\n\t\t}\n\t\telse\n\t\t\tlog_it(\"CRON\", getpid(), \"ERROR\", \"can't set SHELL\", 0);\n\t}\n\tif ((tenvp = env_update_home(e->envp, pw->pw_dir)) == NULL) {\n\t\tecode = e_memory;\n\t\tgoto eof;\n\t}\n\te->envp = tenvp;\n#ifndef LOGIN_CAP\n\t/* If login.conf is in used we will get the default PATH later. */\n\tif (!env_get(\"PATH\", e->envp)) {\n\t\tchar *defpath;\n\n\t\tif (ChangePath)\n\t\t\tdefpath = _PATH_DEFPATH;\n\t\telse {\n\t\t\tdefpath = getenv(\"PATH\");\n\t\t\tif (defpath == NULL)\n\t\t\t\tdefpath = _PATH_DEFPATH;\n\t\t}\n\n\t\tif (glue_strings(envstr, sizeof envstr, \"PATH\", defpath, '=')) {\n\t\t\tif ((tenvp = env_set(e->envp, envstr)) == NULL) {\n\t\t\t\tecode = e_memory;\n\t\t\t\tgoto eof;\n\t\t\t}\n\t\t\te->envp = tenvp;\n\t\t}\n\t\telse\n\t\t\tlog_it(\"CRON\", getpid(), \"ERROR\", \"can't set PATH\", 0);\n\t}\n#endif /* LOGIN_CAP */\n\tif (glue_strings(envstr, sizeof envstr, \"LOGNAME\", pw->pw_name, '=')) {\n\t\tif ((tenvp = env_set(e->envp, envstr)) == NULL) {\n\t\t\tecode = e_memory;\n\t\t\tgoto eof;\n\t\t}\n\t\te->envp = tenvp;\n\t}\n\telse\n\t\tlog_it(\"CRON\", getpid(), \"ERROR\", \"can't set LOGNAME\", 0);\n#if defined(BSD) || defined(__linux)\n\tif (glue_strings(envstr, sizeof envstr, \"USER\", pw->pw_name, '=')) {\n\t\tif ((tenvp = env_set(e->envp, envstr)) == NULL) {\n\t\t\tecode = e_memory;\n\t\t\tgoto eof;\n\t\t}\n\t\te->envp = tenvp;\n\t}\n\telse\n\t\tlog_it(\"CRON\", getpid(), \"ERROR\", \"can't set USER\", 0);\n#endif\n\n\tDebug(DPARS, (\"load_entry()...about to parse command\\n\"));\n\n\t/* Everything up to the next \\n or EOF is part of the command...\n\t * too bad we don't know in advance how long it will be, since we\n\t * need to malloc a string for it... so, we limit it to MAX_COMMAND.\n\t */\n\tch = get_string(cmd, MAX_COMMAND, file, \"\\n\");\n\n\t/* a file without a \\n before the EOF is rude, so we'll complain...\n\t */\n\tif (ch == EOF) {\n\t\tecode = e_cmd;\n\t\tgoto eof;\n\t}\n\n\t/* got the command in the 'cmd' string; save it in *e.\n\t */\n\tif ((e->cmd = strdup(cmd)) == NULL) {\n\t\tecode = e_memory;\n\t\tgoto eof;\n\t}\n\n\tDebug(DPARS, (\"load_entry()...returning successfully\\n\"));\n\n\t\t/* success, fini, return pointer to the entry we just created...\n\t\t */\n\t\treturn (e);\n\n eof:\n\tif (e->envp)\n\t\tenv_free(e->envp);\n\tfree(e->pwd);\n\tfree(e->cmd);\n\tfree(e);\n\twhile (ch != '\\n' && !feof(file))\n\t\tch = get_char(file);\n\tif (ecode != e_none && error_func)\n\t\t(*error_func) (ecodes[(int) ecode]);\n\treturn (NULL);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fix CVE-2019-9704 and CVE-2019-9705\n\nThe users can cause DoS of the crond by loading huge crontab files.\nWe now allow maximum 1000 environment variables and 1000 crontab entries.\nAlso the comments and whitespace between the entries and variables\nare now limited to 32768 characters.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: g_socket_client_async_connect_data_free (GSocketClientAsyncConnectData *data)\n{\n g_clear_object (&data->connectable);\n g_clear_object (&data->enumerator);\n g_clear_object (&data->proxy_addr);\n g_clear_object (&data->socket);\n g_clear_object (&data->connection);\n g_slist_free_full (data->connection_attempts, connection_attempt_unref);\n\n g_clear_error (&data->last_error);\n\n g_slice_free (GSocketClientAsyncConnectData, data);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-754'], 'message': 'gsocketclient: Fix criticals\n\nThis ensures the parent GTask is kept alive as long as an enumeration\nis running and trying to connect.\n\nCloses #1646\nCloses #1649'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int phar_tar_writeheaders_int(phar_entry_info *entry, void *argument) /* {{{ */\n{\n\ttar_header header;\n\tsize_t pos;\n\tstruct _phar_pass_tar_info *fp = (struct _phar_pass_tar_info *)argument;\n\tchar padding[512];\n\n\tif (entry->is_mounted) {\n\t\treturn ZEND_HASH_APPLY_KEEP;\n\t}\n\n\tif (entry->is_deleted) {\n\t\tif (entry->fp_refcount <= 0) {\n\t\t\treturn ZEND_HASH_APPLY_REMOVE;\n\t\t} else {\n\t\t\t/* we can't delete this in-memory until it is closed */\n\t\t\treturn ZEND_HASH_APPLY_KEEP;\n\t\t}\n\t}\n\n\tphar_add_virtual_dirs(entry->phar, entry->filename, entry->filename_len);\n\tmemset((char *) &header, 0, sizeof(header));\n\n\tif (entry->filename_len > 100) {\n\t\tchar *boundary;\n\t\tif (entry->filename_len > 256) {\n\t\t\tif (fp->error) {\n\t\t\t\tspprintf(fp->error, 4096, \"tar-based phar \\\"%s\\\" cannot be created, filename \\\"%s\\\" is too long for tar file format\", entry->phar->fname, entry->filename);\n\t\t\t}\n\t\t\treturn ZEND_HASH_APPLY_STOP;\n\t\t}\n\t\tboundary = entry->filename + entry->filename_len - 101;\n\t\twhile (*boundary && *boundary != '/') {\n\t\t\t++boundary;\n\t\t}\n\t\tif (!*boundary || ((boundary - entry->filename) > 155)) {\n\t\t\tif (fp->error) {\n\t\t\t\tspprintf(fp->error, 4096, \"tar-based phar \\\"%s\\\" cannot be created, filename \\\"%s\\\" is too long for tar file format\", entry->phar->fname, entry->filename);\n\t\t\t}\n\t\t\treturn ZEND_HASH_APPLY_STOP;\n\t\t}\n\t\tmemcpy(header.prefix, entry->filename, boundary - entry->filename);\n\t\tmemcpy(header.name, boundary + 1, entry->filename_len - (boundary + 1 - entry->filename));\n\t} else {\n\t\tmemcpy(header.name, entry->filename, entry->filename_len);\n\t}\n\n\tphar_tar_octal(header.mode, entry->flags & PHAR_ENT_PERM_MASK, sizeof(header.mode)-1);\n\n\tif (FAILURE == phar_tar_octal(header.size, entry->uncompressed_filesize, sizeof(header.size)-1)) {\n\t\tif (fp->error) {\n\t\t\tspprintf(fp->error, 4096, \"tar-based phar \\\"%s\\\" cannot be created, filename \\\"%s\\\" is too large for tar file format\", entry->phar->fname, entry->filename);\n\t\t}\n\t\treturn ZEND_HASH_APPLY_STOP;\n\t}\n\n\tif (FAILURE == phar_tar_octal(header.mtime, entry->timestamp, sizeof(header.mtime)-1)) {\n\t\tif (fp->error) {\n\t\t\tspprintf(fp->error, 4096, \"tar-based phar \\\"%s\\\" cannot be created, file modification time of file \\\"%s\\\" is too large for tar file format\", entry->phar->fname, entry->filename);\n\t\t}\n\t\treturn ZEND_HASH_APPLY_STOP;\n\t}\n\n\t/* calc checksum */\n\theader.typeflag = entry->tar_type;\n\n\tif (entry->link) {\n\t\tstrncpy(header.linkname, entry->link, strlen(entry->link));\n\t}\n\n\tstrncpy(header.magic, \"ustar\", sizeof(\"ustar\")-1);\n\tstrncpy(header.version, \"00\", sizeof(\"00\")-1);\n\tstrncpy(header.checksum, \" \", sizeof(\" \")-1);\n\tentry->crc32 = phar_tar_checksum((char *)&header, sizeof(header));\n\n\tif (FAILURE == phar_tar_octal(header.checksum, entry->crc32, sizeof(header.checksum)-1)) {\n\t\tif (fp->error) {\n\t\t\tspprintf(fp->error, 4096, \"tar-based phar \\\"%s\\\" cannot be created, checksum of file \\\"%s\\\" is too large for tar file format\", entry->phar->fname, entry->filename);\n\t\t}\n\t\treturn ZEND_HASH_APPLY_STOP;\n\t}\n\n\t/* write header */\n\tentry->header_offset = php_stream_tell(fp->new);\n\n\tif (sizeof(header) != php_stream_write(fp->new, (char *) &header, sizeof(header))) {\n\t\tif (fp->error) {\n\t\t\tspprintf(fp->error, 4096, \"tar-based phar \\\"%s\\\" cannot be created, header for file \\\"%s\\\" could not be written\", entry->phar->fname, entry->filename);\n\t\t}\n\t\treturn ZEND_HASH_APPLY_STOP;\n\t}\n\n\tpos = php_stream_tell(fp->new); /* save start of file within tar */\n\n\t/* write contents */\n\tif (entry->uncompressed_filesize) {\n\t\tif (FAILURE == phar_open_entry_fp(entry, fp->error, 0)) {\n\t\t\treturn ZEND_HASH_APPLY_STOP;\n\t\t}\n\n\t\tif (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 0)) {\n\t\t\tif (fp->error) {\n\t\t\t\tspprintf(fp->error, 4096, \"tar-based phar \\\"%s\\\" cannot be created, contents of file \\\"%s\\\" could not be written, seek failed\", entry->phar->fname, entry->filename);\n\t\t\t}\n\t\t\treturn ZEND_HASH_APPLY_STOP;\n\t\t}\n\n\t\tif (SUCCESS != php_stream_copy_to_stream_ex(phar_get_efp(entry, 0), fp->new, entry->uncompressed_filesize, NULL)) {\n\t\t\tif (fp->error) {\n\t\t\t\tspprintf(fp->error, 4096, \"tar-based phar \\\"%s\\\" cannot be created, contents of file \\\"%s\\\" could not be written\", entry->phar->fname, entry->filename);\n\t\t\t}\n\t\t\treturn ZEND_HASH_APPLY_STOP;\n\t\t}\n\n\t\tmemset(padding, 0, 512);\n\t\tphp_stream_write(fp->new, padding, ((entry->uncompressed_filesize +511)&~511) - entry->uncompressed_filesize);\n\t}\n\n\tif (!entry->is_modified && entry->fp_refcount) {\n\t\t/* open file pointers refer to this fp, do not free the stream */\n\t\tswitch (entry->fp_type) {\n\t\t\tcase PHAR_FP:\n\t\t\t\tfp->free_fp = 0;\n\t\t\t\tbreak;\n\t\t\tcase PHAR_UFP:\n\t\t\t\tfp->free_ufp = 0;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tentry->is_modified = 0;\n\n\tif (entry->fp_type == PHAR_MOD && entry->fp != entry->phar->fp && entry->fp != entry->phar->ufp) {\n\t\tif (!entry->fp_refcount) {\n\t\t\tphp_stream_close(entry->fp);\n\t\t}\n\t\tentry->fp = NULL;\n\t}\n\n\tentry->fp_type = PHAR_FP;\n\n\t/* note new location within tar */\n\tentry->offset = entry->offset_abs = pos;\n\treturn ZEND_HASH_APPLY_KEEP;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix bug #77586 - phar_tar_writeheaders_int() buffer overflow'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static MagickBooleanType WritePSImage(const ImageInfo *image_info,Image *image,\n ExceptionInfo *exception)\n{\n#define WriteRunlengthPacket(image,pixel,length,p) \\\n{ \\\n if ((image->alpha_trait != UndefinedPixelTrait) && (length != 0) && \\\n (GetPixelAlpha(image,p) == (Quantum) TransparentAlpha)) \\\n { \\\n q=PopHexPixel(hex_digits,0xff,q); \\\n q=PopHexPixel(hex_digits,0xff,q); \\\n q=PopHexPixel(hex_digits,0xff,q); \\\n } \\\n else \\\n { \\\n q=PopHexPixel(hex_digits,ScaleQuantumToChar(ClampToQuantum(pixel.red)),q); \\\n q=PopHexPixel(hex_digits,ScaleQuantumToChar(ClampToQuantum(pixel.green)),q); \\\n q=PopHexPixel(hex_digits,ScaleQuantumToChar(ClampToQuantum(pixel.blue)),q); \\\n } \\\n q=PopHexPixel(hex_digits,(size_t) MagickMin(length,0xff),q); \\\n}\n\n static const char\n *const hex_digits[] =\n {\n \"00\", \"01\", \"02\", \"03\", \"04\", \"05\", \"06\", \"07\", \"08\", \"09\", \"0A\", \"0B\",\n \"0C\", \"0D\", \"0E\", \"0F\", \"10\", \"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\",\n \"18\", \"19\", \"1A\", \"1B\", \"1C\", \"1D\", \"1E\", \"1F\", \"20\", \"21\", \"22\", \"23\",\n \"24\", \"25\", \"26\", \"27\", \"28\", \"29\", \"2A\", \"2B\", \"2C\", \"2D\", \"2E\", \"2F\",\n \"30\", \"31\", \"32\", \"33\", \"34\", \"35\", \"36\", \"37\", \"38\", \"39\", \"3A\", \"3B\",\n \"3C\", \"3D\", \"3E\", \"3F\", \"40\", \"41\", \"42\", \"43\", \"44\", \"45\", \"46\", \"47\",\n \"48\", \"49\", \"4A\", \"4B\", \"4C\", \"4D\", \"4E\", \"4F\", \"50\", \"51\", \"52\", \"53\",\n \"54\", \"55\", \"56\", \"57\", \"58\", \"59\", \"5A\", \"5B\", \"5C\", \"5D\", \"5E\", \"5F\",\n \"60\", \"61\", \"62\", \"63\", \"64\", \"65\", \"66\", \"67\", \"68\", \"69\", \"6A\", \"6B\",\n \"6C\", \"6D\", \"6E\", \"6F\", \"70\", \"71\", \"72\", \"73\", \"74\", \"75\", \"76\", \"77\",\n \"78\", \"79\", \"7A\", \"7B\", \"7C\", \"7D\", \"7E\", \"7F\", \"80\", \"81\", \"82\", \"83\",\n \"84\", \"85\", \"86\", \"87\", \"88\", \"89\", \"8A\", \"8B\", \"8C\", \"8D\", \"8E\", \"8F\",\n \"90\", \"91\", \"92\", \"93\", \"94\", \"95\", \"96\", \"97\", \"98\", \"99\", \"9A\", \"9B\",\n \"9C\", \"9D\", \"9E\", \"9F\", \"A0\", \"A1\", \"A2\", \"A3\", \"A4\", \"A5\", \"A6\", \"A7\",\n \"A8\", \"A9\", \"AA\", \"AB\", \"AC\", \"AD\", \"AE\", \"AF\", \"B0\", \"B1\", \"B2\", \"B3\",\n \"B4\", \"B5\", \"B6\", \"B7\", \"B8\", \"B9\", \"BA\", \"BB\", \"BC\", \"BD\", \"BE\", \"BF\",\n \"C0\", \"C1\", \"C2\", \"C3\", \"C4\", \"C5\", \"C6\", \"C7\", \"C8\", \"C9\", \"CA\", \"CB\",\n \"CC\", \"CD\", \"CE\", \"CF\", \"D0\", \"D1\", \"D2\", \"D3\", \"D4\", \"D5\", \"D6\", \"D7\",\n \"D8\", \"D9\", \"DA\", \"DB\", \"DC\", \"DD\", \"DE\", \"DF\", \"E0\", \"E1\", \"E2\", \"E3\",\n \"E4\", \"E5\", \"E6\", \"E7\", \"E8\", \"E9\", \"EA\", \"EB\", \"EC\", \"ED\", \"EE\", \"EF\",\n \"F0\", \"F1\", \"F2\", \"F3\", \"F4\", \"F5\", \"F6\", \"F7\", \"F8\", \"F9\", \"FA\", \"FB\",\n \"FC\", \"FD\", \"FE\", \"FF\", (const char *) NULL\n },\n *const PostscriptProlog[]=\n {\n \"%%BeginProlog\",\n \"%\",\n \"% Display a color image. The image is displayed in color on\",\n \"% Postscript viewers or printers that support color, otherwise\",\n \"% it is displayed as grayscale.\",\n \"%\",\n \"/DirectClassPacket\",\n \"{\",\n \" %\",\n \" % Get a DirectClass packet.\",\n \" %\",\n \" % Parameters:\",\n \" % red.\",\n \" % green.\",\n \" % blue.\",\n \" % length: number of pixels minus one of this color (optional).\",\n \" %\",\n \" currentfile color_packet readhexstring pop pop\",\n \" compression 0 eq\",\n \" {\",\n \" /number_pixels 3 def\",\n \" }\",\n \" {\",\n \" currentfile byte readhexstring pop 0 get\",\n \" /number_pixels exch 1 add 3 mul def\",\n \" } ifelse\",\n \" 0 3 number_pixels 1 sub\",\n \" {\",\n \" pixels exch color_packet putinterval\",\n \" } for\",\n \" pixels 0 number_pixels getinterval\",\n \"} bind def\",\n \"\",\n \"/DirectClassImage\",\n \"{\",\n \" %\",\n \" % Display a DirectClass image.\",\n \" %\",\n \" systemdict /colorimage known\",\n \" {\",\n \" columns rows 8\",\n \" [\",\n \" columns 0 0\",\n \" rows neg 0 rows\",\n \" ]\",\n \" { DirectClassPacket } false 3 colorimage\",\n \" }\",\n \" {\",\n \" %\",\n \" % No colorimage operator; convert to grayscale.\",\n \" %\",\n \" columns rows 8\",\n \" [\",\n \" columns 0 0\",\n \" rows neg 0 rows\",\n \" ]\",\n \" { GrayDirectClassPacket } image\",\n \" } ifelse\",\n \"} bind def\",\n \"\",\n \"/GrayDirectClassPacket\",\n \"{\",\n \" %\",\n \" % Get a DirectClass packet; convert to grayscale.\",\n \" %\",\n \" % Parameters:\",\n \" % red\",\n \" % green\",\n \" % blue\",\n \" % length: number of pixels minus one of this color (optional).\",\n \" %\",\n \" currentfile color_packet readhexstring pop pop\",\n \" color_packet 0 get 0.299 mul\",\n \" color_packet 1 get 0.587 mul add\",\n \" color_packet 2 get 0.114 mul add\",\n \" cvi\",\n \" /gray_packet exch def\",\n \" compression 0 eq\",\n \" {\",\n \" /number_pixels 1 def\",\n \" }\",\n \" {\",\n \" currentfile byte readhexstring pop 0 get\",\n \" /number_pixels exch 1 add def\",\n \" } ifelse\",\n \" 0 1 number_pixels 1 sub\",\n \" {\",\n \" pixels exch gray_packet put\",\n \" } for\",\n \" pixels 0 number_pixels getinterval\",\n \"} bind def\",\n \"\",\n \"/GrayPseudoClassPacket\",\n \"{\",\n \" %\",\n \" % Get a PseudoClass packet; convert to grayscale.\",\n \" %\",\n \" % Parameters:\",\n \" % index: index into the colormap.\",\n \" % length: number of pixels minus one of this color (optional).\",\n \" %\",\n \" currentfile byte readhexstring pop 0 get\",\n \" /offset exch 3 mul def\",\n \" /color_packet colormap offset 3 getinterval def\",\n \" color_packet 0 get 0.299 mul\",\n \" color_packet 1 get 0.587 mul add\",\n \" color_packet 2 get 0.114 mul add\",\n \" cvi\",\n \" /gray_packet exch def\",\n \" compression 0 eq\",\n \" {\",\n \" /number_pixels 1 def\",\n \" }\",\n \" {\",\n \" currentfile byte readhexstring pop 0 get\",\n \" /number_pixels exch 1 add def\",\n \" } ifelse\",\n \" 0 1 number_pixels 1 sub\",\n \" {\",\n \" pixels exch gray_packet put\",\n \" } for\",\n \" pixels 0 number_pixels getinterval\",\n \"} bind def\",\n \"\",\n \"/PseudoClassPacket\",\n \"{\",\n \" %\",\n \" % Get a PseudoClass packet.\",\n \" %\",\n \" % Parameters:\",\n \" % index: index into the colormap.\",\n \" % length: number of pixels minus one of this color (optional).\",\n \" %\",\n \" currentfile byte readhexstring pop 0 get\",\n \" /offset exch 3 mul def\",\n \" /color_packet colormap offset 3 getinterval def\",\n \" compression 0 eq\",\n \" {\",\n \" /number_pixels 3 def\",\n \" }\",\n \" {\",\n \" currentfile byte readhexstring pop 0 get\",\n \" /number_pixels exch 1 add 3 mul def\",\n \" } ifelse\",\n \" 0 3 number_pixels 1 sub\",\n \" {\",\n \" pixels exch color_packet putinterval\",\n \" } for\",\n \" pixels 0 number_pixels getinterval\",\n \"} bind def\",\n \"\",\n \"/PseudoClassImage\",\n \"{\",\n \" %\",\n \" % Display a PseudoClass image.\",\n \" %\",\n \" % Parameters:\",\n \" % class: 0-PseudoClass or 1-Grayscale.\",\n \" %\",\n \" currentfile buffer readline pop\",\n \" token pop /class exch def pop\",\n \" class 0 gt\",\n \" {\",\n \" currentfile buffer readline pop\",\n \" token pop /depth exch def pop\",\n \" /grays columns 8 add depth sub depth mul 8 idiv string def\",\n \" columns rows depth\",\n \" [\",\n \" columns 0 0\",\n \" rows neg 0 rows\",\n \" ]\",\n \" { currentfile grays readhexstring pop } image\",\n \" }\",\n \" {\",\n \" %\",\n \" % Parameters:\",\n \" % colors: number of colors in the colormap.\",\n \" % colormap: red, green, blue color packets.\",\n \" %\",\n \" currentfile buffer readline pop\",\n \" token pop /colors exch def pop\",\n \" /colors colors 3 mul def\",\n \" /colormap colors string def\",\n \" currentfile colormap readhexstring pop pop\",\n \" systemdict /colorimage known\",\n \" {\",\n \" columns rows 8\",\n \" [\",\n \" columns 0 0\",\n \" rows neg 0 rows\",\n \" ]\",\n \" { PseudoClassPacket } false 3 colorimage\",\n \" }\",\n \" {\",\n \" %\",\n \" % No colorimage operator; convert to grayscale.\",\n \" %\",\n \" columns rows 8\",\n \" [\",\n \" columns 0 0\",\n \" rows neg 0 rows\",\n \" ]\",\n \" { GrayPseudoClassPacket } image\",\n \" } ifelse\",\n \" } ifelse\",\n \"} bind def\",\n \"\",\n \"/DisplayImage\",\n \"{\",\n \" %\",\n \" % Display a DirectClass or PseudoClass image.\",\n \" %\",\n \" % Parameters:\",\n \" % x & y translation.\",\n \" % x & y scale.\",\n \" % label pointsize.\",\n \" % image label.\",\n \" % image columns & rows.\",\n \" % class: 0-DirectClass or 1-PseudoClass.\",\n \" % compression: 0-none or 1-RunlengthEncoded.\",\n \" % hex color packets.\",\n \" %\",\n \" gsave\",\n \" /buffer 512 string def\",\n \" /byte 1 string def\",\n \" /color_packet 3 string def\",\n \" /pixels 768 string def\",\n \"\",\n \" currentfile buffer readline pop\",\n \" token pop /x exch def\",\n \" token pop /y exch def pop\",\n \" x y translate\",\n \" currentfile buffer readline pop\",\n \" token pop /x exch def\",\n \" token pop /y exch def pop\",\n \" currentfile buffer readline pop\",\n \" token pop /pointsize exch def pop\",\n (const char *) NULL\n },\n *const PostscriptEpilog[]=\n {\n \" x y scale\",\n \" currentfile buffer readline pop\",\n \" token pop /columns exch def\",\n \" token pop /rows exch def pop\",\n \" currentfile buffer readline pop\",\n \" token pop /class exch def pop\",\n \" currentfile buffer readline pop\",\n \" token pop /compression exch def pop\",\n \" class 0 gt { PseudoClassImage } { DirectClassImage } ifelse\",\n \" grestore\",\n (const char *) NULL\n };\n\n char\n buffer[MagickPathExtent],\n date[MagickPathExtent],\n **labels,\n page_geometry[MagickPathExtent];\n\n CompressionType\n compression;\n\n const char\n *const *s,\n *value;\n\n const StringInfo\n *profile;\n\n double\n pointsize;\n\n GeometryInfo\n geometry_info;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n scene;\n\n MagickStatusType\n flags;\n\n PixelInfo\n pixel;\n\n PointInfo\n delta,\n resolution,\n scale;\n\n Quantum\n index;\n\n RectangleInfo\n geometry,\n media_info,\n page_info;\n\n register const Quantum\n *p;\n\n register ssize_t\n i,\n x;\n\n register unsigned char\n *q;\n\n SegmentInfo\n bounds;\n\n size_t\n bit,\n byte,\n imageListLength,\n length,\n page,\n text_size;\n\n ssize_t\n j,\n y;\n\n time_t\n timer;\n\n unsigned char\n pixels[2048];\n\n /*\n Open output image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);\n if (status == MagickFalse)\n return(status);\n (void) memset(&bounds,0,sizeof(bounds));\n compression=image->compression;\n if (image_info->compression != UndefinedCompression)\n compression=image_info->compression;\n page=1;\n scene=0;\n imageListLength=GetImageListLength(image);\n do\n {\n /*\n Scale relative to dots-per-inch.\n */\n (void) TransformImageColorspace(image,sRGBColorspace,exception);\n delta.x=DefaultResolution;\n delta.y=DefaultResolution;\n resolution.x=image->resolution.x;\n resolution.y=image->resolution.y;\n if ((resolution.x == 0.0) || (resolution.y == 0.0))\n {\n flags=ParseGeometry(PSDensityGeometry,&geometry_info);\n resolution.x=geometry_info.rho;\n resolution.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n resolution.y=resolution.x;\n }\n if (image_info->density != (char *) NULL)\n {\n flags=ParseGeometry(image_info->density,&geometry_info);\n resolution.x=geometry_info.rho;\n resolution.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n resolution.y=resolution.x;\n }\n if (image->units == PixelsPerCentimeterResolution)\n {\n resolution.x=(double) ((size_t) (100.0*2.54*resolution.x+0.5)/100.0);\n resolution.y=(double) ((size_t) (100.0*2.54*resolution.y+0.5)/100.0);\n }\n SetGeometry(image,&geometry);\n (void) FormatLocaleString(page_geometry,MagickPathExtent,\"%.20gx%.20g\",\n (double) image->columns,(double) image->rows);\n if (image_info->page != (char *) NULL)\n (void) CopyMagickString(page_geometry,image_info->page,MagickPathExtent);\n else\n if ((image->page.width != 0) && (image->page.height != 0))\n (void) FormatLocaleString(page_geometry,MagickPathExtent,\n \"%.20gx%.20g%+.20g%+.20g\",(double) image->page.width,(double)\n image->page.height,(double) image->page.x,(double) image->page.y);\n else\n if ((image->gravity != UndefinedGravity) &&\n (LocaleCompare(image_info->magick,\"PS\") == 0))\n (void) CopyMagickString(page_geometry,PSPageGeometry,MagickPathExtent);\n (void) ConcatenateMagickString(page_geometry,\">\",MagickPathExtent);\n (void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y,\n &geometry.width,&geometry.height);\n scale.x=(double) (geometry.width*delta.x)/resolution.x;\n geometry.width=(size_t) floor(scale.x+0.5);\n scale.y=(double) (geometry.height*delta.y)/resolution.y;\n geometry.height=(size_t) floor(scale.y+0.5);\n (void) ParseAbsoluteGeometry(page_geometry,&media_info);\n (void) ParseGravityGeometry(image,page_geometry,&page_info,exception);\n if (image->gravity != UndefinedGravity)\n {\n geometry.x=(-page_info.x);\n geometry.y=(ssize_t) (media_info.height+page_info.y-image->rows);\n }\n pointsize=12.0;\n if (image_info->pointsize != 0.0)\n pointsize=image_info->pointsize;\n text_size=0;\n value=GetImageProperty(image,\"label\",exception);\n if (value != (const char *) NULL)\n text_size=(size_t) (MultilineCensus(value)*pointsize+12);\n if (page == 1)\n {\n /*\n Output Postscript header.\n */\n if (LocaleCompare(image_info->magick,\"PS\") == 0)\n (void) CopyMagickString(buffer,\"%!PS-Adobe-3.0\\n\",MagickPathExtent);\n else\n (void) CopyMagickString(buffer,\"%!PS-Adobe-3.0 EPSF-3.0\\n\",\n MagickPathExtent);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"%%Creator: (ImageMagick)\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%%%%Title: (%s)\\n\",\n image->filename);\n (void) WriteBlobString(image,buffer);\n timer=time((time_t *) NULL);\n (void) FormatMagickTime(timer,MagickPathExtent,date);\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"%%%%CreationDate: (%s)\\n\",date);\n (void) WriteBlobString(image,buffer);\n bounds.x1=(double) geometry.x;\n bounds.y1=(double) geometry.y;\n bounds.x2=(double) geometry.x+scale.x;\n bounds.y2=(double) geometry.y+(geometry.height+text_size);\n if ((image_info->adjoin != MagickFalse) &&\n (GetNextImageInList(image) != (Image *) NULL))\n (void) CopyMagickString(buffer,\"%%%%BoundingBox: (atend)\\n\",\n MagickPathExtent);\n else\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"%%%%BoundingBox: %.20g %.20g %.20g %.20g\\n\",ceil(bounds.x1-0.5),\n ceil(bounds.y1-0.5),floor(bounds.x2+0.5),floor(bounds.y2+0.5));\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"%%%%HiResBoundingBox: %g %g %g %g\\n\",bounds.x1,\n bounds.y1,bounds.x2,bounds.y2);\n }\n (void) WriteBlobString(image,buffer);\n profile=GetImageProfile(image,\"8bim\");\n if (profile != (StringInfo *) NULL)\n {\n /*\n Embed Photoshop profile.\n */\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"%%BeginPhotoshop: %.20g\",(double) GetStringInfoLength(profile));\n (void) WriteBlobString(image,buffer);\n for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++)\n {\n if ((i % 32) == 0)\n (void) WriteBlobString(image,\"\\n% \");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%02X\",\n (unsigned int) (GetStringInfoDatum(profile)[i] & 0xff));\n (void) WriteBlobString(image,buffer);\n }\n (void) WriteBlobString(image,\"\\n%EndPhotoshop\\n\");\n }\n profile=GetImageProfile(image,\"xmp\");\nDisableMSCWarning(4127)\n if (0 && (profile != (StringInfo *) NULL))\nRestoreMSCWarning\n {\n /*\n Embed XML profile.\n */\n (void) WriteBlobString(image,\"\\n%begin_xml_code\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"\\n%%begin_xml_packet: %.20g\\n\",(double)\n GetStringInfoLength(profile));\n (void) WriteBlobString(image,buffer);\n for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++)\n (void) WriteBlobByte(image,GetStringInfoDatum(profile)[i]);\n (void) WriteBlobString(image,\"\\n%end_xml_packet\\n%end_xml_code\\n\");\n }\n value=GetImageProperty(image,\"label\",exception);\n if (value != (const char *) NULL)\n (void) WriteBlobString(image,\n \"%%DocumentNeededResources: font Times-Roman\\n\");\n (void) WriteBlobString(image,\"%%DocumentData: Clean7Bit\\n\");\n (void) WriteBlobString(image,\"%%LanguageLevel: 1\\n\");\n if (LocaleCompare(image_info->magick,\"PS\") != 0)\n (void) WriteBlobString(image,\"%%Pages: 1\\n\");\n else\n {\n /*\n Compute the number of pages.\n */\n (void) WriteBlobString(image,\"%%Orientation: Portrait\\n\");\n (void) WriteBlobString(image,\"%%PageOrder: Ascend\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"%%%%Pages: %.20g\\n\",image_info->adjoin != MagickFalse ?\n (double) imageListLength : 1.0);\n (void) WriteBlobString(image,buffer);\n }\n (void) WriteBlobString(image,\"%%EndComments\\n\");\n (void) WriteBlobString(image,\"\\n%%BeginDefaults\\n\");\n (void) WriteBlobString(image,\"%%EndDefaults\\n\\n\");\n if ((LocaleCompare(image_info->magick,\"EPI\") == 0) ||\n (LocaleCompare(image_info->magick,\"EPSI\") == 0) ||\n (LocaleCompare(image_info->magick,\"EPT\") == 0))\n {\n Image\n *preview_image;\n\n Quantum\n pixel;\n\n register ssize_t\n x;\n\n ssize_t\n y;\n\n /*\n Create preview image.\n */\n preview_image=CloneImage(image,0,0,MagickTrue,exception);\n if (preview_image == (Image *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n /*\n Dump image as bitmap.\n */\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"%%%%BeginPreview: %.20g %.20g %.20g %.20g\\n%% \",(double)\n preview_image->columns,(double) preview_image->rows,1.0,\n (double) ((((preview_image->columns+7) >> 3)*preview_image->rows+\n 35)/36));\n (void) WriteBlobString(image,buffer);\n q=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(preview_image,0,y,preview_image->columns,1,\n exception);\n if (p == (const Quantum *) NULL)\n break;\n bit=0;\n byte=0;\n for (x=0; x < (ssize_t) preview_image->columns; x++)\n {\n byte<<=1;\n pixel=ClampToQuantum(GetPixelLuma(preview_image,p));\n if (pixel >= (Quantum) (QuantumRange/2))\n byte|=0x01;\n bit++;\n if (bit == 8)\n {\n q=PopHexPixel(hex_digits,byte,q);\n if ((q-pixels+8) >= 80)\n {\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n q=pixels;\n (void) WriteBlobString(image,\"% \");\n };\n bit=0;\n byte=0;\n }\n }\n if (bit != 0)\n {\n byte<<=(8-bit);\n q=PopHexPixel(hex_digits,byte,q);\n if ((q-pixels+8) >= 80)\n {\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n q=pixels;\n (void) WriteBlobString(image,\"% \");\n };\n };\n }\n if (q != pixels)\n {\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n }\n (void) WriteBlobString(image,\"\\n%%EndPreview\\n\");\n preview_image=DestroyImage(preview_image);\n }\n /*\n Output Postscript commands.\n */\n for (s=PostscriptProlog; *s != (char *) NULL; s++)\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%s\\n\",*s);\n (void) WriteBlobString(image,buffer);\n }\n value=GetImageProperty(image,\"label\",exception);\n if (value != (const char *) NULL)\n {\n (void) WriteBlobString(image,\n \" /Times-Roman findfont pointsize scalefont setfont\\n\");\n for (j=(ssize_t) MultilineCensus(value)-1; j >= 0; j--)\n {\n (void) WriteBlobString(image,\" /label 512 string def\\n\");\n (void) WriteBlobString(image,\n \" currentfile label readline pop\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \" 0 y %g add moveto label show pop\\n\",j*pointsize+12);\n (void) WriteBlobString(image,buffer);\n }\n }\n for (s=PostscriptEpilog; *s != (char *) NULL; s++)\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%s\\n\",*s);\n (void) WriteBlobString(image,buffer);\n }\n if (LocaleCompare(image_info->magick,\"PS\") == 0)\n (void) WriteBlobString(image,\" showpage\\n\");\n (void) WriteBlobString(image,\"} bind def\\n\");\n (void) WriteBlobString(image,\"%%EndProlog\\n\");\n }\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%%%%Page: 1 %.20g\\n\",\n (double) (page++));\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"%%%%PageBoundingBox: %.20g %.20g %.20g %.20g\\n\",(double) geometry.x,\n (double) geometry.y,geometry.x+(double) geometry.width,geometry.y+(double)\n (geometry.height+text_size));\n (void) WriteBlobString(image,buffer);\n if ((double) geometry.x < bounds.x1)\n bounds.x1=(double) geometry.x;\n if ((double) geometry.y < bounds.y1)\n bounds.y1=(double) geometry.y;\n if ((double) (geometry.x+geometry.width-1) > bounds.x2)\n bounds.x2=(double) geometry.x+geometry.width-1;\n if ((double) (geometry.y+(geometry.height+text_size)-1) > bounds.y2)\n bounds.y2=(double) geometry.y+(geometry.height+text_size)-1;\n value=GetImageProperty(image,\"label\",exception);\n if (value != (const char *) NULL)\n (void) WriteBlobString(image,\"%%%%PageResources: font Times-Roman\\n\");\n if (LocaleCompare(image_info->magick,\"PS\") != 0)\n (void) WriteBlobString(image,\"userdict begin\\n\");\n (void) WriteBlobString(image,\"DisplayImage\\n\");\n /*\n Output image data.\n */\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g %.20g\\n%g %g\\n%g\\n\",\n (double) geometry.x,(double) geometry.y,scale.x,scale.y,pointsize);\n (void) WriteBlobString(image,buffer);\n labels=(char **) NULL;\n value=GetImageProperty(image,\"label\",exception);\n if (value != (const char *) NULL)\n labels=StringToList(value);\n if (labels != (char **) NULL)\n {\n for (i=0; labels[i] != (char *) NULL; i++)\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%s \\n\",\n labels[i]);\n (void) WriteBlobString(image,buffer);\n labels[i]=DestroyString(labels[i]);\n }\n labels=(char **) RelinquishMagickMemory(labels);\n }\n (void) memset(&pixel,0,sizeof(pixel));\n pixel.alpha=(MagickRealType) TransparentAlpha;\n index=0;\n x=0;\n if ((image_info->type != TrueColorType) &&\n (SetImageGray(image,exception) != MagickFalse))\n {\n if (SetImageMonochrome(image,exception) == MagickFalse)\n {\n Quantum\n pixel;\n\n /*\n Dump image as grayscale.\n */\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"%.20g %.20g\\n1\\n1\\n1\\n8\\n\",(double) image->columns,(double)\n image->rows);\n (void) WriteBlobString(image,buffer);\n q=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=(Quantum) ScaleQuantumToChar(ClampToQuantum(GetPixelLuma(\n image,p)));\n q=PopHexPixel(hex_digits,(size_t) pixel,q);\n if ((q-pixels+8) >= 80)\n {\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n q=pixels;\n }\n p+=GetPixelChannels(image);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)\n y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n if (q != pixels)\n {\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n }\n }\n else\n {\n ssize_t\n y;\n\n Quantum\n pixel;\n\n /*\n Dump image as bitmap.\n */\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"%.20g %.20g\\n1\\n1\\n1\\n1\\n\",(double) image->columns,(double)\n image->rows);\n (void) WriteBlobString(image,buffer);\n q=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n bit=0;\n byte=0;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n byte<<=1;\n pixel=ClampToQuantum(GetPixelLuma(image,p));\n if (pixel >= (Quantum) (QuantumRange/2))\n byte|=0x01;\n bit++;\n if (bit == 8)\n {\n q=PopHexPixel(hex_digits,byte,q);\n if ((q-pixels+2) >= 80)\n {\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n q=pixels;\n };\n bit=0;\n byte=0;\n }\n p+=GetPixelChannels(image);\n }\n if (bit != 0)\n {\n byte<<=(8-bit);\n q=PopHexPixel(hex_digits,byte,q);\n if ((q-pixels+2) >= 80)\n {\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n q=pixels;\n }\n };\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)\n y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n if (q != pixels)\n {\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n }\n }\n }\n else\n if ((image->storage_class == DirectClass) ||\n (image->colors > 256) || (image->alpha_trait != UndefinedPixelTrait))\n {\n /*\n Dump DirectClass image.\n */\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"%.20g %.20g\\n0\\n%d\\n\",(double) image->columns,(double) image->rows,\n compression == RLECompression ? 1 : 0);\n (void) WriteBlobString(image,buffer);\n switch (compression)\n {\n case RLECompression:\n {\n /*\n Dump runlength-encoded DirectColor packets.\n */\n q=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n GetPixelInfoPixel(image,p,&pixel);\n length=255;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if ((GetPixelRed(image,p) == ClampToQuantum(pixel.red)) &&\n (GetPixelGreen(image,p) == ClampToQuantum(pixel.green)) &&\n (GetPixelBlue(image,p) == ClampToQuantum(pixel.blue)) &&\n (GetPixelAlpha(image,p) == ClampToQuantum(pixel.alpha)) &&\n (length < 255) && (x < (ssize_t) (image->columns-1)))\n length++;\n else\n {\n if (x > 0)\n {\n WriteRunlengthPacket(image,pixel,length,p);\n if ((q-pixels+10) >= 80)\n {\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n q=pixels;\n }\n }\n length=0;\n }\n GetPixelInfoPixel(image,p,&pixel);\n p+=GetPixelChannels(image);\n }\n WriteRunlengthPacket(image,pixel,length,p);\n if ((q-pixels+10) >= 80)\n {\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n q=pixels;\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,\n (MagickOffsetType) y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n if (q != pixels)\n {\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n }\n break;\n }\n case NoCompression:\n default:\n {\n /*\n Dump uncompressed DirectColor packets.\n */\n q=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if ((image->alpha_trait != UndefinedPixelTrait) &&\n (GetPixelAlpha(image,p) == (Quantum) TransparentAlpha))\n {\n q=PopHexPixel(hex_digits,0xff,q);\n q=PopHexPixel(hex_digits,0xff,q);\n q=PopHexPixel(hex_digits,0xff,q);\n }\n else\n {\n q=PopHexPixel(hex_digits,ScaleQuantumToChar(\n GetPixelRed(image,p)),q);\n q=PopHexPixel(hex_digits,ScaleQuantumToChar(\n GetPixelGreen(image,p)),q);\n q=PopHexPixel(hex_digits,ScaleQuantumToChar(\n GetPixelBlue(image,p)),q);\n }\n if ((q-pixels+6) >= 80)\n {\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n q=pixels;\n }\n p+=GetPixelChannels(image);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,\n (MagickOffsetType) y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n if (q != pixels)\n {\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n }\n break;\n }\n }\n (void) WriteBlobByte(image,'\\n');\n }\n else\n {\n /*\n Dump PseudoClass image.\n */\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"%.20g %.20g\\n%d\\n%d\\n0\\n\",(double) image->columns,(double)\n image->rows,image->storage_class == PseudoClass ? 1 : 0,\n compression == RLECompression ? 1 : 0);\n (void) WriteBlobString(image,buffer);\n /*\n Dump number of colors and colormap.\n */\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double)\n image->colors);\n (void) WriteBlobString(image,buffer);\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%02X%02X%02X\\n\",\n ScaleQuantumToChar(ClampToQuantum(image->colormap[i].red)),\n ScaleQuantumToChar(ClampToQuantum(image->colormap[i].green)),\n ScaleQuantumToChar(ClampToQuantum(image->colormap[i].blue)));\n (void) WriteBlobString(image,buffer);\n }\n switch (compression)\n {\n case RLECompression:\n {\n /*\n Dump runlength-encoded PseudoColor packets.\n */\n q=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n index=GetPixelIndex(image,p);\n length=255;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if ((index == GetPixelIndex(image,p)) &&\n (length < 255) && (x < ((ssize_t) image->columns-1)))\n length++;\n else\n {\n if (x > 0)\n {\n q=PopHexPixel(hex_digits,(size_t) index,q);\n q=PopHexPixel(hex_digits,(size_t)\n MagickMin(length,0xff),q);\n i++;\n if ((q-pixels+6) >= 80)\n {\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n q=pixels;\n }\n }\n length=0;\n }\n index=GetPixelIndex(image,p);\n pixel.red=(MagickRealType) GetPixelRed(image,p);\n pixel.green=(MagickRealType) GetPixelGreen(image,p);\n pixel.blue=(MagickRealType) GetPixelBlue(image,p);\n pixel.alpha=(MagickRealType) GetPixelAlpha(image,p);\n p+=GetPixelChannels(image);\n }\n q=PopHexPixel(hex_digits,(size_t) index,q);\n q=PopHexPixel(hex_digits,(size_t)\n MagickMin(length,0xff),q);\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,\n (MagickOffsetType) y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n if (q != pixels)\n {\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n }\n break;\n }\n case NoCompression:\n default:\n {\n /*\n Dump uncompressed PseudoColor packets.\n */\n q=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n q=PopHexPixel(hex_digits,(size_t) GetPixelIndex(image,p),q);\n if ((q-pixels+4) >= 80)\n {\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n q=pixels;\n }\n p+=GetPixelChannels(image);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,\n (MagickOffsetType) y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n if (q != pixels)\n {\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n }\n break;\n }\n }\n (void) WriteBlobByte(image,'\\n');\n }\n if (LocaleCompare(image_info->magick,\"PS\") != 0)\n (void) WriteBlobString(image,\"end\\n\");\n (void) WriteBlobString(image,\"%%PageTrailer\\n\");\n if (GetNextImageInList(image) == (Image *) NULL)\n break;\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);\n if (status == MagickFalse)\n break;\n } while (image_info->adjoin != MagickFalse);\n (void) WriteBlobString(image,\"%%Trailer\\n\");\n if (page > 2)\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"%%%%BoundingBox: %.20g %.20g %.20g %.20g\\n\",ceil(bounds.x1-0.5),\n ceil(bounds.y1-0.5),floor(bounds.x2-0.5),floor(bounds.y2-0.5));\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"%%%%HiResBoundingBox: %g %g %g %g\\n\",bounds.x1,bounds.y1,bounds.x2,\n bounds.y2);\n (void) WriteBlobString(image,buffer);\n }\n (void) WriteBlobString(image,\"%%EOF\\n\");\n (void) CloseBlob(image);\n return(MagickTrue);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1523'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: UsbHubReadDesc (\r\n IN USB_DEVICE *HubDev,\r\n OUT EFI_USB_HUB_DESCRIPTOR *HubDesc\r\n )\r\n{\r\n EFI_STATUS Status;\r\n\r\n if (HubDev->Speed == EFI_USB_SPEED_SUPER) {\r\n //\r\n // Get the super speed hub descriptor\r\n //\r\n Status = UsbHubCtrlGetSuperSpeedHubDesc (HubDev, HubDesc);\r\n } else {\r\n\r\n //\r\n // First get the hub descriptor length\r\n //\r\n Status = UsbHubCtrlGetHubDesc (HubDev, HubDesc, 2);\r\n\r\n if (EFI_ERROR (Status)) {\r\n return Status;\r\n }\r\n\r\n //\r\n // Get the whole hub descriptor\r\n //\r\n Status = UsbHubCtrlGetHubDesc (HubDev, HubDesc, HubDesc->Length);\r\n }\r\n\r\n return Status;\r\n}\r ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'MdeModulePkg UsbBusDxe: Fix wrong buffer length used to read hub desc\n\nREF: https://bugzilla.tianocore.org/show_bug.cgi?id=973\n\nHUB descriptor has variable length.\nBut the code uses stack (HubDesc in UsbHubInit) with fixed length\nsizeof(EFI_USB_HUB_DESCRIPTOR) to hold HUB descriptor data.\nIt uses hard code length value (32 that is greater than\nsizeof(EFI_USB_HUB_DESCRIPTOR)) for SuperSpeed path, then there will\nbe stack overflow when IOMMU is enabled because the Unmap operation\nwill copy the data from device buffer to host buffer.\nAnd it uses HubDesc->Length for none SuperSpeed path, then there will\nbe stack overflow when HubDesc->Length is greater than\nsizeof(EFI_USB_HUB_DESCRIPTOR).\n\nThe patch updates the code to use a big enough buffer to hold the\ndescriptor data.\nThe definition EFI_USB_SUPER_SPEED_HUB_DESCRIPTOR is wrong (HubDelay\nfield should be UINT16 type) and no code is using it, the patch\nremoves it.\n\nCc: Jiewen Yao \nCc: Ruiyu Ni \nCc: Bret Barkelew \nContributed-under: TianoCore Contribution Agreement 1.1\nSigned-off-by: Star Zeng \nReviewed-by: Bret Barkelew '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: request_rec *h2_request_create_rec(const h2_request *req, conn_rec *c)\n{\n int access_status = HTTP_OK; \n const char *rpath;\n const char *s;\n\n#if AP_MODULE_MAGIC_AT_LEAST(20150222, 13)\n request_rec *r = ap_create_request(c);\n#else\n request_rec *r = my_ap_create_request(c);\n#endif\n\n r->headers_in = apr_table_clone(r->pool, req->headers);\n\n ap_run_pre_read_request(r, c);\n \n /* Time to populate r with the data we have. */\n r->request_time = req->request_time;\n r->method = req->method;\n /* Provide quick information about the request method as soon as known */\n r->method_number = ap_method_number_of(r->method);\n if (r->method_number == M_GET && r->method[0] == 'H') {\n r->header_only = 1;\n }\n\n rpath = (req->path ? req->path : \"\");\n ap_parse_uri(r, rpath);\n r->protocol = (char*)\"HTTP/2.0\";\n r->proto_num = HTTP_VERSION(2, 0);\n\n r->the_request = apr_psprintf(r->pool, \"%s %s %s\", \n r->method, rpath, r->protocol);\n \n /* update what we think the virtual host is based on the headers we've\n * now read. may update status.\n * Leave r->hostname empty, vhost will parse if form our Host: header,\n * otherwise we get complains about port numbers.\n */\n r->hostname = NULL;\n ap_update_vhost_from_headers(r);\n \n /* we may have switched to another server */\n r->per_dir_config = r->server->lookup_defaults;\n \n s = apr_table_get(r->headers_in, \"Expect\");\n if (s && s[0]) {\n if (ap_cstr_casecmp(s, \"100-continue\") == 0) {\n r->expecting_100 = 1;\n }\n else {\n r->status = HTTP_EXPECTATION_FAILED;\n ap_send_error_response(r, 0);\n }\n }\n\n /*\n * Add the HTTP_IN filter here to ensure that ap_discard_request_body\n * called by ap_die and by ap_send_error_response works correctly on\n * status codes that do not cause the connection to be dropped and\n * in situations where the connection should be kept alive.\n */\n ap_add_input_filter_handle(ap_http_input_filter_handle,\n NULL, r, r->connection);\n \n if (access_status != HTTP_OK\n || (access_status = ap_run_post_read_request(r))) {\n /* Request check post hooks failed. An example of this would be a\n * request for a vhost where h2 is disabled --> 421.\n */\n ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, c, APLOGNO(03367)\n \"h2_request: access_status=%d, request_create failed\",\n access_status);\n ap_die(access_status, r);\n ap_update_child_status(c->sbh, SERVER_BUSY_LOG, r);\n ap_run_log_transaction(r);\n r = NULL;\n goto traceout;\n }\n\n AP_READ_REQUEST_SUCCESS((uintptr_t)r, (char *)r->method, \n (char *)r->uri, (char *)r->server->defn_name, \n r->status);\n return r;\ntraceout:\n AP_READ_REQUEST_FAILURE((uintptr_t)r);\n return r;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': '* Integrated a forgotten request init fix from Apache subversion'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void aio_complete_rw(struct kiocb *kiocb, long res, long res2)\n{\n\tstruct aio_kiocb *iocb = container_of(kiocb, struct aio_kiocb, rw);\n\n\tif (!list_empty_careful(&iocb->ki_list))\n\t\taio_remove_iocb(iocb);\n\n\tif (kiocb->ki_flags & IOCB_WRITE) {\n\t\tstruct inode *inode = file_inode(kiocb->ki_filp);\n\n\t\t/*\n\t\t * Tell lockdep we inherited freeze protection from submission\n\t\t * thread.\n\t\t */\n\t\tif (S_ISREG(inode->i_mode))\n\t\t\t__sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);\n\t\tfile_end_write(kiocb->ki_filp);\n\t}\n\n\tfput(kiocb->ki_filp);\n\taio_complete(iocb, res, res2);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'aio: simplify - and fix - fget/fput for io_submit()\n\nAl Viro root-caused a race where the IOCB_CMD_POLL handling of\nfget/fput() could cause us to access the file pointer after it had\nalready been freed:\n\n \"In more details - normally IOCB_CMD_POLL handling looks so:\n\n 1) io_submit(2) allocates aio_kiocb instance and passes it to\n aio_poll()\n\n 2) aio_poll() resolves the descriptor to struct file by req->file =\n fget(iocb->aio_fildes)\n\n 3) aio_poll() sets ->woken to false and raises ->ki_refcnt of that\n aio_kiocb to 2 (bumps by 1, that is).\n\n 4) aio_poll() calls vfs_poll(). After sanity checks (basically,\n \"poll_wait() had been called and only once\") it locks the queue.\n That's what the extra reference to iocb had been for - we know we\n can safely access it.\n\n 5) With queue locked, we check if ->woken has already been set to\n true (by aio_poll_wake()) and, if it had been, we unlock the\n queue, drop a reference to aio_kiocb and bugger off - at that\n point it's a responsibility to aio_poll_wake() and the stuff\n called/scheduled by it. That code will drop the reference to file\n in req->file, along with the other reference to our aio_kiocb.\n\n 6) otherwise, we see whether we need to wait. If we do, we unlock the\n queue, drop one reference to aio_kiocb and go away - eventual\n wakeup (or cancel) will deal with the reference to file and with\n the other reference to aio_kiocb\n\n 7) otherwise we remove ourselves from waitqueue (still under the\n queue lock), so that wakeup won't get us. No async activity will\n be happening, so we can safely drop req->file and iocb ourselves.\n\n If wakeup happens while we are in vfs_poll(), we are fine - aio_kiocb\n won't get freed under us, so we can do all the checks and locking\n safely. And we don't touch ->file if we detect that case.\n\n However, vfs_poll() most certainly *does* touch the file it had been\n given. So wakeup coming while we are still in ->poll() might end up\n doing fput() on that file. That case is not too rare, and usually we\n are saved by the still present reference from descriptor table - that\n fput() is not the final one.\n\n But if another thread closes that descriptor right after our fget()\n and wakeup does happen before ->poll() returns, we are in trouble -\n final fput() done while we are in the middle of a method:\n\nAl also wrote a patch to take an extra reference to the file descriptor\nto fix this, but I instead suggested we just streamline the whole file\npointer handling by submit_io() so that the generic aio submission code\nsimply keeps the file pointer around until the aio has completed.\n\nFixes: bfe4037e722e (\"aio: implement IOCB_CMD_POLL\")\nAcked-by: Al Viro \nReported-by: syzbot+503d4cc169fcec1cb18c@syzkaller.appspotmail.com\nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int process_peer_commit (pwd_session_t *session, uint8_t *in, size_t in_len, BN_CTX *bnctx)\n{\n\tuint8_t *ptr;\n\tsize_t data_len;\n\tBIGNUM *x = NULL, *y = NULL, *cofactor = NULL;\n\tEC_POINT *K = NULL, *point = NULL;\n\tint res = 1;\n\n\tif (((session->peer_scalar = BN_new()) == NULL) ||\n\t ((session->k = BN_new()) == NULL) ||\n\t ((cofactor = BN_new()) == NULL) ||\n\t ((x = BN_new()) == NULL) ||\n\t ((y = BN_new()) == NULL) ||\n\t ((point = EC_POINT_new(session->group)) == NULL) ||\n\t ((K = EC_POINT_new(session->group)) == NULL) ||\n\t ((session->peer_element = EC_POINT_new(session->group)) == NULL)) {\n\t\tDEBUG2(\"pwd: failed to allocate room to process peer's commit\");\n\t\tgoto finish;\n\t}\n\n\tif (!EC_GROUP_get_cofactor(session->group, cofactor, NULL)) {\n\t\tDEBUG2(\"pwd: unable to get group co-factor\");\n\t\tgoto finish;\n\t}\n\n\t/* element, x then y, followed by scalar */\n\tptr = (uint8_t *)in;\n\tdata_len = BN_num_bytes(session->prime);\n\n\t/*\n\t *\tDid the peer send enough data?\n\t */\n\tif (in_len < (2 * data_len + BN_num_bytes(session->order))) {\n\t\tDEBUG(\"pwd: Invalid commit packet\");\n\t\tgoto finish;\n\t}\n\n\tBN_bin2bn(ptr, data_len, x);\n\tptr += data_len;\n\tBN_bin2bn(ptr, data_len, y);\n\tptr += data_len;\n\n\tdata_len = BN_num_bytes(session->order);\n\tBN_bin2bn(ptr, data_len, session->peer_scalar);\n\n\tif (!EC_POINT_set_affine_coordinates_GFp(session->group, session->peer_element, x, y, bnctx)) {\n\t\tDEBUG2(\"pwd: unable to get coordinates of peer's element\");\n\t\tgoto finish;\n\t}\n\n\t/* check to ensure peer's element is not in a small sub-group */\n\tif (BN_cmp(cofactor, BN_value_one())) {\n\t\tif (!EC_POINT_mul(session->group, point, NULL, session->peer_element, cofactor, NULL)) {\n\t\t\tDEBUG2(\"pwd: unable to multiply element by co-factor\");\n\t\t\tgoto finish;\n\t\t}\n\n\t\tif (EC_POINT_is_at_infinity(session->group, point)) {\n\t\t\tDEBUG2(\"pwd: peer's element is in small sub-group\");\n\t\t\tgoto finish;\n\t\t}\n\t}\n\n\t/* compute the shared key, k */\n\tif ((!EC_POINT_mul(session->group, K, NULL, session->pwe, session->peer_scalar, bnctx)) ||\n\t (!EC_POINT_add(session->group, K, K, session->peer_element, bnctx)) ||\n\t (!EC_POINT_mul(session->group, K, NULL, K, session->private_value, bnctx))) {\n\t\tDEBUG2(\"pwd: unable to compute shared key, k\");\n\t\tgoto finish;\n\t}\n\n\t/* ensure that the shared key isn't in a small sub-group */\n\tif (BN_cmp(cofactor, BN_value_one())) {\n\t\tif (!EC_POINT_mul(session->group, K, NULL, K, cofactor, NULL)) {\n\t\t\tDEBUG2(\"pwd: unable to multiply k by co-factor\");\n\t\t\tgoto finish;\n\t\t}\n\t}\n\n\t/*\n\t * This check is strictly speaking just for the case above where\n\t * co-factor > 1 but it was suggested that even though this is probably\n\t * never going to happen it is a simple and safe check \"just to be\n\t * sure\" so let's be safe.\n\t */\n\tif (EC_POINT_is_at_infinity(session->group, K)) {\n\t\tDEBUG2(\"pwd: k is point-at-infinity!\");\n\t\tgoto finish;\n\t}\n\n\tif (!EC_POINT_get_affine_coordinates_GFp(session->group, K, session->k, NULL, bnctx)) {\n\t\tDEBUG2(\"pwd: unable to get shared secret from K\");\n\t\tgoto finish;\n\t}\n\tres = 0;\n\nfinish:\n\tEC_POINT_clear_free(K);\n\tEC_POINT_clear_free(point);\n\tBN_clear_free(cofactor);\n\tBN_clear_free(x);\n\tBN_clear_free(y);\n\n\treturn res;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-345'], 'message': 'When processing an EAP-pwd Commit frame, the peer's scalar and elliptic curve\npoint were not validated. This allowed an adversary to bypass authentication,\nand impersonate any user.\n\nFix this vulnerability by assuring the received scalar lies within the valid\nrange, and by checking that the received element is not the point at infinity\nand lies on the elliptic curve being used.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: main (int argc,\n char **argv)\n{\n mode_t old_umask;\n cleanup_free char *base_path = NULL;\n int clone_flags;\n char *old_cwd = NULL;\n pid_t pid;\n int event_fd = -1;\n int child_wait_fd = -1;\n int setup_finished_pipe[] = {-1, -1};\n const char *new_cwd;\n uid_t ns_uid;\n gid_t ns_gid;\n struct stat sbuf;\n uint64_t val;\n int res UNUSED;\n cleanup_free char *seccomp_data = NULL;\n size_t seccomp_len;\n struct sock_fprog seccomp_prog;\n cleanup_free char *args_data = NULL;\n\n /* Handle --version early on before we try to acquire/drop\n * any capabilities so it works in a build environment;\n * right now flatpak's build runs bubblewrap --version.\n * https://github.com/projectatomic/bubblewrap/issues/185\n */\n if (argc == 2 && (strcmp (argv[1], \"--version\") == 0))\n print_version_and_exit ();\n\n real_uid = getuid ();\n real_gid = getgid ();\n\n /* Get the (optional) privileges we need */\n acquire_privs ();\n\n /* Never gain any more privs during exec */\n if (prctl (PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0)\n die_with_error (\"prctl(PR_SET_NO_NEW_CAPS) failed\");\n\n /* The initial code is run with high permissions\n (i.e. CAP_SYS_ADMIN), so take lots of care. */\n\n read_overflowids ();\n\n argv0 = argv[0];\n\n if (isatty (1))\n host_tty_dev = ttyname (1);\n\n argv++;\n argc--;\n\n if (argc == 0)\n usage (EXIT_FAILURE, stderr);\n\n parse_args (&argc, (const char ***) &argv);\n\n /* suck the args into a cleanup_free variable to control their lifecycle */\n args_data = opt_args_data;\n opt_args_data = NULL;\n\n if ((requested_caps[0] || requested_caps[1]) && is_privileged)\n die (\"--cap-add in setuid mode can be used only by root\");\n\n if (opt_userns_block_fd != -1 && !opt_unshare_user)\n die (\"--userns-block-fd requires --unshare-user\");\n\n if (opt_userns_block_fd != -1 && opt_info_fd == -1)\n die (\"--userns-block-fd requires --info-fd\");\n\n /* We have to do this if we weren't installed setuid (and we're not\n * root), so let's just DWIM */\n if (!is_privileged && getuid () != 0)\n opt_unshare_user = TRUE;\n\n#ifdef ENABLE_REQUIRE_USERNS\n /* In this build option, we require userns. */\n if (is_privileged && getuid () != 0)\n opt_unshare_user = TRUE;\n#endif\n\n if (opt_unshare_user_try &&\n stat (\"/proc/self/ns/user\", &sbuf) == 0)\n {\n bool disabled = FALSE;\n\n /* RHEL7 has a kernel module parameter that lets you enable user namespaces */\n if (stat (\"/sys/module/user_namespace/parameters/enable\", &sbuf) == 0)\n {\n cleanup_free char *enable = NULL;\n enable = load_file_at (AT_FDCWD, \"/sys/module/user_namespace/parameters/enable\");\n if (enable != NULL && enable[0] == 'N')\n disabled = TRUE;\n }\n\n /* Check for max_user_namespaces */\n if (stat (\"/proc/sys/user/max_user_namespaces\", &sbuf) == 0)\n {\n cleanup_free char *max_user_ns = NULL;\n max_user_ns = load_file_at (AT_FDCWD, \"/proc/sys/user/max_user_namespaces\");\n if (max_user_ns != NULL && strcmp(max_user_ns, \"0\\n\") == 0)\n disabled = TRUE;\n }\n\n /* Debian lets you disable *unprivileged* user namespaces. However this is not\n a problem if we're privileged, and if we're not opt_unshare_user is TRUE\n already, and there is not much we can do, its just a non-working setup. */\n\n if (!disabled)\n opt_unshare_user = TRUE;\n }\n\n if (argc == 0)\n usage (EXIT_FAILURE, stderr);\n\n __debug__ ((\"Creating root mount point\\n\"));\n\n if (opt_sandbox_uid == -1)\n opt_sandbox_uid = real_uid;\n if (opt_sandbox_gid == -1)\n opt_sandbox_gid = real_gid;\n\n if (!opt_unshare_user && opt_sandbox_uid != real_uid)\n die (\"Specifying --uid requires --unshare-user\");\n\n if (!opt_unshare_user && opt_sandbox_gid != real_gid)\n die (\"Specifying --gid requires --unshare-user\");\n\n if (!opt_unshare_uts && opt_sandbox_hostname != NULL)\n die (\"Specifying --hostname requires --unshare-uts\");\n\n if (opt_as_pid_1 && !opt_unshare_pid)\n die (\"Specifying --as-pid-1 requires --unshare-pid\");\n\n if (opt_as_pid_1 && lock_files != NULL)\n die (\"Specifying --as-pid-1 and --lock-file is not permitted\");\n\n /* We need to read stuff from proc during the pivot_root dance, etc.\n Lets keep a fd to it open */\n proc_fd = open (\"/proc\", O_PATH);\n if (proc_fd == -1)\n die_with_error (\"Can't open /proc\");\n\n /* We need *some* mountpoint where we can mount the root tmpfs.\n We first try in /run, and if that fails, try in /tmp. */\n base_path = xasprintf (\"/run/user/%d/.bubblewrap\", real_uid);\n if (ensure_dir (base_path, 0755))\n {\n free (base_path);\n base_path = xasprintf (\"/tmp/.bubblewrap-%d\", real_uid);\n if (ensure_dir (base_path, 0755))\n die_with_error (\"Creating root mountpoint failed\");\n }\n\n __debug__ ((\"creating new namespace\\n\"));\n\n if (opt_unshare_pid && !opt_as_pid_1)\n {\n event_fd = eventfd (0, EFD_CLOEXEC | EFD_NONBLOCK);\n if (event_fd == -1)\n die_with_error (\"eventfd()\");\n }\n\n /* We block sigchild here so that we can use signalfd in the monitor. */\n block_sigchild ();\n\n clone_flags = SIGCHLD | CLONE_NEWNS;\n if (opt_unshare_user)\n clone_flags |= CLONE_NEWUSER;\n if (opt_unshare_pid)\n clone_flags |= CLONE_NEWPID;\n if (opt_unshare_net)\n clone_flags |= CLONE_NEWNET;\n if (opt_unshare_ipc)\n clone_flags |= CLONE_NEWIPC;\n if (opt_unshare_uts)\n clone_flags |= CLONE_NEWUTS;\n if (opt_unshare_cgroup)\n {\n if (stat (\"/proc/self/ns/cgroup\", &sbuf))\n {\n if (errno == ENOENT)\n die (\"Cannot create new cgroup namespace because the kernel does not support it\");\n else\n die_with_error (\"stat on /proc/self/ns/cgroup failed\");\n }\n clone_flags |= CLONE_NEWCGROUP;\n }\n if (opt_unshare_cgroup_try)\n if (!stat (\"/proc/self/ns/cgroup\", &sbuf))\n clone_flags |= CLONE_NEWCGROUP;\n\n child_wait_fd = eventfd (0, EFD_CLOEXEC);\n if (child_wait_fd == -1)\n die_with_error (\"eventfd()\");\n\n /* Track whether pre-exec setup finished if we're reporting process exit */\n if (opt_json_status_fd != -1)\n {\n int ret;\n ret = pipe2 (setup_finished_pipe, O_CLOEXEC);\n if (ret == -1)\n die_with_error (\"pipe2()\");\n }\n\n pid = raw_clone (clone_flags, NULL);\n if (pid == -1)\n {\n if (opt_unshare_user)\n {\n if (errno == EINVAL)\n die (\"Creating new namespace failed, likely because the kernel does not support user namespaces. bwrap must be installed setuid on such systems.\");\n else if (errno == EPERM && !is_privileged)\n die (\"No permissions to creating new namespace, likely because the kernel does not allow non-privileged user namespaces. On e.g. debian this can be enabled with 'sysctl kernel.unprivileged_userns_clone=1'.\");\n }\n\n die_with_error (\"Creating new namespace failed\");\n }\n\n ns_uid = opt_sandbox_uid;\n ns_gid = opt_sandbox_gid;\n\n if (pid != 0)\n {\n /* Parent, outside sandbox, privileged (initially) */\n\n if (is_privileged && opt_unshare_user && opt_userns_block_fd == -1)\n {\n /* We're running as euid 0, but the uid we want to map is\n * not 0. This means we're not allowed to write this from\n * the child user namespace, so we do it from the parent.\n *\n * Also, we map uid/gid 0 in the namespace (to overflowuid)\n * if opt_needs_devpts is true, because otherwise the mount\n * of devpts fails due to root not being mapped.\n */\n write_uid_gid_map (ns_uid, real_uid,\n ns_gid, real_gid,\n pid, TRUE, opt_needs_devpts);\n }\n\n /* Initial launched process, wait for exec:ed command to exit */\n\n /* We don't need any privileges in the launcher, drop them immediately. */\n drop_privs (FALSE);\n\n /* Optionally bind our lifecycle to that of the parent */\n handle_die_with_parent ();\n\n if (opt_info_fd != -1)\n {\n cleanup_free char *output = xasprintf (\"{\\n \\\"child-pid\\\": %i\\n}\\n\", pid);\n dump_info (opt_info_fd, output, TRUE);\n close (opt_info_fd);\n }\n if (opt_json_status_fd != -1)\n {\n cleanup_free char *output = xasprintf (\"{ \\\"child-pid\\\": %i }\\n\", pid);\n dump_info (opt_json_status_fd, output, TRUE);\n }\n\n if (opt_userns_block_fd != -1)\n {\n char b[1];\n (void) TEMP_FAILURE_RETRY (read (opt_userns_block_fd, b, 1));\n close (opt_userns_block_fd);\n }\n\n /* Let child run now that the uid maps are set up */\n val = 1;\n res = write (child_wait_fd, &val, 8);\n /* Ignore res, if e.g. the child died and closed child_wait_fd we don't want to error out here */\n close (child_wait_fd);\n\n return monitor_child (event_fd, pid, setup_finished_pipe[0]);\n }\n\n /* Child, in sandbox, privileged in the parent or in the user namespace (if --unshare-user).\n *\n * Note that for user namespaces we run as euid 0 during clone(), so\n * the child user namespace is owned by euid 0., This means that the\n * regular user namespace parent (with uid != 0) doesn't have any\n * capabilities in it, which is nice as we can't exploit those. In\n * particular the parent user namespace doesn't have CAP_PTRACE\n * which would otherwise allow the parent to hijack of the child\n * after this point.\n *\n * Unfortunately this also means you can't ptrace the final\n * sandboxed process from outside the sandbox either.\n */\n\n if (opt_info_fd != -1)\n close (opt_info_fd);\n\n if (opt_json_status_fd != -1)\n close (opt_json_status_fd);\n\n /* Wait for the parent to init uid/gid maps and drop caps */\n res = read (child_wait_fd, &val, 8);\n close (child_wait_fd);\n\n /* At this point we can completely drop root uid, but retain the\n * required permitted caps. This allow us to do full setup as\n * the user uid, which makes e.g. fuse access work.\n */\n switch_to_user_with_privs ();\n\n if (opt_unshare_net)\n loopback_setup (); /* Will exit if unsuccessful */\n\n ns_uid = opt_sandbox_uid;\n ns_gid = opt_sandbox_gid;\n if (!is_privileged && opt_unshare_user && opt_userns_block_fd == -1)\n {\n /* In the unprivileged case we have to write the uid/gid maps in\n * the child, because we have no caps in the parent */\n\n if (opt_needs_devpts)\n {\n /* This is a bit hacky, but we need to first map the real uid/gid to\n 0, otherwise we can't mount the devpts filesystem because root is\n not mapped. Later we will create another child user namespace and\n map back to the real uid */\n ns_uid = 0;\n ns_gid = 0;\n }\n\n write_uid_gid_map (ns_uid, real_uid,\n ns_gid, real_gid,\n -1, TRUE, FALSE);\n }\n\n old_umask = umask (0);\n\n /* Need to do this before the chroot, but after we're the real uid */\n resolve_symlinks_in_ops ();\n\n /* Mark everything as slave, so that we still\n * receive mounts from the real root, but don't\n * propagate mounts to the real root. */\n if (mount (NULL, \"/\", NULL, MS_SLAVE | MS_REC, NULL) < 0)\n die_with_error (\"Failed to make / slave\");\n\n /* Create a tmpfs which we will use as / in the namespace */\n if (mount (\"tmpfs\", base_path, \"tmpfs\", MS_NODEV | MS_NOSUID, NULL) != 0)\n die_with_error (\"Failed to mount tmpfs\");\n\n old_cwd = get_current_dir_name ();\n\n /* Chdir to the new root tmpfs mount. This will be the CWD during\n the entire setup. Access old or new root via \"oldroot\" and \"newroot\". */\n if (chdir (base_path) != 0)\n die_with_error (\"chdir base_path\");\n\n /* We create a subdir \"$base_path/newroot\" for the new root, that\n * way we can pivot_root to base_path, and put the old root at\n * \"$base_path/oldroot\". This avoids problems accessing the oldroot\n * dir if the user requested to bind mount something over / */\n\n if (mkdir (\"newroot\", 0755))\n die_with_error (\"Creating newroot failed\");\n\n if (mount (\"newroot\", \"newroot\", NULL, MS_MGC_VAL | MS_BIND | MS_REC, NULL) < 0)\n die_with_error (\"setting up newroot bind\");\n\n if (mkdir (\"oldroot\", 0755))\n die_with_error (\"Creating oldroot failed\");\n\n if (pivot_root (base_path, \"oldroot\"))\n die_with_error (\"pivot_root\");\n\n if (chdir (\"/\") != 0)\n die_with_error (\"chdir / (base path)\");\n\n if (is_privileged)\n {\n pid_t child;\n int privsep_sockets[2];\n\n if (socketpair (AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, privsep_sockets) != 0)\n die_with_error (\"Can't create privsep socket\");\n\n child = fork ();\n if (child == -1)\n die_with_error (\"Can't fork unprivileged helper\");\n\n if (child == 0)\n {\n /* Unprivileged setup process */\n drop_privs (FALSE);\n close (privsep_sockets[0]);\n setup_newroot (opt_unshare_pid, privsep_sockets[1]);\n exit (0);\n }\n else\n {\n int status;\n uint32_t buffer[2048]; /* 8k, but is int32 to guarantee nice alignment */\n uint32_t op, flags;\n const char *arg1, *arg2;\n cleanup_fd int unpriv_socket = -1;\n\n unpriv_socket = privsep_sockets[0];\n close (privsep_sockets[1]);\n\n do\n {\n op = read_priv_sec_op (unpriv_socket, buffer, sizeof (buffer),\n &flags, &arg1, &arg2);\n privileged_op (-1, op, flags, arg1, arg2);\n if (write (unpriv_socket, buffer, 1) != 1)\n die (\"Can't write to op_socket\");\n }\n while (op != PRIV_SEP_OP_DONE);\n\n waitpid (child, &status, 0);\n /* Continue post setup */\n }\n }\n else\n {\n setup_newroot (opt_unshare_pid, -1);\n }\n\n close_ops_fd ();\n\n /* The old root better be rprivate or we will send unmount events to the parent namespace */\n if (mount (\"oldroot\", \"oldroot\", NULL, MS_REC | MS_PRIVATE, NULL) != 0)\n die_with_error (\"Failed to make old root rprivate\");\n\n if (umount2 (\"oldroot\", MNT_DETACH))\n die_with_error (\"unmount old root\");\n\n /* This is our second pivot. It's like we're a Silicon Valley startup flush\n * with cash but short on ideas!\n *\n * We're aiming to make /newroot the real root, and get rid of /oldroot. To do\n * that we need a temporary place to store it before we can unmount it.\n */\n { cleanup_fd int oldrootfd = open (\"/\", O_DIRECTORY | O_RDONLY);\n if (oldrootfd < 0)\n die_with_error (\"can't open /\");\n if (chdir (\"/newroot\") != 0)\n die_with_error (\"chdir /newroot\");\n /* While the documentation claims that put_old must be underneath\n * new_root, it is perfectly fine to use the same directory as the\n * kernel checks only if old_root is accessible from new_root.\n *\n * Both runc and LXC are using this \"alternative\" method for\n * setting up the root of the container:\n *\n * https://github.com/opencontainers/runc/blob/master/libcontainer/rootfs_linux.go#L671\n * https://github.com/lxc/lxc/blob/master/src/lxc/conf.c#L1121\n */\n if (pivot_root (\".\", \".\") != 0)\n die_with_error (\"pivot_root(/newroot)\");\n if (fchdir (oldrootfd) < 0)\n die_with_error (\"fchdir to oldroot\");\n if (umount2 (\".\", MNT_DETACH) < 0)\n die_with_error (\"umount old root\");\n if (chdir (\"/\") != 0)\n die_with_error (\"chdir /\");\n }\n\n if (opt_unshare_user &&\n (ns_uid != opt_sandbox_uid || ns_gid != opt_sandbox_gid) &&\n opt_userns_block_fd == -1)\n {\n /* Now that devpts is mounted and we've no need for mount\n permissions we can create a new userspace and map our uid\n 1:1 */\n\n if (unshare (CLONE_NEWUSER))\n die_with_error (\"unshare user ns\");\n\n write_uid_gid_map (opt_sandbox_uid, ns_uid,\n opt_sandbox_gid, ns_gid,\n -1, FALSE, FALSE);\n }\n\n /* All privileged ops are done now, so drop caps we don't need */\n drop_privs (!is_privileged);\n\n if (opt_block_fd != -1)\n {\n char b[1];\n (void) TEMP_FAILURE_RETRY (read (opt_block_fd, b, 1));\n close (opt_block_fd);\n }\n\n if (opt_seccomp_fd != -1)\n {\n seccomp_data = load_file_data (opt_seccomp_fd, &seccomp_len);\n if (seccomp_data == NULL)\n die_with_error (\"Can't read seccomp data\");\n\n if (seccomp_len % 8 != 0)\n die (\"Invalid seccomp data, must be multiple of 8\");\n\n seccomp_prog.len = seccomp_len / 8;\n seccomp_prog.filter = (struct sock_filter *) seccomp_data;\n\n close (opt_seccomp_fd);\n }\n\n umask (old_umask);\n\n new_cwd = \"/\";\n if (opt_chdir_path)\n {\n if (chdir (opt_chdir_path))\n die_with_error (\"Can't chdir to %s\", opt_chdir_path);\n new_cwd = opt_chdir_path;\n }\n else if (chdir (old_cwd) == 0)\n {\n /* If the old cwd is mapped in the sandbox, go there */\n new_cwd = old_cwd;\n }\n else\n {\n /* If the old cwd is not mapped, go to home */\n const char *home = getenv (\"HOME\");\n if (home != NULL &&\n chdir (home) == 0)\n new_cwd = home;\n }\n xsetenv (\"PWD\", new_cwd, 1);\n free (old_cwd);\n\n if (opt_new_session &&\n setsid () == (pid_t) -1)\n die_with_error (\"setsid\");\n\n if (label_exec (opt_exec_label) == -1)\n die_with_error (\"label_exec %s\", argv[0]);\n\n __debug__ ((\"forking for child\\n\"));\n\n if (!opt_as_pid_1 && (opt_unshare_pid || lock_files != NULL || opt_sync_fd != -1))\n {\n /* We have to have a pid 1 in the pid namespace, because\n * otherwise we'll get a bunch of zombies as nothing reaps\n * them. Alternatively if we're using sync_fd or lock_files we\n * need some process to own these.\n */\n\n pid = fork ();\n if (pid == -1)\n die_with_error (\"Can't fork for pid 1\");\n\n if (pid != 0)\n {\n drop_all_caps (FALSE);\n\n /* Close fds in pid 1, except stdio and optionally event_fd\n (for syncing pid 2 lifetime with monitor_child) and\n opt_sync_fd (for syncing sandbox lifetime with outside\n process).\n Any other fds will been passed on to the child though. */\n {\n int dont_close[3];\n int j = 0;\n if (event_fd != -1)\n dont_close[j++] = event_fd;\n if (opt_sync_fd != -1)\n dont_close[j++] = opt_sync_fd;\n dont_close[j++] = -1;\n fdwalk (proc_fd, close_extra_fds, dont_close);\n }\n\n return do_init (event_fd, pid, seccomp_data != NULL ? &seccomp_prog : NULL);\n }\n }\n\n __debug__ ((\"launch executable %s\\n\", argv[0]));\n\n if (proc_fd != -1)\n close (proc_fd);\n\n /* If we are using --as-pid-1 leak the sync fd into the sandbox.\n --sync-fd will still work unless the container process doesn't close this file. */\n if (!opt_as_pid_1)\n {\n if (opt_sync_fd != -1)\n close (opt_sync_fd);\n }\n\n /* We want sigchild in the child */\n unblock_sigchild ();\n\n /* Optionally bind our lifecycle */\n handle_die_with_parent ();\n\n if (!is_privileged)\n set_ambient_capabilities ();\n\n /* Should be the last thing before execve() so that filters don't\n * need to handle anything above */\n if (seccomp_data != NULL &&\n prctl (PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &seccomp_prog) != 0)\n die_with_error (\"prctl(PR_SET_SECCOMP)\");\n\n if (setup_finished_pipe[1] != -1)\n {\n char data = 0;\n res = write_to_fd (setup_finished_pipe[1], &data, 1);\n /* Ignore res, if e.g. the parent died and closed setup_finished_pipe[0]\n we don't want to error out here */\n }\n\n if (execvp (argv[0], argv) == -1)\n {\n if (setup_finished_pipe[1] != -1)\n {\n int saved_errno = errno;\n char data = 0;\n res = write_to_fd (setup_finished_pipe[1], &data, 1);\n errno = saved_errno;\n /* Ignore res, if e.g. the parent died and closed setup_finished_pipe[0]\n we don't want to error out here */\n }\n die_with_error (\"execvp %s\", argv[0]);\n }\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-269'], 'message': 'Don't create our own temporary mount point for pivot_root\n\nAn attacker could pre-create /tmp/.bubblewrap-$UID and make it a\nnon-directory, non-symlink (in which case mounting our tmpfs would fail,\ncausing denial of service), or make it a symlink under their control\n(potentially allowing bad things if the protected_symlinks sysctl is\nnot enabled).\n\nInstead, temporarily mount the tmpfs on a directory that we are sure\nexists and is not attacker-controlled. /tmp (the directory itself, not\na subdirectory) will do.\n\nFixes: #304\nBug-Debian: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=923557\nSigned-off-by: Simon McVittie \n\nCloses: #305\nApproved by: cgwalters'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: find_lively_task_by_vpid(pid_t vpid)\n{\n\tstruct task_struct *task;\n\tint err;\n\n\trcu_read_lock();\n\tif (!vpid)\n\t\ttask = current;\n\telse\n\t\ttask = find_task_by_vpid(vpid);\n\tif (task)\n\t\tget_task_struct(task);\n\trcu_read_unlock();\n\n\tif (!task)\n\t\treturn ERR_PTR(-ESRCH);\n\n\t/* Reuse ptrace permission checks for now. */\n\terr = -EACCES;\n\tif (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))\n\t\tgoto errout;\n\n\treturn task;\nerrout:\n\tput_task_struct(task);\n\treturn ERR_PTR(err);\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-667'], 'message': 'perf/core: Fix perf_event_open() vs. execve() race\n\nJann reported that the ptrace_may_access() check in\nfind_lively_task_by_vpid() is racy against exec().\n\nSpecifically:\n\n perf_event_open()\t\texecve()\n\n ptrace_may_access()\n\t\t\t\tcommit_creds()\n ...\t\t\t\tif (get_dumpable() != SUID_DUMP_USER)\n\t\t\t\t perf_event_exit_task();\n perf_install_in_context()\n\nwould result in installing a counter across the creds boundary.\n\nFix this by wrapping lots of perf_event_open() in cred_guard_mutex.\nThis should be fine as perf_event_exit_task() is already called with\ncred_guard_mutex held, so all perf locks already nest inside it.\n\nReported-by: Jann Horn \nSigned-off-by: Peter Zijlstra (Intel) \nCc: Alexander Shishkin \nCc: Arnaldo Carvalho de Melo \nCc: Jiri Olsa \nCc: Peter Zijlstra \nCc: Stephane Eranian \nCc: Thomas Gleixner \nCc: Vince Weaver \nSigned-off-by: Ingo Molnar '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void exif_process_CME (image_info_type *image_info, char *value, size_t length)\n{\n\tif (length>3) {\n\t\tswitch(value[2]) {\n\t\t\tcase 0:\n\t\t\t\texif_iif_add_tag(image_info, SECTION_COMMENT, \"Comment\", TAG_COMPUTED_VALUE, TAG_FMT_UNDEFINED, length, value);\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\texif_iif_add_tag(image_info, SECTION_COMMENT, \"Comment\", TAG_COMPUTED_VALUE, TAG_FMT_STRING, length, value);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tphp_error_docref(NULL, E_NOTICE, \"Undefined JPEG2000 comment encoding\");\n\t\t\t\tbreak;\n\t\t}\n\t} else {\n\t\texif_iif_add_tag(image_info, SECTION_COMMENT, \"Comment\", TAG_COMPUTED_VALUE, TAG_FMT_UNDEFINED, 0, NULL);\n\t\tphp_error_docref(NULL, E_NOTICE, \"JPEG2000 comment section too small\");\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed bug #77831 - Heap-buffer-overflow in exif_iif_add_value in EXIF'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void setup_private_mount(const char *snap_name)\n{\n\tuid_t uid = getuid();\n\tgid_t gid = getgid();\n\tchar tmpdir[MAX_BUF] = { 0 };\n\n\t// Create a 0700 base directory, this is the base dir that is\n\t// protected from other users.\n\t//\n\t// Under that basedir, we put a 1777 /tmp dir that is then bind\n\t// mounted for the applications to use\n\tsc_must_snprintf(tmpdir, sizeof(tmpdir), \"/tmp/snap.%s_XXXXXX\", snap_name);\n\tif (mkdtemp(tmpdir) == NULL) {\n\t\tdie(\"cannot create temporary directory essential for private /tmp\");\n\t}\n\t// now we create a 1777 /tmp inside our private dir\n\tmode_t old_mask = umask(0);\n\tchar *d = sc_strdup(tmpdir);\n\tsc_must_snprintf(tmpdir, sizeof(tmpdir), \"%s/tmp\", d);\n\tfree(d);\n\n\tif (mkdir(tmpdir, 01777) != 0) {\n\t\tdie(\"cannot create temporary directory for private /tmp\");\n\t}\n\tumask(old_mask);\n\n\t// chdir to '/' since the mount won't apply to the current directory\n\tchar *pwd = get_current_dir_name();\n\tif (pwd == NULL)\n\t\tdie(\"cannot get current working directory\");\n\tif (chdir(\"/\") != 0)\n\t\tdie(\"cannot change directory to '/'\");\n\n\t// MS_BIND is there from linux 2.4\n\tsc_do_mount(tmpdir, \"/tmp\", NULL, MS_BIND, NULL);\n\t// MS_PRIVATE needs linux > 2.6.11\n\tsc_do_mount(\"none\", \"/tmp\", NULL, MS_PRIVATE, NULL);\n\t// do the chown after the bind mount to avoid potential shenanigans\n\tif (chown(\"/tmp/\", uid, gid) < 0) {\n\t\tdie(\"cannot change ownership of /tmp\");\n\t}\n\t// chdir to original directory\n\tif (chdir(pwd) != 0)\n\t\tdie(\"cannot change current working directory to the original directory\");\n\tfree(pwd);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59', 'CWE-703'], 'message': 'cmd/snap-confine: chown private /tmp parent to root.root\n\nWhen snap-confine creates a private /tmp directory for a given snap it\nfirst creates a temporary directory in /tmp/ named after the snap, along\nwith a random name. Inside that directory it creates a /tmp directory\nwith permissions appropriate for a future /tmp, namely 1777.\n\nUp until recently the that directory was owned by the user who first\ninvoked snap-confine. Since the directory is reused by all the users on\nthe system this logic makes no sense.\n\nThis patch changes the related logic so that the private /tmp directory\nis owned by root, just like the real one.\n\nSigned-off-by: Zygmunt Krynicki '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: find_extend_vma(struct mm_struct *mm, unsigned long addr)\n{\n\tstruct vm_area_struct *vma;\n\tunsigned long start;\n\n\taddr &= PAGE_MASK;\n\tvma = find_vma(mm, addr);\n\tif (!vma)\n\t\treturn NULL;\n\tif (vma->vm_start <= addr)\n\t\treturn vma;\n\tif (!(vma->vm_flags & VM_GROWSDOWN))\n\t\treturn NULL;\n\tstart = vma->vm_start;\n\tif (expand_stack(vma, addr))\n\t\treturn NULL;\n\tif (vma->vm_flags & VM_LOCKED)\n\t\tpopulate_vma_page_range(vma, addr, start, NULL);\n\treturn vma;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362', 'CWE-703', 'CWE-667'], 'message': 'coredump: fix race condition between mmget_not_zero()/get_task_mm() and core dumping\n\nThe core dumping code has always run without holding the mmap_sem for\nwriting, despite that is the only way to ensure that the entire vma\nlayout will not change from under it. Only using some signal\nserialization on the processes belonging to the mm is not nearly enough.\nThis was pointed out earlier. For example in Hugh's post from Jul 2017:\n\n https://lkml.kernel.org/r/alpine.LSU.2.11.1707191716030.2055@eggly.anvils\n\n \"Not strictly relevant here, but a related note: I was very surprised\n to discover, only quite recently, how handle_mm_fault() may be called\n without down_read(mmap_sem) - when core dumping. That seems a\n misguided optimization to me, which would also be nice to correct\"\n\nIn particular because the growsdown and growsup can move the\nvm_start/vm_end the various loops the core dump does around the vma will\nnot be consistent if page faults can happen concurrently.\n\nPretty much all users calling mmget_not_zero()/get_task_mm() and then\ntaking the mmap_sem had the potential to introduce unexpected side\neffects in the core dumping code.\n\nAdding mmap_sem for writing around the ->core_dump invocation is a\nviable long term fix, but it requires removing all copy user and page\nfaults and to replace them with get_dump_page() for all binary formats\nwhich is not suitable as a short term fix.\n\nFor the time being this solution manually covers the places that can\nconfuse the core dump either by altering the vma layout or the vma flags\nwhile it runs. Once ->core_dump runs under mmap_sem for writing the\nfunction mmget_still_valid() can be dropped.\n\nAllowing mmap_sem protected sections to run in parallel with the\ncoredump provides some minor parallelism advantage to the swapoff code\n(which seems to be safe enough by never mangling any vma field and can\nkeep doing swapins in parallel to the core dumping) and to some other\ncorner case.\n\nIn order to facilitate the backporting I added \"Fixes: 86039bd3b4e6\"\nhowever the side effect of this same race condition in /proc/pid/mem\nshould be reproducible since before 2.6.12-rc2 so I couldn't add any\nother \"Fixes:\" because there's no hash beyond the git genesis commit.\n\nBecause find_extend_vma() is the only location outside of the process\ncontext that could modify the \"mm\" structures under mmap_sem for\nreading, by adding the mmget_still_valid() check to it, all other cases\nthat take the mmap_sem for reading don't need the new check after\nmmget_not_zero()/get_task_mm(). The expand_stack() in page fault\ncontext also doesn't need the new check, because all tasks under core\ndumping are frozen.\n\nLink: http://lkml.kernel.org/r/20190325224949.11068-1-aarcange@redhat.com\nFixes: 86039bd3b4e6 (\"userfaultfd: add new syscall to provide memory externalization\")\nSigned-off-by: Andrea Arcangeli \nReported-by: Jann Horn \nSuggested-by: Oleg Nesterov \nAcked-by: Peter Xu \nReviewed-by: Mike Rapoport \nReviewed-by: Oleg Nesterov \nReviewed-by: Jann Horn \nAcked-by: Jason Gunthorpe \nAcked-by: Michal Hocko \nCc: \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadXWDImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n#define CheckOverflowException(length,width,height) \\\n (((height) != 0) && ((length)/((size_t) height) != ((size_t) width)))\n\n char\n *comment;\n\n Image\n *image;\n\n IndexPacket\n index;\n\n int\n x_status;\n\n MagickBooleanType\n authentic_colormap;\n\n MagickStatusType\n status;\n\n register IndexPacket\n *indexes;\n\n register ssize_t\n x;\n\n register PixelPacket\n *q;\n\n register ssize_t\n i;\n\n register size_t\n pixel;\n\n size_t\n length;\n\n ssize_t\n count,\n y;\n\n unsigned long\n lsb_first;\n\n XColor\n *colors;\n\n XImage\n *ximage;\n\n XWDFileHeader\n header;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Read in header information.\n */\n count=ReadBlob(image,sz_XWDheader,(unsigned char *) &header);\n if (count != sz_XWDheader)\n ThrowReaderException(CorruptImageError,\"UnableToReadImageHeader\");\n /*\n Ensure the header byte-order is most-significant byte first.\n */\n lsb_first=1;\n if ((int) (*(char *) &lsb_first) != 0)\n MSBOrderLong((unsigned char *) &header,sz_XWDheader);\n /*\n Check to see if the dump file is in the proper format.\n */\n if (header.file_version != XWD_FILE_VERSION)\n ThrowReaderException(CorruptImageError,\"FileFormatVersionMismatch\");\n if (header.header_size < sz_XWDheader)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if ((header.bits_per_pixel == 0) || (header.bits_per_pixel > 32))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (((header.bitmap_pad % 8) != 0) || (header.bitmap_pad > 32))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (header.bitmap_unit > 32)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (header.ncolors > 256)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n switch (header.visual_class)\n {\n case StaticGray:\n case GrayScale:\n case StaticColor:\n case PseudoColor:\n case TrueColor:\n case DirectColor:\n break;\n default:\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n switch (header.pixmap_format)\n {\n case XYBitmap:\n case XYPixmap:\n case ZPixmap:\n break;\n default:\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n length=(size_t) (header.header_size-sz_XWDheader);\n if ((length+1) != ((size_t) ((CARD32) (length+1))))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n comment=(char *) AcquireQuantumMemory(length+1,sizeof(*comment));\n if (comment == (char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n count=ReadBlob(image,length,(unsigned char *) comment);\n comment[length]='\\0';\n (void) SetImageProperty(image,\"comment\",comment);\n comment=DestroyString(comment);\n if (count != (ssize_t) length)\n ThrowReaderException(CorruptImageError,\"UnexpectedEndOfFile\");\n /*\n Initialize the X image.\n */\n ximage=(XImage *) AcquireMagickMemory(sizeof(*ximage));\n if (ximage == (XImage *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n ximage->depth=(int) header.pixmap_depth;\n ximage->format=(int) header.pixmap_format;\n ximage->xoffset=(int) header.xoffset;\n ximage->data=(char *) NULL;\n ximage->width=(int) header.pixmap_width;\n ximage->height=(int) header.pixmap_height;\n ximage->bitmap_pad=(int) header.bitmap_pad;\n ximage->bytes_per_line=(int) header.bytes_per_line;\n ximage->byte_order=(int) header.byte_order;\n ximage->bitmap_unit=(int) header.bitmap_unit;\n ximage->bitmap_bit_order=(int) header.bitmap_bit_order;\n ximage->bits_per_pixel=(int) header.bits_per_pixel;\n ximage->red_mask=header.red_mask;\n ximage->green_mask=header.green_mask;\n ximage->blue_mask=header.blue_mask;\n if ((ximage->width < 0) || (ximage->height < 0) || (ximage->depth < 0) || \n (ximage->format < 0) || (ximage->byte_order < 0) ||\n (ximage->bitmap_bit_order < 0) || (ximage->bitmap_pad < 0) ||\n (ximage->bytes_per_line < 0))\n {\n ximage=(XImage *) RelinquishMagickMemory(ximage);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n if ((ximage->width > 65535) || (ximage->height > 65535))\n {\n ximage=(XImage *) RelinquishMagickMemory(ximage);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n if ((ximage->bits_per_pixel > 32) || (ximage->bitmap_unit > 32))\n {\n ximage=(XImage *) RelinquishMagickMemory(ximage);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n x_status=XInitImage(ximage);\n if (x_status == 0)\n {\n ximage=(XImage *) RelinquishMagickMemory(ximage);\n ThrowReaderException(CorruptImageError,\"UnexpectedEndOfFile\");\n }\n /*\n Read colormap.\n */\n authentic_colormap=MagickFalse;\n colors=(XColor *) NULL;\n if (header.ncolors != 0)\n {\n XWDColor\n color;\n\n length=(size_t) header.ncolors;\n if (length > ((~0UL)/sizeof(*colors)))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n colors=(XColor *) AcquireQuantumMemory(length,sizeof(*colors));\n if (colors == (XColor *) NULL)\n {\n ximage=(XImage *) RelinquishMagickMemory(ximage);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n for (i=0; i < (ssize_t) header.ncolors; i++)\n {\n count=ReadBlob(image,sz_XWDColor,(unsigned char *) &color);\n if (count != sz_XWDColor)\n {\n colors=(XColor *) RelinquishMagickMemory(colors);\n ximage=(XImage *) RelinquishMagickMemory(ximage);\n ThrowReaderException(CorruptImageError,\"UnexpectedEndOfFile\");\n }\n colors[i].pixel=color.pixel;\n colors[i].red=color.red;\n colors[i].green=color.green;\n colors[i].blue=color.blue;\n colors[i].flags=(char) color.flags;\n if (color.flags != 0)\n authentic_colormap=MagickTrue;\n }\n /*\n Ensure the header byte-order is most-significant byte first.\n */\n lsb_first=1;\n if ((int) (*(char *) &lsb_first) != 0)\n for (i=0; i < (ssize_t) header.ncolors; i++)\n {\n MSBOrderLong((unsigned char *) &colors[i].pixel,\n sizeof(colors[i].pixel));\n MSBOrderShort((unsigned char *) &colors[i].red,3*\n sizeof(colors[i].red));\n }\n }\n /*\n Allocate the pixel buffer.\n */\n length=(size_t) ximage->bytes_per_line*ximage->height;\n if (CheckOverflowException(length,ximage->bytes_per_line,ximage->height))\n {\n if (header.ncolors != 0)\n colors=(XColor *) RelinquishMagickMemory(colors);\n ximage=(XImage *) RelinquishMagickMemory(ximage);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n if (ximage->format != ZPixmap)\n {\n size_t\n extent;\n\n extent=length;\n length*=ximage->depth;\n if (CheckOverflowException(length,extent,ximage->depth))\n {\n if (header.ncolors != 0)\n colors=(XColor *) RelinquishMagickMemory(colors);\n ximage=(XImage *) RelinquishMagickMemory(ximage);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n }\n ximage->data=(char *) AcquireQuantumMemory(length,sizeof(*ximage->data));\n if (ximage->data == (char *) NULL)\n {\n if (header.ncolors != 0)\n colors=(XColor *) RelinquishMagickMemory(colors);\n ximage=(XImage *) RelinquishMagickMemory(ximage);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n count=ReadBlob(image,length,(unsigned char *) ximage->data);\n if (count != (ssize_t) length)\n {\n if (header.ncolors != 0)\n colors=(XColor *) RelinquishMagickMemory(colors);\n ximage->data=DestroyString(ximage->data);\n ximage=(XImage *) RelinquishMagickMemory(ximage);\n ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");\n }\n /*\n Convert image to MIFF format.\n */\n image->columns=(size_t) ximage->width;\n image->rows=(size_t) ximage->height;\n image->depth=8;\n status=SetImageExtent(image,image->columns,image->rows);\n if (status == MagickFalse)\n {\n if (header.ncolors != 0)\n colors=(XColor *) RelinquishMagickMemory(colors);\n ximage->data=DestroyString(ximage->data);\n ximage=(XImage *) RelinquishMagickMemory(ximage);\n InheritException(exception,&image->exception);\n return(DestroyImageList(image));\n }\n if ((header.ncolors == 0U) || (ximage->red_mask != 0) ||\n (ximage->green_mask != 0) || (ximage->blue_mask != 0))\n image->storage_class=DirectClass;\n else\n image->storage_class=PseudoClass;\n image->colors=header.ncolors;\n if (image_info->ping == MagickFalse)\n switch (image->storage_class)\n {\n case DirectClass:\n default:\n {\n register size_t\n color;\n\n size_t\n blue_mask,\n blue_shift,\n green_mask,\n green_shift,\n red_mask,\n red_shift;\n\n /*\n Determine shift and mask for red, green, and blue.\n */\n red_mask=ximage->red_mask;\n red_shift=0;\n while ((red_mask != 0) && ((red_mask & 0x01) == 0))\n {\n red_mask>>=1;\n red_shift++;\n }\n green_mask=ximage->green_mask;\n green_shift=0;\n while ((green_mask != 0) && ((green_mask & 0x01) == 0))\n {\n green_mask>>=1;\n green_shift++;\n }\n blue_mask=ximage->blue_mask;\n blue_shift=0;\n while ((blue_mask != 0) && ((blue_mask & 0x01) == 0))\n {\n blue_mask>>=1;\n blue_shift++;\n }\n /*\n Convert X image to DirectClass packets.\n */\n if ((image->colors != 0) && (authentic_colormap != MagickFalse))\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=XGetPixel(ximage,(int) x,(int) y);\n index=ConstrainColormapIndex(image,(ssize_t) (pixel >>\n red_shift) & red_mask);\n SetPixelRed(q,ScaleShortToQuantum(colors[(ssize_t) index].red));\n index=ConstrainColormapIndex(image,(ssize_t) (pixel >>\n green_shift) & green_mask);\n SetPixelGreen(q,ScaleShortToQuantum(colors[(ssize_t)\n index].green));\n index=ConstrainColormapIndex(image,(ssize_t) (pixel >>\n blue_shift) & blue_mask);\n SetPixelBlue(q,ScaleShortToQuantum(colors[(ssize_t) index].blue));\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n else\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=XGetPixel(ximage,(int) x,(int) y);\n color=(pixel >> red_shift) & red_mask;\n if (red_mask != 0)\n color=(color*65535UL)/red_mask;\n SetPixelRed(q,ScaleShortToQuantum((unsigned short) color));\n color=(pixel >> green_shift) & green_mask;\n if (green_mask != 0)\n color=(color*65535UL)/green_mask;\n SetPixelGreen(q,ScaleShortToQuantum((unsigned short) color));\n color=(pixel >> blue_shift) & blue_mask;\n if (blue_mask != 0)\n color=(color*65535UL)/blue_mask;\n SetPixelBlue(q,ScaleShortToQuantum((unsigned short) color));\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n break;\n }\n case PseudoClass:\n {\n /*\n Convert X image to PseudoClass packets.\n */\n if (AcquireImageColormap(image,image->colors) == MagickFalse)\n {\n if (header.ncolors != 0)\n colors=(XColor *) RelinquishMagickMemory(colors);\n ximage->data=DestroyString(ximage->data);\n ximage=(XImage *) RelinquishMagickMemory(ximage);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n image->colormap[i].red=ScaleShortToQuantum(colors[i].red);\n image->colormap[i].green=ScaleShortToQuantum(colors[i].green);\n image->colormap[i].blue=ScaleShortToQuantum(colors[i].blue);\n }\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n indexes=GetAuthenticIndexQueue(image);\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n index=ConstrainColormapIndex(image,(ssize_t) XGetPixel(ximage,(int)\n x,(int) y));\n SetPixelIndex(indexes+x,index);\n SetPixelRGBO(q,image->colormap+(ssize_t) index);\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n break;\n }\n }\n /*\n Free image and colormap.\n */\n if (header.ncolors != 0)\n colors=(XColor *) RelinquishMagickMemory(colors);\n ximage->data=DestroyString(ximage->data);\n ximage=(XImage *) RelinquishMagickMemory(ximage);\n if (EOFBlob(image) != MagickFalse)\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-369'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1546'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void rds_tcp_kill_sock(struct net *net)\n{\n\tstruct rds_tcp_connection *tc, *_tc;\n\tLIST_HEAD(tmp_list);\n\tstruct rds_tcp_net *rtn = net_generic(net, rds_tcp_netid);\n\tstruct socket *lsock = rtn->rds_tcp_listen_sock;\n\n\trtn->rds_tcp_listen_sock = NULL;\n\trds_tcp_listen_stop(lsock, &rtn->rds_tcp_accept_w);\n\tspin_lock_irq(&rds_tcp_conn_lock);\n\tlist_for_each_entry_safe(tc, _tc, &rds_tcp_conn_list, t_tcp_node) {\n\t\tstruct net *c_net = read_pnet(&tc->t_cpath->cp_conn->c_net);\n\n\t\tif (net != c_net || !tc->t_sock)\n\t\t\tcontinue;\n\t\tif (!list_has_conn(&tmp_list, tc->t_cpath->cp_conn)) {\n\t\t\tlist_move_tail(&tc->t_tcp_node, &tmp_list);\n\t\t} else {\n\t\t\tlist_del(&tc->t_tcp_node);\n\t\t\ttc->t_tcp_node_detached = true;\n\t\t}\n\t}\n\tspin_unlock_irq(&rds_tcp_conn_lock);\n\tlist_for_each_entry_safe(tc, _tc, &tmp_list, t_tcp_node)\n\t\trds_conn_destroy(tc->t_cpath->cp_conn);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-362'], 'message': 'net: rds: force to destroy connection if t_sock is NULL in rds_tcp_kill_sock().\n\nWhen it is to cleanup net namespace, rds_tcp_exit_net() will call\nrds_tcp_kill_sock(), if t_sock is NULL, it will not call\nrds_conn_destroy(), rds_conn_path_destroy() and rds_tcp_conn_free() to free\nconnection, and the worker cp_conn_w is not stopped, afterwards the net is freed in\nnet_drop_ns(); While cp_conn_w rds_connect_worker() will call rds_tcp_conn_path_connect()\nand reference 'net' which has already been freed.\n\nIn rds_tcp_conn_path_connect(), rds_tcp_set_callbacks() will set t_sock = sock before\nsock->ops->connect, but if connect() is failed, it will call\nrds_tcp_restore_callbacks() and set t_sock = NULL, if connect is always\nfailed, rds_connect_worker() will try to reconnect all the time, so\nrds_tcp_kill_sock() will never to cancel worker cp_conn_w and free the\nconnections.\n\nTherefore, the condition !tc->t_sock is not needed if it is going to do\ncleanup_net->rds_tcp_exit_net->rds_tcp_kill_sock, because tc->t_sock is always\nNULL, and there is on other path to cancel cp_conn_w and free\nconnection. So this patch is to fix this.\n\nrds_tcp_kill_sock():\n...\nif (net != c_net || !tc->t_sock)\n...\nAcked-by: Santosh Shilimkar \n\n==================================================================\nBUG: KASAN: use-after-free in inet_create+0xbcc/0xd28\nnet/ipv4/af_inet.c:340\nRead of size 4 at addr ffff8003496a4684 by task kworker/u8:4/3721\n\nCPU: 3 PID: 3721 Comm: kworker/u8:4 Not tainted 5.1.0 #11\nHardware name: linux,dummy-virt (DT)\nWorkqueue: krdsd rds_connect_worker\nCall trace:\n dump_backtrace+0x0/0x3c0 arch/arm64/kernel/time.c:53\n show_stack+0x28/0x38 arch/arm64/kernel/traps.c:152\n __dump_stack lib/dump_stack.c:77 [inline]\n dump_stack+0x120/0x188 lib/dump_stack.c:113\n print_address_description+0x68/0x278 mm/kasan/report.c:253\n kasan_report_error mm/kasan/report.c:351 [inline]\n kasan_report+0x21c/0x348 mm/kasan/report.c:409\n __asan_report_load4_noabort+0x30/0x40 mm/kasan/report.c:429\n inet_create+0xbcc/0xd28 net/ipv4/af_inet.c:340\n __sock_create+0x4f8/0x770 net/socket.c:1276\n sock_create_kern+0x50/0x68 net/socket.c:1322\n rds_tcp_conn_path_connect+0x2b4/0x690 net/rds/tcp_connect.c:114\n rds_connect_worker+0x108/0x1d0 net/rds/threads.c:175\n process_one_work+0x6e8/0x1700 kernel/workqueue.c:2153\n worker_thread+0x3b0/0xdd0 kernel/workqueue.c:2296\n kthread+0x2f0/0x378 kernel/kthread.c:255\n ret_from_fork+0x10/0x18 arch/arm64/kernel/entry.S:1117\n\nAllocated by task 687:\n save_stack mm/kasan/kasan.c:448 [inline]\n set_track mm/kasan/kasan.c:460 [inline]\n kasan_kmalloc+0xd4/0x180 mm/kasan/kasan.c:553\n kasan_slab_alloc+0x14/0x20 mm/kasan/kasan.c:490\n slab_post_alloc_hook mm/slab.h:444 [inline]\n slab_alloc_node mm/slub.c:2705 [inline]\n slab_alloc mm/slub.c:2713 [inline]\n kmem_cache_alloc+0x14c/0x388 mm/slub.c:2718\n kmem_cache_zalloc include/linux/slab.h:697 [inline]\n net_alloc net/core/net_namespace.c:384 [inline]\n copy_net_ns+0xc4/0x2d0 net/core/net_namespace.c:424\n create_new_namespaces+0x300/0x658 kernel/nsproxy.c:107\n unshare_nsproxy_namespaces+0xa0/0x198 kernel/nsproxy.c:206\n ksys_unshare+0x340/0x628 kernel/fork.c:2577\n __do_sys_unshare kernel/fork.c:2645 [inline]\n __se_sys_unshare kernel/fork.c:2643 [inline]\n __arm64_sys_unshare+0x38/0x58 kernel/fork.c:2643\n __invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]\n invoke_syscall arch/arm64/kernel/syscall.c:47 [inline]\n el0_svc_common+0x168/0x390 arch/arm64/kernel/syscall.c:83\n el0_svc_handler+0x60/0xd0 arch/arm64/kernel/syscall.c:129\n el0_svc+0x8/0xc arch/arm64/kernel/entry.S:960\n\nFreed by task 264:\n save_stack mm/kasan/kasan.c:448 [inline]\n set_track mm/kasan/kasan.c:460 [inline]\n __kasan_slab_free+0x114/0x220 mm/kasan/kasan.c:521\n kasan_slab_free+0x10/0x18 mm/kasan/kasan.c:528\n slab_free_hook mm/slub.c:1370 [inline]\n slab_free_freelist_hook mm/slub.c:1397 [inline]\n slab_free mm/slub.c:2952 [inline]\n kmem_cache_free+0xb8/0x3a8 mm/slub.c:2968\n net_free net/core/net_namespace.c:400 [inline]\n net_drop_ns.part.6+0x78/0x90 net/core/net_namespace.c:407\n net_drop_ns net/core/net_namespace.c:406 [inline]\n cleanup_net+0x53c/0x6d8 net/core/net_namespace.c:569\n process_one_work+0x6e8/0x1700 kernel/workqueue.c:2153\n worker_thread+0x3b0/0xdd0 kernel/workqueue.c:2296\n kthread+0x2f0/0x378 kernel/kthread.c:255\n ret_from_fork+0x10/0x18 arch/arm64/kernel/entry.S:1117\n\nThe buggy address belongs to the object at ffff8003496a3f80\n which belongs to the cache net_namespace of size 7872\nThe buggy address is located 1796 bytes inside of\n 7872-byte region [ffff8003496a3f80, ffff8003496a5e40)\nThe buggy address belongs to the page:\npage:ffff7e000d25a800 count:1 mapcount:0 mapping:ffff80036ce4b000\nindex:0x0 compound_mapcount: 0\nflags: 0xffffe0000008100(slab|head)\nraw: 0ffffe0000008100 dead000000000100 dead000000000200 ffff80036ce4b000\nraw: 0000000000000000 0000000080040004 00000001ffffffff 0000000000000000\npage dumped because: kasan: bad access detected\n\nMemory state around the buggy address:\n ffff8003496a4580: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n ffff8003496a4600: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n>ffff8003496a4680: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n ^\n ffff8003496a4700: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n ffff8003496a4780: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n==================================================================\n\nFixes: 467fa15356ac(\"RDS-TCP: Support multiple RDS-TCP listen endpoints, one per netns.\")\nReported-by: Hulk Robot \nSigned-off-by: Mao Wenan \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ipmi_si_port_setup(struct si_sm_io *io)\n{\n\tunsigned int addr = io->addr_data;\n\tint idx;\n\n\tif (!addr)\n\t\treturn -ENODEV;\n\n\tio->io_cleanup = port_cleanup;\n\n\t/*\n\t * Figure out the actual inb/inw/inl/etc routine to use based\n\t * upon the register size.\n\t */\n\tswitch (io->regsize) {\n\tcase 1:\n\t\tio->inputb = port_inb;\n\t\tio->outputb = port_outb;\n\t\tbreak;\n\tcase 2:\n\t\tio->inputb = port_inw;\n\t\tio->outputb = port_outw;\n\t\tbreak;\n\tcase 4:\n\t\tio->inputb = port_inl;\n\t\tio->outputb = port_outl;\n\t\tbreak;\n\tdefault:\n\t\tdev_warn(io->dev, \"Invalid register size: %d\\n\",\n\t\t\t io->regsize);\n\t\treturn -EINVAL;\n\t}\n\n\t/*\n\t * Some BIOSes reserve disjoint I/O regions in their ACPI\n\t * tables. This causes problems when trying to register the\n\t * entire I/O region. Therefore we must register each I/O\n\t * port separately.\n\t */\n\tfor (idx = 0; idx < io->io_size; idx++) {\n\t\tif (request_region(addr + idx * io->regspacing,\n\t\t\t\t io->regsize, DEVICE_NAME) == NULL) {\n\t\t\t/* Undo allocations */\n\t\t\twhile (idx--)\n\t\t\t\trelease_region(addr + idx * io->regspacing,\n\t\t\t\t\t io->regsize);\n\t\t\treturn -EIO;\n\t\t}\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'ipmi_si: fix use-after-free of resource->name\n\nWhen we excute the following commands, we got oops\nrmmod ipmi_si\ncat /proc/ioports\n\n[ 1623.482380] Unable to handle kernel paging request at virtual address ffff00000901d478\n[ 1623.482382] Mem abort info:\n[ 1623.482383] ESR = 0x96000007\n[ 1623.482385] Exception class = DABT (current EL), IL = 32 bits\n[ 1623.482386] SET = 0, FnV = 0\n[ 1623.482387] EA = 0, S1PTW = 0\n[ 1623.482388] Data abort info:\n[ 1623.482389] ISV = 0, ISS = 0x00000007\n[ 1623.482390] CM = 0, WnR = 0\n[ 1623.482393] swapper pgtable: 4k pages, 48-bit VAs, pgdp = 00000000d7d94a66\n[ 1623.482395] [ffff00000901d478] pgd=000000dffbfff003, pud=000000dffbffe003, pmd=0000003f5d06e003, pte=0000000000000000\n[ 1623.482399] Internal error: Oops: 96000007 [#1] SMP\n[ 1623.487407] Modules linked in: ipmi_si(E) nls_utf8 isofs rpcrdma ib_iser ib_srpt target_core_mod ib_srp scsi_transport_srp ib_ipoib rdma_ucm ib_umad rdma_cm ib_cm dm_mirror dm_region_hash dm_log iw_cm dm_mod aes_ce_blk crypto_simd cryptd aes_ce_cipher ses ghash_ce sha2_ce enclosure sha256_arm64 sg sha1_ce hisi_sas_v2_hw hibmc_drm sbsa_gwdt hisi_sas_main ip_tables mlx5_ib ib_uverbs marvell ib_core mlx5_core ixgbe mdio hns_dsaf ipmi_devintf hns_enet_drv ipmi_msghandler hns_mdio [last unloaded: ipmi_si]\n[ 1623.532410] CPU: 30 PID: 11438 Comm: cat Kdump: loaded Tainted: G E 5.0.0-rc3+ #168\n[ 1623.541498] Hardware name: Huawei TaiShan 2280 /BC11SPCD, BIOS 1.37 11/21/2017\n[ 1623.548822] pstate: a0000005 (NzCv daif -PAN -UAO)\n[ 1623.553684] pc : string+0x28/0x98\n[ 1623.557040] lr : vsnprintf+0x368/0x5e8\n[ 1623.560837] sp : ffff000013213a80\n[ 1623.564191] x29: ffff000013213a80 x28: ffff00001138abb5\n[ 1623.569577] x27: ffff000013213c18 x26: ffff805f67d06049\n[ 1623.574963] x25: 0000000000000000 x24: ffff00001138abb5\n[ 1623.580349] x23: 0000000000000fb7 x22: ffff0000117ed000\n[ 1623.585734] x21: ffff000011188fd8 x20: ffff805f67d07000\n[ 1623.591119] x19: ffff805f67d06061 x18: ffffffffffffffff\n[ 1623.596505] x17: 0000000000000200 x16: 0000000000000000\n[ 1623.601890] x15: ffff0000117ed748 x14: ffff805f67d07000\n[ 1623.607276] x13: ffff805f67d0605e x12: 0000000000000000\n[ 1623.612661] x11: 0000000000000000 x10: 0000000000000000\n[ 1623.618046] x9 : 0000000000000000 x8 : 000000000000000f\n[ 1623.623432] x7 : ffff805f67d06061 x6 : fffffffffffffffe\n[ 1623.628817] x5 : 0000000000000012 x4 : ffff00000901d478\n[ 1623.634203] x3 : ffff0a00ffffff04 x2 : ffff805f67d07000\n[ 1623.639588] x1 : ffff805f67d07000 x0 : ffffffffffffffff\n[ 1623.644974] Process cat (pid: 11438, stack limit = 0x000000008d4cbc10)\n[ 1623.651592] Call trace:\n[ 1623.654068] string+0x28/0x98\n[ 1623.657071] vsnprintf+0x368/0x5e8\n[ 1623.660517] seq_vprintf+0x70/0x98\n[ 1623.668009] seq_printf+0x7c/0xa0\n[ 1623.675530] r_show+0xc8/0xf8\n[ 1623.682558] seq_read+0x330/0x440\n[ 1623.689877] proc_reg_read+0x78/0xd0\n[ 1623.697346] __vfs_read+0x60/0x1a0\n[ 1623.704564] vfs_read+0x94/0x150\n[ 1623.711339] ksys_read+0x6c/0xd8\n[ 1623.717939] __arm64_sys_read+0x24/0x30\n[ 1623.725077] el0_svc_common+0x120/0x148\n[ 1623.732035] el0_svc_handler+0x30/0x40\n[ 1623.738757] el0_svc+0x8/0xc\n[ 1623.744520] Code: d1000406 aa0103e2 54000149 b4000080 (39400085)\n[ 1623.753441] ---[ end trace f91b6a4937de9835 ]---\n[ 1623.760871] Kernel panic - not syncing: Fatal exception\n[ 1623.768935] SMP: stopping secondary CPUs\n[ 1623.775718] Kernel Offset: disabled\n[ 1623.781998] CPU features: 0x002,21006008\n[ 1623.788777] Memory Limit: none\n[ 1623.798329] Starting crashdump kernel...\n[ 1623.805202] Bye!\n\nIf io_setup is called successful in try_smi_init() but try_smi_init()\ngoes out_err before calling ipmi_register_smi(), so ipmi_unregister_smi()\nwill not be called while removing module. It leads to the resource that\nallocated in io_setup() can not be freed, but the name(DEVICE_NAME) of\nresource is freed while removing the module. It causes use-after-free\nwhen cat /proc/ioports.\n\nFix this by calling io_cleanup() while try_smi_init() goes to out_err.\nand don't call io_cleanup() until io_setup() returns successful to avoid\nwarning prints.\n\nFixes: 93c303d2045b (\"ipmi_si: Clean up shutdown a bit\")\nCc: stable@vger.kernel.org\nReported-by: NuoHan Qiao \nSuggested-by: Corey Minyard \nSigned-off-by: Yang Yingliang \nSigned-off-by: Corey Minyard '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: upnp_redirect(const char * rhost, unsigned short eport,\n const char * iaddr, unsigned short iport,\n const char * protocol, const char * desc,\n unsigned int leaseduration)\n{\n\tint proto, r;\n\tchar iaddr_old[32];\n\tchar rhost_old[32];\n\tunsigned short iport_old;\n\tstruct in_addr address;\n\tunsigned int timestamp;\n\n\tproto = proto_atoi(protocol);\n\tif(inet_aton(iaddr, &address) <= 0) {\n\t\tsyslog(LOG_ERR, \"inet_aton(%s) FAILED\", iaddr);\n\t\treturn -1;\n\t}\n\n\tif(!check_upnp_rule_against_permissions(upnppermlist, num_upnpperm,\n\t eport, address, iport)) {\n\t\tsyslog(LOG_INFO, \"redirection permission check failed for \"\n\t\t \"%hu->%s:%hu %s\", eport, iaddr, iport, protocol);\n\t\treturn -3;\n\t}\n\t/* IGDv1 (WANIPConnection:1 Service Template Version 1.01 / Nov 12, 2001)\n\t * - 2.2.20.PortMappingDescription :\n\t * Overwriting Previous / Existing Port Mappings:\n\t * If the RemoteHost, ExternalPort, PortMappingProtocol and InternalClient\n\t * are exactly the same as an existing mapping, the existing mapping values\n\t * for InternalPort, PortMappingDescription, PortMappingEnabled and\n\t * PortMappingLeaseDuration are overwritten.\n\t * Rejecting a New Port Mapping:\n\t * In cases where the RemoteHost, ExternalPort and PortMappingProtocol\n\t * are the same as an existing mapping, but the InternalClient is\n\t * different, the action is rejected with an appropriate error.\n\t * Add or Reject New Port Mapping behavior based on vendor implementation:\n\t * In cases where the ExternalPort, PortMappingProtocol and InternalClient\n\t * are the same, but RemoteHost is different, the vendor can choose to\n\t * support both mappings simultaneously, or reject the second mapping\n\t * with an appropriate error.\n\t *\n\t * - 2.4.16.AddPortMapping\n\t * This action creates a new port mapping or overwrites an existing\n\t * mapping with the same internal client. If the ExternalPort and\n\t * PortMappingProtocol pair is already mapped to another internal client,\n\t * an error is returned.\n\t *\n\t * IGDv2 (WANIPConnection:2 Service Standardized DCP (SDCP) Sep 10, 2010)\n\t * Protocol ExternalPort RemoteHost InternalClient Result\n\t * = = \u2260 \u2260 Failure\n\t * = = \u2260 = Failure or success\n\t * (vendor specific)\n\t * = = = \u2260 Failure\n\t * = = = = Success (overwrite)\n\t */\n\trhost_old[0] = '\\0';\n\tr = get_redirect_rule(ext_if_name, eport, proto,\n\t iaddr_old, sizeof(iaddr_old), &iport_old, 0, 0,\n\t rhost_old, sizeof(rhost_old),\n\t ×tamp, 0, 0);\n\tif(r == 0) {\n\t\tif(strcmp(iaddr, iaddr_old)==0 &&\n\t\t ((rhost == NULL && rhost_old[0]=='\\0') ||\n\t\t (rhost && (strcmp(rhost, \"*\") == 0) && rhost_old[0]=='\\0') ||\n\t\t (rhost && (strcmp(rhost, rhost_old) == 0)))) {\n\t\t\tsyslog(LOG_INFO, \"updating existing port mapping %hu %s (rhost '%s') => %s:%hu\",\n\t\t\t\teport, protocol, rhost_old, iaddr_old, iport_old);\n\t\t\ttimestamp = (leaseduration > 0) ? upnp_time() + leaseduration : 0;\n\t\t\tif(iport != iport_old) {\n\t\t\t\tr = update_portmapping(ext_if_name, eport, proto, iport, desc, timestamp);\n\t\t\t} else {\n\t\t\t\tr = update_portmapping_desc_timestamp(ext_if_name, eport, proto, desc, timestamp);\n\t\t\t}\n#ifdef ENABLE_LEASEFILE\n\t\t\tif(r == 0) {\n\t\t\t\tlease_file_remove(eport, proto);\n\t\t\t\tlease_file_add(eport, iaddr, iport, proto, desc, timestamp);\n\t\t\t}\n#endif /* ENABLE_LEASEFILE */\n\t\t\treturn r;\n\t\t} else {\n\t\t\tsyslog(LOG_INFO, \"port %hu %s (rhost '%s') already redirected to %s:%hu\",\n\t\t\t\teport, protocol, rhost_old, iaddr_old, iport_old);\n\t\t\treturn -2;\n\t\t}\n#ifdef CHECK_PORTINUSE\n\t} else if (port_in_use(ext_if_name, eport, proto, iaddr, iport) > 0) {\n\t\tsyslog(LOG_INFO, \"port %hu protocol %s already in use\",\n\t\t eport, protocol);\n\t\treturn -4;\n#endif /* CHECK_PORTINUSE */\n\t} else {\n\t\ttimestamp = (leaseduration > 0) ? upnp_time() + leaseduration : 0;\n\t\tsyslog(LOG_INFO, \"redirecting port %hu to %s:%hu protocol %s for: %s\",\n\t\t\teport, iaddr, iport, protocol, desc);\n\t\treturn upnp_redirect_internal(rhost, eport, iaddr, iport, proto,\n\t\t desc, timestamp);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'upnp_redirect(): accept NULL desc argument'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: con_insert_unipair(struct uni_pagedir *p, u_short unicode, u_short fontpos)\n{\n\tint i, n;\n\tu16 **p1, *p2;\n\n\tp1 = p->uni_pgdir[n = unicode >> 11];\n\tif (!p1) {\n\t\tp1 = p->uni_pgdir[n] = kmalloc_array(32, sizeof(u16 *),\n\t\t\t\t\t\t GFP_KERNEL);\n\t\tif (!p1) return -ENOMEM;\n\t\tfor (i = 0; i < 32; i++)\n\t\t\tp1[i] = NULL;\n\t}\n\n\tp2 = p1[n = (unicode >> 6) & 0x1f];\n\tif (!p2) {\n\t\tp2 = p1[n] = kmalloc_array(64, sizeof(u16), GFP_KERNEL);\n\t\tif (!p2) return -ENOMEM;\n\t\tmemset(p2, 0xff, 64*sizeof(u16)); /* No glyphs for the characters (yet) */\n\t}\n\n\tp2[unicode & 0x3f] = fontpos;\n\t\n\tp->sum += (fontpos << 20) + unicode;\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'consolemap: Fix a memory leaking bug in drivers/tty/vt/consolemap.c\n\nIn function con_insert_unipair(), when allocation for p2 and p1[n]\nfails, ENOMEM is returned, but previously allocated p1 is not freed,\nremains as leaking memory. Thus we should free p1 as well when this\nallocation fails.\n\nSigned-off-by: Gen Zhang \nReviewed-by: Kees Cook \nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: exsltDynMapFunction(xmlXPathParserContextPtr ctxt, int nargs)\n{\n xmlChar *str = NULL;\n xmlNodeSetPtr nodeset = NULL;\n xsltTransformContextPtr tctxt;\n xmlXPathCompExprPtr comp = NULL;\n xmlXPathObjectPtr ret = NULL;\n xmlDocPtr oldDoc, container = NULL;\n xmlNodePtr oldNode;\n int oldContextSize;\n int oldProximityPosition;\n int i, j;\n\n\n if (nargs != 2) {\n xmlXPathSetArityError(ctxt);\n return;\n }\n str = xmlXPathPopString(ctxt);\n if (xmlXPathCheckError(ctxt)) {\n xmlXPathSetTypeError(ctxt);\n return;\n }\n\n nodeset = xmlXPathPopNodeSet(ctxt);\n if (xmlXPathCheckError(ctxt)) {\n xmlXPathSetTypeError(ctxt);\n return;\n }\n if (str == NULL || !xmlStrlen(str) || !(comp = xmlXPathCompile(str))) {\n if (nodeset != NULL)\n xmlXPathFreeNodeSet(nodeset);\n if (str != NULL)\n xmlFree(str);\n valuePush(ctxt, xmlXPathNewNodeSet(NULL));\n return;\n }\n\n ret = xmlXPathNewNodeSet(NULL);\n if (ret == NULL) {\n xsltGenericError(xsltGenericErrorContext,\n \"exsltDynMapFunction: ret == NULL\\n\");\n goto cleanup;\n }\n\n oldDoc = ctxt->context->doc;\n oldNode = ctxt->context->node;\n oldContextSize = ctxt->context->contextSize;\n oldProximityPosition = ctxt->context->proximityPosition;\n\n /**\n\t * since we really don't know we're going to be adding node(s)\n\t * down the road we create the RVT regardless\n\t */\n tctxt = xsltXPathGetTransformContext(ctxt);\n if (tctxt == NULL) {\n\txsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL,\n\t \"dyn:map : internal error tctxt == NULL\\n\");\n\tgoto cleanup;\n }\n container = xsltCreateRVT(tctxt);\n if (container == NULL) {\n\txsltTransformError(tctxt, NULL, NULL,\n\t \"dyn:map : internal error container == NULL\\n\");\n\tgoto cleanup;\n }\n xsltRegisterLocalRVT(tctxt, container);\n if (nodeset && nodeset->nodeNr > 0) {\n xmlXPathNodeSetSort(nodeset);\n ctxt->context->contextSize = nodeset->nodeNr;\n ctxt->context->proximityPosition = 0;\n for (i = 0; i < nodeset->nodeNr; i++) {\n xmlXPathObjectPtr subResult = NULL;\n\n ctxt->context->proximityPosition++;\n ctxt->context->node = nodeset->nodeTab[i];\n ctxt->context->doc = nodeset->nodeTab[i]->doc;\n\n subResult = xmlXPathCompiledEval(comp, ctxt->context);\n if (subResult != NULL) {\n switch (subResult->type) {\n case XPATH_NODESET:\n if (subResult->nodesetval != NULL)\n for (j = 0; j < subResult->nodesetval->nodeNr;\n j++)\n xmlXPathNodeSetAdd(ret->nodesetval,\n subResult->nodesetval->\n nodeTab[j]);\n break;\n case XPATH_BOOLEAN:\n if (container != NULL) {\n xmlNodePtr cur =\n xmlNewChild((xmlNodePtr) container, NULL,\n BAD_CAST \"boolean\",\n BAD_CAST (subResult->\n boolval ? \"true\" : \"\"));\n if (cur != NULL) {\n cur->ns =\n xmlNewNs(cur,\n BAD_CAST\n \"http://exslt.org/common\",\n BAD_CAST \"exsl\");\n xmlXPathNodeSetAddUnique(ret->nodesetval,\n cur);\n }\n\t\t\t xsltExtensionInstructionResultRegister(tctxt, ret);\n }\n break;\n case XPATH_NUMBER:\n if (container != NULL) {\n xmlChar *val =\n xmlXPathCastNumberToString(subResult->\n floatval);\n xmlNodePtr cur =\n xmlNewChild((xmlNodePtr) container, NULL,\n BAD_CAST \"number\", val);\n if (val != NULL)\n xmlFree(val);\n\n if (cur != NULL) {\n cur->ns =\n xmlNewNs(cur,\n BAD_CAST\n \"http://exslt.org/common\",\n BAD_CAST \"exsl\");\n xmlXPathNodeSetAddUnique(ret->nodesetval,\n cur);\n }\n\t\t\t xsltExtensionInstructionResultRegister(tctxt, ret);\n }\n break;\n case XPATH_STRING:\n if (container != NULL) {\n xmlNodePtr cur =\n xmlNewChild((xmlNodePtr) container, NULL,\n BAD_CAST \"string\",\n subResult->stringval);\n if (cur != NULL) {\n cur->ns =\n xmlNewNs(cur,\n BAD_CAST\n \"http://exslt.org/common\",\n BAD_CAST \"exsl\");\n xmlXPathNodeSetAddUnique(ret->nodesetval,\n cur);\n }\n\t\t\t xsltExtensionInstructionResultRegister(tctxt, ret);\n }\n break;\n\t\t default:\n break;\n }\n xmlXPathFreeObject(subResult);\n }\n }\n }\n ctxt->context->doc = oldDoc;\n ctxt->context->node = oldNode;\n ctxt->context->contextSize = oldContextSize;\n ctxt->context->proximityPosition = oldProximityPosition;\n\n\n cleanup:\n /* restore the xpath context */\n if (comp != NULL)\n xmlXPathFreeCompExpr(comp);\n if (nodeset != NULL)\n xmlXPathFreeNodeSet(nodeset);\n if (str != NULL)\n xmlFree(str);\n valuePush(ctxt, ret);\n return;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix dyn:map with namespace nodes\n\nexsltDynMapFunction didn't handle namespace nodes correctly. Namespace\nnodes are actually an xmlNs, not an xmlNode and must be special-cased.\n\nThe old code initialized the doc pointer in the XPath context struct\nwith a value read from past the end of the xmlNs struct. Typically,\nthis resulted in a segfault.\n\nFound with afl-fuzz and ASan.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: const char *get_icalcomponent_errstr(icalcomponent *ical)\n{\n icalcomponent *comp;\n\n for (comp = icalcomponent_get_first_component(ical, ICAL_ANY_COMPONENT);\n\t comp;\n\t comp = icalcomponent_get_next_component(ical, ICAL_ANY_COMPONENT)) {\n\ticalproperty *prop;\n\n\tfor (prop = icalcomponent_get_first_property(comp, ICAL_ANY_PROPERTY);\n\t prop;\n\t prop = icalcomponent_get_next_property(comp, ICAL_ANY_PROPERTY)) {\n\n\t if (icalproperty_isa(prop) == ICAL_XLICERROR_PROPERTY) {\n\t\ticalparameter *param;\n\t\tconst char *errstr = icalproperty_get_xlicerror(prop);\n\n\t\tif (!errstr) return \"Unknown iCal parsing error\";\n\n\t\tparam = icalproperty_get_first_parameter(\n\t\t prop, ICAL_XLICERRORTYPE_PARAMETER);\n\n\t\tif (icalparameter_get_xlicerrortype(param) ==\n\t\t ICAL_XLICERRORTYPE_VALUEPARSEERROR) {\n\t\t /* Check if this is an empty property error */\n\t\t char propname[256];\n\t\t if (sscanf(errstr,\n\t\t\t \"No value for %s property\", propname) == 1) {\n\t\t\t/* Empty LOCATION is OK */\n\t\t\tif (!strcasecmp(propname, \"LOCATION\")) continue;\n\t\t\tif (!strcasecmp(propname, \"COMMENT\")) continue;\n\t\t\tif (!strcasecmp(propname, \"DESCRIPTION\")) continue;\n\t\t }\n\t\t}\n\t }\n\t}\n }\n\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'HTTP: don't overrun buffer when parsing strings with sscanf()'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static bool tcp_collapse_retrans(struct sock *sk, struct sk_buff *skb)\n{\n\tstruct tcp_sock *tp = tcp_sk(sk);\n\tstruct sk_buff *next_skb = skb_rb_next(skb);\n\tint next_skb_size;\n\n\tnext_skb_size = next_skb->len;\n\n\tBUG_ON(tcp_skb_pcount(skb) != 1 || tcp_skb_pcount(next_skb) != 1);\n\n\tif (next_skb_size) {\n\t\tif (next_skb_size <= skb_availroom(skb))\n\t\t\tskb_copy_bits(next_skb, 0, skb_put(skb, next_skb_size),\n\t\t\t\t next_skb_size);\n\t\telse if (!skb_shift(skb, next_skb, next_skb_size))\n\t\t\treturn false;\n\t}\n\ttcp_highest_sack_replace(sk, next_skb, skb);\n\n\t/* Update sequence range on original skb. */\n\tTCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(next_skb)->end_seq;\n\n\t/* Merge over control information. This moves PSH/FIN etc. over */\n\tTCP_SKB_CB(skb)->tcp_flags |= TCP_SKB_CB(next_skb)->tcp_flags;\n\n\t/* All done, get rid of second SKB and account for it so\n\t * packet counting does not break.\n\t */\n\tTCP_SKB_CB(skb)->sacked |= TCP_SKB_CB(next_skb)->sacked & TCPCB_EVER_RETRANS;\n\tTCP_SKB_CB(skb)->eor = TCP_SKB_CB(next_skb)->eor;\n\n\t/* changed transmit queue under us so clear hints */\n\ttcp_clear_retrans_hints_partial(tp);\n\tif (next_skb == tp->retransmit_skb_hint)\n\t\ttp->retransmit_skb_hint = skb;\n\n\ttcp_adjust_pcount(sk, next_skb, tcp_skb_pcount(next_skb));\n\n\ttcp_skb_collapse_tstamp(skb, next_skb);\n\n\ttcp_rtx_queue_unlink_and_free(next_skb, sk);\n\treturn true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'tcp: limit payload size of sacked skbs\n\nJonathan Looney reported that TCP can trigger the following crash\nin tcp_shifted_skb() :\n\n\tBUG_ON(tcp_skb_pcount(skb) < pcount);\n\nThis can happen if the remote peer has advertized the smallest\nMSS that linux TCP accepts : 48\n\nAn skb can hold 17 fragments, and each fragment can hold 32KB\non x86, or 64KB on PowerPC.\n\nThis means that the 16bit witdh of TCP_SKB_CB(skb)->tcp_gso_segs\ncan overflow.\n\nNote that tcp_sendmsg() builds skbs with less than 64KB\nof payload, so this problem needs SACK to be enabled.\nSACK blocks allow TCP to coalesce multiple skbs in the retransmit\nqueue, thus filling the 17 fragments to maximal capacity.\n\nCVE-2019-11477 -- u16 overflow of TCP_SKB_CB(skb)->tcp_gso_segs\n\nFixes: 832d11c5cd07 (\"tcp: Try to restore large SKBs while SACK processing\")\nSigned-off-by: Eric Dumazet \nReported-by: Jonathan Looney \nAcked-by: Neal Cardwell \nReviewed-by: Tyler Hicks \nCc: Yuchung Cheng \nCc: Bruce Curtis \nCc: Jonathan Lemon \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int nfc_llcp_build_gb(struct nfc_llcp_local *local)\n{\n\tu8 *gb_cur, *version_tlv, version, version_length;\n\tu8 *lto_tlv, lto_length;\n\tu8 *wks_tlv, wks_length;\n\tu8 *miux_tlv, miux_length;\n\t__be16 wks = cpu_to_be16(local->local_wks);\n\tu8 gb_len = 0;\n\tint ret = 0;\n\n\tversion = LLCP_VERSION_11;\n\tversion_tlv = nfc_llcp_build_tlv(LLCP_TLV_VERSION, &version,\n\t\t\t\t\t 1, &version_length);\n\tgb_len += version_length;\n\n\tlto_tlv = nfc_llcp_build_tlv(LLCP_TLV_LTO, &local->lto, 1, <o_length);\n\tgb_len += lto_length;\n\n\tpr_debug(\"Local wks 0x%lx\\n\", local->local_wks);\n\twks_tlv = nfc_llcp_build_tlv(LLCP_TLV_WKS, (u8 *)&wks, 2, &wks_length);\n\tgb_len += wks_length;\n\n\tmiux_tlv = nfc_llcp_build_tlv(LLCP_TLV_MIUX, (u8 *)&local->miux, 0,\n\t\t\t\t &miux_length);\n\tgb_len += miux_length;\n\n\tgb_len += ARRAY_SIZE(llcp_magic);\n\n\tif (gb_len > NFC_MAX_GT_LEN) {\n\t\tret = -EINVAL;\n\t\tgoto out;\n\t}\n\n\tgb_cur = local->gb;\n\n\tmemcpy(gb_cur, llcp_magic, ARRAY_SIZE(llcp_magic));\n\tgb_cur += ARRAY_SIZE(llcp_magic);\n\n\tmemcpy(gb_cur, version_tlv, version_length);\n\tgb_cur += version_length;\n\n\tmemcpy(gb_cur, lto_tlv, lto_length);\n\tgb_cur += lto_length;\n\n\tmemcpy(gb_cur, wks_tlv, wks_length);\n\tgb_cur += wks_length;\n\n\tmemcpy(gb_cur, miux_tlv, miux_length);\n\tgb_cur += miux_length;\n\n\tlocal->gb_len = gb_len;\n\nout:\n\tkfree(version_tlv);\n\tkfree(lto_tlv);\n\tkfree(wks_tlv);\n\tkfree(miux_tlv);\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'net: nfc: Fix NULL dereference on nfc_llcp_build_tlv fails\n\nKASAN report this:\n\nBUG: KASAN: null-ptr-deref in nfc_llcp_build_gb+0x37f/0x540 [nfc]\nRead of size 3 at addr 0000000000000000 by task syz-executor.0/5401\n\nCPU: 0 PID: 5401 Comm: syz-executor.0 Not tainted 5.0.0-rc7+ #45\nHardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014\nCall Trace:\n __dump_stack lib/dump_stack.c:77 [inline]\n dump_stack+0xfa/0x1ce lib/dump_stack.c:113\n kasan_report+0x171/0x18d mm/kasan/report.c:321\n memcpy+0x1f/0x50 mm/kasan/common.c:130\n nfc_llcp_build_gb+0x37f/0x540 [nfc]\n nfc_llcp_register_device+0x6eb/0xb50 [nfc]\n nfc_register_device+0x50/0x1d0 [nfc]\n nfcsim_device_new+0x394/0x67d [nfcsim]\n ? 0xffffffffc1080000\n nfcsim_init+0x6b/0x1000 [nfcsim]\n do_one_initcall+0xfa/0x5ca init/main.c:887\n do_init_module+0x204/0x5f6 kernel/module.c:3460\n load_module+0x66b2/0x8570 kernel/module.c:3808\n __do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902\n do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290\n entry_SYSCALL_64_after_hwframe+0x49/0xbe\nRIP: 0033:0x462e99\nCode: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48\nRSP: 002b:00007f9cb79dcc58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139\nRAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99\nRDX: 0000000000000000 RSI: 0000000020000280 RDI: 0000000000000003\nRBP: 00007f9cb79dcc70 R08: 0000000000000000 R09: 0000000000000000\nR10: 0000000000000000 R11: 0000000000000246 R12: 00007f9cb79dd6bc\nR13: 00000000004bcefb R14: 00000000006f7030 R15: 0000000000000004\n\nnfc_llcp_build_tlv will return NULL on fails, caller should check it,\notherwise will trigger a NULL dereference.\n\nReported-by: Hulk Robot \nFixes: eda21f16a5ed (\"NFC: Set MIU and RW values from CONNECT and CC LLCP frames\")\nFixes: d646960f7986 (\"NFC: Initial LLCP support\")\nSigned-off-by: YueHaibing \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: gdImagePtr gdImageCreateFromXbm(FILE * fd)\n{\n\tchar fline[MAX_XBM_LINE_SIZE];\n\tchar iname[MAX_XBM_LINE_SIZE];\n\tchar *type;\n\tint value;\n\tunsigned int width = 0, height = 0;\n\tint fail = 0;\n\tint max_bit = 0;\n\n\tgdImagePtr im;\n\tint bytes = 0, i;\n\tint bit, x = 0, y = 0;\n\tint ch;\n\tchar h[8];\n\tunsigned int b;\n\n\trewind(fd);\n\twhile (fgets(fline, MAX_XBM_LINE_SIZE, fd)) {\n\t\tfline[MAX_XBM_LINE_SIZE-1] = '\\0';\n\t\tif (strlen(fline) == MAX_XBM_LINE_SIZE-1) {\n\t\t\treturn 0;\n\t\t}\n\t\tif (sscanf(fline, \"#define %s %d\", iname, &value) == 2) {\n\t\t\tif (!(type = strrchr(iname, '_'))) {\n\t\t\t\ttype = iname;\n\t\t\t} else {\n\t\t\t\ttype++;\n\t\t\t}\n\n\t\t\tif (!strcmp(\"width\", type)) {\n\t\t\t\twidth = (unsigned int) value;\n\t\t\t}\n\t\t\tif (!strcmp(\"height\", type)) {\n\t\t\t\theight = (unsigned int) value;\n\t\t\t}\n\t\t} else {\n\t\t\tif ( sscanf(fline, \"static unsigned char %s = {\", iname) == 1\n\t\t\t || sscanf(fline, \"static char %s = {\", iname) == 1)\n\t\t\t{\n\t\t\t\tmax_bit = 128;\n\t\t\t} else if (sscanf(fline, \"static unsigned short %s = {\", iname) == 1\n\t\t\t\t\t|| sscanf(fline, \"static short %s = {\", iname) == 1)\n\t\t\t{\n\t\t\t\tmax_bit = 32768;\n\t\t\t}\n\t\t\tif (max_bit) {\n\t\t\t\tbytes = (width + 7) / 8 * height;\n\t\t\t\tif (!bytes) {\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tif (!(type = strrchr(iname, '_'))) {\n\t\t\t\t\ttype = iname;\n\t\t\t\t} else {\n\t\t\t\t\ttype++;\n\t\t\t\t}\n\t\t\t\tif (!strcmp(\"bits[]\", type)) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n \t\t}\n\t}\n\tif (!bytes || !max_bit) {\n\t\treturn 0;\n\t}\n\n\tif(!(im = gdImageCreate(width, height))) {\n\t\treturn 0;\n\t}\n\tgdImageColorAllocate(im, 255, 255, 255);\n\tgdImageColorAllocate(im, 0, 0, 0);\n\th[2] = '\\0';\n\th[4] = '\\0';\n\tfor (i = 0; i < bytes; i++) {\n\t\twhile (1) {\n\t\t\tif ((ch=getc(fd)) == EOF) {\n\t\t\t\tfail = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (ch == 'x') {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (fail) {\n\t\t\tbreak;\n\t\t}\n\t\t/* Get hex value */\n\t\tif ((ch=getc(fd)) == EOF) {\n\t\t\tbreak;\n\t\t}\n\t\th[0] = ch;\n\t\tif ((ch=getc(fd)) == EOF) {\n\t\t\tbreak;\n\t\t}\n\t\th[1] = ch;\n\t\tif (max_bit == 32768) {\n\t\t\tif ((ch=getc(fd)) == EOF) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\th[2] = ch;\n\t\t\tif ((ch=getc(fd)) == EOF) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\th[3] = ch;\n\t\t}\n\t\tsscanf(h, \"%x\", &b);\n\t\tfor (bit = 1; bit <= max_bit; bit = bit << 1) {\n\t\t\tgdImageSetPixel(im, x++, y, (b & bit) ? 1 : 0);\n\t\t\tif (x == im->sx) {\n\t\t\t\tx = 0;\n\t\t\t\ty++;\n\t\t\t\tif (y == im->sy) {\n\t\t\t\t\treturn im;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tphp_gd_error(\"EOF before image was complete\");\n\tgdImageDestroy(im);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-908'], 'message': 'Fix #77973: Uninitialized read in gdImageCreateFromXbm\n\nWe have to ensure that `sscanf()` does indeed read a hex value here,\nand bail out otherwise.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: char *url_decode_r(char *to, char *url, size_t size) {\n char *s = url, // source\n *d = to, // destination\n *e = &to[size - 1]; // destination end\n\n while(*s && d < e) {\n if(unlikely(*s == '%')) {\n if(likely(s[1] && s[2])) {\n *d++ = from_hex(s[1]) << 4 | from_hex(s[2]);\n s += 2;\n }\n }\n else if(unlikely(*s == '+'))\n *d++ = ' ';\n\n else\n *d++ = *s;\n\n s++;\n }\n\n *d = '\\0';\n\n return to;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-113', 'CWE-200', 'CWE-94', 'CWE-74'], 'message': 'fixed vulnerabilities identified by red4sec.com (#4521)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadVIFFImage(const ImageInfo *image_info,\n ExceptionInfo *exception)\n{\n#define VFF_CM_genericRGB 15\n#define VFF_CM_ntscRGB 1\n#define VFF_CM_NONE 0\n#define VFF_DEP_DECORDER 0x4\n#define VFF_DEP_NSORDER 0x8\n#define VFF_DES_RAW 0\n#define VFF_LOC_IMPLICIT 1\n#define VFF_MAPTYP_NONE 0\n#define VFF_MAPTYP_1_BYTE 1\n#define VFF_MAPTYP_2_BYTE 2\n#define VFF_MAPTYP_4_BYTE 4\n#define VFF_MAPTYP_FLOAT 5\n#define VFF_MAPTYP_DOUBLE 7\n#define VFF_MS_NONE 0\n#define VFF_MS_ONEPERBAND 1\n#define VFF_MS_SHARED 3\n#define VFF_TYP_BIT 0\n#define VFF_TYP_1_BYTE 1\n#define VFF_TYP_2_BYTE 2\n#define VFF_TYP_4_BYTE 4\n#define VFF_TYP_FLOAT 5\n#define VFF_TYP_DOUBLE 9\n\n typedef struct _ViffInfo\n {\n unsigned char\n identifier,\n file_type,\n release,\n version,\n machine_dependency,\n reserve[3];\n\n char\n comment[512];\n\n unsigned int\n rows,\n columns,\n subrows;\n\n int\n x_offset,\n y_offset;\n\n float\n x_bits_per_pixel,\n y_bits_per_pixel;\n\n unsigned int\n location_type,\n location_dimension,\n number_of_images,\n number_data_bands,\n data_storage_type,\n data_encode_scheme,\n map_scheme,\n map_storage_type,\n map_rows,\n map_columns,\n map_subrows,\n map_enable,\n maps_per_cycle,\n color_space_model;\n } ViffInfo;\n\n double\n min_value,\n scale_factor,\n value;\n\n Image\n *image;\n\n int\n bit;\n\n MagickBooleanType\n status;\n\n MagickSizeType\n number_pixels;\n\n register ssize_t\n x;\n\n register Quantum\n *q;\n\n register ssize_t\n i;\n\n register unsigned char\n *p;\n\n size_t\n bytes_per_pixel,\n max_packets,\n quantum;\n\n ssize_t\n count,\n y;\n\n unsigned char\n *pixels;\n\n unsigned long\n lsb_first;\n\n ViffInfo\n viff_info;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Read VIFF header (1024 bytes).\n */\n count=ReadBlob(image,1,&viff_info.identifier);\n do\n {\n /*\n Verify VIFF identifier.\n */\n if ((count != 1) || ((unsigned char) viff_info.identifier != 0xab))\n ThrowReaderException(CorruptImageError,\"NotAVIFFImage\");\n /*\n Initialize VIFF image.\n */\n (void) ReadBlob(image,sizeof(viff_info.file_type),&viff_info.file_type);\n (void) ReadBlob(image,sizeof(viff_info.release),&viff_info.release);\n (void) ReadBlob(image,sizeof(viff_info.version),&viff_info.version);\n (void) ReadBlob(image,sizeof(viff_info.machine_dependency),\n &viff_info.machine_dependency);\n (void) ReadBlob(image,sizeof(viff_info.reserve),viff_info.reserve);\n count=ReadBlob(image,512,(unsigned char *) viff_info.comment);\n if (count != 512)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n viff_info.comment[511]='\\0';\n if (strlen(viff_info.comment) > 4)\n (void) SetImageProperty(image,\"comment\",viff_info.comment,exception);\n if ((viff_info.machine_dependency == VFF_DEP_DECORDER) ||\n (viff_info.machine_dependency == VFF_DEP_NSORDER))\n image->endian=LSBEndian;\n else\n image->endian=MSBEndian;\n viff_info.rows=ReadBlobLong(image);\n viff_info.columns=ReadBlobLong(image);\n viff_info.subrows=ReadBlobLong(image);\n viff_info.x_offset=ReadBlobSignedLong(image);\n viff_info.y_offset=ReadBlobSignedLong(image);\n viff_info.x_bits_per_pixel=(float) ReadBlobLong(image);\n viff_info.y_bits_per_pixel=(float) ReadBlobLong(image);\n viff_info.location_type=ReadBlobLong(image);\n viff_info.location_dimension=ReadBlobLong(image);\n viff_info.number_of_images=ReadBlobLong(image);\n viff_info.number_data_bands=ReadBlobLong(image);\n viff_info.data_storage_type=ReadBlobLong(image);\n viff_info.data_encode_scheme=ReadBlobLong(image);\n viff_info.map_scheme=ReadBlobLong(image);\n viff_info.map_storage_type=ReadBlobLong(image);\n viff_info.map_rows=ReadBlobLong(image);\n viff_info.map_columns=ReadBlobLong(image);\n viff_info.map_subrows=ReadBlobLong(image);\n viff_info.map_enable=ReadBlobLong(image);\n viff_info.maps_per_cycle=ReadBlobLong(image);\n viff_info.color_space_model=ReadBlobLong(image);\n for (i=0; i < 420; i++)\n (void) ReadBlobByte(image);\n if (EOFBlob(image) != MagickFalse)\n ThrowReaderException(CorruptImageError,\"UnexpectedEndOfFile\");\n number_pixels=(MagickSizeType) viff_info.columns*viff_info.rows;\n if (number_pixels > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n if (number_pixels != (size_t) number_pixels)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n if (number_pixels == 0)\n ThrowReaderException(CoderError,\"ImageColumnOrRowSizeIsNotSupported\");\n image->columns=viff_info.rows;\n image->rows=viff_info.columns;\n image->depth=viff_info.x_bits_per_pixel <= 8 ? 8UL :\n MAGICKCORE_QUANTUM_DEPTH;\n image->alpha_trait=viff_info.number_data_bands == 4 ? BlendPixelTrait :\n UndefinedPixelTrait;\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n (void) SetImageBackgroundColor(image,exception);\n /*\n Verify that we can read this VIFF image.\n */\n if ((viff_info.number_data_bands < 1) || (viff_info.number_data_bands > 4))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if ((viff_info.data_storage_type != VFF_TYP_BIT) &&\n (viff_info.data_storage_type != VFF_TYP_1_BYTE) &&\n (viff_info.data_storage_type != VFF_TYP_2_BYTE) &&\n (viff_info.data_storage_type != VFF_TYP_4_BYTE) &&\n (viff_info.data_storage_type != VFF_TYP_FLOAT) &&\n (viff_info.data_storage_type != VFF_TYP_DOUBLE))\n ThrowReaderException(CoderError,\"DataStorageTypeIsNotSupported\");\n if (viff_info.data_encode_scheme != VFF_DES_RAW)\n ThrowReaderException(CoderError,\"DataEncodingSchemeIsNotSupported\");\n if ((viff_info.map_storage_type != VFF_MAPTYP_NONE) &&\n (viff_info.map_storage_type != VFF_MAPTYP_1_BYTE) &&\n (viff_info.map_storage_type != VFF_MAPTYP_2_BYTE) &&\n (viff_info.map_storage_type != VFF_MAPTYP_4_BYTE) &&\n (viff_info.map_storage_type != VFF_MAPTYP_FLOAT) &&\n (viff_info.map_storage_type != VFF_MAPTYP_DOUBLE))\n ThrowReaderException(CoderError,\"MapStorageTypeIsNotSupported\");\n if ((viff_info.color_space_model != VFF_CM_NONE) &&\n (viff_info.color_space_model != VFF_CM_ntscRGB) &&\n (viff_info.color_space_model != VFF_CM_genericRGB))\n ThrowReaderException(CoderError,\"ColorspaceModelIsNotSupported\");\n if (viff_info.location_type != VFF_LOC_IMPLICIT)\n ThrowReaderException(CoderError,\"LocationTypeIsNotSupported\");\n if (viff_info.number_of_images != 1)\n ThrowReaderException(CoderError,\"NumberOfImagesIsNotSupported\");\n if (viff_info.map_rows == 0)\n viff_info.map_scheme=VFF_MS_NONE;\n switch ((int) viff_info.map_scheme)\n {\n case VFF_MS_NONE:\n {\n if (viff_info.number_data_bands < 3)\n {\n /*\n Create linear color ramp.\n */\n if (viff_info.data_storage_type == VFF_TYP_BIT)\n image->colors=2;\n else\n if (viff_info.data_storage_type == VFF_MAPTYP_1_BYTE)\n image->colors=256UL;\n else\n image->colors=image->depth <= 8 ? 256UL : 65536UL;\n status=AcquireImageColormap(image,image->colors,exception);\n if (status == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n break;\n }\n case VFF_MS_ONEPERBAND:\n case VFF_MS_SHARED:\n {\n unsigned char\n *viff_colormap;\n\n /*\n Allocate VIFF colormap.\n */\n switch ((int) viff_info.map_storage_type)\n {\n case VFF_MAPTYP_1_BYTE: bytes_per_pixel=1; break;\n case VFF_MAPTYP_2_BYTE: bytes_per_pixel=2; break;\n case VFF_MAPTYP_4_BYTE: bytes_per_pixel=4; break;\n case VFF_MAPTYP_FLOAT: bytes_per_pixel=4; break;\n case VFF_MAPTYP_DOUBLE: bytes_per_pixel=8; break;\n default: bytes_per_pixel=1; break;\n }\n image->colors=viff_info.map_columns;\n if ((MagickSizeType) (viff_info.map_rows*image->colors) > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n if ((MagickSizeType) viff_info.map_rows > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n if ((MagickSizeType) viff_info.map_rows >\n (viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap)))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n viff_colormap=(unsigned char *) AcquireQuantumMemory(image->colors,\n viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap));\n if (viff_colormap == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n /*\n Read VIFF raster colormap.\n */\n count=ReadBlob(image,bytes_per_pixel*image->colors*viff_info.map_rows,\n viff_colormap);\n lsb_first=1;\n if (*(char *) &lsb_first &&\n ((viff_info.machine_dependency != VFF_DEP_DECORDER) &&\n (viff_info.machine_dependency != VFF_DEP_NSORDER)))\n switch ((int) viff_info.map_storage_type)\n {\n case VFF_MAPTYP_2_BYTE:\n {\n MSBOrderShort(viff_colormap,(bytes_per_pixel*image->colors*\n viff_info.map_rows));\n break;\n }\n case VFF_MAPTYP_4_BYTE:\n case VFF_MAPTYP_FLOAT:\n {\n MSBOrderLong(viff_colormap,(bytes_per_pixel*image->colors*\n viff_info.map_rows));\n break;\n }\n default: break;\n }\n for (i=0; i < (ssize_t) (viff_info.map_rows*image->colors); i++)\n {\n switch ((int) viff_info.map_storage_type)\n {\n case VFF_MAPTYP_2_BYTE: value=1.0*((short *) viff_colormap)[i]; break;\n case VFF_MAPTYP_4_BYTE: value=1.0*((int *) viff_colormap)[i]; break;\n case VFF_MAPTYP_FLOAT: value=((float *) viff_colormap)[i]; break;\n case VFF_MAPTYP_DOUBLE: value=((double *) viff_colormap)[i]; break;\n default: value=1.0*viff_colormap[i]; break;\n }\n if (i < (ssize_t) image->colors)\n {\n image->colormap[i].red=(MagickRealType)\n ScaleCharToQuantum((unsigned char) value);\n image->colormap[i].green=(MagickRealType)\n ScaleCharToQuantum((unsigned char) value);\n image->colormap[i].blue=(MagickRealType)\n ScaleCharToQuantum((unsigned char) value);\n }\n else\n if (i < (ssize_t) (2*image->colors))\n image->colormap[i % image->colors].green=(MagickRealType)\n ScaleCharToQuantum((unsigned char) value);\n else\n if (i < (ssize_t) (3*image->colors))\n image->colormap[i % image->colors].blue=(MagickRealType)\n ScaleCharToQuantum((unsigned char) value);\n }\n viff_colormap=(unsigned char *) RelinquishMagickMemory(viff_colormap);\n break;\n }\n default:\n ThrowReaderException(CoderError,\"ColormapTypeNotSupported\");\n }\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n if (viff_info.data_storage_type == VFF_TYP_BIT)\n {\n /*\n Create bi-level colormap.\n */\n image->colors=2;\n if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n image->colorspace=GRAYColorspace;\n }\n /*\n Allocate VIFF pixels.\n */\n switch ((int) viff_info.data_storage_type)\n {\n case VFF_TYP_2_BYTE: bytes_per_pixel=2; break;\n case VFF_TYP_4_BYTE: bytes_per_pixel=4; break;\n case VFF_TYP_FLOAT: bytes_per_pixel=4; break;\n case VFF_TYP_DOUBLE: bytes_per_pixel=8; break;\n default: bytes_per_pixel=1; break;\n }\n if (viff_info.data_storage_type == VFF_TYP_BIT)\n {\n if (HeapOverflowSanityCheck((image->columns+7UL) >> 3UL,image->rows) != MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n max_packets=((image->columns+7UL) >> 3UL)*image->rows;\n }\n else\n {\n if (HeapOverflowSanityCheck((size_t) number_pixels,viff_info.number_data_bands) != MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n max_packets=(size_t) (number_pixels*viff_info.number_data_bands);\n }\n if ((MagickSizeType) (bytes_per_pixel*max_packets) > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n pixels=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax(\n number_pixels,max_packets),bytes_per_pixel*sizeof(*pixels));\n if (pixels == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) memset(pixels,0,MagickMax(number_pixels,max_packets)*\n bytes_per_pixel*sizeof(*pixels));\n count=ReadBlob(image,bytes_per_pixel*max_packets,pixels);\n lsb_first=1;\n if (*(char *) &lsb_first &&\n ((viff_info.machine_dependency != VFF_DEP_DECORDER) &&\n (viff_info.machine_dependency != VFF_DEP_NSORDER)))\n switch ((int) viff_info.data_storage_type)\n {\n case VFF_TYP_2_BYTE:\n {\n MSBOrderShort(pixels,bytes_per_pixel*max_packets);\n break;\n }\n case VFF_TYP_4_BYTE:\n case VFF_TYP_FLOAT:\n {\n MSBOrderLong(pixels,bytes_per_pixel*max_packets);\n break;\n }\n default: break;\n }\n min_value=0.0;\n scale_factor=1.0;\n if ((viff_info.data_storage_type != VFF_TYP_1_BYTE) &&\n (viff_info.map_scheme == VFF_MS_NONE))\n {\n double\n max_value;\n\n /*\n Determine scale factor.\n */\n switch ((int) viff_info.data_storage_type)\n {\n case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[0]; break;\n case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[0]; break;\n case VFF_TYP_FLOAT: value=((float *) pixels)[0]; break;\n case VFF_TYP_DOUBLE: value=((double *) pixels)[0]; break;\n default: value=1.0*pixels[0]; break;\n }\n max_value=value;\n min_value=value;\n for (i=0; i < (ssize_t) max_packets; i++)\n {\n switch ((int) viff_info.data_storage_type)\n {\n case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break;\n case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break;\n case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break;\n case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break;\n default: value=1.0*pixels[i]; break;\n }\n if (value > max_value)\n max_value=value;\n else\n if (value < min_value)\n min_value=value;\n }\n if ((min_value == 0) && (max_value == 0))\n scale_factor=0;\n else\n if (min_value == max_value)\n {\n scale_factor=(double) QuantumRange/min_value;\n min_value=0;\n }\n else\n scale_factor=(double) QuantumRange/(max_value-min_value);\n }\n /*\n Convert pixels to Quantum size.\n */\n p=(unsigned char *) pixels;\n for (i=0; i < (ssize_t) max_packets; i++)\n {\n switch ((int) viff_info.data_storage_type)\n {\n case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break;\n case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break;\n case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break;\n case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break;\n default: value=1.0*pixels[i]; break;\n }\n if (viff_info.map_scheme == VFF_MS_NONE)\n {\n value=(value-min_value)*scale_factor;\n if (value > QuantumRange)\n value=QuantumRange;\n else\n if (value < 0)\n value=0;\n }\n *p=(unsigned char) ((Quantum) value);\n p++;\n }\n /*\n Convert VIFF raster image to pixel packets.\n */\n p=(unsigned char *) pixels;\n if (viff_info.data_storage_type == VFF_TYP_BIT)\n {\n /*\n Convert bitmap scanline.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) (image->columns-7); x+=8)\n {\n for (bit=0; bit < 8; bit++)\n {\n quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1);\n SetPixelRed(image,quantum == 0 ? 0 : QuantumRange,q);\n SetPixelGreen(image,quantum == 0 ? 0 : QuantumRange,q);\n SetPixelBlue(image,quantum == 0 ? 0 : QuantumRange,q);\n if (image->storage_class == PseudoClass)\n SetPixelIndex(image,(Quantum) quantum,q);\n q+=GetPixelChannels(image);\n }\n p++;\n }\n if ((image->columns % 8) != 0)\n {\n for (bit=0; bit < (int) (image->columns % 8); bit++)\n {\n quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1);\n SetPixelRed(image,quantum == 0 ? 0 : QuantumRange,q);\n SetPixelGreen(image,quantum == 0 ? 0 : QuantumRange,q);\n SetPixelBlue(image,quantum == 0 ? 0 : QuantumRange,q);\n if (image->storage_class == PseudoClass)\n SetPixelIndex(image,(Quantum) quantum,q);\n q+=GetPixelChannels(image);\n }\n p++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n }\n else\n if (image->storage_class == PseudoClass)\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelIndex(image,*p++,q);\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n else\n {\n /*\n Convert DirectColor scanline.\n */\n number_pixels=(MagickSizeType) image->columns*image->rows;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelRed(image,ScaleCharToQuantum(*p),q);\n SetPixelGreen(image,ScaleCharToQuantum(*(p+number_pixels)),q);\n SetPixelBlue(image,ScaleCharToQuantum(*(p+2*number_pixels)),q);\n if (image->colors != 0)\n {\n ssize_t\n index;\n\n index=(ssize_t) GetPixelRed(image,q);\n SetPixelRed(image,ClampToQuantum(image->colormap[\n ConstrainColormapIndex(image,index,exception)].red),q);\n index=(ssize_t) GetPixelGreen(image,q);\n SetPixelGreen(image,ClampToQuantum(image->colormap[\n ConstrainColormapIndex(image,index,exception)].green),q);\n index=(ssize_t) GetPixelBlue(image,q);\n SetPixelBlue(image,ClampToQuantum(image->colormap[\n ConstrainColormapIndex(image,index,exception)].blue),q);\n }\n SetPixelAlpha(image,image->alpha_trait != UndefinedPixelTrait ?\n ScaleCharToQuantum(*(p+number_pixels*3)) : OpaqueAlpha,q);\n p++;\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n }\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n if (image->storage_class == PseudoClass)\n (void) SyncImage(image,exception);\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n /*\n Proceed to next image.\n */\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n count=ReadBlob(image,1,&viff_info.identifier);\n if ((count == 1) && (viff_info.identifier == 0xab))\n {\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image,exception);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n GetBlobSize(image));\n if (status == MagickFalse)\n break;\n }\n } while ((count != 0) && (viff_info.identifier == 0xab));\n (void) CloseBlob(image);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1600'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadRGBImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n const unsigned char\n *pixels;\n\n Image\n *canvas_image,\n *image;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n scene;\n\n QuantumInfo\n *quantum_info;\n\n QuantumType\n quantum_type;\n\n register ssize_t\n i;\n\n size_t\n length;\n\n ssize_t\n count,\n y;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info);\n if ((image->columns == 0) || (image->rows == 0))\n ThrowReaderException(OptionError,\"MustSpecifyImageSize\");\n if (image_info->interlace != PartitionInterlace)\n {\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n if (DiscardBlobBytes(image,(MagickSizeType) image->offset) == MagickFalse)\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n }\n /*\n Create virtual canvas to support cropping (i.e. image.rgb[100x100+10+20]).\n */\n canvas_image=CloneImage(image,image->extract_info.width,1,MagickFalse,\n exception);\n if (canvas_image == (Image *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) SetImageVirtualPixelMethod(canvas_image,BlackVirtualPixelMethod);\n quantum_info=AcquireQuantumInfo(image_info,canvas_image);\n if (quantum_info == (QuantumInfo *) NULL)\n {\n canvas_image=DestroyImage(canvas_image);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n quantum_type=RGBQuantum;\n if (LocaleCompare(image_info->magick,\"RGBA\") == 0)\n {\n quantum_type=RGBAQuantum;\n image->matte=MagickTrue;\n }\n if (LocaleCompare(image_info->magick,\"RGBO\") == 0)\n {\n quantum_type=RGBOQuantum;\n image->matte=MagickTrue;\n }\n pixels=(const unsigned char *) NULL;\n if (image_info->number_scenes != 0)\n while (image->scene < image_info->scene)\n {\n /*\n Skip to next image.\n */\n image->scene++;\n length=GetQuantumExtent(canvas_image,quantum_info,quantum_type);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n pixels=(const unsigned char *) ReadBlobStream(image,length,\n GetQuantumPixels(quantum_info),&count);\n if (count != (ssize_t) length)\n break;\n }\n }\n count=0;\n length=0;\n scene=0;\n status=MagickTrue;\n do\n {\n /*\n Read pixels to virtual canvas image then push to image.\n */\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n status=SetImageExtent(image,image->columns,image->rows);\n if (status == MagickFalse)\n break;\n switch (image_info->interlace)\n {\n case NoInterlace:\n default:\n {\n /*\n No interlacing: RGBRGBRGBRGBRGBRGB...\n */\n if (scene == 0)\n {\n length=GetQuantumExtent(canvas_image,quantum_info,quantum_type);\n pixels=(const unsigned char *) ReadBlobStream(image,length,\n GetQuantumPixels(quantum_info),&count);\n }\n for (y=0; y < (ssize_t) image->extract_info.height; y++)\n {\n register const PixelPacket\n *magick_restrict p;\n\n register PixelPacket\n *magick_restrict q;\n\n register ssize_t\n x;\n\n if (count != (ssize_t) length)\n {\n status=MagickFalse;\n ThrowFileException(exception,CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n break;\n }\n q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,\n exception);\n if (q == (PixelPacket *) NULL)\n break;\n length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,\n quantum_info,quantum_type,pixels,exception);\n if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)\n break;\n if (((y-image->extract_info.y) >= 0) &&\n ((y-image->extract_info.y) < (ssize_t) image->rows))\n {\n p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0,\n canvas_image->columns,1,exception);\n q=QueueAuthenticPixels(image,0,y-image->extract_info.y,\n image->columns,1,exception);\n if ((p == (const PixelPacket *) NULL) ||\n (q == (PixelPacket *) NULL))\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelRed(q,GetPixelRed(p));\n SetPixelGreen(q,GetPixelGreen(p));\n SetPixelBlue(q,GetPixelBlue(p));\n SetPixelOpacity(q,OpaqueOpacity);\n if (image->matte != MagickFalse)\n SetPixelOpacity(q,GetPixelOpacity(p));\n p++;\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n pixels=(const unsigned char *) ReadBlobStream(image,length,\n GetQuantumPixels(quantum_info),&count);\n }\n break;\n }\n case LineInterlace:\n {\n static QuantumType\n quantum_types[4] =\n {\n RedQuantum,\n GreenQuantum,\n BlueQuantum,\n AlphaQuantum\n };\n\n /*\n Line interlacing: RRR...GGG...BBB...RRR...GGG...BBB...\n */\n if (LocaleCompare(image_info->magick,\"RGBO\") == 0)\n quantum_types[3]=OpacityQuantum;\n if (scene == 0)\n {\n length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum);\n pixels=(const unsigned char *) ReadBlobStream(image,length,\n GetQuantumPixels(quantum_info),&count);\n }\n for (y=0; y < (ssize_t) image->extract_info.height; y++)\n {\n for (i=0; i < (ssize_t) (image->matte != MagickFalse ? 4 : 3); i++)\n {\n register const PixelPacket\n *magick_restrict p;\n\n register PixelPacket\n *magick_restrict q;\n\n register ssize_t\n x;\n\n if (count != (ssize_t) length)\n {\n status=MagickFalse;\n ThrowFileException(exception,CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n break;\n }\n quantum_type=quantum_types[i];\n q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,\n exception);\n if (q == (PixelPacket *) NULL)\n break;\n length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,\n quantum_info,quantum_type,pixels,exception);\n if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)\n break;\n if (((y-image->extract_info.y) >= 0) &&\n ((y-image->extract_info.y) < (ssize_t) image->rows))\n {\n p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,\n 0,canvas_image->columns,1,exception);\n q=GetAuthenticPixels(image,0,y-image->extract_info.y,\n image->columns,1,exception);\n if ((p == (const PixelPacket *) NULL) ||\n (q == (PixelPacket *) NULL))\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n switch (quantum_type)\n {\n case RedQuantum:\n {\n SetPixelRed(q,GetPixelRed(p));\n break;\n }\n case GreenQuantum:\n {\n SetPixelGreen(q,GetPixelGreen(p));\n break;\n }\n case BlueQuantum:\n {\n SetPixelBlue(q,GetPixelBlue(p));\n break;\n }\n case OpacityQuantum:\n {\n SetPixelOpacity(q,GetPixelOpacity(p));\n break;\n }\n case AlphaQuantum:\n {\n SetPixelAlpha(q,GetPixelAlpha(p));\n break;\n }\n default:\n break;\n }\n p++;\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n pixels=(const unsigned char *) ReadBlobStream(image,length,\n GetQuantumPixels(quantum_info),&count);\n if (count != (ssize_t) length)\n break;\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case PlaneInterlace:\n {\n /*\n Plane interlacing: RRRRRR...GGGGGG...BBBBBB...\n */\n if (scene == 0)\n {\n length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum);\n pixels=(const unsigned char *) ReadBlobStream(image,length,\n GetQuantumPixels(quantum_info),&count);\n if (count != (ssize_t) length)\n break;\n }\n for (y=0; y < (ssize_t) image->extract_info.height; y++)\n {\n register const PixelPacket\n *magick_restrict p;\n\n register PixelPacket\n *magick_restrict q;\n\n register ssize_t\n x;\n\n if (count != (ssize_t) length)\n {\n status=MagickFalse;\n ThrowFileException(exception,CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n break;\n }\n q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,\n exception);\n if (q == (PixelPacket *) NULL)\n break;\n length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,\n quantum_info,RedQuantum,pixels,exception);\n if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)\n break;\n if (((y-image->extract_info.y) >= 0) &&\n ((y-image->extract_info.y) < (ssize_t) image->rows))\n {\n p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0,\n canvas_image->columns,1,exception);\n q=GetAuthenticPixels(image,0,y-image->extract_info.y,\n image->columns,1,exception);\n if ((p == (const PixelPacket *) NULL) ||\n (q == (PixelPacket *) NULL))\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelRed(q,GetPixelRed(p));\n p++;\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n pixels=(const unsigned char *) ReadBlobStream(image,length,\n GetQuantumPixels(quantum_info),&count);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,1,6);\n if (status == MagickFalse)\n break;\n }\n for (y=0; y < (ssize_t) image->extract_info.height; y++)\n {\n register const PixelPacket\n *magick_restrict p;\n\n register PixelPacket\n *magick_restrict q;\n\n register ssize_t\n x;\n\n if (count != (ssize_t) length)\n {\n status=MagickFalse;\n ThrowFileException(exception,CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n break;\n }\n q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,\n exception);\n if (q == (PixelPacket *) NULL)\n break;\n length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,\n quantum_info,GreenQuantum,pixels,exception);\n if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)\n break;\n if (((y-image->extract_info.y) >= 0) &&\n ((y-image->extract_info.y) < (ssize_t) image->rows))\n {\n p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0,\n canvas_image->columns,1,exception);\n q=GetAuthenticPixels(image,0,y-image->extract_info.y,\n image->columns,1,exception);\n if ((p == (const PixelPacket *) NULL) ||\n (q == (PixelPacket *) NULL))\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelGreen(q,GetPixelGreen(p));\n p++;\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n pixels=(const unsigned char *) ReadBlobStream(image,length,\n GetQuantumPixels(quantum_info),&count);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,2,6);\n if (status == MagickFalse)\n break;\n }\n for (y=0; y < (ssize_t) image->extract_info.height; y++)\n {\n register const PixelPacket\n *magick_restrict p;\n\n register PixelPacket\n *magick_restrict q;\n\n register ssize_t\n x;\n\n if (count != (ssize_t) length)\n {\n status=MagickFalse;\n ThrowFileException(exception,CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n break;\n }\n q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,\n exception);\n if (q == (PixelPacket *) NULL)\n break;\n length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,\n quantum_info,BlueQuantum,pixels,exception);\n if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)\n break;\n if (((y-image->extract_info.y) >= 0) &&\n ((y-image->extract_info.y) < (ssize_t) image->rows))\n {\n p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0,\n canvas_image->columns,1,exception);\n q=GetAuthenticPixels(image,0,y-image->extract_info.y,\n image->columns,1,exception);\n if ((p == (const PixelPacket *) NULL) ||\n (q == (PixelPacket *) NULL))\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelBlue(q,GetPixelBlue(p));\n p++;\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n pixels=(const unsigned char *) ReadBlobStream(image,length,\n GetQuantumPixels(quantum_info),&count);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,3,6);\n if (status == MagickFalse)\n break;\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,4,6);\n if (status == MagickFalse)\n break;\n }\n if (image->matte != MagickFalse)\n {\n for (y=0; y < (ssize_t) image->extract_info.height; y++)\n {\n register const PixelPacket\n *magick_restrict p;\n\n register PixelPacket\n *magick_restrict q;\n\n register ssize_t\n x;\n\n if (count != (ssize_t) length)\n {\n status=MagickFalse;\n ThrowFileException(exception,CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n break;\n }\n q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,\n exception);\n if (q == (PixelPacket *) NULL)\n break;\n length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,\n quantum_info,AlphaQuantum,pixels,exception);\n if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)\n break;\n if (((y-image->extract_info.y) >= 0) &&\n ((y-image->extract_info.y) < (ssize_t) image->rows))\n {\n p=GetVirtualPixels(canvas_image,\n canvas_image->extract_info.x,0,canvas_image->columns,1,\n exception);\n q=GetAuthenticPixels(image,0,y-image->extract_info.y,\n image->columns,1,exception);\n if ((p == (const PixelPacket *) NULL) ||\n (q == (PixelPacket *) NULL))\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelOpacity(q,GetPixelOpacity(p));\n p++;\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n pixels=(const unsigned char *) ReadBlobStream(image,length,\n GetQuantumPixels(quantum_info),&count);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,5,6);\n if (status == MagickFalse)\n break;\n }\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,6,6);\n if (status == MagickFalse)\n break;\n }\n break;\n }\n case PartitionInterlace:\n {\n /*\n Partition interlacing: RRRRRR..., GGGGGG..., BBBBBB...\n */\n AppendImageFormat(\"R\",image->filename);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n break;\n if (DiscardBlobBytes(image,(MagickSizeType) image->offset) == MagickFalse)\n {\n status=MagickFalse;\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum);\n for (i=0; i < (ssize_t) scene; i++)\n {\n for (y=0; y < (ssize_t) image->extract_info.height; y++)\n {\n (void) ReadBlobStream(image,length,GetQuantumPixels(quantum_info),\n &count);\n if (count != (ssize_t) length)\n break;\n }\n if (count != (ssize_t) length)\n break;\n }\n pixels=(const unsigned char *) ReadBlobStream(image,length,\n GetQuantumPixels(quantum_info),&count);\n for (y=0; y < (ssize_t) image->extract_info.height; y++)\n {\n register const PixelPacket\n *magick_restrict p;\n\n register PixelPacket\n *magick_restrict q;\n\n register ssize_t\n x;\n\n if (count != (ssize_t) length)\n {\n status=MagickFalse;\n ThrowFileException(exception,CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n break;\n }\n q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,\n exception);\n if (q == (PixelPacket *) NULL)\n break;\n length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,\n quantum_info,RedQuantum,pixels,exception);\n if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)\n break;\n if (((y-image->extract_info.y) >= 0) &&\n ((y-image->extract_info.y) < (ssize_t) image->rows))\n {\n p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0,\n canvas_image->columns,1,exception);\n q=GetAuthenticPixels(image,0,y-image->extract_info.y,\n image->columns,1,exception);\n if ((p == (const PixelPacket *) NULL) ||\n (q == (PixelPacket *) NULL))\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelRed(q,GetPixelRed(p));\n p++;\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n pixels=(const unsigned char *) ReadBlobStream(image,length,\n GetQuantumPixels(quantum_info),&count);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,1,5);\n if (status == MagickFalse)\n break;\n }\n (void) CloseBlob(image);\n AppendImageFormat(\"G\",image->filename);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n break;\n length=GetQuantumExtent(canvas_image,quantum_info,GreenQuantum);\n for (i=0; i < (ssize_t) scene; i++)\n {\n for (y=0; y < (ssize_t) image->extract_info.height; y++)\n {\n (void) ReadBlobStream(image,length,GetQuantumPixels(quantum_info),\n &count);\n if (count != (ssize_t) length)\n break;\n }\n if (count != (ssize_t) length)\n break;\n }\n pixels=(const unsigned char *) ReadBlobStream(image,length,\n GetQuantumPixels(quantum_info),&count);\n for (y=0; y < (ssize_t) image->extract_info.height; y++)\n {\n register const PixelPacket\n *magick_restrict p;\n\n register PixelPacket\n *magick_restrict q;\n\n register ssize_t\n x;\n\n if (count != (ssize_t) length)\n {\n status=MagickFalse;\n ThrowFileException(exception,CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n break;\n }\n q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,\n exception);\n if (q == (PixelPacket *) NULL)\n break;\n length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,\n quantum_info,GreenQuantum,pixels,exception);\n if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)\n break;\n if (((y-image->extract_info.y) >= 0) &&\n ((y-image->extract_info.y) < (ssize_t) image->rows))\n {\n p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0,\n canvas_image->columns,1,exception);\n q=GetAuthenticPixels(image,0,y-image->extract_info.y,\n image->columns,1,exception);\n if ((p == (const PixelPacket *) NULL) ||\n (q == (PixelPacket *) NULL))\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelGreen(q,GetPixelGreen(p));\n p++;\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n pixels=(const unsigned char *) ReadBlobStream(image,length,\n GetQuantumPixels(quantum_info),&count);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,2,5);\n if (status == MagickFalse)\n break;\n }\n (void) CloseBlob(image);\n AppendImageFormat(\"B\",image->filename);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n break;\n length=GetQuantumExtent(canvas_image,quantum_info,BlueQuantum);\n for (i=0; i < (ssize_t) scene; i++)\n {\n for (y=0; y < (ssize_t) image->extract_info.height; y++)\n {\n (void) ReadBlobStream(image,length,GetQuantumPixels(quantum_info),\n &count);\n if (count != (ssize_t) length)\n break;\n }\n if (count != (ssize_t) length)\n break;\n }\n pixels=(const unsigned char *) ReadBlobStream(image,length,\n GetQuantumPixels(quantum_info),&count);\n for (y=0; y < (ssize_t) image->extract_info.height; y++)\n {\n register const PixelPacket\n *magick_restrict p;\n\n register PixelPacket\n *magick_restrict q;\n\n register ssize_t\n x;\n\n if (count != (ssize_t) length)\n {\n status=MagickFalse;\n ThrowFileException(exception,CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n break;\n }\n q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,\n exception);\n if (q == (PixelPacket *) NULL)\n break;\n length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,\n quantum_info,BlueQuantum,pixels,exception);\n if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)\n break;\n if (((y-image->extract_info.y) >= 0) &&\n ((y-image->extract_info.y) < (ssize_t) image->rows))\n {\n p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0,\n canvas_image->columns,1,exception);\n q=GetAuthenticPixels(image,0,y-image->extract_info.y,\n image->columns,1,exception);\n if ((p == (const PixelPacket *) NULL) ||\n (q == (PixelPacket *) NULL))\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelBlue(q,GetPixelBlue(p));\n p++;\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n pixels=(const unsigned char *) ReadBlobStream(image,length,\n GetQuantumPixels(quantum_info),&count);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,3,5);\n if (status == MagickFalse)\n break;\n }\n if (image->matte != MagickFalse)\n {\n (void) CloseBlob(image);\n AppendImageFormat(\"A\",image->filename);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n break;\n length=GetQuantumExtent(canvas_image,quantum_info,AlphaQuantum);\n for (i=0; i < (ssize_t) scene; i++)\n {\n for (y=0; y < (ssize_t) image->extract_info.height; y++)\n {\n (void) ReadBlobStream(image,length,GetQuantumPixels(\n quantum_info),&count);\n if (count != (ssize_t) length)\n break;\n }\n if (count != (ssize_t) length)\n break;\n }\n pixels=(const unsigned char *) ReadBlobStream(image,length,\n GetQuantumPixels(quantum_info),&count);\n for (y=0; y < (ssize_t) image->extract_info.height; y++)\n {\n register const PixelPacket\n *magick_restrict p;\n\n register PixelPacket\n *magick_restrict q;\n\n register ssize_t\n x;\n\n if (count != (ssize_t) length)\n {\n status=MagickFalse;\n ThrowFileException(exception,CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n break;\n }\n q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,\n exception);\n if (q == (PixelPacket *) NULL)\n break;\n length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,\n quantum_info,BlueQuantum,pixels,exception);\n if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)\n break;\n if (((y-image->extract_info.y) >= 0) &&\n ((y-image->extract_info.y) < (ssize_t) image->rows))\n {\n p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,\n 0,canvas_image->columns,1,exception);\n q=GetAuthenticPixels(image,0,y-image->extract_info.y,\n image->columns,1,exception);\n if ((p == (const PixelPacket *) NULL) ||\n (q == (PixelPacket *) NULL))\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelOpacity(q,GetPixelOpacity(p));\n p++;\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n pixels=(const unsigned char *) ReadBlobStream(image,length,\n GetQuantumPixels(quantum_info),&count);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,4,5);\n if (status == MagickFalse)\n break;\n }\n }\n (void) CloseBlob(image);\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,5,5);\n if (status == MagickFalse)\n break;\n }\n break;\n }\n }\n if (status == MagickFalse)\n break;\n SetQuantumImageType(image,quantum_type);\n /*\n Proceed to next image.\n */\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n if (count == (ssize_t) length)\n {\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n GetBlobSize(image));\n if (status == MagickFalse)\n break;\n }\n scene++;\n } while (count == (ssize_t) length);\n quantum_info=DestroyQuantumInfo(quantum_info);\n InheritException(&image->exception,&canvas_image->exception);\n canvas_image=DestroyImage(canvas_image);\n (void) CloseBlob(image);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'Fix ultra rare but potential memory-leak'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadYUVImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n Image\n *chroma_image,\n *image,\n *resize_image;\n\n InterlaceType\n interlace;\n\n MagickBooleanType\n status;\n\n register const PixelPacket\n *chroma_pixels;\n\n register ssize_t\n x;\n\n register PixelPacket\n *q;\n\n register unsigned char\n *p;\n\n ssize_t\n count,\n horizontal_factor,\n vertical_factor,\n y;\n\n size_t\n length,\n quantum;\n\n unsigned char\n *scanline;\n\n /*\n Allocate image structure.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info);\n if ((image->columns == 0) || (image->rows == 0))\n ThrowReaderException(OptionError,\"MustSpecifyImageSize\");\n status=SetImageExtent(image,image->columns,image->rows);\n if (status == MagickFalse)\n {\n InheritException(exception,&image->exception);\n return(DestroyImageList(image));\n }\n quantum=(size_t) (image->depth <= 8 ? 1 : 2);\n interlace=image_info->interlace;\n horizontal_factor=2;\n vertical_factor=2;\n if (image_info->sampling_factor != (char *) NULL)\n {\n GeometryInfo\n geometry_info;\n\n MagickStatusType\n flags;\n\n flags=ParseGeometry(image_info->sampling_factor,&geometry_info);\n horizontal_factor=(ssize_t) geometry_info.rho;\n vertical_factor=(ssize_t) geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n vertical_factor=horizontal_factor;\n if ((horizontal_factor != 1) && (horizontal_factor != 2) &&\n (vertical_factor != 1) && (vertical_factor != 2))\n ThrowReaderException(CorruptImageError,\"UnexpectedSamplingFactor\");\n }\n if ((interlace == UndefinedInterlace) ||\n ((interlace == NoInterlace) && (vertical_factor == 2)))\n {\n interlace=NoInterlace; /* CCIR 4:2:2 */\n if (vertical_factor == 2)\n interlace=PlaneInterlace; /* CCIR 4:1:1 */\n }\n if (interlace != PartitionInterlace)\n {\n /*\n Open image file.\n */\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n if (DiscardBlobBytes(image,(MagickSizeType) image->offset) == MagickFalse)\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n }\n /*\n Allocate memory for a scanline.\n */\n if (interlace == NoInterlace)\n scanline=(unsigned char *) AcquireQuantumMemory((size_t) 2UL*\n image->columns+2UL,quantum*sizeof(*scanline));\n else\n scanline=(unsigned char *) AcquireQuantumMemory(image->columns,\n quantum*sizeof(*scanline));\n if (scanline == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n status=MagickTrue;\n do\n {\n chroma_image=CloneImage(image,(image->columns+horizontal_factor-1)/\n horizontal_factor,(image->rows+vertical_factor-1)/vertical_factor,\n MagickTrue,exception);\n if (chroma_image == (Image *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n /*\n Convert raster image to pixel packets.\n */\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n status=SetImageExtent(image,image->columns,image->rows);\n if (status == MagickFalse)\n break;\n if (interlace == PartitionInterlace)\n {\n AppendImageFormat(\"Y\",image->filename);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n }\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register PixelPacket\n *chroma_pixels;\n\n if (interlace == NoInterlace)\n {\n if ((y > 0) || (GetPreviousImageInList(image) == (Image *) NULL))\n {\n length=2*quantum*image->columns;\n count=ReadBlob(image,length,scanline);\n if (count != (ssize_t) length)\n {\n status=MagickFalse;\n ThrowFileException(exception,CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n break;\n }\n }\n p=scanline;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n chroma_pixels=QueueAuthenticPixels(chroma_image,0,y,\n chroma_image->columns,1,exception);\n if (chroma_pixels == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x+=2)\n {\n SetPixelRed(chroma_pixels,0);\n if (quantum == 1)\n SetPixelGreen(chroma_pixels,ScaleCharToQuantum(*p++));\n else\n {\n SetPixelGreen(chroma_pixels,ScaleShortToQuantum(((*p) << 8) |\n *(p+1)));\n p+=2;\n }\n if (quantum == 1)\n SetPixelRed(q,ScaleCharToQuantum(*p++));\n else\n {\n SetPixelRed(q,ScaleShortToQuantum(((*p) << 8) | *(p+1)));\n p+=2;\n }\n SetPixelGreen(q,0);\n SetPixelBlue(q,0);\n q++;\n SetPixelGreen(q,0);\n SetPixelBlue(q,0);\n if (quantum == 1)\n SetPixelBlue(chroma_pixels,ScaleCharToQuantum(*p++));\n else\n {\n SetPixelBlue(chroma_pixels,ScaleShortToQuantum(((*p) << 8) |\n *(p+1)));\n p+=2;\n }\n if (quantum == 1)\n SetPixelRed(q,ScaleCharToQuantum(*p++));\n else\n {\n SetPixelRed(q,ScaleShortToQuantum(((*p) << 8) | *(p+1)));\n p+=2;\n }\n chroma_pixels++;\n q++;\n }\n }\n else\n {\n if ((y > 0) || (GetPreviousImageInList(image) == (Image *) NULL))\n {\n length=quantum*image->columns;\n count=ReadBlob(image,length,scanline);\n if (count != (ssize_t) length)\n {\n status=MagickFalse;\n ThrowFileException(exception,CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n break;\n }\n }\n p=scanline;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (quantum == 1)\n SetPixelRed(q,ScaleCharToQuantum(*p++));\n else\n {\n SetPixelRed(q,ScaleShortToQuantum(((*p) << 8) | *(p+1)));\n p+=2;\n }\n SetPixelGreen(q,0);\n SetPixelBlue(q,0);\n q++;\n }\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (interlace == NoInterlace)\n if (SyncAuthenticPixels(chroma_image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n if (interlace == PartitionInterlace)\n {\n (void) CloseBlob(image);\n AppendImageFormat(\"U\",image->filename);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n }\n if (interlace != NoInterlace)\n {\n for (y=0; y < (ssize_t) chroma_image->rows; y++)\n {\n length=quantum*chroma_image->columns;\n count=ReadBlob(image,length,scanline);\n if (count != (ssize_t) length)\n {\n status=MagickFalse;\n ThrowFileException(exception,CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n break;\n }\n p=scanline;\n q=QueueAuthenticPixels(chroma_image,0,y,chroma_image->columns,1,\n exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) chroma_image->columns; x++)\n {\n SetPixelRed(q,0);\n if (quantum == 1)\n SetPixelGreen(q,ScaleCharToQuantum(*p++));\n else\n {\n SetPixelGreen(q,ScaleShortToQuantum(((*p) << 8) | *(p+1)));\n p+=2;\n }\n SetPixelBlue(q,0);\n q++;\n }\n if (SyncAuthenticPixels(chroma_image,exception) == MagickFalse)\n break;\n }\n if (interlace == PartitionInterlace)\n {\n (void) CloseBlob(image);\n AppendImageFormat(\"V\",image->filename);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n }\n for (y=0; y < (ssize_t) chroma_image->rows; y++)\n {\n length=quantum*chroma_image->columns;\n count=ReadBlob(image,length,scanline);\n if (count != (ssize_t) length)\n {\n status=MagickFalse;\n ThrowFileException(exception,CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n break;\n }\n p=scanline;\n q=GetAuthenticPixels(chroma_image,0,y,chroma_image->columns,1,\n exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) chroma_image->columns; x++)\n {\n if (quantum == 1)\n SetPixelBlue(q,ScaleCharToQuantum(*p++));\n else\n {\n SetPixelBlue(q,ScaleShortToQuantum(((*p) << 8) | *(p+1)));\n p+=2;\n }\n q++;\n }\n if (SyncAuthenticPixels(chroma_image,exception) == MagickFalse)\n break;\n }\n }\n /*\n Scale image.\n */\n resize_image=ResizeImage(chroma_image,image->columns,image->rows,\n TriangleFilter,1.0,exception);\n chroma_image=DestroyImage(chroma_image);\n if (resize_image == (Image *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n chroma_pixels=GetVirtualPixels(resize_image,0,y,resize_image->columns,1,\n &resize_image->exception);\n if ((q == (PixelPacket *) NULL) ||\n (chroma_pixels == (const PixelPacket *) NULL))\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelGreen(q,GetPixelGreen(chroma_pixels));\n SetPixelBlue(q,GetPixelBlue(chroma_pixels));\n chroma_pixels++;\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n resize_image=DestroyImage(resize_image);\n if (SetImageColorspace(image,YCbCrColorspace) == MagickFalse)\n break;\n if (interlace == PartitionInterlace)\n (void) CopyMagickString(image->filename,image_info->filename,\n MaxTextExtent);\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n /*\n Proceed to next image.\n */\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n if (interlace == NoInterlace)\n count=ReadBlob(image,(size_t) (2*quantum*image->columns),scanline);\n else\n count=ReadBlob(image,(size_t) quantum*image->columns,scanline);\n if (count != 0)\n {\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n GetBlobSize(image));\n if (status == MagickFalse)\n break;\n }\n } while (count != 0);\n scanline=(unsigned char *) RelinquishMagickMemory(scanline);\n InheritException(exception,&image->exception);\n (void) CloseBlob(image);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'Fix ultra rare but potential memory-leak'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadTXTImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n char\n colorspace[MaxTextExtent],\n text[MaxTextExtent];\n\n double\n x_offset,\n y_offset;\n\n Image\n *image;\n\n IndexPacket\n *indexes;\n\n MagickBooleanType\n status;\n\n MagickPixelPacket\n pixel;\n\n QuantumAny\n range;\n\n register ssize_t\n i,\n x;\n\n register PixelPacket\n *q;\n\n ssize_t\n count,\n type,\n y;\n\n unsigned long\n depth,\n height,\n max_value,\n width;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n (void) memset(text,0,sizeof(text));\n (void) ReadBlobString(image,text);\n if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) != 0)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n x_offset=(-1.0);\n y_offset=(-1.0);\n do\n {\n width=0;\n height=0;\n max_value=0;\n *colorspace='\\0';\n count=(ssize_t) sscanf(text+32,\"%lu,%lu,%lu,%32s\",&width,&height,&max_value,\n colorspace);\n if ((count != 4) || (width == 0) || (height == 0) || (max_value == 0))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n image->columns=width;\n image->rows=height;\n if ((max_value == 0) || (max_value > 4294967295U))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n for (depth=1; (GetQuantumRange(depth)+1) < max_value; depth++) ;\n image->depth=depth;\n status=SetImageExtent(image,image->columns,image->rows);\n if (status != MagickFalse)\n status=ResetImagePixels(image,&image->exception);\n if (status == MagickFalse)\n {\n InheritException(exception,&image->exception);\n return(DestroyImageList(image));\n }\n LocaleLower(colorspace);\n i=(ssize_t) strlen(colorspace)-1;\n image->matte=MagickFalse;\n if ((i > 0) && (colorspace[i] == 'a'))\n {\n colorspace[i]='\\0';\n image->matte=MagickTrue;\n }\n type=ParseCommandOption(MagickColorspaceOptions,MagickFalse,colorspace);\n if (type < 0)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n image->colorspace=(ColorspaceType) type;\n (void) memset(&pixel,0,sizeof(pixel));\n (void) SetImageBackgroundColor(image);\n range=GetQuantumRange(image->depth);\n status=MagickTrue;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n double\n blue,\n green,\n index,\n opacity,\n red;\n\n if (status == MagickFalse)\n break;\n red=0.0;\n green=0.0;\n blue=0.0;\n index=0.0;\n opacity=0.0;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (ReadBlobString(image,text) == (char *) NULL)\n {\n status=MagickFalse;\n break;\n }\n switch (image->colorspace)\n {\n case LinearGRAYColorspace:\n case GRAYColorspace:\n {\n if (image->matte != MagickFalse)\n {\n (void) sscanf(text,\"%lf,%lf: (%lf%*[%,]%lf%*[%,]\",&x_offset,\n &y_offset,&red,&opacity);\n green=red;\n blue=red;\n break;\n }\n (void) sscanf(text,\"%lf,%lf: (%lf%*[%,]\",&x_offset,&y_offset,&red);\n green=red;\n blue=red;\n break;\n }\n case CMYKColorspace:\n {\n if (image->matte != MagickFalse)\n {\n (void) sscanf(text,\n \"%lf,%lf: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]\",\n &x_offset,&y_offset,&red,&green,&blue,&index,&opacity);\n break;\n }\n (void) sscanf(text,\n \"%lf,%lf: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]\",&x_offset,\n &y_offset,&red,&green,&blue,&index);\n break;\n }\n default:\n {\n if (image->matte != MagickFalse)\n {\n (void) sscanf(text,\n \"%lf,%lf: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]\",\n &x_offset,&y_offset,&red,&green,&blue,&opacity);\n break;\n }\n (void) sscanf(text,\"%lf,%lf: (%lf%*[%,]%lf%*[%,]%lf%*[%,]\",\n &x_offset,&y_offset,&red,&green,&blue);\n break;\n }\n }\n if (strchr(text,'%') != (char *) NULL)\n {\n red*=0.01*range;\n green*=0.01*range;\n blue*=0.01*range;\n index*=0.01*range;\n opacity*=0.01*range;\n }\n if (image->colorspace == LabColorspace)\n {\n green+=(range+1)/2.0;\n blue+=(range+1)/2.0;\n }\n pixel.red=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (red+0.5),\n range);\n pixel.green=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (green+0.5),\n range);\n pixel.blue=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (blue+0.5),\n range);\n pixel.index=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (index+0.5),\n range);\n pixel.opacity=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (opacity+\n 0.5),range);\n q=GetAuthenticPixels(image,(ssize_t) x_offset,(ssize_t) y_offset,1,1,\n exception);\n if (q == (PixelPacket *) NULL)\n continue;\n SetPixelRed(q,pixel.red);\n SetPixelGreen(q,pixel.green);\n SetPixelBlue(q,pixel.blue);\n if (image->colorspace == CMYKColorspace)\n {\n indexes=GetAuthenticIndexQueue(image);\n SetPixelIndex(indexes,pixel.index);\n }\n if (image->matte != MagickFalse)\n SetPixelAlpha(q,pixel.opacity);\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n {\n status=MagickFalse;\n break;\n }\n }\n }\n if (status == MagickFalse)\n break;\n *text='\\0';\n (void) ReadBlobString(image,text);\n if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0)\n {\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n GetBlobSize(image));\n if (status == MagickFalse)\n break;\n }\n } while (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0);\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'Fix ultra rare but potential memory-leak'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: uint64_t hllCount(struct hllhdr *hdr, int *invalid) {\n double m = HLL_REGISTERS;\n double E;\n int j;\n int reghisto[HLL_Q+2] = {0};\n\n /* Compute register histogram */\n if (hdr->encoding == HLL_DENSE) {\n hllDenseRegHisto(hdr->registers,reghisto);\n } else if (hdr->encoding == HLL_SPARSE) {\n hllSparseRegHisto(hdr->registers,\n sdslen((sds)hdr)-HLL_HDR_SIZE,invalid,reghisto);\n } else if (hdr->encoding == HLL_RAW) {\n hllRawRegHisto(hdr->registers,reghisto);\n } else {\n serverPanic(\"Unknown HyperLogLog encoding in hllCount()\");\n }\n\n /* Estimate cardinality form register histogram. See:\n * \"New cardinality estimation algorithms for HyperLogLog sketches\"\n * Otmar Ertl, arXiv:1702.01284 */\n double z = m * hllTau((m-reghisto[HLL_Q+1])/(double)m);\n for (j = HLL_Q; j >= 1; --j) {\n z += reghisto[j];\n z *= 0.5;\n }\n z += m * hllSigma(reghisto[0]/(double)m);\n E = llroundl(HLL_ALPHA_INF*m*m/z);\n\n return (uint64_t) E;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'HyperLogLog: enlarge reghisto variable for safety.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int extract_or_test_files(__G) /* return PK-type error code */\n __GDEF\n{\n unsigned i, j;\n zoff_t cd_bufstart;\n uch *cd_inptr;\n int cd_incnt;\n ulg filnum=0L, blknum=0L;\n int reached_end;\n#ifndef SFX\n int no_endsig_found;\n#endif\n int error, error_in_archive=PK_COOL;\n int *fn_matched=NULL, *xn_matched=NULL;\n zucn_t members_processed;\n ulg num_skipped=0L, num_bad_pwd=0L;\n zoff_t old_extra_bytes = 0L;\n#ifdef SET_DIR_ATTRIB\n unsigned num_dirs=0;\n direntry *dirlist=(direntry *)NULL, **sorted_dirlist=(direntry **)NULL;\n#endif\n\n /*\n * First, two general initializations are applied. These have been moved\n * here from process_zipfiles() because they are only needed for accessing\n * and/or extracting the data content of the zip archive.\n */\n\n /* a) initialize the CRC table pointer (once) */\n if (CRC_32_TAB == NULL) {\n if ((CRC_32_TAB = get_crc_table()) == NULL) {\n return PK_MEM;\n }\n }\n\n#if (!defined(SFX) || defined(SFX_EXDIR))\n /* b) check out if specified extraction root directory exists */\n if (uO.exdir != (char *)NULL && G.extract_flag) {\n G.create_dirs = !uO.fflag;\n if ((error = checkdir(__G__ uO.exdir, ROOT)) > MPN_INF_SKIP) {\n /* out of memory, or file in way */\n return (error == MPN_NOMEM ? PK_MEM : PK_ERR);\n }\n }\n#endif /* !SFX || SFX_EXDIR */\n\n/*---------------------------------------------------------------------------\n The basic idea of this function is as follows. Since the central di-\n rectory lies at the end of the zipfile and the member files lie at the\n beginning or middle or wherever, it is not very desirable to simply\n read a central directory entry, jump to the member and extract it, and\n then jump back to the central directory. In the case of a large zipfile\n this would lead to a whole lot of disk-grinding, especially if each mem-\n ber file is small. Instead, we read from the central directory the per-\n tinent information for a block of files, then go extract/test the whole\n block. Thus this routine contains two small(er) loops within a very\n large outer loop: the first of the small ones reads a block of files\n from the central directory; the second extracts or tests each file; and\n the outer one loops over blocks. There's some file-pointer positioning\n stuff in between, but that's about it. Btw, it's because of this jump-\n ing around that we can afford to be lenient if an error occurs in one of\n the member files: we should still be able to go find the other members,\n since we know the offset of each from the beginning of the zipfile.\n ---------------------------------------------------------------------------*/\n\n G.pInfo = G.info;\n\n#if CRYPT\n G.newzip = TRUE;\n#endif\n#ifndef SFX\n G.reported_backslash = FALSE;\n#endif\n\n /* malloc space for check on unmatched filespecs (OK if one or both NULL) */\n if (G.filespecs > 0 &&\n (fn_matched=(int *)malloc(G.filespecs*sizeof(int))) != (int *)NULL)\n for (i = 0; i < G.filespecs; ++i)\n fn_matched[i] = FALSE;\n if (G.xfilespecs > 0 &&\n (xn_matched=(int *)malloc(G.xfilespecs*sizeof(int))) != (int *)NULL)\n for (i = 0; i < G.xfilespecs; ++i)\n xn_matched[i] = FALSE;\n\n/*---------------------------------------------------------------------------\n Begin main loop over blocks of member files. We know the entire central\n directory is on this disk: we would not have any of this information un-\n less the end-of-central-directory record was on this disk, and we would\n not have gotten to this routine unless this is also the disk on which\n the central directory starts. In practice, this had better be the ONLY\n disk in the archive, but we'll add multi-disk support soon.\n ---------------------------------------------------------------------------*/\n\n members_processed = 0;\n#ifndef SFX\n no_endsig_found = FALSE;\n#endif\n reached_end = FALSE;\n while (!reached_end) {\n j = 0;\n#ifdef AMIGA\n memzero(G.filenotes, DIR_BLKSIZ * sizeof(char *));\n#endif\n\n /*\n * Loop through files in central directory, storing offsets, file\n * attributes, case-conversion and text-conversion flags until block\n * size is reached.\n */\n\n while ((j < DIR_BLKSIZ)) {\n G.pInfo = &G.info[j];\n\n if (readbuf(__G__ G.sig, 4) == 0) {\n error_in_archive = PK_EOF;\n reached_end = TRUE; /* ...so no more left to do */\n break;\n }\n if (memcmp(G.sig, central_hdr_sig, 4)) { /* is it a new entry? */\n /* no new central directory entry\n * -> is the number of processed entries compatible with the\n * number of entries as stored in the end_central record?\n */\n if ((members_processed\n & (G.ecrec.have_ecr64 ? MASK_ZUCN64 : MASK_ZUCN16))\n == G.ecrec.total_entries_central_dir) {\n#ifndef SFX\n /* yes, so look if we ARE back at the end_central record\n */\n no_endsig_found =\n ( (memcmp(G.sig,\n (G.ecrec.have_ecr64 ?\n end_central64_sig : end_central_sig),\n 4) != 0)\n && (!G.ecrec.is_zip64_archive)\n && (memcmp(G.sig, end_central_sig, 4) != 0)\n );\n#endif /* !SFX */\n } else {\n /* no; we have found an error in the central directory\n * -> report it and stop searching for more Zip entries\n */\n Info(slide, 0x401, ((char *)slide,\n LoadFarString(CentSigMsg), j + blknum*DIR_BLKSIZ + 1));\n Info(slide, 0x401, ((char *)slide,\n LoadFarString(ReportMsg)));\n error_in_archive = PK_BADERR;\n }\n reached_end = TRUE; /* ...so no more left to do */\n break;\n }\n /* process_cdir_file_hdr() sets pInfo->hostnum, pInfo->lcflag */\n if ((error = process_cdir_file_hdr(__G)) != PK_COOL) {\n error_in_archive = error; /* only PK_EOF defined */\n reached_end = TRUE; /* ...so no more left to do */\n break;\n }\n if ((error = do_string(__G__ G.crec.filename_length, DS_FN)) !=\n PK_COOL)\n {\n if (error > error_in_archive)\n error_in_archive = error;\n if (error > PK_WARN) { /* fatal: no more left to do */\n Info(slide, 0x401, ((char *)slide,\n LoadFarString(FilNamMsg),\n FnFilter1(G.filename), \"central\"));\n reached_end = TRUE;\n break;\n }\n }\n if ((error = do_string(__G__ G.crec.extra_field_length,\n EXTRA_FIELD)) != 0)\n {\n if (error > error_in_archive)\n error_in_archive = error;\n if (error > PK_WARN) { /* fatal */\n Info(slide, 0x401, ((char *)slide,\n LoadFarString(ExtFieldMsg),\n FnFilter1(G.filename), \"central\"));\n reached_end = TRUE;\n break;\n }\n }\n#ifdef AMIGA\n G.filenote_slot = j;\n if ((error = do_string(__G__ G.crec.file_comment_length,\n uO.N_flag ? FILENOTE : SKIP)) != PK_COOL)\n#else\n if ((error = do_string(__G__ G.crec.file_comment_length, SKIP))\n != PK_COOL)\n#endif\n {\n if (error > error_in_archive)\n error_in_archive = error;\n if (error > PK_WARN) { /* fatal */\n Info(slide, 0x421, ((char *)slide,\n LoadFarString(BadFileCommLength),\n FnFilter1(G.filename)));\n reached_end = TRUE;\n break;\n }\n }\n if (G.process_all_files) {\n if (store_info(__G))\n ++j; /* file is OK; info[] stored; continue with next */\n else\n ++num_skipped;\n } else {\n int do_this_file;\n\n if (G.filespecs == 0)\n do_this_file = TRUE;\n else { /* check if this entry matches an `include' argument */\n do_this_file = FALSE;\n for (i = 0; i < G.filespecs; i++)\n if (match(G.filename, G.pfnames[i], uO.C_flag WISEP)) {\n do_this_file = TRUE; /* ^-- ignore case or not? */\n if (fn_matched)\n fn_matched[i] = TRUE;\n break; /* found match, so stop looping */\n }\n }\n if (do_this_file) { /* check if this is an excluded file */\n for (i = 0; i < G.xfilespecs; i++)\n if (match(G.filename, G.pxnames[i], uO.C_flag WISEP)) {\n do_this_file = FALSE; /* ^-- ignore case or not? */\n if (xn_matched)\n xn_matched[i] = TRUE;\n break;\n }\n }\n if (do_this_file) {\n if (store_info(__G))\n ++j; /* file is OK */\n else\n ++num_skipped; /* unsupp. compression or encryption */\n }\n } /* end if (process_all_files) */\n\n members_processed++;\n\n } /* end while-loop (adding files to current block) */\n\n /* save position in central directory so can come back later */\n cd_bufstart = G.cur_zipfile_bufstart;\n cd_inptr = G.inptr;\n cd_incnt = G.incnt;\n\n /*-----------------------------------------------------------------------\n Second loop: process files in current block, extracting or testing\n each one.\n -----------------------------------------------------------------------*/\n\n error = extract_or_test_entrylist(__G__ j,\n &filnum, &num_bad_pwd, &old_extra_bytes,\n#ifdef SET_DIR_ATTRIB\n &num_dirs, &dirlist,\n#endif\n error_in_archive);\n if (error != PK_COOL) {\n if (error > error_in_archive)\n error_in_archive = error;\n /* ...and keep going (unless disk full or user break) */\n if (G.disk_full > 1 || error_in_archive == IZ_CTRLC) {\n /* clear reached_end to signal premature stop ... */\n reached_end = FALSE;\n /* ... and cancel scanning the central directory */\n break;\n }\n }\n\n\n /*\n * Jump back to where we were in the central directory, then go and do\n * the next batch of files.\n */\n\n#ifdef USE_STRM_INPUT\n zfseeko(G.zipfd, cd_bufstart, SEEK_SET);\n G.cur_zipfile_bufstart = zftello(G.zipfd);\n#else /* !USE_STRM_INPUT */\n G.cur_zipfile_bufstart =\n zlseek(G.zipfd, cd_bufstart, SEEK_SET);\n#endif /* ?USE_STRM_INPUT */\n read(G.zipfd, (char *)G.inbuf, INBUFSIZ); /* been here before... */\n G.inptr = cd_inptr;\n G.incnt = cd_incnt;\n ++blknum;\n\n#ifdef TEST\n printf(\"\\ncd_bufstart = %ld (%.8lXh)\\n\", cd_bufstart, cd_bufstart);\n printf(\"cur_zipfile_bufstart = %ld (%.8lXh)\\n\", cur_zipfile_bufstart,\n cur_zipfile_bufstart);\n printf(\"inptr-inbuf = %d\\n\", G.inptr-G.inbuf);\n printf(\"incnt = %d\\n\\n\", G.incnt);\n#endif\n\n } /* end while-loop (blocks of files in central directory) */\n\n/*---------------------------------------------------------------------------\n Process the list of deferred symlink extractions and finish up\n the symbolic links.\n ---------------------------------------------------------------------------*/\n\n#ifdef SYMLINKS\n if (G.slink_last != NULL) {\n if (QCOND2)\n Info(slide, 0, ((char *)slide, LoadFarString(SymLnkDeferred)));\n while (G.slink_head != NULL) {\n set_deferred_symlink(__G__ G.slink_head);\n /* remove the processed entry from the chain and free its memory */\n G.slink_last = G.slink_head;\n G.slink_head = G.slink_last->next;\n free(G.slink_last);\n }\n G.slink_last = NULL;\n }\n#endif /* SYMLINKS */\n\n/*---------------------------------------------------------------------------\n Go back through saved list of directories, sort and set times/perms/UIDs\n and GIDs from the deepest level on up.\n ---------------------------------------------------------------------------*/\n\n#ifdef SET_DIR_ATTRIB\n if (num_dirs > 0) {\n sorted_dirlist = (direntry **)malloc(num_dirs*sizeof(direntry *));\n if (sorted_dirlist == (direntry **)NULL) {\n Info(slide, 0x401, ((char *)slide,\n LoadFarString(DirlistSortNoMem)));\n while (dirlist != (direntry *)NULL) {\n direntry *d = dirlist;\n\n dirlist = dirlist->next;\n free(d);\n }\n } else {\n ulg ndirs_fail = 0;\n\n if (num_dirs == 1)\n sorted_dirlist[0] = dirlist;\n else {\n for (i = 0; i < num_dirs; ++i) {\n sorted_dirlist[i] = dirlist;\n dirlist = dirlist->next;\n }\n qsort((char *)sorted_dirlist, num_dirs, sizeof(direntry *),\n dircomp);\n }\n\n Trace((stderr, \"setting directory times/perms/attributes\\n\"));\n for (i = 0; i < num_dirs; ++i) {\n direntry *d = sorted_dirlist[i];\n\n Trace((stderr, \"dir = %s\\n\", d->fn));\n if ((error = set_direc_attribs(__G__ d)) != PK_OK) {\n ndirs_fail++;\n Info(slide, 0x201, ((char *)slide,\n LoadFarString(DirlistSetAttrFailed), d->fn));\n if (!error_in_archive)\n error_in_archive = error;\n }\n free(d);\n }\n free(sorted_dirlist);\n if (!uO.tflag && QCOND2) {\n if (ndirs_fail > 0)\n Info(slide, 0, ((char *)slide,\n LoadFarString(DirlistFailAttrSum), ndirs_fail));\n }\n }\n }\n#endif /* SET_DIR_ATTRIB */\n\n/*---------------------------------------------------------------------------\n Check for unmatched filespecs on command line and print warning if any\n found. Free allocated memory. (But suppress check when central dir\n scan was interrupted prematurely.)\n ---------------------------------------------------------------------------*/\n\n if (fn_matched) {\n if (reached_end) for (i = 0; i < G.filespecs; ++i)\n if (!fn_matched[i]) {\n#ifdef DLL\n if (!G.redirect_data && !G.redirect_text)\n Info(slide, 0x401, ((char *)slide,\n LoadFarString(FilenameNotMatched), G.pfnames[i]));\n else\n setFileNotFound(__G);\n#else\n Info(slide, 1, ((char *)slide,\n LoadFarString(FilenameNotMatched), G.pfnames[i]));\n#endif\n if (error_in_archive <= PK_WARN)\n error_in_archive = PK_FIND; /* some files not found */\n }\n free((zvoid *)fn_matched);\n }\n if (xn_matched) {\n if (reached_end) for (i = 0; i < G.xfilespecs; ++i)\n if (!xn_matched[i])\n Info(slide, 0x401, ((char *)slide,\n LoadFarString(ExclFilenameNotMatched), G.pxnames[i]));\n free((zvoid *)xn_matched);\n }\n\n/*---------------------------------------------------------------------------\n Now, all locally allocated memory has been released. When the central\n directory processing has been interrupted prematurely, it is safe to\n return immediately. All completeness checks and summary messages are\n skipped in this case.\n ---------------------------------------------------------------------------*/\n if (!reached_end)\n return error_in_archive;\n\n/*---------------------------------------------------------------------------\n Double-check that we're back at the end-of-central-directory record, and\n print quick summary of results, if we were just testing the archive. We\n send the summary to stdout so that people doing the testing in the back-\n ground and redirecting to a file can just do a \"tail\" on the output file.\n ---------------------------------------------------------------------------*/\n\n#ifndef SFX\n if (no_endsig_found) { /* just to make sure */\n Info(slide, 0x401, ((char *)slide, LoadFarString(EndSigMsg)));\n Info(slide, 0x401, ((char *)slide, LoadFarString(ReportMsg)));\n if (!error_in_archive) /* don't overwrite stronger error */\n error_in_archive = PK_WARN;\n }\n#endif /* !SFX */\n if (uO.tflag) {\n ulg num = filnum - num_bad_pwd;\n\n if (uO.qflag < 2) { /* GRR 930710: was (uO.qflag == 1) */\n if (error_in_archive)\n Info(slide, 0, ((char *)slide, LoadFarString(ErrorInArchive),\n (error_in_archive == PK_WARN)? \"warning-\" : \"\", G.zipfn));\n else if (num == 0L)\n Info(slide, 0, ((char *)slide, LoadFarString(ZeroFilesTested),\n G.zipfn));\n else if (G.process_all_files && (num_skipped+num_bad_pwd == 0L))\n Info(slide, 0, ((char *)slide, LoadFarString(NoErrInCompData),\n G.zipfn));\n else\n Info(slide, 0, ((char *)slide, LoadFarString(NoErrInTestedFiles)\n , G.zipfn, num, (num==1L)? \"\":\"s\"));\n if (num_skipped > 0L)\n Info(slide, 0, ((char *)slide, LoadFarString(FilesSkipped),\n num_skipped, (num_skipped==1L)? \"\":\"s\"));\n#if CRYPT\n if (num_bad_pwd > 0L)\n Info(slide, 0, ((char *)slide, LoadFarString(FilesSkipBadPasswd)\n , num_bad_pwd, (num_bad_pwd==1L)? \"\":\"s\"));\n#endif /* CRYPT */\n }\n }\n\n /* give warning if files not tested or extracted (first condition can still\n * happen if zipfile is empty and no files specified on command line) */\n\n if ((filnum == 0) && error_in_archive <= PK_WARN) {\n if (num_skipped > 0L)\n error_in_archive = IZ_UNSUP; /* unsupport. compression/encryption */\n else\n error_in_archive = PK_FIND; /* no files found at all */\n }\n#if CRYPT\n else if ((filnum == num_bad_pwd) && error_in_archive <= PK_WARN)\n error_in_archive = IZ_BADPWD; /* bad passwd => all files skipped */\n#endif\n else if ((num_skipped > 0L) && error_in_archive <= PK_WARN)\n error_in_archive = IZ_UNSUP; /* was PK_WARN; Jean-loup complained */\n#if CRYPT\n else if ((num_bad_pwd > 0L) && !error_in_archive)\n error_in_archive = PK_WARN;\n#endif\n\n return error_in_archive;\n\n} /* end function extract_or_test_files() */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': 'Detect and reject a zip bomb using overlapped entries.\n\nThis detects an invalid zip file that has at least one entry that\noverlaps with another entry or with the central directory to the\nend of the file. A Fifield zip bomb uses overlapped local entries\nto vastly increase the potential inflation ratio. Such an invalid\nzip file is rejected.\n\nSee https://www.bamsoftware.com/hacks/zipbomb/ for David Fifield's\nanalysis, construction, and examples of such zip bombs.\n\nThe detection maintains a list of covered spans of the zip files\nso far, where the central directory to the end of the file and any\nbytes preceding the first entry at zip file offset zero are\nconsidered covered initially. Then as each entry is decompressed\nor tested, it is considered covered. When a new entry is about to\nbe processed, its initial offset is checked to see if it is\ncontained by a covered span. If so, the zip file is rejected as\ninvalid.\n\nThis commit depends on a preceding commit: \"Fix bug in\nundefer_input() that misplaced the input state.\"'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void l2cap_do_start(struct l2cap_chan *chan)\n{\n\tstruct l2cap_conn *conn = chan->conn;\n\n\tif (conn->hcon->type == LE_LINK) {\n\t\tl2cap_le_start(chan);\n\t\treturn;\n\t}\n\n\tif (!(conn->info_state & L2CAP_INFO_FEAT_MASK_REQ_SENT)) {\n\t\tl2cap_request_info(conn);\n\t\treturn;\n\t}\n\n\tif (!(conn->info_state & L2CAP_INFO_FEAT_MASK_REQ_DONE))\n\t\treturn;\n\n\tif (l2cap_chan_check_security(chan, true) &&\n\t __l2cap_no_conn_pending(chan))\n\t\tl2cap_start_connection(chan);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-327'], 'message': 'Bluetooth: Fix regression with minimum encryption key size alignment\n\nWhen trying to align the minimum encryption key size requirement for\nBluetooth connections, it turns out doing this in a central location in\nthe HCI connection handling code is not possible.\n\nOriginal Bluetooth version up to 2.0 used a security model where the\nL2CAP service would enforce authentication and encryption. Starting\nwith Bluetooth 2.1 and Secure Simple Pairing that model has changed into\nthat the connection initiator is responsible for providing an encrypted\nACL link before any L2CAP communication can happen.\n\nNow connecting Bluetooth 2.1 or later devices with Bluetooth 2.0 and\nbefore devices are causing a regression. The encryption key size check\nneeds to be moved out of the HCI connection handling into the L2CAP\nchannel setup.\n\nTo achieve this, the current check inside hci_conn_security() has been\nmoved into l2cap_check_enc_key_size() helper function and then called\nfrom four decisions point inside L2CAP to cover all combinations of\nSecure Simple Pairing enabled devices and device using legacy pairing\nand legacy service security model.\n\nFixes: d5bb334a8e17 (\"Bluetooth: Align minimum encryption key size for LE and BR/EDR connections\")\nBugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=203643\nSigned-off-by: Marcel Holtmann \nCc: stable@vger.kernel.org\nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void CiffDirectory::readDirectory(const byte* pData,\n uint32_t size,\n ByteOrder byteOrder)\n {\n if (size < 4)\n throw Error(kerCorruptedMetadata);\n uint32_t o = getULong(pData + size - 4, byteOrder);\n if ( o+2 > size )\n throw Error(kerCorruptedMetadata);\n uint16_t count = getUShort(pData + o, byteOrder);\n#ifdef DEBUG\n std::cout << \"Directory at offset \" << std::dec << o\n <<\", \" << count << \" entries \\n\";\n#endif\n o += 2;\n if ( (o + (count * 10)) > size )\n throw Error(kerCorruptedMetadata);\n\n for (uint16_t i = 0; i < count; ++i) {\n uint16_t tag = getUShort(pData + o, byteOrder);\n CiffComponent::AutoPtr m;\n switch (CiffComponent::typeId(tag)) {\n case directory: m = CiffComponent::AutoPtr(new CiffDirectory); break;\n default: m = CiffComponent::AutoPtr(new CiffEntry); break;\n }\n m->setDir(this->tag());\n m->read(pData, size, o, byteOrder);\n add(m);\n o += 10;\n }\n } // CiffDirectory::readDirectory ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Avoid integer overflow.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static opj_bool pi_next_rpcl(opj_pi_iterator_t * pi)\n{\n opj_pi_comp_t *comp = NULL;\n opj_pi_resolution_t *res = NULL;\n long index = 0;\n\n if (!pi->first) {\n goto LABEL_SKIP;\n } else {\n int compno, resno;\n pi->first = 0;\n pi->dx = 0;\n pi->dy = 0;\n for (compno = 0; compno < pi->numcomps; compno++) {\n comp = &pi->comps[compno];\n for (resno = 0; resno < comp->numresolutions; resno++) {\n int dx, dy;\n res = &comp->resolutions[resno];\n dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));\n dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));\n pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);\n pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);\n }\n }\n }\n if (!pi->tp_on) {\n pi->poc.ty0 = pi->ty0;\n pi->poc.tx0 = pi->tx0;\n pi->poc.ty1 = pi->ty1;\n pi->poc.tx1 = pi->tx1;\n }\n for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) {\n for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;\n pi->y += pi->dy - (pi->y % pi->dy)) {\n for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;\n pi->x += pi->dx - (pi->x % pi->dx)) {\n for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {\n int levelno;\n int trx0, try0;\n int trx1, try1;\n int rpx, rpy;\n int prci, prcj;\n comp = &pi->comps[pi->compno];\n if (pi->resno >= comp->numresolutions) {\n continue;\n }\n res = &comp->resolutions[pi->resno];\n levelno = comp->numresolutions - 1 - pi->resno;\n trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);\n try0 = int_ceildiv(pi->ty0, comp->dy << levelno);\n trx1 = int_ceildiv(pi->tx1, comp->dx << levelno);\n try1 = int_ceildiv(pi->ty1, comp->dy << levelno);\n rpx = res->pdx + levelno;\n rpy = res->pdy + levelno;\n if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&\n ((try0 << levelno) % (1 << rpy))))) {\n continue;\n }\n if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&\n ((trx0 << levelno) % (1 << rpx))))) {\n continue;\n }\n\n if ((res->pw == 0) || (res->ph == 0)) {\n continue;\n }\n\n if ((trx0 == trx1) || (try0 == try1)) {\n continue;\n }\n\n prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx)\n - int_floordivpow2(trx0, res->pdx);\n prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy)\n - int_floordivpow2(try0, res->pdy);\n pi->precno = prci + prcj * res->pw;\n for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {\n index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *\n pi->step_c + pi->precno * pi->step_p;\n if (!pi->include[index]) {\n pi->include[index] = 1;\n return OPJ_TRUE;\n }\nLABEL_SKIP:\n ;\n }\n }\n }\n }\n }\n\n return OPJ_FALSE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-369'], 'message': '[MJ2] To avoid divisions by zero / undefined behaviour on shift\n\nSigned-off-by: Young_X '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: xsltFormatNumberConversion(xsltDecimalFormatPtr self,\n\t\t\t xmlChar *format,\n\t\t\t double number,\n\t\t\t xmlChar **result)\n{\n xmlXPathError status = XPATH_EXPRESSION_OK;\n xmlBufferPtr buffer;\n xmlChar *the_format, *prefix = NULL, *suffix = NULL;\n xmlChar *nprefix, *nsuffix = NULL;\n xmlChar pchar;\n int\t prefix_length, suffix_length = 0, nprefix_length, nsuffix_length;\n double scale;\n int\t j, len;\n int self_grouping_len;\n xsltFormatNumberInfo format_info;\n /*\n * delayed_multiplier allows a 'trailing' percent or\n * permille to be treated as suffix\n */\n int\t\tdelayed_multiplier = 0;\n /* flag to show no -ve format present for -ve number */\n char\tdefault_sign = 0;\n /* flag to show error found, should use default format */\n char\tfound_error = 0;\n\n if (xmlStrlen(format) <= 0) {\n\txsltTransformError(NULL, NULL, NULL,\n \"xsltFormatNumberConversion : \"\n\t\t\"Invalid format (0-length)\\n\");\n }\n *result = NULL;\n switch (xmlXPathIsInf(number)) {\n\tcase -1:\n\t if (self->minusSign == NULL)\n\t\t*result = xmlStrdup(BAD_CAST \"-\");\n\t else\n\t\t*result = xmlStrdup(self->minusSign);\n\t /* no-break on purpose */\n\tcase 1:\n\t if ((self == NULL) || (self->infinity == NULL))\n\t\t*result = xmlStrcat(*result, BAD_CAST \"Infinity\");\n\t else\n\t\t*result = xmlStrcat(*result, self->infinity);\n\t return(status);\n\tdefault:\n\t if (xmlXPathIsNaN(number)) {\n\t\tif ((self == NULL) || (self->noNumber == NULL))\n\t\t *result = xmlStrdup(BAD_CAST \"NaN\");\n\t\telse\n\t\t *result = xmlStrdup(self->noNumber);\n\t\treturn(status);\n\t }\n }\n\n buffer = xmlBufferCreate();\n if (buffer == NULL) {\n\treturn XPATH_MEMORY_ERROR;\n }\n\n format_info.integer_hash = 0;\n format_info.integer_digits = 0;\n format_info.frac_digits = 0;\n format_info.frac_hash = 0;\n format_info.group = -1;\n format_info.multiplier = 1;\n format_info.add_decimal = FALSE;\n format_info.is_multiplier_set = FALSE;\n format_info.is_negative_pattern = FALSE;\n\n the_format = format;\n\n /*\n * First we process the +ve pattern to get percent / permille,\n * as well as main format\n */\n prefix = the_format;\n prefix_length = xsltFormatNumberPreSuffix(self, &the_format, &format_info);\n if (prefix_length < 0) {\n\tfound_error = 1;\n\tgoto OUTPUT_NUMBER;\n }\n\n /*\n * Here we process the \"number\" part of the format. It gets\n * a little messy because of the percent/per-mille - if that\n * appears at the end, it may be part of the suffix instead\n * of part of the number, so the variable delayed_multiplier\n * is used to handle it\n */\n self_grouping_len = xmlStrlen(self->grouping);\n while ((*the_format != 0) &&\n\t (xsltUTF8Charcmp(the_format, self->decimalPoint) != 0) &&\n\t (xsltUTF8Charcmp(the_format, self->patternSeparator) != 0)) {\n\n\tif (delayed_multiplier != 0) {\n\t format_info.multiplier = delayed_multiplier;\n\t format_info.is_multiplier_set = TRUE;\n\t delayed_multiplier = 0;\n\t}\n\tif (xsltUTF8Charcmp(the_format, self->digit) == 0) {\n\t if (format_info.integer_digits > 0) {\n\t\tfound_error = 1;\n\t\tgoto OUTPUT_NUMBER;\n\t }\n\t format_info.integer_hash++;\n\t if (format_info.group >= 0)\n\t\tformat_info.group++;\n\t} else if (xsltUTF8Charcmp(the_format, self->zeroDigit) == 0) {\n\t format_info.integer_digits++;\n\t if (format_info.group >= 0)\n\t\tformat_info.group++;\n\t} else if ((self_grouping_len > 0) &&\n\t (!xmlStrncmp(the_format, self->grouping, self_grouping_len))) {\n\t /* Reset group count */\n\t format_info.group = 0;\n\t the_format += self_grouping_len;\n\t continue;\n\t} else if (xsltUTF8Charcmp(the_format, self->percent) == 0) {\n\t if (format_info.is_multiplier_set) {\n\t\tfound_error = 1;\n\t\tgoto OUTPUT_NUMBER;\n\t }\n\t delayed_multiplier = 100;\n\t} else if (xsltUTF8Charcmp(the_format, self->permille) == 0) {\n\t if (format_info.is_multiplier_set) {\n\t\tfound_error = 1;\n\t\tgoto OUTPUT_NUMBER;\n\t }\n\t delayed_multiplier = 1000;\n\t} else\n\t break; /* while */\n\n\tif ((len=xmlUTF8Strsize(the_format, 1)) < 1) {\n\t found_error = 1;\n\t goto OUTPUT_NUMBER;\n\t}\n\tthe_format += len;\n\n }\n\n /* We have finished the integer part, now work on fraction */\n if ( (*the_format != 0) &&\n (xsltUTF8Charcmp(the_format, self->decimalPoint) == 0) ) {\n format_info.add_decimal = TRUE;\n if ((len = xmlUTF8Strsize(the_format, 1)) < 1) {\n found_error = 1;\n goto OUTPUT_NUMBER;\n }\n\tthe_format += len;\t/* Skip over the decimal */\n }\n\n while (*the_format != 0) {\n\n\tif (xsltUTF8Charcmp(the_format, self->zeroDigit) == 0) {\n\t if (format_info.frac_hash != 0) {\n\t\tfound_error = 1;\n\t\tgoto OUTPUT_NUMBER;\n\t }\n\t format_info.frac_digits++;\n\t} else if (xsltUTF8Charcmp(the_format, self->digit) == 0) {\n\t format_info.frac_hash++;\n\t} else if (xsltUTF8Charcmp(the_format, self->percent) == 0) {\n\t if (format_info.is_multiplier_set) {\n\t\tfound_error = 1;\n\t\tgoto OUTPUT_NUMBER;\n\t }\n\t delayed_multiplier = 100;\n\t if ((len = xmlUTF8Strsize(the_format, 1)) < 1) {\n\t found_error = 1;\n\t\tgoto OUTPUT_NUMBER;\n\t }\n\t the_format += len;\n\t continue; /* while */\n\t} else if (xsltUTF8Charcmp(the_format, self->permille) == 0) {\n\t if (format_info.is_multiplier_set) {\n\t\tfound_error = 1;\n\t\tgoto OUTPUT_NUMBER;\n\t }\n\t delayed_multiplier = 1000;\n\t if ((len = xmlUTF8Strsize(the_format, 1)) < 1) {\n\t found_error = 1;\n\t\tgoto OUTPUT_NUMBER;\n\t }\n\t the_format += len;\n\t continue; /* while */\n\t} else if (xsltUTF8Charcmp(the_format, self->grouping) != 0) {\n\t break; /* while */\n\t}\n\tif ((len = xmlUTF8Strsize(the_format, 1)) < 1) {\n\t found_error = 1;\n\t goto OUTPUT_NUMBER;\n\t}\n\tthe_format += len;\n\tif (delayed_multiplier != 0) {\n\t format_info.multiplier = delayed_multiplier;\n\t delayed_multiplier = 0;\n\t format_info.is_multiplier_set = TRUE;\n\t}\n }\n\n /*\n * If delayed_multiplier is set after processing the\n * \"number\" part, should be in suffix\n */\n if (delayed_multiplier != 0) {\n\tthe_format -= len;\n\tdelayed_multiplier = 0;\n }\n\n suffix = the_format;\n suffix_length = xsltFormatNumberPreSuffix(self, &the_format, &format_info);\n if ( (suffix_length < 0) ||\n\t ((*the_format != 0) &&\n\t (xsltUTF8Charcmp(the_format, self->patternSeparator) != 0)) ) {\n\tfound_error = 1;\n\tgoto OUTPUT_NUMBER;\n }\n\n /*\n * We have processed the +ve prefix, number part and +ve suffix.\n * If the number is -ve, we must substitute the -ve prefix / suffix\n */\n if (number < 0) {\n /*\n\t * Note that j is the number of UTF8 chars before the separator,\n\t * not the number of bytes! (bug 151975)\n\t */\n j = xmlUTF8Strloc(format, self->patternSeparator);\n\tif (j < 0) {\n\t/* No -ve pattern present, so use default signing */\n\t default_sign = 1;\n\t}\n\telse {\n\t /* Skip over pattern separator (accounting for UTF8) */\n\t the_format = (xmlChar *)xmlUTF8Strpos(format, j + 1);\n\t /*\n\t * Flag changes interpretation of percent/permille\n\t * in -ve pattern\n\t */\n\t format_info.is_negative_pattern = TRUE;\n\t format_info.is_multiplier_set = FALSE;\n\n\t /* First do the -ve prefix */\n\t nprefix = the_format;\n\t nprefix_length = xsltFormatNumberPreSuffix(self,\n\t\t\t\t\t&the_format, &format_info);\n\t if (nprefix_length<0) {\n\t\tfound_error = 1;\n\t\tgoto OUTPUT_NUMBER;\n\t }\n\n\t while (*the_format != 0) {\n\t\tif ( (xsltUTF8Charcmp(the_format, (self)->percent) == 0) ||\n\t\t (xsltUTF8Charcmp(the_format, (self)->permille)== 0) ) {\n\t\t if (format_info.is_multiplier_set) {\n\t\t\tfound_error = 1;\n\t\t\tgoto OUTPUT_NUMBER;\n\t\t }\n\t\t format_info.is_multiplier_set = TRUE;\n\t\t delayed_multiplier = 1;\n\t\t}\n\t\telse if (IS_SPECIAL(self, the_format))\n\t\t delayed_multiplier = 0;\n\t\telse\n\t\t break; /* while */\n\t\tif ((len = xmlUTF8Strsize(the_format, 1)) < 1) {\n\t\t found_error = 1;\n\t\t goto OUTPUT_NUMBER;\n\t\t}\n\t\tthe_format += len;\n\t }\n\t if (delayed_multiplier != 0) {\n\t\tformat_info.is_multiplier_set = FALSE;\n\t\tthe_format -= len;\n\t }\n\n\t /* Finally do the -ve suffix */\n\t if (*the_format != 0) {\n\t\tnsuffix = the_format;\n\t\tnsuffix_length = xsltFormatNumberPreSuffix(self,\n\t\t\t\t\t&the_format, &format_info);\n\t\tif (nsuffix_length < 0) {\n\t\t found_error = 1;\n\t\t goto OUTPUT_NUMBER;\n\t\t}\n\t }\n\t else\n\t\tnsuffix_length = 0;\n\t if (*the_format != 0) {\n\t\tfound_error = 1;\n\t\tgoto OUTPUT_NUMBER;\n\t }\n\t /*\n\t * Here's another Java peculiarity:\n\t * if -ve prefix/suffix == +ve ones, discard & use default\n\t */\n\t if ((nprefix_length != prefix_length) ||\n\t\t(nsuffix_length != suffix_length) ||\n\t\t((nprefix_length > 0) &&\n\t\t (xmlStrncmp(nprefix, prefix, prefix_length) !=0 )) ||\n\t\t((nsuffix_length > 0) &&\n\t\t (xmlStrncmp(nsuffix, suffix, suffix_length) !=0 ))) {\n\t\tprefix = nprefix;\n\t\tprefix_length = nprefix_length;\n\t\tsuffix = nsuffix;\n\t\tsuffix_length = nsuffix_length;\n\t } /* else {\n\t\tdefault_sign = 1;\n\t }\n\t */\n\t}\n }\n\nOUTPUT_NUMBER:\n if (found_error != 0) {\n\txsltTransformError(NULL, NULL, NULL,\n \"xsltFormatNumberConversion : \"\n\t\t\"error in format string '%s', using default\\n\", format);\n\tdefault_sign = (number < 0.0) ? 1 : 0;\n\tprefix_length = suffix_length = 0;\n\tformat_info.integer_hash = 0;\n\tformat_info.integer_digits = 1;\n\tformat_info.frac_digits = 1;\n\tformat_info.frac_hash = 4;\n\tformat_info.group = -1;\n\tformat_info.multiplier = 1;\n\tformat_info.add_decimal = TRUE;\n }\n\n /* Ready to output our number. First see if \"default sign\" is required */\n if (default_sign != 0)\n\txmlBufferAdd(buffer, self->minusSign, xmlUTF8Strsize(self->minusSign, 1));\n\n /* Put the prefix into the buffer */\n for (j = 0; j < prefix_length; j++) {\n\tif ((pchar = *prefix++) == SYMBOL_QUOTE) {\n\t len = xmlUTF8Strsize(prefix, 1);\n\t xmlBufferAdd(buffer, prefix, len);\n\t prefix += len;\n\t j += len - 1;\t/* length of symbol less length of quote */\n\t} else\n\t xmlBufferAdd(buffer, &pchar, 1);\n }\n\n /* Next do the integer part of the number */\n number = fabs(number) * (double)format_info.multiplier;\n scale = pow(10.0, (double)(format_info.frac_digits + format_info.frac_hash));\n number = floor((scale * number + 0.5)) / scale;\n if ((self->grouping != NULL) &&\n (self->grouping[0] != 0)) {\n\n\tlen = xmlStrlen(self->grouping);\n\tpchar = xsltGetUTF8Char(self->grouping, &len);\n\txsltNumberFormatDecimal(buffer, floor(number), self->zeroDigit[0],\n\t\t\t\tformat_info.integer_digits,\n\t\t\t\tformat_info.group,\n\t\t\t\tpchar, len);\n } else\n\txsltNumberFormatDecimal(buffer, floor(number), self->zeroDigit[0],\n\t\t\t\tformat_info.integer_digits,\n\t\t\t\tformat_info.group,\n\t\t\t\t',', 1);\n\n /* Special case: java treats '.#' like '.0', '.##' like '.0#', etc. */\n if ((format_info.integer_digits + format_info.integer_hash +\n\t format_info.frac_digits == 0) && (format_info.frac_hash > 0)) {\n ++format_info.frac_digits;\n\t--format_info.frac_hash;\n }\n\n /* Add leading zero, if required */\n if ((floor(number) == 0) &&\n\t(format_info.integer_digits + format_info.frac_digits == 0)) {\n xmlBufferAdd(buffer, self->zeroDigit, xmlUTF8Strsize(self->zeroDigit, 1));\n }\n\n /* Next the fractional part, if required */\n if (format_info.frac_digits + format_info.frac_hash == 0) {\n if (format_info.add_decimal)\n\t xmlBufferAdd(buffer, self->decimalPoint,\n\t\t\t xmlUTF8Strsize(self->decimalPoint, 1));\n }\n else {\n number -= floor(number);\n\tif ((number != 0) || (format_info.frac_digits != 0)) {\n\t xmlBufferAdd(buffer, self->decimalPoint,\n\t\t\t xmlUTF8Strsize(self->decimalPoint, 1));\n\t number = floor(scale * number + 0.5);\n\t for (j = format_info.frac_hash; j > 0; j--) {\n\t\tif (fmod(number, 10.0) >= 1.0)\n\t\t break; /* for */\n\t\tnumber /= 10.0;\n\t }\n\t xsltNumberFormatDecimal(buffer, floor(number), self->zeroDigit[0],\n\t\t\t\tformat_info.frac_digits + j,\n\t\t\t\t0, 0, 0);\n\t}\n }\n /* Put the suffix into the buffer */\n for (j = 0; j < suffix_length; j++) {\n\tif ((pchar = *suffix++) == SYMBOL_QUOTE) {\n len = xmlUTF8Strsize(suffix, 1);\n\t xmlBufferAdd(buffer, suffix, len);\n\t suffix += len;\n\t j += len - 1;\t/* length of symbol less length of escape */\n\t} else\n\t xmlBufferAdd(buffer, &pchar, 1);\n }\n\n *result = xmlStrdup(xmlBufferContent(buffer));\n xmlBufferFree(buffer);\n return status;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-843'], 'message': 'Fix uninitialized read with UTF-8 grouping chars\n\nThe character type in xsltFormatNumberConversion was too narrow and\nan invalid character/length combination could be passed to\nxsltNumberFormatDecimal, resulting in an uninitialized read.\n\nFound by OSS-Fuzz.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: compile_length_bag_node(BagNode* node, regex_t* reg)\n{\n int len;\n int tlen;\n\n if (node->type == BAG_OPTION)\n return compile_length_option_node(node, reg);\n\n if (NODE_BAG_BODY(node)) {\n tlen = compile_length_tree(NODE_BAG_BODY(node), reg);\n if (tlen < 0) return tlen;\n }\n else\n tlen = 0;\n\n switch (node->type) {\n case BAG_MEMORY:\n#ifdef USE_CALL\n\n if (node->m.regnum == 0 && NODE_IS_CALLED(node)) {\n len = tlen + SIZE_OP_CALL + SIZE_OP_JUMP + SIZE_OP_RETURN;\n return len;\n }\n\n if (NODE_IS_CALLED(node)) {\n len = SIZE_OP_MEMORY_START_PUSH + tlen\n + SIZE_OP_CALL + SIZE_OP_JUMP + SIZE_OP_RETURN;\n if (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum))\n len += (NODE_IS_RECURSION(node)\n ? SIZE_OP_MEMORY_END_PUSH_REC : SIZE_OP_MEMORY_END_PUSH);\n else\n len += (NODE_IS_RECURSION(node)\n ? SIZE_OP_MEMORY_END_REC : SIZE_OP_MEMORY_END);\n }\n else if (NODE_IS_RECURSION(node)) {\n len = SIZE_OP_MEMORY_START_PUSH;\n len += tlen + (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum)\n ? SIZE_OP_MEMORY_END_PUSH_REC : SIZE_OP_MEMORY_END_REC);\n }\n else\n#endif\n {\n if (MEM_STATUS_AT0(reg->bt_mem_start, node->m.regnum))\n len = SIZE_OP_MEMORY_START_PUSH;\n else\n len = SIZE_OP_MEMORY_START;\n\n len += tlen + (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum)\n ? SIZE_OP_MEMORY_END_PUSH : SIZE_OP_MEMORY_END);\n }\n break;\n\n case BAG_STOP_BACKTRACK:\n if (NODE_IS_STOP_BT_SIMPLE_REPEAT(node)) {\n int v;\n QuantNode* qn;\n\n qn = QUANT_(NODE_BAG_BODY(node));\n tlen = compile_length_tree(NODE_QUANT_BODY(qn), reg);\n if (tlen < 0) return tlen;\n\n v = onig_positive_int_multiply(qn->lower, tlen);\n if (v < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE;\n len = v + SIZE_OP_PUSH + tlen + SIZE_OP_POP_OUT + SIZE_OP_JUMP;\n }\n else {\n len = SIZE_OP_ATOMIC_START + tlen + SIZE_OP_ATOMIC_END;\n }\n break;\n\n case BAG_IF_ELSE:\n {\n Node* cond = NODE_BAG_BODY(node);\n Node* Then = node->te.Then;\n Node* Else = node->te.Else;\n\n len = compile_length_tree(cond, reg);\n if (len < 0) return len;\n len += SIZE_OP_PUSH;\n len += SIZE_OP_ATOMIC_START + SIZE_OP_ATOMIC_END;\n\n if (IS_NOT_NULL(Then)) {\n tlen = compile_length_tree(Then, reg);\n if (tlen < 0) return tlen;\n len += tlen;\n }\n\n if (IS_NOT_NULL(Else)) {\n len += SIZE_OP_JUMP;\n tlen = compile_length_tree(Else, reg);\n if (tlen < 0) return tlen;\n len += tlen;\n }\n }\n break;\n\n case BAG_OPTION:\n /* never come here, but set for escape warning */\n len = 0;\n break;\n }\n\n return len;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-125'], 'message': 'Fix CVE-2019-13225: problem in converting if-then-else pattern to bytecode.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: WandExport MagickBooleanType MogrifyImageList(ImageInfo *image_info,\n const int argc,const char **argv,Image **images,ExceptionInfo *exception)\n{\n const char\n *option;\n\n ImageInfo\n *mogrify_info;\n\n MagickStatusType\n status;\n\n PixelInterpolateMethod\n interpolate_method;\n\n QuantizeInfo\n *quantize_info;\n\n register ssize_t\n i;\n\n ssize_t\n count,\n index;\n\n /*\n Apply options to the image list.\n */\n assert(image_info != (ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(images != (Image **) NULL);\n assert((*images)->previous == (Image *) NULL);\n assert((*images)->signature == MagickCoreSignature);\n if ((*images)->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n (*images)->filename);\n if ((argc <= 0) || (*argv == (char *) NULL))\n return(MagickTrue);\n interpolate_method=UndefinedInterpolatePixel;\n mogrify_info=CloneImageInfo(image_info);\n quantize_info=AcquireQuantizeInfo(mogrify_info);\n status=MagickTrue;\n for (i=0; i < (ssize_t) argc; i++)\n {\n if (*images == (Image *) NULL)\n break;\n option=argv[i];\n if (IsCommandOption(option) == MagickFalse)\n continue;\n count=ParseCommandOption(MagickCommandOptions,MagickFalse,option);\n count=MagickMax(count,0L);\n if ((i+count) >= (ssize_t) argc)\n break;\n status=MogrifyImageInfo(mogrify_info,(int) count+1,argv+i,exception);\n switch (*(option+1))\n {\n case 'a':\n {\n if (LocaleCompare(\"affinity\",option+1) == 0)\n {\n (void) SyncImagesSettings(mogrify_info,*images,exception);\n if (*option == '+')\n {\n (void) RemapImages(quantize_info,*images,(Image *) NULL,\n exception);\n break;\n }\n i++;\n break;\n }\n if (LocaleCompare(\"append\",option+1) == 0)\n {\n Image\n *append_image;\n\n (void) SyncImagesSettings(mogrify_info,*images,exception);\n append_image=AppendImages(*images,*option == '-' ? MagickTrue :\n MagickFalse,exception);\n if (append_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n *images=DestroyImageList(*images);\n *images=append_image;\n break;\n }\n if (LocaleCompare(\"average\",option+1) == 0)\n {\n Image\n *average_image;\n\n /*\n Average an image sequence (deprecated).\n */\n (void) SyncImagesSettings(mogrify_info,*images,exception);\n average_image=EvaluateImages(*images,MeanEvaluateOperator,\n exception);\n if (average_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n *images=DestroyImageList(*images);\n *images=average_image;\n break;\n }\n break;\n }\n case 'c':\n {\n if (LocaleCompare(\"channel-fx\",option+1) == 0)\n {\n Image\n *channel_image;\n\n (void) SyncImagesSettings(mogrify_info,*images,exception);\n channel_image=ChannelFxImage(*images,argv[i+1],exception);\n if (channel_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n *images=DestroyImageList(*images);\n *images=channel_image;\n break;\n }\n if (LocaleCompare(\"clut\",option+1) == 0)\n {\n Image\n *clut_image,\n *image;\n\n (void) SyncImagesSettings(mogrify_info,*images,exception);\n image=RemoveFirstImageFromList(images);\n clut_image=RemoveFirstImageFromList(images);\n if (clut_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n (void) ClutImage(image,clut_image,interpolate_method,exception);\n clut_image=DestroyImage(clut_image);\n *images=DestroyImageList(*images);\n *images=image;\n break;\n }\n if (LocaleCompare(\"coalesce\",option+1) == 0)\n {\n Image\n *coalesce_image;\n\n (void) SyncImagesSettings(mogrify_info,*images,exception);\n coalesce_image=CoalesceImages(*images,exception);\n if (coalesce_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n *images=DestroyImageList(*images);\n *images=coalesce_image;\n break;\n }\n if (LocaleCompare(\"combine\",option+1) == 0)\n {\n ColorspaceType\n colorspace;\n\n Image\n *combine_image;\n\n (void) SyncImagesSettings(mogrify_info,*images,exception);\n colorspace=(*images)->colorspace;\n if ((*images)->number_channels < GetImageListLength(*images))\n colorspace=sRGBColorspace;\n if (*option == '+')\n colorspace=(ColorspaceType) ParseCommandOption(\n MagickColorspaceOptions,MagickFalse,argv[i+1]);\n combine_image=CombineImages(*images,colorspace,exception);\n if (combine_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n *images=DestroyImageList(*images);\n *images=combine_image;\n break;\n }\n if (LocaleCompare(\"compare\",option+1) == 0)\n {\n double\n distortion;\n\n Image\n *difference_image,\n *image,\n *reconstruct_image;\n\n MetricType\n metric;\n\n /*\n Mathematically and visually annotate the difference between an\n image and its reconstruction.\n */\n (void) SyncImagesSettings(mogrify_info,*images,exception);\n image=RemoveFirstImageFromList(images);\n reconstruct_image=RemoveFirstImageFromList(images);\n if (reconstruct_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n metric=UndefinedErrorMetric;\n option=GetImageOption(mogrify_info,\"metric\");\n if (option != (const char *) NULL)\n metric=(MetricType) ParseCommandOption(MagickMetricOptions,\n MagickFalse,option);\n difference_image=CompareImages(image,reconstruct_image,metric,\n &distortion,exception);\n if (difference_image == (Image *) NULL)\n break;\n if (*images != (Image *) NULL)\n *images=DestroyImageList(*images);\n *images=difference_image;\n break;\n }\n if (LocaleCompare(\"complex\",option+1) == 0)\n {\n ComplexOperator\n op;\n\n Image\n *complex_images;\n\n (void) SyncImageSettings(mogrify_info,*images,exception);\n op=(ComplexOperator) ParseCommandOption(MagickComplexOptions,\n MagickFalse,argv[i+1]);\n complex_images=ComplexImages(*images,op,exception);\n if (complex_images == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n *images=DestroyImageList(*images);\n *images=complex_images;\n break;\n }\n if (LocaleCompare(\"composite\",option+1) == 0)\n {\n CompositeOperator\n compose;\n\n const char*\n value;\n\n MagickBooleanType\n clip_to_self;\n\n Image\n *mask_image,\n *new_images,\n *source_image;\n\n RectangleInfo\n geometry;\n\n /* Compose value from \"-compose\" option only */\n (void) SyncImageSettings(mogrify_info,*images,exception);\n value=GetImageOption(mogrify_info,\"compose\");\n if (value == (const char *) NULL)\n compose=OverCompositeOp; /* use Over not source_image->compose */\n else\n compose=(CompositeOperator) ParseCommandOption(\n MagickComposeOptions,MagickFalse,value);\n\n /* Get \"clip-to-self\" expert setting (false is normal) */\n clip_to_self=GetCompositeClipToSelf(compose);\n value=GetImageOption(mogrify_info,\"compose:clip-to-self\");\n if (value != (const char *) NULL)\n clip_to_self=IsStringTrue(value);\n value=GetImageOption(mogrify_info,\"compose:outside-overlay\");\n if (value != (const char *) NULL)\n clip_to_self=IsStringFalse(value); /* deprecated */\n\n new_images=RemoveFirstImageFromList(images);\n source_image=RemoveFirstImageFromList(images);\n if (source_image == (Image *) NULL)\n break; /* FUTURE - produce Exception, rather than silent fail */\n\n /* FUTURE: this should not be here! - should be part of -geometry */\n if (source_image->geometry != (char *) NULL)\n {\n RectangleInfo\n resize_geometry;\n\n (void) ParseRegionGeometry(source_image,source_image->geometry,\n &resize_geometry,exception);\n if ((source_image->columns != resize_geometry.width) ||\n (source_image->rows != resize_geometry.height))\n {\n Image\n *resize_image;\n\n resize_image=ResizeImage(source_image,resize_geometry.width,\n resize_geometry.height,source_image->filter,exception);\n if (resize_image != (Image *) NULL)\n {\n source_image=DestroyImage(source_image);\n source_image=resize_image;\n }\n }\n }\n SetGeometry(source_image,&geometry);\n (void) ParseAbsoluteGeometry(source_image->geometry,&geometry);\n GravityAdjustGeometry(new_images->columns,new_images->rows,\n new_images->gravity,&geometry);\n mask_image=RemoveFirstImageFromList(images);\n if (mask_image == (Image *) NULL)\n status&=CompositeImage(new_images,source_image,compose,\n clip_to_self,geometry.x,geometry.y,exception);\n else\n {\n if ((compose == DisplaceCompositeOp) ||\n (compose == DistortCompositeOp))\n {\n status&=CompositeImage(source_image,mask_image,\n CopyGreenCompositeOp,MagickTrue,0,0,exception);\n status&=CompositeImage(new_images,source_image,compose,\n clip_to_self,geometry.x,geometry.y,exception);\n }\n else\n {\n Image\n *clone_image;\n\n clone_image=CloneImage(new_images,0,0,MagickTrue,exception);\n if (clone_image == (Image *) NULL)\n break;\n status&=CompositeImage(new_images,source_image,compose,\n clip_to_self,geometry.x,geometry.y,exception);\n status&=CompositeImage(new_images,mask_image,\n CopyAlphaCompositeOp,MagickTrue,0,0,exception);\n status&=CompositeImage(clone_image,new_images,\n OverCompositeOp,clip_to_self,0,0,exception);\n new_images=DestroyImageList(new_images);\n new_images=clone_image;\n }\n mask_image=DestroyImage(mask_image);\n }\n source_image=DestroyImage(source_image);\n *images=DestroyImageList(*images);\n *images=new_images;\n break;\n }\n if (LocaleCompare(\"copy\",option+1) == 0)\n {\n Image\n *source_image;\n\n OffsetInfo\n offset;\n\n RectangleInfo\n geometry;\n\n /*\n Copy image pixels.\n */\n (void) SyncImageSettings(mogrify_info,*images,exception);\n (void) ParsePageGeometry(*images,argv[i+2],&geometry,exception);\n offset.x=geometry.x;\n offset.y=geometry.y;\n source_image=(*images);\n if (source_image->next != (Image *) NULL)\n source_image=source_image->next;\n (void) ParsePageGeometry(source_image,argv[i+1],&geometry,\n exception);\n status=CopyImagePixels(*images,source_image,&geometry,&offset,\n exception);\n break;\n }\n break;\n }\n case 'd':\n {\n if (LocaleCompare(\"deconstruct\",option+1) == 0)\n {\n Image\n *deconstruct_image;\n\n (void) SyncImagesSettings(mogrify_info,*images,exception);\n deconstruct_image=CompareImagesLayers(*images,CompareAnyLayer,\n exception);\n if (deconstruct_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n *images=DestroyImageList(*images);\n *images=deconstruct_image;\n break;\n }\n if (LocaleCompare(\"delete\",option+1) == 0)\n {\n if (*option == '+')\n DeleteImages(images,\"-1\",exception);\n else\n DeleteImages(images,argv[i+1],exception);\n break;\n }\n if (LocaleCompare(\"dither\",option+1) == 0)\n {\n if (*option == '+')\n {\n quantize_info->dither_method=NoDitherMethod;\n break;\n }\n quantize_info->dither_method=(DitherMethod) ParseCommandOption(\n MagickDitherOptions,MagickFalse,argv[i+1]);\n break;\n }\n if (LocaleCompare(\"duplicate\",option+1) == 0)\n {\n Image\n *duplicate_images;\n\n if (*option == '+')\n duplicate_images=DuplicateImages(*images,1,\"-1\",exception);\n else\n {\n const char\n *p;\n\n size_t\n number_duplicates;\n\n number_duplicates=(size_t) StringToLong(argv[i+1]);\n p=strchr(argv[i+1],',');\n if (p == (const char *) NULL)\n duplicate_images=DuplicateImages(*images,number_duplicates,\n \"-1\",exception);\n else\n duplicate_images=DuplicateImages(*images,number_duplicates,p,\n exception);\n }\n AppendImageToList(images, duplicate_images);\n (void) SyncImagesSettings(mogrify_info,*images,exception);\n break;\n }\n break;\n }\n case 'e':\n {\n if (LocaleCompare(\"evaluate-sequence\",option+1) == 0)\n {\n Image\n *evaluate_image;\n\n MagickEvaluateOperator\n op;\n\n (void) SyncImageSettings(mogrify_info,*images,exception);\n op=(MagickEvaluateOperator) ParseCommandOption(\n MagickEvaluateOptions,MagickFalse,argv[i+1]);\n evaluate_image=EvaluateImages(*images,op,exception);\n if (evaluate_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n *images=DestroyImageList(*images);\n *images=evaluate_image;\n break;\n }\n break;\n }\n case 'f':\n {\n if (LocaleCompare(\"fft\",option+1) == 0)\n {\n Image\n *fourier_image;\n\n /*\n Implements the discrete Fourier transform (DFT).\n */\n (void) SyncImageSettings(mogrify_info,*images,exception);\n fourier_image=ForwardFourierTransformImage(*images,*option == '-' ?\n MagickTrue : MagickFalse,exception);\n if (fourier_image == (Image *) NULL)\n break;\n *images=DestroyImageList(*images);\n *images=fourier_image;\n break;\n }\n if (LocaleCompare(\"flatten\",option+1) == 0)\n {\n Image\n *flatten_image;\n\n (void) SyncImagesSettings(mogrify_info,*images,exception);\n flatten_image=MergeImageLayers(*images,FlattenLayer,exception);\n if (flatten_image == (Image *) NULL)\n break;\n *images=DestroyImageList(*images);\n *images=flatten_image;\n break;\n }\n if (LocaleCompare(\"fx\",option+1) == 0)\n {\n Image\n *fx_image;\n\n (void) SyncImagesSettings(mogrify_info,*images,exception);\n fx_image=FxImage(*images,argv[i+1],exception);\n if (fx_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n *images=DestroyImageList(*images);\n *images=fx_image;\n break;\n }\n break;\n }\n case 'h':\n {\n if (LocaleCompare(\"hald-clut\",option+1) == 0)\n {\n Image\n *hald_image,\n *image;\n\n (void) SyncImagesSettings(mogrify_info,*images,exception);\n image=RemoveFirstImageFromList(images);\n hald_image=RemoveFirstImageFromList(images);\n if (hald_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n (void) HaldClutImage(image,hald_image,exception);\n hald_image=DestroyImage(hald_image);\n if (*images != (Image *) NULL)\n *images=DestroyImageList(*images);\n *images=image;\n break;\n }\n break;\n }\n case 'i':\n {\n if (LocaleCompare(\"ift\",option+1) == 0)\n {\n Image\n *fourier_image,\n *magnitude_image,\n *phase_image;\n\n /*\n Implements the inverse fourier discrete Fourier transform (DFT).\n */\n (void) SyncImagesSettings(mogrify_info,*images,exception);\n magnitude_image=RemoveFirstImageFromList(images);\n phase_image=RemoveFirstImageFromList(images);\n if (phase_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n fourier_image=InverseFourierTransformImage(magnitude_image,\n phase_image,*option == '-' ? MagickTrue : MagickFalse,exception);\n if (fourier_image == (Image *) NULL)\n break;\n if (*images != (Image *) NULL)\n *images=DestroyImageList(*images);\n *images=fourier_image;\n break;\n }\n if (LocaleCompare(\"insert\",option+1) == 0)\n {\n Image\n *p,\n *q;\n\n index=0;\n if (*option != '+')\n index=(ssize_t) StringToLong(argv[i+1]);\n p=RemoveLastImageFromList(images);\n if (p == (Image *) NULL)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n OptionError,\"NoSuchImage\",\"`%s'\",argv[i+1]);\n status=MagickFalse;\n break;\n }\n q=p;\n if (index == 0)\n PrependImageToList(images,q);\n else\n if (index == (ssize_t) GetImageListLength(*images))\n AppendImageToList(images,q);\n else\n {\n q=GetImageFromList(*images,index-1);\n if (q == (Image *) NULL)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n OptionError,\"NoSuchImage\",\"`%s'\",argv[i+1]);\n status=MagickFalse;\n break;\n }\n InsertImageInList(&q,p);\n }\n *images=GetFirstImageInList(q);\n break;\n }\n if (LocaleCompare(\"interpolate\",option+1) == 0)\n {\n interpolate_method=(PixelInterpolateMethod) ParseCommandOption(\n MagickInterpolateOptions,MagickFalse,argv[i+1]);\n break;\n }\n break;\n }\n case 'l':\n {\n if (LocaleCompare(\"layers\",option+1) == 0)\n {\n Image\n *layers;\n\n LayerMethod\n method;\n\n (void) SyncImagesSettings(mogrify_info,*images,exception);\n layers=(Image *) NULL;\n method=(LayerMethod) ParseCommandOption(MagickLayerOptions,\n MagickFalse,argv[i+1]);\n switch (method)\n {\n case CoalesceLayer:\n {\n layers=CoalesceImages(*images,exception);\n break;\n }\n case CompareAnyLayer:\n case CompareClearLayer:\n case CompareOverlayLayer:\n default:\n {\n layers=CompareImagesLayers(*images,method,exception);\n break;\n }\n case MergeLayer:\n case FlattenLayer:\n case MosaicLayer:\n case TrimBoundsLayer:\n {\n layers=MergeImageLayers(*images,method,exception);\n break;\n }\n case DisposeLayer:\n {\n layers=DisposeImages(*images,exception);\n break;\n }\n case OptimizeImageLayer:\n {\n layers=OptimizeImageLayers(*images,exception);\n break;\n }\n case OptimizePlusLayer:\n {\n layers=OptimizePlusImageLayers(*images,exception);\n break;\n }\n case OptimizeTransLayer:\n {\n OptimizeImageTransparency(*images,exception);\n break;\n }\n case RemoveDupsLayer:\n {\n RemoveDuplicateLayers(images,exception);\n break;\n }\n case RemoveZeroLayer:\n {\n RemoveZeroDelayLayers(images,exception);\n break;\n }\n case OptimizeLayer:\n {\n /*\n General Purpose, GIF Animation Optimizer.\n */\n layers=CoalesceImages(*images,exception);\n if (layers == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n *images=DestroyImageList(*images);\n *images=layers;\n layers=OptimizeImageLayers(*images,exception);\n if (layers == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n *images=DestroyImageList(*images);\n *images=layers;\n layers=(Image *) NULL;\n OptimizeImageTransparency(*images,exception);\n (void) RemapImages(quantize_info,*images,(Image *) NULL,\n exception);\n break;\n }\n case CompositeLayer:\n {\n CompositeOperator\n compose;\n\n Image\n *source;\n\n RectangleInfo\n geometry;\n\n /*\n Split image sequence at the first 'NULL:' image.\n */\n source=(*images);\n while (source != (Image *) NULL)\n {\n source=GetNextImageInList(source);\n if ((source != (Image *) NULL) &&\n (LocaleCompare(source->magick,\"NULL\") == 0))\n break;\n }\n if (source != (Image *) NULL)\n {\n if ((GetPreviousImageInList(source) == (Image *) NULL) ||\n (GetNextImageInList(source) == (Image *) NULL))\n source=(Image *) NULL;\n else\n {\n /*\n Separate the two lists, junk the null: image.\n */\n source=SplitImageList(source->previous);\n DeleteImageFromList(&source);\n }\n }\n if (source == (Image *) NULL)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n OptionError,\"MissingNullSeparator\",\"layers Composite\");\n status=MagickFalse;\n break;\n }\n /*\n Adjust offset with gravity and virtual canvas.\n */\n SetGeometry(*images,&geometry);\n (void) ParseAbsoluteGeometry((*images)->geometry,&geometry);\n geometry.width=source->page.width != 0 ?\n source->page.width : source->columns;\n geometry.height=source->page.height != 0 ?\n source->page.height : source->rows;\n GravityAdjustGeometry((*images)->page.width != 0 ?\n (*images)->page.width : (*images)->columns,\n (*images)->page.height != 0 ? (*images)->page.height :\n (*images)->rows,(*images)->gravity,&geometry);\n compose=OverCompositeOp;\n option=GetImageOption(mogrify_info,\"compose\");\n if (option != (const char *) NULL)\n compose=(CompositeOperator) ParseCommandOption(\n MagickComposeOptions,MagickFalse,option);\n CompositeLayers(*images,compose,source,geometry.x,geometry.y,\n exception);\n source=DestroyImageList(source);\n break;\n }\n }\n if (layers == (Image *) NULL)\n break;\n *images=DestroyImageList(*images);\n *images=layers;\n break;\n }\n break;\n }\n case 'm':\n {\n if (LocaleCompare(\"map\",option+1) == 0)\n {\n (void) SyncImagesSettings(mogrify_info,*images,exception);\n if (*option == '+')\n {\n (void) RemapImages(quantize_info,*images,(Image *) NULL,\n exception);\n break;\n }\n i++;\n break;\n }\n if (LocaleCompare(\"maximum\",option+1) == 0)\n {\n Image\n *maximum_image;\n\n /*\n Maximum image sequence (deprecated).\n */\n (void) SyncImagesSettings(mogrify_info,*images,exception);\n maximum_image=EvaluateImages(*images,MaxEvaluateOperator,exception);\n if (maximum_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n *images=DestroyImageList(*images);\n *images=maximum_image;\n break;\n }\n if (LocaleCompare(\"minimum\",option+1) == 0)\n {\n Image\n *minimum_image;\n\n /*\n Minimum image sequence (deprecated).\n */\n (void) SyncImagesSettings(mogrify_info,*images,exception);\n minimum_image=EvaluateImages(*images,MinEvaluateOperator,exception);\n if (minimum_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n *images=DestroyImageList(*images);\n *images=minimum_image;\n break;\n }\n if (LocaleCompare(\"morph\",option+1) == 0)\n {\n Image\n *morph_image;\n\n (void) SyncImagesSettings(mogrify_info,*images,exception);\n morph_image=MorphImages(*images,StringToUnsignedLong(argv[i+1]),\n exception);\n if (morph_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n *images=DestroyImageList(*images);\n *images=morph_image;\n break;\n }\n if (LocaleCompare(\"mosaic\",option+1) == 0)\n {\n Image\n *mosaic_image;\n\n (void) SyncImagesSettings(mogrify_info,*images,exception);\n mosaic_image=MergeImageLayers(*images,MosaicLayer,exception);\n if (mosaic_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n *images=DestroyImageList(*images);\n *images=mosaic_image;\n break;\n }\n break;\n }\n case 'p':\n {\n if (LocaleCompare(\"poly\",option+1) == 0)\n {\n char\n *args,\n token[MagickPathExtent];\n\n const char\n *p;\n\n double\n *arguments;\n\n Image\n *polynomial_image;\n\n register ssize_t\n x;\n\n size_t\n number_arguments;\n\n /*\n Polynomial image.\n */\n (void) SyncImageSettings(mogrify_info,*images,exception);\n args=InterpretImageProperties(mogrify_info,*images,argv[i+1],\n exception);\n if (args == (char *) NULL)\n break;\n p=(char *) args;\n for (x=0; *p != '\\0'; x++)\n {\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n }\n number_arguments=(size_t) x;\n arguments=(double *) AcquireQuantumMemory(number_arguments,\n sizeof(*arguments));\n if (arguments == (double *) NULL)\n ThrowWandFatalException(ResourceLimitFatalError,\n \"MemoryAllocationFailed\",(*images)->filename);\n (void) memset(arguments,0,number_arguments*\n sizeof(*arguments));\n p=(char *) args;\n for (x=0; (x < (ssize_t) number_arguments) && (*p != '\\0'); x++)\n {\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n arguments[x]=StringToDouble(token,(char **) NULL);\n }\n args=DestroyString(args);\n polynomial_image=PolynomialImage(*images,number_arguments >> 1,\n arguments,exception);\n arguments=(double *) RelinquishMagickMemory(arguments);\n if (polynomial_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n *images=DestroyImageList(*images);\n *images=polynomial_image;\n }\n if (LocaleCompare(\"print\",option+1) == 0)\n {\n char\n *string;\n\n (void) SyncImagesSettings(mogrify_info,*images,exception);\n string=InterpretImageProperties(mogrify_info,*images,argv[i+1],\n exception);\n if (string == (char *) NULL)\n break;\n (void) FormatLocaleFile(stdout,\"%s\",string);\n string=DestroyString(string);\n }\n if (LocaleCompare(\"process\",option+1) == 0)\n {\n char\n **arguments;\n\n int\n j,\n number_arguments;\n\n (void) SyncImagesSettings(mogrify_info,*images,exception);\n arguments=StringToArgv(argv[i+1],&number_arguments);\n if (arguments == (char **) NULL)\n break;\n if ((argc > 1) && (strchr(arguments[1],'=') != (char *) NULL))\n {\n char\n breaker,\n quote,\n *token;\n\n const char\n *argument;\n\n int\n next,\n token_status;\n\n size_t\n length;\n\n TokenInfo\n *token_info;\n\n /*\n Support old style syntax, filter=\"-option arg\".\n */\n length=strlen(argv[i+1]);\n token=(char *) NULL;\n if (~length >= (MagickPathExtent-1))\n token=(char *) AcquireQuantumMemory(length+MagickPathExtent,\n sizeof(*token));\n if (token == (char *) NULL)\n break;\n next=0;\n argument=argv[i+1];\n token_info=AcquireTokenInfo();\n token_status=Tokenizer(token_info,0,token,length,argument,\"\",\n \"=\",\"\\\"\",'\\0',&breaker,&next,"e);\n token_info=DestroyTokenInfo(token_info);\n if (token_status == 0)\n {\n const char\n *arg;\n\n arg=(&(argument[next]));\n (void) InvokeDynamicImageFilter(token,&(*images),1,&arg,\n exception);\n }\n token=DestroyString(token);\n break;\n }\n (void) SubstituteString(&arguments[1],\"-\",\"\");\n (void) InvokeDynamicImageFilter(arguments[1],&(*images),\n number_arguments-2,(const char **) arguments+2,exception);\n for (j=0; j < number_arguments; j++)\n arguments[j]=DestroyString(arguments[j]);\n arguments=(char **) RelinquishMagickMemory(arguments);\n break;\n }\n break;\n }\n case 'r':\n {\n if (LocaleCompare(\"reverse\",option+1) == 0)\n {\n ReverseImageList(images);\n break;\n }\n break;\n }\n case 's':\n {\n if (LocaleCompare(\"smush\",option+1) == 0)\n {\n Image\n *smush_image;\n\n ssize_t\n offset;\n\n (void) SyncImagesSettings(mogrify_info,*images,exception);\n offset=(ssize_t) StringToLong(argv[i+1]);\n smush_image=SmushImages(*images,*option == '-' ? MagickTrue :\n MagickFalse,offset,exception);\n if (smush_image == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n *images=DestroyImageList(*images);\n *images=smush_image;\n break;\n }\n if (LocaleCompare(\"swap\",option+1) == 0)\n {\n Image\n *p,\n *q,\n *u,\n *v;\n\n ssize_t\n swap_index;\n\n index=(-1);\n swap_index=(-2);\n if (*option != '+')\n {\n GeometryInfo\n geometry_info;\n\n MagickStatusType\n flags;\n\n swap_index=(-1);\n flags=ParseGeometry(argv[i+1],&geometry_info);\n index=(ssize_t) geometry_info.rho;\n if ((flags & SigmaValue) != 0)\n swap_index=(ssize_t) geometry_info.sigma;\n }\n p=GetImageFromList(*images,index);\n q=GetImageFromList(*images,swap_index);\n if ((p == (Image *) NULL) || (q == (Image *) NULL))\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n OptionError,\"NoSuchImage\",\"`%s'\",(*images)->filename);\n status=MagickFalse;\n break;\n }\n if (p == q)\n break;\n u=CloneImage(p,0,0,MagickTrue,exception);\n if (u == (Image *) NULL)\n break;\n v=CloneImage(q,0,0,MagickTrue,exception);\n if (v == (Image *) NULL)\n {\n u=DestroyImage(u);\n break;\n }\n ReplaceImageInList(&p,v);\n ReplaceImageInList(&q,u);\n *images=GetFirstImageInList(q);\n break;\n }\n break;\n }\n case 'w':\n {\n if (LocaleCompare(\"write\",option+1) == 0)\n {\n char\n key[MagickPathExtent];\n\n Image\n *write_images;\n\n ImageInfo\n *write_info;\n\n (void) SyncImagesSettings(mogrify_info,*images,exception);\n (void) FormatLocaleString(key,MagickPathExtent,\"cache:%s\",\n argv[i+1]);\n (void) DeleteImageRegistry(key);\n write_images=(*images);\n if (*option == '+')\n write_images=CloneImageList(*images,exception);\n write_info=CloneImageInfo(mogrify_info);\n status&=WriteImages(write_info,write_images,argv[i+1],exception);\n write_info=DestroyImageInfo(write_info);\n if (*option == '+')\n write_images=DestroyImageList(write_images);\n break;\n }\n break;\n }\n default:\n break;\n }\n i+=count;\n }\n quantize_info=DestroyQuantizeInfo(quantize_info);\n mogrify_info=DestroyImageInfo(mogrify_info);\n status&=MogrifyImageInfo(image_info,argc,argv,exception);\n return(status != 0 ? MagickTrue : MagickFalse);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1616'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image,\n ExceptionInfo *exception)\n{\n char\n buffer[MagickPathExtent],\n format,\n magick[MagickPathExtent];\n\n const char\n *value;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n scene;\n\n Quantum\n index;\n\n QuantumAny\n pixel;\n\n QuantumInfo\n *quantum_info;\n\n QuantumType\n quantum_type;\n\n register unsigned char\n *q;\n\n size_t\n extent,\n imageListLength,\n packet_size;\n\n ssize_t\n count,\n y;\n\n /*\n Open output image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);\n if (status == MagickFalse)\n return(status);\n scene=0;\n imageListLength=GetImageListLength(image);\n do\n {\n QuantumAny\n max_value;\n\n /*\n Write PNM file header.\n */\n packet_size=3;\n quantum_type=RGBQuantum;\n (void) CopyMagickString(magick,image_info->magick,MagickPathExtent);\n max_value=GetQuantumRange(image->depth);\n switch (magick[1])\n {\n case 'A':\n case 'a':\n {\n format='7';\n break;\n }\n case 'B':\n case 'b':\n {\n format='4';\n if (image_info->compression == NoCompression)\n format='1';\n break;\n }\n case 'F':\n case 'f':\n {\n format='F';\n if (SetImageGray(image,exception) != MagickFalse)\n format='f';\n break;\n }\n case 'G':\n case 'g':\n {\n format='5';\n if (image_info->compression == NoCompression)\n format='2';\n break;\n }\n case 'N':\n case 'n':\n {\n if ((image_info->type != TrueColorType) &&\n (SetImageGray(image,exception) != MagickFalse))\n {\n format='5';\n if (image_info->compression == NoCompression)\n format='2';\n if (SetImageMonochrome(image,exception) != MagickFalse)\n {\n format='4';\n if (image_info->compression == NoCompression)\n format='1';\n }\n break;\n }\n }\n default:\n {\n format='6';\n if (image_info->compression == NoCompression)\n format='3';\n break;\n }\n }\n (void) FormatLocaleString(buffer,MagickPathExtent,\"P%c\\n\",format);\n (void) WriteBlobString(image,buffer);\n value=GetImageProperty(image,\"comment\",exception);\n if (value != (const char *) NULL)\n {\n register const char\n *p;\n\n /*\n Write comments to file.\n */\n (void) WriteBlobByte(image,'#');\n for (p=value; *p != '\\0'; p++)\n {\n (void) WriteBlobByte(image,(unsigned char) *p);\n if ((*p == '\\n') || (*p == '\\r'))\n (void) WriteBlobByte(image,'#');\n }\n (void) WriteBlobByte(image,'\\n');\n }\n if (format != '7')\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g %.20g\\n\",\n (double) image->columns,(double) image->rows);\n (void) WriteBlobString(image,buffer);\n }\n else\n {\n char\n type[MagickPathExtent];\n\n /*\n PAM header.\n */\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"WIDTH %.20g\\nHEIGHT %.20g\\n\",(double) image->columns,(double)\n image->rows);\n (void) WriteBlobString(image,buffer);\n quantum_type=GetQuantumType(image,exception);\n switch (quantum_type)\n {\n case CMYKQuantum:\n case CMYKAQuantum:\n {\n packet_size=4;\n (void) CopyMagickString(type,\"CMYK\",MagickPathExtent);\n break;\n }\n case GrayQuantum:\n case GrayAlphaQuantum:\n {\n packet_size=1;\n (void) CopyMagickString(type,\"GRAYSCALE\",MagickPathExtent);\n if (IdentifyImageMonochrome(image,exception) != MagickFalse)\n (void) CopyMagickString(type,\"BLACKANDWHITE\",MagickPathExtent);\n break;\n }\n default:\n {\n quantum_type=RGBQuantum;\n if (image->alpha_trait != UndefinedPixelTrait)\n quantum_type=RGBAQuantum;\n packet_size=3;\n (void) CopyMagickString(type,\"RGB\",MagickPathExtent);\n break;\n }\n }\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n packet_size++;\n (void) ConcatenateMagickString(type,\"_ALPHA\",MagickPathExtent);\n }\n if (image->depth > 32)\n image->depth=32;\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"DEPTH %.20g\\nMAXVAL %.20g\\n\",(double) packet_size,(double)\n ((MagickOffsetType) GetQuantumRange(image->depth)));\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"TUPLTYPE %s\\nENDHDR\\n\",type);\n (void) WriteBlobString(image,buffer);\n }\n /*\n Convert runextent encoded to PNM raster pixels.\n */\n switch (format)\n {\n case '1':\n {\n unsigned char\n pixels[2048];\n\n /*\n Convert image to a PBM image.\n */\n (void) SetImageType(image,BilevelType,exception);\n q=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register const Quantum\n *magick_restrict p;\n\n register ssize_t\n x;\n\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n *q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ?\n '0' : '1');\n *q++=' ';\n if ((q-pixels+1) >= (ssize_t) sizeof(pixels))\n {\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n q=pixels;\n }\n p+=GetPixelChannels(image);\n }\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n q=pixels;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n if (q != pixels)\n {\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n }\n break;\n }\n case '2':\n {\n unsigned char\n pixels[2048];\n\n /*\n Convert image to a PGM image.\n */\n if (image->depth <= 8)\n (void) WriteBlobString(image,\"255\\n\");\n else\n if (image->depth <= 16)\n (void) WriteBlobString(image,\"65535\\n\");\n else\n (void) WriteBlobString(image,\"4294967295\\n\");\n q=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register const Quantum\n *magick_restrict p;\n\n register ssize_t\n x;\n\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n index=ClampToQuantum(GetPixelLuma(image,p));\n if (image->depth <= 8)\n count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,\"%u \",\n ScaleQuantumToChar(index));\n else\n if (image->depth <= 16)\n count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,\n \"%u \",ScaleQuantumToShort(index));\n else\n count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,\n \"%u \",ScaleQuantumToLong(index));\n extent=(size_t) count;\n (void) strncpy((char *) q,buffer,extent);\n q+=extent;\n if ((q-pixels+extent+2) >= sizeof(pixels))\n {\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n q=pixels;\n }\n p+=GetPixelChannels(image);\n }\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n q=pixels;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n if (q != pixels)\n {\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n }\n break;\n }\n case '3':\n {\n unsigned char\n pixels[2048];\n\n /*\n Convert image to a PNM image.\n */\n (void) TransformImageColorspace(image,sRGBColorspace,exception);\n if (image->depth <= 8)\n (void) WriteBlobString(image,\"255\\n\");\n else\n if (image->depth <= 16)\n (void) WriteBlobString(image,\"65535\\n\");\n else\n (void) WriteBlobString(image,\"4294967295\\n\");\n q=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register const Quantum\n *magick_restrict p;\n\n register ssize_t\n x;\n\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (image->depth <= 8)\n count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,\n \"%u %u %u \",ScaleQuantumToChar(GetPixelRed(image,p)),\n ScaleQuantumToChar(GetPixelGreen(image,p)),\n ScaleQuantumToChar(GetPixelBlue(image,p)));\n else\n if (image->depth <= 16)\n count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,\n \"%u %u %u \",ScaleQuantumToShort(GetPixelRed(image,p)),\n ScaleQuantumToShort(GetPixelGreen(image,p)),\n ScaleQuantumToShort(GetPixelBlue(image,p)));\n else\n count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,\n \"%u %u %u \",ScaleQuantumToLong(GetPixelRed(image,p)),\n ScaleQuantumToLong(GetPixelGreen(image,p)),\n ScaleQuantumToLong(GetPixelBlue(image,p)));\n extent=(size_t) count;\n (void) strncpy((char *) q,buffer,extent);\n q+=extent;\n if ((q-pixels+extent+2) >= sizeof(pixels))\n {\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n q=pixels;\n }\n p+=GetPixelChannels(image);\n }\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n q=pixels;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n if (q != pixels)\n {\n *q++='\\n';\n (void) WriteBlob(image,q-pixels,pixels);\n }\n break;\n }\n case '4':\n {\n register unsigned char\n *pixels;\n\n /*\n Convert image to a PBM image.\n */\n (void) SetImageType(image,BilevelType,exception);\n image->depth=1;\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) SetQuantumEndian(image,quantum_info,MSBEndian);\n quantum_info->min_is_white=MagickTrue;\n pixels=GetQuantumPixels(quantum_info);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register const Quantum\n *magick_restrict p;\n\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n GrayQuantum,pixels,exception);\n count=WriteBlob(image,extent,pixels);\n if (count != (ssize_t) extent)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n quantum_info=DestroyQuantumInfo(quantum_info);\n break;\n }\n case '5':\n {\n register unsigned char\n *pixels;\n\n /*\n Convert image to a PGM image.\n */\n if (image->depth > 32)\n image->depth=32;\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double)\n ((MagickOffsetType) GetQuantumRange(image->depth)));\n (void) WriteBlobString(image,buffer);\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) SetQuantumEndian(image,quantum_info,MSBEndian);\n quantum_info->min_is_white=MagickTrue;\n pixels=GetQuantumPixels(quantum_info);\n extent=GetQuantumExtent(image,quantum_info,GrayQuantum);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register const Quantum\n *magick_restrict p;\n\n register ssize_t\n x;\n\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n q=pixels;\n switch (image->depth)\n {\n case 8:\n case 16:\n case 32:\n {\n extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n GrayQuantum,pixels,exception);\n break;\n }\n default:\n {\n if (image->depth <= 8)\n {\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (IsPixelGray(image,p) == MagickFalse)\n pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(\n image,p)),max_value);\n else\n {\n if (image->depth == 8)\n pixel=ScaleQuantumToChar(GetPixelRed(image,p));\n else\n pixel=ScaleQuantumToAny(GetPixelRed(image,p),\n max_value);\n }\n q=PopCharPixel((unsigned char) pixel,q);\n p+=GetPixelChannels(image);\n }\n extent=(size_t) (q-pixels);\n break;\n }\n if (image->depth <= 16)\n {\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (IsPixelGray(image,p) == MagickFalse)\n pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,\n p)),max_value);\n else\n {\n if (image->depth == 16)\n pixel=ScaleQuantumToShort(GetPixelRed(image,p));\n else\n pixel=ScaleQuantumToAny(GetPixelRed(image,p),\n max_value);\n }\n q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);\n p+=GetPixelChannels(image);\n }\n extent=(size_t) (q-pixels);\n break;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (IsPixelGray(image,p) == MagickFalse)\n pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,p)),\n max_value);\n else\n {\n if (image->depth == 16)\n pixel=ScaleQuantumToLong(GetPixelRed(image,p));\n else\n pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);\n }\n q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);\n p+=GetPixelChannels(image);\n }\n extent=(size_t) (q-pixels);\n break;\n }\n }\n count=WriteBlob(image,extent,pixels);\n if (count != (ssize_t) extent)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n quantum_info=DestroyQuantumInfo(quantum_info);\n break;\n }\n case '6':\n {\n register unsigned char\n *pixels;\n\n /*\n Convert image to a PNM image.\n */\n (void) TransformImageColorspace(image,sRGBColorspace,exception);\n if (image->depth > 32)\n image->depth=32;\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double)\n ((MagickOffsetType) GetQuantumRange(image->depth)));\n (void) WriteBlobString(image,buffer);\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) SetQuantumEndian(image,quantum_info,MSBEndian);\n pixels=GetQuantumPixels(quantum_info);\n extent=GetQuantumExtent(image,quantum_info,quantum_type);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register const Quantum\n *magick_restrict p;\n\n register ssize_t\n x;\n\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n q=pixels;\n switch (image->depth)\n {\n case 8:\n case 16:\n case 32:\n {\n extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n break;\n }\n default:\n {\n if (image->depth <= 8)\n {\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);\n q=PopCharPixel((unsigned char) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);\n q=PopCharPixel((unsigned char) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);\n q=PopCharPixel((unsigned char) pixel,q);\n p+=GetPixelChannels(image);\n }\n extent=(size_t) (q-pixels);\n break;\n }\n if (image->depth <= 16)\n {\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);\n q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);\n q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);\n q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);\n p+=GetPixelChannels(image);\n }\n extent=(size_t) (q-pixels);\n break;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);\n q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);\n q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);\n q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);\n p+=GetPixelChannels(image);\n }\n extent=(size_t) (q-pixels);\n break;\n }\n }\n count=WriteBlob(image,extent,pixels);\n if (count != (ssize_t) extent)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n quantum_info=DestroyQuantumInfo(quantum_info);\n break;\n }\n case '7':\n {\n register unsigned char\n *pixels;\n\n /*\n Convert image to a PAM.\n */\n if (image->depth > 32)\n image->depth=32;\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) SetQuantumEndian(image,quantum_info,MSBEndian);\n pixels=GetQuantumPixels(quantum_info);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register const Quantum\n *magick_restrict p;\n\n register ssize_t\n x;\n\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n q=pixels;\n switch (image->depth)\n {\n case 8:\n case 16:\n case 32:\n {\n extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n break;\n }\n default:\n {\n switch (quantum_type)\n {\n case GrayQuantum:\n case GrayAlphaQuantum:\n {\n if (image->depth <= 8)\n {\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(\n image,p)),max_value);\n q=PopCharPixel((unsigned char) pixel,q);\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n pixel=(unsigned char) ScaleQuantumToAny(\n GetPixelAlpha(image,p),max_value);\n q=PopCharPixel((unsigned char) pixel,q);\n }\n p+=GetPixelChannels(image);\n }\n break;\n }\n if (image->depth <= 16)\n {\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(\n image,p)),max_value);\n q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n pixel=(unsigned char) ScaleQuantumToAny(\n GetPixelAlpha(image,p),max_value);\n q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);\n }\n p+=GetPixelChannels(image);\n }\n break;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,\n p)),max_value);\n q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n pixel=(unsigned char) ScaleQuantumToAny(\n GetPixelAlpha(image,p),max_value);\n q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);\n }\n p+=GetPixelChannels(image);\n }\n break;\n }\n case CMYKQuantum:\n case CMYKAQuantum:\n {\n if (image->depth <= 8)\n {\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);\n q=PopCharPixel((unsigned char) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelGreen(image,p),\n max_value);\n q=PopCharPixel((unsigned char) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelBlue(image,p),\n max_value);\n q=PopCharPixel((unsigned char) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelBlack(image,p),\n max_value);\n q=PopCharPixel((unsigned char) pixel,q);\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),\n max_value);\n q=PopCharPixel((unsigned char) pixel,q);\n }\n p+=GetPixelChannels(image);\n }\n break;\n }\n if (image->depth <= 16)\n {\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);\n q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelGreen(image,p),\n max_value);\n q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelBlue(image,p),\n max_value);\n q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelBlack(image,p),\n max_value);\n q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),\n max_value);\n q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);\n }\n p+=GetPixelChannels(image);\n }\n break;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);\n q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);\n q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);\n q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelBlack(image,p),max_value);\n q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),\n max_value);\n q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);\n }\n p+=GetPixelChannels(image);\n }\n break;\n }\n default:\n {\n if (image->depth <= 8)\n {\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);\n q=PopCharPixel((unsigned char) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelGreen(image,p),\n max_value);\n q=PopCharPixel((unsigned char) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelBlue(image,p),\n max_value);\n q=PopCharPixel((unsigned char) pixel,q);\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),\n max_value);\n q=PopCharPixel((unsigned char) pixel,q);\n }\n p+=GetPixelChannels(image);\n }\n break;\n }\n if (image->depth <= 16)\n {\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);\n q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelGreen(image,p),\n max_value);\n q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelBlue(image,p),\n max_value);\n q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),\n max_value);\n q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);\n }\n p+=GetPixelChannels(image);\n }\n break;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);\n q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);\n q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);\n pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);\n q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),\n max_value);\n q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);\n }\n p+=GetPixelChannels(image);\n }\n break;\n }\n }\n extent=(size_t) (q-pixels);\n break;\n }\n }\n count=WriteBlob(image,extent,pixels);\n if (count != (ssize_t) extent)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n quantum_info=DestroyQuantumInfo(quantum_info);\n break;\n }\n case 'F':\n case 'f':\n {\n register unsigned char\n *pixels;\n\n (void) WriteBlobString(image,image->endian == LSBEndian ? \"-1.0\\n\" :\n \"1.0\\n\");\n image->depth=32;\n quantum_type=format == 'f' ? GrayQuantum : RGBQuantum;\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);\n if (status == MagickFalse)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=GetQuantumPixels(quantum_info);\n for (y=(ssize_t) image->rows-1; y >= 0; y--)\n {\n register const Quantum\n *magick_restrict p;\n\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n (void) WriteBlob(image,extent,pixels);\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n quantum_info=DestroyQuantumInfo(quantum_info);\n break;\n }\n }\n if (GetNextImageInList(image) == (Image *) NULL)\n break;\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);\n if (status == MagickFalse)\n break;\n } while (image_info->adjoin != MagickFalse);\n (void) CloseBlob(image);\n return(MagickTrue);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1613'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: MagickExport Image *AdaptiveThresholdImage(const Image *image,\n const size_t width,const size_t height,const double bias,\n ExceptionInfo *exception)\n{\n#define AdaptiveThresholdImageTag \"AdaptiveThreshold/Image\"\n\n CacheView\n *image_view,\n *threshold_view;\n\n Image\n *threshold_image;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n progress;\n\n MagickSizeType\n number_pixels;\n\n ssize_t\n y;\n\n /*\n Initialize threshold image attributes.\n */\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n threshold_image=CloneImage(image,0,0,MagickTrue,exception);\n if (threshold_image == (Image *) NULL)\n return((Image *) NULL);\n status=SetImageStorageClass(threshold_image,DirectClass,exception);\n if (status == MagickFalse)\n {\n threshold_image=DestroyImage(threshold_image);\n return((Image *) NULL);\n }\n /*\n Threshold image.\n */\n status=MagickTrue;\n progress=0;\n number_pixels=(MagickSizeType) width*height;\n image_view=AcquireVirtualCacheView(image,exception);\n threshold_view=AcquireAuthenticCacheView(threshold_image,exception);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static) shared(progress,status) \\\n magick_number_threads(image,threshold_image,image->rows,1)\n#endif\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n double\n channel_bias[MaxPixelChannels],\n channel_sum[MaxPixelChannels];\n\n register const Quantum\n *magick_restrict p,\n *magick_restrict pixels;\n\n register Quantum\n *magick_restrict q;\n\n register ssize_t\n i,\n x;\n\n ssize_t\n center,\n u,\n v;\n\n if (status == MagickFalse)\n continue;\n p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t)\n (height/2L),image->columns+width,height,exception);\n q=QueueCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,\n 1,exception);\n if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))\n {\n status=MagickFalse;\n continue;\n }\n center=(ssize_t) GetPixelChannels(image)*(image->columns+width)*(height/2L)+\n GetPixelChannels(image)*(width/2);\n for (i=0; i < (ssize_t) GetPixelChannels(image); i++)\n {\n PixelChannel channel = GetPixelChannelChannel(image,i);\n PixelTrait traits = GetPixelChannelTraits(image,channel);\n PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image,\n channel);\n if ((traits == UndefinedPixelTrait) ||\n (threshold_traits == UndefinedPixelTrait))\n continue;\n if ((threshold_traits & CopyPixelTrait) != 0)\n {\n SetPixelChannel(threshold_image,channel,p[center+i],q);\n continue;\n }\n pixels=p;\n channel_bias[channel]=0.0;\n channel_sum[channel]=0.0;\n for (v=0; v < (ssize_t) height; v++)\n {\n for (u=0; u < (ssize_t) width; u++)\n {\n if (u == (ssize_t) (width-1))\n channel_bias[channel]+=pixels[i];\n channel_sum[channel]+=pixels[i];\n pixels+=GetPixelChannels(image);\n }\n pixels+=GetPixelChannels(image)*image->columns;\n }\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n for (i=0; i < (ssize_t) GetPixelChannels(image); i++)\n {\n double\n mean;\n\n PixelChannel channel = GetPixelChannelChannel(image,i);\n PixelTrait traits = GetPixelChannelTraits(image,channel);\n PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image,\n channel);\n if ((traits == UndefinedPixelTrait) ||\n (threshold_traits == UndefinedPixelTrait))\n continue;\n if ((threshold_traits & CopyPixelTrait) != 0)\n {\n SetPixelChannel(threshold_image,channel,p[center+i],q);\n continue;\n }\n channel_sum[channel]-=channel_bias[channel];\n channel_bias[channel]=0.0;\n pixels=p;\n for (v=0; v < (ssize_t) height; v++)\n {\n channel_bias[channel]+=pixels[i];\n pixels+=(width-1)*GetPixelChannels(image);\n channel_sum[channel]+=pixels[i];\n pixels+=GetPixelChannels(image)*(image->columns+1);\n }\n mean=(double) (channel_sum[channel]/number_pixels+bias);\n SetPixelChannel(threshold_image,channel,(Quantum) ((double)\n p[center+i] <= mean ? 0 : QuantumRange),q);\n }\n p+=GetPixelChannels(image);\n q+=GetPixelChannels(threshold_image);\n }\n if (SyncCacheViewAuthenticPixels(threshold_view,exception) == MagickFalse)\n status=MagickFalse;\n if (image->progress_monitor != (MagickProgressMonitor) NULL)\n {\n MagickBooleanType\n proceed;\n\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp atomic\n#endif\n progress++;\n proceed=SetImageProgress(image,AdaptiveThresholdImageTag,progress,\n image->rows);\n if (proceed == MagickFalse)\n status=MagickFalse;\n }\n }\n threshold_image->type=image->type;\n threshold_view=DestroyCacheView(threshold_view);\n image_view=DestroyCacheView(image_view);\n if (status == MagickFalse)\n threshold_image=DestroyImage(threshold_image);\n return(threshold_image);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1608'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadPCLImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n#define CropBox \"CropBox\"\n#define DeviceCMYK \"DeviceCMYK\"\n#define MediaBox \"MediaBox\"\n#define RenderPCLText \" Rendering PCL... \"\n\n char\n command[MaxTextExtent],\n *density,\n filename[MaxTextExtent],\n geometry[MaxTextExtent],\n *options,\n input_filename[MaxTextExtent];\n\n const DelegateInfo\n *delegate_info;\n\n Image\n *image,\n *next_image;\n\n ImageInfo\n *read_info;\n\n int\n c;\n\n MagickBooleanType\n cmyk,\n status;\n\n PointInfo\n delta;\n\n RectangleInfo\n bounding_box,\n page;\n\n register char\n *p;\n\n SegmentInfo\n bounds;\n\n size_t\n height,\n width;\n\n ssize_t\n count;\n\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n /*\n Open image file.\n */\n image=AcquireImage(image_info);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n status=AcquireUniqueSymbolicLink(image_info->filename,input_filename);\n if (status == MagickFalse)\n {\n ThrowFileException(exception,FileOpenError,\"UnableToCreateTemporaryFile\",\n image_info->filename);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Set the page density.\n */\n delta.x=DefaultResolution;\n delta.y=DefaultResolution;\n if ((image->x_resolution == 0.0) || (image->y_resolution == 0.0))\n {\n GeometryInfo\n geometry_info;\n\n MagickStatusType\n flags;\n\n flags=ParseGeometry(PSDensityGeometry,&geometry_info);\n image->x_resolution=geometry_info.rho;\n image->y_resolution=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->y_resolution=image->x_resolution;\n }\n /*\n Determine page geometry from the PCL media box.\n */\n cmyk=image->colorspace == CMYKColorspace ? MagickTrue : MagickFalse;\n count=0;\n (void) memset(&bounding_box,0,sizeof(bounding_box));\n (void) memset(&bounds,0,sizeof(bounds));\n (void) memset(&page,0,sizeof(page));\n (void) memset(command,0,sizeof(command));\n p=command;\n for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image))\n {\n if (image_info->page != (char *) NULL)\n continue;\n /*\n Note PCL elements.\n */\n *p++=(char) c;\n if ((c != (int) '/') && (c != '\\n') &&\n ((size_t) (p-command) < (MaxTextExtent-1)))\n continue;\n *p='\\0';\n p=command;\n /*\n Is this a CMYK document?\n */\n if (LocaleNCompare(DeviceCMYK,command,strlen(DeviceCMYK)) == 0)\n cmyk=MagickTrue;\n if (LocaleNCompare(CropBox,command,strlen(CropBox)) == 0)\n {\n /*\n Note region defined by crop box.\n */\n count=(ssize_t) sscanf(command,\"CropBox [%lf %lf %lf %lf\",\n &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);\n if (count != 4)\n count=(ssize_t) sscanf(command,\"CropBox[%lf %lf %lf %lf\",\n &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);\n }\n if (LocaleNCompare(MediaBox,command,strlen(MediaBox)) == 0)\n {\n /*\n Note region defined by media box.\n */\n count=(ssize_t) sscanf(command,\"MediaBox [%lf %lf %lf %lf\",\n &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);\n if (count != 4)\n count=(ssize_t) sscanf(command,\"MediaBox[%lf %lf %lf %lf\",\n &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);\n }\n if (count != 4)\n continue;\n /*\n Set PCL render geometry.\n */\n width=(size_t) floor(bounds.x2-bounds.x1+0.5);\n height=(size_t) floor(bounds.y2-bounds.y1+0.5);\n if (width > page.width)\n page.width=width;\n if (height > page.height)\n page.height=height;\n }\n (void) CloseBlob(image);\n /*\n Render PCL with the GhostPCL delegate.\n */\n if ((page.width == 0) || (page.height == 0))\n (void) ParseAbsoluteGeometry(PSPageGeometry,&page);\n if (image_info->page != (char *) NULL)\n (void) ParseAbsoluteGeometry(image_info->page,&page);\n (void) FormatLocaleString(geometry,MaxTextExtent,\"%.20gx%.20g\",(double)\n page.width,(double) page.height);\n if (image_info->monochrome != MagickFalse)\n delegate_info=GetDelegateInfo(\"pcl:mono\",(char *) NULL,exception);\n else\n if (cmyk != MagickFalse)\n delegate_info=GetDelegateInfo(\"pcl:cmyk\",(char *) NULL,exception);\n else\n delegate_info=GetDelegateInfo(\"pcl:color\",(char *) NULL,exception);\n if (delegate_info == (const DelegateInfo *) NULL)\n return((Image *) NULL);\n if ((page.width == 0) || (page.height == 0))\n (void) ParseAbsoluteGeometry(PSPageGeometry,&page);\n if (image_info->page != (char *) NULL)\n (void) ParseAbsoluteGeometry(image_info->page,&page);\n density=AcquireString(\"\");\n options=AcquireString(\"\");\n (void) FormatLocaleString(density,MaxTextExtent,\"%gx%g\",\n image->x_resolution,image->y_resolution);\n page.width=(size_t) floor((double) page.width*image->x_resolution/delta.x+\n 0.5);\n page.height=(size_t) floor((double) page.height*image->y_resolution/delta.y+\n 0.5);\n (void) FormatLocaleString(options,MaxTextExtent,\"-g%.20gx%.20g \",(double)\n page.width,(double) page.height);\n image=DestroyImage(image);\n read_info=CloneImageInfo(image_info);\n *read_info->magick='\\0';\n if (read_info->number_scenes != 0)\n {\n if (read_info->number_scenes != 1)\n (void) FormatLocaleString(options,MaxTextExtent,\"-dLastPage=%.20g\",\n (double) (read_info->scene+read_info->number_scenes));\n else\n (void) FormatLocaleString(options,MaxTextExtent,\n \"-dFirstPage=%.20g -dLastPage=%.20g\",(double) read_info->scene+1,\n (double) (read_info->scene+read_info->number_scenes));\n read_info->number_scenes=0;\n if (read_info->scenes != (char *) NULL)\n *read_info->scenes='\\0';\n }\n (void) CopyMagickString(filename,read_info->filename,MaxTextExtent);\n (void) AcquireUniqueFilename(read_info->filename);\n (void) FormatLocaleString(command,MaxTextExtent,\n GetDelegateCommands(delegate_info),\n read_info->antialias != MagickFalse ? 4 : 1,\n read_info->antialias != MagickFalse ? 4 : 1,density,options,\n read_info->filename,input_filename);\n options=DestroyString(options);\n density=DestroyString(density);\n status=ExternalDelegateCommand(MagickFalse,read_info->verbose,command,\n (char *) NULL,exception) != 0 ? MagickTrue : MagickFalse;\n image=ReadImage(read_info,exception);\n (void) RelinquishUniqueFileResource(read_info->filename);\n (void) RelinquishUniqueFileResource(input_filename);\n read_info=DestroyImageInfo(read_info);\n if (image == (Image *) NULL)\n ThrowReaderException(DelegateError,\"PCLDelegateFailed\");\n if (LocaleCompare(image->magick,\"BMP\") == 0)\n {\n Image\n *cmyk_image;\n\n cmyk_image=ConsolidateCMYKImages(image,&image->exception);\n if (cmyk_image != (Image *) NULL)\n {\n image=DestroyImageList(image);\n image=cmyk_image;\n }\n }\n do\n {\n (void) CopyMagickString(image->filename,filename,MaxTextExtent);\n image->page=page;\n next_image=SyncNextImageInList(image);\n if (next_image != (Image *) NULL)\n image=next_image;\n } while (next_image != (Image *) NULL);\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1520'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: copy_to_fd (const char *from, int tofd)\n{\n int fromfd;\n ssize_t i;\n\n if ((fromfd = safe_open (from, O_RDONLY | O_BINARY, 0)) < 0)\n pfatal (\"Can't reopen file %s\", quotearg (from));\n while ((i = read (fromfd, buf, bufsize)) != 0)\n {\n if (i == (ssize_t) -1)\n\tread_fatal ();\n if (full_write (tofd, buf, i) != i)\n\twrite_fatal ();\n }\n if (close (fromfd) != 0)\n read_fatal ();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59'], 'message': 'Don't follow symlinks unless --follow-symlinks is given\n\n* src/inp.c (plan_a, plan_b), src/util.c (copy_to_fd, copy_file,\nappend_to_file): Unless the --follow-symlinks option is given, open files with\nthe O_NOFOLLOW flag to avoid following symlinks. So far, we were only doing\nthat consistently for input files.\n* src/util.c (create_backup): When creating empty backup files, (re)create them\nwith O_CREAT | O_EXCL to avoid following symlinks in that case as well.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int set_geometry(unsigned int cmd, struct floppy_struct *g,\n\t\t\t int drive, int type, struct block_device *bdev)\n{\n\tint cnt;\n\n\t/* sanity checking for parameters. */\n\tif (g->sect <= 0 ||\n\t g->head <= 0 ||\n\t g->track <= 0 || g->track > UDP->tracks >> STRETCH(g) ||\n\t /* check if reserved bits are set */\n\t (g->stretch & ~(FD_STRETCH | FD_SWAPSIDES | FD_SECTBASEMASK)) != 0)\n\t\treturn -EINVAL;\n\tif (type) {\n\t\tif (!capable(CAP_SYS_ADMIN))\n\t\t\treturn -EPERM;\n\t\tmutex_lock(&open_lock);\n\t\tif (lock_fdc(drive)) {\n\t\t\tmutex_unlock(&open_lock);\n\t\t\treturn -EINTR;\n\t\t}\n\t\tfloppy_type[type] = *g;\n\t\tfloppy_type[type].name = \"user format\";\n\t\tfor (cnt = type << 2; cnt < (type << 2) + 4; cnt++)\n\t\t\tfloppy_sizes[cnt] = floppy_sizes[cnt + 0x80] =\n\t\t\t floppy_type[type].size + 1;\n\t\tprocess_fd_request();\n\t\tfor (cnt = 0; cnt < N_DRIVE; cnt++) {\n\t\t\tstruct block_device *bdev = opened_bdev[cnt];\n\t\t\tif (!bdev || ITYPE(drive_state[cnt].fd_device) != type)\n\t\t\t\tcontinue;\n\t\t\t__invalidate_device(bdev, true);\n\t\t}\n\t\tmutex_unlock(&open_lock);\n\t} else {\n\t\tint oldStretch;\n\n\t\tif (lock_fdc(drive))\n\t\t\treturn -EINTR;\n\t\tif (cmd != FDDEFPRM) {\n\t\t\t/* notice a disk change immediately, else\n\t\t\t * we lose our settings immediately*/\n\t\t\tif (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR)\n\t\t\t\treturn -EINTR;\n\t\t}\n\t\toldStretch = g->stretch;\n\t\tuser_params[drive] = *g;\n\t\tif (buffer_drive == drive)\n\t\t\tSUPBOUND(buffer_max, user_params[drive].sect);\n\t\tcurrent_type[drive] = &user_params[drive];\n\t\tfloppy_sizes[drive] = user_params[drive].size;\n\t\tif (cmd == FDDEFPRM)\n\t\t\tDRS->keep_data = -1;\n\t\telse\n\t\t\tDRS->keep_data = 1;\n\t\t/* invalidation. Invalidate only when needed, i.e.\n\t\t * when there are already sectors in the buffer cache\n\t\t * whose number will change. This is useful, because\n\t\t * mtools often changes the geometry of the disk after\n\t\t * looking at the boot block */\n\t\tif (DRS->maxblock > user_params[drive].sect ||\n\t\t DRS->maxtrack ||\n\t\t ((user_params[drive].sect ^ oldStretch) &\n\t\t (FD_SWAPSIDES | FD_SECTBASEMASK)))\n\t\t\tinvalidate_drive(bdev);\n\t\telse\n\t\t\tprocess_fd_request();\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-369'], 'message': 'floppy: fix div-by-zero in setup_format_params\n\nThis fixes a divide by zero error in the setup_format_params function of\nthe floppy driver.\n\nTwo consecutive ioctls can trigger the bug: The first one should set the\ndrive geometry with such .sect and .rate values for the F_SECT_PER_TRACK\nto become zero. Next, the floppy format operation should be called.\n\nA floppy disk is not required to be inserted. An unprivileged user\ncould trigger the bug if the device is accessible.\n\nThe patch checks F_SECT_PER_TRACK for a non-zero value in the\nset_geometry function. The proper check should involve a reasonable\nupper limit for the .sect and .rate fields, but it could change the\nUAPI.\n\nThe patch also checks F_SECT_PER_TRACK in the setup_format_params, and\ncancels the formatting operation in case of zero.\n\nThe bug was found by syzkaller.\n\nSigned-off-by: Denis Efremov \nTested-by: Willy Tarreau \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int cx24116_send_diseqc_msg(struct dvb_frontend *fe,\n\tstruct dvb_diseqc_master_cmd *d)\n{\n\tstruct cx24116_state *state = fe->demodulator_priv;\n\tint i, ret;\n\n\t/* Dump DiSEqC message */\n\tif (debug) {\n\t\tprintk(KERN_INFO \"cx24116: %s(\", __func__);\n\t\tfor (i = 0 ; i < d->msg_len ;) {\n\t\t\tprintk(KERN_INFO \"0x%02x\", d->msg[i]);\n\t\t\tif (++i < d->msg_len)\n\t\t\t\tprintk(KERN_INFO \", \");\n\t\t}\n\t\tprintk(\") toneburst=%d\\n\", toneburst);\n\t}\n\n\t/* Validate length */\n\tif (d->msg_len > (CX24116_ARGLEN - CX24116_DISEQC_MSGOFS))\n\t\treturn -EINVAL;\n\n\t/* DiSEqC message */\n\tfor (i = 0; i < d->msg_len; i++)\n\t\tstate->dsec_cmd.args[CX24116_DISEQC_MSGOFS + i] = d->msg[i];\n\n\t/* DiSEqC message length */\n\tstate->dsec_cmd.args[CX24116_DISEQC_MSGLEN] = d->msg_len;\n\n\t/* Command length */\n\tstate->dsec_cmd.len = CX24116_DISEQC_MSGOFS +\n\t\tstate->dsec_cmd.args[CX24116_DISEQC_MSGLEN];\n\n\t/* DiSEqC toneburst */\n\tif (toneburst == CX24116_DISEQC_MESGCACHE)\n\t\t/* Message is cached */\n\t\treturn 0;\n\n\telse if (toneburst == CX24116_DISEQC_TONEOFF)\n\t\t/* Message is sent without burst */\n\t\tstate->dsec_cmd.args[CX24116_DISEQC_BURST] = 0;\n\n\telse if (toneburst == CX24116_DISEQC_TONECACHE) {\n\t\t/*\n\t\t * Message is sent with derived else cached burst\n\t\t *\n\t\t * WRITE PORT GROUP COMMAND 38\n\t\t *\n\t\t * 0/A/A: E0 10 38 F0..F3\n\t\t * 1/B/B: E0 10 38 F4..F7\n\t\t * 2/C/A: E0 10 38 F8..FB\n\t\t * 3/D/B: E0 10 38 FC..FF\n\t\t *\n\t\t * databyte[3]= 8421:8421\n\t\t * ABCD:WXYZ\n\t\t * CLR :SET\n\t\t *\n\t\t * WX= PORT SELECT 0..3 (X=TONEBURST)\n\t\t * Y = VOLTAGE (0=13V, 1=18V)\n\t\t * Z = BAND (0=LOW, 1=HIGH(22K))\n\t\t */\n\t\tif (d->msg_len >= 4 && d->msg[2] == 0x38)\n\t\t\tstate->dsec_cmd.args[CX24116_DISEQC_BURST] =\n\t\t\t\t((d->msg[3] & 4) >> 2);\n\t\tif (debug)\n\t\t\tdprintk(\"%s burst=%d\\n\", __func__,\n\t\t\t\tstate->dsec_cmd.args[CX24116_DISEQC_BURST]);\n\t}\n\n\t/* Wait for LNB ready */\n\tret = cx24116_wait_for_lnb(fe);\n\tif (ret != 0)\n\t\treturn ret;\n\n\t/* Wait for voltage/min repeat delay */\n\tmsleep(100);\n\n\t/* Command */\n\tret = cx24116_cmd_execute(fe, &state->dsec_cmd);\n\tif (ret != 0)\n\t\treturn ret;\n\t/*\n\t * Wait for send\n\t *\n\t * Eutelsat spec:\n\t * >15ms delay + (XXX determine if FW does this, see set_tone)\n\t * 13.5ms per byte +\n\t * >15ms delay +\n\t * 12.5ms burst +\n\t * >15ms delay (XXX determine if FW does this, see set_tone)\n\t */\n\tmsleep((state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] << 4) +\n\t\t((toneburst == CX24116_DISEQC_TONEOFF) ? 30 : 60));\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-119', 'CWE-125'], 'message': '[media] cx24116: fix a buffer overflow when checking userspace params\n\nThe maximum size for a DiSEqC command is 6, according to the\nuserspace API. However, the code allows to write up much more values:\n\tdrivers/media/dvb-frontends/cx24116.c:983 cx24116_send_diseqc_msg() error: buffer overflow 'd->msg' 6 <= 23\n\nCc: stable@vger.kernel.org\nSigned-off-by: Mauro Carvalho Chehab '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: asn1_get_string(\n unsigned char **buffer,\t\t/* IO - Pointer in buffer */\n unsigned char *bufend,\t\t/* I - End of buffer */\n unsigned length,\t\t/* I - Value length */\n char *string,\t\t/* I - String buffer */\n size_t strsize)\t\t/* I - String buffer size */\n{\n if (length > (unsigned)(bufend - *buffer))\n length = (unsigned)(bufend - *buffer);\n\n if (length < strsize)\n {\n /*\n * String is smaller than the buffer...\n */\n\n if (length > 0)\n memcpy(string, *buffer, length);\n\n string[length] = '\\0';\n }\n else\n {\n /*\n * String is larger than the buffer...\n */\n\n memcpy(string, *buffer, strsize - 1);\n string[strsize - 1] = '\\0';\n }\n\n if (length > 0)\n (*buffer) += length;\n\n return (string);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'Fix multiple security/disclosure issues:\n\n- CVE-2019-8696 and CVE-2019-8675: Fixed SNMP buffer overflows (rdar://51685251)\n- Fixed IPP buffer overflow (rdar://50035411)\n- Fixed memory disclosure issue in the scheduler (rdar://51373853)\n- Fixed DoS issues in the scheduler (rdar://51373929)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int exif_scan_thumbnail(image_info_type *ImageInfo)\n{\n\tuchar c, *data = (uchar*)ImageInfo->Thumbnail.data;\n\tint n, marker;\n\tsize_t length=2, pos=0;\n\tjpeg_sof_info sof_info;\n\n\tif (!data) {\n\t\treturn FALSE; /* nothing to do here */\n\t}\n\tif (memcmp(data, \"\\xFF\\xD8\\xFF\", 3)) {\n\t\tif (!ImageInfo->Thumbnail.width && !ImageInfo->Thumbnail.height) {\n\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, \"Thumbnail is not a JPEG image\");\n\t\t}\n\t\treturn FALSE;\n\t}\n\tfor (;;) {\n\t\tpos += length;\n\t\tif (pos>=ImageInfo->Thumbnail.size)\n\t\t\treturn FALSE;\n\t\tc = data[pos++];\n\t\tif (pos>=ImageInfo->Thumbnail.size)\n\t\t\treturn FALSE;\n\t\tif (c != 0xFF) {\n\t\t\treturn FALSE;\n\t\t}\n\t\tn = 8;\n\t\twhile ((c = data[pos++]) == 0xFF && n--) {\n\t\t\tif (pos+3>=ImageInfo->Thumbnail.size)\n\t\t\t\treturn FALSE;\n\t\t\t/* +3 = pos++ of next check when reaching marker + 2 bytes for length */\n\t\t}\n\t\tif (c == 0xFF)\n\t\t\treturn FALSE;\n\t\tmarker = c;\n\t\tif (pos>=ImageInfo->Thumbnail.size)\n\t\t\treturn FALSE;\n\t\tlength = php_jpg_get16(data+pos);\n\t\tif (length > ImageInfo->Thumbnail.size || pos >= ImageInfo->Thumbnail.size - length) {\n\t\t\treturn FALSE;\n\t\t}\n#ifdef EXIF_DEBUG\n\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Thumbnail: process section(x%02X=%s) @ x%04X + x%04X\", marker, exif_get_markername(marker), pos, length);\n#endif\n\t\tswitch (marker) {\n\t\t\tcase M_SOF0:\n\t\t\tcase M_SOF1:\n\t\t\tcase M_SOF2:\n\t\t\tcase M_SOF3:\n\t\t\tcase M_SOF5:\n\t\t\tcase M_SOF6:\n\t\t\tcase M_SOF7:\n\t\t\tcase M_SOF9:\n\t\t\tcase M_SOF10:\n\t\t\tcase M_SOF11:\n\t\t\tcase M_SOF13:\n\t\t\tcase M_SOF14:\n\t\t\tcase M_SOF15:\n\t\t\t\t/* handle SOFn block */\n\t\t\t\tif (length < 8 || ImageInfo->Thumbnail.size - 8 < pos) {\n\t\t\t\t\t/* exif_process_SOFn needs 8 bytes */\n\t\t\t\t\treturn FALSE;\n\t\t\t\t}\n\t\t\t\texif_process_SOFn(data+pos, marker, &sof_info);\n\t\t\t\tImageInfo->Thumbnail.height = sof_info.height;\n\t\t\t\tImageInfo->Thumbnail.width = sof_info.width;\n#ifdef EXIF_DEBUG\n\t\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, \"Thumbnail: size: %d * %d\", sof_info.width, sof_info.height);\n#endif\n\t\t\t\treturn TRUE;\n\n\t\t\tcase M_SOS:\n\t\t\tcase M_EOI:\n\t\t\t\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, \"Could not compute size of thumbnail\");\n\t\t\t\treturn FALSE;\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\t/* just skip */\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\texif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, \"Could not compute size of thumbnail\");\n\treturn FALSE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #78222 (heap-buffer-overflow on exif_scan_thumbnail)\n\n(cherry picked from commit dea2989ab8ba87a6180af497b2efaf0527e985c5)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int h2_mplx_awaits_data(h2_mplx *m)\n{\n int waiting = 1;\n \n H2_MPLX_ENTER_ALWAYS(m);\n\n if (h2_ihash_empty(m->streams)) {\n waiting = 0;\n }\n else if (!m->tasks_active && !h2_ififo_count(m->readyq)\n && h2_iq_empty(m->q)) {\n waiting = 0;\n }\n\n H2_MPLX_LEAVE(m);\n return waiting;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-770'], 'message': '* fixes Timeout vs. KeepAliveTimeout behaviour, see PR 63534 (for trunk now,\n mpm event backport to 2.4.x up for vote).\n * Fixes stream cleanup when connection throttling is in place.\n * Counts stream resets by client on streams initiated by client as cause\n for connection throttling.\n * Header length checks are now logged similar to HTTP/1.1 protocol handler (thanks @mkaufmann)\n * Header length is checked also on the merged value from several header instances\n and results in a 431 response.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static h2_stream *get_timed_out_busy_stream(h2_mplx *m) \n{\n stream_iter_ctx ctx;\n ctx.m = m;\n ctx.stream = NULL;\n ctx.now = apr_time_now();\n h2_ihash_iter(m->streams, timed_out_busy_iter, &ctx);\n return ctx.stream;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-770'], 'message': '* fixes Timeout vs. KeepAliveTimeout behaviour, see PR 63534 (for trunk now,\n mpm event backport to 2.4.x up for vote).\n * Fixes stream cleanup when connection throttling is in place.\n * Counts stream resets by client on streams initiated by client as cause\n for connection throttling.\n * Header length checks are now logged similar to HTTP/1.1 protocol handler (thanks @mkaufmann)\n * Header length is checked also on the merged value from several header instances\n and results in a 431 response.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int pdf_load_xrefs(FILE *fp, pdf_t *pdf)\n{\n int i, ver, is_linear;\n long pos, pos_count;\n char x, *c, buf[256];\n \n c = NULL;\n\n /* Count number of xrefs */\n pdf->n_xrefs = 0;\n fseek(fp, 0, SEEK_SET);\n while (get_next_eof(fp) >= 0)\n ++pdf->n_xrefs;\n\n if (!pdf->n_xrefs)\n return 0;\n\n /* Load in the start/end positions */\n fseek(fp, 0, SEEK_SET);\n pdf->xrefs = calloc(1, sizeof(xref_t) * pdf->n_xrefs);\n ver = 1;\n for (i=0; in_xrefs; i++)\n {\n /* Seek to %%EOF */\n if ((pos = get_next_eof(fp)) < 0)\n break;\n\n /* Set and increment the version */\n pdf->xrefs[i].version = ver++;\n\n /* Rewind until we find end of \"startxref\" */\n pos_count = 0;\n while (SAFE_F(fp, ((x = fgetc(fp)) != 'f')))\n fseek(fp, pos - (++pos_count), SEEK_SET);\n \n /* Suck in end of \"startxref\" to start of %%EOF */\n if (pos_count >= sizeof(buf)) {\n ERR(\"Failed to locate the startxref token. \"\n \"This might be a corrupt PDF.\\n\");\n return -1;\n }\n memset(buf, 0, sizeof(buf));\n SAFE_E(fread(buf, 1, pos_count, fp), pos_count,\n \"Failed to read startxref.\\n\");\n c = buf;\n while (*c == ' ' || *c == '\\n' || *c == '\\r')\n ++c;\n \n /* xref start position */\n pdf->xrefs[i].start = atol(c);\n\n /* If xref is 0 handle linear xref table */\n if (pdf->xrefs[i].start == 0)\n get_xref_linear_skipped(fp, &pdf->xrefs[i]);\n\n /* Non-linear, normal operation, so just find the end of the xref */\n else\n {\n /* xref end position */\n pos = ftell(fp);\n fseek(fp, pdf->xrefs[i].start, SEEK_SET);\n pdf->xrefs[i].end = get_next_eof(fp);\n\n /* Look for next EOF and xref data */\n fseek(fp, pos, SEEK_SET);\n }\n\n /* Check validity */\n if (!is_valid_xref(fp, pdf, &pdf->xrefs[i]))\n {\n is_linear = pdf->xrefs[i].is_linear;\n memset(&pdf->xrefs[i], 0, sizeof(xref_t));\n pdf->xrefs[i].is_linear = is_linear;\n rewind(fp);\n get_next_eof(fp);\n continue;\n }\n\n /* Load the entries from the xref */\n load_xref_entries(fp, &pdf->xrefs[i]);\n }\n\n /* Now we have all xref tables, if this is linearized, we need\n * to make adjustments so that things spit out properly\n */\n if (pdf->xrefs[0].is_linear)\n resolve_linearized_pdf(pdf);\n\n /* Ok now we have all xref data. Go through those versions of the \n * PDF and try to obtain creator information\n */\n load_creator(fp, pdf);\n\n return pdf->n_xrefs;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Zero and sanity check all dynamic allocs.\n\nThis addresses the memory issues in Issue #6 expressed in\ncalloc_some.pdf and malloc_some.pdf'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int f_midi_set_alt(struct usb_function *f, unsigned intf, unsigned alt)\n{\n\tstruct f_midi *midi = func_to_midi(f);\n\tunsigned i;\n\tint err;\n\n\t/* we only set alt for MIDIStreaming interface */\n\tif (intf != midi->ms_id)\n\t\treturn 0;\n\n\terr = f_midi_start_ep(midi, f, midi->in_ep);\n\tif (err)\n\t\treturn err;\n\n\terr = f_midi_start_ep(midi, f, midi->out_ep);\n\tif (err)\n\t\treturn err;\n\n\t/* pre-allocate write usb requests to use on f_midi_transmit. */\n\twhile (kfifo_avail(&midi->in_req_fifo)) {\n\t\tstruct usb_request *req =\n\t\t\tmidi_alloc_ep_req(midi->in_ep, midi->buflen);\n\n\t\tif (req == NULL)\n\t\t\treturn -ENOMEM;\n\n\t\treq->length = 0;\n\t\treq->complete = f_midi_complete;\n\n\t\tkfifo_put(&midi->in_req_fifo, req);\n\t}\n\n\t/* allocate a bunch of read buffers and queue them all at once. */\n\tfor (i = 0; i < midi->qlen && err == 0; i++) {\n\t\tstruct usb_request *req =\n\t\t\tmidi_alloc_ep_req(midi->out_ep, midi->buflen);\n\n\t\tif (req == NULL)\n\t\t\treturn -ENOMEM;\n\n\t\treq->complete = f_midi_complete;\n\t\terr = usb_ep_queue(midi->out_ep, req, GFP_ATOMIC);\n\t\tif (err) {\n\t\t\tERROR(midi, \"%s: couldn't enqueue request: %d\\n\",\n\t\t\t\t midi->out_ep->name, err);\n\t\t\tfree_ep_req(midi->out_ep, req);\n\t\t\treturn err;\n\t\t}\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'USB: gadget: f_midi: fixing a possible double-free in f_midi\n\nIt looks like there is a possibility of a double-free vulnerability on an\nerror path of the f_midi_set_alt function in the f_midi driver. If the\npath is feasible then free_ep_req gets called twice:\n\n req->complete = f_midi_complete;\n err = usb_ep_queue(midi->out_ep, req, GFP_ATOMIC);\n => ...\n usb_gadget_giveback_request\n =>\n f_midi_complete (CALLBACK)\n (inside f_midi_complete, for various cases of status)\n free_ep_req(ep, req); // first kfree\n if (err) {\n ERROR(midi, \"%s: couldn't enqueue request: %d\\n\",\n midi->out_ep->name, err);\n free_ep_req(midi->out_ep, req); // second kfree\n return err;\n }\n\nThe double-free possibility was introduced with commit ad0d1a058eac\n(\"usb: gadget: f_midi: fix leak on failed to enqueue out requests\").\n\nFound by MOXCAFE tool.\n\nSigned-off-by: Tuba Yavuz \nFixes: ad0d1a058eac (\"usb: gadget: f_midi: fix leak on failed to enqueue out requests\")\nAcked-by: Felipe Balbi \nCc: stable \nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int check_input_term(struct mixer_build *state, int id,\n\t\t\t struct usb_audio_term *term)\n{\n\tint protocol = state->mixer->protocol;\n\tint err;\n\tvoid *p1;\n\n\tmemset(term, 0, sizeof(*term));\n\twhile ((p1 = find_audio_control_unit(state, id)) != NULL) {\n\t\tunsigned char *hdr = p1;\n\t\tterm->id = id;\n\n\t\tif (protocol == UAC_VERSION_1 || protocol == UAC_VERSION_2) {\n\t\t\tswitch (hdr[2]) {\n\t\t\tcase UAC_INPUT_TERMINAL:\n\t\t\t\tif (protocol == UAC_VERSION_1) {\n\t\t\t\t\tstruct uac_input_terminal_descriptor *d = p1;\n\n\t\t\t\t\tterm->type = le16_to_cpu(d->wTerminalType);\n\t\t\t\t\tterm->channels = d->bNrChannels;\n\t\t\t\t\tterm->chconfig = le16_to_cpu(d->wChannelConfig);\n\t\t\t\t\tterm->name = d->iTerminal;\n\t\t\t\t} else { /* UAC_VERSION_2 */\n\t\t\t\t\tstruct uac2_input_terminal_descriptor *d = p1;\n\n\t\t\t\t\t/* call recursively to verify that the\n\t\t\t\t\t * referenced clock entity is valid */\n\t\t\t\t\terr = check_input_term(state, d->bCSourceID, term);\n\t\t\t\t\tif (err < 0)\n\t\t\t\t\t\treturn err;\n\n\t\t\t\t\t/* save input term properties after recursion,\n\t\t\t\t\t * to ensure they are not overriden by the\n\t\t\t\t\t * recursion calls */\n\t\t\t\t\tterm->id = id;\n\t\t\t\t\tterm->type = le16_to_cpu(d->wTerminalType);\n\t\t\t\t\tterm->channels = d->bNrChannels;\n\t\t\t\t\tterm->chconfig = le32_to_cpu(d->bmChannelConfig);\n\t\t\t\t\tterm->name = d->iTerminal;\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\tcase UAC_FEATURE_UNIT: {\n\t\t\t\t/* the header is the same for v1 and v2 */\n\t\t\t\tstruct uac_feature_unit_descriptor *d = p1;\n\n\t\t\t\tid = d->bSourceID;\n\t\t\t\tbreak; /* continue to parse */\n\t\t\t}\n\t\t\tcase UAC_MIXER_UNIT: {\n\t\t\t\tstruct uac_mixer_unit_descriptor *d = p1;\n\n\t\t\t\tterm->type = UAC3_MIXER_UNIT << 16; /* virtual type */\n\t\t\t\tterm->channels = uac_mixer_unit_bNrChannels(d);\n\t\t\t\tterm->chconfig = uac_mixer_unit_wChannelConfig(d, protocol);\n\t\t\t\tterm->name = uac_mixer_unit_iMixer(d);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tcase UAC_SELECTOR_UNIT:\n\t\t\tcase UAC2_CLOCK_SELECTOR: {\n\t\t\t\tstruct uac_selector_unit_descriptor *d = p1;\n\t\t\t\t/* call recursively to retrieve the channel info */\n\t\t\t\terr = check_input_term(state, d->baSourceID[0], term);\n\t\t\t\tif (err < 0)\n\t\t\t\t\treturn err;\n\t\t\t\tterm->type = UAC3_SELECTOR_UNIT << 16; /* virtual type */\n\t\t\t\tterm->id = id;\n\t\t\t\tterm->name = uac_selector_unit_iSelector(d);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tcase UAC1_PROCESSING_UNIT:\n\t\t\t/* UAC2_EFFECT_UNIT */\n\t\t\t\tif (protocol == UAC_VERSION_1)\n\t\t\t\t\tterm->type = UAC3_PROCESSING_UNIT << 16; /* virtual type */\n\t\t\t\telse /* UAC_VERSION_2 */\n\t\t\t\t\tterm->type = UAC3_EFFECT_UNIT << 16; /* virtual type */\n\t\t\t\t/* fall through */\n\t\t\tcase UAC1_EXTENSION_UNIT:\n\t\t\t/* UAC2_PROCESSING_UNIT_V2 */\n\t\t\t\tif (protocol == UAC_VERSION_1 && !term->type)\n\t\t\t\t\tterm->type = UAC3_EXTENSION_UNIT << 16; /* virtual type */\n\t\t\t\telse if (protocol == UAC_VERSION_2 && !term->type)\n\t\t\t\t\tterm->type = UAC3_PROCESSING_UNIT << 16; /* virtual type */\n\t\t\t\t/* fall through */\n\t\t\tcase UAC2_EXTENSION_UNIT_V2: {\n\t\t\t\tstruct uac_processing_unit_descriptor *d = p1;\n\n\t\t\t\tif (protocol == UAC_VERSION_2 &&\n\t\t\t\t\thdr[2] == UAC2_EFFECT_UNIT) {\n\t\t\t\t\t/* UAC2/UAC1 unit IDs overlap here in an\n\t\t\t\t\t * uncompatible way. Ignore this unit for now.\n\t\t\t\t\t */\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\n\t\t\t\tif (d->bNrInPins) {\n\t\t\t\t\tid = d->baSourceID[0];\n\t\t\t\t\tbreak; /* continue to parse */\n\t\t\t\t}\n\t\t\t\tif (!term->type)\n\t\t\t\t\tterm->type = UAC3_EXTENSION_UNIT << 16; /* virtual type */\n\n\t\t\t\tterm->channels = uac_processing_unit_bNrChannels(d);\n\t\t\t\tterm->chconfig = uac_processing_unit_wChannelConfig(d, protocol);\n\t\t\t\tterm->name = uac_processing_unit_iProcessing(d, protocol);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tcase UAC2_CLOCK_SOURCE: {\n\t\t\t\tstruct uac_clock_source_descriptor *d = p1;\n\n\t\t\t\tterm->type = UAC3_CLOCK_SOURCE << 16; /* virtual type */\n\t\t\t\tterm->id = id;\n\t\t\t\tterm->name = d->iClockSource;\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn -ENODEV;\n\t\t\t}\n\t\t} else { /* UAC_VERSION_3 */\n\t\t\tswitch (hdr[2]) {\n\t\t\tcase UAC_INPUT_TERMINAL: {\n\t\t\t\tstruct uac3_input_terminal_descriptor *d = p1;\n\n\t\t\t\t/* call recursively to verify that the\n\t\t\t\t * referenced clock entity is valid */\n\t\t\t\terr = check_input_term(state, d->bCSourceID, term);\n\t\t\t\tif (err < 0)\n\t\t\t\t\treturn err;\n\n\t\t\t\t/* save input term properties after recursion,\n\t\t\t\t * to ensure they are not overriden by the\n\t\t\t\t * recursion calls */\n\t\t\t\tterm->id = id;\n\t\t\t\tterm->type = le16_to_cpu(d->wTerminalType);\n\n\t\t\t\terr = get_cluster_channels_v3(state, le16_to_cpu(d->wClusterDescrID));\n\t\t\t\tif (err < 0)\n\t\t\t\t\treturn err;\n\t\t\t\tterm->channels = err;\n\n\t\t\t\t/* REVISIT: UAC3 IT doesn't have channels cfg */\n\t\t\t\tterm->chconfig = 0;\n\n\t\t\t\tterm->name = le16_to_cpu(d->wTerminalDescrStr);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tcase UAC3_FEATURE_UNIT: {\n\t\t\t\tstruct uac3_feature_unit_descriptor *d = p1;\n\n\t\t\t\tid = d->bSourceID;\n\t\t\t\tbreak; /* continue to parse */\n\t\t\t}\n\t\t\tcase UAC3_CLOCK_SOURCE: {\n\t\t\t\tstruct uac3_clock_source_descriptor *d = p1;\n\n\t\t\t\tterm->type = UAC3_CLOCK_SOURCE << 16; /* virtual type */\n\t\t\t\tterm->id = id;\n\t\t\t\tterm->name = le16_to_cpu(d->wClockSourceStr);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tcase UAC3_MIXER_UNIT: {\n\t\t\t\tstruct uac_mixer_unit_descriptor *d = p1;\n\n\t\t\t\terr = uac_mixer_unit_get_channels(state, d);\n\t\t\t\tif (err <= 0)\n\t\t\t\t\treturn err;\n\n\t\t\t\tterm->channels = err;\n\t\t\t\tterm->type = UAC3_MIXER_UNIT << 16; /* virtual type */\n\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tcase UAC3_SELECTOR_UNIT:\n\t\t\tcase UAC3_CLOCK_SELECTOR: {\n\t\t\t\tstruct uac_selector_unit_descriptor *d = p1;\n\t\t\t\t/* call recursively to retrieve the channel info */\n\t\t\t\terr = check_input_term(state, d->baSourceID[0], term);\n\t\t\t\tif (err < 0)\n\t\t\t\t\treturn err;\n\t\t\t\tterm->type = UAC3_SELECTOR_UNIT << 16; /* virtual type */\n\t\t\t\tterm->id = id;\n\t\t\t\tterm->name = 0; /* TODO: UAC3 Class-specific strings */\n\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tcase UAC3_PROCESSING_UNIT: {\n\t\t\t\tstruct uac_processing_unit_descriptor *d = p1;\n\n\t\t\t\tif (!d->bNrInPins)\n\t\t\t\t\treturn -EINVAL;\n\n\t\t\t\t/* call recursively to retrieve the channel info */\n\t\t\t\terr = check_input_term(state, d->baSourceID[0], term);\n\t\t\t\tif (err < 0)\n\t\t\t\t\treturn err;\n\n\t\t\t\tterm->type = UAC3_PROCESSING_UNIT << 16; /* virtual type */\n\t\t\t\tterm->id = id;\n\t\t\t\tterm->name = 0; /* TODO: UAC3 Class-specific strings */\n\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn -ENODEV;\n\t\t\t}\n\t\t}\n\t}\n\treturn -ENODEV;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-674'], 'message': 'ALSA: usb-audio: Fix a stack buffer overflow bug in check_input_term\n\n`check_input_term` recursively calls itself with input from\ndevice side (e.g., uac_input_terminal_descriptor.bCSourceID)\nas argument (id). In `check_input_term`, if `check_input_term`\nis called with the same `id` argument as the caller, it triggers\nendless recursive call, resulting kernel space stack overflow.\n\nThis patch fixes the bug by adding a bitmap to `struct mixer_build`\nto keep track of the checked ids and stop the execution if some id\nhas been checked (similar to how parse_audio_unit handles unitid\nargument).\n\nReported-by: Hui Peng \nReported-by: Mathias Payer \nSigned-off-by: Hui Peng \nCc: \nSigned-off-by: Takashi Iwai '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void dvb_usb_device_exit(struct usb_interface *intf)\n{\n\tstruct dvb_usb_device *d = usb_get_intfdata(intf);\n\tconst char *name = \"generic DVB-USB module\";\n\n\tusb_set_intfdata(intf, NULL);\n\tif (d != NULL && d->desc != NULL) {\n\t\tname = d->desc->name;\n\t\tdvb_usb_exit(d);\n\t}\n\tinfo(\"%s successfully deinitialized and disconnected.\", name);\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'media: dvb: usb: fix use after free in dvb_usb_device_exit\n\ndvb_usb_device_exit() frees and uses the device name in that order.\nFix by storing the name in a buffer before freeing it.\n\nSigned-off-by: Oliver Neukum \nReported-by: syzbot+26ec41e9f788b3eba396@syzkaller.appspotmail.com\nSigned-off-by: Sean Young \nSigned-off-by: Mauro Carvalho Chehab '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void cpia2_usb_disconnect(struct usb_interface *intf)\n{\n\tstruct camera_data *cam = usb_get_intfdata(intf);\n\tusb_set_intfdata(intf, NULL);\n\n\tDBG(\"Stopping stream\\n\");\n\tcpia2_usb_stream_stop(cam);\n\n\tmutex_lock(&cam->v4l2_lock);\n\tDBG(\"Unregistering camera\\n\");\n\tcpia2_unregister_camera(cam);\n\tv4l2_device_disconnect(&cam->v4l2_dev);\n\tmutex_unlock(&cam->v4l2_lock);\n\tv4l2_device_put(&cam->v4l2_dev);\n\n\tif(cam->buffers) {\n\t\tDBG(\"Wakeup waiting processes\\n\");\n\t\tcam->curbuff->status = FRAME_READY;\n\t\tcam->curbuff->length = 0;\n\t\twake_up_interruptible(&cam->wq_stream);\n\t}\n\n\tLOG(\"CPiA2 camera disconnected.\\n\");\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'media: cpia2_usb: first wake up, then free in disconnect\n\nKasan reported a use after free in cpia2_usb_disconnect()\nIt first freed everything and then woke up those waiting.\nThe reverse order is correct.\n\nFixes: 6c493f8b28c67 (\"[media] cpia2: major overhaul to get it in a working state again\")\n\nSigned-off-by: Oliver Neukum \nReported-by: syzbot+0c90fc937c84f97d0aa6@syzkaller.appspotmail.com\nSigned-off-by: Hans Verkuil \nSigned-off-by: Mauro Carvalho Chehab '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: const std::array md5() const {\n int len = 0;\n const char* data = nullptr;\n if (type() == BinData && binDataType() == BinDataType::MD5Type)\n data = binData(len);\n uassert(40437, \"md5 must be a 16-byte binary field with MD5 (5) subtype\", len == 16);\n std::array result;\n memcpy(&result, data, len);\n return result;\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-613'], 'message': 'SERVER-38984 Validate unique User ID on UserCache hit'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: Status V2UserDocumentParser::checkValidUserDocument(const BSONObj& doc) const {\n BSONElement userElement = doc[AuthorizationManager::USER_NAME_FIELD_NAME];\n BSONElement userDBElement = doc[AuthorizationManager::USER_DB_FIELD_NAME];\n BSONElement credentialsElement = doc[CREDENTIALS_FIELD_NAME];\n BSONElement rolesElement = doc[ROLES_FIELD_NAME];\n\n // Validate the \"user\" element.\n if (userElement.type() != String)\n return _badValue(\"User document needs 'user' field to be a string\", 0);\n if (userElement.valueStringData().empty())\n return _badValue(\"User document needs 'user' field to be non-empty\", 0);\n\n // Validate the \"db\" element\n if (userDBElement.type() != String || userDBElement.valueStringData().empty()) {\n return _badValue(\"User document needs 'db' field to be a non-empty string\", 0);\n }\n StringData userDBStr = userDBElement.valueStringData();\n if (!NamespaceString::validDBName(userDBStr, NamespaceString::DollarInDbNameBehavior::Allow) &&\n userDBStr != \"$external\") {\n return _badValue(mongoutils::str::stream() << \"'\" << userDBStr\n << \"' is not a valid value for the db field.\",\n 0);\n }\n\n // Validate the \"credentials\" element\n if (credentialsElement.eoo()) {\n return _badValue(\"User document needs 'credentials' object\", 0);\n }\n if (credentialsElement.type() != Object) {\n return _badValue(\"User document needs 'credentials' field to be an object\", 0);\n }\n\n BSONObj credentialsObj = credentialsElement.Obj();\n if (credentialsObj.isEmpty()) {\n return _badValue(\"User document needs 'credentials' field to be a non-empty object\", 0);\n }\n if (userDBStr == \"$external\") {\n BSONElement externalElement = credentialsObj[MONGODB_EXTERNAL_CREDENTIAL_FIELD_NAME];\n if (externalElement.eoo() || externalElement.type() != Bool || !externalElement.Bool()) {\n return _badValue(\n \"User documents for users defined on '$external' must have \"\n \"'credentials' field set to {external: true}\",\n 0);\n }\n } else {\n BSONElement scramElement = credentialsObj[SCRAM_CREDENTIAL_FIELD_NAME];\n BSONElement mongoCRElement = credentialsObj[MONGODB_CR_CREDENTIAL_FIELD_NAME];\n\n if (!mongoCRElement.eoo()) {\n if (mongoCRElement.type() != String || mongoCRElement.valueStringData().empty()) {\n return _badValue(\n \"MONGODB-CR credential must to be a non-empty string\"\n \", if present\",\n 0);\n }\n } else if (!scramElement.eoo()) {\n if (scramElement.type() != Object) {\n return _badValue(\"SCRAM credential must be an object, if present\", 0);\n }\n } else {\n return _badValue(\n \"User document must provide credentials for all \"\n \"non-external users\",\n 0);\n }\n }\n\n // Validate the \"roles\" element.\n Status status = _checkV2RolesArray(rolesElement);\n if (!status.isOK())\n return status;\n\n return Status::OK();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-613'], 'message': 'SERVER-38984 Validate unique User ID on UserCache hit\n\n(cherry picked from commit e55d6e2292e5dbe2f97153251d8193d1cc89f5d7)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static struct domain_device *sas_ex_discover_expander(\n\tstruct domain_device *parent, int phy_id)\n{\n\tstruct sas_expander_device *parent_ex = rphy_to_expander_device(parent->rphy);\n\tstruct ex_phy *phy = &parent->ex_dev.ex_phy[phy_id];\n\tstruct domain_device *child = NULL;\n\tstruct sas_rphy *rphy;\n\tstruct sas_expander_device *edev;\n\tstruct asd_sas_port *port;\n\tint res;\n\n\tif (phy->routing_attr == DIRECT_ROUTING) {\n\t\tpr_warn(\"ex %016llx:%02d:D <--> ex %016llx:0x%x is not allowed\\n\",\n\t\t\tSAS_ADDR(parent->sas_addr), phy_id,\n\t\t\tSAS_ADDR(phy->attached_sas_addr),\n\t\t\tphy->attached_phy_id);\n\t\treturn NULL;\n\t}\n\tchild = sas_alloc_device();\n\tif (!child)\n\t\treturn NULL;\n\n\tphy->port = sas_port_alloc(&parent->rphy->dev, phy_id);\n\t/* FIXME: better error handling */\n\tBUG_ON(sas_port_add(phy->port) != 0);\n\n\n\tswitch (phy->attached_dev_type) {\n\tcase SAS_EDGE_EXPANDER_DEVICE:\n\t\trphy = sas_expander_alloc(phy->port,\n\t\t\t\t\t SAS_EDGE_EXPANDER_DEVICE);\n\t\tbreak;\n\tcase SAS_FANOUT_EXPANDER_DEVICE:\n\t\trphy = sas_expander_alloc(phy->port,\n\t\t\t\t\t SAS_FANOUT_EXPANDER_DEVICE);\n\t\tbreak;\n\tdefault:\n\t\trphy = NULL;\t/* shut gcc up */\n\t\tBUG();\n\t}\n\tport = parent->port;\n\tchild->rphy = rphy;\n\tget_device(&rphy->dev);\n\tedev = rphy_to_expander_device(rphy);\n\tchild->dev_type = phy->attached_dev_type;\n\tkref_get(&parent->kref);\n\tchild->parent = parent;\n\tchild->port = port;\n\tchild->iproto = phy->attached_iproto;\n\tchild->tproto = phy->attached_tproto;\n\tmemcpy(child->sas_addr, phy->attached_sas_addr, SAS_ADDR_SIZE);\n\tsas_hash_addr(child->hashed_sas_addr, child->sas_addr);\n\tsas_ex_get_linkrate(parent, child, phy);\n\tedev->level = parent_ex->level + 1;\n\tparent->port->disc.max_level = max(parent->port->disc.max_level,\n\t\t\t\t\t edev->level);\n\tsas_init_dev(child);\n\tsas_fill_in_rphy(child, rphy);\n\tsas_rphy_add(rphy);\n\n\tspin_lock_irq(&parent->port->dev_list_lock);\n\tlist_add_tail(&child->dev_list_node, &parent->port->dev_list);\n\tspin_unlock_irq(&parent->port->dev_list_lock);\n\n\tres = sas_discover_expander(child);\n\tif (res) {\n\t\tsas_rphy_delete(rphy);\n\t\tspin_lock_irq(&parent->port->dev_list_lock);\n\t\tlist_del(&child->dev_list_node);\n\t\tspin_unlock_irq(&parent->port->dev_list_lock);\n\t\tsas_put_device(child);\n\t\treturn NULL;\n\t}\n\tlist_add_tail(&child->siblings, &parent->ex_dev.children);\n\treturn child;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'scsi: libsas: delete sas port if expander discover failed\n\nThe sas_port(phy->port) allocated in sas_ex_discover_expander() will not be\ndeleted when the expander failed to discover. This will cause resource leak\nand a further issue of kernel BUG like below:\n\n[159785.843156] port-2:17:29: trying to add phy phy-2:17:29 fails: it's\nalready part of another port\n[159785.852144] ------------[ cut here ]------------\n[159785.856833] kernel BUG at drivers/scsi/scsi_transport_sas.c:1086!\n[159785.863000] Internal error: Oops - BUG: 0 [#1] SMP\n[159785.867866] CPU: 39 PID: 16993 Comm: kworker/u96:2 Tainted: G\nW OE 4.19.25-vhulk1901.1.0.h111.aarch64 #1\n[159785.878458] Hardware name: Huawei Technologies Co., Ltd.\nHi1620EVBCS/Hi1620EVBCS, BIOS Hi1620 CS B070 1P TA 03/21/2019\n[159785.889231] Workqueue: 0000:74:02.0_disco_q sas_discover_domain\n[159785.895224] pstate: 40c00009 (nZcv daif +PAN +UAO)\n[159785.900094] pc : sas_port_add_phy+0x188/0x1b8\n[159785.904524] lr : sas_port_add_phy+0x188/0x1b8\n[159785.908952] sp : ffff0001120e3b80\n[159785.912341] x29: ffff0001120e3b80 x28: 0000000000000000\n[159785.917727] x27: ffff802ade8f5400 x26: ffff0000681b7560\n[159785.923111] x25: ffff802adf11a800 x24: ffff0000680e8000\n[159785.928496] x23: ffff802ade8f5728 x22: ffff802ade8f5708\n[159785.933880] x21: ffff802adea2db40 x20: ffff802ade8f5400\n[159785.939264] x19: ffff802adea2d800 x18: 0000000000000010\n[159785.944649] x17: 00000000821bf734 x16: ffff00006714faa0\n[159785.950033] x15: ffff0000e8ab4ecf x14: 7261702079646165\n[159785.955417] x13: 726c612073277469 x12: ffff00006887b830\n[159785.960802] x11: ffff00006773eaa0 x10: 7968702079687020\n[159785.966186] x9 : 0000000000002453 x8 : 726f702072656874\n[159785.971570] x7 : 6f6e6120666f2074 x6 : ffff802bcfb21290\n[159785.976955] x5 : ffff802bcfb21290 x4 : 0000000000000000\n[159785.982339] x3 : ffff802bcfb298c8 x2 : 337752b234c2ab00\n[159785.987723] x1 : 337752b234c2ab00 x0 : 0000000000000000\n[159785.993108] Process kworker/u96:2 (pid: 16993, stack limit =\n0x0000000072dae094)\n[159786.000576] Call trace:\n[159786.003097] sas_port_add_phy+0x188/0x1b8\n[159786.007179] sas_ex_get_linkrate.isra.5+0x134/0x140\n[159786.012130] sas_ex_discover_expander+0x128/0x408\n[159786.016906] sas_ex_discover_dev+0x218/0x4c8\n[159786.021249] sas_ex_discover_devices+0x9c/0x1a8\n[159786.025852] sas_discover_root_expander+0x134/0x160\n[159786.030802] sas_discover_domain+0x1b8/0x1e8\n[159786.035148] process_one_work+0x1b4/0x3f8\n[159786.039230] worker_thread+0x54/0x470\n[159786.042967] kthread+0x134/0x138\n[159786.046269] ret_from_fork+0x10/0x18\n[159786.049918] Code: 91322300 f0004402 91178042 97fe4c9b (d4210000)\n[159786.056083] Modules linked in: hns3_enet_ut(OE) hclge(OE) hnae3(OE)\nhisi_sas_test_hw(OE) hisi_sas_test_main(OE) serdes(OE)\n[159786.067202] ---[ end trace 03622b9e2d99e196 ]---\n[159786.071893] Kernel panic - not syncing: Fatal exception\n[159786.077190] SMP: stopping secondary CPUs\n[159786.081192] Kernel Offset: disabled\n[159786.084753] CPU features: 0x2,a2a00a38\n\nFixes: 2908d778ab3e (\"[SCSI] aic94xx: new driver\")\nReported-by: Jian Luo \nSigned-off-by: Jason Yan \nCC: John Garry \nSigned-off-by: Martin K. Petersen '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int p54u_probe(struct usb_interface *intf,\n\t\t\t\tconst struct usb_device_id *id)\n{\n\tstruct usb_device *udev = interface_to_usbdev(intf);\n\tstruct ieee80211_hw *dev;\n\tstruct p54u_priv *priv;\n\tint err;\n\tunsigned int i, recognized_pipes;\n\n\tdev = p54_init_common(sizeof(*priv));\n\n\tif (!dev) {\n\t\tdev_err(&udev->dev, \"(p54usb) ieee80211 alloc failed\\n\");\n\t\treturn -ENOMEM;\n\t}\n\n\tpriv = dev->priv;\n\tpriv->hw_type = P54U_INVALID_HW;\n\n\tSET_IEEE80211_DEV(dev, &intf->dev);\n\tusb_set_intfdata(intf, dev);\n\tpriv->udev = udev;\n\tpriv->intf = intf;\n\tskb_queue_head_init(&priv->rx_queue);\n\tinit_usb_anchor(&priv->submitted);\n\n\tusb_get_dev(udev);\n\n\t/* really lazy and simple way of figuring out if we're a 3887 */\n\t/* TODO: should just stick the identification in the device table */\n\ti = intf->altsetting->desc.bNumEndpoints;\n\trecognized_pipes = 0;\n\twhile (i--) {\n\t\tswitch (intf->altsetting->endpoint[i].desc.bEndpointAddress) {\n\t\tcase P54U_PIPE_DATA:\n\t\tcase P54U_PIPE_MGMT:\n\t\tcase P54U_PIPE_BRG:\n\t\tcase P54U_PIPE_DEV:\n\t\tcase P54U_PIPE_DATA | USB_DIR_IN:\n\t\tcase P54U_PIPE_MGMT | USB_DIR_IN:\n\t\tcase P54U_PIPE_BRG | USB_DIR_IN:\n\t\tcase P54U_PIPE_DEV | USB_DIR_IN:\n\t\tcase P54U_PIPE_INT | USB_DIR_IN:\n\t\t\trecognized_pipes++;\n\t\t}\n\t}\n\tpriv->common.open = p54u_open;\n\tpriv->common.stop = p54u_stop;\n\tif (recognized_pipes < P54U_PIPE_NUMBER) {\n#ifdef CONFIG_PM\n\t\t/* ISL3887 needs a full reset on resume */\n\t\tudev->reset_resume = 1;\n#endif /* CONFIG_PM */\n\t\terr = p54u_device_reset(dev);\n\n\t\tpriv->hw_type = P54U_3887;\n\t\tdev->extra_tx_headroom += sizeof(struct lm87_tx_hdr);\n\t\tpriv->common.tx_hdr_len = sizeof(struct lm87_tx_hdr);\n\t\tpriv->common.tx = p54u_tx_lm87;\n\t\tpriv->upload_fw = p54u_upload_firmware_3887;\n\t} else {\n\t\tpriv->hw_type = P54U_NET2280;\n\t\tdev->extra_tx_headroom += sizeof(struct net2280_tx_hdr);\n\t\tpriv->common.tx_hdr_len = sizeof(struct net2280_tx_hdr);\n\t\tpriv->common.tx = p54u_tx_net2280;\n\t\tpriv->upload_fw = p54u_upload_firmware_net2280;\n\t}\n\terr = p54u_load_firmware(dev, intf);\n\tif (err) {\n\t\tusb_put_dev(udev);\n\t\tp54_free_common(dev);\n\t}\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'p54usb: Fix race between disconnect and firmware loading\n\nThe syzbot fuzzer found a bug in the p54 USB wireless driver. The\nissue involves a race between disconnect and the firmware-loader\ncallback routine, and it has several aspects.\n\nOne big problem is that when the firmware can't be loaded, the\ncallback routine tries to unbind the driver from the USB _device_ (by\ncalling device_release_driver) instead of from the USB _interface_ to\nwhich it is actually bound (by calling usb_driver_release_interface).\n\nThe race involves access to the private data structure. The driver's\ndisconnect handler waits for a completion that is signalled by the\nfirmware-loader callback routine. As soon as the completion is\nsignalled, you have to assume that the private data structure may have\nbeen deallocated by the disconnect handler -- even if the firmware was\nloaded without errors. However, the callback routine does access the\nprivate data several times after that point.\n\nAnother problem is that, in order to ensure that the USB device\nstructure hasn't been freed when the callback routine runs, the driver\ntakes a reference to it. This isn't good enough any more, because now\nthat the callback routine calls usb_driver_release_interface, it has\nto ensure that the interface structure hasn't been freed.\n\nFinally, the driver takes an unnecessary reference to the USB device\nstructure in the probe function and drops the reference in the\ndisconnect handler. This extra reference doesn't accomplish anything,\nbecause the USB core already guarantees that a device structure won't\nbe deallocated while a driver is still bound to any of its interfaces.\n\nTo fix these problems, this patch makes the following changes:\n\n\tCall usb_driver_release_interface() rather than\n\tdevice_release_driver().\n\n\tDon't signal the completion until after the important\n\tinformation has been copied out of the private data structure,\n\tand don't refer to the private data at all thereafter.\n\n\tLock udev (the interface's parent) before unbinding the driver\n\tinstead of locking udev->parent.\n\n\tDuring the firmware loading process, take a reference to the\n\tUSB interface instead of the USB device.\n\n\tDon't take an unnecessary reference to the device during probe\n\t(and then don't drop it during disconnect).\n\nSigned-off-by: Alan Stern \nReported-and-tested-by: syzbot+200d4bb11b23d929335f@syzkaller.appspotmail.com\nCC: \nAcked-by: Christian Lamparter \nSigned-off-by: Kalle Valo '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms,\n\t unsigned int *nbytes, struct kvec *iov, int n_vec)\n{\n\tstruct smb_rqst rqst;\n\tint rc = 0;\n\tstruct smb2_write_req *req = NULL;\n\tstruct smb2_write_rsp *rsp = NULL;\n\tint resp_buftype;\n\tstruct kvec rsp_iov;\n\tint flags = 0;\n\tunsigned int total_len;\n\n\t*nbytes = 0;\n\n\tif (n_vec < 1)\n\t\treturn rc;\n\n\trc = smb2_plain_req_init(SMB2_WRITE, io_parms->tcon, (void **) &req,\n\t\t\t &total_len);\n\tif (rc)\n\t\treturn rc;\n\n\tif (io_parms->tcon->ses->server == NULL)\n\t\treturn -ECONNABORTED;\n\n\tif (smb3_encryption_required(io_parms->tcon))\n\t\tflags |= CIFS_TRANSFORM_REQ;\n\n\treq->sync_hdr.ProcessId = cpu_to_le32(io_parms->pid);\n\n\treq->PersistentFileId = io_parms->persistent_fid;\n\treq->VolatileFileId = io_parms->volatile_fid;\n\treq->WriteChannelInfoOffset = 0;\n\treq->WriteChannelInfoLength = 0;\n\treq->Channel = 0;\n\treq->Length = cpu_to_le32(io_parms->length);\n\treq->Offset = cpu_to_le64(io_parms->offset);\n\treq->DataOffset = cpu_to_le16(\n\t\t\t\toffsetof(struct smb2_write_req, Buffer));\n\treq->RemainingBytes = 0;\n\n\ttrace_smb3_write_enter(xid, io_parms->persistent_fid,\n\t\tio_parms->tcon->tid, io_parms->tcon->ses->Suid,\n\t\tio_parms->offset, io_parms->length);\n\n\tiov[0].iov_base = (char *)req;\n\t/* 1 for Buffer */\n\tiov[0].iov_len = total_len - 1;\n\n\tmemset(&rqst, 0, sizeof(struct smb_rqst));\n\trqst.rq_iov = iov;\n\trqst.rq_nvec = n_vec + 1;\n\n\trc = cifs_send_recv(xid, io_parms->tcon->ses, &rqst,\n\t\t\t &resp_buftype, flags, &rsp_iov);\n\tcifs_small_buf_release(req);\n\trsp = (struct smb2_write_rsp *)rsp_iov.iov_base;\n\n\tif (rc) {\n\t\ttrace_smb3_write_err(xid, req->PersistentFileId,\n\t\t\t\t io_parms->tcon->tid,\n\t\t\t\t io_parms->tcon->ses->Suid,\n\t\t\t\t io_parms->offset, io_parms->length, rc);\n\t\tcifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE);\n\t\tcifs_dbg(VFS, \"Send error in write = %d\\n\", rc);\n\t} else {\n\t\t*nbytes = le32_to_cpu(rsp->DataLength);\n\t\ttrace_smb3_write_done(xid, req->PersistentFileId,\n\t\t\t\t io_parms->tcon->tid,\n\t\t\t\t io_parms->tcon->ses->Suid,\n\t\t\t\t io_parms->offset, *nbytes);\n\t}\n\n\tfree_rsp_buf(resp_buftype, rsp);\n\treturn rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-200'], 'message': 'cifs: Fix use-after-free in SMB2_write\n\nThere is a KASAN use-after-free:\nBUG: KASAN: use-after-free in SMB2_write+0x1342/0x1580\nRead of size 8 at addr ffff8880b6a8e450 by task ln/4196\n\nShould not release the 'req' because it will use in the trace.\n\nFixes: eccb4422cf97 (\"smb3: Add ftrace tracepoints for improved SMB3 debugging\")\n\nSigned-off-by: ZhangXiaoxu \nSigned-off-by: Steve French \nCC: Stable 4.18+\nReviewed-by: Pavel Shilovsky '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool HaarEvaluator::Feature :: read( const FileNode& node )\n{\n FileNode rnode = node[CC_RECTS];\n FileNodeIterator it = rnode.begin(), it_end = rnode.end();\n\n int ri;\n for( ri = 0; ri < RECT_NUM; ri++ )\n {\n rect[ri].r = Rect();\n rect[ri].weight = 0.f;\n }\n\n for(ri = 0; it != it_end; ++it, ri++)\n {\n FileNodeIterator it2 = (*it).begin();\n it2 >> rect[ri].r.x >> rect[ri].r.y >>\n rect[ri].r.width >> rect[ri].r.height >> rect[ri].weight;\n }\n\n tilted = (int)node[CC_TILTED] != 0;\n return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'objdetect: validate feature rectangle on reading'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: HeaderMapImpl::HeaderEntryImpl& HeaderMapImpl::maybeCreateInline(HeaderEntryImpl** entry,\n const LowerCaseString& key,\n HeaderString&& value) {\n if (*entry) {\n value.clear();\n return **entry;\n }\n\n std::list::iterator i = headers_.insert(key, std::move(value));\n i->entry_ = i;\n *entry = &(*i);\n return **entry;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally.\n\nIntroduces a cached byte size updated internally in HeaderMap. The value\nis stored as an optional, and is cleared whenever a non-const pointer or\nreference to a HeaderEntry is accessed. The cached value can be set with\nrefreshByteSize() which performs an iteration over the HeaderMap to sum\nthe size of each key and value in the HeaderMap.\n\nSigned-off-by: Asra Ali '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ConnectionImpl::onFrameReceived(const nghttp2_frame* frame) {\n ENVOY_CONN_LOG(trace, \"recv frame type={}\", connection_, static_cast(frame->hd.type));\n\n // onFrameReceived() is called with a complete HEADERS frame assembled from all the HEADERS\n // and CONTINUATION frames, but we track them separately: HEADERS frames in onBeginHeaders()\n // and CONTINUATION frames in onBeforeFrameReceived().\n ASSERT(frame->hd.type != NGHTTP2_CONTINUATION);\n\n if (frame->hd.type == NGHTTP2_DATA) {\n if (!trackInboundFrames(&frame->hd, frame->data.padlen)) {\n return NGHTTP2_ERR_FLOODED;\n }\n }\n\n // Only raise GOAWAY once, since we don't currently expose stream information. Shutdown\n // notifications are the same as a normal GOAWAY.\n if (frame->hd.type == NGHTTP2_GOAWAY && !raised_goaway_) {\n ASSERT(frame->hd.stream_id == 0);\n raised_goaway_ = true;\n callbacks().onGoAway();\n return 0;\n }\n\n StreamImpl* stream = getStream(frame->hd.stream_id);\n if (!stream) {\n return 0;\n }\n\n switch (frame->hd.type) {\n case NGHTTP2_HEADERS: {\n stream->remote_end_stream_ = frame->hd.flags & NGHTTP2_FLAG_END_STREAM;\n if (!stream->cookies_.empty()) {\n HeaderString key(Headers::get().Cookie);\n stream->headers_->addViaMove(std::move(key), std::move(stream->cookies_));\n }\n\n switch (frame->headers.cat) {\n case NGHTTP2_HCAT_RESPONSE: {\n if (CodeUtility::is1xx(Http::Utility::getResponseStatus(*stream->headers_))) {\n stream->waiting_for_non_informational_headers_ = true;\n }\n\n if (stream->headers_->Status()->value() == \"100\") {\n ASSERT(!stream->remote_end_stream_);\n stream->decoder_->decode100ContinueHeaders(std::move(stream->headers_));\n } else {\n stream->decodeHeaders();\n }\n break;\n }\n\n case NGHTTP2_HCAT_REQUEST: {\n stream->decodeHeaders();\n break;\n }\n\n case NGHTTP2_HCAT_HEADERS: {\n // It's possible that we are waiting to send a deferred reset, so only raise headers/trailers\n // if local is not complete.\n if (!stream->deferred_reset_) {\n if (!stream->waiting_for_non_informational_headers_) {\n if (!stream->remote_end_stream_) {\n // This indicates we have received more headers frames than Envoy\n // supports. Even if this is valid HTTP (something like 103 early hints) fail here\n // rather than trying to push unexpected headers through the Envoy pipeline as that\n // will likely result in Envoy crashing.\n // It would be cleaner to reset the stream rather than reset the/ entire connection but\n // it's also slightly more dangerous so currently we err on the side of safety.\n stats_.too_many_header_frames_.inc();\n throw CodecProtocolException(\"Unexpected 'trailers' with no end stream.\");\n } else {\n stream->decoder_->decodeTrailers(std::move(stream->headers_));\n }\n } else {\n ASSERT(!nghttp2_session_check_server_session(session_));\n stream->waiting_for_non_informational_headers_ = false;\n\n // Even if we have :status 100 in the client case in a response, when\n // we received a 1xx to start out with, nghttp2 message checking\n // guarantees proper flow here.\n stream->decodeHeaders();\n }\n }\n\n break;\n }\n\n default:\n // We do not currently support push.\n NOT_IMPLEMENTED_GCOVR_EXCL_LINE;\n }\n\n stream->headers_.reset();\n break;\n }\n case NGHTTP2_DATA: {\n stream->remote_end_stream_ = frame->hd.flags & NGHTTP2_FLAG_END_STREAM;\n\n // It's possible that we are waiting to send a deferred reset, so only raise data if local\n // is not complete.\n if (!stream->deferred_reset_) {\n stream->decoder_->decodeData(stream->pending_recv_data_, stream->remote_end_stream_);\n }\n\n stream->pending_recv_data_.drain(stream->pending_recv_data_.length());\n break;\n }\n case NGHTTP2_RST_STREAM: {\n ENVOY_CONN_LOG(trace, \"remote reset: {}\", connection_, frame->rst_stream.error_code);\n stats_.rx_reset_.inc();\n break;\n }\n }\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally.\n\nIntroduces a cached byte size updated internally in HeaderMap. The value\nis stored as an optional, and is cleared whenever a non-const pointer or\nreference to a HeaderEntry is accessed. The cached value can be set with\nrefreshByteSize() which performs an iteration over the HeaderMap to sum\nthe size of each key and value in the HeaderMap.\n\nSigned-off-by: Asra Ali '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void HeaderMapImpl::removePrefix(const LowerCaseString& prefix) {\n headers_.remove_if([&](const HeaderEntryImpl& entry) {\n bool to_remove = absl::StartsWith(entry.key().getStringView(), prefix.get());\n if (to_remove) {\n // If this header should be removed, make sure any references in the\n // static lookup table are cleared as well.\n EntryCb cb = ConstSingleton::get().find(entry.key().getStringView());\n if (cb) {\n StaticLookupResponse ref_lookup_response = cb(*this);\n if (ref_lookup_response.entry_) {\n *ref_lookup_response.entry_ = nullptr;\n }\n }\n }\n return to_remove;\n });\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally.\n\nIntroduces a cached byte size updated internally in HeaderMap. The value\nis stored as an optional, and is cleared whenever a non-const pointer or\nreference to a HeaderEntry is accessed. The cached value can be set with\nrefreshByteSize() which performs an iteration over the HeaderMap to sum\nthe size of each key and value in the HeaderMap.\n\nSigned-off-by: Asra Ali '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: const HeaderEntry* HeaderMapImpl::get(const LowerCaseString& key) const {\n for (const HeaderEntryImpl& header : headers_) {\n if (header.key() == key.get().c_str()) {\n return &header;\n }\n }\n\n return nullptr;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally.\n\nIntroduces a cached byte size updated internally in HeaderMap. The value\nis stored as an optional, and is cleared whenever a non-const pointer or\nreference to a HeaderEntry is accessed. The cached value can be set with\nrefreshByteSize() which performs an iteration over the HeaderMap to sum\nthe size of each key and value in the HeaderMap.\n\nSigned-off-by: Asra Ali '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TEST(HeaderMapImplTest, LargeCharInHeader) {\n HeaderMapImpl headers;\n LowerCaseString static_key(\"\\x90hello\");\n std::string ref_value(\"value\");\n headers.addReference(static_key, ref_value);\n EXPECT_EQ(\"value\", headers.get(static_key)->value().getStringView());\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Track byteSize of HeaderMap internally.\n\nIntroduces a cached byte size updated internally in HeaderMap. The value\nis stored as an optional, and is cleared whenever a non-const pointer or\nreference to a HeaderEntry is accessed. The cached value can be set with\nrefreshByteSize() which performs an iteration over the HeaderMap to sum\nthe size of each key and value in the HeaderMap.\n\nSigned-off-by: Asra Ali '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: _handle_single_connection (int sockin, int sockout)\n{\n const char *plugin_name;\n int ret = -1, r;\n struct connection *conn;\n int nworkers = threads ? threads : DEFAULT_PARALLEL_REQUESTS;\n pthread_t *workers = NULL;\n\n if (backend->thread_model (backend) < NBDKIT_THREAD_MODEL_PARALLEL ||\n nworkers == 1)\n nworkers = 0;\n conn = new_connection (sockin, sockout, nworkers);\n if (!conn)\n goto done;\n\n lock_request (conn);\n r = backend_open (backend, conn, read_only);\n unlock_request (conn);\n if (r == -1)\n goto done;\n\n /* NB: because of an asynchronous exit backend can be set to NULL at\n * just about any time.\n */\n if (backend)\n plugin_name = backend->plugin_name (backend);\n else\n plugin_name = \"(unknown)\";\n threadlocal_set_name (plugin_name);\n\n /* Prepare (for filters), called just after open. */\n lock_request (conn);\n if (backend)\n r = backend_prepare (backend, conn);\n else\n r = 0;\n unlock_request (conn);\n if (r == -1)\n goto done;\n\n /* Handshake. */\n if (protocol_handshake (conn) == -1)\n goto done;\n\n if (!nworkers) {\n /* No need for a separate thread. */\n debug (\"handshake complete, processing requests serially\");\n while (!quit && connection_get_status (conn) > 0)\n protocol_recv_request_send_reply (conn);\n }\n else {\n /* Create thread pool to process requests. */\n debug (\"handshake complete, processing requests with %d threads\",\n nworkers);\n workers = calloc (nworkers, sizeof *workers);\n if (!workers) {\n perror (\"malloc\");\n goto done;\n }\n\n for (nworkers = 0; nworkers < conn->nworkers; nworkers++) {\n struct worker_data *worker = malloc (sizeof *worker);\n int err;\n\n if (!worker) {\n perror (\"malloc\");\n connection_set_status (conn, -1);\n goto wait;\n }\n if (asprintf (&worker->name, \"%s.%d\", plugin_name, nworkers) < 0) {\n perror (\"asprintf\");\n connection_set_status (conn, -1);\n free (worker);\n goto wait;\n }\n worker->conn = conn;\n err = pthread_create (&workers[nworkers], NULL, connection_worker,\n worker);\n if (err) {\n errno = err;\n perror (\"pthread_create\");\n connection_set_status (conn, -1);\n free (worker);\n goto wait;\n }\n }\n\n wait:\n while (nworkers)\n pthread_join (workers[--nworkers], NULL);\n free (workers);\n }\n\n /* Finalize (for filters), called just before close. */\n lock_request (conn);\n if (backend)\n r = backend->finalize (backend, conn);\n else\n r = 0;\n unlock_request (conn);\n if (r == -1)\n goto done;\n\n ret = connection_get_status (conn);\n done:\n free_connection (conn);\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-406'], 'message': 'server: Wait until handshake complete before calling .open callback\n\nCurrently we call the plugin .open callback as soon as we receive a\nTCP connection:\n\n $ nbdkit -fv --tls=require --tls-certificates=tests/pki null \\\n --run \"telnet localhost 10809\"\n [...]\n Trying ::1...\n Connected to localhost.\n Escape character is '^]'.\n nbdkit: debug: accepted connection\n nbdkit: debug: null: open readonly=0 \u25c0 NOTE\n nbdkit: null[1]: debug: newstyle negotiation: flags: global 0x3\n NBDMAGICIHAVEOPT\n\nIn plugins such as curl, guestfs, ssh, vddk and others we do a\nconsiderable amount of work in the .open callback (such as making a\nremote connection or launching an appliance). Therefore we are\nproviding an easy Denial of Service / Amplification Attack for\nunauthorized clients to cause a lot of work to be done for only the\ncost of a simple TCP 3 way handshake.\n\nThis commit moves the call to the .open callback after the NBD\nhandshake has mostly completed. In particular TLS authentication must\nbe complete before we will call into the plugin.\n\nIt is unlikely that there are plugins which really depend on the\ncurrent behaviour of .open (which I found surprising even though I\nguess I must have written it). If there are then we could add a new\n.connect callback or similar to allow plugins to get control at the\nearlier point in the connection.\n\nAfter this change you can see that the .open callback is not called\nfrom just a simple TCP connection:\n\n $ ./nbdkit -fv --tls=require --tls-certificates=tests/pki null \\\n --run \"telnet localhost 10809\"\n [...]\n Trying ::1...\n Connected to localhost.\n Escape character is '^]'.\n nbdkit: debug: accepted connection\n nbdkit: null[1]: debug: newstyle negotiation: flags: global 0x3\n NBDMAGICIHAVEOPT\n xx\n nbdkit: null[1]: debug: newstyle negotiation: client flags: 0xd0a7878\n nbdkit: null[1]: error: client requested unknown flags 0xd0a7878\n Connection closed by foreign host.\n nbdkit: debug: null: unload plugin\n\nSigned-off-by: Richard W.M. Jones '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: protocol_compute_eflags (struct connection *conn, uint16_t *flags)\n{\n uint16_t eflags = NBD_FLAG_HAS_FLAGS;\n int fl;\n\n fl = backend->can_write (backend, conn);\n if (fl == -1)\n return -1;\n if (readonly || !fl) {\n eflags |= NBD_FLAG_READ_ONLY;\n conn->readonly = true;\n }\n if (!conn->readonly) {\n fl = backend->can_zero (backend, conn);\n if (fl == -1)\n return -1;\n if (fl) {\n eflags |= NBD_FLAG_SEND_WRITE_ZEROES;\n conn->can_zero = true;\n }\n\n fl = backend->can_trim (backend, conn);\n if (fl == -1)\n return -1;\n if (fl) {\n eflags |= NBD_FLAG_SEND_TRIM;\n conn->can_trim = true;\n }\n\n fl = backend->can_fua (backend, conn);\n if (fl == -1)\n return -1;\n if (fl) {\n eflags |= NBD_FLAG_SEND_FUA;\n conn->can_fua = true;\n }\n }\n\n fl = backend->can_flush (backend, conn);\n if (fl == -1)\n return -1;\n if (fl) {\n eflags |= NBD_FLAG_SEND_FLUSH;\n conn->can_flush = true;\n }\n\n fl = backend->is_rotational (backend, conn);\n if (fl == -1)\n return -1;\n if (fl) {\n eflags |= NBD_FLAG_ROTATIONAL;\n conn->is_rotational = true;\n }\n\n /* multi-conn is useless if parallel connections are not allowed */\n if (backend->thread_model (backend) >\n NBDKIT_THREAD_MODEL_SERIALIZE_CONNECTIONS) {\n fl = backend->can_multi_conn (backend, conn);\n if (fl == -1)\n return -1;\n if (fl) {\n eflags |= NBD_FLAG_CAN_MULTI_CONN;\n conn->can_multi_conn = true;\n }\n }\n\n fl = backend->can_cache (backend, conn);\n if (fl == -1)\n return -1;\n if (fl) {\n eflags |= NBD_FLAG_SEND_CACHE;\n conn->can_cache = true;\n conn->emulate_cache = fl == NBDKIT_CACHE_EMULATE;\n }\n\n /* The result of this is not returned to callers here (or at any\n * time during the handshake). However it makes sense to do it once\n * per connection and store the result in the handle anyway. This\n * protocol_compute_eflags function is a bit misnamed XXX.\n */\n fl = backend->can_extents (backend, conn);\n if (fl == -1)\n return -1;\n if (fl)\n conn->can_extents = true;\n\n if (conn->structured_replies)\n eflags |= NBD_FLAG_SEND_DF;\n\n *flags = eflags;\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-406'], 'message': 'server: Wait until handshake complete before calling .open callback\n\nCurrently we call the plugin .open callback as soon as we receive a\nTCP connection:\n\n $ nbdkit -fv --tls=require --tls-certificates=tests/pki null \\\n --run \"telnet localhost 10809\"\n [...]\n Trying ::1...\n Connected to localhost.\n Escape character is '^]'.\n nbdkit: debug: accepted connection\n nbdkit: debug: null: open readonly=0 \u25c0 NOTE\n nbdkit: null[1]: debug: newstyle negotiation: flags: global 0x3\n NBDMAGICIHAVEOPT\n\nIn plugins such as curl, guestfs, ssh, vddk and others we do a\nconsiderable amount of work in the .open callback (such as making a\nremote connection or launching an appliance). Therefore we are\nproviding an easy Denial of Service / Amplification Attack for\nunauthorized clients to cause a lot of work to be done for only the\ncost of a simple TCP 3 way handshake.\n\nThis commit moves the call to the .open callback after the NBD\nhandshake has mostly completed. In particular TLS authentication must\nbe complete before we will call into the plugin.\n\nIt is unlikely that there are plugins which really depend on the\ncurrent behaviour of .open (which I found surprising even though I\nguess I must have written it). If there are then we could add a new\n.connect callback or similar to allow plugins to get control at the\nearlier point in the connection.\n\nAfter this change you can see that the .open callback is not called\nfrom just a simple TCP connection:\n\n $ ./nbdkit -fv --tls=require --tls-certificates=tests/pki null \\\n --run \"telnet localhost 10809\"\n [...]\n Trying ::1...\n Connected to localhost.\n Escape character is '^]'.\n nbdkit: debug: accepted connection\n nbdkit: null[1]: debug: newstyle negotiation: flags: global 0x3\n NBDMAGICIHAVEOPT\n xx\n nbdkit: null[1]: debug: newstyle negotiation: client flags: 0xd0a7878\n nbdkit: null[1]: error: client requested unknown flags 0xd0a7878\n Connection closed by foreign host.\n nbdkit: debug: null: unload plugin\n\nSigned-off-by: Richard W.M. Jones \n(cherry picked from commit c05686f9577fa91b6a3a4d8c065954ca6fc3fd62)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: v9fs_stat2inode_dotl(struct p9_stat_dotl *stat, struct inode *inode)\n{\n\tumode_t mode;\n\tstruct v9fs_inode *v9inode = V9FS_I(inode);\n\n\tif ((stat->st_result_mask & P9_STATS_BASIC) == P9_STATS_BASIC) {\n\t\tinode->i_atime.tv_sec = stat->st_atime_sec;\n\t\tinode->i_atime.tv_nsec = stat->st_atime_nsec;\n\t\tinode->i_mtime.tv_sec = stat->st_mtime_sec;\n\t\tinode->i_mtime.tv_nsec = stat->st_mtime_nsec;\n\t\tinode->i_ctime.tv_sec = stat->st_ctime_sec;\n\t\tinode->i_ctime.tv_nsec = stat->st_ctime_nsec;\n\t\tinode->i_uid = stat->st_uid;\n\t\tinode->i_gid = stat->st_gid;\n\t\tset_nlink(inode, stat->st_nlink);\n\n\t\tmode = stat->st_mode & S_IALLUGO;\n\t\tmode |= inode->i_mode & ~S_IALLUGO;\n\t\tinode->i_mode = mode;\n\n\t\ti_size_write(inode, stat->st_size);\n\t\tinode->i_blocks = stat->st_blocks;\n\t} else {\n\t\tif (stat->st_result_mask & P9_STATS_ATIME) {\n\t\t\tinode->i_atime.tv_sec = stat->st_atime_sec;\n\t\t\tinode->i_atime.tv_nsec = stat->st_atime_nsec;\n\t\t}\n\t\tif (stat->st_result_mask & P9_STATS_MTIME) {\n\t\t\tinode->i_mtime.tv_sec = stat->st_mtime_sec;\n\t\t\tinode->i_mtime.tv_nsec = stat->st_mtime_nsec;\n\t\t}\n\t\tif (stat->st_result_mask & P9_STATS_CTIME) {\n\t\t\tinode->i_ctime.tv_sec = stat->st_ctime_sec;\n\t\t\tinode->i_ctime.tv_nsec = stat->st_ctime_nsec;\n\t\t}\n\t\tif (stat->st_result_mask & P9_STATS_UID)\n\t\t\tinode->i_uid = stat->st_uid;\n\t\tif (stat->st_result_mask & P9_STATS_GID)\n\t\t\tinode->i_gid = stat->st_gid;\n\t\tif (stat->st_result_mask & P9_STATS_NLINK)\n\t\t\tset_nlink(inode, stat->st_nlink);\n\t\tif (stat->st_result_mask & P9_STATS_MODE) {\n\t\t\tinode->i_mode = stat->st_mode;\n\t\t\tif ((S_ISBLK(inode->i_mode)) ||\n\t\t\t\t\t\t(S_ISCHR(inode->i_mode)))\n\t\t\t\tinit_special_inode(inode, inode->i_mode,\n\t\t\t\t\t\t\t\tinode->i_rdev);\n\t\t}\n\t\tif (stat->st_result_mask & P9_STATS_RDEV)\n\t\t\tinode->i_rdev = new_decode_dev(stat->st_rdev);\n\t\tif (stat->st_result_mask & P9_STATS_SIZE)\n\t\t\ti_size_write(inode, stat->st_size);\n\t\tif (stat->st_result_mask & P9_STATS_BLOCKS)\n\t\t\tinode->i_blocks = stat->st_blocks;\n\t}\n\tif (stat->st_result_mask & P9_STATS_GEN)\n\t\tinode->i_generation = stat->st_gen;\n\n\t/* Currently we don't support P9_STATS_BTIME and P9_STATS_DATA_VERSION\n\t * because the inode structure does not have fields for them.\n\t */\n\tv9inode->cache_validity &= ~V9FS_INO_INVALID_ATTR;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': '9p: use inode->i_lock to protect i_size_write() under 32-bit\n\nUse inode->i_lock to protect i_size_write(), else i_size_read() in\ngeneric_fillattr() may loop infinitely in read_seqcount_begin() when\nmultiple processes invoke v9fs_vfs_getattr() or v9fs_vfs_getattr_dotl()\nsimultaneously under 32-bit SMP environment, and a soft lockup will be\ntriggered as show below:\n\n watchdog: BUG: soft lockup - CPU#5 stuck for 22s! [stat:2217]\n Modules linked in:\n CPU: 5 PID: 2217 Comm: stat Not tainted 5.0.0-rc1-00005-g7f702faf5a9e #4\n Hardware name: Generic DT based system\n PC is at generic_fillattr+0x104/0x108\n LR is at 0xec497f00\n pc : [<802b8898>] lr : [] psr: 200c0013\n sp : ec497e20 ip : ed608030 fp : ec497e3c\n r10: 00000000 r9 : ec497f00 r8 : ed608030\n r7 : ec497ebc r6 : ec497f00 r5 : ee5c1550 r4 : ee005780\n r3 : 0000052d r2 : 00000000 r1 : ec497f00 r0 : ed608030\n Flags: nzCv IRQs on FIQs on Mode SVC_32 ISA ARM Segment none\n Control: 10c5387d Table: ac48006a DAC: 00000051\n CPU: 5 PID: 2217 Comm: stat Not tainted 5.0.0-rc1-00005-g7f702faf5a9e #4\n Hardware name: Generic DT based system\n Backtrace:\n [<8010d974>] (dump_backtrace) from [<8010dc88>] (show_stack+0x20/0x24)\n [<8010dc68>] (show_stack) from [<80a1d194>] (dump_stack+0xb0/0xdc)\n [<80a1d0e4>] (dump_stack) from [<80109f34>] (show_regs+0x1c/0x20)\n [<80109f18>] (show_regs) from [<801d0a80>] (watchdog_timer_fn+0x280/0x2f8)\n [<801d0800>] (watchdog_timer_fn) from [<80198658>] (__hrtimer_run_queues+0x18c/0x380)\n [<801984cc>] (__hrtimer_run_queues) from [<80198e60>] (hrtimer_run_queues+0xb8/0xf0)\n [<80198da8>] (hrtimer_run_queues) from [<801973e8>] (run_local_timers+0x28/0x64)\n [<801973c0>] (run_local_timers) from [<80197460>] (update_process_times+0x3c/0x6c)\n [<80197424>] (update_process_times) from [<801ab2b8>] (tick_nohz_handler+0xe0/0x1bc)\n [<801ab1d8>] (tick_nohz_handler) from [<80843050>] (arch_timer_handler_virt+0x38/0x48)\n [<80843018>] (arch_timer_handler_virt) from [<80180a64>] (handle_percpu_devid_irq+0x8c/0x240)\n [<801809d8>] (handle_percpu_devid_irq) from [<8017ac20>] (generic_handle_irq+0x34/0x44)\n [<8017abec>] (generic_handle_irq) from [<8017b344>] (__handle_domain_irq+0x6c/0xc4)\n [<8017b2d8>] (__handle_domain_irq) from [<801022e0>] (gic_handle_irq+0x4c/0x88)\n [<80102294>] (gic_handle_irq) from [<80101a30>] (__irq_svc+0x70/0x98)\n [<802b8794>] (generic_fillattr) from [<8056b284>] (v9fs_vfs_getattr_dotl+0x74/0xa4)\n [<8056b210>] (v9fs_vfs_getattr_dotl) from [<802b8904>] (vfs_getattr_nosec+0x68/0x7c)\n [<802b889c>] (vfs_getattr_nosec) from [<802b895c>] (vfs_getattr+0x44/0x48)\n [<802b8918>] (vfs_getattr) from [<802b8a74>] (vfs_statx+0x9c/0xec)\n [<802b89d8>] (vfs_statx) from [<802b9428>] (sys_lstat64+0x48/0x78)\n [<802b93e0>] (sys_lstat64) from [<80101000>] (ret_fast_syscall+0x0/0x28)\n\n[dominique.martinet@cea.fr: updated comment to not refer to a function\nin another subsystem]\nLink: http://lkml.kernel.org/r/20190124063514.8571-2-houtao1@huawei.com\nCc: stable@vger.kernel.org\nFixes: 7549ae3e81cc (\"9p: Use the i_size_[read, write]() macros instead of using inode->i_size directly.\")\nReported-by: Xing Gaopeng \nSigned-off-by: Hou Tao \nSigned-off-by: Dominique Martinet '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void gfs2_clear_rgrpd(struct gfs2_sbd *sdp)\n{\n\tstruct rb_node *n;\n\tstruct gfs2_rgrpd *rgd;\n\tstruct gfs2_glock *gl;\n\n\twhile ((n = rb_first(&sdp->sd_rindex_tree))) {\n\t\trgd = rb_entry(n, struct gfs2_rgrpd, rd_node);\n\t\tgl = rgd->rd_gl;\n\n\t\trb_erase(n, &sdp->sd_rindex_tree);\n\n\t\tif (gl) {\n\t\t\tspin_lock(&gl->gl_lockref.lock);\n\t\t\tgl->gl_object = NULL;\n\t\t\tspin_unlock(&gl->gl_lockref.lock);\n\t\t\tgfs2_glock_add_to_lru(gl);\n\t\t\tgfs2_glock_put(gl);\n\t\t}\n\n\t\tgfs2_free_clones(rgd);\n\t\tkfree(rgd->rd_bits);\n\t\treturn_all_reservations(rgd);\n\t\tkmem_cache_free(gfs2_rgrpd_cachep, rgd);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'GFS2: don't set rgrp gl_object until it's inserted into rgrp tree\n\nBefore this patch, function read_rindex_entry would set a rgrp\nglock's gl_object pointer to itself before inserting the rgrp into\nthe rgrp rbtree. The problem is: if another process was also reading\nthe rgrp in, and had already inserted its newly created rgrp, then\nthe second call to read_rindex_entry would overwrite that value,\nthen return a bad return code to the caller. Later, other functions\nwould reference the now-freed rgrp memory by way of gl_object.\nIn some cases, that could result in gfs2_rgrp_brelse being called\ntwice for the same rgrp: once for the failed attempt and once for\nthe \"real\" rgrp release. Eventually the kernel would panic.\nThere are also a number of other things that could go wrong when\na kernel module is accessing freed storage. For example, this could\nresult in rgrp corruption because the fake rgrp would point to a\nfake bitmap in memory too, causing gfs2_inplace_reserve to search\nsome random memory for free blocks, and find some, since we were\nnever setting rgd->rd_bits to NULL before freeing it.\n\nThis patch fixes the problem by not setting gl_object until we\nhave successfully inserted the rgrp into the rbtree. Also, it sets\nrd_bits to NULL as it frees them, which will ensure any accidental\naccess to the wrong rgrp will result in a kernel panic rather than\nfile system corruption, which is preferred.\n\nSigned-off-by: Bob Peterson '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: MagickExport void *DetachBlob(BlobInfo *blob_info)\n{\n void\n *data;\n\n assert(blob_info != (BlobInfo *) NULL);\n if (blob_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"...\");\n if (blob_info->mapped != MagickFalse)\n {\n (void) UnmapBlob(blob_info->data,blob_info->length);\n RelinquishMagickResource(MapResource,blob_info->length);\n }\n blob_info->mapped=MagickFalse;\n blob_info->length=0;\n blob_info->offset=0;\n blob_info->eof=MagickFalse;\n blob_info->error=0;\n blob_info->exempt=MagickFalse;\n blob_info->type=UndefinedStream;\n blob_info->file_info.file=(FILE *) NULL;\n data=blob_info->data;\n blob_info->data=(unsigned char *) NULL;\n blob_info->stream=(StreamHandler) NULL;\n blob_info->custom_stream=(CustomStreamInfo *) NULL;\n return(data);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-399'], 'message': 'https://github.com/ImageMagick/ImageMagick6/issues/43'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: S3BootScriptLabelInternal (\r\n IN BOOLEAN BeforeOrAfter,\r\n IN OUT VOID **Position OPTIONAL,\r\n IN UINT32 InformationLength,\r\n IN CONST CHAR8 *Information\r\n )\r\n{\r\n UINT8 Length;\r\n UINT8 *Script;\r\n EFI_BOOT_SCRIPT_INFORMATION ScriptInformation;\r\n\r\n Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_INFORMATION) + InformationLength);\r\n\r\n Script = S3BootScriptGetEntryAddAddress (Length);\r\n if (Script == NULL) {\r\n return RETURN_OUT_OF_RESOURCES;\r\n }\r\n //\r\n // Build script data\r\n //\r\n ScriptInformation.OpCode = S3_BOOT_SCRIPT_LIB_LABEL_OPCODE;\r\n ScriptInformation.Length = Length;\r\n\r\n\r\n ScriptInformation.InformationLength = InformationLength;\r\n\r\n CopyMem ((VOID*)Script, (VOID*)&ScriptInformation, sizeof (EFI_BOOT_SCRIPT_INFORMATION));\r\n CopyMem ((VOID*)(Script + sizeof (EFI_BOOT_SCRIPT_INFORMATION)), (VOID *) Information, (UINTN) InformationLength);\r\n\r\n SyncBootScript (Script);\r\n\r\n return S3BootScriptMoveLastOpcode (BeforeOrAfter, Position);\r\n\r\n}\r ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'MdeModulePkg/PiDxeS3BootScriptLib: Fix potential numeric truncation (CVE-2019-14563)\n\nREF:https://bugzilla.tianocore.org/show_bug.cgi?id=2001\n\nFor S3BootScriptLib APIs:\n\nS3BootScriptSaveIoWrite\nS3BootScriptSaveMemWrite\nS3BootScriptSavePciCfgWrite\nS3BootScriptSavePciCfg2Write\nS3BootScriptSaveSmbusExecute\nS3BootScriptSaveInformation\nS3BootScriptSaveInformationAsciiString\nS3BootScriptLabel (happen in S3BootScriptLabelInternal())\n\npossible numeric truncations will happen that may lead to S3 boot script\nentry with improper size being returned to store the boot script data.\nThis commit will add checks to prevent this kind of issue.\n\nPlease note that the remaining S3BootScriptLib APIs:\n\nS3BootScriptSaveIoReadWrite\nS3BootScriptSaveMemReadWrite\nS3BootScriptSavePciCfgReadWrite\nS3BootScriptSavePciCfg2ReadWrite\nS3BootScriptSaveStall\nS3BootScriptSaveDispatch2\nS3BootScriptSaveDispatch\nS3BootScriptSaveMemPoll\nS3BootScriptSaveIoPoll\nS3BootScriptSavePciPoll\nS3BootScriptSavePci2Poll\nS3BootScriptCloseTable\nS3BootScriptExecute\nS3BootScriptMoveLastOpcode\nS3BootScriptCompare\n\nare not affected by such numeric truncation.\n\nSigned-off-by: Hao A Wu \nReviewed-by: Laszlo Ersek \nReviewed-by: Eric Dong \nAcked-by: Jian J Wang '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int build_audio_procunit(struct mixer_build *state, int unitid,\n\t\t\t\tvoid *raw_desc, struct procunit_info *list,\n\t\t\t\tchar *name)\n{\n\tstruct uac_processing_unit_descriptor *desc = raw_desc;\n\tint num_ins = desc->bNrInPins;\n\tstruct usb_mixer_elem_info *cval;\n\tstruct snd_kcontrol *kctl;\n\tint i, err, nameid, type, len;\n\tstruct procunit_info *info;\n\tstruct procunit_value_info *valinfo;\n\tconst struct usbmix_name_map *map;\n\tstatic struct procunit_value_info default_value_info[] = {\n\t\t{ 0x01, \"Switch\", USB_MIXER_BOOLEAN },\n\t\t{ 0 }\n\t};\n\tstatic struct procunit_info default_info = {\n\t\t0, NULL, default_value_info\n\t};\n\n\tif (desc->bLength < 13 || desc->bLength < 13 + num_ins ||\n\t desc->bLength < num_ins + uac_processing_unit_bControlSize(desc, state->mixer->protocol)) {\n\t\tusb_audio_err(state->chip, \"invalid %s descriptor (id %d)\\n\", name, unitid);\n\t\treturn -EINVAL;\n\t}\n\n\tfor (i = 0; i < num_ins; i++) {\n\t\terr = parse_audio_unit(state, desc->baSourceID[i]);\n\t\tif (err < 0)\n\t\t\treturn err;\n\t}\n\n\ttype = le16_to_cpu(desc->wProcessType);\n\tfor (info = list; info && info->type; info++)\n\t\tif (info->type == type)\n\t\t\tbreak;\n\tif (!info || !info->type)\n\t\tinfo = &default_info;\n\n\tfor (valinfo = info->values; valinfo->control; valinfo++) {\n\t\t__u8 *controls = uac_processing_unit_bmControls(desc, state->mixer->protocol);\n\n\t\tif (state->mixer->protocol == UAC_VERSION_1) {\n\t\t\tif (!(controls[valinfo->control / 8] &\n\t\t\t\t\t(1 << ((valinfo->control % 8) - 1))))\n\t\t\t\tcontinue;\n\t\t} else { /* UAC_VERSION_2/3 */\n\t\t\tif (!uac_v2v3_control_is_readable(controls[valinfo->control / 8],\n\t\t\t\t\t\t\t valinfo->control))\n\t\t\t\tcontinue;\n\t\t}\n\n\t\tmap = find_map(state->map, unitid, valinfo->control);\n\t\tif (check_ignored_ctl(map))\n\t\t\tcontinue;\n\t\tcval = kzalloc(sizeof(*cval), GFP_KERNEL);\n\t\tif (!cval)\n\t\t\treturn -ENOMEM;\n\t\tsnd_usb_mixer_elem_init_std(&cval->head, state->mixer, unitid);\n\t\tcval->control = valinfo->control;\n\t\tcval->val_type = valinfo->val_type;\n\t\tcval->channels = 1;\n\n\t\tif (state->mixer->protocol > UAC_VERSION_1 &&\n\t\t !uac_v2v3_control_is_writeable(controls[valinfo->control / 8],\n\t\t\t\t\t\t valinfo->control))\n\t\t\tcval->master_readonly = 1;\n\n\t\t/* get min/max values */\n\t\tswitch (type) {\n\t\tcase UAC_PROCESS_UP_DOWNMIX: {\n\t\t\tbool mode_sel = false;\n\n\t\t\tswitch (state->mixer->protocol) {\n\t\t\tcase UAC_VERSION_1:\n\t\t\tcase UAC_VERSION_2:\n\t\t\tdefault:\n\t\t\t\tif (cval->control == UAC_UD_MODE_SELECT)\n\t\t\t\t\tmode_sel = true;\n\t\t\t\tbreak;\n\t\t\tcase UAC_VERSION_3:\n\t\t\t\tif (cval->control == UAC3_UD_MODE_SELECT)\n\t\t\t\t\tmode_sel = true;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (mode_sel) {\n\t\t\t\t__u8 *control_spec = uac_processing_unit_specific(desc,\n\t\t\t\t\t\t\t\tstate->mixer->protocol);\n\t\t\t\tcval->min = 1;\n\t\t\t\tcval->max = control_spec[0];\n\t\t\t\tcval->res = 1;\n\t\t\t\tcval->initialized = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tget_min_max(cval, valinfo->min_value);\n\t\t\tbreak;\n\t\t}\n\t\tcase USB_XU_CLOCK_RATE:\n\t\t\t/*\n\t\t\t * E-Mu USB 0404/0202/TrackerPre/0204\n\t\t\t * samplerate control quirk\n\t\t\t */\n\t\t\tcval->min = 0;\n\t\t\tcval->max = 5;\n\t\t\tcval->res = 1;\n\t\t\tcval->initialized = 1;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tget_min_max(cval, valinfo->min_value);\n\t\t\tbreak;\n\t\t}\n\n\t\tkctl = snd_ctl_new1(&mixer_procunit_ctl, cval);\n\t\tif (!kctl) {\n\t\t\tkfree(cval);\n\t\t\treturn -ENOMEM;\n\t\t}\n\t\tkctl->private_free = snd_usb_mixer_elem_free;\n\n\t\tif (check_mapped_name(map, kctl->id.name, sizeof(kctl->id.name))) {\n\t\t\t/* nothing */ ;\n\t\t} else if (info->name) {\n\t\t\tstrlcpy(kctl->id.name, info->name, sizeof(kctl->id.name));\n\t\t} else {\n\t\t\tnameid = uac_processing_unit_iProcessing(desc, state->mixer->protocol);\n\t\t\tlen = 0;\n\t\t\tif (nameid)\n\t\t\t\tlen = snd_usb_copy_string_desc(state->chip,\n\t\t\t\t\t\t\t nameid,\n\t\t\t\t\t\t\t kctl->id.name,\n\t\t\t\t\t\t\t sizeof(kctl->id.name));\n\t\t\tif (!len)\n\t\t\t\tstrlcpy(kctl->id.name, name, sizeof(kctl->id.name));\n\t\t}\n\t\tappend_ctl_name(kctl, \" \");\n\t\tappend_ctl_name(kctl, valinfo->suffix);\n\n\t\tusb_audio_dbg(state->chip,\n\t\t\t \"[%d] PU [%s] ch = %d, val = %d/%d\\n\",\n\t\t\t cval->head.id, kctl->id.name, cval->channels,\n\t\t\t cval->min, cval->max);\n\n\t\terr = snd_usb_mixer_add_control(&cval->head, kctl);\n\t\tif (err < 0)\n\t\t\treturn err;\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'ALSA: usb-audio: Avoid access before bLength check in build_audio_procunit()\n\nThe parser for the processing unit reads bNrInPins field before the\nbLength sanity check, which may lead to an out-of-bound access when a\nmalformed descriptor is given. Fix it by assignment after the bLength\ncheck.\n\nCc: \nSigned-off-by: Takashi Iwai '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int restore_altivec(struct task_struct *tsk)\n{\n\tif (cpu_has_feature(CPU_FTR_ALTIVEC) &&\n\t\t(tsk->thread.load_vec || tm_active_with_altivec(tsk))) {\n\t\tload_vr_state(&tsk->thread.vr_state);\n\t\ttsk->thread.used_vr = 1;\n\t\ttsk->thread.load_vec++;\n\n\t\treturn 1;\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-662'], 'message': 'powerpc/tm: Fix restoring FP/VMX facility incorrectly on interrupts\n\nWhen in userspace and MSR FP=0 the hardware FP state is unrelated to\nthe current process. This is extended for transactions where if tbegin\nis run with FP=0, the hardware checkpoint FP state will also be\nunrelated to the current process. Due to this, we need to ensure this\nhardware checkpoint is updated with the correct state before we enable\nFP for this process.\n\nUnfortunately we get this wrong when returning to a process from a\nhardware interrupt. A process that starts a transaction with FP=0 can\ntake an interrupt. When the kernel returns back to that process, we\nchange to FP=1 but with hardware checkpoint FP state not updated. If\nthis transaction is then rolled back, the FP registers now contain the\nwrong state.\n\nThe process looks like this:\n Userspace: Kernel\n\n Start userspace\n with MSR FP=0 TM=1\n < -----\n ...\n tbegin\n bne\n Hardware interrupt\n ---- >\n \n ....\n ret_from_except\n restore_math()\n\t\t\t\t /* sees FP=0 */\n restore_fp()\n tm_active_with_fp()\n\t\t\t\t\t /* sees FP=1 (Incorrect) */\n load_fp_state()\n FP = 0 -> 1\n < -----\n Return to userspace\n with MSR TM=1 FP=1\n with junk in the FP TM checkpoint\n TM rollback\n reads FP junk\n\nWhen returning from the hardware exception, tm_active_with_fp() is\nincorrectly making restore_fp() call load_fp_state() which is setting\nFP=1.\n\nThe fix is to remove tm_active_with_fp().\n\ntm_active_with_fp() is attempting to handle the case where FP state\nhas been changed inside a transaction. In this case the checkpointed\nand transactional FP state is different and hence we must restore the\nFP state (ie. we can't do lazy FP restore inside a transaction that's\nused FP). It's safe to remove tm_active_with_fp() as this case is\nhandled by restore_tm_state(). restore_tm_state() detects if FP has\nbeen using inside a transaction and will set load_fp and call\nrestore_math() to ensure the FP state (checkpoint and transaction) is\nrestored.\n\nThis is a data integrity problem for the current process as the FP\nregisters are corrupted. It's also a security problem as the FP\nregisters from one process may be leaked to another.\n\nSimilarly for VMX.\n\nA simple testcase to replicate this will be posted to\ntools/testing/selftests/powerpc/tm/tm-poison.c\n\nThis fixes CVE-2019-15031.\n\nFixes: a7771176b439 (\"powerpc: Don't enable FP/Altivec if not checkpointed\")\nCc: stable@vger.kernel.org # 4.15+\nSigned-off-by: Gustavo Romero \nSigned-off-by: Michael Neuling \nSigned-off-by: Michael Ellerman \nLink: https://lore.kernel.org/r/20190904045529.23002-2-gromero@linux.vnet.ibm.com'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: mldv2_query_print(netdissect_options *ndo, const u_char *bp, u_int len)\n{\n const struct icmp6_hdr *icp = (const struct icmp6_hdr *) bp;\n u_int mrc;\n int mrt, qqi;\n u_int nsrcs;\n register u_int i;\n\n /* Minimum len is 28 */\n if (len < 28) {\n ND_PRINT((ndo,\" [invalid len %d]\", len));\n\treturn;\n }\n ND_TCHECK(icp->icmp6_data16[0]);\n mrc = EXTRACT_16BITS(&icp->icmp6_data16[0]);\n if (mrc < 32768) {\n\tmrt = mrc;\n } else {\n mrt = ((mrc & 0x0fff) | 0x1000) << (((mrc & 0x7000) >> 12) + 3);\n }\n if (ndo->ndo_vflag) {\n ND_PRINT((ndo,\" [max resp delay=%d]\", mrt));\n }\n ND_TCHECK2(bp[8], sizeof(struct in6_addr));\n ND_PRINT((ndo,\" [gaddr %s\", ip6addr_string(ndo, &bp[8])));\n\n if (ndo->ndo_vflag) {\n ND_TCHECK(bp[25]);\n\tif (bp[24] & 0x08) {\n\t\tND_PRINT((ndo,\" sflag\"));\n\t}\n\tif (bp[24] & 0x07) {\n\t\tND_PRINT((ndo,\" robustness=%d\", bp[24] & 0x07));\n\t}\n\tif (bp[25] < 128) {\n\t\tqqi = bp[25];\n\t} else {\n\t\tqqi = ((bp[25] & 0x0f) | 0x10) << (((bp[25] & 0x70) >> 4) + 3);\n\t}\n\tND_PRINT((ndo,\" qqi=%d\", qqi));\n }\n\n ND_TCHECK2(bp[26], 2);\n nsrcs = EXTRACT_16BITS(&bp[26]);\n if (nsrcs > 0) {\n\tif (len < 28 + nsrcs * sizeof(struct in6_addr))\n\t ND_PRINT((ndo,\" [invalid number of sources]\"));\n\telse if (ndo->ndo_vflag > 1) {\n\t ND_PRINT((ndo,\" {\"));\n\t for (i = 0; i < nsrcs; i++) {\n\t\tND_TCHECK2(bp[28 + i * sizeof(struct in6_addr)],\n sizeof(struct in6_addr));\n\t\tND_PRINT((ndo,\" %s\", ip6addr_string(ndo, &bp[28 + i * sizeof(struct in6_addr)])));\n\t }\n\t ND_PRINT((ndo,\" }\"));\n\t} else\n ND_PRINT((ndo,\", %d source(s)\", nsrcs));\n }\n ND_PRINT((ndo,\"]\"));\n return;\ntrunc:\n ND_PRINT((ndo,\"[|icmp6]\"));\n return;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': '(for 4.9.3) CVE-2018-14882/ICMP6 RPL: Add a missing bounds check\n\nMoreover:\nAdd and use *_tstr[] strings.\nUpdate four tests outputs accordingly.\nFix a space.\n\nWang Junjie of 360 ESG Codesafe Team had independently identified this\nvulnerability in 2018 by means of fuzzing and provided the packet capture\nfile for the test.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: vrrp_print(netdissect_options *ndo,\n register const u_char *bp, register u_int len,\n register const u_char *bp2, int ttl)\n{\n\tint version, type, auth_type = VRRP_AUTH_NONE; /* keep compiler happy */\n\tconst char *type_s;\n\n\tND_TCHECK(bp[0]);\n\tversion = (bp[0] & 0xf0) >> 4;\n\ttype = bp[0] & 0x0f;\n\ttype_s = tok2str(type2str, \"unknown type (%u)\", type);\n\tND_PRINT((ndo, \"VRRPv%u, %s\", version, type_s));\n\tif (ttl != 255)\n\t\tND_PRINT((ndo, \", (ttl %u)\", ttl));\n\tif (version < 2 || version > 3 || type != VRRP_TYPE_ADVERTISEMENT)\n\t\treturn;\n\tND_TCHECK(bp[2]);\n\tND_PRINT((ndo, \", vrid %u, prio %u\", bp[1], bp[2]));\n\tND_TCHECK(bp[5]);\n\n\tif (version == 2) {\n\t\tauth_type = bp[4];\n\t\tND_PRINT((ndo, \", authtype %s\", tok2str(auth2str, NULL, auth_type)));\n\t\tND_PRINT((ndo, \", intvl %us, length %u\", bp[5], len));\n\t} else { /* version == 3 */\n\t\tuint16_t intvl = (bp[4] & 0x0f) << 8 | bp[5];\n\t\tND_PRINT((ndo, \", intvl %ucs, length %u\", intvl, len));\n\t}\n\n\tif (ndo->ndo_vflag) {\n\t\tint naddrs = bp[3];\n\t\tint i;\n\t\tchar c;\n\n\t\tif (version == 2 && ND_TTEST2(bp[0], len)) {\n\t\t\tstruct cksum_vec vec[1];\n\n\t\t\tvec[0].ptr = bp;\n\t\t\tvec[0].len = len;\n\t\t\tif (in_cksum(vec, 1))\n\t\t\t\tND_PRINT((ndo, \", (bad vrrp cksum %x)\",\n\t\t\t\t\tEXTRACT_16BITS(&bp[6])));\n\t\t}\n\n\t\tif (version == 3 && ND_TTEST2(bp[0], len)) {\n\t\t\tuint16_t cksum = nextproto4_cksum(ndo, (const struct ip *)bp2, bp,\n\t\t\t\tlen, len, IPPROTO_VRRP);\n\t\t\tif (cksum)\n\t\t\t\tND_PRINT((ndo, \", (bad vrrp cksum %x)\",\n\t\t\t\t\tEXTRACT_16BITS(&bp[6])));\n\t\t}\n\n\t\tND_PRINT((ndo, \", addrs\"));\n\t\tif (naddrs > 1)\n\t\t\tND_PRINT((ndo, \"(%d)\", naddrs));\n\t\tND_PRINT((ndo, \":\"));\n\t\tc = ' ';\n\t\tbp += 8;\n\t\tfor (i = 0; i < naddrs; i++) {\n\t\t\tND_TCHECK(bp[3]);\n\t\t\tND_PRINT((ndo, \"%c%s\", c, ipaddr_string(ndo, bp)));\n\t\t\tc = ',';\n\t\t\tbp += 4;\n\t\t}\n\t\tif (version == 2 && auth_type == VRRP_AUTH_SIMPLE) { /* simple text password */\n\t\t\tND_TCHECK(bp[7]);\n\t\t\tND_PRINT((ndo, \" auth \\\"\"));\n\t\t\tif (fn_printn(ndo, bp, 8, ndo->ndo_snapend)) {\n\t\t\t\tND_PRINT((ndo, \"\\\"\"));\n\t\t\t\tgoto trunc;\n\t\t\t}\n\t\t\tND_PRINT((ndo, \"\\\"\"));\n\t\t}\n\t}\n\treturn;\ntrunc:\n\tND_PRINT((ndo, \"[|vrrp]\"));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': '(for 4.9.3) CVE-2018-14463/VRRP: Add a missing bounds check\n\nIn vrrp_print().\n\nThis fixes a buffer over-read discovered by Bhargava Shastry.\n\nAdd a test using the capture file supplied by the reporter(s).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: lmp_print(netdissect_options *ndo,\n register const u_char *pptr, register u_int len)\n{\n const struct lmp_common_header *lmp_com_header;\n const struct lmp_object_header *lmp_obj_header;\n const u_char *tptr,*obj_tptr;\n u_int tlen,lmp_obj_len,lmp_obj_ctype,obj_tlen;\n int hexdump;\n u_int offset;\n u_int link_type;\n\n union { /* int to float conversion buffer */\n float f;\n uint32_t i;\n } bw;\n\n tptr=pptr;\n lmp_com_header = (const struct lmp_common_header *)pptr;\n ND_TCHECK(*lmp_com_header);\n\n /*\n * Sanity checking of the header.\n */\n if (LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]) != LMP_VERSION) {\n\tND_PRINT((ndo, \"LMP version %u packet not supported\",\n LMP_EXTRACT_VERSION(lmp_com_header->version_res[0])));\n\treturn;\n }\n\n /* in non-verbose mode just lets print the basic Message Type*/\n if (ndo->ndo_vflag < 1) {\n ND_PRINT((ndo, \"LMPv%u %s Message, length: %u\",\n LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]),\n tok2str(lmp_msg_type_values, \"unknown (%u)\",lmp_com_header->msg_type),\n len));\n return;\n }\n\n /* ok they seem to want to know everything - lets fully decode it */\n\n tlen=EXTRACT_16BITS(lmp_com_header->length);\n\n ND_PRINT((ndo, \"\\n\\tLMPv%u, msg-type: %s, Flags: [%s], length: %u\",\n LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]),\n tok2str(lmp_msg_type_values, \"unknown, type: %u\",lmp_com_header->msg_type),\n bittok2str(lmp_header_flag_values,\"none\",lmp_com_header->flags),\n tlen));\n if (tlen < sizeof(const struct lmp_common_header)) {\n ND_PRINT((ndo, \" (too short)\"));\n return;\n }\n if (tlen > len) {\n ND_PRINT((ndo, \" (too long)\"));\n tlen = len;\n }\n\n tptr+=sizeof(const struct lmp_common_header);\n tlen-=sizeof(const struct lmp_common_header);\n\n while(tlen>0) {\n /* did we capture enough for fully decoding the object header ? */\n ND_TCHECK2(*tptr, sizeof(struct lmp_object_header));\n\n lmp_obj_header = (const struct lmp_object_header *)tptr;\n lmp_obj_len=EXTRACT_16BITS(lmp_obj_header->length);\n lmp_obj_ctype=(lmp_obj_header->ctype)&0x7f;\n\n ND_PRINT((ndo, \"\\n\\t %s Object (%u), Class-Type: %s (%u) Flags: [%snegotiable], length: %u\",\n tok2str(lmp_obj_values,\n \"Unknown\",\n lmp_obj_header->class_num),\n lmp_obj_header->class_num,\n tok2str(lmp_ctype_values,\n \"Unknown\",\n ((lmp_obj_header->class_num)<<8)+lmp_obj_ctype),\n lmp_obj_ctype,\n (lmp_obj_header->ctype)&0x80 ? \"\" : \"non-\",\n lmp_obj_len));\n\n if (lmp_obj_len < 4) {\n ND_PRINT((ndo, \" (too short)\"));\n return;\n }\n if ((lmp_obj_len % 4) != 0) {\n ND_PRINT((ndo, \" (not a multiple of 4)\"));\n return;\n }\n\n obj_tptr=tptr+sizeof(struct lmp_object_header);\n obj_tlen=lmp_obj_len-sizeof(struct lmp_object_header);\n\n /* did we capture enough for fully decoding the object ? */\n ND_TCHECK2(*tptr, lmp_obj_len);\n hexdump=FALSE;\n\n switch(lmp_obj_header->class_num) {\n\n case LMP_OBJ_CC_ID:\n switch(lmp_obj_ctype) {\n case LMP_CTYPE_LOC:\n case LMP_CTYPE_RMT:\n if (obj_tlen != 4) {\n ND_PRINT((ndo, \" (not correct for object)\"));\n break;\n }\n ND_PRINT((ndo, \"\\n\\t Control Channel ID: %u (0x%08x)\",\n EXTRACT_32BITS(obj_tptr),\n EXTRACT_32BITS(obj_tptr)));\n break;\n\n default:\n hexdump=TRUE;\n }\n break;\n\n case LMP_OBJ_LINK_ID:\n case LMP_OBJ_INTERFACE_ID:\n switch(lmp_obj_ctype) {\n case LMP_CTYPE_IPV4_LOC:\n case LMP_CTYPE_IPV4_RMT:\n if (obj_tlen != 4) {\n ND_PRINT((ndo, \" (not correct for object)\"));\n break;\n }\n ND_PRINT((ndo, \"\\n\\t IPv4 Link ID: %s (0x%08x)\",\n ipaddr_string(ndo, obj_tptr),\n EXTRACT_32BITS(obj_tptr)));\n break;\n case LMP_CTYPE_IPV6_LOC:\n case LMP_CTYPE_IPV6_RMT:\n if (obj_tlen != 16) {\n ND_PRINT((ndo, \" (not correct for object)\"));\n break;\n }\n ND_PRINT((ndo, \"\\n\\t IPv6 Link ID: %s (0x%08x)\",\n ip6addr_string(ndo, obj_tptr),\n EXTRACT_32BITS(obj_tptr)));\n break;\n case LMP_CTYPE_UNMD_LOC:\n case LMP_CTYPE_UNMD_RMT:\n if (obj_tlen != 4) {\n ND_PRINT((ndo, \" (not correct for object)\"));\n break;\n }\n ND_PRINT((ndo, \"\\n\\t Link ID: %u (0x%08x)\",\n EXTRACT_32BITS(obj_tptr),\n EXTRACT_32BITS(obj_tptr)));\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case LMP_OBJ_MESSAGE_ID:\n switch(lmp_obj_ctype) {\n case LMP_CTYPE_1:\n if (obj_tlen != 4) {\n ND_PRINT((ndo, \" (not correct for object)\"));\n break;\n }\n ND_PRINT((ndo, \"\\n\\t Message ID: %u (0x%08x)\",\n EXTRACT_32BITS(obj_tptr),\n EXTRACT_32BITS(obj_tptr)));\n break;\n case LMP_CTYPE_2:\n if (obj_tlen != 4) {\n ND_PRINT((ndo, \" (not correct for object)\"));\n break;\n }\n ND_PRINT((ndo, \"\\n\\t Message ID Ack: %u (0x%08x)\",\n EXTRACT_32BITS(obj_tptr),\n EXTRACT_32BITS(obj_tptr)));\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n case LMP_OBJ_NODE_ID:\n switch(lmp_obj_ctype) {\n case LMP_CTYPE_LOC:\n case LMP_CTYPE_RMT:\n if (obj_tlen != 4) {\n ND_PRINT((ndo, \" (not correct for object)\"));\n break;\n }\n ND_PRINT((ndo, \"\\n\\t Node ID: %s (0x%08x)\",\n ipaddr_string(ndo, obj_tptr),\n EXTRACT_32BITS(obj_tptr)));\n break;\n\n default:\n hexdump=TRUE;\n }\n break;\n\n case LMP_OBJ_CONFIG:\n switch(lmp_obj_ctype) {\n case LMP_CTYPE_HELLO_CONFIG:\n if (obj_tlen != 4) {\n ND_PRINT((ndo, \" (not correct for object)\"));\n break;\n }\n ND_PRINT((ndo, \"\\n\\t Hello Interval: %u\\n\\t Hello Dead Interval: %u\",\n EXTRACT_16BITS(obj_tptr),\n EXTRACT_16BITS(obj_tptr+2)));\n break;\n\n default:\n hexdump=TRUE;\n }\n break;\n\n case LMP_OBJ_HELLO:\n switch(lmp_obj_ctype) {\n\t case LMP_CTYPE_HELLO:\n if (obj_tlen != 8) {\n ND_PRINT((ndo, \" (not correct for object)\"));\n break;\n }\n ND_PRINT((ndo, \"\\n\\t Tx Seq: %u, Rx Seq: %u\",\n EXTRACT_32BITS(obj_tptr),\n EXTRACT_32BITS(obj_tptr+4)));\n break;\n\n default:\n hexdump=TRUE;\n }\n break;\n\n case LMP_OBJ_TE_LINK:\n\t switch(lmp_obj_ctype) {\n\t case LMP_CTYPE_IPV4:\n if (obj_tlen != 12) {\n ND_PRINT((ndo, \" (not correct for object)\"));\n break;\n }\n\t\tND_PRINT((ndo, \"\\n\\t Flags: [%s]\",\n\t\t bittok2str(lmp_obj_te_link_flag_values,\n\t\t\t\"none\",\n\t\t\tEXTRACT_8BITS(obj_tptr))));\n\n\t\tND_PRINT((ndo, \"\\n\\t Local Link-ID: %s (0x%08x)\"\n\t\t \"\\n\\t Remote Link-ID: %s (0x%08x)\",\n ipaddr_string(ndo, obj_tptr+4),\n EXTRACT_32BITS(obj_tptr+4),\n ipaddr_string(ndo, obj_tptr+8),\n EXTRACT_32BITS(obj_tptr+8)));\n\t\tbreak;\n\n\t case LMP_CTYPE_IPV6:\n if (obj_tlen != 36) {\n ND_PRINT((ndo, \" (not correct for object)\"));\n break;\n }\n\t\tND_PRINT((ndo, \"\\n\\t Flags: [%s]\",\n\t\t bittok2str(lmp_obj_te_link_flag_values,\n\t\t\t\"none\",\n\t\t\tEXTRACT_8BITS(obj_tptr))));\n\n\t\tND_PRINT((ndo, \"\\n\\t Local Link-ID: %s (0x%08x)\"\n\t\t \"\\n\\t Remote Link-ID: %s (0x%08x)\",\n ip6addr_string(ndo, obj_tptr+4),\n EXTRACT_32BITS(obj_tptr+4),\n ip6addr_string(ndo, obj_tptr+20),\n EXTRACT_32BITS(obj_tptr+20)));\n break;\n\n\t case LMP_CTYPE_UNMD:\n if (obj_tlen != 12) {\n ND_PRINT((ndo, \" (not correct for object)\"));\n break;\n }\n\t\tND_PRINT((ndo, \"\\n\\t Flags: [%s]\",\n\t\t bittok2str(lmp_obj_te_link_flag_values,\n\t\t\t\"none\",\n\t\t\tEXTRACT_8BITS(obj_tptr))));\n\n\t\tND_PRINT((ndo, \"\\n\\t Local Link-ID: %u (0x%08x)\"\n\t\t \"\\n\\t Remote Link-ID: %u (0x%08x)\",\n EXTRACT_32BITS(obj_tptr+4),\n EXTRACT_32BITS(obj_tptr+4),\n EXTRACT_32BITS(obj_tptr+8),\n EXTRACT_32BITS(obj_tptr+8)));\n\t\tbreak;\n\n default:\n hexdump=TRUE;\n }\n break;\n\n case LMP_OBJ_DATA_LINK:\n\t switch(lmp_obj_ctype) {\n\t case LMP_CTYPE_IPV4:\n if (obj_tlen < 12) {\n ND_PRINT((ndo, \" (not correct for object)\"));\n break;\n }\n\t ND_PRINT((ndo, \"\\n\\t Flags: [%s]\",\n\t\t bittok2str(lmp_obj_data_link_flag_values,\n\t\t\t\"none\",\n\t\t\tEXTRACT_8BITS(obj_tptr))));\n ND_PRINT((ndo, \"\\n\\t Local Interface ID: %s (0x%08x)\"\n \"\\n\\t Remote Interface ID: %s (0x%08x)\",\n ipaddr_string(ndo, obj_tptr+4),\n EXTRACT_32BITS(obj_tptr+4),\n ipaddr_string(ndo, obj_tptr+8),\n EXTRACT_32BITS(obj_tptr+8)));\n\n\t\tif (lmp_print_data_link_subobjs(ndo, obj_tptr, obj_tlen - 12, 12))\n\t\t hexdump=TRUE;\n\t\tbreak;\n\n\t case LMP_CTYPE_IPV6:\n if (obj_tlen < 36) {\n ND_PRINT((ndo, \" (not correct for object)\"));\n break;\n }\n\t ND_PRINT((ndo, \"\\n\\t Flags: [%s]\",\n\t\t bittok2str(lmp_obj_data_link_flag_values,\n\t\t\t\"none\",\n\t\t\tEXTRACT_8BITS(obj_tptr))));\n ND_PRINT((ndo, \"\\n\\t Local Interface ID: %s (0x%08x)\"\n \"\\n\\t Remote Interface ID: %s (0x%08x)\",\n ip6addr_string(ndo, obj_tptr+4),\n EXTRACT_32BITS(obj_tptr+4),\n ip6addr_string(ndo, obj_tptr+20),\n EXTRACT_32BITS(obj_tptr+20)));\n\n\t\tif (lmp_print_data_link_subobjs(ndo, obj_tptr, obj_tlen - 36, 36))\n\t\t hexdump=TRUE;\n\t\tbreak;\n\n\t case LMP_CTYPE_UNMD:\n if (obj_tlen < 12) {\n ND_PRINT((ndo, \" (not correct for object)\"));\n break;\n }\n\t ND_PRINT((ndo, \"\\n\\t Flags: [%s]\",\n\t\t bittok2str(lmp_obj_data_link_flag_values,\n\t\t\t\"none\",\n\t\t\tEXTRACT_8BITS(obj_tptr))));\n ND_PRINT((ndo, \"\\n\\t Local Interface ID: %u (0x%08x)\"\n \"\\n\\t Remote Interface ID: %u (0x%08x)\",\n EXTRACT_32BITS(obj_tptr+4),\n EXTRACT_32BITS(obj_tptr+4),\n EXTRACT_32BITS(obj_tptr+8),\n EXTRACT_32BITS(obj_tptr+8)));\n\n\t\tif (lmp_print_data_link_subobjs(ndo, obj_tptr, obj_tlen - 12, 12))\n\t\t hexdump=TRUE;\n\t\tbreak;\n\n default:\n hexdump=TRUE;\n }\n break;\n\n case LMP_OBJ_VERIFY_BEGIN:\n\t switch(lmp_obj_ctype) {\n case LMP_CTYPE_1:\n if (obj_tlen != 20) {\n ND_PRINT((ndo, \" (not correct for object)\"));\n break;\n }\n\t\tND_PRINT((ndo, \"\\n\\t Flags: %s\",\n\t\tbittok2str(lmp_obj_begin_verify_flag_values,\n\t\t\t\"none\",\n\t\t\tEXTRACT_16BITS(obj_tptr))));\n\t\tND_PRINT((ndo, \"\\n\\t Verify Interval: %u\",\n\t\t\tEXTRACT_16BITS(obj_tptr+2)));\n\t\tND_PRINT((ndo, \"\\n\\t Data links: %u\",\n\t\t\tEXTRACT_32BITS(obj_tptr+4)));\n ND_PRINT((ndo, \"\\n\\t Encoding type: %s\",\n\t\t\ttok2str(gmpls_encoding_values, \"Unknown\", *(obj_tptr+8))));\n ND_PRINT((ndo, \"\\n\\t Verify Transport Mechanism: %u (0x%x)%s\",\n\t\t\tEXTRACT_16BITS(obj_tptr+10),\n\t\t\tEXTRACT_16BITS(obj_tptr+10),\n\t\t\tEXTRACT_16BITS(obj_tptr+10)&8000 ? \" (Payload test messages capable)\" : \"\"));\n bw.i = EXTRACT_32BITS(obj_tptr+12);\n\t\tND_PRINT((ndo, \"\\n\\t Transmission Rate: %.3f Mbps\",bw.f*8/1000000));\n\t\tND_PRINT((ndo, \"\\n\\t Wavelength: %u\",\n\t\t\tEXTRACT_32BITS(obj_tptr+16)));\n\t\tbreak;\n\n default:\n hexdump=TRUE;\n }\n break;\n\n case LMP_OBJ_VERIFY_BEGIN_ACK:\n\t switch(lmp_obj_ctype) {\n case LMP_CTYPE_1:\n if (obj_tlen != 4) {\n ND_PRINT((ndo, \" (not correct for object)\"));\n break;\n }\n ND_PRINT((ndo, \"\\n\\t Verify Dead Interval: %u\"\n \"\\n\\t Verify Transport Response: %u\",\n EXTRACT_16BITS(obj_tptr),\n EXTRACT_16BITS(obj_tptr+2)));\n break;\n\n default:\n hexdump=TRUE;\n }\n break;\n\n\tcase LMP_OBJ_VERIFY_ID:\n\t switch(lmp_obj_ctype) {\n case LMP_CTYPE_1:\n if (obj_tlen != 4) {\n ND_PRINT((ndo, \" (not correct for object)\"));\n break;\n }\n ND_PRINT((ndo, \"\\n\\t Verify ID: %u\",\n EXTRACT_32BITS(obj_tptr)));\n break;\n\n default:\n hexdump=TRUE;\n }\n break;\n\n\tcase LMP_OBJ_CHANNEL_STATUS:\n switch(lmp_obj_ctype) {\n\t case LMP_CTYPE_IPV4:\n\t\toffset = 0;\n\t\t/* Decode pairs: */\n\t\twhile (offset+8 <= obj_tlen) {\n\t\t\tND_PRINT((ndo, \"\\n\\t Interface ID: %s (0x%08x)\",\n\t\t\tipaddr_string(ndo, obj_tptr+offset),\n\t\t\tEXTRACT_32BITS(obj_tptr+offset)));\n\n\t\t\tND_PRINT((ndo, \"\\n\\t\\t Active: %s (%u)\",\n\t\t\t\t(EXTRACT_32BITS(obj_tptr+offset+4)>>31) ?\n\t\t\t\t\t\t\"Allocated\" : \"Non-allocated\",\n\t\t\t\t(EXTRACT_32BITS(obj_tptr+offset+4)>>31)));\n\n\t\t\tND_PRINT((ndo, \"\\n\\t\\t Direction: %s (%u)\",\n\t\t\t\t(EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1 ?\n\t\t\t\t\t\t\"Transmit\" : \"Receive\",\n\t\t\t\t(EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1));\n\n\t\t\tND_PRINT((ndo, \"\\n\\t\\t Channel Status: %s (%u)\",\n\t\t\t\t\ttok2str(lmp_obj_channel_status_values,\n\t\t\t \t\t\"Unknown\",\n\t\t\t\t\tEXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF),\n\t\t\tEXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF));\n\t\t\toffset+=8;\n\t\t}\n break;\n\n\t case LMP_CTYPE_IPV6:\n\t\toffset = 0;\n\t\t/* Decode pairs: */\n\t\twhile (offset+20 <= obj_tlen) {\n\t\t\tND_PRINT((ndo, \"\\n\\t Interface ID: %s (0x%08x)\",\n\t\t\tip6addr_string(ndo, obj_tptr+offset),\n\t\t\tEXTRACT_32BITS(obj_tptr+offset)));\n\n\t\t\tND_PRINT((ndo, \"\\n\\t\\t Active: %s (%u)\",\n\t\t\t\t(EXTRACT_32BITS(obj_tptr+offset+16)>>31) ?\n\t\t\t\t\t\t\"Allocated\" : \"Non-allocated\",\n\t\t\t\t(EXTRACT_32BITS(obj_tptr+offset+16)>>31)));\n\n\t\t\tND_PRINT((ndo, \"\\n\\t\\t Direction: %s (%u)\",\n\t\t\t\t(EXTRACT_32BITS(obj_tptr+offset+16)>>30)&0x1 ?\n\t\t\t\t\t\t\"Transmit\" : \"Receive\",\n\t\t\t\t(EXTRACT_32BITS(obj_tptr+offset+16)>>30)&0x1));\n\n\t\t\tND_PRINT((ndo, \"\\n\\t\\t Channel Status: %s (%u)\",\n\t\t\t\t\ttok2str(lmp_obj_channel_status_values,\n\t\t\t\t\t\"Unknown\",\n\t\t\t\t\tEXTRACT_32BITS(obj_tptr+offset+16)&0x3FFFFFF),\n\t\t\tEXTRACT_32BITS(obj_tptr+offset+16)&0x3FFFFFF));\n\t\t\toffset+=20;\n\t\t}\n break;\n\n\t case LMP_CTYPE_UNMD:\n\t\toffset = 0;\n\t\t/* Decode pairs: */\n\t\twhile (offset+8 <= obj_tlen) {\n\t\t\tND_PRINT((ndo, \"\\n\\t Interface ID: %u (0x%08x)\",\n\t\t\tEXTRACT_32BITS(obj_tptr+offset),\n\t\t\tEXTRACT_32BITS(obj_tptr+offset)));\n\n\t\t\tND_PRINT((ndo, \"\\n\\t\\t Active: %s (%u)\",\n\t\t\t\t(EXTRACT_32BITS(obj_tptr+offset+4)>>31) ?\n\t\t\t\t\t\t\"Allocated\" : \"Non-allocated\",\n\t\t\t\t(EXTRACT_32BITS(obj_tptr+offset+4)>>31)));\n\n\t\t\tND_PRINT((ndo, \"\\n\\t\\t Direction: %s (%u)\",\n\t\t\t\t(EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1 ?\n\t\t\t\t\t\t\"Transmit\" : \"Receive\",\n\t\t\t\t(EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1));\n\n\t\t\tND_PRINT((ndo, \"\\n\\t\\t Channel Status: %s (%u)\",\n\t\t\t\t\ttok2str(lmp_obj_channel_status_values,\n\t\t\t\t\t\"Unknown\",\n\t\t\t\t\tEXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF),\n\t\t\tEXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF));\n\t\t\toffset+=8;\n\t\t}\n break;\n\n default:\n hexdump=TRUE;\n }\n break;\n\n\tcase LMP_OBJ_CHANNEL_STATUS_REQ:\n switch(lmp_obj_ctype) {\n\t case LMP_CTYPE_IPV4:\n\t\toffset = 0;\n\t\twhile (offset+4 <= obj_tlen) {\n\t\t\tND_PRINT((ndo, \"\\n\\t Interface ID: %s (0x%08x)\",\n\t\t\tipaddr_string(ndo, obj_tptr+offset),\n\t\t\tEXTRACT_32BITS(obj_tptr+offset)));\n\t\t\toffset+=4;\n\t\t}\n break;\n\n\t case LMP_CTYPE_IPV6:\n\t\toffset = 0;\n\t\twhile (offset+16 <= obj_tlen) {\n\t\t\tND_PRINT((ndo, \"\\n\\t Interface ID: %s (0x%08x)\",\n\t\t\tip6addr_string(ndo, obj_tptr+offset),\n\t\t\tEXTRACT_32BITS(obj_tptr+offset)));\n\t\t\toffset+=16;\n\t\t}\n break;\n\n\t case LMP_CTYPE_UNMD:\n\t\toffset = 0;\n\t\twhile (offset+4 <= obj_tlen) {\n\t\t\tND_PRINT((ndo, \"\\n\\t Interface ID: %u (0x%08x)\",\n\t\t\tEXTRACT_32BITS(obj_tptr+offset),\n\t\t\tEXTRACT_32BITS(obj_tptr+offset)));\n\t\t\toffset+=4;\n\t\t}\n break;\n\n\t default:\n hexdump=TRUE;\n }\n break;\n\n case LMP_OBJ_ERROR_CODE:\n\t switch(lmp_obj_ctype) {\n case LMP_CTYPE_BEGIN_VERIFY_ERROR:\n if (obj_tlen != 4) {\n ND_PRINT((ndo, \" (not correct for object)\"));\n break;\n }\n\t\tND_PRINT((ndo, \"\\n\\t Error Code: %s\",\n\t\tbittok2str(lmp_obj_begin_verify_error_values,\n\t\t\t\"none\",\n\t\t\tEXTRACT_32BITS(obj_tptr))));\n break;\n\n case LMP_CTYPE_LINK_SUMMARY_ERROR:\n if (obj_tlen != 4) {\n ND_PRINT((ndo, \" (not correct for object)\"));\n break;\n }\n\t\tND_PRINT((ndo, \"\\n\\t Error Code: %s\",\n\t\tbittok2str(lmp_obj_link_summary_error_values,\n\t\t\t\"none\",\n\t\t\tEXTRACT_32BITS(obj_tptr))));\n break;\n default:\n hexdump=TRUE;\n }\n break;\n\n\tcase LMP_OBJ_SERVICE_CONFIG:\n\t switch (lmp_obj_ctype) {\n\t case LMP_CTYPE_SERVICE_CONFIG_SP:\n if (obj_tlen != 4) {\n ND_PRINT((ndo, \" (not correct for object)\"));\n break;\n }\n\t\tND_PRINT((ndo, \"\\n\\t Flags: %s\",\n\t\t bittok2str(lmp_obj_service_config_sp_flag_values,\n\t\t\t\t \"none\",\n\t\t\t\t EXTRACT_8BITS(obj_tptr))));\n\n\t\tND_PRINT((ndo, \"\\n\\t UNI Version: %u\",\n\t\t EXTRACT_8BITS(obj_tptr + 1)));\n\n\t\tbreak;\n\n case LMP_CTYPE_SERVICE_CONFIG_CPSA:\n if (obj_tlen != 16) {\n ND_PRINT((ndo, \" (not correct for object)\"));\n break;\n }\n\n\t\tlink_type = EXTRACT_8BITS(obj_tptr);\n\n\t\tND_PRINT((ndo, \"\\n\\t Link Type: %s (%u)\",\n\t\t tok2str(lmp_sd_service_config_cpsa_link_type_values,\n\t\t\t \"Unknown\", link_type),\n\t\t link_type));\n\n\t\tswitch (link_type) {\n\t\tcase LMP_SD_SERVICE_CONFIG_CPSA_LINK_TYPE_SDH:\n\t\t ND_PRINT((ndo, \"\\n\\t Signal Type: %s (%u)\",\n\t\t\t tok2str(lmp_sd_service_config_cpsa_signal_type_sdh_values,\n\t\t\t\t \"Unknown\",\n\t\t\t\t EXTRACT_8BITS(obj_tptr + 1)),\n\t\t\t\t EXTRACT_8BITS(obj_tptr + 1)));\n\t\t break;\n\n\t\tcase LMP_SD_SERVICE_CONFIG_CPSA_LINK_TYPE_SONET:\n\t\t ND_PRINT((ndo, \"\\n\\t Signal Type: %s (%u)\",\n\t\t\t tok2str(lmp_sd_service_config_cpsa_signal_type_sonet_values,\n\t\t\t\t \"Unknown\",\n\t\t\t\t EXTRACT_8BITS(obj_tptr + 1)),\n\t\t\t\t EXTRACT_8BITS(obj_tptr + 1)));\n\t\t break;\n\t\t}\n\n\t\tND_PRINT((ndo, \"\\n\\t Transparency: %s\",\n\t\t bittok2str(lmp_obj_service_config_cpsa_tp_flag_values,\n\t\t\t\t \"none\",\n\t\t\t\t EXTRACT_8BITS(obj_tptr + 2))));\n\n\t\tND_PRINT((ndo, \"\\n\\t Contiguous Concatenation Types: %s\",\n\t\t bittok2str(lmp_obj_service_config_cpsa_cct_flag_values,\n\t\t\t\t \"none\",\n\t\t\t\t EXTRACT_8BITS(obj_tptr + 3))));\n\n\t\tND_PRINT((ndo, \"\\n\\t Minimum NCC: %u\",\n\t\t EXTRACT_16BITS(obj_tptr+4)));\n\n\t\tND_PRINT((ndo, \"\\n\\t Maximum NCC: %u\",\n\t\t EXTRACT_16BITS(obj_tptr+6)));\n\n\t\tND_PRINT((ndo, \"\\n\\t Minimum NVC:%u\",\n\t\t EXTRACT_16BITS(obj_tptr+8)));\n\n\t\tND_PRINT((ndo, \"\\n\\t Maximum NVC:%u\",\n\t\t EXTRACT_16BITS(obj_tptr+10)));\n\n\t\tND_PRINT((ndo, \"\\n\\t Local Interface ID: %s (0x%08x)\",\n\t\t ipaddr_string(ndo, obj_tptr+12),\n\t\t EXTRACT_32BITS(obj_tptr+12)));\n\n\t\tbreak;\n\n\t case LMP_CTYPE_SERVICE_CONFIG_TRANSPARENCY_TCM:\n if (obj_tlen != 8) {\n ND_PRINT((ndo, \" (not correct for object)\"));\n break;\n }\n\n\t\tND_PRINT((ndo, \"\\n\\t Transparency Flags: %s\",\n\t\t bittok2str(\n\t\t\t lmp_obj_service_config_nsa_transparency_flag_values,\n\t\t\t \"none\",\n\t\t\t EXTRACT_32BITS(obj_tptr))));\n\n\t\tND_PRINT((ndo, \"\\n\\t TCM Monitoring Flags: %s\",\n\t\t bittok2str(\n\t\t\t lmp_obj_service_config_nsa_tcm_flag_values,\n\t\t\t \"none\",\n\t\t\t EXTRACT_8BITS(obj_tptr + 7))));\n\n\t\tbreak;\n\n\t case LMP_CTYPE_SERVICE_CONFIG_NETWORK_DIVERSITY:\n if (obj_tlen != 4) {\n ND_PRINT((ndo, \" (not correct for object)\"));\n break;\n }\n\n\t\tND_PRINT((ndo, \"\\n\\t Diversity: Flags: %s\",\n\t\t bittok2str(\n\t\t\t lmp_obj_service_config_nsa_network_diversity_flag_values,\n\t\t\t \"none\",\n\t\t\t EXTRACT_8BITS(obj_tptr + 3))));\n\t\tbreak;\n\n\t default:\n\t\thexdump = TRUE;\n\t }\n\n\tbreak;\n\n default:\n if (ndo->ndo_vflag <= 1)\n print_unknown_data(ndo,obj_tptr,\"\\n\\t \",obj_tlen);\n break;\n }\n /* do we want to see an additionally hexdump ? */\n if (ndo->ndo_vflag > 1 || hexdump==TRUE)\n print_unknown_data(ndo,tptr+sizeof(struct lmp_object_header),\"\\n\\t \",\n lmp_obj_len-sizeof(struct lmp_object_header));\n\n tptr+=lmp_obj_len;\n tlen-=lmp_obj_len;\n }\n return;\ntrunc:\n ND_PRINT((ndo, \"\\n\\t\\t packet exceeded snapshot\"));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': '(for 4.9.3) CVE-2018-14464/LMP: Add a missing bounds check\n\nIn lmp_print_data_link_subobjs().\n\nThis fixes a buffer over-read discovered by Bhargava Shastry,\nSecT/TU Berlin.\n\nAdd a test using the capture file supplied by the reporter(s).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: lmp_print_data_link_subobjs(netdissect_options *ndo, const u_char *obj_tptr,\n int total_subobj_len, int offset)\n{\n int hexdump = FALSE;\n int subobj_type, subobj_len;\n\n union { /* int to float conversion buffer */\n float f;\n uint32_t i;\n } bw;\n\n while (total_subobj_len > 0 && hexdump == FALSE ) {\n\tsubobj_type = EXTRACT_8BITS(obj_tptr + offset);\n\tsubobj_len = EXTRACT_8BITS(obj_tptr + offset + 1);\n\tND_PRINT((ndo, \"\\n\\t Subobject, Type: %s (%u), Length: %u\",\n\t\ttok2str(lmp_data_link_subobj,\n\t\t\t\"Unknown\",\n\t\t\tsubobj_type),\n\t\t\tsubobj_type,\n\t\t\tsubobj_len));\n\tif (subobj_len < 4) {\n\t ND_PRINT((ndo, \" (too short)\"));\n\t break;\n\t}\n\tif ((subobj_len % 4) != 0) {\n\t ND_PRINT((ndo, \" (not a multiple of 4)\"));\n\t break;\n\t}\n\tif (total_subobj_len < subobj_len) {\n\t ND_PRINT((ndo, \" (goes past the end of the object)\"));\n\t break;\n\t}\n\tswitch(subobj_type) {\n\tcase INT_SWITCHING_TYPE_SUBOBJ:\n\t ND_PRINT((ndo, \"\\n\\t Switching Type: %s (%u)\",\n\t\ttok2str(gmpls_switch_cap_values,\n\t\t\t\"Unknown\",\n\t\t\tEXTRACT_8BITS(obj_tptr + offset + 2)),\n\t\t\tEXTRACT_8BITS(obj_tptr + offset + 2)));\n\t ND_PRINT((ndo, \"\\n\\t Encoding Type: %s (%u)\",\n\t\ttok2str(gmpls_encoding_values,\n\t\t\t\"Unknown\",\n\t\t\tEXTRACT_8BITS(obj_tptr + offset + 3)),\n\t\t\tEXTRACT_8BITS(obj_tptr + offset + 3)));\n\t ND_TCHECK_32BITS(obj_tptr + offset + 4);\n\t bw.i = EXTRACT_32BITS(obj_tptr+offset+4);\n\t ND_PRINT((ndo, \"\\n\\t Min Reservable Bandwidth: %.3f Mbps\",\n bw.f*8/1000000));\n\t bw.i = EXTRACT_32BITS(obj_tptr+offset+8);\n\t ND_PRINT((ndo, \"\\n\\t Max Reservable Bandwidth: %.3f Mbps\",\n bw.f*8/1000000));\n\t break;\n\tcase WAVELENGTH_SUBOBJ:\n\t ND_PRINT((ndo, \"\\n\\t Wavelength: %u\",\n\t\tEXTRACT_32BITS(obj_tptr+offset+4)));\n\t break;\n\tdefault:\n\t /* Any Unknown Subobject ==> Exit loop */\n\t hexdump=TRUE;\n\t break;\n\t}\n\ttotal_subobj_len-=subobj_len;\n\toffset+=subobj_len;\n }\n return (hexdump);\ntrunc:\n return -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-120', 'CWE-119', 'CWE-787'], 'message': '(for 4.9.3) LMP: Add some missing bounds checks\n\nIn lmp_print_data_link_subobjs(), these problems were identified\nthrough code review.\n\nMoreover:\nAdd and use tstr[].\nUpdate two tests outputs accordingly.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: daemon_AuthUserPwd(char *username, char *password, char *errbuf)\n{\n#ifdef _WIN32\n\t/*\n\t * Warning: the user which launches the process must have the\n\t * SE_TCB_NAME right.\n\t * This corresponds to have the \"Act as part of the Operating System\"\n\t * turned on (administrative tools, local security settings, local\n\t * policies, user right assignment)\n\t * However, it seems to me that if you run it as a service, this\n\t * right should be provided by default.\n\t *\n\t * XXX - hopefully, this returns errors such as ERROR_LOGON_FAILURE,\n\t * which merely indicates that the user name or password is\n\t * incorrect, not whether it's the user name or the password\n\t * that's incorrect, so a client that's trying to brute-force\n\t * accounts doesn't know whether it's the user name or the\n\t * password that's incorrect, so it doesn't know whether to\n\t * stop trying to log in with a given user name and move on\n\t * to another user name.\n\t */\n\tHANDLE Token;\n\tif (LogonUser(username, \".\", password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &Token) == 0)\n\t{\n\t\tpcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,\n\t\t GetLastError(), \"LogonUser() failed\");\n\t\treturn -1;\n\t}\n\n\t// This call should change the current thread to the selected user.\n\t// I didn't test it.\n\tif (ImpersonateLoggedOnUser(Token) == 0)\n\t{\n\t\tpcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,\n\t\t GetLastError(), \"ImpersonateLoggedOnUser() failed\");\n\t\tCloseHandle(Token);\n\t\treturn -1;\n\t}\n\n\tCloseHandle(Token);\n\treturn 0;\n\n#else\n\t/*\n\t * See\n\t *\n\t *\thttp://www.unixpapa.com/incnote/passwd.html\n\t *\n\t * We use the Solaris/Linux shadow password authentication if\n\t * we have getspnam(), otherwise we just do traditional\n\t * authentication, which, on some platforms, might work, even\n\t * with shadow passwords, if we're running as root. Traditional\n\t * authenticaion won't work if we're not running as root, as\n\t * I think these days all UN*Xes either won't return the password\n\t * at all with getpwnam() or will only do so if you're root.\n\t *\n\t * XXX - perhaps what we *should* be using is PAM, if we have\n\t * it. That might hide all the details of username/password\n\t * authentication, whether it's done with a visible-to-root-\n\t * only password database or some other authentication mechanism,\n\t * behind its API.\n\t */\n\tstruct passwd *user;\n\tchar *user_password;\n#ifdef HAVE_GETSPNAM\n\tstruct spwd *usersp;\n#endif\n\tchar *crypt_password;\n\n\t// This call is needed to get the uid\n\tif ((user = getpwnam(username)) == NULL)\n\t{\n\t\tpcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, \"Authentication failed: user name or password incorrect\");\n\t\treturn -1;\n\t}\n\n#ifdef HAVE_GETSPNAM\n\t// This call is needed to get the password; otherwise 'x' is returned\n\tif ((usersp = getspnam(username)) == NULL)\n\t{\n\t\tpcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, \"Authentication failed: user name or password incorrect\");\n\t\treturn -1;\n\t}\n\tuser_password = usersp->sp_pwdp;\n#else\n\t/*\n\t * XXX - what about other platforms?\n\t * The unixpapa.com page claims this Just Works on *BSD if you're\n\t * running as root - it's from 2000, so it doesn't indicate whether\n\t * macOS (which didn't come out until 2001, under the name Mac OS\n\t * X) behaves like the *BSDs or not, and might also work on AIX.\n\t * HP-UX does something else.\n\t *\n\t * Again, hopefully PAM hides all that.\n\t */\n\tuser_password = user->pw_passwd;\n#endif\n\n\tcrypt_password = crypt(password, user_password);\n\tif (crypt_password == NULL)\n\t{\n\t\tpcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, \"Authentication failed\");\n\t\treturn -1;\n\t}\n\tif (strcmp(user_password, crypt_password) != 0)\n\t{\n\t\tpcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, \"Authentication failed: user name or password incorrect\");\n\t\treturn -1;\n\t}\n\n\tif (setuid(user->pw_uid))\n\t{\n\t\tpcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,\n\t\t errno, \"setuid\");\n\t\treturn -1;\n\t}\n\n/*\tif (setgid(user->pw_gid))\n\t{\n\t\tpcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,\n\t\t errno, \"setgid\");\n\t\treturn -1;\n\t}\n*/\n\treturn 0;\n\n#endif\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-345', 'CWE-787'], 'message': 'On UN*X, don't tell the client why authentication failed.\n\n\"no such user\" tells the client that the user ID isn't valid and,\ntherefore, that it needn't bother trying to do password cracking for\nthat user ID; just saying that the authentication failed dosn't give\nthem that hint.\n\nThis resolves the third problem in Include Security issue F11: [libpcap]\nRemote Packet Capture Daemon Multiple Authentication Improvements.\n\nThe Windows LogonUser() API returns ERROR_LOGON_FAILURE for both cases,\nso the Windows code doesn't have this issue. Just return the same\n\"Authentication failed\" message on Windows to the user.\n\nFor various authentication failures *other* than \"no such user\" and\n\"password not valid\", log a message, as there's a problem that may need\ndebugging. We don't need to tell the end user what the problem is, as\nthey may not bother reporting it and, even if they do, they may not give\nthe full error message.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void __exit pf_exit(void)\n{\n\tstruct pf_unit *pf;\n\tint unit;\n\tunregister_blkdev(major, name);\n\tfor (pf = units, unit = 0; unit < PF_UNITS; pf++, unit++) {\n\t\tif (pf->present)\n\t\t\tdel_gendisk(pf->disk);\n\n\t\tblk_cleanup_queue(pf->disk->queue);\n\t\tblk_mq_free_tag_set(&pf->tag_set);\n\t\tput_disk(pf->disk);\n\n\t\tif (pf->present)\n\t\t\tpi_release(pf->pi);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-125'], 'message': 'paride/pf: Fix potential NULL pointer dereference\n\nSyzkaller report this:\n\npf: pf version 1.04, major 47, cluster 64, nice 0\npf: No ATAPI disk detected\nkasan: CONFIG_KASAN_INLINE enabled\nkasan: GPF could be caused by NULL-ptr deref or user memory access\ngeneral protection fault: 0000 [#1] SMP KASAN PTI\nCPU: 0 PID: 9887 Comm: syz-executor.0 Tainted: G C 5.1.0-rc3+ #8\nHardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014\nRIP: 0010:pf_init+0x7af/0x1000 [pf]\nCode: 46 77 d2 48 89 d8 48 c1 e8 03 80 3c 28 00 74 08 48 89 df e8 03 25 a6 d2 4c 8b 23 49 8d bc 24 80 05 00 00 48 89 f8 48 c1 e8 03 <80> 3c 28 00 74 05 e8 e6 24 a6 d2 49 8b bc 24 80 05 00 00 e8 79 34\nRSP: 0018:ffff8881abcbf998 EFLAGS: 00010202\nRAX: 00000000000000b0 RBX: ffffffffc1e4a8a8 RCX: ffffffffaec50788\nRDX: 0000000000039b10 RSI: ffffc9000153c000 RDI: 0000000000000580\nRBP: dffffc0000000000 R08: ffffed103ee44e59 R09: ffffed103ee44e59\nR10: 0000000000000001 R11: ffffed103ee44e58 R12: 0000000000000000\nR13: ffffffffc1e4b028 R14: 0000000000000000 R15: 0000000000000020\nFS: 00007f1b78a91700(0000) GS:ffff8881f7200000(0000) knlGS:0000000000000000\nCS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033\nCR2: 00007f6d72b207f8 CR3: 00000001d5790004 CR4: 00000000007606f0\nDR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000\nDR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400\nPKRU: 55555554\nCall Trace:\n ? 0xffffffffc1e50000\n do_one_initcall+0xbc/0x47d init/main.c:901\n do_init_module+0x1b5/0x547 kernel/module.c:3456\n load_module+0x6405/0x8c10 kernel/module.c:3804\n __do_sys_finit_module+0x162/0x190 kernel/module.c:3898\n do_syscall_64+0x9f/0x450 arch/x86/entry/common.c:290\n entry_SYSCALL_64_after_hwframe+0x49/0xbe\nRIP: 0033:0x462e99\nCode: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48\nRSP: 002b:00007f1b78a90c58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139\nRAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99\nRDX: 0000000000000000 RSI: 0000000020000180 RDI: 0000000000000003\nRBP: 00007f1b78a90c70 R08: 0000000000000000 R09: 0000000000000000\nR10: 0000000000000000 R11: 0000000000000246 R12: 00007f1b78a916bc\nR13: 00000000004bcefa R14: 00000000006f6fb0 R15: 0000000000000004\nModules linked in: pf(+) paride gpio_tps65218 tps65218 i2c_cht_wc ati_remote dc395x act_meta_skbtcindex act_ife ife ecdh_generic rc_xbox_dvd sky81452_regulator v4l2_fwnode leds_blinkm snd_usb_hiface comedi(C) aes_ti slhc cfi_cmdset_0020 mtd cfi_util sx8654 mdio_gpio of_mdio fixed_phy mdio_bitbang libphy alcor_pci matrix_keymap hid_uclogic usbhid scsi_transport_fc videobuf2_v4l2 videobuf2_dma_sg snd_soc_pcm179x_spi snd_soc_pcm179x_codec i2c_demux_pinctrl mdev snd_indigodj isl6405 mii enc28j60 cmac adt7316_i2c(C) adt7316(C) fmc_trivial fmc nf_reject_ipv4 authenc rc_dtt200u rtc_ds1672 dvb_usb_dibusb_mc dvb_usb_dibusb_mc_common dib3000mc dibx000_common dvb_usb_dibusb_common dvb_usb dvb_core videobuf2_common videobuf2_vmalloc videobuf2_memops regulator_haptic adf7242 mac802154 ieee802154 s5h1409 da9034_ts snd_intel8x0m wmi cx24120 usbcore sdhci_cadence sdhci_pltfm sdhci mmc_core joydev i2c_algo_bit scsi_transport_iscsi iscsi_boot_sysfs ves1820 lockd grace nfs_acl auth_rpcgss sunrp\n c\n ip_vs snd_soc_adau7002 snd_cs4281 snd_rawmidi gameport snd_opl3_lib snd_seq_device snd_hwdep snd_ac97_codec ad7418 hid_primax hid snd_soc_cs4265 snd_soc_core snd_pcm_dmaengine snd_pcm snd_timer ac97_bus snd_compress snd soundcore ti_adc108s102 eeprom_93cx6 i2c_algo_pca mlxreg_hotplug st_pressure st_sensors industrialio_triggered_buffer kfifo_buf industrialio v4l2_common videodev media snd_soc_adau_utils rc_pinnacle_grey rc_core pps_gpio leds_lm3692x nandcore ledtrig_pattern iptable_security iptable_raw iptable_mangle iptable_nat nf_nat nf_conntrack nf_defrag_ipv6 nf_defrag_ipv4 iptable_filter bpfilter ip6_vti ip_vti ip_gre ipip sit tunnel4 ip_tunnel hsr veth netdevsim vxcan batman_adv cfg80211 rfkill chnl_net caif nlmon dummy team bonding vcan bridge stp llc ip6_gre gre ip6_tunnel tunnel6 tun mousedev ppdev tpm kvm_intel kvm irqbypass crct10dif_pclmul crc32_pclmul crc32c_intel ghash_clmulni_intel aesni_intel ide_pci_generic aes_x86_64 piix crypto_simd input_leds psmouse cryp\n td\n glue_helper ide_core intel_agp serio_raw intel_gtt agpgart ata_generic i2c_piix4 pata_acpi parport_pc parport rtc_cmos floppy sch_fq_codel ip_tables x_tables sha1_ssse3 sha1_generic ipv6 [last unloaded: paride]\nDumping ftrace buffer:\n (ftrace buffer empty)\n---[ end trace 7a818cf5f210d79e ]---\n\nIf alloc_disk fails in pf_init_units, pf->disk will be\nNULL, however in pf_detect and pf_exit, it's not check\nthis before free.It may result a NULL pointer dereference.\n\nAlso when register_blkdev failed, blk_cleanup_queue() and\nblk_mq_free_tag_set() should be called to free resources.\n\nReported-by: Hulk Robot \nFixes: 6ce59025f118 (\"paride/pf: cleanup queues when detection fails\")\nSigned-off-by: YueHaibing \n\nSigned-off-by: Jens Axboe '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: _gcry_ecc_ecdsa_sign (gcry_mpi_t input, ECC_secret_key *skey,\n gcry_mpi_t r, gcry_mpi_t s,\n int flags, int hashalgo)\n{\n gpg_err_code_t rc = 0;\n int extraloops = 0;\n gcry_mpi_t k, dr, sum, k_1, x;\n mpi_point_struct I;\n gcry_mpi_t hash;\n const void *abuf;\n unsigned int abits, qbits;\n mpi_ec_t ctx;\n gcry_mpi_t b; /* Random number needed for blinding. */\n gcry_mpi_t bi; /* multiplicative inverse of B. */\n\n if (DBG_CIPHER)\n log_mpidump (\"ecdsa sign hash \", input );\n\n qbits = mpi_get_nbits (skey->E.n);\n\n /* Convert the INPUT into an MPI if needed. */\n rc = _gcry_dsa_normalize_hash (input, &hash, qbits);\n if (rc)\n return rc;\n\n b = mpi_snew (qbits);\n bi = mpi_snew (qbits);\n do\n {\n _gcry_mpi_randomize (b, qbits, GCRY_WEAK_RANDOM);\n mpi_mod (b, b, skey->E.n);\n }\n while (!mpi_invm (bi, b, skey->E.n));\n\n k = NULL;\n dr = mpi_alloc (0);\n sum = mpi_alloc (0);\n k_1 = mpi_alloc (0);\n x = mpi_alloc (0);\n point_init (&I);\n\n ctx = _gcry_mpi_ec_p_internal_new (skey->E.model, skey->E.dialect, 0,\n skey->E.p, skey->E.a, skey->E.b);\n\n /* Two loops to avoid R or S are zero. This is more of a joke than\n a real demand because the probability of them being zero is less\n than any hardware failure. Some specs however require it. */\n do\n {\n do\n {\n mpi_free (k);\n k = NULL;\n if ((flags & PUBKEY_FLAG_RFC6979) && hashalgo)\n {\n /* Use Pornin's method for deterministic DSA. If this\n flag is set, it is expected that HASH is an opaque\n MPI with the to be signed hash. That hash is also\n used as h1 from 3.2.a. */\n if (!mpi_is_opaque (input))\n {\n rc = GPG_ERR_CONFLICT;\n goto leave;\n }\n\n abuf = mpi_get_opaque (input, &abits);\n rc = _gcry_dsa_gen_rfc6979_k (&k, skey->E.n, skey->d,\n abuf, (abits+7)/8,\n hashalgo, extraloops);\n if (rc)\n goto leave;\n extraloops++;\n }\n else\n k = _gcry_dsa_gen_k (skey->E.n, GCRY_STRONG_RANDOM);\n\n /* Originally, ECDSA computation requires k where 0 < k < n.\n * Here, we add n (the order of curve), to keep k in a\n * range: n < k < 2*n, or, addming more n, keep k in a range:\n * 2*n < k < 3*n, so that timing difference of the EC\n * multiply operation can be small. The result is same.\n */\n mpi_add (k, k, skey->E.n);\n if (!mpi_test_bit (k, qbits))\n mpi_add (k, k, skey->E.n);\n\n _gcry_mpi_ec_mul_point (&I, k, &skey->E.G, ctx);\n if (_gcry_mpi_ec_get_affine (x, NULL, &I, ctx))\n {\n if (DBG_CIPHER)\n log_debug (\"ecc sign: Failed to get affine coordinates\\n\");\n rc = GPG_ERR_BAD_SIGNATURE;\n goto leave;\n }\n mpi_mod (r, x, skey->E.n); /* r = x mod n */\n }\n while (!mpi_cmp_ui (r, 0));\n\n mpi_mulm (dr, b, skey->d, skey->E.n);\n mpi_mulm (dr, dr, r, skey->E.n); /* dr = d*r mod n (blinded with b) */\n mpi_mulm (sum, b, hash, skey->E.n);\n mpi_addm (sum, sum, dr, skey->E.n); /* sum = hash + (d*r) mod n (blinded with b) */\n mpi_mulm (sum, bi, sum, skey->E.n); /* undo blinding by b^-1 */\n mpi_invm (k_1, k, skey->E.n); /* k_1 = k^(-1) mod n */\n mpi_mulm (s, k_1, sum, skey->E.n); /* s = k^(-1)*(hash+(d*r)) mod n */\n }\n while (!mpi_cmp_ui (s, 0));\n\n if (DBG_CIPHER)\n {\n log_mpidump (\"ecdsa sign result r \", r);\n log_mpidump (\"ecdsa sign result s \", s);\n }\n\n leave:\n mpi_free (b);\n mpi_free (bi);\n _gcry_mpi_ec_free (ctx);\n point_free (&I);\n mpi_free (x);\n mpi_free (k_1);\n mpi_free (sum);\n mpi_free (dr);\n mpi_free (k);\n\n if (hash != input)\n mpi_free (hash);\n\n return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-203'], 'message': 'dsa,ecdsa: Fix use of nonce, use larger one.\n\n* cipher/dsa-common.c (_gcry_dsa_modify_k): New.\n* cipher/pubkey-internal.h (_gcry_dsa_modify_k): New.\n* cipher/dsa.c (sign): Use _gcry_dsa_modify_k.\n* cipher/ecc-ecdsa.c (_gcry_ecc_ecdsa_sign): Likewise.\n* cipher/ecc-gost.c (_gcry_ecc_gost_sign): Likewise.\n\nCVE-id: CVE-2019-13627\nGnuPG-bug-id: 4626\nSigned-off-by: NIIBE Yutaka '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: label (const uint8_t * src, size_t srclen, uint8_t * dst, size_t * dstlen,\n int flags)\n{\n size_t plen;\n uint32_t *p;\n int rc;\n size_t tmpl;\n\n if (_idn2_ascii_p (src, srclen))\n {\n if (flags & IDN2_ALABEL_ROUNDTRIP)\n\t/* FIXME implement this MAY:\n\n\t If the input to this procedure appears to be an A-label\n\t (i.e., it starts in \"xn--\", interpreted\n\t case-insensitively), the lookup application MAY attempt to\n\t convert it to a U-label, first ensuring that the A-label is\n\t entirely in lowercase (converting it to lowercase if\n\t necessary), and apply the tests of Section 5.4 and the\n\t conversion of Section 5.5 to that form. */\n\treturn IDN2_INVALID_FLAGS;\n\n if (srclen > IDN2_LABEL_MAX_LENGTH)\n\treturn IDN2_TOO_BIG_LABEL;\n if (srclen > *dstlen)\n\treturn IDN2_TOO_BIG_DOMAIN;\n\n memcpy (dst, src, srclen);\n *dstlen = srclen;\n return IDN2_OK;\n }\n\n rc = _idn2_u8_to_u32_nfc (src, srclen, &p, &plen, flags & IDN2_NFC_INPUT);\n if (rc != IDN2_OK)\n return rc;\n\n if (!(flags & IDN2_TRANSITIONAL))\n {\n rc = _idn2_label_test(\n\tTEST_NFC |\n\tTEST_2HYPHEN |\n\tTEST_LEADING_COMBINING |\n\tTEST_DISALLOWED |\n\tTEST_CONTEXTJ_RULE |\n\tTEST_CONTEXTO_WITH_RULE |\n\tTEST_UNASSIGNED | TEST_BIDI |\n\t((flags & IDN2_NONTRANSITIONAL) ? TEST_NONTRANSITIONAL : 0) |\n\t((flags & IDN2_USE_STD3_ASCII_RULES) ? 0 : TEST_ALLOW_STD3_DISALLOWED),\n\tp, plen);\n\n if (rc != IDN2_OK)\n\t{\n\t free(p);\n\t return rc;\n\t}\n }\n\n dst[0] = 'x';\n dst[1] = 'n';\n dst[2] = '-';\n dst[3] = '-';\n\n tmpl = *dstlen - 4;\n rc = _idn2_punycode_encode (plen, p, &tmpl, (char *) dst + 4);\n free (p);\n if (rc != IDN2_OK)\n return rc;\n\n *dstlen = 4 + tmpl;\n\n return IDN2_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Perform A-Label roundtrip for lookup functions by default\n\nThis adds another check to avoid unexpected results.\nIt was a longstanding FIXME.\n\nThanks to Jonathan Birch of Microsoft Corporation,\nFlorian Weimer (GNU glibc) and Nikos Mavrogiannopoulos (GnuTLS)\nfor investigation, discussion and testing.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int check_resource_valid(struct vrend_renderer_resource_create_args *args)\n{\n /* do not accept handle 0 */\n if (args->handle == 0)\n return -1;\n\n /* limit the target */\n if (args->target >= PIPE_MAX_TEXTURE_TYPES)\n return -1;\n\n if (args->format >= VIRGL_FORMAT_MAX)\n return -1;\n\n /* only texture 2d and 2d array can have multiple samples */\n if (args->nr_samples > 0) {\n if (!has_feature(feat_texture_multisample))\n return -1;\n\n if (args->target != PIPE_TEXTURE_2D && args->target != PIPE_TEXTURE_2D_ARRAY)\n return -1;\n /* multisample can't have miplevels */\n if (args->last_level > 0)\n return -1;\n }\n\n if (args->last_level > 0) {\n /* buffer and rect textures can't have mipmaps */\n if (args->target == PIPE_BUFFER || args->target == PIPE_TEXTURE_RECT)\n return -1;\n if (args->last_level > (floor(log2(MAX2(args->width, args->height))) + 1))\n return -1;\n }\n if (args->flags != 0 && args->flags != VIRGL_RESOURCE_Y_0_TOP)\n return -1;\n\n if (args->flags & VIRGL_RESOURCE_Y_0_TOP)\n if (args->target != PIPE_TEXTURE_2D && args->target != PIPE_TEXTURE_RECT)\n return -1;\n\n /* array size for array textures only */\n if (args->target == PIPE_TEXTURE_CUBE) {\n if (args->array_size != 6)\n return -1;\n } else if (args->target == PIPE_TEXTURE_CUBE_ARRAY) {\n if (!has_feature(feat_cube_map_array))\n return -1;\n if (args->array_size % 6)\n return -1;\n } else if (args->array_size > 1) {\n if (args->target != PIPE_TEXTURE_2D_ARRAY &&\n args->target != PIPE_TEXTURE_1D_ARRAY)\n return -1;\n\n if (!has_feature(feat_texture_array))\n return -1;\n }\n\n if (args->bind == 0 ||\n args->bind == VIRGL_BIND_CUSTOM ||\n args->bind == VIRGL_BIND_STAGING ||\n args->bind == VIRGL_BIND_INDEX_BUFFER ||\n args->bind == VIRGL_BIND_STREAM_OUTPUT ||\n args->bind == VIRGL_BIND_VERTEX_BUFFER ||\n args->bind == VIRGL_BIND_CONSTANT_BUFFER ||\n args->bind == VIRGL_BIND_QUERY_BUFFER ||\n args->bind == VIRGL_BIND_COMMAND_ARGS ||\n args->bind == VIRGL_BIND_SHADER_BUFFER) {\n if (args->target != PIPE_BUFFER)\n return -1;\n if (args->height != 1 || args->depth != 1)\n return -1;\n if (args->bind == VIRGL_BIND_QUERY_BUFFER && !has_feature(feat_qbo))\n return -1;\n if (args->bind == VIRGL_BIND_COMMAND_ARGS && !has_feature(feat_indirect_draw))\n return -1;\n } else {\n if (!((args->bind & VIRGL_BIND_SAMPLER_VIEW) ||\n (args->bind & VIRGL_BIND_DEPTH_STENCIL) ||\n (args->bind & VIRGL_BIND_RENDER_TARGET) ||\n (args->bind & VIRGL_BIND_CURSOR) ||\n (args->bind & VIRGL_BIND_SHARED) ||\n (args->bind & VIRGL_BIND_LINEAR))) {\n return -1;\n }\n\n if (args->target == PIPE_TEXTURE_2D ||\n args->target == PIPE_TEXTURE_RECT ||\n args->target == PIPE_TEXTURE_CUBE ||\n args->target == PIPE_TEXTURE_2D_ARRAY ||\n args->target == PIPE_TEXTURE_CUBE_ARRAY) {\n if (args->depth != 1)\n return -1;\n }\n if (args->target == PIPE_TEXTURE_1D ||\n args->target == PIPE_TEXTURE_1D_ARRAY) {\n if (args->height != 1 || args->depth != 1)\n return -1;\n }\n }\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'vrend: Check resource creation more thoroughly\n\nWhile we are at it:\n - free memory if texture allocation fails\n\nCloses #144\nCloses #145\nCloses #146\n\nv2: Move the error string creation to extra patch (Emil)\nv3: Fix whitespace errors (Emil) and one logic error\n\nSigned-off-by: Gert Wollny \nReviewed-by: Emil Velikov '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: _nc_find_type_entry(const char *string,\n\t\t int type,\n\t\t bool termcap)\n{\n struct name_table_entry const *ptr = NULL;\n const HashData *data = _nc_get_hash_info(termcap);\n int hashvalue = data->hash_of(string);\n\n if (data->table_data[hashvalue] >= 0) {\n\tconst struct name_table_entry *const table = _nc_get_table(termcap);\n\n\tptr = table + data->table_data[hashvalue];\n\twhile (ptr->nte_type != type\n\t || !data->compare_names(ptr->nte_name, string)) {\n\t if (ptr->nte_link < 0) {\n\t\tptr = 0;\n\t\tbreak;\n\t }\n\t ptr = table + (ptr->nte_link + data->table_data[data->table_size]);\n\t}\n }\n\n return ptr;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'ncurses 6.1 - patch 20191012\n\n+ amend recent changes to ncurses*-config and pc-files to filter out\n Debian linker-flags (report by Sven Joachim, cf: 20150516).\n+ clarify relationship between tic, infocmp and captoinfo in manpage.\n+ check for invalid hashcode in _nc_find_type_entry and\n _nc_find_name_entry.\n> fix several errata in tic (reports/testcases by \"zjuchenyuan\"):\n+ check for invalid hashcode in _nc_find_entry.\n+ check for missing character after backslash in fmt_entry\n+ check for acsc with odd length in dump_entry in check for one-one\n mapping (cf: 20060415);\n+ check length when converting from old AIX box_chars_1 capability,\n overlooked in changes to eliminate strcpy (cf: 20001007).\n+ amend the ncurses*-config and pc-files to take into account the rpath'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static boolean ReadICCProfile(j_decompress_ptr jpeg_info)\n{\n char\n magick[12];\n\n ErrorManager\n *error_manager;\n\n ExceptionInfo\n *exception;\n\n Image\n *image;\n\n MagickBooleanType\n status;\n\n register ssize_t\n i;\n\n register unsigned char\n *p;\n\n size_t\n length;\n\n StringInfo\n *icc_profile,\n *profile;\n\n /*\n Read color profile.\n */\n length=(size_t) ((size_t) GetCharacter(jpeg_info) << 8);\n length+=(size_t) GetCharacter(jpeg_info);\n length-=2;\n if (length <= 14)\n {\n while (length-- > 0)\n if (GetCharacter(jpeg_info) == EOF)\n break;\n return(TRUE);\n }\n for (i=0; i < 12; i++)\n magick[i]=(char) GetCharacter(jpeg_info);\n if (LocaleCompare(magick,ICC_PROFILE) != 0)\n {\n /*\n Not a ICC profile, return.\n */\n for (i=0; i < (ssize_t) (length-12); i++)\n if (GetCharacter(jpeg_info) == EOF)\n break;\n return(TRUE);\n }\n (void) GetCharacter(jpeg_info); /* id */\n (void) GetCharacter(jpeg_info); /* markers */\n length-=14;\n error_manager=(ErrorManager *) jpeg_info->client_data;\n exception=error_manager->exception;\n image=error_manager->image;\n profile=BlobToStringInfo((const void *) NULL,length);\n if (profile == (StringInfo *) NULL)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",image->filename);\n return(FALSE);\n }\n error_manager->profile=profile;\n p=GetStringInfoDatum(profile);\n for (i=0; i < (ssize_t) length; i++)\n {\n int\n c;\n\n c=GetCharacter(jpeg_info);\n if (c == EOF)\n break;\n *p++=(unsigned char) c;\n }\n if (i != (ssize_t) length)\n {\n profile=DestroyStringInfo(profile);\n (void) ThrowMagickException(exception,GetMagickModule(),\n CorruptImageError,\"InsufficientImageDataInFile\",\"`%s'\",\n image->filename);\n return(FALSE);\n }\n error_manager->profile=NULL;\n icc_profile=(StringInfo *) GetImageProfile(image,\"icc\");\n if (icc_profile != (StringInfo *) NULL)\n {\n ConcatenateStringInfo(icc_profile,profile);\n profile=DestroyStringInfo(profile);\n }\n else\n {\n status=SetImageProfile(image,\"icc\",profile,exception);\n profile=DestroyStringInfo(profile);\n if (status == MagickFalse)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",image->filename);\n return(FALSE);\n }\n }\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"Profile: ICC, %.20g bytes\",(double) length);\n return(TRUE);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1641'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadMATImageV4(const ImageInfo *image_info,Image *image,\n ExceptionInfo *exception)\n{\n typedef struct {\n unsigned char Type[4];\n unsigned int nRows;\n unsigned int nCols;\n unsigned int imagf;\n unsigned int nameLen;\n } MAT4_HDR;\n\n long\n ldblk;\n\n EndianType\n endian;\n\n Image\n *rotated_image;\n\n MagickBooleanType\n status;\n\n MAT4_HDR\n HDR;\n\n QuantumInfo\n *quantum_info;\n\n QuantumFormatType\n format_type;\n\n register ssize_t\n i;\n\n ssize_t\n count,\n y;\n\n unsigned char\n *pixels;\n\n unsigned int\n depth;\n\n quantum_info=(QuantumInfo *) NULL;\n (void) SeekBlob(image,0,SEEK_SET);\n status=MagickTrue;\n while (EOFBlob(image) == MagickFalse)\n {\n /*\n Object parser loop.\n */\n ldblk=ReadBlobLSBLong(image);\n if ((ldblk > 9999) || (ldblk < 0))\n break;\n HDR.Type[3]=ldblk % 10; ldblk /= 10; /* T digit */\n HDR.Type[2]=ldblk % 10; ldblk /= 10; /* P digit */\n HDR.Type[1]=ldblk % 10; ldblk /= 10; /* O digit */\n HDR.Type[0]=ldblk; /* M digit */\n if (HDR.Type[3] != 0)\n break; /* Data format */\n if (HDR.Type[2] != 0)\n break; /* Always 0 */\n if (HDR.Type[0] == 0)\n {\n HDR.nRows=ReadBlobLSBLong(image);\n HDR.nCols=ReadBlobLSBLong(image);\n HDR.imagf=ReadBlobLSBLong(image);\n HDR.nameLen=ReadBlobLSBLong(image);\n endian=LSBEndian;\n }\n else\n {\n HDR.nRows=ReadBlobMSBLong(image);\n HDR.nCols=ReadBlobMSBLong(image);\n HDR.imagf=ReadBlobMSBLong(image);\n HDR.nameLen=ReadBlobMSBLong(image);\n endian=MSBEndian;\n }\n if ((HDR.imagf != 0) && (HDR.imagf != 1))\n break;\n if (HDR.nameLen > 0xFFFF)\n return(DestroyImageList(image));\n for (i=0; i < (ssize_t) HDR.nameLen; i++)\n {\n int\n byte;\n\n /*\n Skip matrix name.\n */\n byte=ReadBlobByte(image);\n if (byte == EOF)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n }\n image->columns=(size_t) HDR.nRows;\n image->rows=(size_t) HDR.nCols;\n if ((image->columns == 0) || (image->rows == 0))\n return(DestroyImageList(image));\n if (image_info->ping != MagickFalse)\n {\n Swap(image->columns,image->rows);\n if(HDR.imagf==1) ldblk *= 2;\n SeekBlob(image, HDR.nCols*ldblk, SEEK_CUR);\n if ((image->columns == 0) || (image->rows == 0))\n return(image->previous == (Image *) NULL ? DestroyImageList(image)\n : image);\n goto skip_reading_current;\n }\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n (void) SetImageBackgroundColor(image,exception);\n (void) SetImageColorspace(image,GRAYColorspace,exception);\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n return(DestroyImageList(image));\n switch(HDR.Type[1])\n {\n case 0:\n format_type=FloatingPointQuantumFormat;\n depth=64;\n break;\n case 1:\n format_type=FloatingPointQuantumFormat;\n depth=32;\n break;\n case 2:\n format_type=UnsignedQuantumFormat;\n depth=16;\n break;\n case 3:\n format_type=SignedQuantumFormat;\n depth=16;\n break;\n case 4:\n format_type=UnsignedQuantumFormat;\n depth=8;\n break;\n default:\n format_type=UnsignedQuantumFormat;\n depth=8;\n break;\n }\n image->depth=depth;\n if (HDR.Type[0] != 0)\n SetQuantumEndian(image,quantum_info,MSBEndian);\n status=SetQuantumFormat(image,quantum_info,format_type);\n status=SetQuantumDepth(image,quantum_info,depth);\n status=SetQuantumEndian(image,quantum_info,endian);\n SetQuantumScale(quantum_info,1.0);\n pixels=(unsigned char *) GetQuantumPixels(quantum_info);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;\n\n count=ReadBlob(image,depth/8*image->columns,(char *) pixels);\n if (count == -1)\n break;\n q=QueueAuthenticPixels(image,0,image->rows-y-1,image->columns,1,\n exception);\n if (q == (Quantum *) NULL)\n break;\n (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n GrayQuantum,pixels,exception);\n if ((HDR.Type[1] == 2) || (HDR.Type[1] == 3))\n FixSignedValues(image,q,(int) image->columns);\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n if (HDR.imagf == 1)\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n /*\n Read complex pixels.\n */\n count=ReadBlob(image,depth/8*image->columns,(char *) pixels);\n if (count == -1)\n break;\n if (HDR.Type[1] == 0)\n InsertComplexDoubleRow(image,(double *) pixels,y,0,0,exception);\n else\n InsertComplexFloatRow(image,(float *) pixels,y,0,0,exception);\n }\n if (quantum_info != (QuantumInfo *) NULL)\n quantum_info=DestroyQuantumInfo(quantum_info);\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n rotated_image=RotateImage(image,90.0,exception);\n if (rotated_image != (Image *) NULL)\n {\n rotated_image->page.x=0;\n rotated_image->page.y=0;\n rotated_image->colors = image->colors;\n DestroyBlob(rotated_image);\n rotated_image->blob=ReferenceBlob(image->blob);\n AppendImageToList(&image,rotated_image);\n DeleteImageFromList(&image);\n }\n /*\n Proceed to next image.\n */\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n /*\n Allocate next image structure.\n */\nskip_reading_current:\n AcquireNextImage(image_info,image,exception);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n GetBlobSize(image));\n if (status == MagickFalse)\n break;\n }\n (void) CloseBlob(image);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1554'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int v2_init_io(struct quota_handle *h)\n{\n\tstruct v2_disk_dqinfo ddqinfo;\n\n\th->qh_info.u.v2_mdqi.dqi_qtree.dqi_entry_size =\n\t\tsizeof(struct v2r1_disk_dqblk);\n\th->qh_info.u.v2_mdqi.dqi_qtree.dqi_ops = &v2r1_fmt_ops;\n\n\t/* Read information about quotafile */\n\tif (h->e2fs_read(&h->qh_qf, V2_DQINFOOFF, &ddqinfo,\n\t\t\t sizeof(ddqinfo)) != sizeof(ddqinfo))\n\t\treturn -1;\n\tv2_disk2memdqinfo(&h->qh_info, &ddqinfo);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'libsupport: add checks to prevent buffer overrun bugs in quota code\n\nA maliciously corrupted file systems can trigger buffer overruns in\nthe quota code used by e2fsck. To fix this, add sanity checks to the\nquota header fields as well as to block number references in the quota\ntree.\n\nAddresses: CVE-2019-5094\nAddresses: TALOS-2019-0887\nSigned-off-by: Theodore Ts'o '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: fetch_token(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env)\n{\n int r, num;\n OnigCodePoint c;\n OnigEncoding enc = env->enc;\n OnigSyntaxType* syn = env->syntax;\n UChar* prev;\n UChar* p = *src;\n PFETCH_READY;\n\n start:\n if (PEND) {\n tok->type = TK_EOT;\n return tok->type;\n }\n\n tok->type = TK_STRING;\n tok->base = 0;\n tok->backp = p;\n\n PFETCH(c);\n if (IS_MC_ESC_CODE(c, syn)) {\n if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE;\n\n tok->backp = p;\n PFETCH(c);\n\n tok->u.c = c;\n tok->escaped = 1;\n switch (c) {\n case '*':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_ASTERISK_ZERO_INF)) break;\n tok->type = TK_OP_REPEAT;\n tok->u.repeat.lower = 0;\n tok->u.repeat.upper = REPEAT_INFINITE;\n goto greedy_check;\n break;\n\n case '+':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_PLUS_ONE_INF)) break;\n tok->type = TK_OP_REPEAT;\n tok->u.repeat.lower = 1;\n tok->u.repeat.upper = REPEAT_INFINITE;\n goto greedy_check;\n break;\n\n case '?':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_QMARK_ZERO_ONE)) break;\n tok->type = TK_OP_REPEAT;\n tok->u.repeat.lower = 0;\n tok->u.repeat.upper = 1;\n greedy_check:\n if (!PEND && PPEEK_IS('?') &&\n IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_NON_GREEDY)) {\n PFETCH(c);\n tok->u.repeat.greedy = 0;\n tok->u.repeat.possessive = 0;\n }\n else {\n possessive_check:\n if (!PEND && PPEEK_IS('+') &&\n ((IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_REPEAT) &&\n tok->type != TK_INTERVAL) ||\n (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_INTERVAL) &&\n tok->type == TK_INTERVAL))) {\n PFETCH(c);\n tok->u.repeat.greedy = 1;\n tok->u.repeat.possessive = 1;\n }\n else {\n tok->u.repeat.greedy = 1;\n tok->u.repeat.possessive = 0;\n }\n }\n break;\n\n case '{':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_BRACE_INTERVAL)) break;\n r = fetch_range_quantifier(&p, end, tok, env);\n if (r < 0) return r; /* error */\n if (r == 0) goto greedy_check;\n else if (r == 2) { /* {n} */\n if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY))\n goto possessive_check;\n\n goto greedy_check;\n }\n /* r == 1 : normal char */\n break;\n\n case '|':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_VBAR_ALT)) break;\n tok->type = TK_ALT;\n break;\n\n case '(':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break;\n tok->type = TK_SUBEXP_OPEN;\n break;\n\n case ')':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break;\n tok->type = TK_SUBEXP_CLOSE;\n break;\n\n case 'w':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break;\n tok->type = TK_CHAR_TYPE;\n tok->u.prop.ctype = ONIGENC_CTYPE_WORD;\n tok->u.prop.not = 0;\n break;\n\n case 'W':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break;\n tok->type = TK_CHAR_TYPE;\n tok->u.prop.ctype = ONIGENC_CTYPE_WORD;\n tok->u.prop.not = 1;\n break;\n\n case 'b':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break;\n tok->type = TK_ANCHOR;\n tok->u.anchor = ANCHOR_WORD_BOUNDARY;\n break;\n\n case 'B':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break;\n tok->type = TK_ANCHOR;\n tok->u.anchor = ANCHOR_NO_WORD_BOUNDARY;\n break;\n\n case 'y':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP2_ESC_X_Y_GRAPHEME_CLUSTER)) break;\n tok->type = TK_ANCHOR;\n tok->u.anchor = ANCHOR_EXTENDED_GRAPHEME_CLUSTER_BOUNDARY;\n break;\n\n case 'Y':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP2_ESC_X_Y_GRAPHEME_CLUSTER)) break;\n tok->type = TK_ANCHOR;\n tok->u.anchor = ANCHOR_NO_EXTENDED_GRAPHEME_CLUSTER_BOUNDARY;\n break;\n\n#ifdef USE_WORD_BEGIN_END\n case '<':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break;\n tok->type = TK_ANCHOR;\n tok->u.anchor = ANCHOR_WORD_BEGIN;\n break;\n\n case '>':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break;\n tok->type = TK_ANCHOR;\n tok->u.anchor = ANCHOR_WORD_END;\n break;\n#endif\n\n case 's':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break;\n tok->type = TK_CHAR_TYPE;\n tok->u.prop.ctype = ONIGENC_CTYPE_SPACE;\n tok->u.prop.not = 0;\n break;\n\n case 'S':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break;\n tok->type = TK_CHAR_TYPE;\n tok->u.prop.ctype = ONIGENC_CTYPE_SPACE;\n tok->u.prop.not = 1;\n break;\n\n case 'd':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break;\n tok->type = TK_CHAR_TYPE;\n tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT;\n tok->u.prop.not = 0;\n break;\n\n case 'D':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break;\n tok->type = TK_CHAR_TYPE;\n tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT;\n tok->u.prop.not = 1;\n break;\n\n case 'h':\n if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break;\n tok->type = TK_CHAR_TYPE;\n tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT;\n tok->u.prop.not = 0;\n break;\n\n case 'H':\n if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break;\n tok->type = TK_CHAR_TYPE;\n tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT;\n tok->u.prop.not = 1;\n break;\n\n case 'K':\n if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_K_KEEP)) break;\n tok->type = TK_KEEP;\n break;\n\n case 'R':\n if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_R_GENERAL_NEWLINE)) break;\n tok->type = TK_GENERAL_NEWLINE;\n break;\n\n case 'N':\n if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_N_O_SUPER_DOT)) break;\n tok->type = TK_NO_NEWLINE;\n break;\n\n case 'O':\n if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_N_O_SUPER_DOT)) break;\n tok->type = TK_TRUE_ANYCHAR;\n break;\n\n case 'X':\n if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_X_Y_GRAPHEME_CLUSTER)) break;\n tok->type = TK_EXTENDED_GRAPHEME_CLUSTER;\n break;\n\n case 'A':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break;\n begin_buf:\n tok->type = TK_ANCHOR;\n tok->u.subtype = ANCHOR_BEGIN_BUF;\n break;\n\n case 'Z':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break;\n tok->type = TK_ANCHOR;\n tok->u.subtype = ANCHOR_SEMI_END_BUF;\n break;\n\n case 'z':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break;\n end_buf:\n tok->type = TK_ANCHOR;\n tok->u.subtype = ANCHOR_END_BUF;\n break;\n\n case 'G':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_CAPITAL_G_BEGIN_ANCHOR)) break;\n tok->type = TK_ANCHOR;\n tok->u.subtype = ANCHOR_BEGIN_POSITION;\n break;\n\n case '`':\n if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break;\n goto begin_buf;\n break;\n\n case '\\'':\n if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break;\n goto end_buf;\n break;\n\n case 'o':\n if (PEND) break;\n\n prev = p;\n if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_O_BRACE_OCTAL)) {\n PINC;\n num = scan_unsigned_octal_number(&p, end, 11, enc);\n if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE;\n if (!PEND) {\n if (IS_CODE_DIGIT_ASCII(enc, PPEEK))\n return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE;\n }\n\n if ((p > prev + enclen(enc, prev)) && !PEND && PPEEK_IS('}')) {\n PINC;\n tok->type = TK_CODE_POINT;\n tok->u.code = (OnigCodePoint )num;\n }\n else {\n /* can't read nothing or invalid format */\n p = prev;\n }\n }\n break;\n\n case 'x':\n if (PEND) break;\n\n prev = p;\n if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) {\n PINC;\n num = scan_unsigned_hexadecimal_number(&p, end, 0, 8, enc);\n if (num < 0) {\n if (num == ONIGERR_TOO_BIG_NUMBER)\n return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE;\n else\n return num;\n }\n if (!PEND) {\n if (IS_CODE_XDIGIT_ASCII(enc, PPEEK))\n return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE;\n }\n\n if ((p > prev + enclen(enc, prev)) && !PEND && PPEEK_IS('}')) {\n PINC;\n tok->type = TK_CODE_POINT;\n tok->u.code = (OnigCodePoint )num;\n }\n else {\n /* can't read nothing or invalid format */\n p = prev;\n }\n }\n else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) {\n num = scan_unsigned_hexadecimal_number(&p, end, 0, 2, enc);\n if (num < 0) return num;\n if (p == prev) { /* can't read nothing. */\n num = 0; /* but, it's not error */\n }\n tok->type = TK_RAW_BYTE;\n tok->base = 16;\n tok->u.c = num;\n }\n break;\n\n case 'u':\n if (PEND) break;\n\n prev = p;\n if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) {\n num = scan_unsigned_hexadecimal_number(&p, end, 4, 4, enc);\n if (num < 0) return num;\n if (p == prev) { /* can't read nothing. */\n num = 0; /* but, it's not error */\n }\n tok->type = TK_CODE_POINT;\n tok->base = 16;\n tok->u.code = (OnigCodePoint )num;\n }\n break;\n\n case '1': case '2': case '3': case '4':\n case '5': case '6': case '7': case '8': case '9':\n PUNFETCH;\n prev = p;\n num = onig_scan_unsigned_number(&p, end, enc);\n if (num < 0 || num > ONIG_MAX_BACKREF_NUM) {\n goto skip_backref;\n }\n\n if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_DECIMAL_BACKREF) && \n (num <= env->num_mem || num <= 9)) { /* This spec. from GNU regex */\n if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) {\n if (num > env->num_mem || IS_NULL(SCANENV_MEMENV(env)[num].node))\n return ONIGERR_INVALID_BACKREF;\n }\n\n tok->type = TK_BACKREF;\n tok->u.backref.num = 1;\n tok->u.backref.ref1 = num;\n tok->u.backref.by_name = 0;\n#ifdef USE_BACKREF_WITH_LEVEL\n tok->u.backref.exist_level = 0;\n#endif\n break;\n }\n\n skip_backref:\n if (c == '8' || c == '9') {\n /* normal char */\n p = prev; PINC;\n break;\n }\n\n p = prev;\n /* fall through */\n case '0':\n if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) {\n prev = p;\n num = scan_unsigned_octal_number(&p, end, (c == '0' ? 2:3), enc);\n if (num < 0 || num >= 256) return ONIGERR_TOO_BIG_NUMBER;\n if (p == prev) { /* can't read nothing. */\n num = 0; /* but, it's not error */\n }\n tok->type = TK_RAW_BYTE;\n tok->base = 8;\n tok->u.c = num;\n }\n else if (c != '0') {\n PINC;\n }\n break;\n\n case 'k':\n if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_K_NAMED_BACKREF)) {\n PFETCH(c);\n if (c == '<' || c == '\\'') {\n UChar* name_end;\n int* backs;\n int back_num;\n enum REF_NUM num_type;\n\n prev = p;\n\n#ifdef USE_BACKREF_WITH_LEVEL\n name_end = NULL_UCHARP; /* no need. escape gcc warning. */\n r = fetch_name_with_level((OnigCodePoint )c, &p, end, &name_end,\n env, &back_num, &tok->u.backref.level, &num_type);\n if (r == 1) tok->u.backref.exist_level = 1;\n else tok->u.backref.exist_level = 0;\n#else\n r = fetch_name(c, &p, end, &name_end, env, &back_num, &num_type, 1);\n#endif\n if (r < 0) return r;\n\n if (num_type != IS_NOT_NUM) {\n if (num_type == IS_REL_NUM) {\n back_num = backref_rel_to_abs(back_num, env);\n }\n if (back_num <= 0)\n return ONIGERR_INVALID_BACKREF;\n\n if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) {\n if (back_num > env->num_mem ||\n IS_NULL(SCANENV_MEMENV(env)[back_num].node))\n return ONIGERR_INVALID_BACKREF;\n }\n tok->type = TK_BACKREF;\n tok->u.backref.by_name = 0;\n tok->u.backref.num = 1;\n tok->u.backref.ref1 = back_num;\n }\n else {\n num = onig_name_to_group_numbers(env->reg, prev, name_end, &backs);\n if (num <= 0) {\n onig_scan_env_set_error_string(env,\n ONIGERR_UNDEFINED_NAME_REFERENCE, prev, name_end);\n return ONIGERR_UNDEFINED_NAME_REFERENCE;\n }\n if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) {\n int i;\n for (i = 0; i < num; i++) {\n if (backs[i] > env->num_mem ||\n IS_NULL(SCANENV_MEMENV(env)[backs[i]].node))\n return ONIGERR_INVALID_BACKREF;\n }\n }\n\n tok->type = TK_BACKREF;\n tok->u.backref.by_name = 1;\n if (num == 1) {\n tok->u.backref.num = 1;\n tok->u.backref.ref1 = backs[0];\n }\n else {\n tok->u.backref.num = num;\n tok->u.backref.refs = backs;\n }\n }\n }\n else\n PUNFETCH;\n }\n break;\n\n#ifdef USE_CALL\n case 'g':\n if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_G_SUBEXP_CALL)) {\n PFETCH(c);\n if (c == '<' || c == '\\'') {\n int gnum;\n UChar* name_end;\n enum REF_NUM num_type;\n\n prev = p;\n r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env,\n &gnum, &num_type, 1);\n if (r < 0) return r;\n\n if (num_type != IS_NOT_NUM) {\n if (num_type == IS_REL_NUM) {\n gnum = backref_rel_to_abs(gnum, env);\n if (gnum < 0)\n return ONIGERR_UNDEFINED_GROUP_REFERENCE;\n }\n tok->u.call.by_number = 1;\n tok->u.call.gnum = gnum;\n }\n else {\n tok->u.call.by_number = 0;\n tok->u.call.gnum = 0;\n }\n\n tok->type = TK_CALL;\n tok->u.call.name = prev;\n tok->u.call.name_end = name_end;\n }\n else\n PUNFETCH;\n }\n break;\n#endif\n\n case 'Q':\n if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_Q_QUOTE)) {\n tok->type = TK_QUOTE_OPEN;\n }\n break;\n\n case 'p':\n case 'P':\n if (!PEND && PPEEK_IS('{') &&\n IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) {\n PINC;\n tok->type = TK_CHAR_PROPERTY;\n tok->u.prop.not = (c == 'P' ? 1 : 0);\n\n if (!PEND &&\n IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) {\n PFETCH(c);\n if (c == '^') {\n tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0);\n }\n else\n PUNFETCH;\n }\n }\n break;\n\n default:\n {\n OnigCodePoint c2;\n\n PUNFETCH;\n num = fetch_escaped_value(&p, end, env, &c2);\n if (num < 0) return num;\n /* set_raw: */\n if (tok->u.c != c2) {\n tok->type = TK_CODE_POINT;\n tok->u.code = c2;\n }\n else { /* string */\n p = tok->backp + enclen(enc, tok->backp);\n }\n }\n break;\n }\n }\n else {\n tok->u.c = c;\n tok->escaped = 0;\n\n#ifdef USE_VARIABLE_META_CHARS\n if ((c != ONIG_INEFFECTIVE_META_CHAR) &&\n IS_SYNTAX_OP(syn, ONIG_SYN_OP_VARIABLE_META_CHARACTERS)) {\n if (c == MC_ANYCHAR(syn))\n goto any_char;\n else if (c == MC_ANYTIME(syn))\n goto anytime;\n else if (c == MC_ZERO_OR_ONE_TIME(syn))\n goto zero_or_one_time;\n else if (c == MC_ONE_OR_MORE_TIME(syn))\n goto one_or_more_time;\n else if (c == MC_ANYCHAR_ANYTIME(syn)) {\n tok->type = TK_ANYCHAR_ANYTIME;\n goto out;\n }\n }\n#endif\n\n switch (c) {\n case '.':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_DOT_ANYCHAR)) break;\n#ifdef USE_VARIABLE_META_CHARS\n any_char:\n#endif\n tok->type = TK_ANYCHAR;\n break;\n\n case '*':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ASTERISK_ZERO_INF)) break;\n#ifdef USE_VARIABLE_META_CHARS\n anytime:\n#endif\n tok->type = TK_OP_REPEAT;\n tok->u.repeat.lower = 0;\n tok->u.repeat.upper = REPEAT_INFINITE;\n goto greedy_check;\n break;\n\n case '+':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_PLUS_ONE_INF)) break;\n#ifdef USE_VARIABLE_META_CHARS\n one_or_more_time:\n#endif\n tok->type = TK_OP_REPEAT;\n tok->u.repeat.lower = 1;\n tok->u.repeat.upper = REPEAT_INFINITE;\n goto greedy_check;\n break;\n\n case '?':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_ZERO_ONE)) break;\n#ifdef USE_VARIABLE_META_CHARS\n zero_or_one_time:\n#endif\n tok->type = TK_OP_REPEAT;\n tok->u.repeat.lower = 0;\n tok->u.repeat.upper = 1;\n goto greedy_check;\n break;\n\n case '{':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACE_INTERVAL)) break;\n r = fetch_range_quantifier(&p, end, tok, env);\n if (r < 0) return r; /* error */\n if (r == 0) goto greedy_check;\n else if (r == 2) { /* {n} */\n if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY))\n goto possessive_check;\n\n goto greedy_check;\n }\n /* r == 1 : normal char */\n break;\n\n case '|':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_VBAR_ALT)) break;\n tok->type = TK_ALT;\n break;\n\n case '(':\n if (!PEND && PPEEK_IS('?') &&\n IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_QMARK_GROUP_EFFECT)) {\n PINC;\n if (! PEND) {\n c = PPEEK;\n if (c == '#') {\n PFETCH(c);\n while (1) {\n if (PEND) return ONIGERR_END_PATTERN_IN_GROUP;\n PFETCH(c);\n if (c == MC_ESC(syn)) {\n if (! PEND) PFETCH(c);\n }\n else {\n if (c == ')') break;\n }\n }\n goto start;\n }\n else if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_QMARK_PERL_SUBEXP_CALL)) {\n int gnum;\n UChar* name;\n UChar* name_end;\n enum REF_NUM num_type;\n\n switch (c) {\n case '&':\n {\n PINC;\n name = p;\n r = fetch_name((OnigCodePoint )'(', &p, end, &name_end, env, &gnum,\n &num_type, 0);\n if (r < 0) return r;\n\n tok->type = TK_CALL;\n tok->u.call.by_number = 0;\n tok->u.call.gnum = 0;\n tok->u.call.name = name;\n tok->u.call.name_end = name_end;\n }\n break;\n\n case 'R':\n tok->type = TK_CALL;\n tok->u.call.by_number = 1;\n tok->u.call.gnum = 0;\n tok->u.call.name = p;\n PINC;\n if (! PPEEK_IS(')')) return ONIGERR_INVALID_GROUP_NAME;\n tok->u.call.name_end = p;\n break;\n\n case '-':\n case '+':\n goto lparen_qmark_num;\n break;\n default:\n if (! ONIGENC_IS_CODE_DIGIT(enc, c)) goto lparen_qmark_end;\n\n lparen_qmark_num:\n {\n name = p;\n r = fetch_name((OnigCodePoint )'(', &p, end, &name_end, env,\n &gnum, &num_type, 1);\n if (r < 0) return r;\n\n if (num_type == IS_NOT_NUM) {\n return ONIGERR_INVALID_GROUP_NAME;\n }\n else {\n if (num_type == IS_REL_NUM) {\n gnum = backref_rel_to_abs(gnum, env);\n if (gnum < 0)\n return ONIGERR_UNDEFINED_GROUP_REFERENCE;\n }\n tok->u.call.by_number = 1;\n tok->u.call.gnum = gnum;\n }\n\n tok->type = TK_CALL;\n tok->u.call.name = name;\n tok->u.call.name_end = name_end;\n }\n break;\n }\n }\n }\n lparen_qmark_end:\n PUNFETCH;\n }\n\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break;\n tok->type = TK_SUBEXP_OPEN;\n break;\n\n case ')':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break;\n tok->type = TK_SUBEXP_CLOSE;\n break;\n\n case '^':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break;\n tok->type = TK_ANCHOR;\n tok->u.subtype = (IS_SINGLELINE(env->options)\n ? ANCHOR_BEGIN_BUF : ANCHOR_BEGIN_LINE);\n break;\n\n case '$':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break;\n tok->type = TK_ANCHOR;\n tok->u.subtype = (IS_SINGLELINE(env->options)\n ? ANCHOR_SEMI_END_BUF : ANCHOR_END_LINE);\n break;\n\n case '[':\n if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACKET_CC)) break;\n tok->type = TK_CC_OPEN;\n break;\n\n case ']':\n if (*src > env->pattern) /* /].../ is allowed. */\n CLOSE_BRACKET_WITHOUT_ESC_WARN(env, (UChar* )\"]\");\n break;\n\n case '#':\n if (IS_EXTEND(env->options)) {\n while (!PEND) {\n PFETCH(c);\n if (ONIGENC_IS_CODE_NEWLINE(enc, c))\n break;\n }\n goto start;\n break;\n }\n break;\n\n case ' ': case '\\t': case '\\n': case '\\r': case '\\f':\n if (IS_EXTEND(env->options))\n goto start;\n break;\n\n default:\n /* string */\n break;\n }\n }\n\n#ifdef USE_VARIABLE_META_CHARS\n out:\n#endif\n *src = p;\n return tok->type;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'fix #87: Read unknown address in onig_error_code_to_str()'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TEST_F(ConnectionHandlerTest, ListenerFilterDisabledTimeout) {\n InSequence s;\n\n TestListener* test_listener =\n addListener(1, true, false, \"test_listener\", Network::Address::SocketType::Stream,\n std::chrono::milliseconds());\n Network::MockListener* listener = new Network::MockListener();\n Network::ListenerCallbacks* listener_callbacks;\n EXPECT_CALL(dispatcher_, createListener_(_, _, _))\n .WillOnce(\n Invoke([&](Network::Socket&, Network::ListenerCallbacks& cb, bool) -> Network::Listener* {\n listener_callbacks = &cb;\n return listener;\n }));\n EXPECT_CALL(test_listener->socket_, localAddress());\n handler_->addListener(*test_listener);\n\n Network::MockListenerFilter* test_filter = new Network::MockListenerFilter();\n EXPECT_CALL(factory_, createListenerFilterChain(_))\n .WillRepeatedly(Invoke([&](Network::ListenerFilterManager& manager) -> bool {\n manager.addAcceptFilter(Network::ListenerFilterPtr{test_filter});\n return true;\n }));\n EXPECT_CALL(*test_filter, onAccept(_))\n .WillOnce(Invoke([&](Network::ListenerFilterCallbacks&) -> Network::FilterStatus {\n return Network::FilterStatus::StopIteration;\n }));\n EXPECT_CALL(dispatcher_, createTimer_(_)).Times(0);\n Network::MockConnectionSocket* accepted_socket = new NiceMock();\n listener_callbacks->onAccept(Network::ConnectionSocketPtr{accepted_socket});\n\n EXPECT_CALL(*listener, onDestroy());\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': 'listener: clean up accept filter before creating connection (#8922)\n\nSigned-off-by: Yuchen Dai '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static char *__filterShell(const char *arg) {\n\tr_return_val_if_fail (arg, NULL);\n\tchar *a = malloc (strlen (arg) + 1);\n\tif (!a) {\n\t\treturn NULL;\n\t}\n\tchar *b = a;\n\twhile (*arg) {\n\t\tswitch (*arg) {\n\t\tcase '@':\n\t\tcase '`':\n\t\tcase '|':\n\t\tcase ';':\n\t\tcase '\\n':\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t*b++ = *arg;\n\t\t\tbreak;\n\t\t}\n\t\targ++;\n\t}\n\t*b = 0;\n\treturn a;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-78'], 'message': 'More fixes for the CVE-2019-14745'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: DLLEXPORT int tjCompress2(tjhandle handle, const unsigned char *srcBuf,\n int width, int pitch, int height, int pixelFormat,\n unsigned char **jpegBuf, unsigned long *jpegSize,\n int jpegSubsamp, int jpegQual, int flags)\n{\n int i, retval = 0, alloc = 1;\n JSAMPROW *row_pointer = NULL;\n\n GET_CINSTANCE(handle)\n this->jerr.stopOnWarning = (flags & TJFLAG_STOPONWARNING) ? TRUE : FALSE;\n if ((this->init & COMPRESS) == 0)\n THROW(\"tjCompress2(): Instance has not been initialized for compression\");\n\n if (srcBuf == NULL || width <= 0 || pitch < 0 || height <= 0 ||\n pixelFormat < 0 || pixelFormat >= TJ_NUMPF || jpegBuf == NULL ||\n jpegSize == NULL || jpegSubsamp < 0 || jpegSubsamp >= NUMSUBOPT ||\n jpegQual < 0 || jpegQual > 100)\n THROW(\"tjCompress2(): Invalid argument\");\n\n if (pitch == 0) pitch = width * tjPixelSize[pixelFormat];\n\n if ((row_pointer = (JSAMPROW *)malloc(sizeof(JSAMPROW) * height)) == NULL)\n THROW(\"tjCompress2(): Memory allocation failure\");\n\n if (setjmp(this->jerr.setjmp_buffer)) {\n /* If we get here, the JPEG code has signaled an error. */\n retval = -1; goto bailout;\n }\n\n cinfo->image_width = width;\n cinfo->image_height = height;\n\n#ifndef NO_PUTENV\n if (flags & TJFLAG_FORCEMMX) putenv(\"JSIMD_FORCEMMX=1\");\n else if (flags & TJFLAG_FORCESSE) putenv(\"JSIMD_FORCESSE=1\");\n else if (flags & TJFLAG_FORCESSE2) putenv(\"JSIMD_FORCESSE2=1\");\n#endif\n\n if (flags & TJFLAG_NOREALLOC) {\n alloc = 0; *jpegSize = tjBufSize(width, height, jpegSubsamp);\n }\n jpeg_mem_dest_tj(cinfo, jpegBuf, jpegSize, alloc);\n if (setCompDefaults(cinfo, pixelFormat, jpegSubsamp, jpegQual, flags) == -1)\n return -1;\n\n jpeg_start_compress(cinfo, TRUE);\n for (i = 0; i < height; i++) {\n if (flags & TJFLAG_BOTTOMUP)\n row_pointer[i] = (JSAMPROW)&srcBuf[(height - i - 1) * pitch];\n else\n row_pointer[i] = (JSAMPROW)&srcBuf[i * pitch];\n }\n while (cinfo->next_scanline < cinfo->image_height)\n jpeg_write_scanlines(cinfo, &row_pointer[cinfo->next_scanline],\n cinfo->image_height - cinfo->next_scanline);\n jpeg_finish_compress(cinfo);\n\nbailout:\n if (cinfo->global_state > CSTATE_START) jpeg_abort_compress(cinfo);\n if (row_pointer) free(row_pointer);\n if (this->jerr.warning) retval = -1;\n this->jerr.stopOnWarning = FALSE;\n return retval;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'TurboJPEG: Properly handle gigapixel images\n\nPrevent several integer overflow issues and subsequent segfaults that\noccurred when attempting to compress or decompress gigapixel images with\nthe TurboJPEG API:\n\n- Modify tjBufSize(), tjBufSizeYUV2(), and tjPlaneSizeYUV() to avoid\n integer overflow when computing the return values and to return an\n error if such an overflow is unavoidable.\n- Modify tjunittest to validate the above.\n- Modify tjCompress2(), tjEncodeYUVPlanes(), tjDecompress2(), and\n tjDecodeYUVPlanes() to avoid integer overflow when computing the row\n pointers in the 64-bit TurboJPEG C API.\n- Modify TJBench (both C and Java versions) to avoid overflowing the\n size argument to malloc()/new and to fail gracefully if such an\n overflow is unavoidable.\n\nIn general, this allows gigapixel images to be accommodated by the\n64-bit TurboJPEG C API when using automatic JPEG buffer (re)allocation.\nSuch images cannot currently be accommodated without automatic JPEG\nbuffer (re)allocation, due to the fact that tjAlloc() accepts a 32-bit\ninteger argument (oops.) Such images cannot be accommodated in the\nTurboJPEG Java API due to the fact that Java always uses a signed 32-bit\ninteger as an array index.\n\nFixes #361'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int modbus_reply(modbus_t *ctx, const uint8_t *req,\n int req_length, modbus_mapping_t *mb_mapping)\n{\n int offset;\n int slave;\n int function;\n uint16_t address;\n uint8_t rsp[MAX_MESSAGE_LENGTH];\n int rsp_length = 0;\n sft_t sft;\n\n if (ctx == NULL) {\n errno = EINVAL;\n return -1;\n }\n\n offset = ctx->backend->header_length;\n slave = req[offset - 1];\n function = req[offset];\n address = (req[offset + 1] << 8) + req[offset + 2];\n\n sft.slave = slave;\n sft.function = function;\n sft.t_id = ctx->backend->prepare_response_tid(req, &req_length);\n\n /* Data are flushed on illegal number of values errors. */\n switch (function) {\n case MODBUS_FC_READ_COILS:\n case MODBUS_FC_READ_DISCRETE_INPUTS: {\n unsigned int is_input = (function == MODBUS_FC_READ_DISCRETE_INPUTS);\n int start_bits = is_input ? mb_mapping->start_input_bits : mb_mapping->start_bits;\n int nb_bits = is_input ? mb_mapping->nb_input_bits : mb_mapping->nb_bits;\n uint8_t *tab_bits = is_input ? mb_mapping->tab_input_bits : mb_mapping->tab_bits;\n const char * const name = is_input ? \"read_input_bits\" : \"read_bits\";\n int nb = (req[offset + 3] << 8) + req[offset + 4];\n /* The mapping can be shifted to reduce memory consumption and it\n doesn't always start at address zero. */\n int mapping_address = address - start_bits;\n\n if (nb < 1 || MODBUS_MAX_READ_BITS < nb) {\n rsp_length = response_exception(\n ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,\n \"Illegal nb of values %d in %s (max %d)\\n\",\n nb, name, MODBUS_MAX_READ_BITS);\n } else if (mapping_address < 0 || (mapping_address + nb) > nb_bits) {\n rsp_length = response_exception(\n ctx, &sft,\n MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,\n \"Illegal data address 0x%0X in %s\\n\",\n mapping_address < 0 ? address : address + nb, name);\n } else {\n rsp_length = ctx->backend->build_response_basis(&sft, rsp);\n rsp[rsp_length++] = (nb / 8) + ((nb % 8) ? 1 : 0);\n rsp_length = response_io_status(tab_bits, mapping_address, nb,\n rsp, rsp_length);\n }\n }\n break;\n case MODBUS_FC_READ_HOLDING_REGISTERS:\n case MODBUS_FC_READ_INPUT_REGISTERS: {\n unsigned int is_input = (function == MODBUS_FC_READ_INPUT_REGISTERS);\n int start_registers = is_input ? mb_mapping->start_input_registers : mb_mapping->start_registers;\n int nb_registers = is_input ? mb_mapping->nb_input_registers : mb_mapping->nb_registers;\n uint16_t *tab_registers = is_input ? mb_mapping->tab_input_registers : mb_mapping->tab_registers;\n const char * const name = is_input ? \"read_input_registers\" : \"read_registers\";\n int nb = (req[offset + 3] << 8) + req[offset + 4];\n /* The mapping can be shifted to reduce memory consumption and it\n doesn't always start at address zero. */\n int mapping_address = address - start_registers;\n\n if (nb < 1 || MODBUS_MAX_READ_REGISTERS < nb) {\n rsp_length = response_exception(\n ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,\n \"Illegal nb of values %d in %s (max %d)\\n\",\n nb, name, MODBUS_MAX_READ_REGISTERS);\n } else if (mapping_address < 0 || (mapping_address + nb) > nb_registers) {\n rsp_length = response_exception(\n ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,\n \"Illegal data address 0x%0X in %s\\n\",\n mapping_address < 0 ? address : address + nb, name);\n } else {\n int i;\n\n rsp_length = ctx->backend->build_response_basis(&sft, rsp);\n rsp[rsp_length++] = nb << 1;\n for (i = mapping_address; i < mapping_address + nb; i++) {\n rsp[rsp_length++] = tab_registers[i] >> 8;\n rsp[rsp_length++] = tab_registers[i] & 0xFF;\n }\n }\n }\n break;\n case MODBUS_FC_WRITE_SINGLE_COIL: {\n int mapping_address = address - mb_mapping->start_bits;\n\n if (mapping_address < 0 || mapping_address >= mb_mapping->nb_bits) {\n rsp_length = response_exception(\n ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,\n \"Illegal data address 0x%0X in write_bit\\n\",\n address);\n } else {\n int data = (req[offset + 3] << 8) + req[offset + 4];\n\n if (data == 0xFF00 || data == 0x0) {\n mb_mapping->tab_bits[mapping_address] = data ? ON : OFF;\n memcpy(rsp, req, req_length);\n rsp_length = req_length;\n } else {\n rsp_length = response_exception(\n ctx, &sft,\n MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, FALSE,\n \"Illegal data value 0x%0X in write_bit request at address %0X\\n\",\n data, address);\n }\n }\n }\n break;\n case MODBUS_FC_WRITE_SINGLE_REGISTER: {\n int mapping_address = address - mb_mapping->start_registers;\n\n if (mapping_address < 0 || mapping_address >= mb_mapping->nb_registers) {\n rsp_length = response_exception(\n ctx, &sft,\n MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,\n \"Illegal data address 0x%0X in write_register\\n\",\n address);\n } else {\n int data = (req[offset + 3] << 8) + req[offset + 4];\n\n mb_mapping->tab_registers[mapping_address] = data;\n memcpy(rsp, req, req_length);\n rsp_length = req_length;\n }\n }\n break;\n case MODBUS_FC_WRITE_MULTIPLE_COILS: {\n int nb = (req[offset + 3] << 8) + req[offset + 4];\n int mapping_address = address - mb_mapping->start_bits;\n\n if (nb < 1 || MODBUS_MAX_WRITE_BITS < nb) {\n /* May be the indication has been truncated on reading because of\n * invalid address (eg. nb is 0 but the request contains values to\n * write) so it's necessary to flush. */\n rsp_length = response_exception(\n ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,\n \"Illegal number of values %d in write_bits (max %d)\\n\",\n nb, MODBUS_MAX_WRITE_BITS);\n } else if (mapping_address < 0 ||\n (mapping_address + nb) > mb_mapping->nb_bits) {\n rsp_length = response_exception(\n ctx, &sft,\n MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,\n \"Illegal data address 0x%0X in write_bits\\n\",\n mapping_address < 0 ? address : address + nb);\n } else {\n /* 6 = byte count */\n modbus_set_bits_from_bytes(mb_mapping->tab_bits, mapping_address, nb,\n &req[offset + 6]);\n\n rsp_length = ctx->backend->build_response_basis(&sft, rsp);\n /* 4 to copy the bit address (2) and the quantity of bits */\n memcpy(rsp + rsp_length, req + rsp_length, 4);\n rsp_length += 4;\n }\n }\n break;\n case MODBUS_FC_WRITE_MULTIPLE_REGISTERS: {\n int nb = (req[offset + 3] << 8) + req[offset + 4];\n int mapping_address = address - mb_mapping->start_registers;\n\n if (nb < 1 || MODBUS_MAX_WRITE_REGISTERS < nb) {\n rsp_length = response_exception(\n ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,\n \"Illegal number of values %d in write_registers (max %d)\\n\",\n nb, MODBUS_MAX_WRITE_REGISTERS);\n } else if (mapping_address < 0 ||\n (mapping_address + nb) > mb_mapping->nb_registers) {\n rsp_length = response_exception(\n ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,\n \"Illegal data address 0x%0X in write_registers\\n\",\n mapping_address < 0 ? address : address + nb);\n } else {\n int i, j;\n for (i = mapping_address, j = 6; i < mapping_address + nb; i++, j += 2) {\n /* 6 and 7 = first value */\n mb_mapping->tab_registers[i] =\n (req[offset + j] << 8) + req[offset + j + 1];\n }\n\n rsp_length = ctx->backend->build_response_basis(&sft, rsp);\n /* 4 to copy the address (2) and the no. of registers */\n memcpy(rsp + rsp_length, req + rsp_length, 4);\n rsp_length += 4;\n }\n }\n break;\n case MODBUS_FC_REPORT_SLAVE_ID: {\n int str_len;\n int byte_count_pos;\n\n rsp_length = ctx->backend->build_response_basis(&sft, rsp);\n /* Skip byte count for now */\n byte_count_pos = rsp_length++;\n rsp[rsp_length++] = _REPORT_SLAVE_ID;\n /* Run indicator status to ON */\n rsp[rsp_length++] = 0xFF;\n /* LMB + length of LIBMODBUS_VERSION_STRING */\n str_len = 3 + strlen(LIBMODBUS_VERSION_STRING);\n memcpy(rsp + rsp_length, \"LMB\" LIBMODBUS_VERSION_STRING, str_len);\n rsp_length += str_len;\n rsp[byte_count_pos] = rsp_length - byte_count_pos - 1;\n }\n break;\n case MODBUS_FC_READ_EXCEPTION_STATUS:\n if (ctx->debug) {\n fprintf(stderr, \"FIXME Not implemented\\n\");\n }\n errno = ENOPROTOOPT;\n return -1;\n break;\n case MODBUS_FC_MASK_WRITE_REGISTER: {\n int mapping_address = address - mb_mapping->start_registers;\n\n if (mapping_address < 0 || mapping_address >= mb_mapping->nb_registers) {\n rsp_length = response_exception(\n ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,\n \"Illegal data address 0x%0X in write_register\\n\",\n address);\n } else {\n uint16_t data = mb_mapping->tab_registers[mapping_address];\n uint16_t and = (req[offset + 3] << 8) + req[offset + 4];\n uint16_t or = (req[offset + 5] << 8) + req[offset + 6];\n\n data = (data & and) | (or & (~and));\n mb_mapping->tab_registers[mapping_address] = data;\n memcpy(rsp, req, req_length);\n rsp_length = req_length;\n }\n }\n break;\n case MODBUS_FC_WRITE_AND_READ_REGISTERS: {\n int nb = (req[offset + 3] << 8) + req[offset + 4];\n uint16_t address_write = (req[offset + 5] << 8) + req[offset + 6];\n int nb_write = (req[offset + 7] << 8) + req[offset + 8];\n int nb_write_bytes = req[offset + 9];\n int mapping_address = address - mb_mapping->start_registers;\n int mapping_address_write = address_write - mb_mapping->start_registers;\n\n if (nb_write < 1 || MODBUS_MAX_WR_WRITE_REGISTERS < nb_write ||\n nb < 1 || MODBUS_MAX_WR_READ_REGISTERS < nb ||\n nb_write_bytes != nb_write * 2) {\n rsp_length = response_exception(\n ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE,\n \"Illegal nb of values (W%d, R%d) in write_and_read_registers (max W%d, R%d)\\n\",\n nb_write, nb, MODBUS_MAX_WR_WRITE_REGISTERS, MODBUS_MAX_WR_READ_REGISTERS);\n } else if (mapping_address < 0 ||\n (mapping_address + nb) > mb_mapping->nb_registers ||\n mapping_address < 0 ||\n (mapping_address_write + nb_write) > mb_mapping->nb_registers) {\n rsp_length = response_exception(\n ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE,\n \"Illegal data read address 0x%0X or write address 0x%0X write_and_read_registers\\n\",\n mapping_address < 0 ? address : address + nb,\n mapping_address_write < 0 ? address_write : address_write + nb_write);\n } else {\n int i, j;\n rsp_length = ctx->backend->build_response_basis(&sft, rsp);\n rsp[rsp_length++] = nb << 1;\n\n /* Write first.\n 10 and 11 are the offset of the first values to write */\n for (i = mapping_address_write, j = 10;\n i < mapping_address_write + nb_write; i++, j += 2) {\n mb_mapping->tab_registers[i] =\n (req[offset + j] << 8) + req[offset + j + 1];\n }\n\n /* and read the data for the response */\n for (i = mapping_address; i < mapping_address + nb; i++) {\n rsp[rsp_length++] = mb_mapping->tab_registers[i] >> 8;\n rsp[rsp_length++] = mb_mapping->tab_registers[i] & 0xFF;\n }\n }\n }\n break;\n\n default:\n rsp_length = response_exception(\n ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_FUNCTION, rsp, TRUE,\n \"Unknown Modbus function code: 0x%0X\\n\", function);\n break;\n }\n\n /* Suppress any responses when the request was a broadcast */\n return (ctx->backend->backend_type == _MODBUS_BACKEND_TYPE_RTU &&\n slave == MODBUS_BROADCAST_ADDRESS) ? 0 : send_msg(ctx, rsp, rsp_length);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix VD-1301 and VD-1302 vulnerabilities\n\nThis patch was contributed by Maor Vermucht and Or Peles from\nVDOO Connected Trust.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: psutil_net_io_counters(PyObject *self, PyObject *args) {\n char *buf = NULL, *lim, *next;\n struct if_msghdr *ifm;\n int mib[6];\n size_t len;\n PyObject *py_retdict = PyDict_New();\n PyObject *py_ifc_info = NULL;\n if (py_retdict == NULL)\n return NULL;\n\n mib[0] = CTL_NET; // networking subsystem\n mib[1] = PF_ROUTE; // type of information\n mib[2] = 0; // protocol (IPPROTO_xxx)\n mib[3] = 0; // address family\n mib[4] = NET_RT_IFLIST; // operation\n mib[5] = 0;\n\n if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {\n PyErr_SetFromErrno(PyExc_OSError);\n goto error;\n }\n\n buf = malloc(len);\n if (buf == NULL) {\n PyErr_NoMemory();\n goto error;\n }\n\n if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {\n PyErr_SetFromErrno(PyExc_OSError);\n goto error;\n }\n\n lim = buf + len;\n\n for (next = buf; next < lim; ) {\n py_ifc_info = NULL;\n ifm = (struct if_msghdr *)next;\n next += ifm->ifm_msglen;\n\n if (ifm->ifm_type == RTM_IFINFO) {\n struct if_msghdr *if2m = (struct if_msghdr *)ifm;\n struct sockaddr_dl *sdl = (struct sockaddr_dl *)(if2m + 1);\n char ifc_name[32];\n\n strncpy(ifc_name, sdl->sdl_data, sdl->sdl_nlen);\n ifc_name[sdl->sdl_nlen] = 0;\n // XXX: ignore usbus interfaces:\n // http://lists.freebsd.org/pipermail/freebsd-current/\n // 2011-October/028752.html\n // 'ifconfig -a' doesn't show them, nor do we.\n if (strncmp(ifc_name, \"usbus\", 5) == 0)\n continue;\n\n py_ifc_info = Py_BuildValue(\"(kkkkkkki)\",\n if2m->ifm_data.ifi_obytes,\n if2m->ifm_data.ifi_ibytes,\n if2m->ifm_data.ifi_opackets,\n if2m->ifm_data.ifi_ipackets,\n if2m->ifm_data.ifi_ierrors,\n if2m->ifm_data.ifi_oerrors,\n if2m->ifm_data.ifi_iqdrops,\n#ifdef _IFI_OQDROPS\n if2m->ifm_data.ifi_oqdrops\n#else\n 0\n#endif\n );\n if (!py_ifc_info)\n goto error;\n if (PyDict_SetItemString(py_retdict, ifc_name, py_ifc_info))\n goto error;\n Py_DECREF(py_ifc_info);\n }\n else {\n continue;\n }\n }\n\n free(buf);\n return py_retdict;\n\nerror:\n Py_XDECREF(py_ifc_info);\n Py_DECREF(py_retdict);\n if (buf != NULL)\n free(buf);\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616)\n\nThese files contain loops that convert system data into python objects\r\nand during the process they create objects and dereference their\r\nrefcounts after they have been added to the resulting list.\r\n\r\nHowever, in case of errors during the creation of those python objects,\r\nthe refcount to previously allocated objects is dropped again with\r\nPy_XDECREF, which should be a no-op in case the paramater is NULL. Even\r\nso, in most of these loops the variables pointing to the objects are\r\nnever set to NULL, even after Py_DECREF is called at the end of the loop\r\niteration. This means, after the first iteration, if an error occurs\r\nthose python objects will get their refcount dropped two times,\r\nresulting in a possible double-free.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: psutil_pids(PyObject *self, PyObject *args) {\n DWORD *proclist = NULL;\n DWORD numberOfReturnedPIDs;\n DWORD i;\n PyObject *py_pid = NULL;\n PyObject *py_retlist = PyList_New(0);\n\n if (py_retlist == NULL)\n return NULL;\n proclist = psutil_get_pids(&numberOfReturnedPIDs);\n if (proclist == NULL)\n goto error;\n\n for (i = 0; i < numberOfReturnedPIDs; i++) {\n py_pid = Py_BuildValue(\"I\", proclist[i]);\n if (!py_pid)\n goto error;\n if (PyList_Append(py_retlist, py_pid))\n goto error;\n Py_DECREF(py_pid);\n }\n\n // free C array allocated for PIDs\n free(proclist);\n return py_retlist;\n\nerror:\n Py_XDECREF(py_pid);\n Py_DECREF(py_retlist);\n if (proclist != NULL)\n free(proclist);\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616)\n\nThese files contain loops that convert system data into python objects\r\nand during the process they create objects and dereference their\r\nrefcounts after they have been added to the resulting list.\r\n\r\nHowever, in case of errors during the creation of those python objects,\r\nthe refcount to previously allocated objects is dropped again with\r\nPy_XDECREF, which should be a no-op in case the paramater is NULL. Even\r\nso, in most of these loops the variables pointing to the objects are\r\nnever set to NULL, even after Py_DECREF is called at the end of the loop\r\niteration. This means, after the first iteration, if an error occurs\r\nthose python objects will get their refcount dropped two times,\r\nresulting in a possible double-free.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: psutil_disk_partitions(PyObject *self, PyObject *args) {\n FILE *file;\n struct mnttab mt;\n PyObject *py_dev = NULL;\n PyObject *py_mountp = NULL;\n PyObject *py_tuple = NULL;\n PyObject *py_retlist = PyList_New(0);\n\n if (py_retlist == NULL)\n return NULL;\n\n file = fopen(MNTTAB, \"rb\");\n if (file == NULL) {\n PyErr_SetFromErrno(PyExc_OSError);\n goto error;\n }\n\n while (getmntent(file, &mt) == 0) {\n py_dev = PyUnicode_DecodeFSDefault(mt.mnt_special);\n if (! py_dev)\n goto error;\n py_mountp = PyUnicode_DecodeFSDefault(mt.mnt_mountp);\n if (! py_mountp)\n goto error;\n py_tuple = Py_BuildValue(\n \"(OOss)\",\n py_dev, // device\n py_mountp, // mount point\n mt.mnt_fstype, // fs type\n mt.mnt_mntopts); // options\n if (py_tuple == NULL)\n goto error;\n if (PyList_Append(py_retlist, py_tuple))\n goto error;\n Py_DECREF(py_dev);\n Py_DECREF(py_mountp);\n Py_DECREF(py_tuple);\n }\n fclose(file);\n return py_retlist;\n\nerror:\n Py_XDECREF(py_dev);\n Py_XDECREF(py_mountp);\n Py_XDECREF(py_tuple);\n Py_DECREF(py_retlist);\n if (file != NULL)\n fclose(file);\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616)\n\nThese files contain loops that convert system data into python objects\r\nand during the process they create objects and dereference their\r\nrefcounts after they have been added to the resulting list.\r\n\r\nHowever, in case of errors during the creation of those python objects,\r\nthe refcount to previously allocated objects is dropped again with\r\nPy_XDECREF, which should be a no-op in case the paramater is NULL. Even\r\nso, in most of these loops the variables pointing to the objects are\r\nnever set to NULL, even after Py_DECREF is called at the end of the loop\r\niteration. This means, after the first iteration, if an error occurs\r\nthose python objects will get their refcount dropped two times,\r\nresulting in a possible double-free.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: psutil_pids(PyObject *self, PyObject *args) {\n kinfo_proc *proclist = NULL;\n kinfo_proc *orig_address = NULL;\n size_t num_processes;\n size_t idx;\n PyObject *py_pid = NULL;\n PyObject *py_retlist = PyList_New(0);\n\n if (py_retlist == NULL)\n return NULL;\n\n if (psutil_get_proc_list(&proclist, &num_processes) != 0)\n goto error;\n\n // save the address of proclist so we can free it later\n orig_address = proclist;\n for (idx = 0; idx < num_processes; idx++) {\n py_pid = Py_BuildValue(\"i\", proclist->kp_proc.p_pid);\n if (! py_pid)\n goto error;\n if (PyList_Append(py_retlist, py_pid))\n goto error;\n Py_DECREF(py_pid);\n proclist++;\n }\n free(orig_address);\n\n return py_retlist;\n\nerror:\n Py_XDECREF(py_pid);\n Py_DECREF(py_retlist);\n if (orig_address != NULL)\n free(orig_address);\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616)\n\nThese files contain loops that convert system data into python objects\r\nand during the process they create objects and dereference their\r\nrefcounts after they have been added to the resulting list.\r\n\r\nHowever, in case of errors during the creation of those python objects,\r\nthe refcount to previously allocated objects is dropped again with\r\nPy_XDECREF, which should be a no-op in case the paramater is NULL. Even\r\nso, in most of these loops the variables pointing to the objects are\r\nnever set to NULL, even after Py_DECREF is called at the end of the loop\r\niteration. This means, after the first iteration, if an error occurs\r\nthose python objects will get their refcount dropped two times,\r\nresulting in a possible double-free.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int htc_config_pipe_credits(struct htc_target *target)\n{\n\tstruct sk_buff *skb;\n\tstruct htc_config_pipe_msg *cp_msg;\n\tint ret;\n\tunsigned long time_left;\n\n\tskb = alloc_skb(50 + sizeof(struct htc_frame_hdr), GFP_ATOMIC);\n\tif (!skb) {\n\t\tdev_err(target->dev, \"failed to allocate send buffer\\n\");\n\t\treturn -ENOMEM;\n\t}\n\tskb_reserve(skb, sizeof(struct htc_frame_hdr));\n\n\tcp_msg = skb_put(skb, sizeof(struct htc_config_pipe_msg));\n\n\tcp_msg->message_id = cpu_to_be16(HTC_MSG_CONFIG_PIPE_ID);\n\tcp_msg->pipe_id = USB_WLAN_TX_PIPE;\n\tcp_msg->credits = target->credits;\n\n\ttarget->htc_flags |= HTC_OP_CONFIG_PIPE_CREDITS;\n\n\tret = htc_issue_send(target, skb, skb->len, 0, ENDPOINT0);\n\tif (ret)\n\t\tgoto err;\n\n\ttime_left = wait_for_completion_timeout(&target->cmd_wait, HZ);\n\tif (!time_left) {\n\t\tdev_err(target->dev, \"HTC credit config timeout\\n\");\n\t\treturn -ETIMEDOUT;\n\t}\n\n\treturn 0;\nerr:\n\tkfree_skb(skb);\n\treturn -EINVAL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'ath9k_htc: release allocated buffer if timed out\n\nIn htc_config_pipe_credits, htc_setup_complete, and htc_connect_service\nif time out happens, the allocated buffer needs to be released.\nOtherwise there will be memory leak.\n\nSigned-off-by: Navid Emamdoost \nSigned-off-by: Kalle Valo '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bfad_im_get_stats(struct Scsi_Host *shost)\n{\n\tstruct bfad_im_port_s *im_port =\n\t\t\t(struct bfad_im_port_s *) shost->hostdata[0];\n\tstruct bfad_s *bfad = im_port->bfad;\n\tstruct bfad_hal_comp fcomp;\n\tunion bfa_port_stats_u *fcstats;\n\tstruct fc_host_statistics *hstats;\n\tbfa_status_t rc;\n\tunsigned long flags;\n\n\tfcstats = kzalloc(sizeof(union bfa_port_stats_u), GFP_KERNEL);\n\tif (fcstats == NULL)\n\t\treturn NULL;\n\n\thstats = &bfad->link_stats;\n\tinit_completion(&fcomp.comp);\n\tspin_lock_irqsave(&bfad->bfad_lock, flags);\n\tmemset(hstats, 0, sizeof(struct fc_host_statistics));\n\trc = bfa_port_get_stats(BFA_FCPORT(&bfad->bfa),\n\t\t\t\tfcstats, bfad_hcb_comp, &fcomp);\n\tspin_unlock_irqrestore(&bfad->bfad_lock, flags);\n\tif (rc != BFA_STATUS_OK)\n\t\treturn NULL;\n\n\twait_for_completion(&fcomp.comp);\n\n\t/* Fill the fc_host_statistics structure */\n\thstats->seconds_since_last_reset = fcstats->fc.secs_reset;\n\thstats->tx_frames = fcstats->fc.tx_frames;\n\thstats->tx_words = fcstats->fc.tx_words;\n\thstats->rx_frames = fcstats->fc.rx_frames;\n\thstats->rx_words = fcstats->fc.rx_words;\n\thstats->lip_count = fcstats->fc.lip_count;\n\thstats->nos_count = fcstats->fc.nos_count;\n\thstats->error_frames = fcstats->fc.error_frames;\n\thstats->dumped_frames = fcstats->fc.dropped_frames;\n\thstats->link_failure_count = fcstats->fc.link_failures;\n\thstats->loss_of_sync_count = fcstats->fc.loss_of_syncs;\n\thstats->loss_of_signal_count = fcstats->fc.loss_of_signals;\n\thstats->prim_seq_protocol_err_count = fcstats->fc.primseq_errs;\n\thstats->invalid_crc_count = fcstats->fc.invalid_crcs;\n\n\tkfree(fcstats);\n\treturn hstats;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'scsi: bfa: release allocated memory in case of error\n\nIn bfad_im_get_stats if bfa_port_get_stats fails, allocated memory needs to\nbe released.\n\nLink: https://lore.kernel.org/r/20190910234417.22151-1-navid.emamdoost@gmail.com\nSigned-off-by: Navid Emamdoost \nSigned-off-by: Martin K. Petersen '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int gs_can_open(struct net_device *netdev)\n{\n\tstruct gs_can *dev = netdev_priv(netdev);\n\tstruct gs_usb *parent = dev->parent;\n\tint rc, i;\n\tstruct gs_device_mode *dm;\n\tu32 ctrlmode;\n\n\trc = open_candev(netdev);\n\tif (rc)\n\t\treturn rc;\n\n\tif (atomic_add_return(1, &parent->active_channels) == 1) {\n\t\tfor (i = 0; i < GS_MAX_RX_URBS; i++) {\n\t\t\tstruct urb *urb;\n\t\t\tu8 *buf;\n\n\t\t\t/* alloc rx urb */\n\t\t\turb = usb_alloc_urb(0, GFP_KERNEL);\n\t\t\tif (!urb)\n\t\t\t\treturn -ENOMEM;\n\n\t\t\t/* alloc rx buffer */\n\t\t\tbuf = usb_alloc_coherent(dev->udev,\n\t\t\t\t\t\t sizeof(struct gs_host_frame),\n\t\t\t\t\t\t GFP_KERNEL,\n\t\t\t\t\t\t &urb->transfer_dma);\n\t\t\tif (!buf) {\n\t\t\t\tnetdev_err(netdev,\n\t\t\t\t\t \"No memory left for USB buffer\\n\");\n\t\t\t\tusb_free_urb(urb);\n\t\t\t\treturn -ENOMEM;\n\t\t\t}\n\n\t\t\t/* fill, anchor, and submit rx urb */\n\t\t\tusb_fill_bulk_urb(urb,\n\t\t\t\t\t dev->udev,\n\t\t\t\t\t usb_rcvbulkpipe(dev->udev,\n\t\t\t\t\t\t\t GSUSB_ENDPOINT_IN),\n\t\t\t\t\t buf,\n\t\t\t\t\t sizeof(struct gs_host_frame),\n\t\t\t\t\t gs_usb_receive_bulk_callback,\n\t\t\t\t\t parent);\n\t\t\turb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;\n\n\t\t\tusb_anchor_urb(urb, &parent->rx_submitted);\n\n\t\t\trc = usb_submit_urb(urb, GFP_KERNEL);\n\t\t\tif (rc) {\n\t\t\t\tif (rc == -ENODEV)\n\t\t\t\t\tnetif_device_detach(dev->netdev);\n\n\t\t\t\tnetdev_err(netdev,\n\t\t\t\t\t \"usb_submit failed (err=%d)\\n\",\n\t\t\t\t\t rc);\n\n\t\t\t\tusb_unanchor_urb(urb);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t/* Drop reference,\n\t\t\t * USB core will take care of freeing it\n\t\t\t */\n\t\t\tusb_free_urb(urb);\n\t\t}\n\t}\n\n\tdm = kmalloc(sizeof(*dm), GFP_KERNEL);\n\tif (!dm)\n\t\treturn -ENOMEM;\n\n\t/* flags */\n\tctrlmode = dev->can.ctrlmode;\n\tdm->flags = 0;\n\n\tif (ctrlmode & CAN_CTRLMODE_LOOPBACK)\n\t\tdm->flags |= GS_CAN_MODE_LOOP_BACK;\n\telse if (ctrlmode & CAN_CTRLMODE_LISTENONLY)\n\t\tdm->flags |= GS_CAN_MODE_LISTEN_ONLY;\n\n\t/* Controller is not allowed to retry TX\n\t * this mode is unavailable on atmels uc3c hardware\n\t */\n\tif (ctrlmode & CAN_CTRLMODE_ONE_SHOT)\n\t\tdm->flags |= GS_CAN_MODE_ONE_SHOT;\n\n\tif (ctrlmode & CAN_CTRLMODE_3_SAMPLES)\n\t\tdm->flags |= GS_CAN_MODE_TRIPLE_SAMPLE;\n\n\t/* finally start device */\n\tdm->mode = GS_CAN_MODE_START;\n\trc = usb_control_msg(interface_to_usbdev(dev->iface),\n\t\t\t usb_sndctrlpipe(interface_to_usbdev(dev->iface), 0),\n\t\t\t GS_USB_BREQ_MODE,\n\t\t\t USB_DIR_OUT | USB_TYPE_VENDOR |\n\t\t\t USB_RECIP_INTERFACE,\n\t\t\t dev->channel,\n\t\t\t 0,\n\t\t\t dm,\n\t\t\t sizeof(*dm),\n\t\t\t 1000);\n\n\tif (rc < 0) {\n\t\tnetdev_err(netdev, \"Couldn't start device (err=%d)\\n\", rc);\n\t\tkfree(dm);\n\t\treturn rc;\n\t}\n\n\tkfree(dm);\n\n\tdev->can.state = CAN_STATE_ERROR_ACTIVE;\n\n\tif (!(dev->can.ctrlmode & CAN_CTRLMODE_LISTENONLY))\n\t\tnetif_start_queue(netdev);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'can: gs_usb: gs_can_open(): prevent memory leak\n\nIn gs_can_open() if usb_submit_urb() fails the allocated urb should be\nreleased.\n\nFixes: d08e973a77d1 (\"can: gs_usb: Added support for the GS_USB CAN devices\")\nCc: linux-stable \nSigned-off-by: Navid Emamdoost \nSigned-off-by: Marc Kleine-Budde '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int cx23888_ir_probe(struct cx23885_dev *dev)\n{\n\tstruct cx23888_ir_state *state;\n\tstruct v4l2_subdev *sd;\n\tstruct v4l2_subdev_ir_parameters default_params;\n\tint ret;\n\n\tstate = kzalloc(sizeof(struct cx23888_ir_state), GFP_KERNEL);\n\tif (state == NULL)\n\t\treturn -ENOMEM;\n\n\tspin_lock_init(&state->rx_kfifo_lock);\n\tif (kfifo_alloc(&state->rx_kfifo, CX23888_IR_RX_KFIFO_SIZE, GFP_KERNEL))\n\t\treturn -ENOMEM;\n\n\tstate->dev = dev;\n\tsd = &state->sd;\n\n\tv4l2_subdev_init(sd, &cx23888_ir_controller_ops);\n\tv4l2_set_subdevdata(sd, state);\n\t/* FIXME - fix the formatting of dev->v4l2_dev.name and use it */\n\tsnprintf(sd->name, sizeof(sd->name), \"%s/888-ir\", dev->name);\n\tsd->grp_id = CX23885_HW_888_IR;\n\n\tret = v4l2_device_register_subdev(&dev->v4l2_dev, sd);\n\tif (ret == 0) {\n\t\t/*\n\t\t * Ensure no interrupts arrive from '888 specific conditions,\n\t\t * since we ignore them in this driver to have commonality with\n\t\t * similar IR controller cores.\n\t\t */\n\t\tcx23888_ir_write4(dev, CX23888_IR_IRQEN_REG, 0);\n\n\t\tmutex_init(&state->rx_params_lock);\n\t\tdefault_params = default_rx_params;\n\t\tv4l2_subdev_call(sd, ir, rx_s_parameters, &default_params);\n\n\t\tmutex_init(&state->tx_params_lock);\n\t\tdefault_params = default_tx_params;\n\t\tv4l2_subdev_call(sd, ir, tx_s_parameters, &default_params);\n\t} else {\n\t\tkfifo_free(&state->rx_kfifo);\n\t}\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'media: rc: prevent memory leak in cx23888_ir_probe\n\nIn cx23888_ir_probe if kfifo_alloc fails the allocated memory for state\nshould be released.\n\nSigned-off-by: Navid Emamdoost \nSigned-off-by: Sean Young \nSigned-off-by: Mauro Carvalho Chehab '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static struct btrfs_device *btrfs_find_device_by_path(\n\t\tstruct btrfs_fs_info *fs_info, const char *device_path)\n{\n\tint ret = 0;\n\tstruct btrfs_super_block *disk_super;\n\tu64 devid;\n\tu8 *dev_uuid;\n\tstruct block_device *bdev;\n\tstruct buffer_head *bh;\n\tstruct btrfs_device *device;\n\n\tret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,\n\t\t\t\t fs_info->bdev_holder, 0, &bdev, &bh);\n\tif (ret)\n\t\treturn ERR_PTR(ret);\n\tdisk_super = (struct btrfs_super_block *)bh->b_data;\n\tdevid = btrfs_stack_device_id(&disk_super->dev_item);\n\tdev_uuid = disk_super->dev_item.uuid;\n\tif (btrfs_fs_incompat(fs_info, METADATA_UUID))\n\t\tdevice = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,\n\t\t\t\t\t disk_super->metadata_uuid);\n\telse\n\t\tdevice = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,\n\t\t\t\t\t disk_super->fsid);\n\n\tbrelse(bh);\n\tif (!device)\n\t\tdevice = ERR_PTR(-ENOENT);\n\tblkdev_put(bdev, FMODE_READ);\n\treturn device;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-284'], 'message': 'btrfs: merge btrfs_find_device and find_device\n\nBoth btrfs_find_device() and find_device() does the same thing except\nthat the latter does not take the seed device onto account in the device\nscanning context. We can merge them.\n\nSigned-off-by: Anand Jain \nReviewed-by: David Sterba \nSigned-off-by: David Sterba '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int read_one_dev(struct btrfs_fs_info *fs_info,\n\t\t\tstruct extent_buffer *leaf,\n\t\t\tstruct btrfs_dev_item *dev_item)\n{\n\tstruct btrfs_fs_devices *fs_devices = fs_info->fs_devices;\n\tstruct btrfs_device *device;\n\tu64 devid;\n\tint ret;\n\tu8 fs_uuid[BTRFS_FSID_SIZE];\n\tu8 dev_uuid[BTRFS_UUID_SIZE];\n\n\tdevid = btrfs_device_id(leaf, dev_item);\n\tread_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),\n\t\t\t BTRFS_UUID_SIZE);\n\tread_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),\n\t\t\t BTRFS_FSID_SIZE);\n\n\tif (memcmp(fs_uuid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE)) {\n\t\tfs_devices = open_seed_devices(fs_info, fs_uuid);\n\t\tif (IS_ERR(fs_devices))\n\t\t\treturn PTR_ERR(fs_devices);\n\t}\n\n\tdevice = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,\n\t\t\t\t fs_uuid);\n\tif (!device) {\n\t\tif (!btrfs_test_opt(fs_info, DEGRADED)) {\n\t\t\tbtrfs_report_missing_device(fs_info, devid,\n\t\t\t\t\t\t\tdev_uuid, true);\n\t\t\treturn -ENOENT;\n\t\t}\n\n\t\tdevice = add_missing_dev(fs_devices, devid, dev_uuid);\n\t\tif (IS_ERR(device)) {\n\t\t\tbtrfs_err(fs_info,\n\t\t\t\t\"failed to add missing dev %llu: %ld\",\n\t\t\t\tdevid, PTR_ERR(device));\n\t\t\treturn PTR_ERR(device);\n\t\t}\n\t\tbtrfs_report_missing_device(fs_info, devid, dev_uuid, false);\n\t} else {\n\t\tif (!device->bdev) {\n\t\t\tif (!btrfs_test_opt(fs_info, DEGRADED)) {\n\t\t\t\tbtrfs_report_missing_device(fs_info,\n\t\t\t\t\t\tdevid, dev_uuid, true);\n\t\t\t\treturn -ENOENT;\n\t\t\t}\n\t\t\tbtrfs_report_missing_device(fs_info, devid,\n\t\t\t\t\t\t\tdev_uuid, false);\n\t\t}\n\n\t\tif (!device->bdev &&\n\t\t !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {\n\t\t\t/*\n\t\t\t * this happens when a device that was properly setup\n\t\t\t * in the device info lists suddenly goes bad.\n\t\t\t * device->bdev is NULL, and so we have to set\n\t\t\t * device->missing to one here\n\t\t\t */\n\t\t\tdevice->fs_devices->missing_devices++;\n\t\t\tset_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);\n\t\t}\n\n\t\t/* Move the device to its own fs_devices */\n\t\tif (device->fs_devices != fs_devices) {\n\t\t\tASSERT(test_bit(BTRFS_DEV_STATE_MISSING,\n\t\t\t\t\t\t\t&device->dev_state));\n\n\t\t\tlist_move(&device->dev_list, &fs_devices->devices);\n\t\t\tdevice->fs_devices->num_devices--;\n\t\t\tfs_devices->num_devices++;\n\n\t\t\tdevice->fs_devices->missing_devices--;\n\t\t\tfs_devices->missing_devices++;\n\n\t\t\tdevice->fs_devices = fs_devices;\n\t\t}\n\t}\n\n\tif (device->fs_devices != fs_info->fs_devices) {\n\t\tBUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));\n\t\tif (device->generation !=\n\t\t btrfs_device_generation(leaf, dev_item))\n\t\t\treturn -EINVAL;\n\t}\n\n\tfill_device_from_item(leaf, dev_item, device);\n\tset_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);\n\tif (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&\n\t !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {\n\t\tdevice->fs_devices->total_rw_bytes += device->total_bytes;\n\t\tatomic64_add(device->total_bytes - device->bytes_used,\n\t\t\t\t&fs_info->free_chunk_space);\n\t}\n\tret = 0;\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-284'], 'message': 'btrfs: merge btrfs_find_device and find_device\n\nBoth btrfs_find_device() and find_device() does the same thing except\nthat the latter does not take the seed device onto account in the device\nscanning context. We can merge them.\n\nSigned-off-by: Anand Jain \nReviewed-by: David Sterba \nSigned-off-by: David Sterba '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: struct resource_pool *dce120_create_resource_pool(\n\tuint8_t num_virtual_links,\n\tstruct dc *dc)\n{\n\tstruct dce110_resource_pool *pool =\n\t\tkzalloc(sizeof(struct dce110_resource_pool), GFP_KERNEL);\n\n\tif (!pool)\n\t\treturn NULL;\n\n\tif (construct(num_virtual_links, dc, pool))\n\t\treturn &pool->base;\n\n\tBREAK_TO_DEBUGGER();\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'drm/amd/display: prevent memory leak\n\nIn dcn*_create_resource_pool the allocated memory should be released if\nconstruct pool fails.\n\nReviewed-by: Harry Wentland \nSigned-off-by: Navid Emamdoost \nSigned-off-by: Alex Deucher '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int ca8210_probe(struct spi_device *spi_device)\n{\n\tstruct ca8210_priv *priv;\n\tstruct ieee802154_hw *hw;\n\tstruct ca8210_platform_data *pdata;\n\tint ret;\n\n\tdev_info(&spi_device->dev, \"Inserting ca8210\\n\");\n\n\t/* allocate ieee802154_hw and private data */\n\thw = ieee802154_alloc_hw(sizeof(struct ca8210_priv), &ca8210_phy_ops);\n\tif (!hw) {\n\t\tdev_crit(&spi_device->dev, \"ieee802154_alloc_hw failed\\n\");\n\t\tret = -ENOMEM;\n\t\tgoto error;\n\t}\n\n\tpriv = hw->priv;\n\tpriv->hw = hw;\n\tpriv->spi = spi_device;\n\thw->parent = &spi_device->dev;\n\tspin_lock_init(&priv->lock);\n\tpriv->async_tx_pending = false;\n\tpriv->hw_registered = false;\n\tpriv->sync_up = 0;\n\tpriv->sync_down = 0;\n\tpriv->promiscuous = false;\n\tpriv->retries = 0;\n\tinit_completion(&priv->ca8210_is_awake);\n\tinit_completion(&priv->spi_transfer_complete);\n\tinit_completion(&priv->sync_exchange_complete);\n\tspi_set_drvdata(priv->spi, priv);\n\tif (IS_ENABLED(CONFIG_IEEE802154_CA8210_DEBUGFS)) {\n\t\tcascoda_api_upstream = ca8210_test_int_driver_write;\n\t\tca8210_test_interface_init(priv);\n\t} else {\n\t\tcascoda_api_upstream = NULL;\n\t}\n\tca8210_hw_setup(hw);\n\tieee802154_random_extended_addr(&hw->phy->perm_extended_addr);\n\n\tpdata = kmalloc(sizeof(*pdata), GFP_KERNEL);\n\tif (!pdata) {\n\t\tret = -ENOMEM;\n\t\tgoto error;\n\t}\n\n\tret = ca8210_get_platform_data(priv->spi, pdata);\n\tif (ret) {\n\t\tdev_crit(&spi_device->dev, \"ca8210_get_platform_data failed\\n\");\n\t\tgoto error;\n\t}\n\tpriv->spi->dev.platform_data = pdata;\n\n\tret = ca8210_dev_com_init(priv);\n\tif (ret) {\n\t\tdev_crit(&spi_device->dev, \"ca8210_dev_com_init failed\\n\");\n\t\tgoto error;\n\t}\n\tret = ca8210_reset_init(priv->spi);\n\tif (ret) {\n\t\tdev_crit(&spi_device->dev, \"ca8210_reset_init failed\\n\");\n\t\tgoto error;\n\t}\n\n\tret = ca8210_interrupt_init(priv->spi);\n\tif (ret) {\n\t\tdev_crit(&spi_device->dev, \"ca8210_interrupt_init failed\\n\");\n\t\tgoto error;\n\t}\n\n\tmsleep(100);\n\n\tca8210_reset_send(priv->spi, 1);\n\n\tret = tdme_chipinit(priv->spi);\n\tif (ret) {\n\t\tdev_crit(&spi_device->dev, \"tdme_chipinit failed\\n\");\n\t\tgoto error;\n\t}\n\n\tif (pdata->extclockenable) {\n\t\tret = ca8210_config_extern_clk(pdata, priv->spi, 1);\n\t\tif (ret) {\n\t\t\tdev_crit(\n\t\t\t\t&spi_device->dev,\n\t\t\t\t\"ca8210_config_extern_clk failed\\n\"\n\t\t\t);\n\t\t\tgoto error;\n\t\t}\n\t\tret = ca8210_register_ext_clock(priv->spi);\n\t\tif (ret) {\n\t\t\tdev_crit(\n\t\t\t\t&spi_device->dev,\n\t\t\t\t\"ca8210_register_ext_clock failed\\n\"\n\t\t\t);\n\t\t\tgoto error;\n\t\t}\n\t}\n\n\tret = ieee802154_register_hw(hw);\n\tif (ret) {\n\t\tdev_crit(&spi_device->dev, \"ieee802154_register_hw failed\\n\");\n\t\tgoto error;\n\t}\n\tpriv->hw_registered = true;\n\n\treturn 0;\nerror:\n\tmsleep(100); /* wait for pending spi transfers to complete */\n\tca8210_remove(spi_device);\n\treturn link_to_linux_err(ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'ieee802154: ca8210: prevent memory leak\n\nIn ca8210_probe the allocated pdata needs to be assigned to\nspi_device->dev.platform_data before calling ca8210_get_platform_data.\nOthrwise when ca8210_get_platform_data fails pdata cannot be released.\n\nSigned-off-by: Navid Emamdoost \nLink: https://lore.kernel.org/r/20190917224713.26371-1-navid.emamdoost@gmail.com\nSigned-off-by: Stefan Schmidt '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: str_lower_case_match(OnigEncoding enc, int case_fold_flag,\n const UChar* t, const UChar* tend,\n const UChar* p, const UChar* end)\n{\n int lowlen;\n UChar *q, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN];\n\n while (t < tend) {\n lowlen = ONIGENC_MBC_CASE_FOLD(enc, case_fold_flag, &p, end, lowbuf);\n q = lowbuf;\n while (lowlen > 0) {\n if (*t++ != *q++) return 0;\n lowlen--;\n }\n }\n\n return 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'fix heap-buffer-overflow'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int sqlite3Select(\n Parse *pParse, /* The parser context */\n Select *p, /* The SELECT statement being coded. */\n SelectDest *pDest /* What to do with the query results */\n){\n int i, j; /* Loop counters */\n WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */\n Vdbe *v; /* The virtual machine under construction */\n int isAgg; /* True for select lists like \"count(*)\" */\n ExprList *pEList = 0; /* List of columns to extract. */\n SrcList *pTabList; /* List of tables to select from */\n Expr *pWhere; /* The WHERE clause. May be NULL */\n ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */\n Expr *pHaving; /* The HAVING clause. May be NULL */\n int rc = 1; /* Value to return from this function */\n DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */\n SortCtx sSort; /* Info on how to code the ORDER BY clause */\n AggInfo sAggInfo; /* Information used by aggregate queries */\n int iEnd; /* Address of the end of the query */\n sqlite3 *db; /* The database connection */\n ExprList *pMinMaxOrderBy = 0; /* Added ORDER BY for min/max queries */\n u8 minMaxFlag; /* Flag for min/max queries */\n\n db = pParse->db;\n v = sqlite3GetVdbe(pParse);\n if( p==0 || db->mallocFailed || pParse->nErr ){\n return 1;\n }\n if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;\n memset(&sAggInfo, 0, sizeof(sAggInfo));\n#if SELECTTRACE_ENABLED\n SELECTTRACE(1,pParse,p, (\"begin processing:\\n\", pParse->addrExplain));\n if( sqlite3SelectTrace & 0x100 ){\n sqlite3TreeViewSelect(0, p, 0);\n }\n#endif\n\n assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );\n assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );\n assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );\n assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );\n if( IgnorableOrderby(pDest) ){\n assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || \n pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||\n pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo ||\n pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);\n /* If ORDER BY makes no difference in the output then neither does\n ** DISTINCT so it can be removed too. */\n sqlite3ExprListDelete(db, p->pOrderBy);\n p->pOrderBy = 0;\n p->selFlags &= ~SF_Distinct;\n }\n sqlite3SelectPrep(pParse, p, 0);\n if( pParse->nErr || db->mallocFailed ){\n goto select_end;\n }\n assert( p->pEList!=0 );\n#if SELECTTRACE_ENABLED\n if( sqlite3SelectTrace & 0x104 ){\n SELECTTRACE(0x104,pParse,p, (\"after name resolution:\\n\"));\n sqlite3TreeViewSelect(0, p, 0);\n }\n#endif\n\n if( pDest->eDest==SRT_Output ){\n generateColumnNames(pParse, p);\n }\n\n#ifndef SQLITE_OMIT_WINDOWFUNC\n if( sqlite3WindowRewrite(pParse, p) ){\n goto select_end;\n }\n#if SELECTTRACE_ENABLED\n if( p->pWin && (sqlite3SelectTrace & 0x108)!=0 ){\n SELECTTRACE(0x104,pParse,p, (\"after window rewrite:\\n\"));\n sqlite3TreeViewSelect(0, p, 0);\n }\n#endif\n#endif /* SQLITE_OMIT_WINDOWFUNC */\n pTabList = p->pSrc;\n isAgg = (p->selFlags & SF_Aggregate)!=0;\n memset(&sSort, 0, sizeof(sSort));\n sSort.pOrderBy = p->pOrderBy;\n\n /* Try to various optimizations (flattening subqueries, and strength\n ** reduction of join operators) in the FROM clause up into the main query\n */\n#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)\n for(i=0; !p->pPrior && inSrc; i++){\n struct SrcList_item *pItem = &pTabList->a[i];\n Select *pSub = pItem->pSelect;\n Table *pTab = pItem->pTab;\n\n /* Convert LEFT JOIN into JOIN if there are terms of the right table\n ** of the LEFT JOIN used in the WHERE clause.\n */\n if( (pItem->fg.jointype & JT_LEFT)!=0\n && sqlite3ExprImpliesNonNullRow(p->pWhere, pItem->iCursor)\n && OptimizationEnabled(db, SQLITE_SimplifyJoin)\n ){\n SELECTTRACE(0x100,pParse,p,\n (\"LEFT-JOIN simplifies to JOIN on term %d\\n\",i));\n pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER);\n unsetJoinExpr(p->pWhere, pItem->iCursor);\n }\n\n /* No futher action if this term of the FROM clause is no a subquery */\n if( pSub==0 ) continue;\n\n /* Catch mismatch in the declared columns of a view and the number of\n ** columns in the SELECT on the RHS */\n if( pTab->nCol!=pSub->pEList->nExpr ){\n sqlite3ErrorMsg(pParse, \"expected %d columns for '%s' but got %d\",\n pTab->nCol, pTab->zName, pSub->pEList->nExpr);\n goto select_end;\n }\n\n /* Do not try to flatten an aggregate subquery.\n **\n ** Flattening an aggregate subquery is only possible if the outer query\n ** is not a join. But if the outer query is not a join, then the subquery\n ** will be implemented as a co-routine and there is no advantage to\n ** flattening in that case.\n */\n if( (pSub->selFlags & SF_Aggregate)!=0 ) continue;\n assert( pSub->pGroupBy==0 );\n\n /* If the outer query contains a \"complex\" result set (that is,\n ** if the result set of the outer query uses functions or subqueries)\n ** and if the subquery contains an ORDER BY clause and if\n ** it will be implemented as a co-routine, then do not flatten. This\n ** restriction allows SQL constructs like this:\n **\n ** SELECT expensive_function(x)\n ** FROM (SELECT x FROM tab ORDER BY y LIMIT 10);\n **\n ** The expensive_function() is only computed on the 10 rows that\n ** are output, rather than every row of the table.\n **\n ** The requirement that the outer query have a complex result set\n ** means that flattening does occur on simpler SQL constraints without\n ** the expensive_function() like:\n **\n ** SELECT x FROM (SELECT x FROM tab ORDER BY y LIMIT 10);\n */\n if( pSub->pOrderBy!=0\n && i==0\n && (p->selFlags & SF_ComplexResult)!=0\n && (pTabList->nSrc==1\n || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0)\n ){\n continue;\n }\n\n if( flattenSubquery(pParse, p, i, isAgg) ){\n if( pParse->nErr ) goto select_end;\n /* This subquery can be absorbed into its parent. */\n i = -1;\n }\n pTabList = p->pSrc;\n if( db->mallocFailed ) goto select_end;\n if( !IgnorableOrderby(pDest) ){\n sSort.pOrderBy = p->pOrderBy;\n }\n }\n#endif\n\n#ifndef SQLITE_OMIT_COMPOUND_SELECT\n /* Handle compound SELECT statements using the separate multiSelect()\n ** procedure.\n */\n if( p->pPrior ){\n rc = multiSelect(pParse, p, pDest);\n#if SELECTTRACE_ENABLED\n SELECTTRACE(0x1,pParse,p,(\"end compound-select processing\\n\"));\n if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){\n sqlite3TreeViewSelect(0, p, 0);\n }\n#endif\n if( p->pNext==0 ) ExplainQueryPlanPop(pParse);\n return rc;\n }\n#endif\n\n /* Do the WHERE-clause constant propagation optimization if this is\n ** a join. No need to speed time on this operation for non-join queries\n ** as the equivalent optimization will be handled by query planner in\n ** sqlite3WhereBegin().\n */\n if( pTabList->nSrc>1\n && OptimizationEnabled(db, SQLITE_PropagateConst)\n && propagateConstants(pParse, p)\n ){\n#if SELECTTRACE_ENABLED\n if( sqlite3SelectTrace & 0x100 ){\n SELECTTRACE(0x100,pParse,p,(\"After constant propagation:\\n\"));\n sqlite3TreeViewSelect(0, p, 0);\n }\n#endif\n }else{\n SELECTTRACE(0x100,pParse,p,(\"Constant propagation not helpful\\n\"));\n }\n\n#ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION\n if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView)\n && countOfViewOptimization(pParse, p)\n ){\n if( db->mallocFailed ) goto select_end;\n pEList = p->pEList;\n pTabList = p->pSrc;\n }\n#endif\n\n /* For each term in the FROM clause, do two things:\n ** (1) Authorized unreferenced tables\n ** (2) Generate code for all sub-queries\n */\n for(i=0; inSrc; i++){\n struct SrcList_item *pItem = &pTabList->a[i];\n SelectDest dest;\n Select *pSub;\n#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)\n const char *zSavedAuthContext;\n#endif\n\n /* Issue SQLITE_READ authorizations with a fake column name for any\n ** tables that are referenced but from which no values are extracted.\n ** Examples of where these kinds of null SQLITE_READ authorizations\n ** would occur:\n **\n ** SELECT count(*) FROM t1; -- SQLITE_READ t1.\"\"\n ** SELECT t1.* FROM t1, t2; -- SQLITE_READ t2.\"\"\n **\n ** The fake column name is an empty string. It is possible for a table to\n ** have a column named by the empty string, in which case there is no way to\n ** distinguish between an unreferenced table and an actual reference to the\n ** \"\" column. The original design was for the fake column name to be a NULL,\n ** which would be unambiguous. But legacy authorization callbacks might\n ** assume the column name is non-NULL and segfault. The use of an empty\n ** string for the fake column name seems safer.\n */\n if( pItem->colUsed==0 && pItem->zName!=0 ){\n sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, \"\", pItem->zDatabase);\n }\n\n#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)\n /* Generate code for all sub-queries in the FROM clause\n */\n pSub = pItem->pSelect;\n if( pSub==0 ) continue;\n\n /* The code for a subquery should only be generated once, though it is\n ** technically harmless for it to be generated multiple times. The\n ** following assert() will detect if something changes to cause\n ** the same subquery to be coded multiple times, as a signal to the\n ** developers to try to optimize the situation.\n **\n ** Update 2019-07-24:\n ** See ticket https://sqlite.org/src/tktview/c52b09c7f38903b1311cec40.\n ** The dbsqlfuzz fuzzer found a case where the same subquery gets\n ** coded twice. So this assert() now becomes a testcase(). It should\n ** be very rare, though.\n */\n testcase( pItem->addrFillSub!=0 );\n\n /* Increment Parse.nHeight by the height of the largest expression\n ** tree referred to by this, the parent select. The child select\n ** may contain expression trees of at most\n ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit\n ** more conservative than necessary, but much easier than enforcing\n ** an exact limit.\n */\n pParse->nHeight += sqlite3SelectExprHeight(p);\n\n /* Make copies of constant WHERE-clause terms in the outer query down\n ** inside the subquery. This can help the subquery to run more efficiently.\n */\n if( OptimizationEnabled(db, SQLITE_PushDown)\n && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor,\n (pItem->fg.jointype & JT_OUTER)!=0)\n ){\n#if SELECTTRACE_ENABLED\n if( sqlite3SelectTrace & 0x100 ){\n SELECTTRACE(0x100,pParse,p,\n (\"After WHERE-clause push-down into subquery %d:\\n\", pSub->selId));\n sqlite3TreeViewSelect(0, p, 0);\n }\n#endif\n }else{\n SELECTTRACE(0x100,pParse,p,(\"Push-down not possible\\n\"));\n }\n\n zSavedAuthContext = pParse->zAuthContext;\n pParse->zAuthContext = pItem->zName;\n\n /* Generate code to implement the subquery\n **\n ** The subquery is implemented as a co-routine if the subquery is\n ** guaranteed to be the outer loop (so that it does not need to be\n ** computed more than once)\n **\n ** TODO: Are there other reasons beside (1) to use a co-routine\n ** implementation?\n */\n if( i==0\n && (pTabList->nSrc==1\n || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) /* (1) */\n ){\n /* Implement a co-routine that will return a single row of the result\n ** set on each invocation.\n */\n int addrTop = sqlite3VdbeCurrentAddr(v)+1;\n \n pItem->regReturn = ++pParse->nMem;\n sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);\n VdbeComment((v, \"%s\", pItem->pTab->zName));\n pItem->addrFillSub = addrTop;\n sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);\n ExplainQueryPlan((pParse, 1, \"CO-ROUTINE %u\", pSub->selId));\n sqlite3Select(pParse, pSub, &dest);\n pItem->pTab->nRowLogEst = pSub->nSelectRow;\n pItem->fg.viaCoroutine = 1;\n pItem->regResult = dest.iSdst;\n sqlite3VdbeEndCoroutine(v, pItem->regReturn);\n sqlite3VdbeJumpHere(v, addrTop-1);\n sqlite3ClearTempRegCache(pParse);\n }else{\n /* Generate a subroutine that will fill an ephemeral table with\n ** the content of this subquery. pItem->addrFillSub will point\n ** to the address of the generated subroutine. pItem->regReturn\n ** is a register allocated to hold the subroutine return address\n */\n int topAddr;\n int onceAddr = 0;\n int retAddr;\n struct SrcList_item *pPrior;\n\n testcase( pItem->addrFillSub==0 ); /* Ticket c52b09c7f38903b1311 */\n pItem->regReturn = ++pParse->nMem;\n topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);\n pItem->addrFillSub = topAddr+1;\n if( pItem->fg.isCorrelated==0 ){\n /* If the subquery is not correlated and if we are not inside of\n ** a trigger, then we only need to compute the value of the subquery\n ** once. */\n onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);\n VdbeComment((v, \"materialize \\\"%s\\\"\", pItem->pTab->zName));\n }else{\n VdbeNoopComment((v, \"materialize \\\"%s\\\"\", pItem->pTab->zName));\n }\n pPrior = isSelfJoinView(pTabList, pItem);\n if( pPrior ){\n sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);\n assert( pPrior->pSelect!=0 );\n pSub->nSelectRow = pPrior->pSelect->nSelectRow;\n }else{\n sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);\n ExplainQueryPlan((pParse, 1, \"MATERIALIZE %u\", pSub->selId));\n sqlite3Select(pParse, pSub, &dest);\n }\n pItem->pTab->nRowLogEst = pSub->nSelectRow;\n if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);\n retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);\n VdbeComment((v, \"end %s\", pItem->pTab->zName));\n sqlite3VdbeChangeP1(v, topAddr, retAddr);\n sqlite3ClearTempRegCache(pParse);\n }\n if( db->mallocFailed ) goto select_end;\n pParse->nHeight -= sqlite3SelectExprHeight(p);\n pParse->zAuthContext = zSavedAuthContext;\n#endif\n }\n\n /* Various elements of the SELECT copied into local variables for\n ** convenience */\n pEList = p->pEList;\n pWhere = p->pWhere;\n pGroupBy = p->pGroupBy;\n pHaving = p->pHaving;\n sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;\n\n#if SELECTTRACE_ENABLED\n if( sqlite3SelectTrace & 0x400 ){\n SELECTTRACE(0x400,pParse,p,(\"After all FROM-clause analysis:\\n\"));\n sqlite3TreeViewSelect(0, p, 0);\n }\n#endif\n\n /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and \n ** if the select-list is the same as the ORDER BY list, then this query\n ** can be rewritten as a GROUP BY. In other words, this:\n **\n ** SELECT DISTINCT xyz FROM ... ORDER BY xyz\n **\n ** is transformed to:\n **\n ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz\n **\n ** The second form is preferred as a single index (or temp-table) may be \n ** used for both the ORDER BY and DISTINCT processing. As originally \n ** written the query must use a temp-table for at least one of the ORDER \n ** BY and DISTINCT, and an index or separate temp-table for the other.\n */\n if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct \n && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0\n ){\n p->selFlags &= ~SF_Distinct;\n pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);\n /* Notice that even thought SF_Distinct has been cleared from p->selFlags,\n ** the sDistinct.isTnct is still set. Hence, isTnct represents the\n ** original setting of the SF_Distinct flag, not the current setting */\n assert( sDistinct.isTnct );\n\n#if SELECTTRACE_ENABLED\n if( sqlite3SelectTrace & 0x400 ){\n SELECTTRACE(0x400,pParse,p,(\"Transform DISTINCT into GROUP BY:\\n\"));\n sqlite3TreeViewSelect(0, p, 0);\n }\n#endif\n }\n\n /* If there is an ORDER BY clause, then create an ephemeral index to\n ** do the sorting. But this sorting ephemeral index might end up\n ** being unused if the data can be extracted in pre-sorted order.\n ** If that is the case, then the OP_OpenEphemeral instruction will be\n ** changed to an OP_Noop once we figure out that the sorting index is\n ** not needed. The sSort.addrSortIndex variable is used to facilitate\n ** that change.\n */\n if( sSort.pOrderBy ){\n KeyInfo *pKeyInfo;\n pKeyInfo = sqlite3KeyInfoFromExprList(\n pParse, sSort.pOrderBy, 0, pEList->nExpr);\n sSort.iECursor = pParse->nTab++;\n sSort.addrSortIndex =\n sqlite3VdbeAddOp4(v, OP_OpenEphemeral,\n sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,\n (char*)pKeyInfo, P4_KEYINFO\n );\n }else{\n sSort.addrSortIndex = -1;\n }\n\n /* If the output is destined for a temporary table, open that table.\n */\n if( pDest->eDest==SRT_EphemTab ){\n sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);\n }\n\n /* Set the limiter.\n */\n iEnd = sqlite3VdbeMakeLabel(pParse);\n if( (p->selFlags & SF_FixedLimit)==0 ){\n p->nSelectRow = 320; /* 4 billion rows */\n }\n computeLimitRegisters(pParse, p, iEnd);\n if( p->iLimit==0 && sSort.addrSortIndex>=0 ){\n sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);\n sSort.sortFlags |= SORTFLAG_UseSorter;\n }\n\n /* Open an ephemeral index to use for the distinct set.\n */\n if( p->selFlags & SF_Distinct ){\n sDistinct.tabTnct = pParse->nTab++;\n sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,\n sDistinct.tabTnct, 0, 0,\n (char*)sqlite3KeyInfoFromExprList(pParse, p->pEList,0,0),\n P4_KEYINFO);\n sqlite3VdbeChangeP5(v, BTREE_UNORDERED);\n sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;\n }else{\n sDistinct.eTnctType = WHERE_DISTINCT_NOOP;\n }\n\n if( !isAgg && pGroupBy==0 ){\n /* No aggregate functions and no GROUP BY clause */\n u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0)\n | (p->selFlags & SF_FixedLimit);\n#ifndef SQLITE_OMIT_WINDOWFUNC\n Window *pWin = p->pWin; /* Master window object (or NULL) */\n if( pWin ){\n sqlite3WindowCodeInit(pParse, pWin);\n }\n#endif\n assert( WHERE_USE_LIMIT==SF_FixedLimit );\n\n\n /* Begin the database scan. */\n SELECTTRACE(1,pParse,p,(\"WhereBegin\\n\"));\n pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,\n p->pEList, wctrlFlags, p->nSelectRow);\n if( pWInfo==0 ) goto select_end;\n if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){\n p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);\n }\n if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){\n sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);\n }\n if( sSort.pOrderBy ){\n sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);\n sSort.labelOBLopt = sqlite3WhereOrderByLimitOptLabel(pWInfo);\n if( sSort.nOBSat==sSort.pOrderBy->nExpr ){\n sSort.pOrderBy = 0;\n }\n }\n\n /* If sorting index that was created by a prior OP_OpenEphemeral \n ** instruction ended up not being needed, then change the OP_OpenEphemeral\n ** into an OP_Noop.\n */\n if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){\n sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);\n }\n\n assert( p->pEList==pEList );\n#ifndef SQLITE_OMIT_WINDOWFUNC\n if( pWin ){\n int addrGosub = sqlite3VdbeMakeLabel(pParse);\n int iCont = sqlite3VdbeMakeLabel(pParse);\n int iBreak = sqlite3VdbeMakeLabel(pParse);\n int regGosub = ++pParse->nMem;\n\n sqlite3WindowCodeStep(pParse, p, pWInfo, regGosub, addrGosub);\n\n sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);\n sqlite3VdbeResolveLabel(v, addrGosub);\n VdbeNoopComment((v, \"inner-loop subroutine\"));\n sSort.labelOBLopt = 0;\n selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, iCont, iBreak);\n sqlite3VdbeResolveLabel(v, iCont);\n sqlite3VdbeAddOp1(v, OP_Return, regGosub);\n VdbeComment((v, \"end inner-loop subroutine\"));\n sqlite3VdbeResolveLabel(v, iBreak);\n }else\n#endif /* SQLITE_OMIT_WINDOWFUNC */\n {\n /* Use the standard inner loop. */\n selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest,\n sqlite3WhereContinueLabel(pWInfo),\n sqlite3WhereBreakLabel(pWInfo));\n\n /* End the database scan loop.\n */\n sqlite3WhereEnd(pWInfo);\n }\n }else{\n /* This case when there exist aggregate functions or a GROUP BY clause\n ** or both */\n NameContext sNC; /* Name context for processing aggregate information */\n int iAMem; /* First Mem address for storing current GROUP BY */\n int iBMem; /* First Mem address for previous GROUP BY */\n int iUseFlag; /* Mem address holding flag indicating that at least\n ** one row of the input to the aggregator has been\n ** processed */\n int iAbortFlag; /* Mem address which causes query abort if positive */\n int groupBySort; /* Rows come from source in GROUP BY order */\n int addrEnd; /* End of processing for this SELECT */\n int sortPTab = 0; /* Pseudotable used to decode sorting results */\n int sortOut = 0; /* Output register from the sorter */\n int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */\n\n /* Remove any and all aliases between the result set and the\n ** GROUP BY clause.\n */\n if( pGroupBy ){\n int k; /* Loop counter */\n struct ExprList_item *pItem; /* For looping over expression in a list */\n\n for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){\n pItem->u.x.iAlias = 0;\n }\n for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){\n pItem->u.x.iAlias = 0;\n }\n assert( 66==sqlite3LogEst(100) );\n if( p->nSelectRow>66 ) p->nSelectRow = 66;\n\n /* If there is both a GROUP BY and an ORDER BY clause and they are\n ** identical, then it may be possible to disable the ORDER BY clause \n ** on the grounds that the GROUP BY will cause elements to come out \n ** in the correct order. It also may not - the GROUP BY might use a\n ** database index that causes rows to be grouped together as required\n ** but not actually sorted. Either way, record the fact that the\n ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp\n ** variable. */\n if( sSort.pOrderBy && pGroupBy->nExpr==sSort.pOrderBy->nExpr ){\n int ii;\n /* The GROUP BY processing doesn't care whether rows are delivered in\n ** ASC or DESC order - only that each group is returned contiguously.\n ** So set the ASC/DESC flags in the GROUP BY to match those in the \n ** ORDER BY to maximize the chances of rows being delivered in an \n ** order that makes the ORDER BY redundant. */\n for(ii=0; iinExpr; ii++){\n u8 sortFlags = sSort.pOrderBy->a[ii].sortFlags & KEYINFO_ORDER_DESC;\n pGroupBy->a[ii].sortFlags = sortFlags;\n }\n if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){\n orderByGrp = 1;\n }\n }\n }else{\n assert( 0==sqlite3LogEst(1) );\n p->nSelectRow = 0;\n }\n\n /* Create a label to jump to when we want to abort the query */\n addrEnd = sqlite3VdbeMakeLabel(pParse);\n\n /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in\n ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the\n ** SELECT statement.\n */\n memset(&sNC, 0, sizeof(sNC));\n sNC.pParse = pParse;\n sNC.pSrcList = pTabList;\n sNC.uNC.pAggInfo = &sAggInfo;\n VVA_ONLY( sNC.ncFlags = NC_UAggInfo; )\n sAggInfo.mnReg = pParse->nMem+1;\n sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;\n sAggInfo.pGroupBy = pGroupBy;\n sqlite3ExprAnalyzeAggList(&sNC, pEList);\n sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);\n if( pHaving ){\n if( pGroupBy ){\n assert( pWhere==p->pWhere );\n assert( pHaving==p->pHaving );\n assert( pGroupBy==p->pGroupBy );\n havingToWhere(pParse, p);\n pWhere = p->pWhere;\n }\n sqlite3ExprAnalyzeAggregates(&sNC, pHaving);\n }\n sAggInfo.nAccumulator = sAggInfo.nColumn;\n if( p->pGroupBy==0 && p->pHaving==0 && sAggInfo.nFunc==1 ){\n minMaxFlag = minMaxQuery(db, sAggInfo.aFunc[0].pExpr, &pMinMaxOrderBy);\n }else{\n minMaxFlag = WHERE_ORDERBY_NORMAL;\n }\n for(i=0; ix.pList);\n#ifndef SQLITE_OMIT_WINDOWFUNC\n assert( !IsWindowFunc(pExpr) );\n if( ExprHasProperty(pExpr, EP_WinFunc) ){\n sqlite3ExprAnalyzeAggregates(&sNC, pExpr->y.pWin->pFilter);\n }\n#endif\n sNC.ncFlags &= ~NC_InAggFunc;\n }\n sAggInfo.mxReg = pParse->nMem;\n if( db->mallocFailed ) goto select_end;\n#if SELECTTRACE_ENABLED\n if( sqlite3SelectTrace & 0x400 ){\n int ii;\n SELECTTRACE(0x400,pParse,p,(\"After aggregate analysis:\\n\"));\n sqlite3TreeViewSelect(0, p, 0);\n for(ii=0; iinTab++;\n pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pGroupBy,0,sAggInfo.nColumn);\n addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, \n sAggInfo.sortingIdx, sAggInfo.nSortingColumn, \n 0, (char*)pKeyInfo, P4_KEYINFO);\n\n /* Initialize memory locations used by GROUP BY aggregate processing\n */\n iUseFlag = ++pParse->nMem;\n iAbortFlag = ++pParse->nMem;\n regOutputRow = ++pParse->nMem;\n addrOutputRow = sqlite3VdbeMakeLabel(pParse);\n regReset = ++pParse->nMem;\n addrReset = sqlite3VdbeMakeLabel(pParse);\n iAMem = pParse->nMem + 1;\n pParse->nMem += pGroupBy->nExpr;\n iBMem = pParse->nMem + 1;\n pParse->nMem += pGroupBy->nExpr;\n sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);\n VdbeComment((v, \"clear abort flag\"));\n sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);\n\n /* Begin a loop that will extract all source rows in GROUP BY order.\n ** This might involve two separate loops with an OP_Sort in between, or\n ** it might be a single loop that uses an index to extract information\n ** in the right order to begin with.\n */\n sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);\n SELECTTRACE(1,pParse,p,(\"WhereBegin\\n\"));\n pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,\n WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0\n );\n if( pWInfo==0 ) goto select_end;\n if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){\n /* The optimizer is able to deliver rows in group by order so\n ** we do not have to sort. The OP_OpenEphemeral table will be\n ** cancelled later because we still need to use the pKeyInfo\n */\n groupBySort = 0;\n }else{\n /* Rows are coming out in undetermined order. We have to push\n ** each row into a sorting index, terminate the first loop,\n ** then loop over the sorting index in order to get the output\n ** in sorted order\n */\n int regBase;\n int regRecord;\n int nCol;\n int nGroupBy;\n\n explainTempTable(pParse, \n (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?\n \"DISTINCT\" : \"GROUP BY\");\n\n groupBySort = 1;\n nGroupBy = pGroupBy->nExpr;\n nCol = nGroupBy;\n j = nGroupBy;\n for(i=0; i=j ){\n nCol++;\n j++;\n }\n }\n regBase = sqlite3GetTempRange(pParse, nCol);\n sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);\n j = nGroupBy;\n for(i=0; iiSorterColumn>=j ){\n int r1 = j + regBase;\n sqlite3ExprCodeGetColumnOfTable(v,\n pCol->pTab, pCol->iTable, pCol->iColumn, r1);\n j++;\n }\n }\n regRecord = sqlite3GetTempReg(pParse);\n sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);\n sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);\n sqlite3ReleaseTempReg(pParse, regRecord);\n sqlite3ReleaseTempRange(pParse, regBase, nCol);\n sqlite3WhereEnd(pWInfo);\n sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;\n sortOut = sqlite3GetTempReg(pParse);\n sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);\n sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);\n VdbeComment((v, \"GROUP BY sort\")); VdbeCoverage(v);\n sAggInfo.useSortingIdx = 1;\n }\n\n /* If the index or temporary table used by the GROUP BY sort\n ** will naturally deliver rows in the order required by the ORDER BY\n ** clause, cancel the ephemeral table open coded earlier.\n **\n ** This is an optimization - the correct answer should result regardless.\n ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to \n ** disable this optimization for testing purposes. */\n if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder) \n && (groupBySort || sqlite3WhereIsSorted(pWInfo))\n ){\n sSort.pOrderBy = 0;\n sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);\n }\n\n /* Evaluate the current GROUP BY terms and store in b0, b1, b2...\n ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)\n ** Then compare the current GROUP BY terms against the GROUP BY terms\n ** from the previous row currently stored in a0, a1, a2...\n */\n addrTopOfLoop = sqlite3VdbeCurrentAddr(v);\n if( groupBySort ){\n sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,\n sortOut, sortPTab);\n }\n for(j=0; jnExpr; j++){\n if( groupBySort ){\n sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);\n }else{\n sAggInfo.directMode = 1;\n sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);\n }\n }\n sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,\n (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);\n addr1 = sqlite3VdbeCurrentAddr(v);\n sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);\n\n /* Generate code that runs whenever the GROUP BY changes.\n ** Changes in the GROUP BY are detected by the previous code\n ** block. If there were no changes, this block is skipped.\n **\n ** This code copies current group by terms in b0,b1,b2,...\n ** over to a0,a1,a2. It then calls the output subroutine\n ** and resets the aggregate accumulator registers in preparation\n ** for the next GROUP BY batch.\n */\n sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);\n sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);\n VdbeComment((v, \"output one row\"));\n sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);\n VdbeComment((v, \"check abort flag\"));\n sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);\n VdbeComment((v, \"reset accumulator\"));\n\n /* Update the aggregate accumulators based on the content of\n ** the current row\n */\n sqlite3VdbeJumpHere(v, addr1);\n updateAccumulator(pParse, iUseFlag, &sAggInfo);\n sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);\n VdbeComment((v, \"indicate data in accumulator\"));\n\n /* End of the loop\n */\n if( groupBySort ){\n sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);\n VdbeCoverage(v);\n }else{\n sqlite3WhereEnd(pWInfo);\n sqlite3VdbeChangeToNoop(v, addrSortingIdx);\n }\n\n /* Output the final row of result\n */\n sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);\n VdbeComment((v, \"output final row\"));\n\n /* Jump over the subroutines\n */\n sqlite3VdbeGoto(v, addrEnd);\n\n /* Generate a subroutine that outputs a single row of the result\n ** set. This subroutine first looks at the iUseFlag. If iUseFlag\n ** is less than or equal to zero, the subroutine is a no-op. If\n ** the processing calls for the query to abort, this subroutine\n ** increments the iAbortFlag memory location before returning in\n ** order to signal the caller to abort.\n */\n addrSetAbort = sqlite3VdbeCurrentAddr(v);\n sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);\n VdbeComment((v, \"set abort flag\"));\n sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);\n sqlite3VdbeResolveLabel(v, addrOutputRow);\n addrOutputRow = sqlite3VdbeCurrentAddr(v);\n sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);\n VdbeCoverage(v);\n VdbeComment((v, \"Groupby result generator entry point\"));\n sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);\n finalizeAggFunctions(pParse, &sAggInfo);\n sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);\n selectInnerLoop(pParse, p, -1, &sSort,\n &sDistinct, pDest,\n addrOutputRow+1, addrSetAbort);\n sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);\n VdbeComment((v, \"end groupby result generator\"));\n\n /* Generate a subroutine that will reset the group-by accumulator\n */\n sqlite3VdbeResolveLabel(v, addrReset);\n resetAccumulator(pParse, &sAggInfo);\n sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);\n VdbeComment((v, \"indicate accumulator empty\"));\n sqlite3VdbeAddOp1(v, OP_Return, regReset);\n \n } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */\n else {\n#ifndef SQLITE_OMIT_BTREECOUNT\n Table *pTab;\n if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){\n /* If isSimpleCount() returns a pointer to a Table structure, then\n ** the SQL statement is of the form:\n **\n ** SELECT count(*) FROM \n **\n ** where the Table structure returned represents table .\n **\n ** This statement is so common that it is optimized specially. The\n ** OP_Count instruction is executed either on the intkey table that\n ** contains the data for table or on one of its indexes. It\n ** is better to execute the op on an index, as indexes are almost\n ** always spread across less pages than their corresponding tables.\n */\n const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);\n const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */\n Index *pIdx; /* Iterator variable */\n KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */\n Index *pBest = 0; /* Best index found so far */\n int iRoot = pTab->tnum; /* Root page of scanned b-tree */\n\n sqlite3CodeVerifySchema(pParse, iDb);\n sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);\n\n /* Search for the index that has the lowest scan cost.\n **\n ** (2011-04-15) Do not do a full scan of an unordered index.\n **\n ** (2013-10-03) Do not count the entries in a partial index.\n **\n ** In practice the KeyInfo structure will not be used. It is only \n ** passed to keep OP_OpenRead happy.\n */\n if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);\n for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){\n if( pIdx->bUnordered==0\n && pIdx->szIdxRowszTabRow\n && pIdx->pPartIdxWhere==0\n && (!pBest || pIdx->szIdxRowszIdxRow)\n ){\n pBest = pIdx;\n }\n }\n if( pBest ){\n iRoot = pBest->tnum;\n pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);\n }\n\n /* Open a read-only cursor, execute the OP_Count, close the cursor. */\n sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);\n if( pKeyInfo ){\n sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);\n }\n sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);\n sqlite3VdbeAddOp1(v, OP_Close, iCsr);\n explainSimpleCount(pParse, pTab, pBest);\n }else\n#endif /* SQLITE_OMIT_BTREECOUNT */\n {\n int regAcc = 0; /* \"populate accumulators\" flag */\n\n /* If there are accumulator registers but no min() or max() functions\n ** without FILTER clauses, allocate register regAcc. Register regAcc\n ** will contain 0 the first time the inner loop runs, and 1 thereafter.\n ** The code generated by updateAccumulator() uses this to ensure\n ** that the accumulator registers are (a) updated only once if\n ** there are no min() or max functions or (b) always updated for the\n ** first row visited by the aggregate, so that they are updated at\n ** least once even if the FILTER clause means the min() or max() \n ** function visits zero rows. */\n if( sAggInfo.nAccumulator ){\n for(i=0; ifuncFlags&SQLITE_FUNC_NEEDCOLL ) break;\n }\n if( i==sAggInfo.nFunc ){\n regAcc = ++pParse->nMem;\n sqlite3VdbeAddOp2(v, OP_Integer, 0, regAcc);\n }\n }\n\n /* This case runs if the aggregate has no GROUP BY clause. The\n ** processing is much simpler since there is only a single row\n ** of output.\n */\n assert( p->pGroupBy==0 );\n resetAccumulator(pParse, &sAggInfo);\n\n /* If this query is a candidate for the min/max optimization, then\n ** minMaxFlag will have been previously set to either\n ** WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX and pMinMaxOrderBy will\n ** be an appropriate ORDER BY expression for the optimization.\n */\n assert( minMaxFlag==WHERE_ORDERBY_NORMAL || pMinMaxOrderBy!=0 );\n assert( pMinMaxOrderBy==0 || pMinMaxOrderBy->nExpr==1 );\n\n SELECTTRACE(1,pParse,p,(\"WhereBegin\\n\"));\n pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMaxOrderBy,\n 0, minMaxFlag, 0);\n if( pWInfo==0 ){\n goto select_end;\n }\n updateAccumulator(pParse, regAcc, &sAggInfo);\n if( regAcc ) sqlite3VdbeAddOp2(v, OP_Integer, 1, regAcc);\n if( sqlite3WhereIsOrdered(pWInfo)>0 ){\n sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));\n VdbeComment((v, \"%s() by index\",\n (minMaxFlag==WHERE_ORDERBY_MIN?\"min\":\"max\")));\n }\n sqlite3WhereEnd(pWInfo);\n finalizeAggFunctions(pParse, &sAggInfo);\n }\n\n sSort.pOrderBy = 0;\n sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);\n selectInnerLoop(pParse, p, -1, 0, 0, \n pDest, addrEnd, addrEnd);\n }\n sqlite3VdbeResolveLabel(v, addrEnd);\n \n } /* endif aggregate query */\n\n if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){\n explainTempTable(pParse, \"DISTINCT\");\n }\n\n /* If there is an ORDER BY clause, then we need to sort the results\n ** and send them to the callback one by one.\n */\n if( sSort.pOrderBy ){\n explainTempTable(pParse,\n sSort.nOBSat>0 ? \"RIGHT PART OF ORDER BY\":\"ORDER BY\");\n assert( p->pEList==pEList );\n generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);\n }\n\n /* Jump here to skip this query\n */\n sqlite3VdbeResolveLabel(v, iEnd);\n\n /* The SELECT has been coded. If there is an error in the Parse structure,\n ** set the return code to 1. Otherwise 0. */\n rc = (pParse->nErr>0);\n\n /* Control jumps to here if an error is encountered above, or upon\n ** successful coding of the SELECT.\n */\nselect_end:\n sqlite3ExprListDelete(db, pMinMaxOrderBy);\n sqlite3DbFree(db, sAggInfo.aCol);\n sqlite3DbFree(db, sAggInfo.aFunc);\n#if SELECTTRACE_ENABLED\n SELECTTRACE(0x1,pParse,p,(\"end processing\\n\"));\n if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){\n sqlite3TreeViewSelect(0, p, 0);\n }\n#endif\n ExplainQueryPlanPop(pParse);\n return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fix a crash that could occur if a sub-select that uses both DISTINCT and window functions also used an ORDER BY that is the same as its select list.\n\nFossilOrigin-Name: bcdd66c1691955c697f3d756c2b035acfe98f6aad72e90b0021bab6e9023b3ba'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int prepare_to_clone_next_submodule(const struct cache_entry *ce,\n\t\t\t\t\t struct child_process *child,\n\t\t\t\t\t struct submodule_update_clone *suc,\n\t\t\t\t\t struct strbuf *out)\n{\n\tconst struct submodule *sub = NULL;\n\tstruct strbuf displaypath_sb = STRBUF_INIT;\n\tstruct strbuf sb = STRBUF_INIT;\n\tconst char *displaypath = NULL;\n\tint needs_cloning = 0;\n\n\tif (ce_stage(ce)) {\n\t\tif (suc->recursive_prefix)\n\t\t\tstrbuf_addf(&sb, \"%s/%s\", suc->recursive_prefix, ce->name);\n\t\telse\n\t\t\tstrbuf_addstr(&sb, ce->name);\n\t\tstrbuf_addf(out, _(\"Skipping unmerged submodule %s\"), sb.buf);\n\t\tstrbuf_addch(out, '\\n');\n\t\tgoto cleanup;\n\t}\n\n\tsub = submodule_from_path(null_sha1, ce->name);\n\n\tif (suc->recursive_prefix)\n\t\tdisplaypath = relative_path(suc->recursive_prefix,\n\t\t\t\t\t ce->name, &displaypath_sb);\n\telse\n\t\tdisplaypath = ce->name;\n\n\tif (!sub) {\n\t\tnext_submodule_warn_missing(suc, out, displaypath);\n\t\tgoto cleanup;\n\t}\n\n\tif (suc->update.type == SM_UPDATE_NONE\n\t || (suc->update.type == SM_UPDATE_UNSPECIFIED\n\t\t&& sub->update_strategy.type == SM_UPDATE_NONE)) {\n\t\tstrbuf_addf(out, _(\"Skipping submodule '%s'\"), displaypath);\n\t\tstrbuf_addch(out, '\\n');\n\t\tgoto cleanup;\n\t}\n\n\t/* Check if the submodule has been initialized. */\n\tif (!is_submodule_active(the_repository, ce->name)) {\n\t\tnext_submodule_warn_missing(suc, out, displaypath);\n\t\tgoto cleanup;\n\t}\n\n\tstrbuf_reset(&sb);\n\tstrbuf_addf(&sb, \"%s/.git\", ce->name);\n\tneeds_cloning = !file_exists(sb.buf);\n\n\tstrbuf_reset(&sb);\n\tstrbuf_addf(&sb, \"%06o %s %d %d\\t%s\\n\", ce->ce_mode,\n\t\t\toid_to_hex(&ce->oid), ce_stage(ce),\n\t\t\tneeds_cloning, ce->name);\n\tstring_list_append(&suc->projectlines, sb.buf);\n\n\tif (!needs_cloning)\n\t\tgoto cleanup;\n\n\tchild->git_cmd = 1;\n\tchild->no_stdin = 1;\n\tchild->stdout_to_stderr = 1;\n\tchild->err = -1;\n\targv_array_push(&child->args, \"submodule--helper\");\n\targv_array_push(&child->args, \"clone\");\n\tif (suc->progress)\n\t\targv_array_push(&child->args, \"--progress\");\n\tif (suc->quiet)\n\t\targv_array_push(&child->args, \"--quiet\");\n\tif (suc->prefix)\n\t\targv_array_pushl(&child->args, \"--prefix\", suc->prefix, NULL);\n\tif (suc->recommend_shallow && sub->recommend_shallow == 1)\n\t\targv_array_push(&child->args, \"--depth=1\");\n\targv_array_pushl(&child->args, \"--path\", sub->path, NULL);\n\targv_array_pushl(&child->args, \"--name\", sub->name, NULL);\n\targv_array_pushl(&child->args, \"--url\", sub->url, NULL);\n\tif (suc->references.nr) {\n\t\tstruct string_list_item *item;\n\t\tfor_each_string_list_item(item, &suc->references)\n\t\t\targv_array_pushl(&child->args, \"--reference\", item->string, NULL);\n\t}\n\tif (suc->depth)\n\t\targv_array_push(&child->args, suc->depth);\n\ncleanup:\n\tstrbuf_reset(&displaypath_sb);\n\tstrbuf_reset(&sb);\n\n\treturn needs_cloning;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'clone --recurse-submodules: prevent name squatting on Windows\n\nIn addition to preventing `.git` from being tracked by Git, on Windows\nwe also have to prevent `git~1` from being tracked, as the default NTFS\nshort name (also known as the \"8.3 filename\") for the file name `.git`\nis `git~1`, otherwise it would be possible for malicious repositories to\nwrite directly into the `.git/` directory, e.g. a `post-checkout` hook\nthat would then be executed _during_ a recursive clone.\n\nWhen we implemented appropriate protections in 2b4c6efc821 (read-cache:\noptionally disallow NTFS .git variants, 2014-12-16), we had analyzed\ncarefully that the `.git` directory or file would be guaranteed to be\nthe first directory entry to be written. Otherwise it would be possible\ne.g. for a file named `..git` to be assigned the short name `git~1` and\nsubsequently, the short name generated for `.git` would be `git~2`. Or\n`git~3`. Or even `~9999999` (for a detailed explanation of the lengths\nwe have to go to protect `.gitmodules`, see the commit message of\ne7cb0b4455c (is_ntfs_dotgit: match other .git files, 2018-05-11)).\n\nHowever, by exploiting two issues (that will be addressed in a related\npatch series close by), it is currently possible to clone a submodule\ninto a non-empty directory:\n\n- On Windows, file names cannot end in a space or a period (for\n historical reasons: the period separating the base name from the file\n extension was not actually written to disk, and the base name/file\n extension was space-padded to the full 8/3 characters, respectively).\n Helpfully, when creating a directory under the name, say, `sub.`, that\n trailing period is trimmed automatically and the actual name on disk\n is `sub`.\n\n This means that while Git thinks that the submodule names `sub` and\n `sub.` are different, they both access `.git/modules/sub/`.\n\n- While the backslash character is a valid file name character on Linux,\n it is not so on Windows. As Git tries to be cross-platform, it\n therefore allows backslash characters in the file names stored in tree\n objects.\n\n Which means that it is totally possible that a submodule `c` sits next\n to a file `c\\..git`, and on Windows, during recursive clone a file\n called `..git` will be written into `c/`, of course _before_ the\n submodule is cloned.\n\nNote that the actual exploit is not quite as simple as having a\nsubmodule `c` next to a file `c\\..git`, as we have to make sure that the\ndirectory `.git/modules/b` already exists when the submodule is checked\nout, otherwise a different code path is taken in `module_clone()` that\ndoes _not_ allow a non-empty submodule directory to exist already.\n\nEven if we will address both issues nearby (the next commit will\ndisallow backslash characters in tree entries' file names on Windows,\nand another patch will disallow creating directories/files with trailing\nspaces or periods), it is a wise idea to defend in depth against this\nsort of attack vector: when submodules are cloned recursively, we now\n_require_ the directory to be empty, addressing CVE-2019-1349.\n\nNote: the code path we patch is shared with the code path of `git\nsubmodule update --init`, which must not expect, in general, that the\ndirectory is empty. Hence we have to introduce the new option\n`--force-init` and hand it all the way down from `git submodule` to the\nactual `git submodule--helper` process that performs the initial clone.\n\nReported-by: Nicolas Joly \nSigned-off-by: Johannes Schindelin '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int lg2ff_init(struct hid_device *hid)\n{\n\tstruct lg2ff_device *lg2ff;\n\tstruct hid_report *report;\n\tstruct hid_input *hidinput = list_entry(hid->inputs.next,\n\t\t\t\t\t\tstruct hid_input, list);\n\tstruct input_dev *dev = hidinput->input;\n\tint error;\n\n\t/* Check that the report looks ok */\n\treport = hid_validate_values(hid, HID_OUTPUT_REPORT, 0, 0, 7);\n\tif (!report)\n\t\treturn -ENODEV;\n\n\tlg2ff = kmalloc(sizeof(struct lg2ff_device), GFP_KERNEL);\n\tif (!lg2ff)\n\t\treturn -ENOMEM;\n\n\tset_bit(FF_RUMBLE, dev->ffbit);\n\n\terror = input_ff_create_memless(dev, lg2ff, play_effect);\n\tif (error) {\n\t\tkfree(lg2ff);\n\t\treturn error;\n\t}\n\n\tlg2ff->report = report;\n\treport->field[0]->value[0] = 0xf3;\n\treport->field[0]->value[1] = 0x00;\n\treport->field[0]->value[2] = 0x00;\n\treport->field[0]->value[3] = 0x00;\n\treport->field[0]->value[4] = 0x00;\n\treport->field[0]->value[5] = 0x00;\n\treport->field[0]->value[6] = 0x00;\n\n\thid_hw_request(hid, report, HID_REQ_SET_REPORT);\n\n\thid_info(hid, \"Force feedback for Logitech variant 2 rumble devices by Anssi Hannula \\n\");\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'HID: Fix assumption that devices have inputs\n\nThe syzbot fuzzer found a slab-out-of-bounds write bug in the hid-gaff\ndriver. The problem is caused by the driver's assumption that the\ndevice must have an input report. While this will be true for all\nnormal HID input devices, a suitably malicious device can violate the\nassumption.\n\nThe same assumption is present in over a dozen other HID drivers.\nThis patch fixes them by checking that the list of hid_inputs for the\nhid_device is nonempty before allowing it to be used.\n\nReported-and-tested-by: syzbot+403741a091bf41d4ae79@syzkaller.appspotmail.com\nSigned-off-by: Alan Stern \nCC: \nSigned-off-by: Benjamin Tissoires '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int tmff_init(struct hid_device *hid, const signed short *ff_bits)\n{\n\tstruct tmff_device *tmff;\n\tstruct hid_report *report;\n\tstruct list_head *report_list;\n\tstruct hid_input *hidinput = list_entry(hid->inputs.next,\n\t\t\t\t\t\t\tstruct hid_input, list);\n\tstruct input_dev *input_dev = hidinput->input;\n\tint error;\n\tint i;\n\n\ttmff = kzalloc(sizeof(struct tmff_device), GFP_KERNEL);\n\tif (!tmff)\n\t\treturn -ENOMEM;\n\n\t/* Find the report to use */\n\treport_list = &hid->report_enum[HID_OUTPUT_REPORT].report_list;\n\tlist_for_each_entry(report, report_list, list) {\n\t\tint fieldnum;\n\n\t\tfor (fieldnum = 0; fieldnum < report->maxfield; ++fieldnum) {\n\t\t\tstruct hid_field *field = report->field[fieldnum];\n\n\t\t\tif (field->maxusage <= 0)\n\t\t\t\tcontinue;\n\n\t\t\tswitch (field->usage[0].hid) {\n\t\t\tcase THRUSTMASTER_USAGE_FF:\n\t\t\t\tif (field->report_count < 2) {\n\t\t\t\t\thid_warn(hid, \"ignoring FF field with report_count < 2\\n\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (field->logical_maximum ==\n\t\t\t\t\t\tfield->logical_minimum) {\n\t\t\t\t\thid_warn(hid, \"ignoring FF field with logical_maximum == logical_minimum\\n\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (tmff->report && tmff->report != report) {\n\t\t\t\t\thid_warn(hid, \"ignoring FF field in other report\\n\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (tmff->ff_field && tmff->ff_field != field) {\n\t\t\t\t\thid_warn(hid, \"ignoring duplicate FF field\\n\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\ttmff->report = report;\n\t\t\t\ttmff->ff_field = field;\n\n\t\t\t\tfor (i = 0; ff_bits[i] >= 0; i++)\n\t\t\t\t\tset_bit(ff_bits[i], input_dev->ffbit);\n\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\thid_warn(hid, \"ignoring unknown output usage %08x\\n\",\n\t\t\t\t\t field->usage[0].hid);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!tmff->report) {\n\t\thid_err(hid, \"can't find FF field in output reports\\n\");\n\t\terror = -ENODEV;\n\t\tgoto fail;\n\t}\n\n\terror = input_ff_create_memless(input_dev, tmff, tmff_play);\n\tif (error)\n\t\tgoto fail;\n\n\thid_info(hid, \"force feedback for ThrustMaster devices by Zinx Verituse \\n\");\n\treturn 0;\n\nfail:\n\tkfree(tmff);\n\treturn error;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'HID: Fix assumption that devices have inputs\n\nThe syzbot fuzzer found a slab-out-of-bounds write bug in the hid-gaff\ndriver. The problem is caused by the driver's assumption that the\ndevice must have an input report. While this will be true for all\nnormal HID input devices, a suitably malicious device can violate the\nassumption.\n\nThe same assumption is present in over a dozen other HID drivers.\nThis patch fixes them by checking that the list of hid_inputs for the\nhid_device is nonempty before allowing it to be used.\n\nReported-and-tested-by: syzbot+403741a091bf41d4ae79@syzkaller.appspotmail.com\nSigned-off-by: Alan Stern \nCC: \nSigned-off-by: Benjamin Tissoires '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int fts3IncrmergeLoad(\n Fts3Table *p, /* Fts3 table handle */\n sqlite3_int64 iAbsLevel, /* Absolute level of input segments */\n int iIdx, /* Index of candidate output segment */\n const char *zKey, /* First key to write */\n int nKey, /* Number of bytes in nKey */\n IncrmergeWriter *pWriter /* Populate this object */\n){\n int rc; /* Return code */\n sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */\n\n rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);\n if( rc==SQLITE_OK ){\n sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */\n sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */\n sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */\n const char *aRoot = 0; /* Pointer to %_segdir.root buffer */\n int nRoot = 0; /* Size of aRoot[] in bytes */\n int rc2; /* Return code from sqlite3_reset() */\n int bAppendable = 0; /* Set to true if segment is appendable */\n\n /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */\n sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);\n sqlite3_bind_int(pSelect, 2, iIdx);\n if( sqlite3_step(pSelect)==SQLITE_ROW ){\n iStart = sqlite3_column_int64(pSelect, 1);\n iLeafEnd = sqlite3_column_int64(pSelect, 2);\n fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);\n if( pWriter->nLeafData<0 ){\n pWriter->nLeafData = pWriter->nLeafData * -1;\n }\n pWriter->bNoLeafData = (pWriter->nLeafData==0);\n nRoot = sqlite3_column_bytes(pSelect, 4);\n aRoot = sqlite3_column_blob(pSelect, 4);\n }else{\n return sqlite3_reset(pSelect);\n }\n\n /* Check for the zero-length marker in the %_segments table */\n rc = fts3IsAppendable(p, iEnd, &bAppendable);\n\n /* Check that zKey/nKey is larger than the largest key the candidate */\n if( rc==SQLITE_OK && bAppendable ){\n char *aLeaf = 0;\n int nLeaf = 0;\n\n rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);\n if( rc==SQLITE_OK ){\n NodeReader reader;\n for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);\n rc==SQLITE_OK && reader.aNode;\n rc = nodeReaderNext(&reader)\n ){\n assert( reader.aNode );\n }\n if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){\n bAppendable = 0;\n }\n nodeReaderRelease(&reader);\n }\n sqlite3_free(aLeaf);\n }\n\n if( rc==SQLITE_OK && bAppendable ){\n /* It is possible to append to this segment. Set up the IncrmergeWriter\n ** object to do so. */\n int i;\n int nHeight = (int)aRoot[0];\n NodeWriter *pNode;\n\n pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;\n pWriter->iStart = iStart;\n pWriter->iEnd = iEnd;\n pWriter->iAbsLevel = iAbsLevel;\n pWriter->iIdx = iIdx;\n\n for(i=nHeight+1; iaNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;\n }\n\n pNode = &pWriter->aNodeWriter[nHeight];\n pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;\n blobGrowBuffer(&pNode->block, \n MAX(nRoot, p->nNodeSize)+FTS3_NODE_PADDING, &rc\n );\n if( rc==SQLITE_OK ){\n memcpy(pNode->block.a, aRoot, nRoot);\n pNode->block.n = nRoot;\n memset(&pNode->block.a[nRoot], 0, FTS3_NODE_PADDING);\n }\n\n for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){\n NodeReader reader;\n pNode = &pWriter->aNodeWriter[i];\n\n if( pNode->block.a){\n rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);\n while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);\n blobGrowBuffer(&pNode->key, reader.term.n, &rc);\n if( rc==SQLITE_OK ){\n memcpy(pNode->key.a, reader.term.a, reader.term.n);\n pNode->key.n = reader.term.n;\n if( i>0 ){\n char *aBlock = 0;\n int nBlock = 0;\n pNode = &pWriter->aNodeWriter[i-1];\n pNode->iBlock = reader.iChild;\n rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);\n blobGrowBuffer(&pNode->block, \n MAX(nBlock, p->nNodeSize)+FTS3_NODE_PADDING, &rc\n );\n if( rc==SQLITE_OK ){\n memcpy(pNode->block.a, aBlock, nBlock);\n pNode->block.n = nBlock;\n memset(&pNode->block.a[nBlock], 0, FTS3_NODE_PADDING);\n }\n sqlite3_free(aBlock);\n }\n }\n }\n nodeReaderRelease(&reader);\n }\n }\n\n rc2 = sqlite3_reset(pSelect);\n if( rc==SQLITE_OK ) rc = rc2;\n }\n\n return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'More improvements to shadow table corruption detection in FTS3.\n\nFossilOrigin-Name: 51525f9c3235967bc00a090e84c70a6400698c897aa4742e817121c725b8c99d'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int fts3IncrmergePush(\n Fts3Table *p, /* Fts3 table handle */\n IncrmergeWriter *pWriter, /* Writer object */\n const char *zTerm, /* Term to write to internal node */\n int nTerm /* Bytes at zTerm */\n){\n sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;\n int iLayer;\n\n assert( nTerm>0 );\n for(iLayer=1; ALWAYS(iLayeraNodeWriter[iLayer];\n int rc = SQLITE_OK;\n int nPrefix;\n int nSuffix;\n int nSpace;\n\n /* Figure out how much space the key will consume if it is written to\n ** the current node of layer iLayer. Due to the prefix compression, \n ** the space required changes depending on which node the key is to\n ** be added to. */\n nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);\n nSuffix = nTerm - nPrefix;\n if( NEVER(nSuffix<=0) ) return FTS_CORRUPT_VTAB;\n nSpace = sqlite3Fts3VarintLen(nPrefix);\n nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;\n\n if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){ \n /* If the current node of layer iLayer contains zero keys, or if adding\n ** the key to it will not cause it to grow to larger than nNodeSize \n ** bytes in size, write the key here. */\n\n Blob *pBlk = &pNode->block;\n if( pBlk->n==0 ){\n blobGrowBuffer(pBlk, p->nNodeSize, &rc);\n if( rc==SQLITE_OK ){\n pBlk->a[0] = (char)iLayer;\n pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);\n }\n }\n blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);\n blobGrowBuffer(&pNode->key, nTerm, &rc);\n\n if( rc==SQLITE_OK ){\n if( pNode->key.n ){\n pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);\n }\n pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);\n memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);\n pBlk->n += nSuffix;\n\n memcpy(pNode->key.a, zTerm, nTerm);\n pNode->key.n = nTerm;\n }\n }else{\n /* Otherwise, flush the current node of layer iLayer to disk.\n ** Then allocate a new, empty sibling node. The key will be written\n ** into the parent of this node. */\n rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);\n\n assert( pNode->block.nAlloc>=p->nNodeSize );\n pNode->block.a[0] = (char)iLayer;\n pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);\n\n iNextPtr = pNode->iBlock;\n pNode->iBlock++;\n pNode->key.n = 0;\n }\n\n if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;\n iPtr = iNextPtr;\n }\n\n assert( 0 );\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Remove a reachable NEVER() in FTS3.\n\nFossilOrigin-Name: 8bd75bf636f72f32d66c6c38e1918f27daf2f13290f00a001f41d50838bbda47'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int renameUnmapSelectCb(Walker *pWalker, Select *p){\n Parse *pParse = pWalker->pParse;\n int i;\n if( pParse->nErr ) return WRC_Abort;\n if( ALWAYS(p->pEList) ){\n ExprList *pList = p->pEList;\n for(i=0; inExpr; i++){\n if( pList->a[i].zName ){\n sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zName);\n }\n }\n }\n if( ALWAYS(p->pSrc) ){ /* Every Select as a SrcList, even if it is empty */\n SrcList *pSrc = p->pSrc;\n for(i=0; inSrc; i++){\n sqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName);\n }\n }\n\n renameWalkWith(pWalker, p);\n return WRC_Continue;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-674', 'CWE-787'], 'message': 'Avoid infinite recursion in the ALTER TABLE code when a view contains an unused CTE that references, directly or indirectly, the view itself.\n\nFossilOrigin-Name: 1d2e53a39b87e364685e21de137655b6eee725e4c6d27fc90865072d7c5892b5'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void mcba_usb_disconnect(struct usb_interface *intf)\n{\n\tstruct mcba_priv *priv = usb_get_intfdata(intf);\n\n\tusb_set_intfdata(intf, NULL);\n\n\tnetdev_info(priv->netdev, \"device disconnected\\n\");\n\n\tunregister_candev(priv->netdev);\n\tfree_candev(priv->netdev);\n\n\tmcba_urb_unlink(priv);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'can: mcba_usb: fix use-after-free on disconnect\n\nThe driver was accessing its driver data after having freed it.\n\nFixes: 51f3baad7de9 (\"can: mcba_usb: Add support for Microchip CAN BUS Analyzer\")\nCc: stable # 4.12\nCc: Remigiusz Ko\u0142\u0142\u0105taj \nReported-by: syzbot+e29b17e5042bbc56fae9@syzkaller.appspotmail.com\nSigned-off-by: Johan Hovold \nSigned-off-by: Marc Kleine-Budde '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline int fpregs_state_valid(struct fpu *fpu, unsigned int cpu)\n{\n\treturn fpu == this_cpu_read_stable(fpu_fpregs_owner_ctx) && cpu == fpu->last_cpu;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-732', 'CWE-787'], 'message': 'x86/fpu: Don't cache access to fpu_fpregs_owner_ctx\n\nThe state/owner of the FPU is saved to fpu_fpregs_owner_ctx by pointing\nto the context that is currently loaded. It never changed during the\nlifetime of a task - it remained stable/constant.\n\nAfter deferred FPU registers loading until return to userland was\nimplemented, the content of fpu_fpregs_owner_ctx may change during\npreemption and must not be cached.\n\nThis went unnoticed for some time and was now noticed, in particular\nsince gcc 9 is caching that load in copy_fpstate_to_sigframe() and\nreusing it in the retry loop:\n\n copy_fpstate_to_sigframe()\n load fpu_fpregs_owner_ctx and save on stack\n fpregs_lock()\n copy_fpregs_to_sigframe() /* failed */\n fpregs_unlock()\n *** PREEMPTION, another uses FPU, changes fpu_fpregs_owner_ctx ***\n\n fault_in_pages_writeable() /* succeed, retry */\n\n fpregs_lock()\n\t__fpregs_load_activate()\n\t fpregs_state_valid() /* uses fpu_fpregs_owner_ctx from stack */\n copy_fpregs_to_sigframe() /* succeeds, random FPU content */\n\nThis is a comparison of the assembly produced by gcc 9, without vs with this\npatch:\n\n| # arch/x86/kernel/fpu/signal.c:173: if (!access_ok(buf, size))\n| cmpq %rdx, %rax # tmp183, _4\n| jb .L190 #,\n|-# arch/x86/include/asm/fpu/internal.h:512: return fpu == this_cpu_read_stable(fpu_fpregs_owner_ctx) && cpu == fpu->last_cpu;\n|-#APP\n|-# 512 \"arch/x86/include/asm/fpu/internal.h\" 1\n|- movq %gs:fpu_fpregs_owner_ctx,%rax #, pfo_ret__\n|-# 0 \"\" 2\n|-#NO_APP\n|- movq %rax, -88(%rbp) # pfo_ret__, %sfp\n\u2026\n|-# arch/x86/include/asm/fpu/internal.h:512: return fpu == this_cpu_read_stable(fpu_fpregs_owner_ctx) && cpu == fpu->last_cpu;\n|- movq -88(%rbp), %rcx # %sfp, pfo_ret__\n|- cmpq %rcx, -64(%rbp) # pfo_ret__, %sfp\n|+# arch/x86/include/asm/fpu/internal.h:512: return fpu == this_cpu_read(fpu_fpregs_owner_ctx) && cpu == fpu->last_cpu;\n|+#APP\n|+# 512 \"arch/x86/include/asm/fpu/internal.h\" 1\n|+ movq %gs:fpu_fpregs_owner_ctx(%rip),%rax # fpu_fpregs_owner_ctx, pfo_ret__\n|+# 0 \"\" 2\n|+# arch/x86/include/asm/fpu/internal.h:512: return fpu == this_cpu_read(fpu_fpregs_owner_ctx) && cpu == fpu->last_cpu;\n|+#NO_APP\n|+ cmpq %rax, -64(%rbp) # pfo_ret__, %sfp\n\nUse this_cpu_read() instead this_cpu_read_stable() to avoid caching of\nfpu_fpregs_owner_ctx during preemption points.\n\nThe Fixes: tag points to the commit where deferred FPU loading was\nadded. Since this commit, the compiler is no longer allowed to move the\nload of fpu_fpregs_owner_ctx somewhere else / outside of the locked\nsection. A task preemption will change its value and stale content will\nbe observed.\n\n [ bp: Massage. ]\n\nDebugged-by: Austin Clements \nDebugged-by: David Chase \nDebugged-by: Ian Lance Taylor \nFixes: 5f409e20b7945 (\"x86/fpu: Defer FPU state load until return to userspace\")\nSigned-off-by: Sebastian Andrzej Siewior \nSigned-off-by: Borislav Petkov \nReviewed-by: Rik van Riel \nTested-by: Borislav Petkov \nCc: Aubrey Li \nCc: Austin Clements \nCc: Barret Rhoden \nCc: Dave Hansen \nCc: David Chase \nCc: \"H. Peter Anvin\" \nCc: ian@airs.com\nCc: Ingo Molnar \nCc: Josh Bleecher Snyder \nCc: Thomas Gleixner \nCc: x86-ml \nLink: https://lkml.kernel.org/r/20191128085306.hxfa2o3knqtu4wfn@linutronix.de\nLink: https://bugzilla.kernel.org/show_bug.cgi?id=205663'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){\n Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);\n if( p ){\n struct SrcList_item *pItem = &pSrc->a[iSrc];\n p->y.pTab = pItem->pTab;\n p->iTable = pItem->iCursor;\n if( p->y.pTab->iPKey==iCol ){\n p->iColumn = -1;\n }else{\n p->iColumn = (ynVar)iCol;\n testcase( iCol==BMS );\n testcase( iCol==BMS-1 );\n pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);\n }\n }\n return p;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-754'], 'message': 'Ensure that the SrcList_item.colUsed field is set correctly (set to have a\n1 for all columns of the table) when a generated column appears in the USING\nclause of a join.\n\nFossilOrigin-Name: 1923efb283e8840fa7436eb20b9d2174ef7cace1690d3b97b572a0db2048b8e3'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int codeCompare(\n Parse *pParse, /* The parsing (and code generating) context */\n Expr *pLeft, /* The left operand */\n Expr *pRight, /* The right operand */\n int opcode, /* The comparison opcode */\n int in1, int in2, /* Register holding operands */\n int dest, /* Jump here if true. */\n int jumpIfNull, /* If true, jump if either operand is NULL */\n int isCommuted /* The comparison has been commuted */\n){\n int p5;\n int addr;\n CollSeq *p4;\n\n if( isCommuted ){\n p4 = sqlite3BinaryCompareCollSeq(pParse, pRight, pLeft);\n }else{\n p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);\n }\n p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);\n addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,\n (void*)p4, P4_COLLSEQ);\n sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);\n return addr;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-755'], 'message': 'When an error occurs while rewriting the parser tree for window functions\nin the sqlite3WindowRewrite() routine, make sure that pParse->nErr is set,\nand make sure that this shuts down any subsequent code generation that might\ndepend on the transformations that were implemented. This fixes a problem\ndiscovered by the Yongheng and Rui fuzzer.\n\nFossilOrigin-Name: e2bddcd4c55ba3cbe0130332679ff4b048630d0ced9a8899982edb5a3569ba7f'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: uint64 WriteFrame(IMkvWriter* writer, const Frame* const frame,\n Cluster* cluster) {\n if (!writer || !frame || !frame->IsValid() || !cluster ||\n !cluster->timecode_scale())\n return 0;\n\n // Technically the timecode for a block can be less than the\n // timecode for the cluster itself (remember that block timecode\n // is a signed, 16-bit integer). However, as a simplification we\n // only permit non-negative cluster-relative timecodes for blocks.\n const int64 relative_timecode = cluster->GetRelativeTimecode(\n frame->timestamp() / cluster->timecode_scale());\n if (relative_timecode < 0 || relative_timecode > kMaxBlockTimecode)\n return 0;\n\n return frame->CanBeSimpleBlock() ?\n WriteSimpleBlock(writer, frame, relative_timecode) :\n WriteBlock(writer, frame, relative_timecode,\n cluster->timecode_scale());\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'update libwebm to libwebm-1.0.0.27-358-gdbf1d10\n\nchangelog:\nhttps://chromium.googlesource.com/webm/libwebm/+log/libwebm-1.0.0.27-351-g9f23fbc..libwebm-1.0.0.27-358-gdbf1d10\n\nChange-Id: I28a6b3ae02a53fb1f2029eee11e9449afb94c8e3'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: IMkvReader::~IMkvReader() {} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'update libwebm to libwebm-1.0.0.27-352-g6ab9fcf\n\nhttps://chromium.googlesource.com/webm/libwebm/+log/af81f26..6ab9fcf\n\nChange-Id: I9d56e1fbaba9b96404b4fbabefddc1a85b79c25d'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: exif_data_load_data_thumbnail (ExifData *data, const unsigned char *d,\n\t\t\t unsigned int ds, ExifLong o, ExifLong s)\n{\n\t/* Sanity checks */\n\tif ((o + s < o) || (o + s < s) || (o + s > ds) || (o > ds)) {\n\t\texif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, \"ExifData\",\n\t\t\t \"Bogus thumbnail offset (%u) or size (%u).\",\n\t\t\t o, s);\n\t\treturn;\n\t}\n\n\tif (data->data) \n\t\texif_mem_free (data->priv->mem, data->data);\n\tif (!(data->data = exif_data_alloc (data, s))) {\n\t\tEXIF_LOG_NO_MEMORY (data->priv->log, \"ExifData\", s);\n\t\tdata->size = 0;\n\t\treturn;\n\t}\n\tdata->size = s;\n\tmemcpy (data->data, d + o, s);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190', 'CWE-787'], 'message': 'fix CVE-2019-9278\n\navoid the use of unsafe integer overflow checking constructs (unsigned integer operations cannot overflow, so \"u1 + u2 > u1\" can be optimized away)\n\ncheck for the actual sizes, which should also handle the overflows\ndocument other places google patched, but do not seem relevant due to other restrictions\n\nfixes https://github.com/libexif/libexif/issues/26'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int expandrow(UINT8* dest, UINT8* src, int n, int z)\n{\n UINT8 pixel, count;\n\n for (;n > 0; n--)\n {\n pixel = *src++;\n if (n == 1 && pixel != 0)\n return n;\n count = pixel & RLE_MAX_RUN;\n if (!count)\n return count;\n if (pixel & RLE_COPY_FLAG) {\n while(count--) {\n *dest = *src++;\n dest += z;\n }\n\n }\n else {\n pixel = *src++;\n while (count--) {\n *dest = pixel;\n dest += z;\n }\n }\n\n }\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'Catch SGI buffer overruns'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void SFDGetSpiros(FILE *sfd,SplineSet *cur) {\n int ch;\n spiro_cp cp;\n\n ch = nlgetc(sfd);\t\t/* S */\n ch = nlgetc(sfd);\t\t/* p */\n ch = nlgetc(sfd);\t\t/* i */\n ch = nlgetc(sfd);\t\t/* r */\n ch = nlgetc(sfd);\t\t/* o */\n while ( fscanf(sfd,\"%lg %lg %c\", &cp.x, &cp.y, &cp.ty )==3 ) {\n\tif ( cur!=NULL ) {\n\t if ( cur->spiro_cnt>=cur->spiro_max )\n\t\tcur->spiros = realloc(cur->spiros,(cur->spiro_max+=10)*sizeof(spiro_cp));\n\t cur->spiros[cur->spiro_cnt++] = cp;\n\t}\n }\n if ( cur!=NULL && (cur->spiros[cur->spiro_cnt-1].ty&0x7f)!=SPIRO_END ) {\n\tif ( cur->spiro_cnt>=cur->spiro_max )\n\t cur->spiros = realloc(cur->spiros,(cur->spiro_max+=1)*sizeof(spiro_cp));\n\tmemset(&cur->spiros[cur->spiro_cnt],0,sizeof(spiro_cp));\n\tcur->spiros[cur->spiro_cnt++].ty = SPIRO_END;\n }\n ch = nlgetc(sfd);\n if ( ch=='E' ) {\n\tch = nlgetc(sfd);\t\t/* n */\n\tch = nlgetc(sfd);\t\t/* d */\n\tch = nlgetc(sfd);\t\t/* S */\n\tch = nlgetc(sfd);\t\t/* p */\n\tch = nlgetc(sfd);\t\t/* i */\n\tch = nlgetc(sfd);\t\t/* r */\n\tch = nlgetc(sfd);\t\t/* o */\n } else\n\tungetc(ch,sfd);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Fix for #4084 Use-after-free (heap) in the SFD_GetFontMetaData() function\nFix for #4086 NULL pointer dereference in the SFDGetSpiros() function\nFix for #4088 NULL pointer dereference in the SFD_AssignLookups() function\nAdd empty sf->fontname string if it isn't set, fixing #4089 #4090 and many\n other potential issues (many downstream calls to strlen() on the value).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void e2fsck_rehash_directories(e2fsck_t ctx)\n{\n\tstruct problem_context\tpctx;\n#ifdef RESOURCE_TRACK\n\tstruct resource_track\trtrack;\n#endif\n\tstruct dir_info\t\t*dir;\n\text2_u32_iterate \titer;\n\tstruct dir_info_iter *\tdirinfo_iter = 0;\n\text2_ino_t\t\tino;\n\terrcode_t\t\tretval;\n\tint\t\t\tcur, max, all_dirs, first = 1;\n\n\tinit_resource_track(&rtrack, ctx->fs->io);\n\tall_dirs = ctx->options & E2F_OPT_COMPRESS_DIRS;\n\n\tif (!ctx->dirs_to_hash && !all_dirs)\n\t\treturn;\n\n\t(void) e2fsck_get_lost_and_found(ctx, 0);\n\n\tclear_problem_context(&pctx);\n\n\tcur = 0;\n\tif (all_dirs) {\n\t\tdirinfo_iter = e2fsck_dir_info_iter_begin(ctx);\n\t\tmax = e2fsck_get_num_dirinfo(ctx);\n\t} else {\n\t\tretval = ext2fs_u32_list_iterate_begin(ctx->dirs_to_hash,\n\t\t\t\t\t\t &iter);\n\t\tif (retval) {\n\t\t\tpctx.errcode = retval;\n\t\t\tfix_problem(ctx, PR_3A_OPTIMIZE_ITER, &pctx);\n\t\t\treturn;\n\t\t}\n\t\tmax = ext2fs_u32_list_count(ctx->dirs_to_hash);\n\t}\n\twhile (1) {\n\t\tif (all_dirs) {\n\t\t\tif ((dir = e2fsck_dir_info_iter(ctx,\n\t\t\t\t\t\t\tdirinfo_iter)) == 0)\n\t\t\t\tbreak;\n\t\t\tino = dir->ino;\n\t\t} else {\n\t\t\tif (!ext2fs_u32_list_iterate(iter, &ino))\n\t\t\t\tbreak;\n\t\t}\n\n\t\tpctx.dir = ino;\n\t\tif (first) {\n\t\t\tfix_problem(ctx, PR_3A_PASS_HEADER, &pctx);\n\t\t\tfirst = 0;\n\t\t}\n#if 0\n\t\tfix_problem(ctx, PR_3A_OPTIMIZE_DIR, &pctx);\n#endif\n\t\tpctx.errcode = e2fsck_rehash_dir(ctx, ino, &pctx);\n\t\tif (pctx.errcode) {\n\t\t\tend_problem_latch(ctx, PR_LATCH_OPTIMIZE_DIR);\n\t\t\tfix_problem(ctx, PR_3A_OPTIMIZE_DIR_ERR, &pctx);\n\t\t}\n\t\tif (ctx->progress && !ctx->progress_fd)\n\t\t\te2fsck_simple_progress(ctx, \"Rebuilding directory\",\n\t\t\t 100.0 * (float) (++cur) / (float) max, ino);\n\t}\n\tend_problem_latch(ctx, PR_LATCH_OPTIMIZE_DIR);\n\tif (all_dirs)\n\t\te2fsck_dir_info_iter_end(ctx, dirinfo_iter);\n\telse\n\t\text2fs_u32_list_iterate_end(iter);\n\n\tif (ctx->dirs_to_hash)\n\t\text2fs_u32_list_free(ctx->dirs_to_hash);\n\tctx->dirs_to_hash = 0;\n\n\tprint_resource_track(ctx, \"Pass 3A\", &rtrack, ctx->fs->io);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'e2fsck: don't try to rehash a deleted directory\n\nIf directory has been deleted in pass1[bcd] processing, then we\nshouldn't try to rehash the directory in pass 3a when we try to\nrehash/reoptimize directories.\n\nSigned-off-by: Theodore Ts'o '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void reposition(int pos) { ptr = start + pos; } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-787'], 'message': 'Use size_t for lengths in stream objects\n\nProvides safety against them accidentally becoming negative because\nof bugs in the calculations.\n\nAlso does the same to CharArray and friends as they were strongly\nconnection to the stream objects.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: inline void skip(int bytes) {\n while (bytes > 0) {\n int n = check(1, bytes);\n ptr += n;\n bytes -= n;\n }\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-787'], 'message': 'Use size_t for lengths in stream objects\n\nProvides safety against them accidentally becoming negative because\nof bugs in the calculations.\n\nAlso does the same to CharArray and friends as they were strongly\nconnection to the stream objects.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void tftp_handle_rrq(Slirp *slirp, struct sockaddr_storage *srcsas,\n struct tftp_t *tp, int pktlen)\n{\n struct tftp_session *spt;\n int s, k;\n size_t prefix_len;\n char *req_fname;\n const char *option_name[2];\n uint32_t option_value[2];\n int nb_options = 0;\n\n /* check if a session already exists and if so terminate it */\n s = tftp_session_find(slirp, srcsas, tp);\n if (s >= 0) {\n tftp_session_terminate(&slirp->tftp_sessions[s]);\n }\n\n s = tftp_session_allocate(slirp, srcsas, tp);\n\n if (s < 0) {\n return;\n }\n\n spt = &slirp->tftp_sessions[s];\n\n /* unspecified prefix means service disabled */\n if (!slirp->tftp_prefix) {\n tftp_send_error(spt, 2, \"Access violation\", tp);\n return;\n }\n\n /* skip header fields */\n k = 0;\n pktlen -= offsetof(struct tftp_t, x.tp_buf);\n\n /* prepend tftp_prefix */\n prefix_len = strlen(slirp->tftp_prefix);\n spt->filename = g_malloc(prefix_len + TFTP_FILENAME_MAX + 2);\n memcpy(spt->filename, slirp->tftp_prefix, prefix_len);\n spt->filename[prefix_len] = '/';\n\n /* get name */\n req_fname = spt->filename + prefix_len + 1;\n\n while (1) {\n if (k >= TFTP_FILENAME_MAX || k >= pktlen) {\n tftp_send_error(spt, 2, \"Access violation\", tp);\n return;\n }\n req_fname[k] = tp->x.tp_buf[k];\n if (req_fname[k++] == '\\0') {\n break;\n }\n }\n\n DEBUG_TFTP(\"tftp rrq file: %s\", req_fname);\n\n /* check mode */\n if ((pktlen - k) < 6) {\n tftp_send_error(spt, 2, \"Access violation\", tp);\n return;\n }\n\n if (strcasecmp(&tp->x.tp_buf[k], \"octet\") != 0) {\n tftp_send_error(spt, 4, \"Unsupported transfer mode\", tp);\n return;\n }\n\n k += 6; /* skipping octet */\n\n /* do sanity checks on the filename */\n if (!strncmp(req_fname, \"../\", 3) ||\n req_fname[strlen(req_fname) - 1] == '/' || strstr(req_fname, \"/../\")) {\n tftp_send_error(spt, 2, \"Access violation\", tp);\n return;\n }\n\n /* check if the file exists */\n if (tftp_read_data(spt, 0, NULL, 0) < 0) {\n tftp_send_error(spt, 1, \"File not found\", tp);\n return;\n }\n\n if (tp->x.tp_buf[pktlen - 1] != 0) {\n tftp_send_error(spt, 2, \"Access violation\", tp);\n return;\n }\n\n while (k < pktlen && nb_options < G_N_ELEMENTS(option_name)) {\n const char *key, *value;\n\n key = &tp->x.tp_buf[k];\n k += strlen(key) + 1;\n\n if (k >= pktlen) {\n tftp_send_error(spt, 2, \"Access violation\", tp);\n return;\n }\n\n value = &tp->x.tp_buf[k];\n k += strlen(value) + 1;\n\n if (strcasecmp(key, \"tsize\") == 0) {\n int tsize = atoi(value);\n struct stat stat_p;\n\n if (tsize == 0) {\n if (stat(spt->filename, &stat_p) == 0)\n tsize = stat_p.st_size;\n else {\n tftp_send_error(spt, 1, \"File not found\", tp);\n return;\n }\n }\n\n option_name[nb_options] = \"tsize\";\n option_value[nb_options] = tsize;\n nb_options++;\n } else if (strcasecmp(key, \"blksize\") == 0) {\n int blksize = atoi(value);\n\n /* Accept blksize up to our maximum size */\n if (blksize > 0) {\n spt->block_size = MIN(blksize, TFTP_BLOCKSIZE_MAX);\n option_name[nb_options] = \"blksize\";\n option_value[nb_options] = spt->block_size;\n nb_options++;\n }\n }\n }\n\n if (nb_options > 0) {\n assert(nb_options <= G_N_ELEMENTS(option_name));\n tftp_send_oack(spt, option_name, option_value, nb_options, tp);\n return;\n }\n\n spt->block_nr = 0;\n tftp_send_next_block(spt, tp);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-22'], 'message': 'slirp: tftp: restrict relative path access\n\ntftp restricts relative or directory path access on Linux systems.\nApply same restrictions on Windows systems too. It helps to avoid\ndirectory traversal issue.\n\nFixes: https://bugs.launchpad.net/qemu/+bug/1812451\nReported-by: Peter Maydell \nSigned-off-by: Prasad J Pandit \nReviewed-by: Samuel Thibault \nMessage-Id: <20200113121431.156708-1-ppandit@redhat.com>'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)\n{\n\tu64 now;\n\n\tif (cfs_b->quota == RUNTIME_INF)\n\t\treturn;\n\n\tnow = sched_clock_cpu(smp_processor_id());\n\tcfs_b->runtime = cfs_b->quota;\n\tcfs_b->runtime_expires = now + ktime_to_ns(cfs_b->period);\n\tcfs_b->expires_seq++;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'sched/fair: Fix low cpu usage with high throttling by removing expiration of cpu-local slices\n\nIt has been observed, that highly-threaded, non-cpu-bound applications\nrunning under cpu.cfs_quota_us constraints can hit a high percentage of\nperiods throttled while simultaneously not consuming the allocated\namount of quota. This use case is typical of user-interactive non-cpu\nbound applications, such as those running in kubernetes or mesos when\nrun on multiple cpu cores.\n\nThis has been root caused to cpu-local run queue being allocated per cpu\nbandwidth slices, and then not fully using that slice within the period.\nAt which point the slice and quota expires. This expiration of unused\nslice results in applications not being able to utilize the quota for\nwhich they are allocated.\n\nThe non-expiration of per-cpu slices was recently fixed by\n'commit 512ac999d275 (\"sched/fair: Fix bandwidth timer clock drift\ncondition\")'. Prior to that it appears that this had been broken since\nat least 'commit 51f2176d74ac (\"sched/fair: Fix unlocked reads of some\ncfs_b->quota/period\")' which was introduced in v3.16-rc1 in 2014. That\nadded the following conditional which resulted in slices never being\nexpired.\n\nif (cfs_rq->runtime_expires != cfs_b->runtime_expires) {\n\t/* extend local deadline, drift is bounded above by 2 ticks */\n\tcfs_rq->runtime_expires += TICK_NSEC;\n\nBecause this was broken for nearly 5 years, and has recently been fixed\nand is now being noticed by many users running kubernetes\n(https://github.com/kubernetes/kubernetes/issues/67577) it is my opinion\nthat the mechanisms around expiring runtime should be removed\naltogether.\n\nThis allows quota already allocated to per-cpu run-queues to live longer\nthan the period boundary. This allows threads on runqueues that do not\nuse much CPU to continue to use their remaining slice over a longer\nperiod of time than cpu.cfs_period_us. However, this helps prevent the\nabove condition of hitting throttling while also not fully utilizing\nyour cpu quota.\n\nThis theoretically allows a machine to use slightly more than its\nallotted quota in some periods. This overflow would be bounded by the\nremaining quota left on each per-cpu runqueueu. This is typically no\nmore than min_cfs_rq_runtime=1ms per cpu. For CPU bound tasks this will\nchange nothing, as they should theoretically fully utilize all of their\nquota in each period. For user-interactive tasks as described above this\nprovides a much better user/application experience as their cpu\nutilization will more closely match the amount they requested when they\nhit throttling. This means that cpu limits no longer strictly apply per\nperiod for non-cpu bound applications, but that they are still accurate\nover longer timeframes.\n\nThis greatly improves performance of high-thread-count, non-cpu bound\napplications with low cfs_quota_us allocation on high-core-count\nmachines. In the case of an artificial testcase (10ms/100ms of quota on\n80 CPU machine), this commit resulted in almost 30x performance\nimprovement, while still maintaining correct cpu quota restrictions.\nThat testcase is available at https://github.com/indeedeng/fibtest.\n\nFixes: 512ac999d275 (\"sched/fair: Fix bandwidth timer clock drift condition\")\nSigned-off-by: Dave Chiluk \nSigned-off-by: Peter Zijlstra (Intel) \nReviewed-by: Phil Auld \nReviewed-by: Ben Segall \nCc: Ingo Molnar \nCc: John Hammond \nCc: Jonathan Corbet \nCc: Kyle Anderson \nCc: Gabriel Munos \nCc: Peter Oskolkov \nCc: Cong Wang \nCc: Brendan Gregg \nLink: https://lkml.kernel.org/r/1563900266-19734-2-git-send-email-chiluk+linux@indeed.com'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: resolve_list_keys(struct lys_node_list *list, const char *keys_str)\n{\n int i, len, rc;\n const char *value;\n char *s = NULL;\n struct ly_ctx *ctx = list->module->ctx;\n\n for (i = 0; i < list->keys_size; ++i) {\n assert(keys_str);\n\n if (!list->child) {\n /* no child, possible forward reference */\n LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_LYS, list, \"list keys\", keys_str);\n return EXIT_FAILURE;\n }\n /* get the key name */\n if ((value = strpbrk(keys_str, \" \\t\\n\"))) {\n len = value - keys_str;\n while (isspace(value[0])) {\n value++;\n }\n } else {\n len = strlen(keys_str);\n }\n\n rc = lys_getnext_data(lys_node_module((struct lys_node *)list), (struct lys_node *)list, keys_str, len, LYS_LEAF,\n (const struct lys_node **)&list->keys[i]);\n if (rc) {\n LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_LYS, list, \"list key\", keys_str);\n return EXIT_FAILURE;\n }\n\n if (check_key(list, i, keys_str, len)) {\n /* check_key logs */\n return -1;\n }\n\n /* check status */\n if (lyp_check_status(list->flags, list->module, list->name,\n list->keys[i]->flags, list->keys[i]->module, list->keys[i]->name,\n (struct lys_node *)list->keys[i])) {\n return -1;\n }\n\n /* default value - is ignored, keep it but print a warning */\n if (list->keys[i]->dflt) {\n /* log is not hidden only in case this resolving fails and in such a case\n * we cannot get here\n */\n assert(log_opt == ILO_STORE);\n log_opt = ILO_LOG;\n LOGWRN(ctx, \"Default value \\\"%s\\\" in the list key \\\"%s\\\" is ignored. (%s)\", list->keys[i]->dflt,\n list->keys[i]->name, s = lys_path((struct lys_node*)list, LYS_PATH_FIRST_PREFIX));\n log_opt = ILO_STORE;\n free(s);\n }\n\n /* prepare for next iteration */\n while (value && isspace(value[0])) {\n value++;\n }\n keys_str = value;\n }\n\n return EXIT_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'schema tree BUGFIX do not check features while still resolving schema\n\nFixes #723'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: yang_read_extcomplex_str(struct lys_module *module, struct lys_ext_instance_complex *ext, const char *arg_name,\n const char *parent_name, char *value, int parent_stmt, LY_STMT stmt)\n{\n int c;\n const char **str, ***p = NULL;\n void *reallocated;\n struct lyext_substmt *info;\n\n c = 0;\n if (stmt == LY_STMT_PREFIX && parent_stmt == LY_STMT_BELONGSTO) {\n /* str contains no NULL value */\n str = lys_ext_complex_get_substmt(LY_STMT_BELONGSTO, ext, &info);\n if (info->cardinality < LY_STMT_CARD_SOME) {\n str++;\n } else {\n /* get the index in the array to add new item */\n p = (const char ***)str;\n for (c = 0; p[0][c + 1]; c++);\n str = p[1];\n }\n str[c] = lydict_insert_zc(module->ctx, value);\n } else {\n str = lys_ext_complex_get_substmt(stmt, ext, &info);\n if (!str) {\n LOGVAL(module->ctx, LYE_INCHILDSTMT, LY_VLOG_NONE, NULL, arg_name, parent_name);\n goto error;\n }\n if (info->cardinality < LY_STMT_CARD_SOME && *str) {\n LOGVAL(module->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, arg_name, parent_name);\n goto error;\n }\n\n if (info->cardinality >= LY_STMT_CARD_SOME) {\n /* there can be multiple instances, str is actually const char *** */\n p = (const char ***)str;\n if (!p[0]) {\n /* allocate initial array */\n p[0] = calloc(2, sizeof(const char *));\n LY_CHECK_ERR_GOTO(!p[0], LOGMEM(module->ctx), error);\n if (stmt == LY_STMT_BELONGSTO) {\n /* allocate another array for the belongs-to's prefixes */\n p[1] = calloc(2, sizeof(const char *));\n LY_CHECK_ERR_GOTO(!p[1], LOGMEM(module->ctx), error);\n } else if (stmt == LY_STMT_ARGUMENT) {\n /* allocate another array for the yin element */\n ((uint8_t **)p)[1] = calloc(2, sizeof(uint8_t));\n LY_CHECK_ERR_GOTO(!p[1], LOGMEM(module->ctx), error);\n /* default value of yin element */\n ((uint8_t *)p[1])[0] = 2;\n }\n } else {\n /* get the index in the array to add new item */\n for (c = 0; p[0][c]; c++);\n }\n str = p[0];\n }\n\n str[c] = lydict_insert_zc(module->ctx, value);\n value = NULL;\n\n if (c) {\n /* enlarge the array(s) */\n reallocated = realloc(p[0], (c + 2) * sizeof(const char *));\n if (!reallocated) {\n LOGMEM(module->ctx);\n lydict_remove(module->ctx, p[0][c]);\n p[0][c] = NULL;\n return EXIT_FAILURE;\n }\n p[0] = reallocated;\n p[0][c + 1] = NULL;\n\n if (stmt == LY_STMT_BELONGSTO) {\n /* enlarge the second belongs-to's array with prefixes */\n reallocated = realloc(p[1], (c + 2) * sizeof(const char *));\n if (!reallocated) {\n LOGMEM(module->ctx);\n lydict_remove(module->ctx, p[1][c]);\n p[1][c] = NULL;\n return EXIT_FAILURE;\n }\n p[1] = reallocated;\n p[1][c + 1] = NULL;\n } else if (stmt == LY_STMT_ARGUMENT) {\n /* enlarge the second argument's array with yin element */\n reallocated = realloc(p[1], (c + 2) * sizeof(uint8_t));\n if (!reallocated) {\n LOGMEM(module->ctx);\n ((uint8_t *)p[1])[c] = 0;\n return EXIT_FAILURE;\n }\n p[1] = reallocated;\n ((uint8_t *)p[1])[c + 1] = 0;\n }\n }\n }\n\n return EXIT_SUCCESS;\n\nerror:\n free(value);\n return EXIT_FAILURE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'yang parser BUGFIX double free\n\nFixes #742'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void async_polkit_query_free(AsyncPolkitQuery *q) {\n\n if (!q)\n return;\n\n sd_bus_slot_unref(q->slot);\n\n if (q->registry && q->request)\n hashmap_remove(q->registry, q->request);\n\n sd_bus_message_unref(q->request);\n sd_bus_message_unref(q->reply);\n\n free(q->action);\n strv_free(q->details);\n\n free(q);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'polkit: when authorizing via PK let's re-resolve callback/userdata instead of caching it\n\nPreviously, when doing an async PK query we'd store the original\ncallback/userdata pair and call it again after the PK request is\ncomplete. This is problematic, since PK queries might be slow and in the\nmeantime the userdata might be released and re-acquired. Let's avoid\nthis by always traversing through the message handlers so that we always\nre-resolve the callback and userdata pair and thus can be sure it's\nup-to-date and properly valid.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int gem_context_register(struct i915_gem_context *ctx,\n\t\t\t\tstruct drm_i915_file_private *fpriv)\n{\n\tint ret;\n\n\tctx->file_priv = fpriv;\n\tif (ctx->ppgtt)\n\t\tctx->ppgtt->vm.file = fpriv;\n\n\tctx->pid = get_task_pid(current, PIDTYPE_PID);\n\tctx->name = kasprintf(GFP_KERNEL, \"%s[%d]\",\n\t\t\t current->comm, pid_nr(ctx->pid));\n\tif (!ctx->name) {\n\t\tret = -ENOMEM;\n\t\tgoto err_pid;\n\t}\n\n\t/* And finally expose ourselves to userspace via the idr */\n\tret = idr_alloc(&fpriv->context_idr, ctx,\n\t\t\tDEFAULT_CONTEXT_HANDLE, 0, GFP_KERNEL);\n\tif (ret < 0)\n\t\tgoto err_name;\n\n\tctx->user_handle = ret;\n\n\treturn 0;\n\nerr_name:\n\tkfree(fetch_and_zero(&ctx->name));\nerr_pid:\n\tput_pid(fetch_and_zero(&ctx->pid));\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'drm/i915: Introduce a mutex for file_priv->context_idr\n\nDefine a mutex for the exclusive use of interacting with the per-file\ncontext-idr, that was previously guarded by struct_mutex. This allows us\nto reduce the coverage of struct_mutex, with a view to removing the last\nbits coordinating GEM context later. (In the short term, we avoid taking\nstruct_mutex while using the extended constructor functions, preventing\nsome nasty recursion.)\n\nv2: s/context_lock/context_idr_lock/\n\nSigned-off-by: Chris Wilson \nCc: Tvrtko Ursulin \nReviewed-by: Tvrtko Ursulin \nLink: https://patchwork.freedesktop.org/patch/msgid/20190321140711.11190-2-chris@chris-wilson.co.uk'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline size_t flow_keys_hash_length(const struct flow_keys *flow)\n{\n\tsize_t diff = FLOW_KEYS_HASH_OFFSET + sizeof(flow->addrs);\n\tBUILD_BUG_ON((sizeof(*flow) - FLOW_KEYS_HASH_OFFSET) % sizeof(u32));\n\tBUILD_BUG_ON(offsetof(typeof(*flow), addrs) !=\n\t\t sizeof(*flow) - sizeof(flow->addrs));\n\n\tswitch (flow->control.addr_type) {\n\tcase FLOW_DISSECTOR_KEY_IPV4_ADDRS:\n\t\tdiff -= sizeof(flow->addrs.v4addrs);\n\t\tbreak;\n\tcase FLOW_DISSECTOR_KEY_IPV6_ADDRS:\n\t\tdiff -= sizeof(flow->addrs.v6addrs);\n\t\tbreak;\n\tcase FLOW_DISSECTOR_KEY_TIPC:\n\t\tdiff -= sizeof(flow->addrs.tipckey);\n\t\tbreak;\n\t}\n\treturn (sizeof(*flow) - diff) / sizeof(u32);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-330'], 'message': 'net/flow_dissector: switch to siphash\n\nUDP IPv6 packets auto flowlabels are using a 32bit secret\n(static u32 hashrnd in net/core/flow_dissector.c) and\napply jhash() over fields known by the receivers.\n\nAttackers can easily infer the 32bit secret and use this information\nto identify a device and/or user, since this 32bit secret is only\nset at boot time.\n\nReally, using jhash() to generate cookies sent on the wire\nis a serious security concern.\n\nTrying to change the rol32(hash, 16) in ip6_make_flowlabel() would be\na dead end. Trying to periodically change the secret (like in sch_sfq.c)\ncould change paths taken in the network for long lived flows.\n\nLet's switch to siphash, as we did in commit df453700e8d8\n(\"inet: switch IP ID generator to siphash\")\n\nUsing a cryptographically strong pseudo random function will solve this\nprivacy issue and more generally remove other weak points in the stack.\n\nPacket schedulers using skb_get_hash_perturb() benefit from this change.\n\nFixes: b56774163f99 (\"ipv6: Enable auto flow labels by default\")\nFixes: 42240901f7c4 (\"ipv6: Implement different admin modes for automatic flow labels\")\nFixes: 67800f9b1f4e (\"ipv6: Call skb_get_hash_flowi6 to get skb->hash in ip6_make_flowlabel\")\nFixes: cb1ce2ef387b (\"ipv6: Implement automatic flow label generation on transmit\")\nSigned-off-by: Eric Dumazet \nReported-by: Jonathan Berger \nReported-by: Amit Klein \nReported-by: Benny Pinkas \nCc: Tom Herbert \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: u32 flow_hash_from_keys(struct flow_keys *keys)\n{\n\t__flow_hash_secret_init();\n\treturn __flow_hash_from_keys(keys, hashrnd);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-330'], 'message': 'net/flow_dissector: switch to siphash\n\nUDP IPv6 packets auto flowlabels are using a 32bit secret\n(static u32 hashrnd in net/core/flow_dissector.c) and\napply jhash() over fields known by the receivers.\n\nAttackers can easily infer the 32bit secret and use this information\nto identify a device and/or user, since this 32bit secret is only\nset at boot time.\n\nReally, using jhash() to generate cookies sent on the wire\nis a serious security concern.\n\nTrying to change the rol32(hash, 16) in ip6_make_flowlabel() would be\na dead end. Trying to periodically change the secret (like in sch_sfq.c)\ncould change paths taken in the network for long lived flows.\n\nLet's switch to siphash, as we did in commit df453700e8d8\n(\"inet: switch IP ID generator to siphash\")\n\nUsing a cryptographically strong pseudo random function will solve this\nprivacy issue and more generally remove other weak points in the stack.\n\nPacket schedulers using skb_get_hash_perturb() benefit from this change.\n\nFixes: b56774163f99 (\"ipv6: Enable auto flow labels by default\")\nFixes: 42240901f7c4 (\"ipv6: Implement different admin modes for automatic flow labels\")\nFixes: 67800f9b1f4e (\"ipv6: Call skb_get_hash_flowi6 to get skb->hash in ip6_make_flowlabel\")\nFixes: cb1ce2ef387b (\"ipv6: Implement automatic flow label generation on transmit\")\nSigned-off-by: Eric Dumazet \nReported-by: Jonathan Berger \nReported-by: Amit Klein \nReported-by: Benny Pinkas \nCc: Tom Herbert \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: char* skipSpaces( char* ptr, int mode )\n {\n int level = 0;\n\n for(;;)\n {\n char c;\n ptr--;\n\n if( mode == CV_XML_INSIDE_COMMENT )\n {\n do c = *++ptr;\n while( cv_isprint_or_tab(c) && (c != '-' || ptr[1] != '-' || ptr[2] != '>') );\n\n if( c == '-' )\n {\n assert( ptr[1] == '-' && ptr[2] == '>' );\n mode = 0;\n ptr += 3;\n }\n }\n else if( mode == CV_XML_INSIDE_DIRECTIVE )\n {\n // !!!NOTE!!! This is not quite correct, but should work in most cases\n do\n {\n c = *++ptr;\n level += c == '<';\n level -= c == '>';\n if( level < 0 )\n return ptr;\n } while( cv_isprint_or_tab(c) );\n }\n else\n {\n do c = *++ptr;\n while( c == ' ' || c == '\\t' );\n\n if( c == '<' && ptr[1] == '!' && ptr[2] == '-' && ptr[3] == '-' )\n {\n if( mode != 0 )\n CV_PARSE_ERROR_CPP( \"Comments are not allowed here\" );\n mode = CV_XML_INSIDE_COMMENT;\n ptr += 4;\n }\n else if( cv_isprint(c) )\n break;\n }\n\n if( !cv_isprint(*ptr) )\n {\n if( *ptr != '\\0' && *ptr != '\\n' && *ptr != '\\r' )\n CV_PARSE_ERROR_CPP( \"Invalid character in the stream\" );\n ptr = fs->gets();\n if( !ptr || *ptr == '\\0' )\n break;\n }\n }\n return ptr;\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'core(persistence): added null ptr checks'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool SplashOutputDev::tilingPatternFill(GfxState *state, Gfx *gfxA, Catalog *catalog, Object *str,\n\t\t\t\t\tconst double *ptm, int paintType, int /*tilingType*/, Dict *resDict,\n\t\t\t\t\tconst double *mat, const double *bbox,\n\t\t\t\t\tint x0, int y0, int x1, int y1,\n\t\t\t\t\tdouble xStep, double yStep)\n{\n PDFRectangle box;\n Gfx *gfx;\n Splash *formerSplash = splash;\n SplashBitmap *formerBitmap = bitmap;\n double width, height;\n int surface_width, surface_height, result_width, result_height, i;\n int repeatX, repeatY;\n SplashCoord matc[6];\n Matrix m1;\n const double *ctm;\n double savedCTM[6];\n double kx, ky, sx, sy;\n bool retValue = false;\n\n width = bbox[2] - bbox[0];\n height = bbox[3] - bbox[1];\n\n if (xStep != width || yStep != height)\n return false;\n\n // calculate offsets\n ctm = state->getCTM();\n for (i = 0; i < 6; ++i) {\n savedCTM[i] = ctm[i];\n }\n state->concatCTM(mat[0], mat[1], mat[2], mat[3], mat[4], mat[5]);\n state->concatCTM(1, 0, 0, 1, bbox[0], bbox[1]);\n ctm = state->getCTM();\n for (i = 0; i < 6; ++i) {\n if (!std::isfinite(ctm[i])) {\n state->setCTM(savedCTM[0], savedCTM[1], savedCTM[2], savedCTM[3], savedCTM[4], savedCTM[5]);\n return false;\n }\n }\n matc[4] = x0 * xStep * ctm[0] + y0 * yStep * ctm[2] + ctm[4];\n matc[5] = x0 * xStep * ctm[1] + y0 * yStep * ctm[3] + ctm[5];\n if (splashAbs(ctm[1]) > splashAbs(ctm[0])) {\n kx = -ctm[1];\n ky = ctm[2] - (ctm[0] * ctm[3]) / ctm[1];\n } else {\n kx = ctm[0];\n ky = ctm[3] - (ctm[1] * ctm[2]) / ctm[0];\n }\n result_width = (int) ceil(fabs(kx * width * (x1 - x0)));\n result_height = (int) ceil(fabs(ky * height * (y1 - y0)));\n kx = state->getHDPI() / 72.0;\n ky = state->getVDPI() / 72.0;\n m1.m[0] = (ptm[0] == 0) ? fabs(ptm[2]) * kx : fabs(ptm[0]) * kx;\n m1.m[1] = 0;\n m1.m[2] = 0;\n m1.m[3] = (ptm[3] == 0) ? fabs(ptm[1]) * ky : fabs(ptm[3]) * ky;\n m1.m[4] = 0;\n m1.m[5] = 0;\n m1.transform(width, height, &kx, &ky);\n surface_width = (int) ceil (fabs(kx));\n surface_height = (int) ceil (fabs(ky));\n\n sx = (double) result_width / (surface_width * (x1 - x0));\n sy = (double) result_height / (surface_height * (y1 - y0));\n m1.m[0] *= sx;\n m1.m[3] *= sy;\n m1.transform(width, height, &kx, &ky);\n\n if(fabs(kx) < 1 && fabs(ky) < 1) {\n kx = std::min(kx, ky);\n ky = 2 / kx;\n m1.m[0] *= ky;\n m1.m[3] *= ky;\n m1.transform(width, height, &kx, &ky);\n surface_width = (int) ceil (fabs(kx));\n surface_height = (int) ceil (fabs(ky));\n repeatX = x1 - x0;\n repeatY = y1 - y0;\n } else {\n if ((unsigned long) surface_width * surface_height > 0x800000L) {\n state->setCTM(savedCTM[0], savedCTM[1], savedCTM[2], savedCTM[3], savedCTM[4], savedCTM[5]);\n return false;\n }\n while(fabs(kx) > 16384 || fabs(ky) > 16384) {\n // limit pattern bitmap size\n m1.m[0] /= 2;\n m1.m[3] /= 2;\n m1.transform(width, height, &kx, &ky);\n }\n surface_width = (int) ceil (fabs(kx));\n surface_height = (int) ceil (fabs(ky));\n // adjust repeat values to completely fill region\n repeatX = result_width / surface_width;\n repeatY = result_height / surface_height;\n if (surface_width * repeatX < result_width)\n repeatX++;\n if (surface_height * repeatY < result_height)\n repeatY++;\n if (x1 - x0 > repeatX)\n repeatX = x1 - x0;\n if (y1 - y0 > repeatY)\n repeatY = y1 - y0;\n }\n // restore CTM and calculate rotate and scale with rounded matrix\n state->setCTM(savedCTM[0], savedCTM[1], savedCTM[2], savedCTM[3], savedCTM[4], savedCTM[5]);\n state->concatCTM(mat[0], mat[1], mat[2], mat[3], mat[4], mat[5]);\n state->concatCTM(width * repeatX, 0, 0, height * repeatY, bbox[0], bbox[1]);\n ctm = state->getCTM();\n matc[0] = ctm[0];\n matc[1] = ctm[1];\n matc[2] = ctm[2];\n matc[3] = ctm[3];\n\n if (surface_width == 0 || surface_height == 0 || repeatX * repeatY <= 4) {\n state->setCTM(savedCTM[0], savedCTM[1], savedCTM[2], savedCTM[3], savedCTM[4], savedCTM[5]);\n return false;\n }\n m1.transform(bbox[0], bbox[1], &kx, &ky);\n m1.m[4] = -kx;\n m1.m[5] = -ky;\n\n bitmap = new SplashBitmap(surface_width, surface_height, 1,\n (paintType == 1) ? colorMode : splashModeMono8, true);\n if (bitmap->getDataPtr() == nullptr) {\n SplashBitmap *tBitmap = bitmap;\n bitmap = formerBitmap;\n delete tBitmap;\n state->setCTM(savedCTM[0], savedCTM[1], savedCTM[2], savedCTM[3], savedCTM[4], savedCTM[5]);\n return false;\n }\n splash = new Splash(bitmap, true);\n if (paintType == 2) {\n SplashColor clearColor;\n#ifdef SPLASH_CMYK\n clearColor[0] = (colorMode == splashModeCMYK8 || colorMode == splashModeDeviceN8) ? 0x00 : 0xFF;\n#else\n clearColor[0] = 0xFF;\n#endif\n splash->clear(clearColor, 0);\n } else {\n splash->clear(paperColor, 0);\n }\n splash->setThinLineMode(formerSplash->getThinLineMode());\n splash->setMinLineWidth(s_minLineWidth);\n\n box.x1 = bbox[0]; box.y1 = bbox[1];\n box.x2 = bbox[2]; box.y2 = bbox[3];\n gfx = new Gfx(doc, this, resDict, &box, nullptr, nullptr, nullptr, gfxA);\n // set pattern transformation matrix\n gfx->getState()->setCTM(m1.m[0], m1.m[1], m1.m[2], m1.m[3], m1.m[4], m1.m[5]);\n updateCTM(gfx->getState(), m1.m[0], m1.m[1], m1.m[2], m1.m[3], m1.m[4], m1.m[5]);\n gfx->display(str);\n delete splash;\n splash = formerSplash;\n TilingSplashOutBitmap imgData;\n imgData.bitmap = bitmap;\n imgData.paintType = paintType;\n imgData.pattern = splash->getFillPattern();\n imgData.colorMode = colorMode;\n imgData.y = 0;\n imgData.repeatX = repeatX;\n imgData.repeatY = repeatY;\n SplashBitmap *tBitmap = bitmap;\n bitmap = formerBitmap;\n result_width = tBitmap->getWidth() * imgData.repeatX;\n result_height = tBitmap->getHeight() * imgData.repeatY;\n\n if (splashAbs(matc[1]) > splashAbs(matc[0])) {\n kx = -matc[1];\n ky = matc[2] - (matc[0] * matc[3]) / matc[1];\n } else {\n kx = matc[0];\n ky = matc[3] - (matc[1] * matc[2]) / matc[0];\n }\n kx = result_width / (fabs(kx) + 1);\n ky = result_height / (fabs(ky) + 1);\n state->concatCTM(kx, 0, 0, ky, 0, 0);\n ctm = state->getCTM();\n matc[0] = ctm[0];\n matc[1] = ctm[1];\n matc[2] = ctm[2];\n matc[3] = ctm[3];\n bool minorAxisZero = matc[1] == 0 && matc[2] == 0;\n if (matc[0] > 0 && minorAxisZero && matc[3] > 0) {\n // draw the tiles\n for (int y = 0; y < imgData.repeatY; ++y) {\n for (int x = 0; x < imgData.repeatX; ++x) {\n x0 = splashFloor(matc[4]) + x * tBitmap->getWidth();\n y0 = splashFloor(matc[5]) + y * tBitmap->getHeight();\n splash->blitImage(tBitmap, true, x0, y0);\n }\n }\n retValue = true;\n } else {\n retValue = splash->drawImage(&tilingBitmapSrc, nullptr, &imgData, colorMode, true, result_width, result_height, matc, false, true) == splashOk;\n }\n delete tBitmap;\n delete gfx;\n return retValue;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-369'], 'message': 'SplashOutputDev::tilingPatternFill: Fix crash on broken file\n\nIssue #802'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ipmi_sdr_print_sensor_mc_locator(struct sdr_record_mc_locator *mc)\n{\n\tchar desc[17];\n\n\tif (!mc)\n\t\treturn -1;\n\n\tmemset(desc, 0, sizeof (desc));\n\tsnprintf(desc, (mc->id_code & 0x1f) + 1, \"%s\", mc->id_string);\n\n\tif (verbose == 0) {\n\t\tif (csv_output)\n\t\t\tprintf(\"%s,00h,ok,%d.%d\\n\",\n\t\t\t mc->id_code ? desc : \"\",\n\t\t\t mc->entity.id, mc->entity.instance);\n\t\telse if (sdr_extended) {\n\t\t\tprintf(\"%-16s | 00h | ok | %2d.%1d | \",\n\t\t\t mc->id_code ? desc : \"\",\n\t\t\t mc->entity.id, mc->entity.instance);\n\n\t\t\tprintf(\"%s MC @ %02Xh\\n\",\n\t\t\t (mc->\n\t\t\t\tpwr_state_notif & 0x1) ? \"Static\" : \"Dynamic\",\n\t\t\t mc->dev_slave_addr);\n\t\t} else {\n\t\t\tprintf(\"%-16s | %s MC @ %02Xh %s | ok\\n\",\n\t\t\t mc->id_code ? desc : \"\",\n\t\t\t (mc->\n\t\t\t\tpwr_state_notif & 0x1) ? \"Static\" : \"Dynamic\",\n\t\t\t mc->dev_slave_addr,\n\t\t\t (mc->pwr_state_notif & 0x1) ? \" \" : \"\");\n\t\t}\n\n\t\treturn 0;\t/* done */\n\t}\n\n\tprintf(\"Device ID : %s\\n\", mc->id_string);\n\tprintf(\"Entity ID : %d.%d (%s)\\n\",\n\t mc->entity.id, mc->entity.instance,\n\t val2str(mc->entity.id, entity_id_vals));\n\n\tprintf(\"Device Slave Address : %02Xh\\n\", mc->dev_slave_addr);\n\tprintf(\"Channel Number : %01Xh\\n\", mc->channel_num);\n\n\tprintf(\"ACPI System P/S Notif : %sRequired\\n\",\n\t (mc->pwr_state_notif & 0x4) ? \"\" : \"Not \");\n\tprintf(\"ACPI Device P/S Notif : %sRequired\\n\",\n\t (mc->pwr_state_notif & 0x2) ? \"\" : \"Not \");\n\tprintf(\"Controller Presence : %s\\n\",\n\t (mc->pwr_state_notif & 0x1) ? \"Static\" : \"Dynamic\");\n\tprintf(\"Logs Init Agent Errors : %s\\n\",\n\t (mc->global_init & 0x8) ? \"Yes\" : \"No\");\n\n\tprintf(\"Event Message Gen : \");\n\tif (!(mc->global_init & 0x3))\n\t\tprintf(\"Enable\\n\");\n\telse if ((mc->global_init & 0x3) == 0x1)\n\t\tprintf(\"Disable\\n\");\n\telse if ((mc->global_init & 0x3) == 0x2)\n\t\tprintf(\"Do Not Init Controller\\n\");\n\telse\n\t\tprintf(\"Reserved\\n\");\n\n\tprintf(\"Device Capabilities\\n\");\n\tprintf(\" Chassis Device : %s\\n\",\n\t (mc->dev_support & 0x80) ? \"Yes\" : \"No\");\n\tprintf(\" Bridge : %s\\n\",\n\t (mc->dev_support & 0x40) ? \"Yes\" : \"No\");\n\tprintf(\" IPMB Event Generator : %s\\n\",\n\t (mc->dev_support & 0x20) ? \"Yes\" : \"No\");\n\tprintf(\" IPMB Event Receiver : %s\\n\",\n\t (mc->dev_support & 0x10) ? \"Yes\" : \"No\");\n\tprintf(\" FRU Inventory Device : %s\\n\",\n\t (mc->dev_support & 0x08) ? \"Yes\" : \"No\");\n\tprintf(\" SEL Device : %s\\n\",\n\t (mc->dev_support & 0x04) ? \"Yes\" : \"No\");\n\tprintf(\" SDR Repository : %s\\n\",\n\t (mc->dev_support & 0x02) ? \"Yes\" : \"No\");\n\tprintf(\" Sensor Device : %s\\n\",\n\t (mc->dev_support & 0x01) ? \"Yes\" : \"No\");\n\n\tprintf(\"\\n\");\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'fru, sdr: Fix id_string buffer overflows\n\nFinal part of the fixes for CVE-2020-5208, see\nhttps://github.com/ipmitool/ipmitool/security/advisories/GHSA-g659-9qxw-p7cp\n\n9 variants of stack buffer overflow when parsing `id_string` field of\nSDR records returned from `CMD_GET_SDR` command.\n\nSDR record structs have an `id_code` field, and an `id_string` `char`\narray.\n\nThe length of `id_string` is calculated as `(id_code & 0x1f) + 1`,\nwhich can be larger than expected 16 characters (if `id_code = 0xff`,\nthen length will be `(0xff & 0x1f) + 1 = 32`).\n\nIn numerous places, this can cause stack buffer overflow when copying\ninto fixed buffer of size `17` bytes from this calculated length.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: \nsize_t http_parser_execute (http_parser *parser,\n const http_parser_settings *settings,\n const char *data,\n size_t len)\n{\n char c, ch;\n int8_t unhex_val;\n const char *p = data;\n const char *header_field_mark = 0;\n const char *header_value_mark = 0;\n const char *url_mark = 0;\n const char *body_mark = 0;\n const char *status_mark = 0;\n enum state p_state = (enum state) parser->state;\n const unsigned int lenient = parser->lenient_http_headers;\n uint32_t nread = parser->nread;\n\n /* We're in an error state. Don't bother doing anything. */\n if (HTTP_PARSER_ERRNO(parser) != HPE_OK) {\n return 0;\n }\n\n if (len == 0) {\n switch (CURRENT_STATE()) {\n case s_body_identity_eof:\n /* Use of CALLBACK_NOTIFY() here would erroneously return 1 byte read if\n * we got paused.\n */\n CALLBACK_NOTIFY_NOADVANCE(message_complete);\n return 0;\n\n case s_dead:\n case s_start_req_or_res:\n case s_start_res:\n case s_start_req:\n return 0;\n\n default:\n SET_ERRNO(HPE_INVALID_EOF_STATE);\n return 1;\n }\n }\n\n\n if (CURRENT_STATE() == s_header_field)\n header_field_mark = data;\n if (CURRENT_STATE() == s_header_value)\n header_value_mark = data;\n switch (CURRENT_STATE()) {\n case s_req_path:\n case s_req_schema:\n case s_req_schema_slash:\n case s_req_schema_slash_slash:\n case s_req_server_start:\n case s_req_server:\n case s_req_server_with_at:\n case s_req_query_string_start:\n case s_req_query_string:\n case s_req_fragment_start:\n case s_req_fragment:\n url_mark = data;\n break;\n case s_res_status:\n status_mark = data;\n break;\n default:\n break;\n }\n\n for (p=data; p != data + len; p++) {\n ch = *p;\n\n if (PARSING_HEADER(CURRENT_STATE()))\n COUNT_HEADER_SIZE(1);\n\nreexecute:\n switch (CURRENT_STATE()) {\n\n case s_dead:\n /* this state is used after a 'Connection: close' message\n * the parser will error out if it reads another message\n */\n if (LIKELY(ch == CR || ch == LF))\n break;\n\n SET_ERRNO(HPE_CLOSED_CONNECTION);\n goto error;\n\n case s_start_req_or_res:\n {\n if (ch == CR || ch == LF)\n break;\n parser->flags = 0;\n parser->content_length = ULLONG_MAX;\n\n if (ch == 'H') {\n UPDATE_STATE(s_res_or_resp_H);\n\n CALLBACK_NOTIFY(message_begin);\n } else {\n parser->type = HTTP_REQUEST;\n UPDATE_STATE(s_start_req);\n REEXECUTE();\n }\n\n break;\n }\n\n case s_res_or_resp_H:\n if (ch == 'T') {\n parser->type = HTTP_RESPONSE;\n UPDATE_STATE(s_res_HT);\n } else {\n if (UNLIKELY(ch != 'E')) {\n SET_ERRNO(HPE_INVALID_CONSTANT);\n goto error;\n }\n\n parser->type = HTTP_REQUEST;\n parser->method = HTTP_HEAD;\n parser->index = 2;\n UPDATE_STATE(s_req_method);\n }\n break;\n\n case s_start_res:\n {\n if (ch == CR || ch == LF)\n break;\n parser->flags = 0;\n parser->content_length = ULLONG_MAX;\n\n if (ch == 'H') {\n UPDATE_STATE(s_res_H);\n } else {\n SET_ERRNO(HPE_INVALID_CONSTANT);\n goto error;\n }\n\n CALLBACK_NOTIFY(message_begin);\n break;\n }\n\n case s_res_H:\n STRICT_CHECK(ch != 'T');\n UPDATE_STATE(s_res_HT);\n break;\n\n case s_res_HT:\n STRICT_CHECK(ch != 'T');\n UPDATE_STATE(s_res_HTT);\n break;\n\n case s_res_HTT:\n STRICT_CHECK(ch != 'P');\n UPDATE_STATE(s_res_HTTP);\n break;\n\n case s_res_HTTP:\n STRICT_CHECK(ch != '/');\n UPDATE_STATE(s_res_http_major);\n break;\n\n case s_res_http_major:\n if (UNLIKELY(!IS_NUM(ch))) {\n SET_ERRNO(HPE_INVALID_VERSION);\n goto error;\n }\n\n parser->http_major = ch - '0';\n UPDATE_STATE(s_res_http_dot);\n break;\n\n case s_res_http_dot:\n {\n if (UNLIKELY(ch != '.')) {\n SET_ERRNO(HPE_INVALID_VERSION);\n goto error;\n }\n\n UPDATE_STATE(s_res_http_minor);\n break;\n }\n\n case s_res_http_minor:\n if (UNLIKELY(!IS_NUM(ch))) {\n SET_ERRNO(HPE_INVALID_VERSION);\n goto error;\n }\n\n parser->http_minor = ch - '0';\n UPDATE_STATE(s_res_http_end);\n break;\n\n case s_res_http_end:\n {\n if (UNLIKELY(ch != ' ')) {\n SET_ERRNO(HPE_INVALID_VERSION);\n goto error;\n }\n\n UPDATE_STATE(s_res_first_status_code);\n break;\n }\n\n case s_res_first_status_code:\n {\n if (!IS_NUM(ch)) {\n if (ch == ' ') {\n break;\n }\n\n SET_ERRNO(HPE_INVALID_STATUS);\n goto error;\n }\n parser->status_code = ch - '0';\n UPDATE_STATE(s_res_status_code);\n break;\n }\n\n case s_res_status_code:\n {\n if (!IS_NUM(ch)) {\n switch (ch) {\n case ' ':\n UPDATE_STATE(s_res_status_start);\n break;\n case CR:\n case LF:\n UPDATE_STATE(s_res_status_start);\n REEXECUTE();\n break;\n default:\n SET_ERRNO(HPE_INVALID_STATUS);\n goto error;\n }\n break;\n }\n\n parser->status_code *= 10;\n parser->status_code += ch - '0';\n\n if (UNLIKELY(parser->status_code > 999)) {\n SET_ERRNO(HPE_INVALID_STATUS);\n goto error;\n }\n\n break;\n }\n\n case s_res_status_start:\n {\n MARK(status);\n UPDATE_STATE(s_res_status);\n parser->index = 0;\n\n if (ch == CR || ch == LF)\n REEXECUTE();\n\n break;\n }\n\n case s_res_status:\n if (ch == CR) {\n UPDATE_STATE(s_res_line_almost_done);\n CALLBACK_DATA(status);\n break;\n }\n\n if (ch == LF) {\n UPDATE_STATE(s_header_field_start);\n CALLBACK_DATA(status);\n break;\n }\n\n break;\n\n case s_res_line_almost_done:\n STRICT_CHECK(ch != LF);\n UPDATE_STATE(s_header_field_start);\n break;\n\n case s_start_req:\n {\n if (ch == CR || ch == LF)\n break;\n parser->flags = 0;\n parser->content_length = ULLONG_MAX;\n\n if (UNLIKELY(!IS_ALPHA(ch))) {\n SET_ERRNO(HPE_INVALID_METHOD);\n goto error;\n }\n\n parser->method = (enum http_method) 0;\n parser->index = 1;\n switch (ch) {\n case 'A': parser->method = HTTP_ACL; break;\n case 'B': parser->method = HTTP_BIND; break;\n case 'C': parser->method = HTTP_CONNECT; /* or COPY, CHECKOUT */ break;\n case 'D': parser->method = HTTP_DELETE; break;\n case 'G': parser->method = HTTP_GET; break;\n case 'H': parser->method = HTTP_HEAD; break;\n case 'L': parser->method = HTTP_LOCK; /* or LINK */ break;\n case 'M': parser->method = HTTP_MKCOL; /* or MOVE, MKACTIVITY, MERGE, M-SEARCH, MKCALENDAR */ break;\n case 'N': parser->method = HTTP_NOTIFY; break;\n case 'O': parser->method = HTTP_OPTIONS; break;\n case 'P': parser->method = HTTP_POST;\n /* or PROPFIND|PROPPATCH|PUT|PATCH|PURGE */\n break;\n case 'R': parser->method = HTTP_REPORT; /* or REBIND */ break;\n case 'S': parser->method = HTTP_SUBSCRIBE; /* or SEARCH, SOURCE */ break;\n case 'T': parser->method = HTTP_TRACE; break;\n case 'U': parser->method = HTTP_UNLOCK; /* or UNSUBSCRIBE, UNBIND, UNLINK */ break;\n default:\n SET_ERRNO(HPE_INVALID_METHOD);\n goto error;\n }\n UPDATE_STATE(s_req_method);\n\n CALLBACK_NOTIFY(message_begin);\n\n break;\n }\n\n case s_req_method:\n {\n const char *matcher;\n if (UNLIKELY(ch == '\\0')) {\n SET_ERRNO(HPE_INVALID_METHOD);\n goto error;\n }\n\n matcher = method_strings[parser->method];\n if (ch == ' ' && matcher[parser->index] == '\\0') {\n UPDATE_STATE(s_req_spaces_before_url);\n } else if (ch == matcher[parser->index]) {\n ; /* nada */\n } else if ((ch >= 'A' && ch <= 'Z') || ch == '-') {\n\n switch (parser->method << 16 | parser->index << 8 | ch) {\n#define XX(meth, pos, ch, new_meth) \\\n case (HTTP_##meth << 16 | pos << 8 | ch): \\\n parser->method = HTTP_##new_meth; break;\n\n XX(POST, 1, 'U', PUT)\n XX(POST, 1, 'A', PATCH)\n XX(POST, 1, 'R', PROPFIND)\n XX(PUT, 2, 'R', PURGE)\n XX(CONNECT, 1, 'H', CHECKOUT)\n XX(CONNECT, 2, 'P', COPY)\n XX(MKCOL, 1, 'O', MOVE)\n XX(MKCOL, 1, 'E', MERGE)\n XX(MKCOL, 1, '-', MSEARCH)\n XX(MKCOL, 2, 'A', MKACTIVITY)\n XX(MKCOL, 3, 'A', MKCALENDAR)\n XX(SUBSCRIBE, 1, 'E', SEARCH)\n XX(SUBSCRIBE, 1, 'O', SOURCE)\n XX(REPORT, 2, 'B', REBIND)\n XX(PROPFIND, 4, 'P', PROPPATCH)\n XX(LOCK, 1, 'I', LINK)\n XX(UNLOCK, 2, 'S', UNSUBSCRIBE)\n XX(UNLOCK, 2, 'B', UNBIND)\n XX(UNLOCK, 3, 'I', UNLINK)\n#undef XX\n default:\n SET_ERRNO(HPE_INVALID_METHOD);\n goto error;\n }\n } else {\n SET_ERRNO(HPE_INVALID_METHOD);\n goto error;\n }\n\n ++parser->index;\n break;\n }\n\n case s_req_spaces_before_url:\n {\n if (ch == ' ') break;\n\n MARK(url);\n if (parser->method == HTTP_CONNECT) {\n UPDATE_STATE(s_req_server_start);\n }\n\n UPDATE_STATE(parse_url_char(CURRENT_STATE(), ch));\n if (UNLIKELY(CURRENT_STATE() == s_dead)) {\n SET_ERRNO(HPE_INVALID_URL);\n goto error;\n }\n\n break;\n }\n\n case s_req_schema:\n case s_req_schema_slash:\n case s_req_schema_slash_slash:\n case s_req_server_start:\n {\n switch (ch) {\n /* No whitespace allowed here */\n case ' ':\n case CR:\n case LF:\n SET_ERRNO(HPE_INVALID_URL);\n goto error;\n default:\n UPDATE_STATE(parse_url_char(CURRENT_STATE(), ch));\n if (UNLIKELY(CURRENT_STATE() == s_dead)) {\n SET_ERRNO(HPE_INVALID_URL);\n goto error;\n }\n }\n\n break;\n }\n\n case s_req_server:\n case s_req_server_with_at:\n case s_req_path:\n case s_req_query_string_start:\n case s_req_query_string:\n case s_req_fragment_start:\n case s_req_fragment:\n {\n switch (ch) {\n case ' ':\n UPDATE_STATE(s_req_http_start);\n CALLBACK_DATA(url);\n break;\n case CR:\n case LF:\n parser->http_major = 0;\n parser->http_minor = 9;\n UPDATE_STATE((ch == CR) ?\n s_req_line_almost_done :\n s_header_field_start);\n CALLBACK_DATA(url);\n break;\n default:\n UPDATE_STATE(parse_url_char(CURRENT_STATE(), ch));\n if (UNLIKELY(CURRENT_STATE() == s_dead)) {\n SET_ERRNO(HPE_INVALID_URL);\n goto error;\n }\n }\n break;\n }\n\n case s_req_http_start:\n switch (ch) {\n case ' ':\n break;\n case 'H':\n UPDATE_STATE(s_req_http_H);\n break;\n case 'I':\n if (parser->method == HTTP_SOURCE) {\n UPDATE_STATE(s_req_http_I);\n break;\n }\n /* fall through */\n default:\n SET_ERRNO(HPE_INVALID_CONSTANT);\n goto error;\n }\n break;\n\n case s_req_http_H:\n STRICT_CHECK(ch != 'T');\n UPDATE_STATE(s_req_http_HT);\n break;\n\n case s_req_http_HT:\n STRICT_CHECK(ch != 'T');\n UPDATE_STATE(s_req_http_HTT);\n break;\n\n case s_req_http_HTT:\n STRICT_CHECK(ch != 'P');\n UPDATE_STATE(s_req_http_HTTP);\n break;\n\n case s_req_http_I:\n STRICT_CHECK(ch != 'C');\n UPDATE_STATE(s_req_http_IC);\n break;\n\n case s_req_http_IC:\n STRICT_CHECK(ch != 'E');\n UPDATE_STATE(s_req_http_HTTP); /* Treat \"ICE\" as \"HTTP\". */\n break;\n\n case s_req_http_HTTP:\n STRICT_CHECK(ch != '/');\n UPDATE_STATE(s_req_http_major);\n break;\n\n case s_req_http_major:\n if (UNLIKELY(!IS_NUM(ch))) {\n SET_ERRNO(HPE_INVALID_VERSION);\n goto error;\n }\n\n parser->http_major = ch - '0';\n UPDATE_STATE(s_req_http_dot);\n break;\n\n case s_req_http_dot:\n {\n if (UNLIKELY(ch != '.')) {\n SET_ERRNO(HPE_INVALID_VERSION);\n goto error;\n }\n\n UPDATE_STATE(s_req_http_minor);\n break;\n }\n\n case s_req_http_minor:\n if (UNLIKELY(!IS_NUM(ch))) {\n SET_ERRNO(HPE_INVALID_VERSION);\n goto error;\n }\n\n parser->http_minor = ch - '0';\n UPDATE_STATE(s_req_http_end);\n break;\n\n case s_req_http_end:\n {\n if (ch == CR) {\n UPDATE_STATE(s_req_line_almost_done);\n break;\n }\n\n if (ch == LF) {\n UPDATE_STATE(s_header_field_start);\n break;\n }\n\n SET_ERRNO(HPE_INVALID_VERSION);\n goto error;\n break;\n }\n\n /* end of request line */\n case s_req_line_almost_done:\n {\n if (UNLIKELY(ch != LF)) {\n SET_ERRNO(HPE_LF_EXPECTED);\n goto error;\n }\n\n UPDATE_STATE(s_header_field_start);\n break;\n }\n\n case s_header_field_start:\n {\n if (ch == CR) {\n UPDATE_STATE(s_headers_almost_done);\n break;\n }\n\n if (ch == LF) {\n /* they might be just sending \\n instead of \\r\\n so this would be\n * the second \\n to denote the end of headers*/\n UPDATE_STATE(s_headers_almost_done);\n REEXECUTE();\n }\n\n c = TOKEN(ch);\n\n if (UNLIKELY(!c)) {\n SET_ERRNO(HPE_INVALID_HEADER_TOKEN);\n goto error;\n }\n\n MARK(header_field);\n\n parser->index = 0;\n UPDATE_STATE(s_header_field);\n\n switch (c) {\n case 'c':\n parser->header_state = h_C;\n break;\n\n case 'p':\n parser->header_state = h_matching_proxy_connection;\n break;\n\n case 't':\n parser->header_state = h_matching_transfer_encoding;\n break;\n\n case 'u':\n parser->header_state = h_matching_upgrade;\n break;\n\n default:\n parser->header_state = h_general;\n break;\n }\n break;\n }\n\n case s_header_field:\n {\n const char* start = p;\n for (; p != data + len; p++) {\n ch = *p;\n c = TOKEN(ch);\n\n if (!c)\n break;\n\n switch (parser->header_state) {\n case h_general: {\n size_t left = data + len - p;\n const char* pe = p + MIN(left, max_header_size);\n while (p+1 < pe && TOKEN(p[1])) {\n p++;\n }\n break;\n }\n\n case h_C:\n parser->index++;\n parser->header_state = (c == 'o' ? h_CO : h_general);\n break;\n\n case h_CO:\n parser->index++;\n parser->header_state = (c == 'n' ? h_CON : h_general);\n break;\n\n case h_CON:\n parser->index++;\n switch (c) {\n case 'n':\n parser->header_state = h_matching_connection;\n break;\n case 't':\n parser->header_state = h_matching_content_length;\n break;\n default:\n parser->header_state = h_general;\n break;\n }\n break;\n\n /* connection */\n\n case h_matching_connection:\n parser->index++;\n if (parser->index > sizeof(CONNECTION)-1\n || c != CONNECTION[parser->index]) {\n parser->header_state = h_general;\n } else if (parser->index == sizeof(CONNECTION)-2) {\n parser->header_state = h_connection;\n }\n break;\n\n /* proxy-connection */\n\n case h_matching_proxy_connection:\n parser->index++;\n if (parser->index > sizeof(PROXY_CONNECTION)-1\n || c != PROXY_CONNECTION[parser->index]) {\n parser->header_state = h_general;\n } else if (parser->index == sizeof(PROXY_CONNECTION)-2) {\n parser->header_state = h_connection;\n }\n break;\n\n /* content-length */\n\n case h_matching_content_length:\n parser->index++;\n if (parser->index > sizeof(CONTENT_LENGTH)-1\n || c != CONTENT_LENGTH[parser->index]) {\n parser->header_state = h_general;\n } else if (parser->index == sizeof(CONTENT_LENGTH)-2) {\n parser->header_state = h_content_length;\n }\n break;\n\n /* transfer-encoding */\n\n case h_matching_transfer_encoding:\n parser->index++;\n if (parser->index > sizeof(TRANSFER_ENCODING)-1\n || c != TRANSFER_ENCODING[parser->index]) {\n parser->header_state = h_general;\n } else if (parser->index == sizeof(TRANSFER_ENCODING)-2) {\n parser->header_state = h_transfer_encoding;\n }\n break;\n\n /* upgrade */\n\n case h_matching_upgrade:\n parser->index++;\n if (parser->index > sizeof(UPGRADE)-1\n || c != UPGRADE[parser->index]) {\n parser->header_state = h_general;\n } else if (parser->index == sizeof(UPGRADE)-2) {\n parser->header_state = h_upgrade;\n }\n break;\n\n case h_connection:\n case h_content_length:\n case h_transfer_encoding:\n case h_upgrade:\n if (ch != ' ') parser->header_state = h_general;\n break;\n\n default:\n assert(0 && \"Unknown header_state\");\n break;\n }\n }\n\n if (p == data + len) {\n --p;\n COUNT_HEADER_SIZE(p - start);\n break;\n }\n\n COUNT_HEADER_SIZE(p - start);\n\n if (ch == ':') {\n UPDATE_STATE(s_header_value_discard_ws);\n CALLBACK_DATA(header_field);\n break;\n }\n\n SET_ERRNO(HPE_INVALID_HEADER_TOKEN);\n goto error;\n }\n\n case s_header_value_discard_ws:\n if (ch == ' ' || ch == '\\t') break;\n\n if (ch == CR) {\n UPDATE_STATE(s_header_value_discard_ws_almost_done);\n break;\n }\n\n if (ch == LF) {\n UPDATE_STATE(s_header_value_discard_lws);\n break;\n }\n\n /* fall through */\n\n case s_header_value_start:\n {\n MARK(header_value);\n\n UPDATE_STATE(s_header_value);\n parser->index = 0;\n\n c = LOWER(ch);\n\n switch (parser->header_state) {\n case h_upgrade:\n parser->flags |= F_UPGRADE;\n parser->header_state = h_general;\n break;\n\n case h_transfer_encoding:\n /* looking for 'Transfer-Encoding: chunked' */\n if ('c' == c) {\n parser->header_state = h_matching_transfer_encoding_chunked;\n } else {\n parser->header_state = h_general;\n }\n break;\n\n case h_content_length:\n if (UNLIKELY(!IS_NUM(ch))) {\n SET_ERRNO(HPE_INVALID_CONTENT_LENGTH);\n goto error;\n }\n\n if (parser->flags & F_CONTENTLENGTH) {\n SET_ERRNO(HPE_UNEXPECTED_CONTENT_LENGTH);\n goto error;\n }\n\n parser->flags |= F_CONTENTLENGTH;\n parser->content_length = ch - '0';\n parser->header_state = h_content_length_num;\n break;\n\n /* when obsolete line folding is encountered for content length\n * continue to the s_header_value state */\n case h_content_length_ws:\n break;\n\n case h_connection:\n /* looking for 'Connection: keep-alive' */\n if (c == 'k') {\n parser->header_state = h_matching_connection_keep_alive;\n /* looking for 'Connection: close' */\n } else if (c == 'c') {\n parser->header_state = h_matching_connection_close;\n } else if (c == 'u') {\n parser->header_state = h_matching_connection_upgrade;\n } else {\n parser->header_state = h_matching_connection_token;\n }\n break;\n\n /* Multi-value `Connection` header */\n case h_matching_connection_token_start:\n break;\n\n default:\n parser->header_state = h_general;\n break;\n }\n break;\n }\n\n case s_header_value:\n {\n const char* start = p;\n enum header_states h_state = (enum header_states) parser->header_state;\n for (; p != data + len; p++) {\n ch = *p;\n if (ch == CR) {\n UPDATE_STATE(s_header_almost_done);\n parser->header_state = h_state;\n CALLBACK_DATA(header_value);\n break;\n }\n\n if (ch == LF) {\n UPDATE_STATE(s_header_almost_done);\n COUNT_HEADER_SIZE(p - start);\n parser->header_state = h_state;\n CALLBACK_DATA_NOADVANCE(header_value);\n REEXECUTE();\n }\n\n if (!lenient && !IS_HEADER_CHAR(ch)) {\n SET_ERRNO(HPE_INVALID_HEADER_TOKEN);\n goto error;\n }\n\n c = LOWER(ch);\n\n switch (h_state) {\n case h_general:\n {\n size_t left = data + len - p;\n const char* pe = p + MIN(left, max_header_size);\n\n for (; p != pe; p++) {\n ch = *p;\n if (ch == CR || ch == LF) {\n --p;\n break;\n }\n if (!lenient && !IS_HEADER_CHAR(ch)) {\n SET_ERRNO(HPE_INVALID_HEADER_TOKEN);\n goto error;\n }\n }\n if (p == data + len)\n --p;\n break;\n }\n\n case h_connection:\n case h_transfer_encoding:\n assert(0 && \"Shouldn't get here.\");\n break;\n\n case h_content_length:\n if (ch == ' ') break;\n h_state = h_content_length_num;\n /* fall through */\n\n case h_content_length_num:\n {\n uint64_t t;\n\n if (ch == ' ') {\n h_state = h_content_length_ws;\n break;\n }\n\n if (UNLIKELY(!IS_NUM(ch))) {\n SET_ERRNO(HPE_INVALID_CONTENT_LENGTH);\n parser->header_state = h_state;\n goto error;\n }\n\n t = parser->content_length;\n t *= 10;\n t += ch - '0';\n\n /* Overflow? Test against a conservative limit for simplicity. */\n if (UNLIKELY((ULLONG_MAX - 10) / 10 < parser->content_length)) {\n SET_ERRNO(HPE_INVALID_CONTENT_LENGTH);\n parser->header_state = h_state;\n goto error;\n }\n\n parser->content_length = t;\n break;\n }\n\n case h_content_length_ws:\n if (ch == ' ') break;\n SET_ERRNO(HPE_INVALID_CONTENT_LENGTH);\n parser->header_state = h_state;\n goto error;\n\n /* Transfer-Encoding: chunked */\n case h_matching_transfer_encoding_chunked:\n parser->index++;\n if (parser->index > sizeof(CHUNKED)-1\n || c != CHUNKED[parser->index]) {\n h_state = h_general;\n } else if (parser->index == sizeof(CHUNKED)-2) {\n h_state = h_transfer_encoding_chunked;\n }\n break;\n\n case h_matching_connection_token_start:\n /* looking for 'Connection: keep-alive' */\n if (c == 'k') {\n h_state = h_matching_connection_keep_alive;\n /* looking for 'Connection: close' */\n } else if (c == 'c') {\n h_state = h_matching_connection_close;\n } else if (c == 'u') {\n h_state = h_matching_connection_upgrade;\n } else if (STRICT_TOKEN(c)) {\n h_state = h_matching_connection_token;\n } else if (c == ' ' || c == '\\t') {\n /* Skip lws */\n } else {\n h_state = h_general;\n }\n break;\n\n /* looking for 'Connection: keep-alive' */\n case h_matching_connection_keep_alive:\n parser->index++;\n if (parser->index > sizeof(KEEP_ALIVE)-1\n || c != KEEP_ALIVE[parser->index]) {\n h_state = h_matching_connection_token;\n } else if (parser->index == sizeof(KEEP_ALIVE)-2) {\n h_state = h_connection_keep_alive;\n }\n break;\n\n /* looking for 'Connection: close' */\n case h_matching_connection_close:\n parser->index++;\n if (parser->index > sizeof(CLOSE)-1 || c != CLOSE[parser->index]) {\n h_state = h_matching_connection_token;\n } else if (parser->index == sizeof(CLOSE)-2) {\n h_state = h_connection_close;\n }\n break;\n\n /* looking for 'Connection: upgrade' */\n case h_matching_connection_upgrade:\n parser->index++;\n if (parser->index > sizeof(UPGRADE) - 1 ||\n c != UPGRADE[parser->index]) {\n h_state = h_matching_connection_token;\n } else if (parser->index == sizeof(UPGRADE)-2) {\n h_state = h_connection_upgrade;\n }\n break;\n\n case h_matching_connection_token:\n if (ch == ',') {\n h_state = h_matching_connection_token_start;\n parser->index = 0;\n }\n break;\n\n case h_transfer_encoding_chunked:\n if (ch != ' ') h_state = h_general;\n break;\n\n case h_connection_keep_alive:\n case h_connection_close:\n case h_connection_upgrade:\n if (ch == ',') {\n if (h_state == h_connection_keep_alive) {\n parser->flags |= F_CONNECTION_KEEP_ALIVE;\n } else if (h_state == h_connection_close) {\n parser->flags |= F_CONNECTION_CLOSE;\n } else if (h_state == h_connection_upgrade) {\n parser->flags |= F_CONNECTION_UPGRADE;\n }\n h_state = h_matching_connection_token_start;\n parser->index = 0;\n } else if (ch != ' ') {\n h_state = h_matching_connection_token;\n }\n break;\n\n default:\n UPDATE_STATE(s_header_value);\n h_state = h_general;\n break;\n }\n }\n parser->header_state = h_state;\n\n if (p == data + len)\n --p;\n\n COUNT_HEADER_SIZE(p - start);\n break;\n }\n\n case s_header_almost_done:\n {\n if (UNLIKELY(ch != LF)) {\n SET_ERRNO(HPE_LF_EXPECTED);\n goto error;\n }\n\n UPDATE_STATE(s_header_value_lws);\n break;\n }\n\n case s_header_value_lws:\n {\n if (ch == ' ' || ch == '\\t') {\n if (parser->header_state == h_content_length_num) {\n /* treat obsolete line folding as space */\n parser->header_state = h_content_length_ws;\n }\n UPDATE_STATE(s_header_value_start);\n REEXECUTE();\n }\n\n /* finished the header */\n switch (parser->header_state) {\n case h_connection_keep_alive:\n parser->flags |= F_CONNECTION_KEEP_ALIVE;\n break;\n case h_connection_close:\n parser->flags |= F_CONNECTION_CLOSE;\n break;\n case h_transfer_encoding_chunked:\n parser->flags |= F_CHUNKED;\n break;\n case h_connection_upgrade:\n parser->flags |= F_CONNECTION_UPGRADE;\n break;\n default:\n break;\n }\n\n UPDATE_STATE(s_header_field_start);\n REEXECUTE();\n }\n\n case s_header_value_discard_ws_almost_done:\n {\n STRICT_CHECK(ch != LF);\n UPDATE_STATE(s_header_value_discard_lws);\n break;\n }\n\n case s_header_value_discard_lws:\n {\n if (ch == ' ' || ch == '\\t') {\n UPDATE_STATE(s_header_value_discard_ws);\n break;\n } else {\n switch (parser->header_state) {\n case h_connection_keep_alive:\n parser->flags |= F_CONNECTION_KEEP_ALIVE;\n break;\n case h_connection_close:\n parser->flags |= F_CONNECTION_CLOSE;\n break;\n case h_connection_upgrade:\n parser->flags |= F_CONNECTION_UPGRADE;\n break;\n case h_transfer_encoding_chunked:\n parser->flags |= F_CHUNKED;\n break;\n case h_content_length:\n /* do not allow empty content length */\n SET_ERRNO(HPE_INVALID_CONTENT_LENGTH);\n goto error;\n break;\n default:\n break;\n }\n\n /* header value was empty */\n MARK(header_value);\n UPDATE_STATE(s_header_field_start);\n CALLBACK_DATA_NOADVANCE(header_value);\n REEXECUTE();\n }\n }\n\n case s_headers_almost_done:\n {\n STRICT_CHECK(ch != LF);\n\n if (parser->flags & F_TRAILING) {\n /* End of a chunked request */\n UPDATE_STATE(s_message_done);\n CALLBACK_NOTIFY_NOADVANCE(chunk_complete);\n REEXECUTE();\n }\n\n /* Cannot use chunked encoding and a content-length header together\n per the HTTP specification. */\n if ((parser->flags & F_CHUNKED) &&\n (parser->flags & F_CONTENTLENGTH)) {\n SET_ERRNO(HPE_UNEXPECTED_CONTENT_LENGTH);\n goto error;\n }\n\n UPDATE_STATE(s_headers_done);\n\n /* Set this here so that on_headers_complete() callbacks can see it */\n if ((parser->flags & F_UPGRADE) &&\n (parser->flags & F_CONNECTION_UPGRADE)) {\n /* For responses, \"Upgrade: foo\" and \"Connection: upgrade\" are\n * mandatory only when it is a 101 Switching Protocols response,\n * otherwise it is purely informational, to announce support.\n */\n parser->upgrade =\n (parser->type == HTTP_REQUEST || parser->status_code == 101);\n } else {\n parser->upgrade = (parser->method == HTTP_CONNECT);\n }\n\n /* Here we call the headers_complete callback. This is somewhat\n * different than other callbacks because if the user returns 1, we\n * will interpret that as saying that this message has no body. This\n * is needed for the annoying case of recieving a response to a HEAD\n * request.\n *\n * We'd like to use CALLBACK_NOTIFY_NOADVANCE() here but we cannot, so\n * we have to simulate it by handling a change in errno below.\n */\n if (settings->on_headers_complete) {\n switch (settings->on_headers_complete(parser)) {\n case 0:\n break;\n\n case 2:\n parser->upgrade = 1;\n\n /* fall through */\n case 1:\n parser->flags |= F_SKIPBODY;\n break;\n\n default:\n SET_ERRNO(HPE_CB_headers_complete);\n RETURN(p - data); /* Error */\n }\n }\n\n if (HTTP_PARSER_ERRNO(parser) != HPE_OK) {\n RETURN(p - data);\n }\n\n REEXECUTE();\n }\n\n case s_headers_done:\n {\n int hasBody;\n STRICT_CHECK(ch != LF);\n\n parser->nread = 0;\n nread = 0;\n\n hasBody = parser->flags & F_CHUNKED ||\n (parser->content_length > 0 && parser->content_length != ULLONG_MAX);\n if (parser->upgrade && (parser->method == HTTP_CONNECT ||\n (parser->flags & F_SKIPBODY) || !hasBody)) {\n /* Exit, the rest of the message is in a different protocol. */\n UPDATE_STATE(NEW_MESSAGE());\n CALLBACK_NOTIFY(message_complete);\n RETURN((p - data) + 1);\n }\n\n if (parser->flags & F_SKIPBODY) {\n UPDATE_STATE(NEW_MESSAGE());\n CALLBACK_NOTIFY(message_complete);\n } else if (parser->flags & F_CHUNKED) {\n /* chunked encoding - ignore Content-Length header */\n UPDATE_STATE(s_chunk_size_start);\n } else {\n if (parser->content_length == 0) {\n /* Content-Length header given but zero: Content-Length: 0\\r\\n */\n UPDATE_STATE(NEW_MESSAGE());\n CALLBACK_NOTIFY(message_complete);\n } else if (parser->content_length != ULLONG_MAX) {\n /* Content-Length header given and non-zero */\n UPDATE_STATE(s_body_identity);\n } else {\n if (!http_message_needs_eof(parser)) {\n /* Assume content-length 0 - read the next */\n UPDATE_STATE(NEW_MESSAGE());\n CALLBACK_NOTIFY(message_complete);\n } else {\n /* Read body until EOF */\n UPDATE_STATE(s_body_identity_eof);\n }\n }\n }\n\n break;\n }\n\n case s_body_identity:\n {\n uint64_t to_read = MIN(parser->content_length,\n (uint64_t) ((data + len) - p));\n\n assert(parser->content_length != 0\n && parser->content_length != ULLONG_MAX);\n\n /* The difference between advancing content_length and p is because\n * the latter will automaticaly advance on the next loop iteration.\n * Further, if content_length ends up at 0, we want to see the last\n * byte again for our message complete callback.\n */\n MARK(body);\n parser->content_length -= to_read;\n p += to_read - 1;\n\n if (parser->content_length == 0) {\n UPDATE_STATE(s_message_done);\n\n /* Mimic CALLBACK_DATA_NOADVANCE() but with one extra byte.\n *\n * The alternative to doing this is to wait for the next byte to\n * trigger the data callback, just as in every other case. The\n * problem with this is that this makes it difficult for the test\n * harness to distinguish between complete-on-EOF and\n * complete-on-length. It's not clear that this distinction is\n * important for applications, but let's keep it for now.\n */\n CALLBACK_DATA_(body, p - body_mark + 1, p - data);\n REEXECUTE();\n }\n\n break;\n }\n\n /* read until EOF */\n case s_body_identity_eof:\n MARK(body);\n p = data + len - 1;\n\n break;\n\n case s_message_done:\n UPDATE_STATE(NEW_MESSAGE());\n CALLBACK_NOTIFY(message_complete);\n if (parser->upgrade) {\n /* Exit, the rest of the message is in a different protocol. */\n RETURN((p - data) + 1);\n }\n break;\n\n case s_chunk_size_start:\n {\n assert(nread == 1);\n assert(parser->flags & F_CHUNKED);\n\n unhex_val = unhex[(unsigned char)ch];\n if (UNLIKELY(unhex_val == -1)) {\n SET_ERRNO(HPE_INVALID_CHUNK_SIZE);\n goto error;\n }\n\n parser->content_length = unhex_val;\n UPDATE_STATE(s_chunk_size);\n break;\n }\n\n case s_chunk_size:\n {\n uint64_t t;\n\n assert(parser->flags & F_CHUNKED);\n\n if (ch == CR) {\n UPDATE_STATE(s_chunk_size_almost_done);\n break;\n }\n\n unhex_val = unhex[(unsigned char)ch];\n\n if (unhex_val == -1) {\n if (ch == ';' || ch == ' ') {\n UPDATE_STATE(s_chunk_parameters);\n break;\n }\n\n SET_ERRNO(HPE_INVALID_CHUNK_SIZE);\n goto error;\n }\n\n t = parser->content_length;\n t *= 16;\n t += unhex_val;\n\n /* Overflow? Test against a conservative limit for simplicity. */\n if (UNLIKELY((ULLONG_MAX - 16) / 16 < parser->content_length)) {\n SET_ERRNO(HPE_INVALID_CONTENT_LENGTH);\n goto error;\n }\n\n parser->content_length = t;\n break;\n }\n\n case s_chunk_parameters:\n {\n assert(parser->flags & F_CHUNKED);\n /* just ignore this shit. TODO check for overflow */\n if (ch == CR) {\n UPDATE_STATE(s_chunk_size_almost_done);\n break;\n }\n break;\n }\n\n case s_chunk_size_almost_done:\n {\n assert(parser->flags & F_CHUNKED);\n STRICT_CHECK(ch != LF);\n\n parser->nread = 0;\n nread = 0;\n\n if (parser->content_length == 0) {\n parser->flags |= F_TRAILING;\n UPDATE_STATE(s_header_field_start);\n } else {\n UPDATE_STATE(s_chunk_data);\n }\n CALLBACK_NOTIFY(chunk_header);\n break;\n }\n\n case s_chunk_data:\n {\n uint64_t to_read = MIN(parser->content_length,\n (uint64_t) ((data + len) - p));\n\n assert(parser->flags & F_CHUNKED);\n assert(parser->content_length != 0\n && parser->content_length != ULLONG_MAX);\n\n /* See the explanation in s_body_identity for why the content\n * length and data pointers are managed this way.\n */\n MARK(body);\n parser->content_length -= to_read;\n p += to_read - 1;\n\n if (parser->content_length == 0) {\n UPDATE_STATE(s_chunk_data_almost_done);\n }\n\n break;\n }\n\n case s_chunk_data_almost_done:\n assert(parser->flags & F_CHUNKED);\n assert(parser->content_length == 0);\n STRICT_CHECK(ch != CR);\n UPDATE_STATE(s_chunk_data_done);\n CALLBACK_DATA(body);\n break;\n\n case s_chunk_data_done:\n assert(parser->flags & F_CHUNKED);\n STRICT_CHECK(ch != LF);\n parser->nread = 0;\n nread = 0;\n UPDATE_STATE(s_chunk_size_start);\n CALLBACK_NOTIFY(chunk_complete);\n break;\n\n default:\n assert(0 && \"unhandled state\");\n SET_ERRNO(HPE_INVALID_INTERNAL_STATE);\n goto error;\n }\n }\n\n /* Run callbacks for any marks that we have leftover after we ran out of\n * bytes. There should be at most one of these set, so it's OK to invoke\n * them in series (unset marks will not result in callbacks).\n *\n * We use the NOADVANCE() variety of callbacks here because 'p' has already\n * overflowed 'data' and this allows us to correct for the off-by-one that\n * we'd otherwise have (since CALLBACK_DATA() is meant to be run with a 'p'\n * value that's in-bounds).\n */\n\n assert(((header_field_mark ? 1 : 0) +\n (header_value_mark ? 1 : 0) +\n (url_mark ? 1 : 0) +\n (body_mark ? 1 : 0) +\n (status_mark ? 1 : 0)) <= 1);\n\n CALLBACK_DATA_NOADVANCE(header_field);\n CALLBACK_DATA_NOADVANCE(header_value);\n CALLBACK_DATA_NOADVANCE(url);\n CALLBACK_DATA_NOADVANCE(body);\n CALLBACK_DATA_NOADVANCE(status);\n\n RETURN(len);\n\nerror:\n if (HTTP_PARSER_ERRNO(parser) == HPE_OK) {\n SET_ERRNO(HPE_UNKNOWN);\n }\n\n RETURN(p - data); ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-444'], 'message': 'Support multi-coding Transfer-Encoding\n\n`Transfer-Encoding` header might have multiple codings in it. Even\nthough llhttp cares only about `chunked`, it must check that `chunked`\nis the last coding (if present).\n\nABNF from RFC 7230:\n\n```\nTransfer-Encoding = *( \",\" OWS ) transfer-coding *( OWS \",\" [ OWS\n transfer-coding ] )\ntransfer-coding = \"chunked\" / \"compress\" / \"deflate\" / \"gzip\" /\n transfer-extension\n transfer-extension = token *( OWS \";\" OWS transfer-parameter )\n transfer-parameter = token BWS \"=\" BWS ( token / quoted-string )\n```\n\nHowever, if `chunked` is not last - llhttp must assume that the encoding\nand size of the body is unknown (according to 3.3.3 of RFC 7230) and\nread the response until EOF. For request - the error must be raised for\nan unknown `Transfer-Encoding`.\n\nFurthermore, 3.3.3 of RFC 7230 explicitly states that presence of both\n`Transfer-Encoding` and `Content-Length` indicates the smuggling attack\nand \"ought to be handled as an error\".\n\nFor the lenient mode:\n\n* Unknown `Transfer-Encoding` in requests is not an error and request\n body is simply read until EOF (end of connection)\n* Only `Transfer-Encoding: chunked` together with `Content-Length` would\n result an error (just like before the patch)\n\nPR-URL: https://github.com/nodejs-private/http-parser-private/pull/4\nReviewed-By: Matteo Collina \nReviewed-By: Sam Roberts \nReviewed-By: James M Snell '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: archive_wstring_append_from_mbs(struct archive_wstring *dest,\n const char *p, size_t len)\n{\n\tsize_t r;\n\tint ret_val = 0;\n\t/*\n\t * No single byte will be more than one wide character,\n\t * so this length estimate will always be big enough.\n\t */\n\tsize_t wcs_length = len;\n\tsize_t mbs_length = len;\n\tconst char *mbs = p;\n\twchar_t *wcs;\n#if HAVE_MBRTOWC\n\tmbstate_t shift_state;\n\n\tmemset(&shift_state, 0, sizeof(shift_state));\n#endif\n\tif (NULL == archive_wstring_ensure(dest, dest->length + wcs_length + 1))\n\t\treturn (-1);\n\twcs = dest->s + dest->length;\n\t/*\n\t * We cannot use mbsrtowcs/mbstowcs here because those may convert\n\t * extra MBS when strlen(p) > len and one wide character consists of\n\t * multi bytes.\n\t */\n\twhile (*mbs && mbs_length > 0) {\n\t\tif (wcs_length == 0) {\n\t\t\tdest->length = wcs - dest->s;\n\t\t\tdest->s[dest->length] = L'\\0';\n\t\t\twcs_length = mbs_length;\n\t\t\tif (NULL == archive_wstring_ensure(dest,\n\t\t\t dest->length + wcs_length + 1))\n\t\t\t\treturn (-1);\n\t\t\twcs = dest->s + dest->length;\n\t\t}\n#if HAVE_MBRTOWC\n\t\tr = mbrtowc(wcs, mbs, wcs_length, &shift_state);\n#else\n\t\tr = mbtowc(wcs, mbs, wcs_length);\n#endif\n\t\tif (r == (size_t)-1 || r == (size_t)-2) {\n\t\t\tret_val = -1;\n\t\t\tif (errno == EILSEQ) {\n\t\t\t\t++mbs;\n\t\t\t\t--mbs_length;\n\t\t\t\tcontinue;\n\t\t\t} else\n\t\t\t\tbreak;\n\t\t}\n\t\tif (r == 0 || r > mbs_length)\n\t\t\tbreak;\n\t\twcs++;\n\t\twcs_length--;\n\t\tmbs += r;\n\t\tmbs_length -= r;\n\t}\n\tdest->length = wcs - dest->s;\n\tdest->s[dest->length] = L'\\0';\n\treturn (ret_val);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Bugfix and optimize archive_wstring_append_from_mbs()\n\nThe cal to mbrtowc() or mbtowc() should read up to mbs_length\nbytes and not wcs_length. This avoids out-of-bounds reads.\n\nmbrtowc() and mbtowc() return (size_t)-1 wit errno EILSEQ when\nthey encounter an invalid multibyte character and (size_t)-2 when\nthey they encounter an incomplete multibyte character. As we return\nfailure and all our callers error out it makes no sense to continue\nparsing mbs.\n\nAs we allocate `len` wchars at the beginning and each wchar has\nat least one byte, there will never be need to grow the buffer,\nso the code can be left out. On the other hand, we are always\nallocatng more memory than we need.\n\nAs long as wcs_length == mbs_length == len we can omit wcs_length.\nWe keep the old code commented if we decide to save memory and\nuse autoexpanding wcs_length in the future.\n\nFixes #1276'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadDOTImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n char\n command[MaxTextExtent];\n\n const char\n *option;\n\n graph_t\n *graph;\n\n Image\n *image;\n\n ImageInfo\n *read_info;\n\n MagickBooleanType\n status;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n assert(graphic_context != (GVC_t *) NULL);\n image=AcquireImage(image_info);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n read_info=CloneImageInfo(image_info);\n SetImageInfoBlob(read_info,(void *) NULL,0);\n (void) CopyMagickString(read_info->magick,\"SVG\",MaxTextExtent);\n (void) AcquireUniqueFilename(read_info->filename);\n (void) FormatLocaleString(command,MaxTextExtent,\"-Tsvg -o%s %s\",\n read_info->filename,image_info->filename);\n#if !defined(WITH_CGRAPH)\n graph=agread(GetBlobFileHandle(image));\n#else\n graph=agread(GetBlobFileHandle(image),(Agdisc_t *) NULL);\n#endif\n if (graph == (graph_t *) NULL)\n {\n (void) RelinquishUniqueFileResource(read_info->filename);\n return ((Image *) NULL);\n }\n option=GetImageOption(image_info,\"dot:layout-engine\");\n if (option == (const char *) NULL)\n gvLayout(graphic_context,graph,(char *) \"dot\");\n else\n gvLayout(graphic_context,graph,(char *) option);\n gvRenderFilename(graphic_context,graph,(char *) \"svg\",read_info->filename);\n gvFreeLayout(graphic_context,graph);\n agclose(graph);\n /*\n Read SVG graph.\n */\n (void) CopyMagickString(read_info->magick,\"SVG\",MaxTextExtent);\n image=ReadImage(read_info,exception);\n (void) RelinquishUniqueFileResource(read_info->filename);\n read_info=DestroyImageInfo(read_info);\n if (image == (Image *) NULL)\n return((Image *) NULL);\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'Fixed memory leak reported in #1558 and fixed other leak.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: search_in_range(regex_t* reg, const UChar* str, const UChar* end,\n const UChar* start, const UChar* range, /* match start range */\n const UChar* data_range, /* subject string range */\n OnigRegion* region,\n OnigOptionType option, OnigMatchParam* mp)\n{\n int r;\n UChar *s, *prev;\n MatchArg msa;\n const UChar *orig_start = start;\n\n#ifdef ONIG_DEBUG_SEARCH\n fprintf(stderr,\n \"onig_search (entry point): str: %p, end: %d, start: %d, range: %d\\n\",\n str, (int )(end - str), (int )(start - str), (int )(range - str));\n#endif\n\n ADJUST_MATCH_PARAM(reg, mp);\n\n if (region\n#ifdef USE_POSIX_API_REGION_OPTION\n && !IS_POSIX_REGION(option)\n#endif\n ) {\n r = onig_region_resize_clear(region, reg->num_mem + 1);\n if (r != 0) goto finish_no_msa;\n }\n\n if (start > end || start < str) goto mismatch_no_msa;\n\n if (ONIG_IS_OPTION_ON(option, ONIG_OPTION_CHECK_VALIDITY_OF_STRING)) {\n if (! ONIGENC_IS_VALID_MBC_STRING(reg->enc, str, end)) {\n r = ONIGERR_INVALID_WIDE_CHAR_VALUE;\n goto finish_no_msa;\n }\n }\n\n\n#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE\n#define MATCH_AND_RETURN_CHECK(upper_range) \\\n r = match_at(reg, str, end, (upper_range), s, prev, &msa); \\\n if (r != ONIG_MISMATCH) {\\\n if (r >= 0) {\\\n if (! IS_FIND_LONGEST(reg->options)) {\\\n goto match;\\\n }\\\n }\\\n else goto finish; /* error */ \\\n }\n#else\n#define MATCH_AND_RETURN_CHECK(upper_range) \\\n r = match_at(reg, str, end, (upper_range), s, prev, &msa); \\\n if (r != ONIG_MISMATCH) {\\\n if (r >= 0) {\\\n goto match;\\\n }\\\n else goto finish; /* error */ \\\n }\n#endif /* USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE */\n\n\n /* anchor optimize: resume search range */\n if (reg->anchor != 0 && str < end) {\n UChar *min_semi_end, *max_semi_end;\n\n if (reg->anchor & ANCR_BEGIN_POSITION) {\n /* search start-position only */\n begin_position:\n if (range > start)\n range = start + 1;\n else\n range = start;\n }\n else if (reg->anchor & ANCR_BEGIN_BUF) {\n /* search str-position only */\n if (range > start) {\n if (start != str) goto mismatch_no_msa;\n range = str + 1;\n }\n else {\n if (range <= str) {\n start = str;\n range = str;\n }\n else\n goto mismatch_no_msa;\n }\n }\n else if (reg->anchor & ANCR_END_BUF) {\n min_semi_end = max_semi_end = (UChar* )end;\n\n end_buf:\n if ((OnigLen )(max_semi_end - str) < reg->anc_dist_min)\n goto mismatch_no_msa;\n\n if (range > start) {\n if ((OnigLen )(min_semi_end - start) > reg->anc_dist_max) {\n start = min_semi_end - reg->anc_dist_max;\n if (start < end)\n start = onigenc_get_right_adjust_char_head(reg->enc, str, start);\n }\n if ((OnigLen )(max_semi_end - (range - 1)) < reg->anc_dist_min) {\n range = max_semi_end - reg->anc_dist_min + 1;\n }\n\n if (start > range) goto mismatch_no_msa;\n /* If start == range, match with empty at end.\n Backward search is used. */\n }\n else {\n if ((OnigLen )(min_semi_end - range) > reg->anc_dist_max) {\n range = min_semi_end - reg->anc_dist_max;\n }\n if ((OnigLen )(max_semi_end - start) < reg->anc_dist_min) {\n start = max_semi_end - reg->anc_dist_min;\n start = ONIGENC_LEFT_ADJUST_CHAR_HEAD(reg->enc, str, start);\n }\n if (range > start) goto mismatch_no_msa;\n }\n }\n else if (reg->anchor & ANCR_SEMI_END_BUF) {\n UChar* pre_end = ONIGENC_STEP_BACK(reg->enc, str, end, 1);\n\n max_semi_end = (UChar* )end;\n if (ONIGENC_IS_MBC_NEWLINE(reg->enc, pre_end, end)) {\n min_semi_end = pre_end;\n\n#ifdef USE_CRNL_AS_LINE_TERMINATOR\n pre_end = ONIGENC_STEP_BACK(reg->enc, str, pre_end, 1);\n if (IS_NOT_NULL(pre_end) &&\n ONIGENC_IS_MBC_CRNL(reg->enc, pre_end, end)) {\n min_semi_end = pre_end;\n }\n#endif\n if (min_semi_end > str && start <= min_semi_end) {\n goto end_buf;\n }\n }\n else {\n min_semi_end = (UChar* )end;\n goto end_buf;\n }\n }\n else if ((reg->anchor & ANCR_ANYCHAR_INF_ML)) {\n goto begin_position;\n }\n }\n else if (str == end) { /* empty string */\n static const UChar* address_for_empty_string = (UChar* )\"\";\n\n#ifdef ONIG_DEBUG_SEARCH\n fprintf(stderr, \"onig_search: empty string.\\n\");\n#endif\n\n if (reg->threshold_len == 0) {\n start = end = str = address_for_empty_string;\n s = (UChar* )start;\n prev = (UChar* )NULL;\n\n MATCH_ARG_INIT(msa, reg, option, region, start, mp);\n MATCH_AND_RETURN_CHECK(end);\n goto mismatch;\n }\n goto mismatch_no_msa;\n }\n\n#ifdef ONIG_DEBUG_SEARCH\n fprintf(stderr, \"onig_search(apply anchor): end: %d, start: %d, range: %d\\n\",\n (int )(end - str), (int )(start - str), (int )(range - str));\n#endif\n\n MATCH_ARG_INIT(msa, reg, option, region, orig_start, mp);\n\n s = (UChar* )start;\n if (range > start) { /* forward search */\n if (s > str)\n prev = onigenc_get_prev_char_head(reg->enc, str, s);\n else\n prev = (UChar* )NULL;\n\n if (reg->optimize != OPTIMIZE_NONE) {\n UChar *sch_range, *low, *high, *low_prev;\n\n if (reg->dist_max != 0) {\n if (reg->dist_max == INFINITE_LEN)\n sch_range = (UChar* )end;\n else {\n if ((end - range) < reg->dist_max)\n sch_range = (UChar* )end;\n else {\n sch_range = (UChar* )range + reg->dist_max;\n }\n }\n }\n else\n sch_range = (UChar* )range;\n\n if ((end - start) < reg->threshold_len)\n goto mismatch;\n\n if (reg->dist_max != INFINITE_LEN) {\n do {\n if (! forward_search(reg, str, end, s, sch_range, &low, &high,\n &low_prev)) goto mismatch;\n if (s < low) {\n s = low;\n prev = low_prev;\n }\n while (s <= high) {\n MATCH_AND_RETURN_CHECK(data_range);\n prev = s;\n s += enclen(reg->enc, s);\n }\n } while (s < range);\n goto mismatch;\n }\n else { /* check only. */\n if (! forward_search(reg, str, end, s, sch_range, &low, &high,\n (UChar** )NULL)) goto mismatch;\n\n if ((reg->anchor & ANCR_ANYCHAR_INF) != 0) {\n do {\n MATCH_AND_RETURN_CHECK(data_range);\n prev = s;\n s += enclen(reg->enc, s);\n\n if ((reg->anchor & (ANCR_LOOK_BEHIND | ANCR_PREC_READ_NOT)) == 0) {\n while (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end) && s < range) {\n prev = s;\n s += enclen(reg->enc, s);\n }\n }\n } while (s < range);\n goto mismatch;\n }\n }\n }\n\n do {\n MATCH_AND_RETURN_CHECK(data_range);\n prev = s;\n s += enclen(reg->enc, s);\n } while (s < range);\n\n if (s == range) { /* because empty match with /$/. */\n MATCH_AND_RETURN_CHECK(data_range);\n }\n }\n else { /* backward search */\n if (range < str) goto mismatch;\n\n if (orig_start < end)\n orig_start += enclen(reg->enc, orig_start); /* is upper range */\n\n if (reg->optimize != OPTIMIZE_NONE) {\n UChar *low, *high, *adjrange, *sch_start;\n const UChar *min_range;\n\n if ((end - range) < reg->threshold_len) goto mismatch;\n\n if (range < end)\n adjrange = ONIGENC_LEFT_ADJUST_CHAR_HEAD(reg->enc, str, range);\n else\n adjrange = (UChar* )end;\n\n if (end - range > reg->dist_min)\n min_range = range + reg->dist_min;\n else\n min_range = end;\n\n if (reg->dist_max != INFINITE_LEN) {\n do {\n if (end - s > reg->dist_max)\n sch_start = s + reg->dist_max;\n else {\n sch_start = onigenc_get_prev_char_head(reg->enc, str, end);\n }\n\n if (backward_search(reg, str, end, sch_start, min_range, adjrange,\n &low, &high) <= 0)\n goto mismatch;\n\n if (s > high)\n s = high;\n\n while (s >= low) {\n prev = onigenc_get_prev_char_head(reg->enc, str, s);\n MATCH_AND_RETURN_CHECK(orig_start);\n s = prev;\n }\n } while (s >= range);\n goto mismatch;\n }\n else { /* check only. */\n sch_start = onigenc_get_prev_char_head(reg->enc, str, end);\n\n if (backward_search(reg, str, end, sch_start, min_range, adjrange,\n &low, &high) <= 0) goto mismatch;\n }\n }\n\n do {\n prev = onigenc_get_prev_char_head(reg->enc, str, s);\n MATCH_AND_RETURN_CHECK(orig_start);\n s = prev;\n } while (s >= range);\n }\n\n mismatch:\n#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE\n if (IS_FIND_LONGEST(reg->options)) {\n if (msa.best_len >= 0) {\n s = msa.best_s;\n goto match;\n }\n }\n#endif\n r = ONIG_MISMATCH;\n\n finish:\n MATCH_ARG_FREE(msa);\n\n /* If result is mismatch and no FIND_NOT_EMPTY option,\n then the region is not set in match_at(). */\n if (IS_FIND_NOT_EMPTY(reg->options) && region\n#ifdef USE_POSIX_API_REGION_OPTION\n && !IS_POSIX_REGION(option)\n#endif\n ) {\n onig_region_clear(region);\n }\n\n#ifdef ONIG_DEBUG\n if (r != ONIG_MISMATCH)\n fprintf(stderr, \"onig_search: error %d\\n\", r);\n#endif\n return r;\n\n mismatch_no_msa:\n r = ONIG_MISMATCH;\n finish_no_msa:\n#ifdef ONIG_DEBUG\n if (r != ONIG_MISMATCH)\n fprintf(stderr, \"onig_search: error %d\\n\", r);\n#endif\n return r;\n\n match:\n MATCH_ARG_FREE(msa);\n return (int )(s - str);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'fix #164: Integer overflow related to reg->dmax in search_in_range()'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void sm501_2d_operation(SM501State *s)\n{\n int cmd = (s->twoD_control >> 16) & 0x1F;\n int rtl = s->twoD_control & BIT(27);\n int format = (s->twoD_stretch >> 20) & 0x3;\n int rop_mode = (s->twoD_control >> 15) & 0x1; /* 1 for rop2, else rop3 */\n /* 1 if rop2 source is the pattern, otherwise the source is the bitmap */\n int rop2_source_is_pattern = (s->twoD_control >> 14) & 0x1;\n int rop = s->twoD_control & 0xFF;\n int dst_x = (s->twoD_destination >> 16) & 0x01FFF;\n int dst_y = s->twoD_destination & 0xFFFF;\n int width = (s->twoD_dimension >> 16) & 0x1FFF;\n int height = s->twoD_dimension & 0xFFFF;\n uint32_t dst_base = s->twoD_destination_base & 0x03FFFFFF;\n uint8_t *dst = s->local_mem + dst_base;\n int dst_pitch = (s->twoD_pitch >> 16) & 0x1FFF;\n int crt = (s->dc_crt_control & SM501_DC_CRT_CONTROL_SEL) ? 1 : 0;\n int fb_len = get_width(s, crt) * get_height(s, crt) * get_bpp(s, crt);\n\n if ((s->twoD_stretch >> 16) & 0xF) {\n qemu_log_mask(LOG_UNIMP, \"sm501: only XY addressing is supported.\\n\");\n return;\n }\n\n if (rop_mode == 0) {\n if (rop != 0xcc) {\n /* Anything other than plain copies are not supported */\n qemu_log_mask(LOG_UNIMP, \"sm501: rop3 mode with rop %x is not \"\n \"supported.\\n\", rop);\n }\n } else {\n if (rop2_source_is_pattern && rop != 0x5) {\n /* For pattern source, we support only inverse dest */\n qemu_log_mask(LOG_UNIMP, \"sm501: rop2 source being the pattern and \"\n \"rop %x is not supported.\\n\", rop);\n } else {\n if (rop != 0x5 && rop != 0xc) {\n /* Anything other than plain copies or inverse dest is not\n * supported */\n qemu_log_mask(LOG_UNIMP, \"sm501: rop mode %x is not \"\n \"supported.\\n\", rop);\n }\n }\n }\n\n if (s->twoD_source_base & BIT(27) || s->twoD_destination_base & BIT(27)) {\n qemu_log_mask(LOG_UNIMP, \"sm501: only local memory is supported.\\n\");\n return;\n }\n\n switch (cmd) {\n case 0x00: /* copy area */\n {\n int src_x = (s->twoD_source >> 16) & 0x01FFF;\n int src_y = s->twoD_source & 0xFFFF;\n uint32_t src_base = s->twoD_source_base & 0x03FFFFFF;\n uint8_t *src = s->local_mem + src_base;\n int src_pitch = s->twoD_pitch & 0x1FFF;\n\n#define COPY_AREA(_bpp, _pixel_type, rtl) { \\\n int y, x, index_d, index_s; \\\n for (y = 0; y < height; y++) { \\\n for (x = 0; x < width; x++) { \\\n _pixel_type val; \\\n \\\n if (rtl) { \\\n index_s = ((src_y - y) * src_pitch + src_x - x) * _bpp; \\\n index_d = ((dst_y - y) * dst_pitch + dst_x - x) * _bpp; \\\n } else { \\\n index_s = ((src_y + y) * src_pitch + src_x + x) * _bpp; \\\n index_d = ((dst_y + y) * dst_pitch + dst_x + x) * _bpp; \\\n } \\\n if (rop_mode == 1 && rop == 5) { \\\n /* Invert dest */ \\\n val = ~*(_pixel_type *)&dst[index_d]; \\\n } else { \\\n val = *(_pixel_type *)&src[index_s]; \\\n } \\\n *(_pixel_type *)&dst[index_d] = val; \\\n } \\\n } \\\n }\n switch (format) {\n case 0:\n COPY_AREA(1, uint8_t, rtl);\n break;\n case 1:\n COPY_AREA(2, uint16_t, rtl);\n break;\n case 2:\n COPY_AREA(4, uint32_t, rtl);\n break;\n }\n break;\n }\n case 0x01: /* fill rectangle */\n {\n uint32_t color = s->twoD_foreground;\n\n#define FILL_RECT(_bpp, _pixel_type) { \\\n int y, x; \\\n for (y = 0; y < height; y++) { \\\n for (x = 0; x < width; x++) { \\\n int index = ((dst_y + y) * dst_pitch + dst_x + x) * _bpp; \\\n *(_pixel_type *)&dst[index] = (_pixel_type)color; \\\n } \\\n } \\\n }\n\n switch (format) {\n case 0:\n FILL_RECT(1, uint8_t);\n break;\n case 1:\n color = cpu_to_le16(color);\n FILL_RECT(2, uint16_t);\n break;\n case 2:\n color = cpu_to_le32(color);\n FILL_RECT(4, uint32_t);\n break;\n }\n break;\n }\n default:\n qemu_log_mask(LOG_UNIMP, \"sm501: not implemented 2D operation: %d\\n\",\n cmd);\n return;\n }\n\n if (dst_base >= get_fb_addr(s, crt) &&\n dst_base <= get_fb_addr(s, crt) + fb_len) {\n int dst_len = MIN(fb_len, ((dst_y + height - 1) * dst_pitch +\n dst_x + width) * (1 << format));\n if (dst_len) {\n memory_region_set_dirty(&s->local_mem_region, dst_base, dst_len);\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'sm501: Replace hand written implementation with pixman where possible\n\nBesides being faster this should also prevent malicious guests to\nabuse 2D engine to overwrite data or cause a crash.\n\nSigned-off-by: BALATON Zoltan \nMessage-id: 58666389b6cae256e4e972a32c05cf8aa51bffc0.1590089984.git.balaton@eik.bme.hu\nSigned-off-by: Gerd Hoffmann '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int send_sub_rect(VncState *vs, int x, int y, int w, int h)\n{\n uint32_t bg = 0, fg = 0;\n int colors;\n int ret = 0;\n#ifdef CONFIG_VNC_JPEG\n bool force_jpeg = false;\n bool allow_jpeg = true;\n#endif\n\n if (!color_count_palette) {\n color_count_palette = g_malloc(sizeof(VncPalette));\n vnc_tight_cleanup_notifier.notify = vnc_tight_cleanup;\n qemu_thread_atexit_add(&vnc_tight_cleanup_notifier);\n }\n\n vnc_framebuffer_update(vs, x, y, w, h, vs->tight.type);\n\n vnc_tight_start(vs);\n vnc_raw_send_framebuffer_update(vs, x, y, w, h);\n vnc_tight_stop(vs);\n\n#ifdef CONFIG_VNC_JPEG\n if (!vs->vd->non_adaptive && vs->tight.quality != (uint8_t)-1) {\n double freq = vnc_update_freq(vs, x, y, w, h);\n\n if (freq < tight_jpeg_conf[vs->tight.quality].jpeg_freq_min) {\n allow_jpeg = false;\n }\n if (freq >= tight_jpeg_conf[vs->tight.quality].jpeg_freq_threshold) {\n force_jpeg = true;\n vnc_sent_lossy_rect(vs, x, y, w, h);\n }\n }\n#endif\n\n colors = tight_fill_palette(vs, x, y, w * h, &bg, &fg, color_count_palette);\n\n#ifdef CONFIG_VNC_JPEG\n if (allow_jpeg && vs->tight.quality != (uint8_t)-1) {\n ret = send_sub_rect_jpeg(vs, x, y, w, h, bg, fg, colors,\n color_count_palette, force_jpeg);\n } else {\n ret = send_sub_rect_nojpeg(vs, x, y, w, h, bg, fg, colors,\n color_count_palette);\n }\n#else\n ret = send_sub_rect_nojpeg(vs, x, y, w, h, bg, fg, colors,\n color_count_palette);\n#endif\n\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect\n\nCurrently when qemu receives a vnc connect, it creates a 'VncState' to\nrepresent this connection. In 'vnc_worker_thread_loop' it creates a\nlocal 'VncState'. The connection 'VcnState' and local 'VncState' exchange\ndata in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'.\nIn 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library\nopaque data. The 'VncState' used in 'zrle_compress_data' is the local\n'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz\nlibrary opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection\n'VncState'. In currently implementation there will be a memory leak when the\nvnc disconnect. Following is the asan output backtrack:\n\nDirect leak of 29760 byte(s) in 5 object(s) allocated from:\n 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3)\n 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb)\n 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7)\n 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87\n 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344\n 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919\n 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271\n 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340\n 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502\n 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb)\n 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb)\n\nThis is because the opaque allocated in 'deflateInit2' is not freed in\n'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck'\nand in the latter will check whether 's->strm != strm'(libz's data structure).\nThis check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and\nnot free the data allocated in 'deflateInit2'.\n\nThe reason this happens is that the 'VncState' contains the whole 'VncZrle',\nso when calling 'deflateInit2', the 's->strm' will be the local address.\nSo 's->strm != strm' will be true.\n\nTo fix this issue, we need to make 'zrle' of 'VncState' to be a pointer.\nThen the connection 'VncState' and local 'VncState' exchange mechanism will\nwork as expection. The 'tight' of 'VncState' has the same issue, let's also turn\nit to a pointer.\n\nReported-by: Ying Fang \nSigned-off-by: Li Qiang \nMessage-id: 20190831153922.121308-1-liq3ea@163.com\nSigned-off-by: Gerd Hoffmann '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static bool tight_can_send_png_rect(VncState *vs, int w, int h)\n{\n if (vs->tight.type != VNC_ENCODING_TIGHT_PNG) {\n return false;\n }\n\n if (surface_bytes_per_pixel(vs->vd->ds) == 1 ||\n vs->client_pf.bytes_per_pixel == 1) {\n return false;\n }\n\n return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect\n\nCurrently when qemu receives a vnc connect, it creates a 'VncState' to\nrepresent this connection. In 'vnc_worker_thread_loop' it creates a\nlocal 'VncState'. The connection 'VcnState' and local 'VncState' exchange\ndata in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'.\nIn 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library\nopaque data. The 'VncState' used in 'zrle_compress_data' is the local\n'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz\nlibrary opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection\n'VncState'. In currently implementation there will be a memory leak when the\nvnc disconnect. Following is the asan output backtrack:\n\nDirect leak of 29760 byte(s) in 5 object(s) allocated from:\n 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3)\n 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb)\n 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7)\n 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87\n 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344\n 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919\n 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271\n 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340\n 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502\n 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb)\n 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb)\n\nThis is because the opaque allocated in 'deflateInit2' is not freed in\n'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck'\nand in the latter will check whether 's->strm != strm'(libz's data structure).\nThis check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and\nnot free the data allocated in 'deflateInit2'.\n\nThe reason this happens is that the 'VncState' contains the whole 'VncZrle',\nso when calling 'deflateInit2', the 's->strm' will be the local address.\nSo 's->strm != strm' will be true.\n\nTo fix this issue, we need to make 'zrle' of 'VncState' to be a pointer.\nThen the connection 'VncState' and local 'VncState' exchange mechanism will\nwork as expection. The 'tight' of 'VncState' has the same issue, let's also turn\nit to a pointer.\n\nReported-by: Ying Fang \nSigned-off-by: Li Qiang \nMessage-id: 20190831153922.121308-1-liq3ea@163.com\nSigned-off-by: Gerd Hoffmann '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int send_palette_rect(VncState *vs, int x, int y,\n int w, int h, VncPalette *palette)\n{\n int stream = 2;\n int level = tight_conf[vs->tight.compression].idx_zlib_level;\n int colors;\n ssize_t bytes;\n\n#ifdef CONFIG_VNC_PNG\n if (tight_can_send_png_rect(vs, w, h)) {\n return send_png_rect(vs, x, y, w, h, palette);\n }\n#endif\n\n colors = palette_size(palette);\n\n vnc_write_u8(vs, (stream | VNC_TIGHT_EXPLICIT_FILTER) << 4);\n vnc_write_u8(vs, VNC_TIGHT_FILTER_PALETTE);\n vnc_write_u8(vs, colors - 1);\n\n switch (vs->client_pf.bytes_per_pixel) {\n case 4:\n {\n size_t old_offset, offset;\n uint32_t header[palette_size(palette)];\n struct palette_cb_priv priv = { vs, (uint8_t *)header };\n\n old_offset = vs->output.offset;\n palette_iter(palette, write_palette, &priv);\n vnc_write(vs, header, sizeof(header));\n\n if (vs->tight.pixel24) {\n tight_pack24(vs, vs->output.buffer + old_offset, colors, &offset);\n vs->output.offset = old_offset + offset;\n }\n\n tight_encode_indexed_rect32(vs->tight.tight.buffer, w * h, palette);\n break;\n }\n case 2:\n {\n uint16_t header[palette_size(palette)];\n struct palette_cb_priv priv = { vs, (uint8_t *)header };\n\n palette_iter(palette, write_palette, &priv);\n vnc_write(vs, header, sizeof(header));\n tight_encode_indexed_rect16(vs->tight.tight.buffer, w * h, palette);\n break;\n }\n default:\n return -1; /* No palette for 8bits colors */\n break;\n }\n bytes = w * h;\n vs->tight.tight.offset = bytes;\n\n bytes = tight_compress_data(vs, stream, bytes,\n level, Z_DEFAULT_STRATEGY);\n return (bytes >= 0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect\n\nCurrently when qemu receives a vnc connect, it creates a 'VncState' to\nrepresent this connection. In 'vnc_worker_thread_loop' it creates a\nlocal 'VncState'. The connection 'VcnState' and local 'VncState' exchange\ndata in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'.\nIn 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library\nopaque data. The 'VncState' used in 'zrle_compress_data' is the local\n'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz\nlibrary opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection\n'VncState'. In currently implementation there will be a memory leak when the\nvnc disconnect. Following is the asan output backtrack:\n\nDirect leak of 29760 byte(s) in 5 object(s) allocated from:\n 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3)\n 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb)\n 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7)\n 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87\n 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344\n 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919\n 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271\n 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340\n 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502\n 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb)\n 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb)\n\nThis is because the opaque allocated in 'deflateInit2' is not freed in\n'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck'\nand in the latter will check whether 's->strm != strm'(libz's data structure).\nThis check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and\nnot free the data allocated in 'deflateInit2'.\n\nThe reason this happens is that the 'VncState' contains the whole 'VncZrle',\nso when calling 'deflateInit2', the 's->strm' will be the local address.\nSo 's->strm != strm' will be true.\n\nTo fix this issue, we need to make 'zrle' of 'VncState' to be a pointer.\nThen the connection 'VncState' and local 'VncState' exchange mechanism will\nwork as expection. The 'tight' of 'VncState' has the same issue, let's also turn\nit to a pointer.\n\nReported-by: Ying Fang \nSigned-off-by: Li Qiang \nMessage-id: 20190831153922.121308-1-liq3ea@163.com\nSigned-off-by: Gerd Hoffmann '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int send_png_rect(VncState *vs, int x, int y, int w, int h,\n VncPalette *palette)\n{\n png_byte color_type;\n png_structp png_ptr;\n png_infop info_ptr;\n png_colorp png_palette = NULL;\n pixman_image_t *linebuf;\n int level = tight_png_conf[vs->tight.compression].png_zlib_level;\n int filters = tight_png_conf[vs->tight.compression].png_filters;\n uint8_t *buf;\n int dy;\n\n png_ptr = png_create_write_struct_2(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL,\n NULL, vnc_png_malloc, vnc_png_free);\n\n if (png_ptr == NULL)\n return -1;\n\n info_ptr = png_create_info_struct(png_ptr);\n\n if (info_ptr == NULL) {\n png_destroy_write_struct(&png_ptr, NULL);\n return -1;\n }\n\n png_set_write_fn(png_ptr, (void *) vs, png_write_data, png_flush_data);\n png_set_compression_level(png_ptr, level);\n png_set_filter(png_ptr, PNG_FILTER_TYPE_DEFAULT, filters);\n\n if (palette) {\n color_type = PNG_COLOR_TYPE_PALETTE;\n } else {\n color_type = PNG_COLOR_TYPE_RGB;\n }\n\n png_set_IHDR(png_ptr, info_ptr, w, h,\n 8, color_type, PNG_INTERLACE_NONE,\n PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);\n\n if (color_type == PNG_COLOR_TYPE_PALETTE) {\n struct palette_cb_priv priv;\n\n png_palette = png_malloc(png_ptr, sizeof(*png_palette) *\n palette_size(palette));\n\n priv.vs = vs;\n priv.png_palette = png_palette;\n palette_iter(palette, write_png_palette, &priv);\n\n png_set_PLTE(png_ptr, info_ptr, png_palette, palette_size(palette));\n\n if (vs->client_pf.bytes_per_pixel == 4) {\n tight_encode_indexed_rect32(vs->tight.tight.buffer, w * h, palette);\n } else {\n tight_encode_indexed_rect16(vs->tight.tight.buffer, w * h, palette);\n }\n }\n\n png_write_info(png_ptr, info_ptr);\n\n buffer_reserve(&vs->tight.png, 2048);\n linebuf = qemu_pixman_linebuf_create(PIXMAN_BE_r8g8b8, w);\n buf = (uint8_t *)pixman_image_get_data(linebuf);\n for (dy = 0; dy < h; dy++)\n {\n if (color_type == PNG_COLOR_TYPE_PALETTE) {\n memcpy(buf, vs->tight.tight.buffer + (dy * w), w);\n } else {\n qemu_pixman_linebuf_fill(linebuf, vs->vd->server, w, x, y + dy);\n }\n png_write_row(png_ptr, buf);\n }\n qemu_pixman_image_unref(linebuf);\n\n png_write_end(png_ptr, NULL);\n\n if (color_type == PNG_COLOR_TYPE_PALETTE) {\n png_free(png_ptr, png_palette);\n }\n\n png_destroy_write_struct(&png_ptr, &info_ptr);\n\n vnc_write_u8(vs, VNC_TIGHT_PNG << 4);\n\n tight_send_compact_size(vs, vs->tight.png.offset);\n vnc_write(vs, vs->tight.png.buffer, vs->tight.png.offset);\n buffer_reset(&vs->tight.png);\n return 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect\n\nCurrently when qemu receives a vnc connect, it creates a 'VncState' to\nrepresent this connection. In 'vnc_worker_thread_loop' it creates a\nlocal 'VncState'. The connection 'VcnState' and local 'VncState' exchange\ndata in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'.\nIn 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library\nopaque data. The 'VncState' used in 'zrle_compress_data' is the local\n'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz\nlibrary opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection\n'VncState'. In currently implementation there will be a memory leak when the\nvnc disconnect. Following is the asan output backtrack:\n\nDirect leak of 29760 byte(s) in 5 object(s) allocated from:\n 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3)\n 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb)\n 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7)\n 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87\n 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344\n 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919\n 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271\n 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340\n 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502\n 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb)\n 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb)\n\nThis is because the opaque allocated in 'deflateInit2' is not freed in\n'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck'\nand in the latter will check whether 's->strm != strm'(libz's data structure).\nThis check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and\nnot free the data allocated in 'deflateInit2'.\n\nThe reason this happens is that the 'VncState' contains the whole 'VncZrle',\nso when calling 'deflateInit2', the 's->strm' will be the local address.\nSo 's->strm != strm' will be true.\n\nTo fix this issue, we need to make 'zrle' of 'VncState' to be a pointer.\nThen the connection 'VncState' and local 'VncState' exchange mechanism will\nwork as expection. The 'tight' of 'VncState' has the same issue, let's also turn\nit to a pointer.\n\nReported-by: Ying Fang \nSigned-off-by: Li Qiang \nMessage-id: 20190831153922.121308-1-liq3ea@163.com\nSigned-off-by: Gerd Hoffmann '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void vnc_tight_clear(VncState *vs)\n{\n int i;\n for (i=0; itight.stream); i++) {\n if (vs->tight.stream[i].opaque) {\n deflateEnd(&vs->tight.stream[i]);\n }\n }\n\n buffer_free(&vs->tight.tight);\n buffer_free(&vs->tight.zlib);\n buffer_free(&vs->tight.gradient);\n#ifdef CONFIG_VNC_JPEG\n buffer_free(&vs->tight.jpeg);\n#endif\n#ifdef CONFIG_VNC_PNG\n buffer_free(&vs->tight.png);\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect\n\nCurrently when qemu receives a vnc connect, it creates a 'VncState' to\nrepresent this connection. In 'vnc_worker_thread_loop' it creates a\nlocal 'VncState'. The connection 'VcnState' and local 'VncState' exchange\ndata in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'.\nIn 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library\nopaque data. The 'VncState' used in 'zrle_compress_data' is the local\n'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz\nlibrary opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection\n'VncState'. In currently implementation there will be a memory leak when the\nvnc disconnect. Following is the asan output backtrack:\n\nDirect leak of 29760 byte(s) in 5 object(s) allocated from:\n 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3)\n 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb)\n 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7)\n 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87\n 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344\n 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919\n 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271\n 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340\n 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502\n 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb)\n 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb)\n\nThis is because the opaque allocated in 'deflateInit2' is not freed in\n'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck'\nand in the latter will check whether 's->strm != strm'(libz's data structure).\nThis check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and\nnot free the data allocated in 'deflateInit2'.\n\nThe reason this happens is that the 'VncState' contains the whole 'VncZrle',\nso when calling 'deflateInit2', the 's->strm' will be the local address.\nSo 's->strm != strm' will be true.\n\nTo fix this issue, we need to make 'zrle' of 'VncState' to be a pointer.\nThen the connection 'VncState' and local 'VncState' exchange mechanism will\nwork as expection. The 'tight' of 'VncState' has the same issue, let's also turn\nit to a pointer.\n\nReported-by: Ying Fang \nSigned-off-by: Li Qiang \nMessage-id: 20190831153922.121308-1-liq3ea@163.com\nSigned-off-by: Gerd Hoffmann '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: fstring_find_expr(const char **str, const char *end, int raw, int recurse_lvl,\n expr_ty *expression, struct compiling *c, const node *n)\n{\n /* Return -1 on error, else 0. */\n\n const char *expr_start;\n const char *expr_end;\n expr_ty simple_expression;\n expr_ty format_spec = NULL; /* Optional format specifier. */\n int conversion = -1; /* The conversion char. -1 if not specified. */\n\n /* 0 if we're not in a string, else the quote char we're trying to\n match (single or double quote). */\n char quote_char = 0;\n\n /* If we're inside a string, 1=normal, 3=triple-quoted. */\n int string_type = 0;\n\n /* Keep track of nesting level for braces/parens/brackets in\n expressions. */\n Py_ssize_t nested_depth = 0;\n char parenstack[MAXLEVEL];\n\n /* Can only nest one level deep. */\n if (recurse_lvl >= 2) {\n ast_error(c, n, \"f-string: expressions nested too deeply\");\n return -1;\n }\n\n /* The first char must be a left brace, or we wouldn't have gotten\n here. Skip over it. */\n assert(**str == '{');\n *str += 1;\n\n expr_start = *str;\n for (; *str < end; (*str)++) {\n char ch;\n\n /* Loop invariants. */\n assert(nested_depth >= 0);\n assert(*str >= expr_start && *str < end);\n if (quote_char)\n assert(string_type == 1 || string_type == 3);\n else\n assert(string_type == 0);\n\n ch = **str;\n /* Nowhere inside an expression is a backslash allowed. */\n if (ch == '\\\\') {\n /* Error: can't include a backslash character, inside\n parens or strings or not. */\n ast_error(c, n, \"f-string expression part \"\n \"cannot include a backslash\");\n return -1;\n }\n if (quote_char) {\n /* We're inside a string. See if we're at the end. */\n /* This code needs to implement the same non-error logic\n as tok_get from tokenizer.c, at the letter_quote\n label. To actually share that code would be a\n nightmare. But, it's unlikely to change and is small,\n so duplicate it here. Note we don't need to catch all\n of the errors, since they'll be caught when parsing the\n expression. We just need to match the non-error\n cases. Thus we can ignore \\n in single-quoted strings,\n for example. Or non-terminated strings. */\n if (ch == quote_char) {\n /* Does this match the string_type (single or triple\n quoted)? */\n if (string_type == 3) {\n if (*str+2 < end && *(*str+1) == ch && *(*str+2) == ch) {\n /* We're at the end of a triple quoted string. */\n *str += 2;\n string_type = 0;\n quote_char = 0;\n continue;\n }\n } else {\n /* We're at the end of a normal string. */\n quote_char = 0;\n string_type = 0;\n continue;\n }\n }\n } else if (ch == '\\'' || ch == '\"') {\n /* Is this a triple quoted string? */\n if (*str+2 < end && *(*str+1) == ch && *(*str+2) == ch) {\n string_type = 3;\n *str += 2;\n } else {\n /* Start of a normal string. */\n string_type = 1;\n }\n /* Start looking for the end of the string. */\n quote_char = ch;\n } else if (ch == '[' || ch == '{' || ch == '(') {\n if (nested_depth >= MAXLEVEL) {\n ast_error(c, n, \"f-string: too many nested parenthesis\");\n return -1;\n }\n parenstack[nested_depth] = ch;\n nested_depth++;\n } else if (ch == '#') {\n /* Error: can't include a comment character, inside parens\n or not. */\n ast_error(c, n, \"f-string expression part cannot include '#'\");\n return -1;\n } else if (nested_depth == 0 &&\n (ch == '!' || ch == ':' || ch == '}')) {\n /* First, test for the special case of \"!=\". Since '=' is\n not an allowed conversion character, nothing is lost in\n this test. */\n if (ch == '!' && *str+1 < end && *(*str+1) == '=') {\n /* This isn't a conversion character, just continue. */\n continue;\n }\n /* Normal way out of this loop. */\n break;\n } else if (ch == ']' || ch == '}' || ch == ')') {\n if (!nested_depth) {\n ast_error(c, n, \"f-string: unmatched '%c'\", ch);\n return -1;\n }\n nested_depth--;\n int opening = parenstack[nested_depth];\n if (!((opening == '(' && ch == ')') ||\n (opening == '[' && ch == ']') ||\n (opening == '{' && ch == '}')))\n {\n ast_error(c, n,\n \"f-string: closing parenthesis '%c' \"\n \"does not match opening parenthesis '%c'\",\n ch, opening);\n return -1;\n }\n } else {\n /* Just consume this char and loop around. */\n }\n }\n expr_end = *str;\n /* If we leave this loop in a string or with mismatched parens, we\n don't care. We'll get a syntax error when compiling the\n expression. But, we can produce a better error message, so\n let's just do that.*/\n if (quote_char) {\n ast_error(c, n, \"f-string: unterminated string\");\n return -1;\n }\n if (nested_depth) {\n int opening = parenstack[nested_depth - 1];\n ast_error(c, n, \"f-string: unmatched '%c'\", opening);\n return -1;\n }\n\n if (*str >= end)\n goto unexpected_end_of_string;\n\n /* Compile the expression as soon as possible, so we show errors\n related to the expression before errors related to the\n conversion or format_spec. */\n simple_expression = fstring_compile_expr(expr_start, expr_end, c, n);\n if (!simple_expression)\n return -1;\n\n /* Check for a conversion char, if present. */\n if (**str == '!') {\n *str += 1;\n if (*str >= end)\n goto unexpected_end_of_string;\n\n conversion = **str;\n *str += 1;\n\n /* Validate the conversion. */\n if (!(conversion == 's' || conversion == 'r'\n || conversion == 'a')) {\n ast_error(c, n, \"f-string: invalid conversion character: \"\n \"expected 's', 'r', or 'a'\");\n return -1;\n }\n }\n\n /* Check for the format spec, if present. */\n if (*str >= end)\n goto unexpected_end_of_string;\n if (**str == ':') {\n *str += 1;\n if (*str >= end)\n goto unexpected_end_of_string;\n\n /* Parse the format spec. */\n format_spec = fstring_parse(str, end, raw, recurse_lvl+1, c, n);\n if (!format_spec)\n return -1;\n }\n\n if (*str >= end || **str != '}')\n goto unexpected_end_of_string;\n\n /* We're at a right brace. Consume it. */\n assert(*str < end);\n assert(**str == '}');\n *str += 1;\n\n /* And now create the FormattedValue node that represents this\n entire expression with the conversion and format spec. */\n *expression = FormattedValue(simple_expression, conversion,\n format_spec, LINENO(n), n->n_col_offset,\n n->n_end_lineno, n->n_end_col_offset,\n c->c_arena);\n if (!*expression)\n return -1;\n\n return 0;\n\nunexpected_end_of_string:\n ast_error(c, n, \"f-string: expecting '}'\");\n return -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: tok_get(struct tok_state *tok, char **p_start, char **p_end)\n{\n int c;\n int blankline, nonascii;\n\n *p_start = *p_end = NULL;\n nextline:\n tok->start = NULL;\n blankline = 0;\n\n /* Get indentation level */\n if (tok->atbol) {\n int col = 0;\n int altcol = 0;\n tok->atbol = 0;\n for (;;) {\n c = tok_nextc(tok);\n if (c == ' ') {\n col++, altcol++;\n }\n else if (c == '\\t') {\n col = (col / tok->tabsize + 1) * tok->tabsize;\n altcol = (altcol / ALTTABSIZE + 1) * ALTTABSIZE;\n }\n else if (c == '\\014') {/* Control-L (formfeed) */\n col = altcol = 0; /* For Emacs users */\n }\n else {\n break;\n }\n }\n tok_backup(tok, c);\n if (c == '#' || c == '\\n') {\n /* Lines with only whitespace and/or comments\n shouldn't affect the indentation and are\n not passed to the parser as NEWLINE tokens,\n except *totally* empty lines in interactive\n mode, which signal the end of a command group. */\n if (col == 0 && c == '\\n' && tok->prompt != NULL) {\n blankline = 0; /* Let it through */\n }\n else {\n blankline = 1; /* Ignore completely */\n }\n /* We can't jump back right here since we still\n may need to skip to the end of a comment */\n }\n if (!blankline && tok->level == 0) {\n if (col == tok->indstack[tok->indent]) {\n /* No change */\n if (altcol != tok->altindstack[tok->indent]) {\n return indenterror(tok);\n }\n }\n else if (col > tok->indstack[tok->indent]) {\n /* Indent -- always one */\n if (tok->indent+1 >= MAXINDENT) {\n tok->done = E_TOODEEP;\n tok->cur = tok->inp;\n return ERRORTOKEN;\n }\n if (altcol <= tok->altindstack[tok->indent]) {\n return indenterror(tok);\n }\n tok->pendin++;\n tok->indstack[++tok->indent] = col;\n tok->altindstack[tok->indent] = altcol;\n }\n else /* col < tok->indstack[tok->indent] */ {\n /* Dedent -- any number, must be consistent */\n while (tok->indent > 0 &&\n col < tok->indstack[tok->indent]) {\n tok->pendin--;\n tok->indent--;\n }\n if (col != tok->indstack[tok->indent]) {\n tok->done = E_DEDENT;\n tok->cur = tok->inp;\n return ERRORTOKEN;\n }\n if (altcol != tok->altindstack[tok->indent]) {\n return indenterror(tok);\n }\n }\n }\n }\n\n tok->start = tok->cur;\n\n /* Return pending indents/dedents */\n if (tok->pendin != 0) {\n if (tok->pendin < 0) {\n tok->pendin++;\n return DEDENT;\n }\n else {\n tok->pendin--;\n return INDENT;\n }\n }\n\n again:\n tok->start = NULL;\n /* Skip spaces */\n do {\n c = tok_nextc(tok);\n } while (c == ' ' || c == '\\t' || c == '\\014');\n\n /* Set start of current token */\n tok->start = tok->cur - 1;\n\n /* Skip comment */\n if (c == '#') {\n while (c != EOF && c != '\\n') {\n c = tok_nextc(tok);\n }\n }\n\n /* Check for EOF and errors now */\n if (c == EOF) {\n return tok->done == E_EOF ? ENDMARKER : ERRORTOKEN;\n }\n\n /* Identifier (most frequent token!) */\n nonascii = 0;\n if (is_potential_identifier_start(c)) {\n /* Process the various legal combinations of b\"\", r\"\", u\"\", and f\"\". */\n int saw_b = 0, saw_r = 0, saw_u = 0, saw_f = 0;\n while (1) {\n if (!(saw_b || saw_u || saw_f) && (c == 'b' || c == 'B'))\n saw_b = 1;\n /* Since this is a backwards compatibility support literal we don't\n want to support it in arbitrary order like byte literals. */\n else if (!(saw_b || saw_u || saw_r || saw_f)\n && (c == 'u'|| c == 'U')) {\n saw_u = 1;\n }\n /* ur\"\" and ru\"\" are not supported */\n else if (!(saw_r || saw_u) && (c == 'r' || c == 'R')) {\n saw_r = 1;\n }\n else if (!(saw_f || saw_b || saw_u) && (c == 'f' || c == 'F')) {\n saw_f = 1;\n }\n else {\n break;\n }\n c = tok_nextc(tok);\n if (c == '\"' || c == '\\'') {\n goto letter_quote;\n }\n }\n while (is_potential_identifier_char(c)) {\n if (c >= 128) {\n nonascii = 1;\n }\n c = tok_nextc(tok);\n }\n tok_backup(tok, c);\n if (nonascii && !verify_identifier(tok)) {\n return ERRORTOKEN;\n }\n *p_start = tok->start;\n *p_end = tok->cur;\n\n return NAME;\n }\n\n /* Newline */\n if (c == '\\n') {\n tok->atbol = 1;\n if (blankline || tok->level > 0) {\n goto nextline;\n }\n *p_start = tok->start;\n *p_end = tok->cur - 1; /* Leave '\\n' out of the string */\n tok->cont_line = 0;\n return NEWLINE;\n }\n\n /* Period or number starting with period? */\n if (c == '.') {\n c = tok_nextc(tok);\n if (isdigit(c)) {\n goto fraction;\n } else if (c == '.') {\n c = tok_nextc(tok);\n if (c == '.') {\n *p_start = tok->start;\n *p_end = tok->cur;\n return ELLIPSIS;\n }\n else {\n tok_backup(tok, c);\n }\n tok_backup(tok, '.');\n }\n else {\n tok_backup(tok, c);\n }\n *p_start = tok->start;\n *p_end = tok->cur;\n return DOT;\n }\n\n /* Number */\n if (isdigit(c)) {\n if (c == '0') {\n /* Hex, octal or binary -- maybe. */\n c = tok_nextc(tok);\n if (c == 'x' || c == 'X') {\n /* Hex */\n c = tok_nextc(tok);\n do {\n if (c == '_') {\n c = tok_nextc(tok);\n }\n if (!isxdigit(c)) {\n tok_backup(tok, c);\n return syntaxerror(tok, \"invalid hexadecimal literal\");\n }\n do {\n c = tok_nextc(tok);\n } while (isxdigit(c));\n } while (c == '_');\n }\n else if (c == 'o' || c == 'O') {\n /* Octal */\n c = tok_nextc(tok);\n do {\n if (c == '_') {\n c = tok_nextc(tok);\n }\n if (c < '0' || c >= '8') {\n tok_backup(tok, c);\n if (isdigit(c)) {\n return syntaxerror(tok,\n \"invalid digit '%c' in octal literal\", c);\n }\n else {\n return syntaxerror(tok, \"invalid octal literal\");\n }\n }\n do {\n c = tok_nextc(tok);\n } while ('0' <= c && c < '8');\n } while (c == '_');\n if (isdigit(c)) {\n return syntaxerror(tok,\n \"invalid digit '%c' in octal literal\", c);\n }\n }\n else if (c == 'b' || c == 'B') {\n /* Binary */\n c = tok_nextc(tok);\n do {\n if (c == '_') {\n c = tok_nextc(tok);\n }\n if (c != '0' && c != '1') {\n tok_backup(tok, c);\n if (isdigit(c)) {\n return syntaxerror(tok,\n \"invalid digit '%c' in binary literal\", c);\n }\n else {\n return syntaxerror(tok, \"invalid binary literal\");\n }\n }\n do {\n c = tok_nextc(tok);\n } while (c == '0' || c == '1');\n } while (c == '_');\n if (isdigit(c)) {\n return syntaxerror(tok,\n \"invalid digit '%c' in binary literal\", c);\n }\n }\n else {\n int nonzero = 0;\n /* maybe old-style octal; c is first char of it */\n /* in any case, allow '0' as a literal */\n while (1) {\n if (c == '_') {\n c = tok_nextc(tok);\n if (!isdigit(c)) {\n tok_backup(tok, c);\n return syntaxerror(tok, \"invalid decimal literal\");\n }\n }\n if (c != '0') {\n break;\n }\n c = tok_nextc(tok);\n }\n if (isdigit(c)) {\n nonzero = 1;\n c = tok_decimal_tail(tok);\n if (c == 0) {\n return ERRORTOKEN;\n }\n }\n if (c == '.') {\n c = tok_nextc(tok);\n goto fraction;\n }\n else if (c == 'e' || c == 'E') {\n goto exponent;\n }\n else if (c == 'j' || c == 'J') {\n goto imaginary;\n }\n else if (nonzero) {\n /* Old-style octal: now disallowed. */\n tok_backup(tok, c);\n return syntaxerror(tok,\n \"leading zeros in decimal integer \"\n \"literals are not permitted; \"\n \"use an 0o prefix for octal integers\");\n }\n }\n }\n else {\n /* Decimal */\n c = tok_decimal_tail(tok);\n if (c == 0) {\n return ERRORTOKEN;\n }\n {\n /* Accept floating point numbers. */\n if (c == '.') {\n c = tok_nextc(tok);\n fraction:\n /* Fraction */\n if (isdigit(c)) {\n c = tok_decimal_tail(tok);\n if (c == 0) {\n return ERRORTOKEN;\n }\n }\n }\n if (c == 'e' || c == 'E') {\n int e;\n exponent:\n e = c;\n /* Exponent part */\n c = tok_nextc(tok);\n if (c == '+' || c == '-') {\n c = tok_nextc(tok);\n if (!isdigit(c)) {\n tok_backup(tok, c);\n return syntaxerror(tok, \"invalid decimal literal\");\n }\n } else if (!isdigit(c)) {\n tok_backup(tok, c);\n tok_backup(tok, e);\n *p_start = tok->start;\n *p_end = tok->cur;\n return NUMBER;\n }\n c = tok_decimal_tail(tok);\n if (c == 0) {\n return ERRORTOKEN;\n }\n }\n if (c == 'j' || c == 'J') {\n /* Imaginary part */\n imaginary:\n c = tok_nextc(tok);\n }\n }\n }\n tok_backup(tok, c);\n *p_start = tok->start;\n *p_end = tok->cur;\n return NUMBER;\n }\n\n letter_quote:\n /* String */\n if (c == '\\'' || c == '\"') {\n int quote = c;\n int quote_size = 1; /* 1 or 3 */\n int end_quote_size = 0;\n\n /* Nodes of type STRING, especially multi line strings\n must be handled differently in order to get both\n the starting line number and the column offset right.\n (cf. issue 16806) */\n tok->first_lineno = tok->lineno;\n tok->multi_line_start = tok->line_start;\n\n /* Find the quote size and start of string */\n c = tok_nextc(tok);\n if (c == quote) {\n c = tok_nextc(tok);\n if (c == quote) {\n quote_size = 3;\n }\n else {\n end_quote_size = 1; /* empty string found */\n }\n }\n if (c != quote) {\n tok_backup(tok, c);\n }\n\n /* Get rest of string */\n while (end_quote_size != quote_size) {\n c = tok_nextc(tok);\n if (c == EOF) {\n if (quote_size == 3) {\n tok->done = E_EOFS;\n }\n else {\n tok->done = E_EOLS;\n }\n tok->cur = tok->inp;\n return ERRORTOKEN;\n }\n if (quote_size == 1 && c == '\\n') {\n tok->done = E_EOLS;\n tok->cur = tok->inp;\n return ERRORTOKEN;\n }\n if (c == quote) {\n end_quote_size += 1;\n }\n else {\n end_quote_size = 0;\n if (c == '\\\\') {\n tok_nextc(tok); /* skip escaped char */\n }\n }\n }\n\n *p_start = tok->start;\n *p_end = tok->cur;\n return STRING;\n }\n\n /* Line continuation */\n if (c == '\\\\') {\n c = tok_nextc(tok);\n if (c != '\\n') {\n tok->done = E_LINECONT;\n tok->cur = tok->inp;\n return ERRORTOKEN;\n }\n tok->cont_line = 1;\n goto again; /* Read next line */\n }\n\n /* Check for two-character token */\n {\n int c2 = tok_nextc(tok);\n int token = PyToken_TwoChars(c, c2);\n if (token != OP) {\n int c3 = tok_nextc(tok);\n int token3 = PyToken_ThreeChars(c, c2, c3);\n if (token3 != OP) {\n token = token3;\n }\n else {\n tok_backup(tok, c3);\n }\n *p_start = tok->start;\n *p_end = tok->cur;\n return token;\n }\n tok_backup(tok, c2);\n }\n\n /* Keep track of parentheses nesting level */\n switch (c) {\n case '(':\n case '[':\n case '{':\n#ifndef PGEN\n if (tok->level >= MAXLEVEL) {\n return syntaxerror(tok, \"too many nested parentheses\");\n }\n tok->parenstack[tok->level] = c;\n tok->parenlinenostack[tok->level] = tok->lineno;\n#endif\n tok->level++;\n break;\n case ')':\n case ']':\n case '}':\n#ifndef PGEN\n if (!tok->level) {\n return syntaxerror(tok, \"unmatched '%c'\", c);\n }\n#endif\n tok->level--;\n#ifndef PGEN\n int opening = tok->parenstack[tok->level];\n if (!((opening == '(' && c == ')') ||\n (opening == '[' && c == ']') ||\n (opening == '{' && c == '}')))\n {\n if (tok->parenlinenostack[tok->level] != tok->lineno) {\n return syntaxerror(tok,\n \"closing parenthesis '%c' does not match \"\n \"opening parenthesis '%c' on line %d\",\n c, opening, tok->parenlinenostack[tok->level]);\n }\n else {\n return syntaxerror(tok,\n \"closing parenthesis '%c' does not match \"\n \"opening parenthesis '%c'\",\n c, opening);\n }\n }\n#endif\n break;\n }\n\n /* Punctuation character */\n *p_start = tok->start;\n *p_end = tok->cur;\n return PyToken_OneChar(c);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: With(asdl_seq * items, asdl_seq * body, int lineno, int col_offset, int\n end_lineno, int end_col_offset, PyArena *arena)\n{\n stmt_ty p;\n p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));\n if (!p)\n return NULL;\n p->kind = With_kind;\n p->v.With.items = items;\n p->v.With.body = body;\n p->lineno = lineno;\n p->col_offset = col_offset;\n p->end_lineno = end_lineno;\n p->end_col_offset = end_col_offset;\n return p;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: For(expr_ty target, expr_ty iter, asdl_seq * body, asdl_seq * orelse, int\n lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena)\n{\n stmt_ty p;\n if (!target) {\n PyErr_SetString(PyExc_ValueError,\n \"field target is required for For\");\n return NULL;\n }\n if (!iter) {\n PyErr_SetString(PyExc_ValueError,\n \"field iter is required for For\");\n return NULL;\n }\n p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));\n if (!p)\n return NULL;\n p->kind = For_kind;\n p->v.For.target = target;\n p->v.For.iter = iter;\n p->v.For.body = body;\n p->v.For.orelse = orelse;\n p->lineno = lineno;\n p->col_offset = col_offset;\n p->end_lineno = end_lineno;\n p->end_col_offset = end_col_offset;\n return p;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: CtPtr ProtocolV2::write(const std::string &desc,\n CONTINUATION_TYPE &next,\n F &frame) {\n ceph::bufferlist bl = frame.get_buffer(session_stream_handlers);\n return write(desc, next, bl);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-323'], 'message': 'msg/async/ProtocolV2: avoid AES-GCM nonce reuse vulnerabilities\n\nThe secure mode uses AES-128-GCM with 96-bit nonces consisting of a\n32-bit counter followed by a 64-bit salt. The counter is incremented\nafter processing each frame, the salt is fixed for the duration of\nthe session. Both are initialized from the session key generated\nduring session negotiation, so the counter starts with essentially\na random value. It is allowed to wrap, and, after 2**32 frames, it\nrepeats, resulting in nonce reuse (the actual sequence numbers that\nthe messenger works with are 64-bit, so the session continues on).\n\nBecause of how GCM works, this completely breaks both confidentiality\nand integrity aspects of the secure mode. A single nonce reuse reveals\nthe XOR of two plaintexts and almost completely reveals the subkey\nused for producing authentication tags. After a few nonces get used\ntwice, all confidentiality and integrity goes out the window and the\nattacker can potentially encrypt-authenticate plaintext of their\nchoice.\n\nWe can't easily change the nonce format to extend the counter to\n64 bits (and possibly XOR it with a longer salt). Instead, just\nremember the initial nonce and cut the session before it repeats,\nforcing renegotiation.\n\nSigned-off-by: Ilya Dryomov \nReviewed-by: Radoslaw Zarzynski \nReviewed-by: Sage Weil \n\nConflicts:\n\tsrc/msg/async/ProtocolV2.h [ context: commit ed3ec4c01d17\n\t (\"msg: Build target 'common' without using namespace in\n\t headers\") not in octopus ]'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void ProtocolV2::write_event() {\n ldout(cct, 10) << __func__ << dendl;\n ssize_t r = 0;\n\n connection->write_lock.lock();\n if (can_write) {\n if (keepalive) {\n append_keepalive();\n keepalive = false;\n }\n\n auto start = ceph::mono_clock::now();\n bool more;\n do {\n const auto out_entry = _get_next_outgoing();\n if (!out_entry.m) {\n break;\n }\n\n if (!connection->policy.lossy) {\n // put on sent list\n sent.push_back(out_entry.m);\n out_entry.m->get();\n }\n more = !out_queue.empty();\n connection->write_lock.unlock();\n\n // send_message or requeue messages may not encode message\n if (!out_entry.is_prepared) {\n prepare_send_message(connection->get_features(), out_entry.m);\n }\n\n r = write_message(out_entry.m, more);\n\n connection->write_lock.lock();\n if (r == 0) {\n ;\n } else if (r < 0) {\n ldout(cct, 1) << __func__ << \" send msg failed\" << dendl;\n break;\n } else if (r > 0)\n break;\n } while (can_write);\n write_in_progress = false;\n\n // if r > 0 mean data still lefted, so no need _try_send.\n if (r == 0) {\n uint64_t left = ack_left;\n if (left) {\n ceph_le64 s;\n s = in_seq;\n auto ack = AckFrame::Encode(in_seq);\n connection->outgoing_bl.append(ack.get_buffer(session_stream_handlers));\n ldout(cct, 10) << __func__ << \" try send msg ack, acked \" << left\n << \" messages\" << dendl;\n ack_left -= left;\n left = ack_left;\n r = connection->_try_send(left);\n } else if (is_queued()) {\n r = connection->_try_send();\n }\n }\n connection->write_lock.unlock();\n\n connection->logger->tinc(l_msgr_running_send_time,\n ceph::mono_clock::now() - start);\n if (r < 0) {\n ldout(cct, 1) << __func__ << \" send msg failed\" << dendl;\n connection->lock.lock();\n fault();\n connection->lock.unlock();\n return;\n }\n } else {\n write_in_progress = false;\n connection->write_lock.unlock();\n connection->lock.lock();\n connection->write_lock.lock();\n if (state == STANDBY && !connection->policy.server && is_queued()) {\n ldout(cct, 10) << __func__ << \" policy.server is false\" << dendl;\n if (server_cookie) { // only increment connect_seq if there is a session\n connect_seq++;\n }\n connection->_connect();\n } else if (connection->cs && state != NONE && state != CLOSED &&\n state != START_CONNECT) {\n r = connection->_try_send();\n if (r < 0) {\n ldout(cct, 1) << __func__ << \" send outcoming bl failed\" << dendl;\n connection->write_lock.unlock();\n fault();\n connection->lock.unlock();\n return;\n }\n }\n connection->write_lock.unlock();\n connection->lock.unlock();\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-323'], 'message': 'msg/async/ProtocolV2: avoid AES-GCM nonce reuse vulnerabilities\n\nThe secure mode uses AES-128-GCM with 96-bit nonces consisting of a\n32-bit counter followed by a 64-bit salt. The counter is incremented\nafter processing each frame, the salt is fixed for the duration of\nthe session. Both are initialized from the session key generated\nduring session negotiation, so the counter starts with essentially\na random value. It is allowed to wrap, and, after 2**32 frames, it\nrepeats, resulting in nonce reuse (the actual sequence numbers that\nthe messenger works with are 64-bit, so the session continues on).\n\nBecause of how GCM works, this completely breaks both confidentiality\nand integrity aspects of the secure mode. A single nonce reuse reveals\nthe XOR of two plaintexts and almost completely reveals the subkey\nused for producing authentication tags. After a few nonces get used\ntwice, all confidentiality and integrity goes out the window and the\nattacker can potentially encrypt-authenticate plaintext of their\nchoice.\n\nWe can't easily change the nonce format to extend the counter to\n64 bits (and possibly XOR it with a longer salt). Instead, just\nremember the initial nonce and cut the session before it repeats,\nforcing renegotiation.\n\nSigned-off-by: Ilya Dryomov \nReviewed-by: Radoslaw Zarzynski \nReviewed-by: Sage Weil \n\nConflicts:\n\tsrc/msg/async/ProtocolV2.cc [ context: commit 697aafa2aad2\n\t (\"msg/async/ProtocolV2: remove unused parameter\") not in\n\t nautilus ]\n\tsrc/msg/async/ProtocolV2.h [ context: commit ed3ec4c01d17\n\t (\"msg: Build target 'common' without using namespace in\n\t headers\") not in nautilus ]'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int RGWGetObj_ObjStore_S3::send_response_data(bufferlist& bl, off_t bl_ofs,\n\t\t\t\t\t off_t bl_len)\n{\n const char *content_type = NULL;\n string content_type_str;\n map response_attrs;\n map::iterator riter;\n bufferlist metadata_bl;\n\n if (sent_header)\n goto send_data;\n\n if (custom_http_ret) {\n set_req_state_err(s, 0);\n dump_errno(s, custom_http_ret);\n } else {\n set_req_state_err(s, (partial_content && !op_ret) ? STATUS_PARTIAL_CONTENT\n : op_ret);\n dump_errno(s);\n }\n\n if (op_ret)\n goto done;\n\n if (range_str)\n dump_range(s, start, end, s->obj_size);\n\n if (s->system_request &&\n s->info.args.exists(RGW_SYS_PARAM_PREFIX \"prepend-metadata\")) {\n\n dump_header(s, \"Rgwx-Object-Size\", (long long)total_len);\n\n if (rgwx_stat) {\n /*\n * in this case, we're not returning the object's content, only the prepended\n * extra metadata\n */\n total_len = 0;\n }\n\n /* JSON encode object metadata */\n JSONFormatter jf;\n jf.open_object_section(\"obj_metadata\");\n encode_json(\"attrs\", attrs, &jf);\n utime_t ut(lastmod);\n encode_json(\"mtime\", ut, &jf);\n jf.close_section();\n stringstream ss;\n jf.flush(ss);\n metadata_bl.append(ss.str());\n dump_header(s, \"Rgwx-Embedded-Metadata-Len\", metadata_bl.length());\n total_len += metadata_bl.length();\n }\n\n if (s->system_request && !real_clock::is_zero(lastmod)) {\n /* we end up dumping mtime in two different methods, a bit redundant */\n dump_epoch_header(s, \"Rgwx-Mtime\", lastmod);\n uint64_t pg_ver = 0;\n int r = decode_attr_bl_single_value(attrs, RGW_ATTR_PG_VER, &pg_ver, (uint64_t)0);\n if (r < 0) {\n ldout(s->cct, 0) << \"ERROR: failed to decode pg ver attr, ignoring\" << dendl;\n }\n dump_header(s, \"Rgwx-Obj-PG-Ver\", pg_ver);\n\n uint32_t source_zone_short_id = 0;\n r = decode_attr_bl_single_value(attrs, RGW_ATTR_SOURCE_ZONE, &source_zone_short_id, (uint32_t)0);\n if (r < 0) {\n ldout(s->cct, 0) << \"ERROR: failed to decode pg ver attr, ignoring\" << dendl;\n }\n if (source_zone_short_id != 0) {\n dump_header(s, \"Rgwx-Source-Zone-Short-Id\", source_zone_short_id);\n }\n }\n\n for (auto &it : crypt_http_responses)\n dump_header(s, it.first, it.second);\n\n dump_content_length(s, total_len);\n dump_last_modified(s, lastmod);\n dump_header_if_nonempty(s, \"x-amz-version-id\", version_id);\n if (attrs.find(RGW_ATTR_APPEND_PART_NUM) != attrs.end()) {\n dump_header(s, \"x-rgw-object-type\", \"Appendable\");\n dump_header(s, \"x-rgw-next-append-position\", s->obj_size);\n } else {\n dump_header(s, \"x-rgw-object-type\", \"Normal\");\n }\n\n if (! op_ret) {\n if (! lo_etag.empty()) {\n /* Handle etag of Swift API's large objects (DLO/SLO). It's entirerly\n * legit to perform GET on them through S3 API. In such situation,\n * a client should receive the composited content with corresponding\n * etag value. */\n dump_etag(s, lo_etag);\n } else {\n auto iter = attrs.find(RGW_ATTR_ETAG);\n if (iter != attrs.end()) {\n dump_etag(s, iter->second.to_str());\n }\n }\n\n for (struct response_attr_param *p = resp_attr_params; p->param; p++) {\n bool exists;\n string val = s->info.args.get(p->param, &exists);\n if (exists) {\n\t/* reject unauthenticated response header manipulation, see\n\t * https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html */\n\tif (s->auth.identity->is_anonymous()) {\n\t return -ERR_INVALID_REQUEST;\n\t}\n\tif (strcmp(p->param, \"response-content-type\") != 0) {\n\t response_attrs[p->http_attr] = val;\n\t} else {\n\t content_type_str = val;\n\t content_type = content_type_str.c_str();\n\t}\n }\n }\n\n for (auto iter = attrs.begin(); iter != attrs.end(); ++iter) {\n const char *name = iter->first.c_str();\n map::iterator aiter = rgw_to_http_attrs.find(name);\n if (aiter != rgw_to_http_attrs.end()) {\n if (response_attrs.count(aiter->second) == 0) {\n /* Was not already overridden by a response param. */\n\n size_t len = iter->second.length();\n string s(iter->second.c_str(), len);\n while (len && !s[len - 1]) {\n --len;\n s.resize(len);\n }\n response_attrs[aiter->second] = s;\n }\n } else if (iter->first.compare(RGW_ATTR_CONTENT_TYPE) == 0) {\n /* Special handling for content_type. */\n if (!content_type) {\n content_type_str = rgw_bl_str(iter->second);\n content_type = content_type_str.c_str();\n }\n } else if (strcmp(name, RGW_ATTR_SLO_UINDICATOR) == 0) {\n // this attr has an extra length prefix from encode() in prior versions\n dump_header(s, \"X-Object-Meta-Static-Large-Object\", \"True\");\n } else if (strncmp(name, RGW_ATTR_META_PREFIX,\n\t\t\t sizeof(RGW_ATTR_META_PREFIX)-1) == 0) {\n /* User custom metadata. */\n name += sizeof(RGW_ATTR_PREFIX) - 1;\n dump_header(s, name, iter->second);\n } else if (iter->first.compare(RGW_ATTR_TAGS) == 0) {\n RGWObjTags obj_tags;\n try{\n auto it = iter->second.cbegin();\n obj_tags.decode(it);\n } catch (buffer::error &err) {\n ldout(s->cct,0) << \"Error caught buffer::error couldn't decode TagSet \" << dendl;\n }\n dump_header(s, RGW_AMZ_TAG_COUNT, obj_tags.count());\n } else if (iter->first.compare(RGW_ATTR_OBJECT_RETENTION) == 0 && get_retention){\n RGWObjectRetention retention;\n try {\n decode(retention, iter->second);\n dump_header(s, \"x-amz-object-lock-mode\", retention.get_mode());\n dump_time_header(s, \"x-amz-object-lock-retain-until-date\", retention.get_retain_until_date());\n } catch (buffer::error& err) {\n ldpp_dout(this, 0) << \"ERROR: failed to decode RGWObjectRetention\" << dendl;\n }\n } else if (iter->first.compare(RGW_ATTR_OBJECT_LEGAL_HOLD) == 0 && get_legal_hold) {\n RGWObjectLegalHold legal_hold;\n try {\n decode(legal_hold, iter->second);\n dump_header(s, \"x-amz-object-lock-legal-hold\",legal_hold.get_status());\n } catch (buffer::error& err) {\n ldpp_dout(this, 0) << \"ERROR: failed to decode RGWObjectLegalHold\" << dendl;\n }\n }\n }\n }\n\ndone:\n for (riter = response_attrs.begin(); riter != response_attrs.end();\n ++riter) {\n dump_header(s, riter->first, riter->second);\n }\n\n if (op_ret == -ERR_NOT_MODIFIED) {\n end_header(s, this);\n } else {\n if (!content_type)\n content_type = \"binary/octet-stream\";\n\n end_header(s, this, content_type);\n }\n\n if (metadata_bl.length()) {\n dump_body(s, metadata_bl);\n }\n sent_header = true;\n\nsend_data:\n if (get_data && !op_ret) {\n int r = dump_body(s, bl.c_str() + bl_ofs, bl_len);\n if (r < 0)\n return r;\n }\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-79'], 'message': 'rgw: reject control characters in response-header actions\n\nS3 GetObject permits overriding response header values, but those inputs\nneed to be validated to insure only characters that are valid in an HTTP\nheader value are present.\n\nCredit: Initial vulnerability discovery by William Bowling (@wcbowling)\nCredit: Further vulnerability discovery by Robin H. Johnson \nSigned-off-by: Robin H. Johnson '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: unsigned long ksys_mmap_pgoff(unsigned long addr, unsigned long len,\n\t\t\t unsigned long prot, unsigned long flags,\n\t\t\t unsigned long fd, unsigned long pgoff)\n{\n\tstruct file *file = NULL;\n\tunsigned long retval;\n\n\taddr = untagged_addr(addr);\n\n\tif (!(flags & MAP_ANONYMOUS)) {\n\t\taudit_mmap_fd(fd, flags);\n\t\tfile = fget(fd);\n\t\tif (!file)\n\t\t\treturn -EBADF;\n\t\tif (is_file_hugepages(file))\n\t\t\tlen = ALIGN(len, huge_page_size(hstate_file(file)));\n\t\tretval = -EINVAL;\n\t\tif (unlikely(flags & MAP_HUGETLB && !is_file_hugepages(file)))\n\t\t\tgoto out_fput;\n\t} else if (flags & MAP_HUGETLB) {\n\t\tstruct user_struct *user = NULL;\n\t\tstruct hstate *hs;\n\n\t\ths = hstate_sizelog((flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);\n\t\tif (!hs)\n\t\t\treturn -EINVAL;\n\n\t\tlen = ALIGN(len, huge_page_size(hs));\n\t\t/*\n\t\t * VM_NORESERVE is used because the reservations will be\n\t\t * taken when vm_ops->mmap() is called\n\t\t * A dummy user value is used because we are not locking\n\t\t * memory so no accounting is necessary\n\t\t */\n\t\tfile = hugetlb_file_setup(HUGETLB_ANON_FILE, len,\n\t\t\t\tVM_NORESERVE,\n\t\t\t\t&user, HUGETLB_ANONHUGE_INODE,\n\t\t\t\t(flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);\n\t\tif (IS_ERR(file))\n\t\t\treturn PTR_ERR(file);\n\t}\n\n\tflags &= ~(MAP_EXECUTABLE | MAP_DENYWRITE);\n\n\tretval = vm_mmap_pgoff(file, addr, len, prot, flags, pgoff);\nout_fput:\n\tif (file)\n\t\tfput(file);\n\treturn retval;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'mm: Avoid creating virtual address aliases in brk()/mmap()/mremap()\n\nCurrently the arm64 kernel ignores the top address byte passed to brk(),\nmmap() and mremap(). When the user is not aware of the 56-bit address\nlimit or relies on the kernel to return an error, untagging such\npointers has the potential to create address aliases in user-space.\nPassing a tagged address to munmap(), madvise() is permitted since the\ntagged pointer is expected to be inside an existing mapping.\n\nThe current behaviour breaks the existing glibc malloc() implementation\nwhich relies on brk() with an address beyond 56-bit to be rejected by\nthe kernel.\n\nRemove untagging in the above functions by partially reverting commit\nce18d171cb73 (\"mm: untag user pointers in mmap/munmap/mremap/brk\"). In\naddition, update the arm64 tagged-address-abi.rst document accordingly.\n\nLink: https://bugzilla.redhat.com/1797052\nFixes: ce18d171cb73 (\"mm: untag user pointers in mmap/munmap/mremap/brk\")\nCc: # 5.4.x-\nCc: Florian Weimer \nReviewed-by: Andrew Morton \nReported-by: Victor Stinner \nAcked-by: Will Deacon \nAcked-by: Andrey Konovalov \nSigned-off-by: Catalin Marinas \nSigned-off-by: Will Deacon '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int mod_detach (void *arg)\n{\n\teap_pwd_t *inst;\n\n\tinst = (eap_pwd_t *) arg;\n\n\tif (inst->bnctx) BN_CTX_free(inst->bnctx);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-662'], 'message': 'EAP-pwd: fix DoS due to multithreaded BN_CTX access\n\nThe EAP-pwd module created one global OpenSSL BN_CTX instance, and\nused this instance in all incoming requests. This means that different\nthreads used the same BN_CTX instance, which can result in a crash.\nAn adversary can trigger these crashes by concurrently initiating\nmultiple EAP-pwd handshakes from different clients.\n\nFix this bug by creating a separate BN_CTX instance for each request.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadSVGImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n Image\n *image,\n *svg_image;\n\n MagickBooleanType\n status;\n\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(exception != (ExceptionInfo *) NULL);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n if ((fabs(image->resolution.x) < MagickEpsilon) ||\n (fabs(image->resolution.y) < MagickEpsilon))\n {\n GeometryInfo\n geometry_info;\n\n MagickStatusType\n flags;\n\n flags=ParseGeometry(SVGDensityGeometry,&geometry_info);\n image->resolution.x=geometry_info.rho;\n image->resolution.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->resolution.y=image->resolution.x;\n }\n svg_image=RenderSVGImage(image_info,image,exception);\n image=DestroyImage(image);\n return(svg_image);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-674', 'CWE-787'], 'message': '[FG-VD-19-136] ImageMagick Convert SVG MacOS Denial Of Service'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static ssize_t tulip_receive(TULIPState *s, const uint8_t *buf, size_t size)\n{\n struct tulip_descriptor desc;\n\n trace_tulip_receive(buf, size);\n\n if (size < 14 || size > 2048 || s->rx_frame_len || tulip_rx_stopped(s)) {\n return 0;\n }\n\n if (!tulip_filter_address(s, buf)) {\n return size;\n }\n\n do {\n tulip_desc_read(s, s->current_rx_desc, &desc);\n tulip_dump_rx_descriptor(s, &desc);\n\n if (!(desc.status & RDES0_OWN)) {\n s->csr[5] |= CSR5_RU;\n tulip_update_int(s);\n return s->rx_frame_size - s->rx_frame_len;\n }\n desc.status = 0;\n\n if (!s->rx_frame_len) {\n s->rx_frame_size = size + 4;\n s->rx_status = RDES0_LS |\n ((s->rx_frame_size & RDES0_FL_MASK) << RDES0_FL_SHIFT);\n desc.status |= RDES0_FS;\n memcpy(s->rx_frame, buf, size);\n s->rx_frame_len = s->rx_frame_size;\n }\n\n tulip_copy_rx_bytes(s, &desc);\n\n if (!s->rx_frame_len) {\n desc.status |= s->rx_status;\n s->csr[5] |= CSR5_RI;\n tulip_update_int(s);\n }\n tulip_dump_rx_descriptor(s, &desc);\n tulip_desc_write(s, s->current_rx_desc, &desc);\n tulip_next_rx_descriptor(s, &desc);\n } while (s->rx_frame_len);\n return size;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'net: tulip: check frame size and r/w data length\n\nTulip network driver while copying tx/rx buffers does not check\nframe size against r/w data length. This may lead to OOB buffer\naccess. Add check to avoid it.\n\nLimit iterations over descriptors to avoid potential infinite\nloop issue in tulip_xmit_list_update.\n\nReported-by: Li Qiang \nReported-by: Ziming Zhang \nReported-by: Jason Wang \nTested-by: Li Qiang \nReviewed-by: Li Qiang \nSigned-off-by: Prasad J Pandit \nSigned-off-by: Jason Wang '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: extract_archive_thread (GSimpleAsyncResult *result,\n\t\t\tGObject *object,\n\t\t\tGCancellable *cancellable)\n{\n\tExtractData *extract_data;\n\tLoadData *load_data;\n\tGHashTable *checked_folders;\n\tGHashTable *created_files;\n\tGHashTable *folders_created_during_extraction;\n\tstruct archive *a;\n\tstruct archive_entry *entry;\n\tint r;\n\n\textract_data = g_simple_async_result_get_op_res_gpointer (result);\n\tload_data = LOAD_DATA (extract_data);\n\n\tr = create_read_object (load_data, &a);\n\tif (r != ARCHIVE_OK) {\n\t\tarchive_read_free(a);\n\t\treturn;\n\t}\n\n\tchecked_folders = g_hash_table_new_full (g_file_hash, (GEqualFunc) g_file_equal, g_object_unref, NULL);\n\tcreated_files = g_hash_table_new_full (g_file_hash, (GEqualFunc) g_file_equal, g_object_unref, g_object_unref);\n\tfolders_created_during_extraction = g_hash_table_new_full (g_file_hash, (GEqualFunc) g_file_equal, g_object_unref, NULL);\n\tfr_archive_progress_set_total_files (load_data->archive, extract_data->n_files_to_extract);\n\n\twhile ((r = archive_read_next_header (a, &entry)) == ARCHIVE_OK) {\n\t\tconst char *pathname;\n\t\tchar *fullpath;\n\t\tconst char *relative_path;\n\t\tGFile *file;\n\t\tGFile *parent;\n\t\tGOutputStream *ostream;\n\t\tconst void *buffer;\n\t\tsize_t buffer_size;\n\t\tint64_t target_offset, actual_offset;\n\t\tGError *local_error = NULL;\n\t\t__LA_MODE_T filetype;\n\n\t\tif (g_cancellable_is_cancelled (cancellable))\n\t\t\tbreak;\n\n\t\tpathname = archive_entry_pathname (entry);\n\t\tif (! extract_data_get_extraction_requested (extract_data, pathname)) {\n\t\t\tarchive_read_data_skip (a);\n\t\t\tcontinue;\n\t\t}\n\n\t\tfullpath = (*pathname == '/') ? g_strdup (pathname) : g_strconcat (\"/\", pathname, NULL);\n\t\trelative_path = _g_path_get_relative_basename_safe (fullpath, extract_data->base_dir, extract_data->junk_paths);\n\t\tif (relative_path == NULL) {\n\t\t\tarchive_read_data_skip (a);\n\t\t\tcontinue;\n\t\t}\n\n\t\tfile = g_file_get_child (extract_data->destination, relative_path);\n\n\t\t/* honor the skip_older and overwrite options */\n\n\t\tif ((g_hash_table_lookup (folders_created_during_extraction, file) == NULL)\n\t\t && (extract_data->skip_older || ! extract_data->overwrite))\n\t\t{\n\t\t\tGFileInfo *info;\n\n\t\t\tinfo = g_file_query_info (file,\n\t\t\t\t\t\t G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME \",\" G_FILE_ATTRIBUTE_TIME_MODIFIED,\n\t\t\t\t\t\t G_FILE_QUERY_INFO_NONE,\n\t\t\t\t\t\t cancellable,\n\t\t\t\t\t\t &local_error);\n\t\t\tif (info != NULL) {\n\t\t\t\tgboolean skip = FALSE;\n\n\t\t\t\tif (! extract_data->overwrite) {\n\t\t\t\t\tskip = TRUE;\n\t\t\t\t}\n\t\t\t\telse if (extract_data->skip_older) {\n\t\t\t\t\tGTimeVal modification_time;\n\n\t\t\t\t\tg_file_info_get_modification_time (info, &modification_time);\n\t\t\t\t\tif (archive_entry_mtime (entry) < modification_time.tv_sec)\n\t\t\t\t\t\tskip = TRUE;\n\t\t\t\t}\n\n\t\t\t\tg_object_unref (info);\n\n\t\t\t\tif (skip) {\n\t\t\t\t\tg_object_unref (file);\n\n\t\t\t\t\tarchive_read_data_skip (a);\n\t\t\t\t\tfr_archive_progress_inc_completed_bytes (load_data->archive, archive_entry_size_is_set (entry) ? archive_entry_size (entry) : 0);\n\n\t\t\t\t\tif ((extract_data->file_list != NULL) && (--extract_data->n_files_to_extract == 0)) {\n\t\t\t\t\t\tr = ARCHIVE_EOF;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (! g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND)) {\n\t\t\t\t\tload_data->error = local_error;\n\t\t\t\t\tg_object_unref (info);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tg_clear_error (&local_error);\n\t\t\t}\n\t\t}\n\n\t\tfr_archive_progress_inc_completed_files (load_data->archive, 1);\n\n\t\t/* create the file parents */\n\n\t\tparent = g_file_get_parent (file);\n\n\t\tif ((parent != NULL)\n\t\t && (g_hash_table_lookup (checked_folders, parent) == NULL)\n\t\t && ! g_file_query_exists (parent, cancellable))\n\t\t{\n\t\t\tif (! _g_file_make_directory_with_parents (parent,\n\t\t\t\t\t\t\t\t folders_created_during_extraction,\n\t\t\t\t\t\t\t\t cancellable,\n\t\t\t\t\t\t\t\t &local_error))\n\t\t\t{\n\t\t\t\tif (! g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_EXISTS))\n\t\t\t\t\tload_data->error = local_error;\n\t\t\t\telse\n\t\t\t\t\tg_clear_error (&local_error);\n\t\t\t}\n\n\t\t\tif (load_data->error == NULL) {\n\t\t\t\tGFile *grandparent;\n\n\t\t\t\tgrandparent = g_object_ref (parent);\n\t\t\t\twhile (grandparent != NULL) {\n\t\t\t\t\tif (g_hash_table_lookup (checked_folders, grandparent) == NULL)\n\t\t\t\t\t\tg_hash_table_insert (checked_folders, grandparent, GINT_TO_POINTER (1));\n\t\t\t\t\tgrandparent = g_file_get_parent (grandparent);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tg_object_unref (parent);\n\n\t\t/* create the file */\n\n\t\tfiletype = archive_entry_filetype (entry);\n\n\t\tif (load_data->error == NULL) {\n\t\t\tconst char *linkname;\n\n\t\t\tlinkname = archive_entry_hardlink (entry);\n\t\t\tif (linkname != NULL) {\n\t\t\t\tchar *link_fullpath;\n\t\t\t\tconst char *relative_path;\n\t\t\t\tGFile *link_file;\n\t\t\t\tchar *oldname;\n\t\t\t\tchar *newname;\n\t\t\t\tint r;\n\n\t\t\t\tlink_fullpath = (*linkname == '/') ? g_strdup (linkname) : g_strconcat (\"/\", linkname, NULL);\n\t\t\t\trelative_path = _g_path_get_relative_basename_safe (link_fullpath, extract_data->base_dir, extract_data->junk_paths);\n\t\t\t\tif (relative_path == NULL) {\n\t\t\t\t\tg_free (link_fullpath);\n\t\t\t\t\tarchive_read_data_skip (a);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tlink_file = g_file_get_child (extract_data->destination, relative_path);\n\t\t\t\toldname = g_file_get_path (link_file);\n\t\t\t\tnewname = g_file_get_path (file);\n\n\t\t\t\tif ((oldname != NULL) && (newname != NULL))\n\t\t\t\t\tr = link (oldname, newname);\n\t\t\t\telse\n\t\t\t\t\tr = -1;\n\n\t\t\t\tif (r == 0) {\n\t\t\t\t\t__LA_INT64_T filesize;\n\n\t\t\t\t\tif (archive_entry_size_is_set (entry))\n\t\t\t\t\t\tfilesize = archive_entry_size (entry);\n\t\t\t\t\telse\n\t\t\t\t\t\tfilesize = -1;\n\n\t\t\t\t\tif (filesize > 0)\n\t\t\t\t\t\tfiletype = AE_IFREG; /* treat as a regular file to save the data */\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tchar *uri;\n\t\t\t\t\tchar *msg;\n\n\t\t\t\t\turi = g_file_get_uri (file);\n\t\t\t\t\tmsg = g_strdup_printf (\"Could not create the hard link %s\", uri);\n\t\t\t\t\tload_data->error = g_error_new_literal (G_IO_ERROR, G_IO_ERROR_FAILED, msg);\n\n\t\t\t\t\tg_free (msg);\n\t\t\t\t\tg_free (uri);\n\t\t\t\t}\n\n\t\t\t\tg_free (newname);\n\t\t\t\tg_free (oldname);\n\t\t\t\tg_object_unref (link_file);\n\t\t\t\tg_free (link_fullpath);\n\t\t\t}\n\t\t}\n\n\t\tif (load_data->error == NULL) {\n\t\t\tswitch (filetype) {\n\t\t\tcase AE_IFDIR:\n\t\t\t\tif (! g_file_make_directory (file, cancellable, &local_error)) {\n\t\t\t\t\tif (! g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_EXISTS))\n\t\t\t\t\t\tload_data->error = g_error_copy (local_error);\n\t\t\t\t\tg_clear_error (&local_error);\n\t\t\t\t}\n\t\t\t\tif (load_data->error == NULL)\n\t\t\t\t\tg_hash_table_insert (created_files, g_object_ref (file), _g_file_info_create_from_entry (entry, extract_data));\n\t\t\t\tarchive_read_data_skip (a);\n\t\t\t\tbreak;\n\n\t\t\tcase AE_IFREG:\n\t\t\t\tostream = (GOutputStream *) g_file_replace (file, NULL, FALSE, G_FILE_CREATE_REPLACE_DESTINATION, cancellable, &load_data->error);\n\t\t\t\tif (ostream == NULL)\n\t\t\t\t\tbreak;\n\n\t\t\t\tactual_offset = 0;\n\t\t\t\twhile ((r = archive_read_data_block (a, &buffer, &buffer_size, &target_offset)) == ARCHIVE_OK) {\n\t\t\t\t\tgsize bytes_written;\n\n\t\t\t\t\tif (target_offset > actual_offset) {\n\t\t\t\t\t\tif (! _g_output_stream_add_padding (extract_data, ostream, target_offset, actual_offset, cancellable, &load_data->error))\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tfr_archive_progress_inc_completed_bytes (load_data->archive, target_offset - actual_offset);\n\t\t\t\t\t\tactual_offset = target_offset;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (! g_output_stream_write_all (ostream, buffer, buffer_size, &bytes_written, cancellable, &load_data->error))\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tactual_offset += bytes_written;\n\t\t\t\t\tfr_archive_progress_inc_completed_bytes (load_data->archive, bytes_written);\n\t\t\t\t}\n\n\t\t\t\tif ((r == ARCHIVE_EOF) && (target_offset > actual_offset))\n\t\t\t\t\t_g_output_stream_add_padding (extract_data, ostream, target_offset, actual_offset, cancellable, &load_data->error);\n\n\t\t\t\t_g_object_unref (ostream);\n\n\t\t\t\tif (r != ARCHIVE_EOF)\n\t\t\t\t\tload_data->error = _g_error_new_from_archive_error (archive_error_string (a));\n\t\t\t\telse\n\t\t\t\t\tg_hash_table_insert (created_files, g_object_ref (file), _g_file_info_create_from_entry (entry, extract_data));\n\t\t\t\tbreak;\n\n\t\t\tcase AE_IFLNK:\n\t\t\t\tif (! g_file_make_symbolic_link (file, archive_entry_symlink (entry), cancellable, &local_error)) {\n\t\t\t\t\tif (! g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_EXISTS))\n\t\t\t\t\t\tload_data->error = g_error_copy (local_error);\n\t\t\t\t\tg_clear_error (&local_error);\n\t\t\t\t}\n\t\t\t\tarchive_read_data_skip (a);\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tarchive_read_data_skip (a);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tg_object_unref (file);\n\t\tg_free (fullpath);\n\n\t\tif (load_data->error != NULL)\n\t\t\tbreak;\n\n\t\tif ((extract_data->file_list != NULL) && (--extract_data->n_files_to_extract == 0)) {\n\t\t\tr = ARCHIVE_EOF;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (load_data->error == NULL)\n\t\trestore_original_file_attributes (created_files, cancellable);\n\n\tif ((load_data->error == NULL) && (r != ARCHIVE_EOF))\n\t\tload_data->error = _g_error_new_from_archive_error (archive_error_string (a));\n\tif (load_data->error == NULL)\n\t\tg_cancellable_set_error_if_cancelled (cancellable, &load_data->error);\n\tif (load_data->error != NULL)\n\t\tg_simple_async_result_set_from_error (result, load_data->error);\n\n\tg_hash_table_unref (folders_created_during_extraction);\n\tg_hash_table_unref (created_files);\n\tg_hash_table_unref (checked_folders);\n\tarchive_read_free (a);\n\textract_data_free (extract_data);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-22'], 'message': 'libarchive: do not follow external links when extracting files\n\nDo not extract a file if its parent is a symbolic link to a\ndirectory external to the destination.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: vhost_reserve_avail_batch_packed(struct virtio_net *dev,\n\t\t\t\t struct vhost_virtqueue *vq,\n\t\t\t\t struct rte_mempool *mbuf_pool,\n\t\t\t\t struct rte_mbuf **pkts,\n\t\t\t\t uint16_t avail_idx,\n\t\t\t\t uintptr_t *desc_addrs,\n\t\t\t\t uint16_t *ids)\n{\n\tbool wrap = vq->avail_wrap_counter;\n\tstruct vring_packed_desc *descs = vq->desc_packed;\n\tstruct virtio_net_hdr *hdr;\n\tuint64_t lens[PACKED_BATCH_SIZE];\n\tuint64_t buf_lens[PACKED_BATCH_SIZE];\n\tuint32_t buf_offset = dev->vhost_hlen;\n\tuint16_t flags, i;\n\n\tif (unlikely(avail_idx & PACKED_BATCH_MASK))\n\t\treturn -1;\n\tif (unlikely((avail_idx + PACKED_BATCH_SIZE) > vq->size))\n\t\treturn -1;\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) {\n\t\tflags = descs[avail_idx + i].flags;\n\t\tif (unlikely((wrap != !!(flags & VRING_DESC_F_AVAIL)) ||\n\t\t\t (wrap == !!(flags & VRING_DESC_F_USED)) ||\n\t\t\t (flags & PACKED_DESC_SINGLE_DEQUEUE_FLAG)))\n\t\t\treturn -1;\n\t}\n\n\trte_smp_rmb();\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE)\n\t\tlens[i] = descs[avail_idx + i].len;\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) {\n\t\tdesc_addrs[i] = vhost_iova_to_vva(dev, vq,\n\t\t\t\t\t\t descs[avail_idx + i].addr,\n\t\t\t\t\t\t &lens[i], VHOST_ACCESS_RW);\n\t}\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) {\n\t\tif (unlikely((lens[i] != descs[avail_idx + i].len)))\n\t\t\treturn -1;\n\t}\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) {\n\t\tpkts[i] = virtio_dev_pktmbuf_alloc(dev, mbuf_pool, lens[i]);\n\t\tif (!pkts[i])\n\t\t\tgoto free_buf;\n\t}\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE)\n\t\tbuf_lens[i] = pkts[i]->buf_len - pkts[i]->data_off;\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) {\n\t\tif (unlikely(buf_lens[i] < (lens[i] - buf_offset)))\n\t\t\tgoto free_buf;\n\t}\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) {\n\t\tpkts[i]->pkt_len = descs[avail_idx + i].len - buf_offset;\n\t\tpkts[i]->data_len = pkts[i]->pkt_len;\n\t\tids[i] = descs[avail_idx + i].id;\n\t}\n\n\tif (virtio_net_with_host_offload(dev)) {\n\t\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) {\n\t\t\thdr = (struct virtio_net_hdr *)(desc_addrs[i]);\n\t\t\tvhost_dequeue_offload(hdr, pkts[i]);\n\t\t}\n\t}\n\n\treturn 0;\n\nfree_buf:\n\tfor (i = 0; i < PACKED_BATCH_SIZE; i++)\n\t\trte_pktmbuf_free(pkts[i]);\n\n\treturn -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-665'], 'message': 'vhost: fix translated address not checked\n\nMalicious guest can construct desc with invalid address and zero buffer\nlength. That will request vhost to check both translated address and\ntranslated data length. This patch will add missed address check.\n\nCVE-2020-10725\nFixes: 75ed51697820 (\"vhost: add packed ring batch dequeue\")\nFixes: ef861692c398 (\"vhost: add packed ring batch enqueue\")\nCc: stable@dpdk.org\n\nSigned-off-by: Marvin Liu \nReviewed-by: Maxime Coquelin '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: getScanlineChunkOffsetTableSize(const Header& header)\n{\n const Box2i &dataWindow = header.dataWindow();\n\n vector bytesPerLine;\n size_t maxBytesPerLine = bytesPerLineTable (header,\n bytesPerLine);\n\n Compressor* compressor = newCompressor(header.compression(),\n maxBytesPerLine,\n header);\n\n int linesInBuffer = numLinesInBuffer (compressor);\n\n int lineOffsetSize = (dataWindow.max.y - dataWindow.min.y +\n linesInBuffer) / linesInBuffer;\n\n delete compressor;\n\n return lineOffsetSize;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'fix memory leaks and invalid memory accesses\n\nSigned-off-by: Peter Hillman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: DeepTiledInputFile::DeepTiledInputFile (InputPartData* part) :\n _data (new Data (part->numThreads))\n{\n _data->_deleteStream=false;\n multiPartInitialize(part);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'fix memory leaks and invalid memory accesses\n\nSigned-off-by: Peter Hillman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void ScanLineInputFile::initialize(const Header& header)\n{\n try\n {\n _data->header = header;\n\n _data->lineOrder = _data->header.lineOrder();\n\n const Box2i &dataWindow = _data->header.dataWindow();\n\n _data->minX = dataWindow.min.x;\n _data->maxX = dataWindow.max.x;\n _data->minY = dataWindow.min.y;\n _data->maxY = dataWindow.max.y;\n\n size_t maxBytesPerLine = bytesPerLineTable (_data->header,\n _data->bytesPerLine);\n\n for (size_t i = 0; i < _data->lineBuffers.size(); i++)\n {\n _data->lineBuffers[i] = new LineBuffer (newCompressor\n (_data->header.compression(),\n maxBytesPerLine,\n _data->header));\n }\n\n _data->linesInBuffer =\n numLinesInBuffer (_data->lineBuffers[0]->compressor);\n\n _data->lineBufferSize = maxBytesPerLine * _data->linesInBuffer;\n\n if (!_streamData->is->isMemoryMapped())\n {\n for (size_t i = 0; i < _data->lineBuffers.size(); i++)\n {\n _data->lineBuffers[i]->buffer = (char *) EXRAllocAligned(_data->lineBufferSize*sizeof(char),16);\n }\n }\n _data->nextLineBufferMinY = _data->minY - 1;\n\n offsetInLineBufferTable (_data->bytesPerLine,\n _data->linesInBuffer,\n _data->offsetInLineBuffer);\n\n int lineOffsetSize = (dataWindow.max.y - dataWindow.min.y +\n _data->linesInBuffer) / _data->linesInBuffer;\n\n _data->lineOffsets.resize (lineOffsetSize);\n }\n catch (...)\n {\n delete _data;\n _data=NULL;\n throw;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'fix memory leaks and invalid memory accesses\n\nSigned-off-by: Peter Hillman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: GIT_INLINE(bool) verify_dotgit_ntfs(git_repository *repo, const char *path, size_t len)\n{\n\tgit_buf *reserved = git_repository__reserved_names_win32;\n\tsize_t reserved_len = git_repository__reserved_names_win32_len;\n\tsize_t start = 0, i;\n\n\tif (repo)\n\t\tgit_repository__reserved_names(&reserved, &reserved_len, repo, true);\n\n\tfor (i = 0; i < reserved_len; i++) {\n\t\tgit_buf *r = &reserved[i];\n\n\t\tif (len >= r->size &&\n\t\t\tstrncasecmp(path, r->ptr, r->size) == 0) {\n\t\t\tstart = r->size;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (!start)\n\t\treturn true;\n\n\t/* Reject paths like \".git\\\" */\n\tif (path[start] == '\\\\')\n\t\treturn false;\n\n\t/* Reject paths like '.git ' or '.git.' */\n\tfor (i = start; i < len; i++) {\n\t\tif (path[i] != ' ' && path[i] != '.')\n\t\t\treturn true;\n\t}\n\n\treturn false;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-706'], 'message': 'Disallow NTFS Alternate Data Stream attacks, even on Linux/macOS\n\nA little-known feature of NTFS is that it offers to store metadata in\nso-called \"Alternate Data Streams\" (inspired by Apple's \"resource\nforks\") that are copied together with the file they are associated with.\nThese Alternate Data Streams can be accessed via `::`.\n\nDirectories, too, have Alternate Data Streams, and they even have a\ndefault stream type `$INDEX_ALLOCATION`. Which means that `abc/` and\n`abc::$INDEX_ALLOCATION/` are actually equivalent.\n\nThis is of course another attack vector on the Git directory that we\ndefinitely want to prevent.\n\nOn Windows, we already do this incidentally, by disallowing colons in\nfile/directory names.\n\nWhile it looks as if files'/directories' Alternate Data Streams are not\naccessible in the Windows Subsystem for Linux, and neither via\nCIFS/SMB-mounted network shares in Linux, it _is_ possible to access\nthem on SMB-mounted network shares on macOS.\n\nTherefore, let's go the extra mile and prevent this particular attack\n_everywhere_. To keep things simple, let's just disallow *any* Alternate\nData Stream of `.git`.\n\nThis is libgit2's variant of CVE-2019-1352.\n\nSigned-off-by: Johannes Schindelin '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void usb_sg_cancel(struct usb_sg_request *io)\n{\n\tunsigned long flags;\n\tint i, retval;\n\n\tspin_lock_irqsave(&io->lock, flags);\n\tif (io->status) {\n\t\tspin_unlock_irqrestore(&io->lock, flags);\n\t\treturn;\n\t}\n\t/* shut everything down */\n\tio->status = -ECONNRESET;\n\tspin_unlock_irqrestore(&io->lock, flags);\n\n\tfor (i = io->entries - 1; i >= 0; --i) {\n\t\tusb_block_urb(io->urbs[i]);\n\n\t\tretval = usb_unlink_urb(io->urbs[i]);\n\t\tif (retval != -EINPROGRESS\n\t\t && retval != -ENODEV\n\t\t && retval != -EBUSY\n\t\t && retval != -EIDRM)\n\t\t\tdev_warn(&io->dev->dev, \"%s, unlink --> %d\\n\",\n\t\t\t\t __func__, retval);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'USB: core: Fix free-while-in-use bug in the USB S-Glibrary\n\nFuzzUSB (a variant of syzkaller) found a free-while-still-in-use bug\nin the USB scatter-gather library:\n\nBUG: KASAN: use-after-free in atomic_read\ninclude/asm-generic/atomic-instrumented.h:26 [inline]\nBUG: KASAN: use-after-free in usb_hcd_unlink_urb+0x5f/0x170\ndrivers/usb/core/hcd.c:1607\nRead of size 4 at addr ffff888065379610 by task kworker/u4:1/27\n\nCPU: 1 PID: 27 Comm: kworker/u4:1 Not tainted 5.5.11 #2\nHardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS\n1.10.2-1ubuntu1 04/01/2014\nWorkqueue: scsi_tmf_2 scmd_eh_abort_handler\nCall Trace:\n __dump_stack lib/dump_stack.c:77 [inline]\n dump_stack+0xce/0x128 lib/dump_stack.c:118\n print_address_description.constprop.4+0x21/0x3c0 mm/kasan/report.c:374\n __kasan_report+0x153/0x1cb mm/kasan/report.c:506\n kasan_report+0x12/0x20 mm/kasan/common.c:639\n check_memory_region_inline mm/kasan/generic.c:185 [inline]\n check_memory_region+0x152/0x1b0 mm/kasan/generic.c:192\n __kasan_check_read+0x11/0x20 mm/kasan/common.c:95\n atomic_read include/asm-generic/atomic-instrumented.h:26 [inline]\n usb_hcd_unlink_urb+0x5f/0x170 drivers/usb/core/hcd.c:1607\n usb_unlink_urb+0x72/0xb0 drivers/usb/core/urb.c:657\n usb_sg_cancel+0x14e/0x290 drivers/usb/core/message.c:602\n usb_stor_stop_transport+0x5e/0xa0 drivers/usb/storage/transport.c:937\n\nThis bug occurs when cancellation of the S-G transfer races with\ntransfer completion. When that happens, usb_sg_cancel() may continue\nto access the transfer's URBs after usb_sg_wait() has freed them.\n\nThe bug is caused by the fact that usb_sg_cancel() does not take any\nsort of reference to the transfer, and so there is nothing to prevent\nthe URBs from being deallocated while the routine is trying to use\nthem. The fix is to take such a reference by incrementing the\ntransfer's io->count field while the cancellation is in progres and\ndecrementing it afterward. The transfer's URBs are not deallocated\nuntil io->complete is triggered, which happens when io->count reaches\nzero.\n\nSigned-off-by: Alan Stern \nReported-and-tested-by: Kyungtae Kim \nCC: \n\nLink: https://lore.kernel.org/r/Pine.LNX.4.44L0.2003281615140.14837-100000@netrider.rowland.org\nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: compat_mpt_command(struct file *filp, unsigned int cmd,\n\t\t\tunsigned long arg)\n{\n\tstruct mpt_ioctl_command32 karg32;\n\tstruct mpt_ioctl_command32 __user *uarg = (struct mpt_ioctl_command32 __user *) arg;\n\tstruct mpt_ioctl_command karg;\n\tMPT_ADAPTER *iocp = NULL;\n\tint iocnum, iocnumX;\n\tint nonblock = (filp->f_flags & O_NONBLOCK);\n\tint ret;\n\n\tif (copy_from_user(&karg32, (char __user *)arg, sizeof(karg32)))\n\t\treturn -EFAULT;\n\n\t/* Verify intended MPT adapter */\n\tiocnumX = karg32.hdr.iocnum & 0xFF;\n\tif (((iocnum = mpt_verify_adapter(iocnumX, &iocp)) < 0) ||\n\t (iocp == NULL)) {\n\t\tprintk(KERN_DEBUG MYNAM \"::compat_mpt_command @%d - ioc%d not found!\\n\",\n\t\t\t__LINE__, iocnumX);\n\t\treturn -ENODEV;\n\t}\n\n\tif ((ret = mptctl_syscall_down(iocp, nonblock)) != 0)\n\t\treturn ret;\n\n\tdctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT \"compat_mpt_command() called\\n\",\n\t iocp->name));\n\t/* Copy data to karg */\n\tkarg.hdr.iocnum = karg32.hdr.iocnum;\n\tkarg.hdr.port = karg32.hdr.port;\n\tkarg.timeout = karg32.timeout;\n\tkarg.maxReplyBytes = karg32.maxReplyBytes;\n\n\tkarg.dataInSize = karg32.dataInSize;\n\tkarg.dataOutSize = karg32.dataOutSize;\n\tkarg.maxSenseBytes = karg32.maxSenseBytes;\n\tkarg.dataSgeOffset = karg32.dataSgeOffset;\n\n\tkarg.replyFrameBufPtr = (char __user *)(unsigned long)karg32.replyFrameBufPtr;\n\tkarg.dataInBufPtr = (char __user *)(unsigned long)karg32.dataInBufPtr;\n\tkarg.dataOutBufPtr = (char __user *)(unsigned long)karg32.dataOutBufPtr;\n\tkarg.senseDataPtr = (char __user *)(unsigned long)karg32.senseDataPtr;\n\n\t/* Pass new structure to do_mpt_command\n\t */\n\tret = mptctl_do_mpt_command (karg, &uarg->MF);\n\n\tmutex_unlock(&iocp->ioctl_cmds.mutex);\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362', 'CWE-369'], 'message': 'scsi: mptfusion: Fix double fetch bug in ioctl\n\nTom Hatskevich reported that we look up \"iocp\" then, in the called\nfunctions we do a second copy_from_user() and look it up again.\nThe problem that could cause is:\n\ndrivers/message/fusion/mptctl.c\n 674 /* All of these commands require an interrupt or\n 675 * are unknown/illegal.\n 676 */\n 677 if ((ret = mptctl_syscall_down(iocp, nonblock)) != 0)\n ^^^^\nWe take this lock.\n\n 678 return ret;\n 679\n 680 if (cmd == MPTFWDOWNLOAD)\n 681 ret = mptctl_fw_download(arg);\n ^^^\nThen the user memory changes and we look up \"iocp\" again but a different\none so now we are holding the incorrect lock and have a race condition.\n\n 682 else if (cmd == MPTCOMMAND)\n 683 ret = mptctl_mpt_command(arg);\n\nThe security impact of this bug is not as bad as it could have been\nbecause these operations are all privileged and root already has\nenormous destructive power. But it's still worth fixing.\n\nThis patch passes the \"iocp\" pointer to the functions to avoid the\nsecond lookup. That deletes 100 lines of code from the driver so\nit's a nice clean up as well.\n\nLink: https://lore.kernel.org/r/20200114123414.GA7957@kadam\nReported-by: Tom Hatskevich \nReviewed-by: Greg Kroah-Hartman \nSigned-off-by: Dan Carpenter \nSigned-off-by: Martin K. Petersen '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: mptctl_eventreport (unsigned long arg)\n{\n\tstruct mpt_ioctl_eventreport __user *uarg = (void __user *) arg;\n\tstruct mpt_ioctl_eventreport\t karg;\n\tMPT_ADAPTER\t\t *ioc;\n\tint\t\t\t iocnum;\n\tint\t\t\t numBytes, maxEvents, max;\n\n\tif (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_eventreport))) {\n\t\tprintk(KERN_ERR MYNAM \"%s@%d::mptctl_eventreport - \"\n\t\t\t\"Unable to read in mpt_ioctl_eventreport struct @ %p\\n\",\n\t\t\t\t__FILE__, __LINE__, uarg);\n\t\treturn -EFAULT;\n\t}\n\n\tif (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||\n\t (ioc == NULL)) {\n\t\tprintk(KERN_DEBUG MYNAM \"%s::mptctl_eventreport() @%d - ioc%d not found!\\n\",\n\t\t\t\t__FILE__, __LINE__, iocnum);\n\t\treturn -ENODEV;\n\t}\n\tdctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT \"mptctl_eventreport called.\\n\",\n\t ioc->name));\n\n\tnumBytes = karg.hdr.maxDataSize - sizeof(mpt_ioctl_header);\n\tmaxEvents = numBytes/sizeof(MPT_IOCTL_EVENTS);\n\n\n\tmax = MPTCTL_EVENT_LOG_SIZE < maxEvents ? MPTCTL_EVENT_LOG_SIZE : maxEvents;\n\n\t/* If fewer than 1 event is requested, there must have\n\t * been some type of error.\n\t */\n\tif ((max < 1) || !ioc->events)\n\t\treturn -ENODATA;\n\n\t/* reset this flag so SIGIO can restart */\n\tioc->aen_event_read_flag=0;\n\n\t/* Copy the data from kernel memory to user memory\n\t */\n\tnumBytes = max * sizeof(MPT_IOCTL_EVENTS);\n\tif (copy_to_user(uarg->eventData, ioc->events, numBytes)) {\n\t\tprintk(MYIOC_s_ERR_FMT \"%s@%d::mptctl_eventreport - \"\n\t\t\t\"Unable to write out mpt_ioctl_eventreport struct @ %p\\n\",\n\t\t\tioc->name, __FILE__, __LINE__, ioc->events);\n\t\treturn -EFAULT;\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362', 'CWE-369'], 'message': 'scsi: mptfusion: Fix double fetch bug in ioctl\n\nTom Hatskevich reported that we look up \"iocp\" then, in the called\nfunctions we do a second copy_from_user() and look it up again.\nThe problem that could cause is:\n\ndrivers/message/fusion/mptctl.c\n 674 /* All of these commands require an interrupt or\n 675 * are unknown/illegal.\n 676 */\n 677 if ((ret = mptctl_syscall_down(iocp, nonblock)) != 0)\n ^^^^\nWe take this lock.\n\n 678 return ret;\n 679\n 680 if (cmd == MPTFWDOWNLOAD)\n 681 ret = mptctl_fw_download(arg);\n ^^^\nThen the user memory changes and we look up \"iocp\" again but a different\none so now we are holding the incorrect lock and have a race condition.\n\n 682 else if (cmd == MPTCOMMAND)\n 683 ret = mptctl_mpt_command(arg);\n\nThe security impact of this bug is not as bad as it could have been\nbecause these operations are all privileged and root already has\nenormous destructive power. But it's still worth fixing.\n\nThis patch passes the \"iocp\" pointer to the functions to avoid the\nsecond lookup. That deletes 100 lines of code from the driver so\nit's a nice clean up as well.\n\nLink: https://lore.kernel.org/r/20200114123414.GA7957@kadam\nReported-by: Tom Hatskevich \nReviewed-by: Greg Kroah-Hartman \nSigned-off-by: Dan Carpenter \nSigned-off-by: Martin K. Petersen '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: \nstatic void bfq_idle_slice_timer_body(struct bfq_queue *bfqq)\n{\n\tstruct bfq_data *bfqd = bfqq->bfqd;\n\tenum bfqq_expiration reason;\n\tunsigned long flags;\n\n\tspin_lock_irqsave(&bfqd->lock, flags);\n\tbfq_clear_bfqq_wait_request(bfqq);\n\n\tif (bfqq != bfqd->in_service_queue) {\n\t\tspin_unlock_irqrestore(&bfqd->lock, flags);\n\t\treturn;\n\t}\n\n\tif (bfq_bfqq_budget_timeout(bfqq))\n\t\t/*\n\t\t * Also here the queue can be safely expired\n\t\t * for budget timeout without wasting\n\t\t * guarantees\n\t\t */\n\t\treason = BFQQE_BUDGET_TIMEOUT;\n\telse if (bfqq->queued[0] == 0 && bfqq->queued[1] == 0)\n\t\t/*\n\t\t * The queue may not be empty upon timer expiration,\n\t\t * because we may not disable the timer when the\n\t\t * first request of the in-service queue arrives\n\t\t * during disk idling.\n\t\t */\n\t\treason = BFQQE_TOO_IDLE;\n\telse\n\t\tgoto schedule_dispatch;\n\n\tbfq_bfqq_expire(bfqd, bfqq, true, reason);\n\nschedule_dispatch:\n\tspin_unlock_irqrestore(&bfqd->lock, flags);\n\tbfq_schedule_dispatch(bfqd); ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'block, bfq: fix use-after-free in bfq_idle_slice_timer_body\n\nIn bfq_idle_slice_timer func, bfqq = bfqd->in_service_queue is\nnot in bfqd-lock critical section. The bfqq, which is not\nequal to NULL in bfq_idle_slice_timer, may be freed after passing\nto bfq_idle_slice_timer_body. So we will access the freed memory.\n\nIn addition, considering the bfqq may be in race, we should\nfirstly check whether bfqq is in service before doing something\non it in bfq_idle_slice_timer_body func. If the bfqq in race is\nnot in service, it means the bfqq has been expired through\n__bfq_bfqq_expire func, and wait_request flags has been cleared in\n__bfq_bfqd_reset_in_service func. So we do not need to re-clear the\nwait_request of bfqq which is not in service.\n\nKASAN log is given as follows:\n[13058.354613] ==================================================================\n[13058.354640] BUG: KASAN: use-after-free in bfq_idle_slice_timer+0xac/0x290\n[13058.354644] Read of size 8 at addr ffffa02cf3e63f78 by task fork13/19767\n[13058.354646]\n[13058.354655] CPU: 96 PID: 19767 Comm: fork13\n[13058.354661] Call trace:\n[13058.354667] dump_backtrace+0x0/0x310\n[13058.354672] show_stack+0x28/0x38\n[13058.354681] dump_stack+0xd8/0x108\n[13058.354687] print_address_description+0x68/0x2d0\n[13058.354690] kasan_report+0x124/0x2e0\n[13058.354697] __asan_load8+0x88/0xb0\n[13058.354702] bfq_idle_slice_timer+0xac/0x290\n[13058.354707] __hrtimer_run_queues+0x298/0x8b8\n[13058.354710] hrtimer_interrupt+0x1b8/0x678\n[13058.354716] arch_timer_handler_phys+0x4c/0x78\n[13058.354722] handle_percpu_devid_irq+0xf0/0x558\n[13058.354731] generic_handle_irq+0x50/0x70\n[13058.354735] __handle_domain_irq+0x94/0x110\n[13058.354739] gic_handle_irq+0x8c/0x1b0\n[13058.354742] el1_irq+0xb8/0x140\n[13058.354748] do_wp_page+0x260/0xe28\n[13058.354752] __handle_mm_fault+0x8ec/0x9b0\n[13058.354756] handle_mm_fault+0x280/0x460\n[13058.354762] do_page_fault+0x3ec/0x890\n[13058.354765] do_mem_abort+0xc0/0x1b0\n[13058.354768] el0_da+0x24/0x28\n[13058.354770]\n[13058.354773] Allocated by task 19731:\n[13058.354780] kasan_kmalloc+0xe0/0x190\n[13058.354784] kasan_slab_alloc+0x14/0x20\n[13058.354788] kmem_cache_alloc_node+0x130/0x440\n[13058.354793] bfq_get_queue+0x138/0x858\n[13058.354797] bfq_get_bfqq_handle_split+0xd4/0x328\n[13058.354801] bfq_init_rq+0x1f4/0x1180\n[13058.354806] bfq_insert_requests+0x264/0x1c98\n[13058.354811] blk_mq_sched_insert_requests+0x1c4/0x488\n[13058.354818] blk_mq_flush_plug_list+0x2d4/0x6e0\n[13058.354826] blk_flush_plug_list+0x230/0x548\n[13058.354830] blk_finish_plug+0x60/0x80\n[13058.354838] read_pages+0xec/0x2c0\n[13058.354842] __do_page_cache_readahead+0x374/0x438\n[13058.354846] ondemand_readahead+0x24c/0x6b0\n[13058.354851] page_cache_sync_readahead+0x17c/0x2f8\n[13058.354858] generic_file_buffered_read+0x588/0xc58\n[13058.354862] generic_file_read_iter+0x1b4/0x278\n[13058.354965] ext4_file_read_iter+0xa8/0x1d8 [ext4]\n[13058.354972] __vfs_read+0x238/0x320\n[13058.354976] vfs_read+0xbc/0x1c0\n[13058.354980] ksys_read+0xdc/0x1b8\n[13058.354984] __arm64_sys_read+0x50/0x60\n[13058.354990] el0_svc_common+0xb4/0x1d8\n[13058.354994] el0_svc_handler+0x50/0xa8\n[13058.354998] el0_svc+0x8/0xc\n[13058.354999]\n[13058.355001] Freed by task 19731:\n[13058.355007] __kasan_slab_free+0x120/0x228\n[13058.355010] kasan_slab_free+0x10/0x18\n[13058.355014] kmem_cache_free+0x288/0x3f0\n[13058.355018] bfq_put_queue+0x134/0x208\n[13058.355022] bfq_exit_icq_bfqq+0x164/0x348\n[13058.355026] bfq_exit_icq+0x28/0x40\n[13058.355030] ioc_exit_icq+0xa0/0x150\n[13058.355035] put_io_context_active+0x250/0x438\n[13058.355038] exit_io_context+0xd0/0x138\n[13058.355045] do_exit+0x734/0xc58\n[13058.355050] do_group_exit+0x78/0x220\n[13058.355054] __wake_up_parent+0x0/0x50\n[13058.355058] el0_svc_common+0xb4/0x1d8\n[13058.355062] el0_svc_handler+0x50/0xa8\n[13058.355066] el0_svc+0x8/0xc\n[13058.355067]\n[13058.355071] The buggy address belongs to the object at ffffa02cf3e63e70#012 which belongs to the cache bfq_queue of size 464\n[13058.355075] The buggy address is located 264 bytes inside of#012 464-byte region [ffffa02cf3e63e70, ffffa02cf3e64040)\n[13058.355077] The buggy address belongs to the page:\n[13058.355083] page:ffff7e80b3cf9800 count:1 mapcount:0 mapping:ffff802db5c90780 index:0xffffa02cf3e606f0 compound_mapcount: 0\n[13058.366175] flags: 0x2ffffe0000008100(slab|head)\n[13058.370781] raw: 2ffffe0000008100 ffff7e80b53b1408 ffffa02d730c1c90 ffff802db5c90780\n[13058.370787] raw: ffffa02cf3e606f0 0000000000370023 00000001ffffffff 0000000000000000\n[13058.370789] page dumped because: kasan: bad access detected\n[13058.370791]\n[13058.370792] Memory state around the buggy address:\n[13058.370797] ffffa02cf3e63e00: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fb fb\n[13058.370801] ffffa02cf3e63e80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n[13058.370805] >ffffa02cf3e63f00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n[13058.370808] ^\n[13058.370811] ffffa02cf3e63f80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n[13058.370815] ffffa02cf3e64000: fb fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc\n[13058.370817] ==================================================================\n[13058.370820] Disabling lock debugging due to kernel taint\n\nHere, we directly pass the bfqd to bfq_idle_slice_timer_body func.\n--\nV2->V3: rewrite the comment as suggested by Paolo Valente\nV1->V2: add one comment, and add Fixes and Reported-by tag.\n\nFixes: aee69d78d (\"block, bfq: introduce the BFQ-v0 I/O scheduler as an extra scheduler\")\nAcked-by: Paolo Valente \nReported-by: Wang Wang \nSigned-off-by: Zhiqiang Liu \nSigned-off-by: Feilong Lin \nSigned-off-by: Jens Axboe '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: get_filter_list( Operation *op, BerElement *ber,\n\tFilter **f,\n\tconst char **text )\n{\n\tFilter\t\t**new;\n\tint\t\terr;\n\tber_tag_t\ttag;\n\tber_len_t\tlen;\n\tchar\t\t*last;\n\n\tDebug( LDAP_DEBUG_FILTER, \"begin get_filter_list\\n\", 0, 0, 0 );\n\tnew = f;\n\tfor ( tag = ber_first_element( ber, &len, &last );\n\t\ttag != LBER_DEFAULT;\n\t\ttag = ber_next_element( ber, &len, last ) )\n\t{\n\t\terr = get_filter( op, ber, new, text );\n\t\tif ( err != LDAP_SUCCESS )\n\t\t\treturn( err );\n\t\tnew = &(*new)->f_next;\n\t}\n\t*new = NULL;\n\n\tDebug( LDAP_DEBUG_FILTER, \"end get_filter_list\\n\", 0, 0, 0 );\n\treturn( LDAP_SUCCESS );\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-674'], 'message': 'ITS#9202 limit depth of nested filters\n\nUsing a hardcoded limit for now; no reasonable apps\nshould ever run into it.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static BOOL update_read_bitmap_data(rdpUpdate* update, wStream* s, BITMAP_DATA* bitmapData)\n{\n\tWINPR_UNUSED(update);\n\tif (Stream_GetRemainingLength(s) < 18)\n\t\treturn FALSE;\n\n\tStream_Read_UINT16(s, bitmapData->destLeft);\n\tStream_Read_UINT16(s, bitmapData->destTop);\n\tStream_Read_UINT16(s, bitmapData->destRight);\n\tStream_Read_UINT16(s, bitmapData->destBottom);\n\tStream_Read_UINT16(s, bitmapData->width);\n\tStream_Read_UINT16(s, bitmapData->height);\n\tStream_Read_UINT16(s, bitmapData->bitsPerPixel);\n\tStream_Read_UINT16(s, bitmapData->flags);\n\tStream_Read_UINT16(s, bitmapData->bitmapLength);\n\n\tif (bitmapData->flags & BITMAP_COMPRESSION)\n\t{\n\t\tif (!(bitmapData->flags & NO_BITMAP_COMPRESSION_HDR))\n\t\t{\n\t\t\tStream_Read_UINT16(s,\n\t\t\t bitmapData->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */\n\t\t\tStream_Read_UINT16(s,\n\t\t\t bitmapData->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */\n\t\t\tStream_Read_UINT16(s, bitmapData->cbScanWidth); /* cbScanWidth (2 bytes) */\n\t\t\tStream_Read_UINT16(s,\n\t\t\t bitmapData->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */\n\t\t\tbitmapData->bitmapLength = bitmapData->cbCompMainBodySize;\n\t\t}\n\n\t\tbitmapData->compressed = TRUE;\n\t}\n\telse\n\t\tbitmapData->compressed = FALSE;\n\n\tif (Stream_GetRemainingLength(s) < bitmapData->bitmapLength)\n\t\treturn FALSE;\n\n\tif (bitmapData->bitmapLength > 0)\n\t{\n\t\tbitmapData->bitmapDataStream = malloc(bitmapData->bitmapLength);\n\n\t\tif (!bitmapData->bitmapDataStream)\n\t\t\treturn FALSE;\n\n\t\tmemcpy(bitmapData->bitmapDataStream, Stream_Pointer(s), bitmapData->bitmapLength);\n\t\tStream_Seek(s, bitmapData->bitmapLength);\n\t}\n\n\treturn TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed #6005: Bounds checks in update_read_bitmap_data'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static CACHE_BITMAP_ORDER* update_read_cache_bitmap_order(rdpUpdate* update, wStream* s,\n BOOL compressed, UINT16 flags)\n{\n\tCACHE_BITMAP_ORDER* cache_bitmap;\n\n\tif (!update || !s)\n\t\treturn NULL;\n\n\tcache_bitmap = calloc(1, sizeof(CACHE_BITMAP_ORDER));\n\n\tif (!cache_bitmap)\n\t\tgoto fail;\n\n\tif (Stream_GetRemainingLength(s) < 9)\n\t\tgoto fail;\n\n\tStream_Read_UINT8(s, cache_bitmap->cacheId); /* cacheId (1 byte) */\n\tStream_Seek_UINT8(s); /* pad1Octet (1 byte) */\n\tStream_Read_UINT8(s, cache_bitmap->bitmapWidth); /* bitmapWidth (1 byte) */\n\tStream_Read_UINT8(s, cache_bitmap->bitmapHeight); /* bitmapHeight (1 byte) */\n\tStream_Read_UINT8(s, cache_bitmap->bitmapBpp); /* bitmapBpp (1 byte) */\n\n\tif ((cache_bitmap->bitmapBpp < 1) || (cache_bitmap->bitmapBpp > 32))\n\t{\n\t\tWLog_Print(update->log, WLOG_ERROR, \"invalid bitmap bpp %\" PRIu32 \"\",\n\t\t cache_bitmap->bitmapBpp);\n\t\tgoto fail;\n\t}\n\n\tStream_Read_UINT16(s, cache_bitmap->bitmapLength); /* bitmapLength (2 bytes) */\n\tStream_Read_UINT16(s, cache_bitmap->cacheIndex); /* cacheIndex (2 bytes) */\n\n\tif (compressed)\n\t{\n\t\tif ((flags & NO_BITMAP_COMPRESSION_HDR) == 0)\n\t\t{\n\t\t\tBYTE* bitmapComprHdr = (BYTE*)&(cache_bitmap->bitmapComprHdr);\n\n\t\t\tif (Stream_GetRemainingLength(s) < 8)\n\t\t\t\tgoto fail;\n\n\t\t\tStream_Read(s, bitmapComprHdr, 8); /* bitmapComprHdr (8 bytes) */\n\t\t\tcache_bitmap->bitmapLength -= 8;\n\t\t}\n\t}\n\n\tif (Stream_GetRemainingLength(s) < cache_bitmap->bitmapLength)\n\t\tgoto fail;\n\n\tcache_bitmap->bitmapDataStream = malloc(cache_bitmap->bitmapLength);\n\n\tif (!cache_bitmap->bitmapDataStream)\n\t\tgoto fail;\n\n\tStream_Read(s, cache_bitmap->bitmapDataStream, cache_bitmap->bitmapLength);\n\tcache_bitmap->compressed = compressed;\n\treturn cache_bitmap;\nfail:\n\tfree_cache_bitmap_order(update->context, cache_bitmap);\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed CVE-2020-11521: Out of bounds write in planar codec.\n\nThanks to Sunglin and HuanGMz from Knownsec 404'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void bitmap_cache_free(rdpBitmapCache* bitmapCache)\n{\n\tint i, j;\n\trdpBitmap* bitmap;\n\n\tif (bitmapCache)\n\t{\n\t\tfor (i = 0; i < (int)bitmapCache->maxCells; i++)\n\t\t{\n\t\t\tfor (j = 0; j < (int)bitmapCache->cells[i].number + 1; j++)\n\t\t\t{\n\t\t\t\tbitmap = bitmapCache->cells[i].entries[j];\n\t\t\t\tBitmap_Free(bitmapCache->context, bitmap);\n\t\t\t}\n\n\t\t\tfree(bitmapCache->cells[i].entries);\n\t\t}\n\n\t\tfree(bitmapCache->cells);\n\t\tfree(bitmapCache);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed CVE-2020-11525: Out of bounds read in bitmap_cache_new\n\nThanks to Sunglin and HuanGMz from Knownsec 404'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void nodeConstruct(struct SaveNode* node, tr_variant const* v, bool sort_dicts)\n{\n node->isVisited = false;\n node->childIndex = 0;\n\n if (sort_dicts && tr_variantIsDict(v))\n {\n /* make node->sorted a sorted version of this dictionary */\n\n size_t const n = v->val.l.count;\n struct KeyIndex* tmp = tr_new(struct KeyIndex, n);\n\n for (size_t i = 0; i < n; i++)\n {\n tmp[i].val = v->val.l.vals + i;\n tmp[i].keystr = tr_quark_get_string(tmp[i].val->key, NULL);\n }\n\n qsort(tmp, n, sizeof(struct KeyIndex), compareKeyIndex);\n\n tr_variantInitDict(&node->sorted, n);\n\n for (size_t i = 0; i < n; ++i)\n {\n node->sorted.val.l.vals[i] = *tmp[i].val;\n }\n\n node->sorted.val.l.count = n;\n\n tr_free(tmp);\n\n node->v = &node->sorted;\n }\n else\n {\n node->v = v;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-284'], 'message': 'CVE-2018-10756: Fix heap-use-after-free in tr_variantWalk\n\nIn libtransmission/variant.c, function tr_variantWalk, when the variant\nstack is reallocated, a pointer to the previously allocated memory\nregion is kept. This address is later accessed (heap use-after-free)\nwhile walking back down the stack, causing the application to crash.\nThe application can be any application which uses libtransmission, such\nas transmission-daemon, transmission-gtk, transmission-show, etc.\n\nReported-by: Tom Richards '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: delegpt_add_addr(struct delegpt* dp, struct regional* region, \n\tstruct sockaddr_storage* addr, socklen_t addrlen, uint8_t bogus, \n\tuint8_t lame, char* tls_auth_name)\n{\n\tstruct delegpt_addr* a;\n\tlog_assert(!dp->dp_type_mlc);\n\t/* check for duplicates */\n\tif((a = delegpt_find_addr(dp, addr, addrlen))) {\n\t\tif(bogus)\n\t\t\ta->bogus = bogus;\n\t\tif(!lame)\n\t\t\ta->lame = 0;\n\t\treturn 1;\n\t}\n\n\ta = (struct delegpt_addr*)regional_alloc(region,\n\t\tsizeof(struct delegpt_addr));\n\tif(!a)\n\t\treturn 0;\n\ta->next_target = dp->target_list;\n\tdp->target_list = a;\n\ta->next_result = 0;\n\ta->next_usable = dp->usable_list;\n\tdp->usable_list = a;\n\tmemcpy(&a->addr, addr, addrlen);\n\ta->addrlen = addrlen;\n\ta->attempts = 0;\n\ta->bogus = bogus;\n\ta->lame = lame;\n\ta->dnsseclame = 0;\n\tif(tls_auth_name) {\n\t\ta->tls_auth_name = regional_strdup(region, tls_auth_name);\n\t\tif(!a->tls_auth_name)\n\t\t\treturn 0;\n\t} else {\n\t\ta->tls_auth_name = NULL;\n\t}\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming\n query into a large number of queries directed to a target.\n- CVE-2020-12663 Malformed answers from upstream name servers can be\n used to make Unbound unresponsive.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: prime_stub(struct module_qstate* qstate, struct iter_qstate* iq, int id,\n\tuint8_t* qname, uint16_t qclass)\n{\n\t/* Lookup the stub hint. This will return null if the stub doesn't \n\t * need to be re-primed. */\n\tstruct iter_hints_stub* stub;\n\tstruct delegpt* stub_dp;\n\tstruct module_qstate* subq;\n\n\tif(!qname) return 0;\n\tstub = hints_lookup_stub(qstate->env->hints, qname, qclass, iq->dp);\n\t/* The stub (if there is one) does not need priming. */\n\tif(!stub)\n\t\treturn 0;\n\tstub_dp = stub->dp;\n\t/* if we have an auth_zone dp, and stub is equal, don't prime stub\n\t * yet, unless we want to fallback and avoid the auth_zone */\n\tif(!iq->auth_zone_avoid && iq->dp && iq->dp->auth_dp && \n\t\tquery_dname_compare(iq->dp->name, stub_dp->name) == 0)\n\t\treturn 0;\n\n\t/* is it a noprime stub (always use) */\n\tif(stub->noprime) {\n\t\tint r = 0;\n\t\tif(iq->dp == NULL) r = 2;\n\t\t/* copy the dp out of the fixed hints structure, so that\n\t\t * it can be changed when servicing this query */\n\t\tiq->dp = delegpt_copy(stub_dp, qstate->region);\n\t\tif(!iq->dp) {\n\t\t\tlog_err(\"out of memory priming stub\");\n\t\t\terrinf(qstate, \"malloc failure, priming stub\");\n\t\t\t(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);\n\t\t\treturn 1; /* return 1 to make module stop, with error */\n\t\t}\n\t\tlog_nametypeclass(VERB_DETAIL, \"use stub\", stub_dp->name, \n\t\t\tLDNS_RR_TYPE_NS, qclass);\n\t\treturn r;\n\t}\n\n\t/* Otherwise, we need to (re)prime the stub. */\n\tlog_nametypeclass(VERB_DETAIL, \"priming stub\", stub_dp->name, \n\t\tLDNS_RR_TYPE_NS, qclass);\n\n\t/* Stub priming events start at the QUERYTARGETS state to avoid the\n\t * redundant INIT state processing. */\n\tif(!generate_sub_request(stub_dp->name, stub_dp->namelen, \n\t\tLDNS_RR_TYPE_NS, qclass, qstate, id, iq,\n\t\tQUERYTARGETS_STATE, PRIME_RESP_STATE, &subq, 0)) {\n\t\tverbose(VERB_ALGO, \"could not prime stub\");\n\t\terrinf(qstate, \"could not generate lookup for stub prime\");\n\t\t(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);\n\t\treturn 1; /* return 1 to make module stop, with error */\n\t}\n\tif(subq) {\n\t\tstruct iter_qstate* subiq = \n\t\t\t(struct iter_qstate*)subq->minfo[id];\n\n\t\t/* Set the initial delegation point to the hint. */\n\t\t/* make copy to avoid use of stub dp by different qs/threads */\n\t\tsubiq->dp = delegpt_copy(stub_dp, subq->region);\n\t\tif(!subiq->dp) {\n\t\t\tlog_err(\"out of memory priming stub, copydp\");\n\t\t\tfptr_ok(fptr_whitelist_modenv_kill_sub(\n\t\t\t\tqstate->env->kill_sub));\n\t\t\t(*qstate->env->kill_sub)(subq);\n\t\t\terrinf(qstate, \"malloc failure, in stub prime\");\n\t\t\t(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);\n\t\t\treturn 1; /* return 1 to make module stop, with error */\n\t\t}\n\t\t/* there should not be any target queries -- although there \n\t\t * wouldn't be anyway, since stub hints never have \n\t\t * missing targets. */\n\t\tsubiq->num_target_queries = 0; \n\t\tsubiq->wait_priming_stub = 1;\n\t\tsubiq->dnssec_expected = iter_indicates_dnssec(\n\t\t\tqstate->env, subiq->dp, NULL, subq->qinfo.qclass);\n\t}\n\t\n\t/* this module stops, our submodule starts, and does the query. */\n\tqstate->ext_state[id] = module_wait_subquery;\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming\n query into a large number of queries directed to a target.\n- CVE-2020-12663 Malformed answers from upstream name servers can be\n used to make Unbound unresponsive.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: scrub_normalize(sldns_buffer* pkt, struct msg_parse* msg, \n\tstruct query_info* qinfo, struct regional* region)\n{\n\tuint8_t* sname = qinfo->qname;\n\tsize_t snamelen = qinfo->qname_len;\n\tstruct rrset_parse* rrset, *prev, *nsset=NULL;\n\n\tif(FLAGS_GET_RCODE(msg->flags) != LDNS_RCODE_NOERROR &&\n\t\tFLAGS_GET_RCODE(msg->flags) != LDNS_RCODE_NXDOMAIN)\n\t\treturn 1;\n\n\t/* For the ANSWER section, remove all \"irrelevant\" records and add\n\t * synthesized CNAMEs from DNAMEs\n\t * This will strip out-of-order CNAMEs as well. */\n\n\t/* walk through the parse packet rrset list, keep track of previous\n\t * for insert and delete ease, and examine every RRset */\n\tprev = NULL;\n\trrset = msg->rrset_first;\n\twhile(rrset && rrset->section == LDNS_SECTION_ANSWER) {\n\t\tif(rrset->type == LDNS_RR_TYPE_DNAME && \n\t\t\tpkt_strict_sub(pkt, sname, rrset->dname)) {\n\t\t\t/* check if next rrset is correct CNAME. else,\n\t\t\t * synthesize a CNAME */\n\t\t\tstruct rrset_parse* nx = rrset->rrset_all_next;\n\t\t\tuint8_t alias[LDNS_MAX_DOMAINLEN+1];\n\t\t\tsize_t aliaslen = 0;\n\t\t\tif(rrset->rr_count != 1) {\n\t\t\t\tverbose(VERB_ALGO, \"Found DNAME rrset with \"\n\t\t\t\t\t\"size > 1: %u\", \n\t\t\t\t\t(unsigned)rrset->rr_count);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif(!synth_cname(sname, snamelen, rrset, alias, \n\t\t\t\t&aliaslen, pkt)) {\n\t\t\t\tverbose(VERB_ALGO, \"synthesized CNAME \"\n\t\t\t\t\t\"too long\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif(nx && nx->type == LDNS_RR_TYPE_CNAME && \n\t\t\t dname_pkt_compare(pkt, sname, nx->dname) == 0) {\n\t\t\t\t/* check next cname */\n\t\t\t\tuint8_t* t = NULL;\n\t\t\t\tsize_t tlen = 0;\n\t\t\t\tif(!parse_get_cname_target(nx, &t, &tlen))\n\t\t\t\t\treturn 0;\n\t\t\t\tif(dname_pkt_compare(pkt, alias, t) == 0) {\n\t\t\t\t\t/* it's OK and better capitalized */\n\t\t\t\t\tprev = rrset;\n\t\t\t\t\trrset = nx;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t/* synth ourselves */\n\t\t\t}\n\t\t\t/* synth a CNAME rrset */\n\t\t\tprev = synth_cname_rrset(&sname, &snamelen, alias, \n\t\t\t\taliaslen, region, msg, rrset, rrset, nx, pkt);\n\t\t\tif(!prev) {\n\t\t\t\tlog_err(\"out of memory synthesizing CNAME\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\t/* FIXME: resolve the conflict between synthesized \n\t\t\t * CNAME ttls and the cache. */\n\t\t\trrset = nx;\n\t\t\tcontinue;\n\n\t\t}\n\n\t\t/* The only records in the ANSWER section not allowed to */\n\t\tif(dname_pkt_compare(pkt, sname, rrset->dname) != 0) {\n\t\t\tremove_rrset(\"normalize: removing irrelevant RRset:\", \n\t\t\t\tpkt, msg, prev, &rrset);\n\t\t\tcontinue;\n\t\t}\n\n\t\t/* Follow the CNAME chain. */\n\t\tif(rrset->type == LDNS_RR_TYPE_CNAME) {\n\t\t\tstruct rrset_parse* nx = rrset->rrset_all_next;\n\t\t\tuint8_t* oldsname = sname;\n\t\t\t/* see if the next one is a DNAME, if so, swap them */\n\t\t\tif(nx && nx->section == LDNS_SECTION_ANSWER &&\n\t\t\t\tnx->type == LDNS_RR_TYPE_DNAME &&\n\t\t\t\tnx->rr_count == 1 &&\n\t\t\t\tpkt_strict_sub(pkt, sname, nx->dname)) {\n\t\t\t\t/* there is a DNAME after this CNAME, it \n\t\t\t\t * is in the ANSWER section, and the DNAME\n\t\t\t\t * applies to the name we cover */\n\t\t\t\t/* check if the alias of the DNAME equals\n\t\t\t\t * this CNAME */\n\t\t\t\tuint8_t alias[LDNS_MAX_DOMAINLEN+1];\n\t\t\t\tsize_t aliaslen = 0;\n\t\t\t\tuint8_t* t = NULL;\n\t\t\t\tsize_t tlen = 0;\n\t\t\t\tif(synth_cname(sname, snamelen, nx, alias,\n\t\t\t\t\t&aliaslen, pkt) &&\n\t\t\t\t\tparse_get_cname_target(rrset, &t, &tlen) &&\n\t\t\t \t\tdname_pkt_compare(pkt, alias, t) == 0) {\n\t\t\t\t\t/* the synthesized CNAME equals the\n\t\t\t\t\t * current CNAME. This CNAME is the\n\t\t\t\t\t * one that the DNAME creates, and this\n\t\t\t\t\t * CNAME is better capitalised */\n\t\t\t\t\tverbose(VERB_ALGO, \"normalize: re-order of DNAME and its CNAME\");\n\t\t\t\t\tif(prev) prev->rrset_all_next = nx;\n\t\t\t\t\telse msg->rrset_first = nx;\n\t\t\t\t\tif(nx->rrset_all_next == NULL)\n\t\t\t\t\t\tmsg->rrset_last = rrset;\n\t\t\t\t\trrset->rrset_all_next =\n\t\t\t\t\t\tnx->rrset_all_next;\n\t\t\t\t\tnx->rrset_all_next = rrset;\n\t\t\t\t\t/* prev = nx; unused, enable if there\n\t\t\t\t\t * is other rrset removal code after\n\t\t\t\t\t * this */\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/* move to next name in CNAME chain */\n\t\t\tif(!parse_get_cname_target(rrset, &sname, &snamelen))\n\t\t\t\treturn 0;\n\t\t\tprev = rrset;\n\t\t\trrset = rrset->rrset_all_next;\n\t\t\t/* in CNAME ANY response, can have data after CNAME */\n\t\t\tif(qinfo->qtype == LDNS_RR_TYPE_ANY) {\n\t\t\t\twhile(rrset && rrset->section ==\n\t\t\t\t\tLDNS_SECTION_ANSWER &&\n\t\t\t\t\tdname_pkt_compare(pkt, oldsname,\n\t\t\t\t\trrset->dname) == 0) {\n\t\t\t\t\tprev = rrset;\n\t\t\t\t\trrset = rrset->rrset_all_next;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\t/* Otherwise, make sure that the RRset matches the qtype. */\n\t\tif(qinfo->qtype != LDNS_RR_TYPE_ANY && \n\t\t\tqinfo->qtype != rrset->type) {\n\t\t\tremove_rrset(\"normalize: removing irrelevant RRset:\", \n\t\t\t\tpkt, msg, prev, &rrset);\n\t\t\tcontinue;\n\t\t}\n\n\t\t/* Mark the additional names from relevant rrset as OK. */\n\t\t/* only for RRsets that match the query name, other ones\n\t\t * will be removed by sanitize, so no additional for them */\n\t\tif(dname_pkt_compare(pkt, qinfo->qname, rrset->dname) == 0)\n\t\t\tmark_additional_rrset(pkt, msg, rrset);\n\t\t\n\t\tprev = rrset;\n\t\trrset = rrset->rrset_all_next;\n\t}\n\n\t/* Mark additional names from AUTHORITY */\n\twhile(rrset && rrset->section == LDNS_SECTION_AUTHORITY) {\n\t\tif(rrset->type==LDNS_RR_TYPE_DNAME ||\n\t\t\trrset->type==LDNS_RR_TYPE_CNAME ||\n\t\t\trrset->type==LDNS_RR_TYPE_A ||\n\t\t\trrset->type==LDNS_RR_TYPE_AAAA) {\n\t\t\tremove_rrset(\"normalize: removing irrelevant \"\n\t\t\t\t\"RRset:\", pkt, msg, prev, &rrset);\n\t\t\tcontinue;\n\t\t}\n\t\t/* only one NS set allowed in authority section */\n\t\tif(rrset->type==LDNS_RR_TYPE_NS) {\n\t\t\t/* NS set must be pertinent to the query */\n\t\t\tif(!sub_of_pkt(pkt, qinfo->qname, rrset->dname)) {\n\t\t\t\tremove_rrset(\"normalize: removing irrelevant \"\n\t\t\t\t\t\"RRset:\", pkt, msg, prev, &rrset);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t/* we don't want NS sets for NXDOMAIN answers,\n\t\t\t * because they could contain poisonous contents,\n\t\t\t * from. eg. fragmentation attacks, inserted after\n\t\t\t * long RRSIGs in the packet get to the packet\n\t\t\t * border and such */\n\t\t\t/* also for NODATA answers */\n\t\t\tif(FLAGS_GET_RCODE(msg->flags) == LDNS_RCODE_NXDOMAIN ||\n\t\t\t (FLAGS_GET_RCODE(msg->flags) == LDNS_RCODE_NOERROR\n\t\t\t && soa_in_auth(msg) && msg->an_rrsets == 0)) {\n\t\t\t\tremove_rrset(\"normalize: removing irrelevant \"\n\t\t\t\t\t\"RRset:\", pkt, msg, prev, &rrset);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif(nsset == NULL) {\n\t\t\t\tnsset = rrset;\n\t\t\t} else {\n\t\t\t\tremove_rrset(\"normalize: removing irrelevant \"\n\t\t\t\t\t\"RRset:\", pkt, msg, prev, &rrset);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\t/* if this is type DS and we query for type DS we just got\n\t\t * a referral answer for our type DS query, fix packet */\n\t\tif(rrset->type==LDNS_RR_TYPE_DS &&\n\t\t\tqinfo->qtype == LDNS_RR_TYPE_DS &&\n\t\t\tdname_pkt_compare(pkt, qinfo->qname, rrset->dname) == 0) {\n\t\t\trrset->section = LDNS_SECTION_ANSWER;\n\t\t\tmsg->ancount = rrset->rr_count + rrset->rrsig_count;\n\t\t\tmsg->nscount = 0;\n\t\t\tmsg->arcount = 0;\n\t\t\tmsg->an_rrsets = 1;\n\t\t\tmsg->ns_rrsets = 0;\n\t\t\tmsg->ar_rrsets = 0;\n\t\t\tmsg->rrset_count = 1;\n\t\t\tmsg->rrset_first = rrset;\n\t\t\tmsg->rrset_last = rrset;\n\t\t\trrset->rrset_all_next = NULL;\n\t\t\treturn 1;\n\t\t}\n\t\tmark_additional_rrset(pkt, msg, rrset);\n\t\tprev = rrset;\n\t\trrset = rrset->rrset_all_next;\n\t}\n\n\t/* For each record in the additional section, remove it if it is an\n\t * address record and not in the collection of additional names \n\t * found in ANSWER and AUTHORITY. */\n\t/* These records have not been marked OK previously */\n\twhile(rrset && rrset->section == LDNS_SECTION_ADDITIONAL) {\n\t\t/* FIXME: what about other types? */\n\t\tif(rrset->type==LDNS_RR_TYPE_A || \n\t\t\trrset->type==LDNS_RR_TYPE_AAAA) \n\t\t{\n\t\t\tif((rrset->flags & RRSET_SCRUB_OK)) {\n\t\t\t\t/* remove flag to clean up flags variable */\n\t\t\t\trrset->flags &= ~RRSET_SCRUB_OK;\n\t\t\t} else {\n\t\t\t\tremove_rrset(\"normalize: removing irrelevant \"\n\t\t\t\t\t\"RRset:\", pkt, msg, prev, &rrset);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tif(rrset->type==LDNS_RR_TYPE_DNAME || \n\t\t\trrset->type==LDNS_RR_TYPE_CNAME ||\n\t\t\trrset->type==LDNS_RR_TYPE_NS) {\n\t\t\tremove_rrset(\"normalize: removing irrelevant \"\n\t\t\t\t\"RRset:\", pkt, msg, prev, &rrset);\n\t\t\tcontinue;\n\t\t}\n\t\tprev = rrset;\n\t\trrset = rrset->rrset_all_next;\n\t}\n\t\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming\n query into a large number of queries directed to a target.\n- CVE-2020-12663 Malformed answers from upstream name servers can be\n used to make Unbound unresponsive.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void dname_pkt_copy(sldns_buffer* pkt, uint8_t* to, uint8_t* dname)\n{\n\t/* copy over the dname and decompress it at the same time */\n\tsize_t comprcount = 0;\n\tsize_t len = 0;\n\tuint8_t lablen;\n\tlablen = *dname++;\n\twhile(lablen) {\n\t\tif(LABEL_IS_PTR(lablen)) {\n\t\t\tif(comprcount++ > MAX_COMPRESS_PTRS) {\n\t\t\t\t/* too many compression pointers */\n\t\t\t\t*to = 0; /* end the result prematurely */\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t/* follow pointer */\n\t\t\tdname = sldns_buffer_at(pkt, PTR_OFFSET(lablen, *dname));\n\t\t\tlablen = *dname++;\n\t\t\tcontinue;\n\t\t}\n\t\tif(lablen > LDNS_MAX_LABELLEN) {\n\t\t\t*to = 0; /* end the result prematurely */\n\t\t\treturn;\n\t\t}\n\t\tlog_assert(lablen <= LDNS_MAX_LABELLEN);\n\t\tlen += (size_t)lablen+1;\n\t\tif(len >= LDNS_MAX_DOMAINLEN) {\n\t\t\t*to = 0; /* end the result prematurely */\n\t\t\tlog_err(\"bad dname in dname_pkt_copy\");\n\t\t\treturn;\n\t\t}\n\t\t*to++ = lablen;\n\t\tmemmove(to, dname, lablen);\n\t\tdname += lablen;\n\t\tto += lablen;\n\t\tlablen = *dname++;\n\t}\n\t/* copy last \\0 */\n\t*to = 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming\n query into a large number of queries directed to a target.\n- CVE-2020-12663 Malformed answers from upstream name servers can be\n used to make Unbound unresponsive.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int selinux_netlink_send(struct sock *sk, struct sk_buff *skb)\n{\n\tint err = 0;\n\tu32 perm;\n\tstruct nlmsghdr *nlh;\n\tstruct sk_security_struct *sksec = sk->sk_security;\n\n\tif (skb->len < NLMSG_HDRLEN) {\n\t\terr = -EINVAL;\n\t\tgoto out;\n\t}\n\tnlh = nlmsg_hdr(skb);\n\n\terr = selinux_nlmsg_lookup(sksec->sclass, nlh->nlmsg_type, &perm);\n\tif (err) {\n\t\tif (err == -EINVAL) {\n\t\t\tpr_warn_ratelimited(\"SELinux: unrecognized netlink\"\n\t\t\t \" message: protocol=%hu nlmsg_type=%hu sclass=%s\"\n\t\t\t \" pid=%d comm=%s\\n\",\n\t\t\t sk->sk_protocol, nlh->nlmsg_type,\n\t\t\t secclass_map[sksec->sclass - 1].name,\n\t\t\t task_pid_nr(current), current->comm);\n\t\t\tif (!enforcing_enabled(&selinux_state) ||\n\t\t\t security_get_allow_unknown(&selinux_state))\n\t\t\t\terr = 0;\n\t\t}\n\n\t\t/* Ignore */\n\t\tif (err == -ENOENT)\n\t\t\terr = 0;\n\t\tgoto out;\n\t}\n\n\terr = sock_has_perm(sk, perm);\nout:\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-349'], 'message': 'selinux: properly handle multiple messages in selinux_netlink_send()\n\nFix the SELinux netlink_send hook to properly handle multiple netlink\nmessages in a single sk_buff; each message is parsed and subject to\nSELinux access control. Prior to this patch, SELinux only inspected\nthe first message in the sk_buff.\n\nCc: stable@vger.kernel.org\nReported-by: Dmitry Vyukov \nReviewed-by: Stephen Smalley \nSigned-off-by: Paul Moore '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: exif_mnote_data_canon_load (ExifMnoteData *ne,\n\tconst unsigned char *buf, unsigned int buf_size)\n{\n\tExifMnoteDataCanon *n = (ExifMnoteDataCanon *) ne;\n\tExifShort c;\n\tsize_t i, tcount, o, datao;\n\n\tif (!n || !buf || !buf_size) {\n\t\texif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t \"ExifMnoteCanon\", \"Short MakerNote\");\n\t\treturn;\n\t}\n\tdatao = 6 + n->offset;\n\tif (CHECKOVERFLOW(datao, buf_size, 2)) {\n\t\texif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t \"ExifMnoteCanon\", \"Short MakerNote\");\n\t\treturn;\n\t}\n\n\t/* Read the number of tags */\n\tc = exif_get_short (buf + datao, n->order);\n\tdatao += 2;\n\n\t/* Remove any old entries */\n\texif_mnote_data_canon_clear (n);\n\n\t/* Reserve enough space for all the possible MakerNote tags */\n\tn->entries = exif_mem_alloc (ne->mem, sizeof (MnoteCanonEntry) * c);\n\tif (!n->entries) {\n\t\tEXIF_LOG_NO_MEMORY(ne->log, \"ExifMnoteCanon\", sizeof (MnoteCanonEntry) * c);\n\t\treturn;\n\t}\n\n\t/* Parse the entries */\n\ttcount = 0;\n\tfor (i = c, o = datao; i; --i, o += 12) {\n\t\tsize_t s;\n\n\t\tmemset(&n->entries[tcount], 0, sizeof(MnoteCanonEntry));\n\t\tif (CHECKOVERFLOW(o,buf_size,12)) {\n\t\t\texif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t\t\"ExifMnoteCanon\", \"Short MakerNote\");\n\t\t\tbreak;\n\t\t}\n\n\t\tn->entries[tcount].tag = exif_get_short (buf + o, n->order);\n\t\tn->entries[tcount].format = exif_get_short (buf + o + 2, n->order);\n\t\tn->entries[tcount].components = exif_get_long (buf + o + 4, n->order);\n\t\tn->entries[tcount].order = n->order;\n\n\t\texif_log (ne->log, EXIF_LOG_CODE_DEBUG, \"ExifMnoteCanon\",\n\t\t\t\"Loading entry 0x%x ('%s')...\", n->entries[tcount].tag,\n\t\t\t mnote_canon_tag_get_name (n->entries[tcount].tag));\n\n\t\t/* Check if we overflow the multiplication. Use buf_size as the max size for integer overflow detection,\n\t\t * we will check the buffer sizes closer later. */\n\t\tif (\texif_format_get_size (n->entries[tcount].format) &&\n\t\t\tbuf_size / exif_format_get_size (n->entries[tcount].format) < n->entries[tcount].components\n\t\t) {\n\t\t\texif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t\t \"ExifMnoteCanon\", \"Tag size overflow detected (%u * %lu)\", exif_format_get_size (n->entries[tcount].format), n->entries[tcount].components);\n\t\t\tcontinue;\n\t\t}\n\n\t\t/*\n\t\t * Size? If bigger than 4 bytes, the actual data is not\n\t\t * in the entry but somewhere else (offset).\n\t\t */\n\t\ts = exif_format_get_size (n->entries[tcount].format) * \n\t\t\t\t\t\t\t\t n->entries[tcount].components;\n\t\tn->entries[tcount].size = s;\n\t\tif (!s) {\n\t\t\texif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t\t \"ExifMnoteCanon\",\n\t\t\t\t \"Invalid zero-length tag size\");\n\t\t\tcontinue;\n\n\t\t} else {\n\t\t\tsize_t dataofs = o + 8;\n\t\t\tif (s > 4) dataofs = exif_get_long (buf + dataofs, n->order) + 6;\n\n\t\t\tif (CHECKOVERFLOW(dataofs, buf_size, s)) {\n\t\t\t\texif_log (ne->log, EXIF_LOG_CODE_DEBUG,\n\t\t\t\t\t\"ExifMnoteCanon\",\n\t\t\t\t\t\"Tag data past end of buffer (%u > %u)\",\n\t\t\t\t\t(unsigned)(dataofs + s), buf_size);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tn->entries[tcount].data = exif_mem_alloc (ne->mem, s);\n\t\t\tif (!n->entries[tcount].data) {\n\t\t\t\tEXIF_LOG_NO_MEMORY(ne->log, \"ExifMnoteCanon\", s);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tmemcpy (n->entries[tcount].data, buf + dataofs, s);\n\t\t}\n\n\t\t/* Tag was successfully parsed */\n\t\t++tcount;\n\t}\n\t/* Store the count of successfully parsed tags */\n\tn->count = tcount;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-703', 'CWE-770'], 'message': 'Add a failsafe on the maximum number of Canon MakerNote subtags.\n\nA malicious file could be crafted to cause extremely large values in some\ntags without tripping any buffer range checks. This is bad with the libexif\nrepresentation of Canon MakerNotes because some arrays are turned into\nindividual tags that the application must loop around.\n\nThe largest value I've seen for failsafe_size in a (very small) sample of valid\nCanon files is <5000. The limit is set two orders of magnitude larger to avoid\ntripping up falsely in case some models use much larger values.\n\nPatch from Google.\n\nCVE-2020-13114'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: main (int argc,\n char *argv[])\n{\n int ret;\n\n g_test_init (&argc, &argv, NULL);\n g_test_bug_base (\"http://bugzilla.gnome.org/\");\n\n g_setenv (\"GSETTINGS_BACKEND\", \"memory\", TRUE);\n g_setenv (\"GIO_USE_TLS\", BACKEND, TRUE);\n\n g_assert_true (g_ascii_strcasecmp (G_OBJECT_TYPE_NAME (g_tls_backend_get_default ()), \"GTlsBackend\" BACKEND) == 0);\n\n g_test_add (\"/tls/\" BACKEND \"/connection/basic\", TestConnection, NULL,\n setup_connection, test_basic_connection, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/verified\", TestConnection, NULL,\n setup_connection, test_verified_connection, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/verified-chain\", TestConnection, NULL,\n setup_connection, test_verified_chain, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/verified-chain-with-redundant-root-cert\", TestConnection, NULL,\n setup_connection, test_verified_chain_with_redundant_root_cert, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/verified-chain-with-duplicate-server-cert\", TestConnection, NULL,\n setup_connection, test_verified_chain_with_duplicate_server_cert, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/verified-unordered-chain\", TestConnection, NULL,\n setup_connection, test_verified_unordered_chain, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/verified-chain-with-alternative-ca-cert\", TestConnection, NULL,\n setup_connection, test_verified_chain_with_alternative_ca_cert, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/invalid-chain-with-alternative-ca-cert\", TestConnection, NULL,\n setup_connection, test_invalid_chain_with_alternative_ca_cert, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/client-auth\", TestConnection, NULL,\n setup_connection, test_client_auth_connection, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/client-auth-rehandshake\", TestConnection, NULL,\n setup_connection, test_client_auth_rehandshake, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/client-auth-failure\", TestConnection, NULL,\n setup_connection, test_client_auth_failure, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/client-auth-fail-missing-client-private-key\", TestConnection, NULL,\n setup_connection, test_client_auth_fail_missing_client_private_key, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/client-auth-request-cert\", TestConnection, NULL,\n setup_connection, test_client_auth_request_cert, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/client-auth-request-fail\", TestConnection, NULL,\n setup_connection, test_client_auth_request_fail, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/client-auth-request-none\", TestConnection, NULL,\n setup_connection, test_client_auth_request_none, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/no-database\", TestConnection, NULL,\n setup_connection, test_connection_no_database, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/failed\", TestConnection, NULL,\n setup_connection, test_failed_connection, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/socket-client\", TestConnection, NULL,\n setup_connection, test_connection_socket_client, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/socket-client-failed\", TestConnection, NULL,\n setup_connection, test_connection_socket_client_failed, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/read-time-out-then-write\", TestConnection, NULL,\n setup_connection, test_connection_read_time_out_write, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/simultaneous-async\", TestConnection, NULL,\n setup_connection, test_simultaneous_async, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/simultaneous-sync\", TestConnection, NULL,\n setup_connection, test_simultaneous_sync, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/simultaneous-async-rehandshake\", TestConnection, NULL,\n setup_connection, test_simultaneous_async_rehandshake, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/simultaneous-sync-rehandshake\", TestConnection, NULL,\n setup_connection, test_simultaneous_sync_rehandshake, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/close-immediately\", TestConnection, NULL,\n setup_connection, test_close_immediately, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/unclean-close-by-server\", TestConnection, NULL,\n setup_connection, test_unclean_close_by_server, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/async-implicit-handshake\", TestConnection, NULL,\n setup_connection, test_async_implicit_handshake, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/output-stream-close\", TestConnection, NULL,\n setup_connection, test_output_stream_close, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/fallback\", TestConnection, NULL,\n setup_connection, test_fallback, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/garbage-database\", TestConnection, NULL,\n setup_connection, test_garbage_database, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/readwrite-after-connection-destroyed\", TestConnection, NULL,\n setup_connection, test_readwrite_after_connection_destroyed, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/alpn/match\", TestConnection, NULL,\n setup_connection, test_alpn_match, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/alpn/no-match\", TestConnection, NULL,\n setup_connection, test_alpn_no_match, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/alpn/client-only\", TestConnection, NULL,\n setup_connection, test_alpn_client_only, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/alpn/server-only\", TestConnection, NULL,\n setup_connection, test_alpn_server_only, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/sync-op-during-handshake\", TestConnection, NULL,\n setup_connection, test_sync_op_during_handshake, teardown_connection);\n g_test_add (\"/tls/\" BACKEND \"/connection/socket-timeout\", TestConnection, NULL,\n setup_connection, test_socket_timeout, teardown_connection);\n\n ret = g_test_run ();\n\n /* for valgrinding */\n g_main_context_unref (g_main_context_default ());\n\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-295'], 'message': 'Return bad identity error if identity is unset\n\nWhen the server-identity property of GTlsClientConnection is unset, the\ndocumentation sasy we need to fail the certificate verification with\nG_TLS_CERTIFICATE_BAD_IDENTITY. This is important because otherwise,\nit's easy for applications to fail to specify server identity.\n\nUnfortunately, we did not correctly implement the intended, documented\nbehavior. When server identity is missing, we check the validity of the\nTLS certificate, but do not check if it corresponds to the expected\nserver (since we have no expected server). Then we assume the identity\nis good, instead of returning bad identity, as documented. This means,\nfor example, that evil.com can present a valid certificate issued to\nevil.com, and we would happily accept it for paypal.com.\n\nFixes #135'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: f_setbufvar(typval_T *argvars, typval_T *rettv UNUSED)\n{\n buf_T\t*buf;\n char_u\t*varname, *bufvarname;\n typval_T\t*varp;\n char_u\tnbuf[NUMBUFLEN];\n\n if (check_restricted() || check_secure())\n\treturn;\n (void)tv_get_number(&argvars[0]);\t /* issue errmsg if type error */\n varname = tv_get_string_chk(&argvars[1]);\n buf = tv_get_buf(&argvars[0], FALSE);\n varp = &argvars[2];\n\n if (buf != NULL && varname != NULL && varp != NULL)\n {\n\tif (*varname == '&')\n\t{\n\t long\tnumval;\n\t char_u\t*strval;\n\t int\t\terror = FALSE;\n\t aco_save_T\taco;\n\n\t /* set curbuf to be our buf, temporarily */\n\t aucmd_prepbuf(&aco, buf);\n\n\t ++varname;\n\t numval = (long)tv_get_number_chk(varp, &error);\n\t strval = tv_get_string_buf_chk(varp, nbuf);\n\t if (!error && strval != NULL)\n\t\tset_option_value(varname, numval, strval, OPT_LOCAL);\n\n\t /* reset notion of buffer */\n\t aucmd_restbuf(&aco);\n\t}\n\telse\n\t{\n\t buf_T *save_curbuf = curbuf;\n\n\t bufvarname = alloc((unsigned)STRLEN(varname) + 3);\n\t if (bufvarname != NULL)\n\t {\n\t\tcurbuf = buf;\n\t\tSTRCPY(bufvarname, \"b:\");\n\t\tSTRCPY(bufvarname + 2, varname);\n\t\tset_var(bufvarname, varp, TRUE);\n\t\tvim_free(bufvarname);\n\t\tcurbuf = save_curbuf;\n\t }\n\t}\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-78'], 'message': 'patch 8.1.0881: can execute shell commands in rvim through interfaces\n\nProblem: Can execute shell commands in rvim through interfaces.\nSolution: Disable using interfaces in restricted mode. Allow for writing\n file with writefile(), histadd() and a few others.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void nego_process_negotiation_response(rdpNego* nego, wStream* s)\n{\n\tUINT16 length;\n\tWLog_DBG(TAG, \"RDP_NEG_RSP\");\n\n\tif (Stream_GetRemainingLength(s) < 7)\n\t{\n\t\tWLog_ERR(TAG, \"Invalid RDP_NEG_RSP\");\n\t\tnego->state = NEGO_STATE_FAIL;\n\t\treturn;\n\t}\n\n\tStream_Read_UINT8(s, nego->flags);\n\tStream_Read_UINT16(s, length);\n\tStream_Read_UINT32(s, nego->SelectedProtocol);\n\tnego->state = NEGO_STATE_FINAL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed oob read in irp_write and similar'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static UINT parallel_process_irp_create(PARALLEL_DEVICE* parallel, IRP* irp)\n{\n\tchar* path = NULL;\n\tint status;\n\tUINT32 PathLength;\n\tStream_Seek(irp->input, 28);\n\t/* DesiredAccess(4) AllocationSize(8), FileAttributes(4) */\n\t/* SharedAccess(4) CreateDisposition(4), CreateOptions(4) */\n\tStream_Read_UINT32(irp->input, PathLength);\n\tstatus = ConvertFromUnicode(CP_UTF8, 0, (WCHAR*)Stream_Pointer(irp->input), PathLength / 2,\n\t &path, 0, NULL, NULL);\n\n\tif (status < 1)\n\t\tif (!(path = (char*)calloc(1, 1)))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}\n\n\tparallel->id = irp->devman->id_sequence++;\n\tparallel->file = open(parallel->path, O_RDWR);\n\n\tif (parallel->file < 0)\n\t{\n\t\tirp->IoStatus = STATUS_ACCESS_DENIED;\n\t\tparallel->id = 0;\n\t}\n\telse\n\t{\n\t\t/* all read and write operations should be non-blocking */\n\t\tif (fcntl(parallel->file, F_SETFL, O_NONBLOCK) == -1)\n\t\t{\n\t\t}\n\t}\n\n\tStream_Write_UINT32(irp->output, parallel->id);\n\tStream_Write_UINT8(irp->output, 0);\n\tfree(path);\n\treturn irp->Complete(irp);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415', 'CWE-125'], 'message': 'Fixed oob read in parallel_process_irp_create'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: virtual void initialize() {\n http2OptionsFromTuple(client_http2_options_, client_settings_);\n http2OptionsFromTuple(server_http2_options_, server_settings_);\n client_ = std::make_unique(\n client_connection_, client_callbacks_, stats_store_, client_http2_options_,\n max_request_headers_kb_, max_response_headers_count_, ProdNghttp2SessionFactory::get());\n server_ = std::make_unique(\n server_connection_, server_callbacks_, stats_store_, server_http2_options_,\n max_request_headers_kb_, max_request_headers_count_, headers_with_underscores_action_);\n\n request_encoder_ = &client_->newStream(response_decoder_);\n setupDefaultConnectionMocks();\n\n EXPECT_CALL(server_callbacks_, newStream(_, _))\n .WillRepeatedly(Invoke([&](ResponseEncoder& encoder, bool) -> RequestDecoder& {\n response_encoder_ = &encoder;\n encoder.getStream().addCallbacks(server_stream_callbacks_);\n return request_decoder_;\n }));\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139)\n\nThis commit adds a new stream flush timeout to guard against a\nremote server that does not open window once an entire stream has\nbeen buffered for flushing. Additional stats have also been added\nto better understand the codecs view of active streams as well as\namount of data buffered.\n\nSigned-off-by: Matt Klein '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TEST_P(Http2CodecImplTest, PingFlood) {\n initialize();\n\n TestRequestHeaderMapImpl request_headers;\n HttpTestUtility::addDefaultHeaders(request_headers);\n EXPECT_CALL(request_decoder_, decodeHeaders_(_, false));\n request_encoder_->encodeHeaders(request_headers, false);\n\n // Send one frame above the outbound control queue size limit\n for (uint32_t i = 0; i < CommonUtility::OptionsLimits::DEFAULT_MAX_OUTBOUND_CONTROL_FRAMES + 1;\n ++i) {\n EXPECT_EQ(0, nghttp2_submit_ping(client_->session(), NGHTTP2_FLAG_NONE, nullptr));\n }\n\n int ack_count = 0;\n Buffer::OwnedImpl buffer;\n ON_CALL(server_connection_, write(_, _))\n .WillByDefault(Invoke([&buffer, &ack_count](Buffer::Instance& frame, bool) {\n ++ack_count;\n buffer.move(frame);\n }));\n\n EXPECT_THROW(client_->sendPendingFrames(), ServerCodecError);\n EXPECT_EQ(ack_count, CommonUtility::OptionsLimits::DEFAULT_MAX_OUTBOUND_CONTROL_FRAMES);\n EXPECT_EQ(1, stats_store_.counter(\"http2.outbound_control_flood\").value());\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139)\n\nThis commit adds a new stream flush timeout to guard against a\nremote server that does not open window once an entire stream has\nbeen buffered for flushing. Additional stats have also been added\nto better understand the codecs view of active streams as well as\namount of data buffered.\n\nSigned-off-by: Matt Klein '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TEST_P(Http2CodecImplTest, InvalidContinueWithFinAllowed) {\n stream_error_on_invalid_http_messaging_ = true;\n initialize();\n\n MockStreamCallbacks request_callbacks;\n request_encoder_->getStream().addCallbacks(request_callbacks);\n\n TestRequestHeaderMapImpl request_headers;\n HttpTestUtility::addDefaultHeaders(request_headers);\n EXPECT_CALL(request_decoder_, decodeHeaders_(_, true));\n request_encoder_->encodeHeaders(request_headers, true);\n\n // Buffer client data to avoid mock recursion causing lifetime issues.\n ON_CALL(server_connection_, write(_, _))\n .WillByDefault(\n Invoke([&](Buffer::Instance& data, bool) -> void { client_wrapper_.buffer_.add(data); }));\n\n TestResponseHeaderMapImpl continue_headers{{\":status\", \"100\"}};\n response_encoder_->encodeHeaders(continue_headers, true);\n\n // Flush pending data.\n EXPECT_CALL(request_callbacks, onResetStream(StreamResetReason::LocalReset, _));\n setupDefaultConnectionMocks();\n auto status = client_wrapper_.dispatch(Buffer::OwnedImpl(), *client_);\n EXPECT_TRUE(status.ok());\n\n EXPECT_EQ(1, stats_store_.counter(\"http2.rx_messaging_error\").value());\n expectDetailsRequest(\"http2.violation.of.messaging.rule\");\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139)\n\nThis commit adds a new stream flush timeout to guard against a\nremote server that does not open window once an entire stream has\nbeen buffered for flushing. Additional stats have also been added\nto better understand the codecs view of active streams as well as\namount of data buffered.\n\nSigned-off-by: Matt Klein '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TEST_P(Http2CodecImplTest, InvalidHeadersFrame) {\n initialize();\n\n EXPECT_THROW(request_encoder_->encodeHeaders(TestRequestHeaderMapImpl{}, true), ServerCodecError);\n EXPECT_EQ(1, stats_store_.counter(\"http2.rx_messaging_error\").value());\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139)\n\nThis commit adds a new stream flush timeout to guard against a\nremote server that does not open window once an entire stream has\nbeen buffered for flushing. Additional stats have also been added\nto better understand the codecs view of active streams as well as\namount of data buffered.\n\nSigned-off-by: Matt Klein '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void maybeAllocTrailers() override {\n ASSERT(processing_trailers_);\n if (!absl::holds_alternative(headers_or_trailers_)) {\n headers_or_trailers_.emplace(RequestTrailerMapImpl::create());\n }\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-770'], 'message': '[http1] Include request URL in request header size computation, and reject partial headers that exceed configured limits (#145)\n\nSigned-off-by: antonio '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool canCreate() override { return current_ < max(); } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': 'listener: Add configurable accepted connection limits (#153)\n\nAdd support for per-listener limits on accepted connections.\n\nSigned-off-by: Tony Allen '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TEST_F(OwnedImplTest, ReserveZeroCommit) {\n BufferFragmentImpl frag(\"\", 0, nullptr);\n Buffer::OwnedImpl buf;\n buf.addBufferFragment(frag);\n buf.prepend(\"bbbbb\");\n buf.add(\"\");\n constexpr uint32_t reserve_slices = 16;\n Buffer::RawSlice slices[reserve_slices];\n const uint32_t allocated_slices = buf.reserve(1280, slices, reserve_slices);\n for (uint32_t i = 0; i < allocated_slices; ++i) {\n slices[i].len_ = 0;\n }\n buf.commit(slices, allocated_slices);\n os_fd_t pipe_fds[2] = {0, 0};\n auto& os_sys_calls = Api::OsSysCallsSingleton::get();\n#ifdef WIN32\n ASSERT_EQ(os_sys_calls.socketpair(AF_INET, SOCK_STREAM, 0, pipe_fds).rc_, 0);\n#else\n ASSERT_EQ(pipe(pipe_fds), 0);\n#endif\n Network::IoSocketHandleImpl io_handle(pipe_fds[0]);\n ASSERT_EQ(os_sys_calls.setsocketblocking(pipe_fds[0], false).rc_, 0);\n ASSERT_EQ(os_sys_calls.setsocketblocking(pipe_fds[1], false).rc_, 0);\n const uint32_t max_length = 1953;\n std::string data(max_length, 'e');\n const ssize_t rc = os_sys_calls.write(pipe_fds[1], data.data(), max_length).rc_;\n ASSERT_GT(rc, 0);\n const uint32_t previous_length = buf.length();\n Api::IoCallUint64Result result = buf.read(io_handle, max_length);\n ASSERT_EQ(result.rc_, static_cast(rc));\n ASSERT_EQ(os_sys_calls.close(pipe_fds[1]).rc_, 0);\n ASSERT_EQ(previous_length, buf.search(data.data(), rc, previous_length));\n EXPECT_EQ(\"bbbbb\", buf.toString().substr(0, 5));\n expectSlices({{5, 0, 4056}, {1953, 2103, 4056}}, buf);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': '[buffer] Add on-drain hook to buffer API and use it to avoid fragmentation due to tracking of H2 data and control frames in the output buffer (#144)\n\nSigned-off-by: antonio '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void* OwnedImpl::linearize(uint32_t size) {\n RELEASE_ASSERT(size <= length(), \"Linearize size exceeds buffer size\");\n if (slices_.empty()) {\n return nullptr;\n }\n uint64_t linearized_size = 0;\n uint64_t num_slices_to_linearize = 0;\n for (const auto& slice : slices_) {\n num_slices_to_linearize++;\n linearized_size += slice->dataSize();\n if (linearized_size >= size) {\n break;\n }\n }\n if (num_slices_to_linearize > 1) {\n auto new_slice = OwnedSlice::create(linearized_size);\n uint64_t bytes_copied = 0;\n Slice::Reservation reservation = new_slice->reserve(linearized_size);\n ASSERT(reservation.mem_ != nullptr);\n ASSERT(reservation.len_ == linearized_size);\n auto dest = static_cast(reservation.mem_);\n do {\n uint64_t data_size = slices_.front()->dataSize();\n memcpy(dest, slices_.front()->data(), data_size);\n bytes_copied += data_size;\n dest += data_size;\n slices_.pop_front();\n } while (bytes_copied < linearized_size);\n ASSERT(dest == static_cast(reservation.mem_) + linearized_size);\n new_slice->commit(reservation);\n slices_.emplace_front(std::move(new_slice));\n }\n return slices_.front()->data();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': '[buffer] Add on-drain hook to buffer API and use it to avoid fragmentation due to tracking of H2 data and control frames in the output buffer (#144)\n\nSigned-off-by: antonio '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void test_parse_uid(void) {\n int r;\n uid_t uid;\n\n log_info(\"/* %s */\", __func__);\n\n r = parse_uid(\"100\", &uid);\n assert_se(r == 0);\n assert_se(uid == 100);\n\n r = parse_uid(\"65535\", &uid);\n assert_se(r == -ENXIO);\n\n r = parse_uid(\"asdsdas\", &uid);\n assert_se(r == -EINVAL);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-269'], 'message': 'basic/user-util: always use base 10 for user/group numbers\n\nWe would parse numbers with base prefixes as user identifiers. For example,\n\"0x2b3bfa0\" would be interpreted as UID==45334432 and \"01750\" would be\ninterpreted as UID==1000. This parsing was used also in cases where either a\nuser/group name or number may be specified. This means that names like\n0x2b3bfa0 would be ambiguous: they are a valid user name according to our\ndocumented relaxed rules, but they would also be parsed as numeric uids.\n\nThis behaviour is definitely not expected by users, since tools generally only\naccept decimal numbers (e.g. id, getent passwd), while other tools only accept\nuser names and thus will interpret such strings as user names without even\nattempting to convert them to numbers (su, ssh). So let's follow suit and only\naccept numbers in decimal notation. Effectively this means that we will reject\nsuch strings as a username/uid/groupname/gid where strict mode is used, and try\nto look up a user/group with such a name in relaxed mode.\n\nSince the function changed is fairly low-level and fairly widely used, this\naffects multiple tools: loginctl show-user/enable-linger/disable-linger foo',\nthe third argument in sysusers.d, fourth and fifth arguments in tmpfiles.d,\netc.\n\nFixes #15985.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static BOOL clear_decompress_subcode_rlex(wStream* s, UINT32 bitmapDataByteCount, UINT32 width,\n UINT32 height, BYTE* pDstData, UINT32 DstFormat,\n UINT32 nDstStep, UINT32 nXDstRel, UINT32 nYDstRel,\n UINT32 nDstWidth, UINT32 nDstHeight)\n{\n\tUINT32 x = 0, y = 0;\n\tUINT32 i;\n\tUINT32 pixelCount;\n\tUINT32 bitmapDataOffset;\n\tUINT32 pixelIndex;\n\tUINT32 numBits;\n\tBYTE startIndex;\n\tBYTE stopIndex;\n\tBYTE suiteIndex;\n\tBYTE suiteDepth;\n\tBYTE paletteCount;\n\tUINT32 palette[128] = { 0 };\n\n\tif (Stream_GetRemainingLength(s) < bitmapDataByteCount)\n\t{\n\t\tWLog_ERR(TAG, \"stream short %\" PRIuz \" [%\" PRIu32 \" expected]\",\n\t\t Stream_GetRemainingLength(s), bitmapDataByteCount);\n\t\treturn FALSE;\n\t}\n\n\tStream_Read_UINT8(s, paletteCount);\n\tbitmapDataOffset = 1 + (paletteCount * 3);\n\n\tif ((paletteCount > 127) || (paletteCount < 1))\n\t{\n\t\tWLog_ERR(TAG, \"paletteCount %\" PRIu8 \"\", paletteCount);\n\t\treturn FALSE;\n\t}\n\n\tfor (i = 0; i < paletteCount; i++)\n\t{\n\t\tBYTE r, g, b;\n\t\tStream_Read_UINT8(s, b);\n\t\tStream_Read_UINT8(s, g);\n\t\tStream_Read_UINT8(s, r);\n\t\tpalette[i] = FreeRDPGetColor(DstFormat, r, g, b, 0xFF);\n\t}\n\n\tpixelIndex = 0;\n\tpixelCount = width * height;\n\tnumBits = CLEAR_LOG2_FLOOR[paletteCount - 1] + 1;\n\n\twhile (bitmapDataOffset < bitmapDataByteCount)\n\t{\n\t\tUINT32 tmp;\n\t\tUINT32 color;\n\t\tUINT32 runLengthFactor;\n\n\t\tif (Stream_GetRemainingLength(s) < 2)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"stream short %\" PRIuz \" [2 expected]\", Stream_GetRemainingLength(s));\n\t\t\treturn FALSE;\n\t\t}\n\n\t\tStream_Read_UINT8(s, tmp);\n\t\tStream_Read_UINT8(s, runLengthFactor);\n\t\tbitmapDataOffset += 2;\n\t\tsuiteDepth = (tmp >> numBits) & CLEAR_8BIT_MASKS[(8 - numBits)];\n\t\tstopIndex = tmp & CLEAR_8BIT_MASKS[numBits];\n\t\tstartIndex = stopIndex - suiteDepth;\n\n\t\tif (runLengthFactor >= 0xFF)\n\t\t{\n\t\t\tif (Stream_GetRemainingLength(s) < 2)\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"stream short %\" PRIuz \" [2 expected]\", Stream_GetRemainingLength(s));\n\t\t\t\treturn FALSE;\n\t\t\t}\n\n\t\t\tStream_Read_UINT16(s, runLengthFactor);\n\t\t\tbitmapDataOffset += 2;\n\n\t\t\tif (runLengthFactor >= 0xFFFF)\n\t\t\t{\n\t\t\t\tif (Stream_GetRemainingLength(s) < 4)\n\t\t\t\t{\n\t\t\t\t\tWLog_ERR(TAG, \"stream short %\" PRIuz \" [4 expected]\",\n\t\t\t\t\t Stream_GetRemainingLength(s));\n\t\t\t\t\treturn FALSE;\n\t\t\t\t}\n\n\t\t\t\tStream_Read_UINT32(s, runLengthFactor);\n\t\t\t\tbitmapDataOffset += 4;\n\t\t\t}\n\t\t}\n\n\t\tif (startIndex >= paletteCount)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"startIndex %\" PRIu8 \" > paletteCount %\" PRIu8 \"]\", startIndex,\n\t\t\t paletteCount);\n\t\t\treturn FALSE;\n\t\t}\n\n\t\tif (stopIndex >= paletteCount)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"stopIndex %\" PRIu8 \" > paletteCount %\" PRIu8 \"]\", stopIndex,\n\t\t\t paletteCount);\n\t\t\treturn FALSE;\n\t\t}\n\n\t\tsuiteIndex = startIndex;\n\n\t\tif (suiteIndex > 127)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"suiteIndex %\" PRIu8 \" > 127]\", suiteIndex);\n\t\t\treturn FALSE;\n\t\t}\n\n\t\tcolor = palette[suiteIndex];\n\n\t\tif ((pixelIndex + runLengthFactor) > pixelCount)\n\t\t{\n\t\t\tWLog_ERR(TAG,\n\t\t\t \"pixelIndex %\" PRIu32 \" + runLengthFactor %\" PRIu32 \" > pixelCount %\" PRIu32\n\t\t\t \"\",\n\t\t\t pixelIndex, runLengthFactor, pixelCount);\n\t\t\treturn FALSE;\n\t\t}\n\n\t\tfor (i = 0; i < runLengthFactor; i++)\n\t\t{\n\t\t\tBYTE* pTmpData =\n\t\t\t &pDstData[(nXDstRel + x) * GetBytesPerPixel(DstFormat) + (nYDstRel + y) * nDstStep];\n\n\t\t\tif ((nXDstRel + x < nDstWidth) && (nYDstRel + y < nDstHeight))\n\t\t\t\tWriteColor(pTmpData, DstFormat, color);\n\n\t\t\tif (++x >= width)\n\t\t\t{\n\t\t\t\ty++;\n\t\t\t\tx = 0;\n\t\t\t}\n\t\t}\n\n\t\tpixelIndex += runLengthFactor;\n\n\t\tif ((pixelIndex + (suiteDepth + 1)) > pixelCount)\n\t\t{\n\t\t\tWLog_ERR(TAG,\n\t\t\t \"pixelIndex %\" PRIu32 \" + suiteDepth %\" PRIu8 \" + 1 > pixelCount %\" PRIu32 \"\",\n\t\t\t pixelIndex, suiteDepth, pixelCount);\n\t\t\treturn FALSE;\n\t\t}\n\n\t\tfor (i = 0; i <= suiteDepth; i++)\n\t\t{\n\t\t\tBYTE* pTmpData =\n\t\t\t &pDstData[(nXDstRel + x) * GetBytesPerPixel(DstFormat) + (nYDstRel + y) * nDstStep];\n\t\t\tUINT32 color = palette[suiteIndex];\n\n\t\t\tif (suiteIndex > 127)\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"suiteIndex %\" PRIu8 \" > 127\", suiteIndex);\n\t\t\t\treturn FALSE;\n\t\t\t}\n\n\t\t\tsuiteIndex++;\n\n\t\t\tif ((nXDstRel + x < nDstWidth) && (nYDstRel + y < nDstHeight))\n\t\t\t\tWriteColor(pTmpData, DstFormat, color);\n\n\t\t\tif (++x >= width)\n\t\t\t{\n\t\t\t\ty++;\n\t\t\t\tx = 0;\n\t\t\t}\n\t\t}\n\n\t\tpixelIndex += (suiteDepth + 1);\n\t}\n\n\tif (pixelIndex != pixelCount)\n\t{\n\t\tWLog_ERR(TAG, \"pixelIndex %\" PRIu32 \" != pixelCount %\" PRIu32 \"\", pixelIndex, pixelCount);\n\t\treturn FALSE;\n\t}\n\n\treturn TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed oob read in clear_decompress_subcode_rlex\n\nFixed length checks before stream read.\nThanks to hac425 CVE-2020-11040'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: Status RoleGraph::getBSONForRole(RoleGraph* graph,\n const RoleName& roleName,\n mutablebson::Element result) try {\n if (!graph->roleExists(roleName)) {\n return Status(ErrorCodes::RoleNotFound,\n mongoutils::str::stream() << roleName.getFullName()\n << \"does not name an existing role\");\n }\n std::string id = mongoutils::str::stream() << roleName.getDB() << \".\" << roleName.getRole();\n uassertStatusOK(result.appendString(\"_id\", id));\n uassertStatusOK(\n result.appendString(AuthorizationManager::ROLE_NAME_FIELD_NAME, roleName.getRole()));\n uassertStatusOK(\n result.appendString(AuthorizationManager::ROLE_DB_FIELD_NAME, roleName.getDB()));\n\n // Build privileges array\n mutablebson::Element privilegesArrayElement =\n result.getDocument().makeElementArray(\"privileges\");\n uassertStatusOK(result.pushBack(privilegesArrayElement));\n const PrivilegeVector& privileges = graph->getDirectPrivileges(roleName);\n uassertStatusOK(Privilege::getBSONForPrivileges(privileges, privilegesArrayElement));\n\n // Build roles array\n mutablebson::Element rolesArrayElement = result.getDocument().makeElementArray(\"roles\");\n uassertStatusOK(result.pushBack(rolesArrayElement));\n for (RoleNameIterator roles = graph->getDirectSubordinates(roleName); roles.more();\n roles.next()) {\n const RoleName& subRole = roles.get();\n mutablebson::Element roleObj = result.getDocument().makeElementObject(\"\");\n uassertStatusOK(\n roleObj.appendString(AuthorizationManager::ROLE_NAME_FIELD_NAME, subRole.getRole()));\n uassertStatusOK(\n roleObj.appendString(AuthorizationManager::ROLE_DB_FIELD_NAME, subRole.getDB()));\n uassertStatusOK(rolesArrayElement.pushBack(roleObj));\n }\n\n return Status::OK();\n} catch (...) { ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-863'], 'message': 'SERVER-45472 Ensure RoleGraph can serialize authentication restrictions to BSON\n\n(cherry picked from commit 521e56b407ac72bc69a97a24d1253f51a5b6e81b)\n(cherry picked from commit a10d0a22d5d009d27664967181042933ec1bef36)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: PackLinuxElf32::invert_pt_dynamic(Elf32_Dyn const *dynp)\n{\n if (dt_table[Elf32_Dyn::DT_NULL]) {\n return; // not 1st time; do not change upx_dt_init\n }\n Elf32_Dyn const *const dynp0 = dynp;\n unsigned ndx = 1+ 0;\n if (dynp)\n for (; ; ++ndx, ++dynp) {\n unsigned const d_tag = get_te32(&dynp->d_tag);\n if (d_tag < DT_NUM) {\n dt_table[d_tag] = ndx;\n }\n if (Elf32_Dyn::DT_NULL == d_tag) {\n break; // check here so that dt_table[DT_NULL] is set\n }\n }\n upx_dt_init = 0;\n if (dt_table[Elf32_Dyn::DT_INIT]) upx_dt_init = Elf32_Dyn::DT_INIT;\n else if (dt_table[Elf32_Dyn::DT_PREINIT_ARRAY]) upx_dt_init = Elf32_Dyn::DT_PREINIT_ARRAY;\n else if (dt_table[Elf32_Dyn::DT_INIT_ARRAY]) upx_dt_init = Elf32_Dyn::DT_INIT_ARRAY;\n\n unsigned const z_str = dt_table[Elf32_Dyn::DT_STRSZ];\n if (z_str) {\n strtab_end = get_te32(&dynp0[-1+ z_str].d_val);\n if ((u32_t)file_size <= strtab_end) { // FIXME: weak\n char msg[50]; snprintf(msg, sizeof(msg),\n \"bad DT_STRSZ %#x\", strtab_end);\n throwCantPack(msg);\n }\n }\n unsigned const x_sym = dt_table[Elf32_Dyn::DT_SYMTAB];\n unsigned const x_str = dt_table[Elf32_Dyn::DT_STRTAB];\n if (x_sym && x_str) {\n upx_uint32_t const v_sym = get_te32(&dynp0[-1+ x_sym].d_val);\n upx_uint32_t const v_str = get_te32(&dynp0[-1+ x_str].d_val);\n unsigned const z_sym = dt_table[Elf32_Dyn::DT_SYMENT];\n unsigned const sz_sym = !z_sym ? sizeof(Elf32_Sym)\n : get_te32(&dynp0[-1+ z_sym].d_val);\n if (v_sym < v_str) {\n symnum_end = (v_str - v_sym) / sz_sym;\n }\n }\n // DT_HASH often ends at DT_SYMTAB\n unsigned const v_hsh = elf_unsigned_dynamic(Elf64_Dyn::DT_HASH);\n if (v_hsh && file_image) {\n hashtab = (unsigned const *)elf_find_dynamic(Elf64_Dyn::DT_HASH);\n unsigned const nbucket = get_te32(&hashtab[0]);\n unsigned const *const buckets = &hashtab[2];\n unsigned const *const chains = &buckets[nbucket]; (void)chains;\n\n unsigned const v_sym = get_te32(&dynp0[-1+ x_sym].d_val);\n if (!nbucket\n || (nbucket>>31) || (file_size/sizeof(unsigned)) <= (2*nbucket) // FIXME: weak\n || ((v_hsh < v_sym) && (v_sym - v_hsh) < (sizeof(unsigned)*2 // headers\n + sizeof(*buckets)*nbucket // buckets\n + sizeof(*chains) *nbucket // chains\n ))\n ) {\n char msg[90]; snprintf(msg, sizeof(msg),\n \"bad DT_HASH nbucket=%#x len=%#x\",\n nbucket, (v_sym - v_hsh));\n throwCantPack(msg);\n }\n }\n // DT_GNU_HASH often ends at DT_SYMTAB; FIXME: not for Android?\n unsigned const v_gsh = elf_unsigned_dynamic(Elf32_Dyn::DT_GNU_HASH);\n if (v_gsh && file_image) {\n gashtab = (unsigned const *)elf_find_dynamic(Elf32_Dyn::DT_GNU_HASH);\n unsigned const n_bucket = get_te32(&gashtab[0]);\n unsigned const n_bitmask = get_te32(&gashtab[2]);\n unsigned const gnu_shift = get_te32(&gashtab[3]);\n unsigned const *const bitmask = (unsigned const *)(void const *)&gashtab[4];\n unsigned const *const buckets = (unsigned const *)&bitmask[n_bitmask];\n unsigned const *const hasharr = &buckets[n_bucket]; (void)hasharr;\n //unsigned const *const gashend = &hasharr[n_bucket]; // minimum\n\n unsigned const v_sym = get_te32(&dynp0[-1+ x_sym].d_val);\n if (!n_bucket || !n_bitmask\n || (-1+ n_bitmask) & n_bitmask // not a power of 2\n || 8*sizeof(unsigned) <= gnu_shift // shifted result always == 0\n || (n_bucket>>30) // fie on fuzzers\n || (n_bitmask>>30)\n || (file_size / sizeof(unsigned)) <= (n_bitmask + 2*n_bucket) // FIXME: weak\n // FIXME: next test does work for Android?\n || ((v_gsh < v_sym) && (v_sym - v_gsh) < (sizeof(unsigned)*4 // headers\n + sizeof(*bitmask)*n_bitmask // bitmask\n + sizeof(*buckets)*n_bucket // buckets\n + sizeof(*hasharr)*n_bucket // hasharr\n ))\n ) {\n char msg[90]; snprintf(msg, sizeof(msg),\n \"bad DT_GNU_HASH n_bucket=%#x n_bitmask=%#x len=%#x\",\n n_bucket, n_bitmask, v_sym - v_gsh);\n throwCantPack(msg);\n }\n }\n unsigned const e_shstrndx = get_te16(&ehdri.e_shstrndx);\n if (e_shnum <= e_shstrndx\n && !(0==e_shnum && 0==e_shstrndx) ) {\n char msg[40]; snprintf(msg, sizeof(msg),\n \"bad .e_shstrndx %d >= .e_shnum %d\", e_shstrndx, e_shnum);\n throwCantPack(msg);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-190'], 'message': 'Avoid bogus values in PT_DYNAMIC segment.\n\nDetect duplicate DT_*.\nDetect out-of-bounds hashtab and gashtab.\nDetect missing DT_REL, DT_RELA.\nDetect out-of-bounds d_val.\nhttps://github.com/upx/upx/issues/317\n\tmodified: p_lx_elf.cpp'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: paged_results_copy_down_controls(TALLOC_CTX *mem_ctx,\n\t\t\t\t struct ldb_control **controls)\n{\n\n\tstruct ldb_control **new_controls;\n\tunsigned int i, j, num_ctrls;\n\tif (controls == NULL) {\n\t\treturn NULL;\n\t}\n\n\tfor (num_ctrls = 0; controls[num_ctrls]; num_ctrls++);\n\n\tnew_controls = talloc_array(mem_ctx, struct ldb_control *, num_ctrls);\n\tif (new_controls == NULL) {\n\t\treturn NULL;\n\t}\n\n\tfor (j = 0, i = 0; i < (num_ctrls); i++) {\n\t\tstruct ldb_control *control = controls[i];\n\t\tif (control->oid == NULL) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (strcmp(control->oid, LDB_CONTROL_PAGED_RESULTS_OID) == 0) {\n\t\t\tcontinue;\n\t\t}\n\t\t/*\n\t\t * ASQ changes everything, do not copy it down for the\n\t\t * per-GUID search\n\t\t */\n\t\tif (strcmp(control->oid, LDB_CONTROL_ASQ_OID) == 0) {\n\t\t\tcontinue;\n\t\t}\n\t\tnew_controls[j] = talloc_steal(new_controls, control);\n\t\tj++;\n\t}\n\tnew_controls[j] = NULL;\n\treturn new_controls;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'CVE-2020-10760 dsdb: Ensure a proper talloc tree for saved controls\n\nOtherwise a paged search on the GC port will fail as the ->data was\nnot kept around for the second page of searches.\n\nAn example command to produce this is\n bin/ldbsearch --paged -H ldap://$SERVER:3268 -U$USERNAME%$PASSWORD\n\nThis shows up later in the partition module as:\n\nERROR: AddressSanitizer: heap-use-after-free on address 0x60b00151ef20 at pc 0x7fec3f801aac bp 0x7ffe8472c270 sp 0x7ffe8472c260\nREAD of size 4 at 0x60b00151ef20 thread T0 (ldap(0))\n #0 0x7fec3f801aab in talloc_chunk_from_ptr ../../lib/talloc/talloc.c:526\n #1 0x7fec3f801aab in __talloc_get_name ../../lib/talloc/talloc.c:1559\n #2 0x7fec3f801aab in talloc_check_name ../../lib/talloc/talloc.c:1582\n #3 0x7fec1b86b2e1 in partition_search ../../source4/dsdb/samdb/ldb_modules/partition.c:780\n\nor\n\nsmb_panic_default: PANIC (pid 13287): Bad talloc magic value - unknown value\n(from source4/dsdb/samdb/ldb_modules/partition.c:780)\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=14402\n\nSigned-off-by: Andrew Bartlett '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int pop_open_connection(struct PopAccountData *adata)\n{\n char buf[1024];\n\n int rc = pop_connect(adata);\n if (rc < 0)\n return rc;\n\n rc = pop_capabilities(adata, 0);\n if (rc == -1)\n goto err_conn;\n if (rc == -2)\n return -2;\n\n#ifdef USE_SSL\n /* Attempt STLS if available and desired. */\n if (!adata->conn->ssf && (adata->cmd_stls || C_SslForceTls))\n {\n if (C_SslForceTls)\n adata->use_stls = 2;\n if (adata->use_stls == 0)\n {\n enum QuadOption ans =\n query_quadoption(C_SslStarttls, _(\"Secure connection with TLS?\"));\n if (ans == MUTT_ABORT)\n return -2;\n adata->use_stls = 1;\n if (ans == MUTT_YES)\n adata->use_stls = 2;\n }\n if (adata->use_stls == 2)\n {\n mutt_str_strfcpy(buf, \"STLS\\r\\n\", sizeof(buf));\n rc = pop_query(adata, buf, sizeof(buf));\n if (rc == -1)\n goto err_conn;\n if (rc != 0)\n {\n mutt_error(\"%s\", adata->err_msg);\n }\n else if (mutt_ssl_starttls(adata->conn))\n {\n mutt_error(_(\"Could not negotiate TLS connection\"));\n return -2;\n }\n else\n {\n /* recheck capabilities after STLS completes */\n rc = pop_capabilities(adata, 1);\n if (rc == -1)\n goto err_conn;\n if (rc == -2)\n return -2;\n }\n }\n }\n\n if (C_SslForceTls && !adata->conn->ssf)\n {\n mutt_error(_(\"Encrypted connection unavailable\"));\n return -2;\n }\n#endif\n\n rc = pop_authenticate(adata);\n if (rc == -1)\n goto err_conn;\n if (rc == -3)\n mutt_clear_error();\n if (rc != 0)\n return rc;\n\n /* recheck capabilities after authentication */\n rc = pop_capabilities(adata, 2);\n if (rc == -1)\n goto err_conn;\n if (rc == -2)\n return -2;\n\n /* get total size of mailbox */\n mutt_str_strfcpy(buf, \"STAT\\r\\n\", sizeof(buf));\n rc = pop_query(adata, buf, sizeof(buf));\n if (rc == -1)\n goto err_conn;\n if (rc == -2)\n {\n mutt_error(\"%s\", adata->err_msg);\n return rc;\n }\n\n unsigned int n = 0, size = 0;\n sscanf(buf, \"+OK %u %u\", &n, &size);\n adata->size = size;\n return 0;\n\nerr_conn:\n adata->status = POP_DISCONNECTED;\n mutt_error(_(\"Server closed connection\"));\n return -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-94', 'CWE-74'], 'message': 'tls: clear data after a starttls acknowledgement\n\nAfter a starttls acknowledgement message, clear the buffers of any\nincoming data / commands. This will ensure that all future data is\nhandled securely.\n\nCo-authored-by: Pietro Cerutti '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void nbt_name_socket_recv(struct nbt_name_socket *nbtsock)\n{\n\tTALLOC_CTX *tmp_ctx = talloc_new(nbtsock);\n\tNTSTATUS status;\n\tenum ndr_err_code ndr_err;\n\tstruct socket_address *src;\n\tDATA_BLOB blob;\n\tsize_t nread, dsize;\n\tstruct nbt_name_packet *packet;\n\tstruct nbt_name_request *req;\n\n\tstatus = socket_pending(nbtsock->sock, &dsize);\n\tif (!NT_STATUS_IS_OK(status)) {\n\t\ttalloc_free(tmp_ctx);\n\t\treturn;\n\t}\n\n\tblob = data_blob_talloc(tmp_ctx, NULL, dsize);\n\tif (blob.data == NULL) {\n\t\ttalloc_free(tmp_ctx);\n\t\treturn;\n\t}\n\n\tstatus = socket_recvfrom(nbtsock->sock, blob.data, blob.length, &nread,\n\t\t\t\t tmp_ctx, &src);\n\tif (!NT_STATUS_IS_OK(status)) {\n\t\ttalloc_free(tmp_ctx);\n\t\treturn;\n\t}\n\n\tpacket = talloc(tmp_ctx, struct nbt_name_packet);\n\tif (packet == NULL) {\n\t\ttalloc_free(tmp_ctx);\n\t\treturn;\n\t}\n\n\t/* parse the request */\n\tndr_err = ndr_pull_struct_blob(&blob, packet, packet,\n\t\t\t\t (ndr_pull_flags_fn_t)ndr_pull_nbt_name_packet);\n\tif (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {\n\t\tstatus = ndr_map_error2ntstatus(ndr_err);\n\t\tDEBUG(2,(\"Failed to parse incoming NBT name packet - %s\\n\",\n\t\t\t nt_errstr(status)));\n\t\ttalloc_free(tmp_ctx);\n\t\treturn;\n\t}\n\n\tif (DEBUGLVL(10)) {\n\t\tDEBUG(10,(\"Received nbt packet of length %d from %s:%d\\n\",\n\t\t\t (int)blob.length, src->addr, src->port));\n\t\tNDR_PRINT_DEBUG(nbt_name_packet, packet);\n\t}\n\n\t/* if its not a reply then pass it off to the incoming request\n\t handler, if any */\n\tif (!(packet->operation & NBT_FLAG_REPLY)) {\n\t\tif (nbtsock->incoming.handler) {\n\t\t\tnbtsock->incoming.handler(nbtsock, packet, src);\n\t\t}\n\t\ttalloc_free(tmp_ctx);\n\t\treturn;\n\t}\n\n\t/* find the matching request */\n\treq = (struct nbt_name_request *)idr_find(nbtsock->idr,\n\t\t\t\t\t\t packet->name_trn_id);\n\tif (req == NULL) {\n\t\tif (nbtsock->unexpected.handler) {\n\t\t\tnbtsock->unexpected.handler(nbtsock, packet, src);\n\t\t} else {\n\t\t\tDEBUG(10,(\"Failed to match request for incoming name packet id 0x%04x on %p\\n\",\n\t\t\t\t packet->name_trn_id, nbtsock));\n\t\t}\n\t\ttalloc_free(tmp_ctx);\n\t\treturn;\n\t}\n\n\ttalloc_steal(req, packet);\n\ttalloc_steal(req, src);\n\ttalloc_free(tmp_ctx);\n\tnbt_name_socket_handle_response_packet(req, packet, src);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-834'], 'message': 'CVE-2020-14303: s4 nbt: fix busy loop on empty UDP packet\n\nAn empty UDP packet put the nbt server into a busy loop that consumes\n100% of a cpu.\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=14417\n\nSigned-off-by: Gary Lockyer \n\nAutobuild-User(master): Karolin Seeger \nAutobuild-Date(master): Thu Jul 2 10:26:24 UTC 2020 on sn-devel-184'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: webSocketsDecodeHybi(rfbClientPtr cl, char *dst, int len)\n{\n char *buf, *payload;\n uint32_t *payload32;\n int ret = -1, result = -1;\n int total = 0;\n ws_mask_t mask;\n ws_header_t *header;\n int i;\n unsigned char opcode;\n ws_ctx_t *wsctx = (ws_ctx_t *)cl->wsctx;\n int flength, fhlen;\n /* int fin; */ /* not used atm */ \n\n /* rfbLog(\" <== %s[%d]: %d cl: %p, wsctx: %p-%p (%d)\\n\", __func__, gettid(), len, cl, wsctx, (char *)wsctx + sizeof(ws_ctx_t), sizeof(ws_ctx_t)); */\n\n if (wsctx->readbuflen) {\n /* simply return what we have */\n if (wsctx->readbuflen > len) {\n\tmemcpy(dst, wsctx->readbuf + wsctx->readbufstart, len);\n\tresult = len;\n\twsctx->readbuflen -= len;\n\twsctx->readbufstart += len;\n } else {\n\tmemcpy(dst, wsctx->readbuf + wsctx->readbufstart, wsctx->readbuflen);\n\tresult = wsctx->readbuflen;\n\twsctx->readbuflen = 0;\n\twsctx->readbufstart = 0;\n }\n goto spor;\n }\n\n buf = wsctx->codeBufDecode;\n header = (ws_header_t *)wsctx->codeBufDecode;\n\n ret = ws_peek(cl, buf, B64LEN(len) + WSHLENMAX);\n\n if (ret < 2) {\n /* save errno because rfbErr() will tamper it */\n if (-1 == ret) {\n int olderrno = errno;\n rfbErr(\"%s: peek; %m\\n\", __func__);\n errno = olderrno;\n } else if (0 == ret) {\n result = 0;\n } else {\n errno = EAGAIN;\n }\n goto spor;\n }\n\n opcode = header->b0 & 0x0f;\n /* fin = (header->b0 & 0x80) >> 7; */ /* not used atm */\n flength = header->b1 & 0x7f;\n\n /*\n * 4.3. Client-to-Server Masking\n *\n * The client MUST mask all frames sent to the server. A server MUST\n * close the connection upon receiving a frame with the MASK bit set to 0.\n **/\n if (!(header->b1 & 0x80)) {\n\trfbErr(\"%s: got frame without mask\\n\", __func__, ret);\n\terrno = EIO;\n\tgoto spor;\n }\n\n if (flength < 126) {\n\tfhlen = 2;\n\tmask = header->u.m;\n } else if (flength == 126 && 4 <= ret) {\n\tflength = WS_NTOH16(header->u.s16.l16);\n\tfhlen = 4;\n\tmask = header->u.s16.m16;\n } else if (flength == 127 && 10 <= ret) {\n\tflength = WS_NTOH64(header->u.s64.l64);\n\tfhlen = 10;\n\tmask = header->u.s64.m64;\n } else {\n /* Incomplete frame header */\n rfbErr(\"%s: incomplete frame header\\n\", __func__, ret);\n errno = EIO;\n goto spor;\n }\n\n /* absolute length of frame */\n total = fhlen + flength + 4;\n payload = buf + fhlen + 4; /* header length + mask */\n\n if (-1 == (ret = ws_read(cl, buf, total))) {\n int olderrno = errno;\n rfbErr(\"%s: read; %m\", __func__);\n errno = olderrno;\n return ret;\n } else if (ret < total) {\n /* GT TODO: hmm? */\n rfbLog(\"%s: read; got partial data\\n\", __func__);\n } else {\n buf[ret] = '\\0';\n }\n\n /* process 1 frame (32 bit op) */\n payload32 = (uint32_t *)payload;\n for (i = 0; i < flength / 4; i++) {\n\tpayload32[i] ^= mask.u;\n }\n /* process the remaining bytes (if any) */\n for (i*=4; i < flength; i++) {\n\tpayload[i] ^= mask.c[i % 4];\n }\n\n switch (opcode) {\n case WS_OPCODE_CLOSE:\n\trfbLog(\"got closure, reason %d\\n\", WS_NTOH16(((uint16_t *)payload)[0]));\n\terrno = ECONNRESET;\n\tbreak;\n case WS_OPCODE_TEXT_FRAME:\n\tif (-1 == (flength = b64_pton(payload, (unsigned char *)wsctx->codeBufDecode, sizeof(wsctx->codeBufDecode)))) {\n\t rfbErr(\"%s: Base64 decode error; %m\\n\", __func__);\n\t break;\n\t}\n\tpayload = wsctx->codeBufDecode;\n\t/* fall through */\n case WS_OPCODE_BINARY_FRAME:\n\tif (flength > len) {\n\t memcpy(wsctx->readbuf, payload + len, flength - len);\n\t wsctx->readbufstart = 0;\n\t wsctx->readbuflen = flength - len;\n\t flength = len;\n\t}\n\tmemcpy(dst, payload, flength);\n\tresult = flength;\n\tbreak;\n default:\n\trfbErr(\"%s: unhandled opcode %d, b0: %02x, b1: %02x\\n\", __func__, (int)opcode, header->b0, header->b1);\n }\n\n /* single point of return, if someone has questions :-) */\nspor:\n /* rfbLog(\"%s: ret: %d/%d\\n\", __func__, result, len); */\n return result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'fix overflow and refactor websockets decode (Hybi)\n\nfix critical heap-based buffer overflow which allowed easy modification\nof a return address via an overwritten function pointer\n\nfix bug causing connections to fail due a \"one websocket frame = one\nws_read\" assumption, which failed with LibVNCServer-0.9.11\n\nrefactor websocket Hybi decode to use a simple state machine for\ndecoding of websocket frames'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static struct ext4_dir_entry_2 *do_split(handle_t *handle, struct inode *dir,\n\t\t\tstruct buffer_head **bh,struct dx_frame *frame,\n\t\t\tstruct dx_hash_info *hinfo)\n{\n\tunsigned blocksize = dir->i_sb->s_blocksize;\n\tunsigned count, continued;\n\tstruct buffer_head *bh2;\n\text4_lblk_t newblock;\n\tu32 hash2;\n\tstruct dx_map_entry *map;\n\tchar *data1 = (*bh)->b_data, *data2;\n\tunsigned split, move, size;\n\tstruct ext4_dir_entry_2 *de = NULL, *de2;\n\tint\tcsum_size = 0;\n\tint\terr = 0, i;\n\n\tif (ext4_has_metadata_csum(dir->i_sb))\n\t\tcsum_size = sizeof(struct ext4_dir_entry_tail);\n\n\tbh2 = ext4_append(handle, dir, &newblock);\n\tif (IS_ERR(bh2)) {\n\t\tbrelse(*bh);\n\t\t*bh = NULL;\n\t\treturn (struct ext4_dir_entry_2 *) bh2;\n\t}\n\n\tBUFFER_TRACE(*bh, \"get_write_access\");\n\terr = ext4_journal_get_write_access(handle, *bh);\n\tif (err)\n\t\tgoto journal_error;\n\n\tBUFFER_TRACE(frame->bh, \"get_write_access\");\n\terr = ext4_journal_get_write_access(handle, frame->bh);\n\tif (err)\n\t\tgoto journal_error;\n\n\tdata2 = bh2->b_data;\n\n\t/* create map in the end of data2 block */\n\tmap = (struct dx_map_entry *) (data2 + blocksize);\n\tcount = dx_make_map(dir, (struct ext4_dir_entry_2 *) data1,\n\t\t\t blocksize, hinfo, map);\n\tmap -= count;\n\tdx_sort_map(map, count);\n\t/* Split the existing block in the middle, size-wise */\n\tsize = 0;\n\tmove = 0;\n\tfor (i = count-1; i >= 0; i--) {\n\t\t/* is more than half of this entry in 2nd half of the block? */\n\t\tif (size + map[i].size/2 > blocksize/2)\n\t\t\tbreak;\n\t\tsize += map[i].size;\n\t\tmove++;\n\t}\n\t/* map index at which we will split */\n\tsplit = count - move;\n\thash2 = map[split].hash;\n\tcontinued = hash2 == map[split - 1].hash;\n\tdxtrace(printk(KERN_INFO \"Split block %lu at %x, %i/%i\\n\",\n\t\t\t(unsigned long)dx_get_block(frame->at),\n\t\t\t\t\thash2, split, count-split));\n\n\t/* Fancy dance to stay within two buffers */\n\tde2 = dx_move_dirents(data1, data2, map + split, count - split,\n\t\t\t blocksize);\n\tde = dx_pack_dirents(data1, blocksize);\n\tde->rec_len = ext4_rec_len_to_disk(data1 + (blocksize - csum_size) -\n\t\t\t\t\t (char *) de,\n\t\t\t\t\t blocksize);\n\tde2->rec_len = ext4_rec_len_to_disk(data2 + (blocksize - csum_size) -\n\t\t\t\t\t (char *) de2,\n\t\t\t\t\t blocksize);\n\tif (csum_size) {\n\t\text4_initialize_dirent_tail(*bh, blocksize);\n\t\text4_initialize_dirent_tail(bh2, blocksize);\n\t}\n\n\tdxtrace(dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *) data1,\n\t\t\tblocksize, 1));\n\tdxtrace(dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *) data2,\n\t\t\tblocksize, 1));\n\n\t/* Which block gets the new entry? */\n\tif (hinfo->hash >= hash2) {\n\t\tswap(*bh, bh2);\n\t\tde = de2;\n\t}\n\tdx_insert_block(frame, hash2 + continued, newblock);\n\terr = ext4_handle_dirty_dirblock(handle, dir, bh2);\n\tif (err)\n\t\tgoto journal_error;\n\terr = ext4_handle_dirty_dx_node(handle, dir, frame->bh);\n\tif (err)\n\t\tgoto journal_error;\n\tbrelse(bh2);\n\tdxtrace(dx_show_index(\"frame\", frame->entries));\n\treturn de;\n\njournal_error:\n\tbrelse(*bh);\n\tbrelse(bh2);\n\t*bh = NULL;\n\text4_std_error(dir->i_sb, err);\n\treturn ERR_PTR(err);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'ext4: fix potential negative array index in do_split()\n\nIf for any reason a directory passed to do_split() does not have enough\nactive entries to exceed half the size of the block, we can end up\niterating over all \"count\" entries without finding a split point.\n\nIn this case, count == move, and split will be zero, and we will\nattempt a negative index into map[].\n\nGuard against this by detecting this case, and falling back to\nsplit-to-half-of-count instead; in this case we will still have\nplenty of space (> half blocksize) in each split block.\n\nFixes: ef2b02d3e617 (\"ext34: ensure do_split leaves enough free space in both blocks\")\nSigned-off-by: Eric Sandeen \nReviewed-by: Andreas Dilger \nReviewed-by: Jan Kara \nLink: https://lore.kernel.org/r/f53e246b-647c-64bb-16ec-135383c70ad7@redhat.com\nSigned-off-by: Theodore Ts'o '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: BOOL update_write_cache_bitmap_v2_order(wStream* s, CACHE_BITMAP_V2_ORDER* cache_bitmap_v2,\n BOOL compressed, UINT16* flags)\n{\n\tBYTE bitsPerPixelId;\n\n\tif (!Stream_EnsureRemainingCapacity(\n\t s, update_approximate_cache_bitmap_v2_order(cache_bitmap_v2, compressed, flags)))\n\t\treturn FALSE;\n\n\tbitsPerPixelId = BPP_CBR2[cache_bitmap_v2->bitmapBpp];\n\t*flags = (cache_bitmap_v2->cacheId & 0x0003) | (bitsPerPixelId << 3) |\n\t ((cache_bitmap_v2->flags << 7) & 0xFF80);\n\n\tif (cache_bitmap_v2->flags & CBR2_PERSISTENT_KEY_PRESENT)\n\t{\n\t\tStream_Write_UINT32(s, cache_bitmap_v2->key1); /* key1 (4 bytes) */\n\t\tStream_Write_UINT32(s, cache_bitmap_v2->key2); /* key2 (4 bytes) */\n\t}\n\n\tif (cache_bitmap_v2->flags & CBR2_HEIGHT_SAME_AS_WIDTH)\n\t{\n\t\tif (!update_write_2byte_unsigned(s, cache_bitmap_v2->bitmapWidth)) /* bitmapWidth */\n\t\t\treturn FALSE;\n\t}\n\telse\n\t{\n\t\tif (!update_write_2byte_unsigned(s, cache_bitmap_v2->bitmapWidth) || /* bitmapWidth */\n\t\t !update_write_2byte_unsigned(s, cache_bitmap_v2->bitmapHeight)) /* bitmapHeight */\n\t\t\treturn FALSE;\n\t}\n\n\tif (cache_bitmap_v2->flags & CBR2_DO_NOT_CACHE)\n\t\tcache_bitmap_v2->cacheIndex = BITMAP_CACHE_WAITING_LIST_INDEX;\n\n\tif (!update_write_4byte_unsigned(s, cache_bitmap_v2->bitmapLength) || /* bitmapLength */\n\t !update_write_2byte_unsigned(s, cache_bitmap_v2->cacheIndex)) /* cacheIndex */\n\t\treturn FALSE;\n\n\tif (compressed)\n\t{\n\t\tif (!(cache_bitmap_v2->flags & CBR2_NO_BITMAP_COMPRESSION_HDR))\n\t\t{\n\t\t\tStream_Write_UINT16(\n\t\t\t s, cache_bitmap_v2->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */\n\t\t\tStream_Write_UINT16(\n\t\t\t s, cache_bitmap_v2->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */\n\t\t\tStream_Write_UINT16(s, cache_bitmap_v2->cbScanWidth); /* cbScanWidth (2 bytes) */\n\t\t\tStream_Write_UINT16(\n\t\t\t s, cache_bitmap_v2->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */\n\t\t\tcache_bitmap_v2->bitmapLength = cache_bitmap_v2->cbCompMainBodySize;\n\t\t}\n\n\t\tif (!Stream_EnsureRemainingCapacity(s, cache_bitmap_v2->bitmapLength))\n\t\t\treturn FALSE;\n\n\t\tStream_Write(s, cache_bitmap_v2->bitmapDataStream, cache_bitmap_v2->bitmapLength);\n\t}\n\telse\n\t{\n\t\tif (!Stream_EnsureRemainingCapacity(s, cache_bitmap_v2->bitmapLength))\n\t\t\treturn FALSE;\n\n\t\tStream_Write(s, cache_bitmap_v2->bitmapDataStream, cache_bitmap_v2->bitmapLength);\n\t}\n\n\tcache_bitmap_v2->compressed = compressed;\n\treturn TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed OOB read in update_read_cache_bitmap_v3_order\n\nCVE-2020-11096 thanks @antonio-morales for finding this.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TRIO_PUBLIC_STRING void trio_destroy TRIO_ARGS1((string), char* string)\n{\n\tif (string)\n\t{\n\t\tTRIO_FREE(string);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190', 'CWE-125'], 'message': 'Fixed TrioParse and trio_length limts.\n\nCVE-2020-4030 thanks to @antonio-morales for finding this.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static size_t ntlm_av_pair_get_next_offset(NTLM_AV_PAIR* pAvPair)\n{\n\treturn ntlm_av_pair_get_len(pAvPair) + sizeof(NTLM_AV_PAIR);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190', 'CWE-125'], 'message': 'Fixed OOB read in ntlm_av_pair_get\n\nCVE-2020-11097 thanks to @antonio-morales for finding this.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static UINT gdi_CacheToSurface(RdpgfxClientContext* context,\n const RDPGFX_CACHE_TO_SURFACE_PDU* cacheToSurface)\n{\n\tUINT status = ERROR_INTERNAL_ERROR;\n\tUINT16 index;\n\tRDPGFX_POINT16* destPt;\n\tgdiGfxSurface* surface;\n\tgdiGfxCacheEntry* cacheEntry;\n\tRECTANGLE_16 invalidRect;\n\trdpGdi* gdi = (rdpGdi*)context->custom;\n\tEnterCriticalSection(&context->mux);\n\tsurface = (gdiGfxSurface*)context->GetSurfaceData(context, cacheToSurface->surfaceId);\n\tcacheEntry = (gdiGfxCacheEntry*)context->GetCacheSlotData(context, cacheToSurface->cacheSlot);\n\n\tif (!surface || !cacheEntry)\n\t\tgoto fail;\n\n\tfor (index = 0; index < cacheToSurface->destPtsCount; index++)\n\t{\n\t\tdestPt = &cacheToSurface->destPts[index];\n\n\t\tif (!freerdp_image_copy(surface->data, surface->format, surface->scanline, destPt->x,\n\t\t destPt->y, cacheEntry->width, cacheEntry->height, cacheEntry->data,\n\t\t cacheEntry->format, cacheEntry->scanline, 0, 0, NULL,\n\t\t FREERDP_FLIP_NONE))\n\t\t\tgoto fail;\n\n\t\tinvalidRect.left = destPt->x;\n\t\tinvalidRect.top = destPt->y;\n\t\tinvalidRect.right = destPt->x + cacheEntry->width;\n\t\tinvalidRect.bottom = destPt->y + cacheEntry->height;\n\t\tregion16_union_rect(&surface->invalidRegion, &surface->invalidRegion, &invalidRect);\n\t\tstatus = IFCALLRESULT(CHANNEL_RC_OK, context->UpdateSurfaceArea, context,\n\t\t surface->surfaceId, 1, &invalidRect);\n\n\t\tif (status != CHANNEL_RC_OK)\n\t\t\tgoto fail;\n\t}\n\n\tLeaveCriticalSection(&context->mux);\n\n\tif (!gdi->inGfxFrame)\n\t{\n\t\tstatus = CHANNEL_RC_NOT_INITIALIZED;\n\t\tIFCALLRET(context->UpdateSurfaces, status, context);\n\t}\n\telse\n\t\tstatus = CHANNEL_RC_OK;\n\n\treturn status;\nfail:\n\tLeaveCriticalSection(&context->mux);\n\treturn status;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fixed missing input sanitation for GFX surfaces.\n\nThanks to Sunglin and HuanGMz of the Knownsec 404 security team and pangzi of pwnzen'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void luaV_execute (lua_State *L, CallInfo *ci) {\n LClosure *cl;\n TValue *k;\n StkId base;\n const Instruction *pc;\n int trap;\n#if LUA_USE_JUMPTABLE\n#include \"ljumptab.h\"\n#endif\n tailcall:\n trap = L->hookmask;\n cl = clLvalue(s2v(ci->func));\n k = cl->p->k;\n pc = ci->u.l.savedpc;\n if (trap) {\n if (cl->p->is_vararg)\n trap = 0; /* hooks will start after VARARGPREP instruction */\n else if (pc == cl->p->code) /* first instruction (not resuming)? */\n luaD_hookcall(L, ci);\n ci->u.l.trap = 1; /* there may be other hooks */\n }\n base = ci->func + 1;\n /* main loop of interpreter */\n for (;;) {\n Instruction i; /* instruction being executed */\n StkId ra; /* instruction's A register */\n vmfetch();\n lua_assert(base == ci->func + 1);\n lua_assert(base <= L->top && L->top < L->stack + L->stacksize);\n /* invalidate top for instructions not expecting it */\n lua_assert(isIT(i) || (cast_void(L->top = base), 1));\n vmdispatch (GET_OPCODE(i)) {\n vmcase(OP_MOVE) {\n setobjs2s(L, ra, RB(i));\n vmbreak;\n }\n vmcase(OP_LOADI) {\n lua_Integer b = GETARG_sBx(i);\n setivalue(s2v(ra), b);\n vmbreak;\n }\n vmcase(OP_LOADF) {\n int b = GETARG_sBx(i);\n setfltvalue(s2v(ra), cast_num(b));\n vmbreak;\n }\n vmcase(OP_LOADK) {\n TValue *rb = k + GETARG_Bx(i);\n setobj2s(L, ra, rb);\n vmbreak;\n }\n vmcase(OP_LOADKX) {\n TValue *rb;\n rb = k + GETARG_Ax(*pc); pc++;\n setobj2s(L, ra, rb);\n vmbreak;\n }\n vmcase(OP_LOADFALSE) {\n setbfvalue(s2v(ra));\n vmbreak;\n }\n vmcase(OP_LFALSESKIP) {\n setbfvalue(s2v(ra));\n pc++; /* skip next instruction */\n vmbreak;\n }\n vmcase(OP_LOADTRUE) {\n setbtvalue(s2v(ra));\n vmbreak;\n }\n vmcase(OP_LOADNIL) {\n int b = GETARG_B(i);\n do {\n setnilvalue(s2v(ra++));\n } while (b--);\n vmbreak;\n }\n vmcase(OP_GETUPVAL) {\n int b = GETARG_B(i);\n setobj2s(L, ra, cl->upvals[b]->v);\n vmbreak;\n }\n vmcase(OP_SETUPVAL) {\n UpVal *uv = cl->upvals[GETARG_B(i)];\n setobj(L, uv->v, s2v(ra));\n luaC_barrier(L, uv, s2v(ra));\n vmbreak;\n }\n vmcase(OP_GETTABUP) {\n const TValue *slot;\n TValue *upval = cl->upvals[GETARG_B(i)]->v;\n TValue *rc = KC(i);\n TString *key = tsvalue(rc); /* key must be a string */\n if (luaV_fastget(L, upval, key, slot, luaH_getshortstr)) {\n setobj2s(L, ra, slot);\n }\n else\n Protect(luaV_finishget(L, upval, rc, ra, slot));\n vmbreak;\n }\n vmcase(OP_GETTABLE) {\n const TValue *slot;\n TValue *rb = vRB(i);\n TValue *rc = vRC(i);\n lua_Unsigned n;\n if (ttisinteger(rc) /* fast track for integers? */\n ? (cast_void(n = ivalue(rc)), luaV_fastgeti(L, rb, n, slot))\n : luaV_fastget(L, rb, rc, slot, luaH_get)) {\n setobj2s(L, ra, slot);\n }\n else\n Protect(luaV_finishget(L, rb, rc, ra, slot));\n vmbreak;\n }\n vmcase(OP_GETI) {\n const TValue *slot;\n TValue *rb = vRB(i);\n int c = GETARG_C(i);\n if (luaV_fastgeti(L, rb, c, slot)) {\n setobj2s(L, ra, slot);\n }\n else {\n TValue key;\n setivalue(&key, c);\n Protect(luaV_finishget(L, rb, &key, ra, slot));\n }\n vmbreak;\n }\n vmcase(OP_GETFIELD) {\n const TValue *slot;\n TValue *rb = vRB(i);\n TValue *rc = KC(i);\n TString *key = tsvalue(rc); /* key must be a string */\n if (luaV_fastget(L, rb, key, slot, luaH_getshortstr)) {\n setobj2s(L, ra, slot);\n }\n else\n Protect(luaV_finishget(L, rb, rc, ra, slot));\n vmbreak;\n }\n vmcase(OP_SETTABUP) {\n const TValue *slot;\n TValue *upval = cl->upvals[GETARG_A(i)]->v;\n TValue *rb = KB(i);\n TValue *rc = RKC(i);\n TString *key = tsvalue(rb); /* key must be a string */\n if (luaV_fastget(L, upval, key, slot, luaH_getshortstr)) {\n luaV_finishfastset(L, upval, slot, rc);\n }\n else\n Protect(luaV_finishset(L, upval, rb, rc, slot));\n vmbreak;\n }\n vmcase(OP_SETTABLE) {\n const TValue *slot;\n TValue *rb = vRB(i); /* key (table is in 'ra') */\n TValue *rc = RKC(i); /* value */\n lua_Unsigned n;\n if (ttisinteger(rb) /* fast track for integers? */\n ? (cast_void(n = ivalue(rb)), luaV_fastgeti(L, s2v(ra), n, slot))\n : luaV_fastget(L, s2v(ra), rb, slot, luaH_get)) {\n luaV_finishfastset(L, s2v(ra), slot, rc);\n }\n else\n Protect(luaV_finishset(L, s2v(ra), rb, rc, slot));\n vmbreak;\n }\n vmcase(OP_SETI) {\n const TValue *slot;\n int c = GETARG_B(i);\n TValue *rc = RKC(i);\n if (luaV_fastgeti(L, s2v(ra), c, slot)) {\n luaV_finishfastset(L, s2v(ra), slot, rc);\n }\n else {\n TValue key;\n setivalue(&key, c);\n Protect(luaV_finishset(L, s2v(ra), &key, rc, slot));\n }\n vmbreak;\n }\n vmcase(OP_SETFIELD) {\n const TValue *slot;\n TValue *rb = KB(i);\n TValue *rc = RKC(i);\n TString *key = tsvalue(rb); /* key must be a string */\n if (luaV_fastget(L, s2v(ra), key, slot, luaH_getshortstr)) {\n luaV_finishfastset(L, s2v(ra), slot, rc);\n }\n else\n Protect(luaV_finishset(L, s2v(ra), rb, rc, slot));\n vmbreak;\n }\n vmcase(OP_NEWTABLE) {\n int b = GETARG_B(i); /* log2(hash size) + 1 */\n int c = GETARG_C(i); /* array size */\n Table *t;\n if (b > 0)\n b = 1 << (b - 1); /* size is 2^(b - 1) */\n lua_assert((!TESTARG_k(i)) == (GETARG_Ax(*pc) == 0));\n if (TESTARG_k(i)) /* non-zero extra argument? */\n c += GETARG_Ax(*pc) * (MAXARG_C + 1); /* add it to size */\n pc++; /* skip extra argument */\n L->top = ra + 1; /* correct top in case of emergency GC */\n t = luaH_new(L); /* memory allocation */\n sethvalue2s(L, ra, t);\n if (b != 0 || c != 0)\n luaH_resize(L, t, c, b); /* idem */\n checkGC(L, ra + 1);\n vmbreak;\n }\n vmcase(OP_SELF) {\n const TValue *slot;\n TValue *rb = vRB(i);\n TValue *rc = RKC(i);\n TString *key = tsvalue(rc); /* key must be a string */\n setobj2s(L, ra + 1, rb);\n if (luaV_fastget(L, rb, key, slot, luaH_getstr)) {\n setobj2s(L, ra, slot);\n }\n else\n Protect(luaV_finishget(L, rb, rc, ra, slot));\n vmbreak;\n }\n vmcase(OP_ADDI) {\n op_arithI(L, l_addi, luai_numadd);\n vmbreak;\n }\n vmcase(OP_ADDK) {\n op_arithK(L, l_addi, luai_numadd);\n vmbreak;\n }\n vmcase(OP_SUBK) {\n op_arithK(L, l_subi, luai_numsub);\n vmbreak;\n }\n vmcase(OP_MULK) {\n op_arithK(L, l_muli, luai_nummul);\n vmbreak;\n }\n vmcase(OP_MODK) {\n op_arithK(L, luaV_mod, luaV_modf);\n vmbreak;\n }\n vmcase(OP_POWK) {\n op_arithfK(L, luai_numpow);\n vmbreak;\n }\n vmcase(OP_DIVK) {\n op_arithfK(L, luai_numdiv);\n vmbreak;\n }\n vmcase(OP_IDIVK) {\n op_arithK(L, luaV_idiv, luai_numidiv);\n vmbreak;\n }\n vmcase(OP_BANDK) {\n op_bitwiseK(L, l_band);\n vmbreak;\n }\n vmcase(OP_BORK) {\n op_bitwiseK(L, l_bor);\n vmbreak;\n }\n vmcase(OP_BXORK) {\n op_bitwiseK(L, l_bxor);\n vmbreak;\n }\n vmcase(OP_SHRI) {\n TValue *rb = vRB(i);\n int ic = GETARG_sC(i);\n lua_Integer ib;\n if (tointegerns(rb, &ib)) {\n pc++; setivalue(s2v(ra), luaV_shiftl(ib, -ic));\n }\n vmbreak;\n }\n vmcase(OP_SHLI) {\n TValue *rb = vRB(i);\n int ic = GETARG_sC(i);\n lua_Integer ib;\n if (tointegerns(rb, &ib)) {\n pc++; setivalue(s2v(ra), luaV_shiftl(ic, ib));\n }\n vmbreak;\n }\n vmcase(OP_ADD) {\n op_arith(L, l_addi, luai_numadd);\n vmbreak;\n }\n vmcase(OP_SUB) {\n op_arith(L, l_subi, luai_numsub);\n vmbreak;\n }\n vmcase(OP_MUL) {\n op_arith(L, l_muli, luai_nummul);\n vmbreak;\n }\n vmcase(OP_MOD) {\n op_arith(L, luaV_mod, luaV_modf);\n vmbreak;\n }\n vmcase(OP_POW) {\n op_arithf(L, luai_numpow);\n vmbreak;\n }\n vmcase(OP_DIV) { /* float division (always with floats) */\n op_arithf(L, luai_numdiv);\n vmbreak;\n }\n vmcase(OP_IDIV) { /* floor division */\n op_arith(L, luaV_idiv, luai_numidiv);\n vmbreak;\n }\n vmcase(OP_BAND) {\n op_bitwise(L, l_band);\n vmbreak;\n }\n vmcase(OP_BOR) {\n op_bitwise(L, l_bor);\n vmbreak;\n }\n vmcase(OP_BXOR) {\n op_bitwise(L, l_bxor);\n vmbreak;\n }\n vmcase(OP_SHR) {\n op_bitwise(L, luaV_shiftr);\n vmbreak;\n }\n vmcase(OP_SHL) {\n op_bitwise(L, luaV_shiftl);\n vmbreak;\n }\n vmcase(OP_MMBIN) {\n Instruction pi = *(pc - 2); /* original arith. expression */\n TValue *rb = vRB(i);\n TMS tm = (TMS)GETARG_C(i);\n StkId result = RA(pi);\n lua_assert(OP_ADD <= GET_OPCODE(pi) && GET_OPCODE(pi) <= OP_SHR);\n Protect(luaT_trybinTM(L, s2v(ra), rb, result, tm));\n vmbreak;\n }\n vmcase(OP_MMBINI) {\n Instruction pi = *(pc - 2); /* original arith. expression */\n int imm = GETARG_sB(i);\n TMS tm = (TMS)GETARG_C(i);\n int flip = GETARG_k(i);\n StkId result = RA(pi);\n Protect(luaT_trybiniTM(L, s2v(ra), imm, flip, result, tm));\n vmbreak;\n }\n vmcase(OP_MMBINK) {\n Instruction pi = *(pc - 2); /* original arith. expression */\n TValue *imm = KB(i);\n TMS tm = (TMS)GETARG_C(i);\n int flip = GETARG_k(i);\n StkId result = RA(pi);\n Protect(luaT_trybinassocTM(L, s2v(ra), imm, flip, result, tm));\n vmbreak;\n }\n vmcase(OP_UNM) {\n TValue *rb = vRB(i);\n lua_Number nb;\n if (ttisinteger(rb)) {\n lua_Integer ib = ivalue(rb);\n setivalue(s2v(ra), intop(-, 0, ib));\n }\n else if (tonumberns(rb, nb)) {\n setfltvalue(s2v(ra), luai_numunm(L, nb));\n }\n else\n Protect(luaT_trybinTM(L, rb, rb, ra, TM_UNM));\n vmbreak;\n }\n vmcase(OP_BNOT) {\n TValue *rb = vRB(i);\n lua_Integer ib;\n if (tointegerns(rb, &ib)) {\n setivalue(s2v(ra), intop(^, ~l_castS2U(0), ib));\n }\n else\n Protect(luaT_trybinTM(L, rb, rb, ra, TM_BNOT));\n vmbreak;\n }\n vmcase(OP_NOT) {\n TValue *rb = vRB(i);\n if (l_isfalse(rb))\n setbtvalue(s2v(ra));\n else\n setbfvalue(s2v(ra));\n vmbreak;\n }\n vmcase(OP_LEN) {\n Protect(luaV_objlen(L, ra, vRB(i)));\n vmbreak;\n }\n vmcase(OP_CONCAT) {\n int n = GETARG_B(i); /* number of elements to concatenate */\n L->top = ra + n; /* mark the end of concat operands */\n ProtectNT(luaV_concat(L, n));\n checkGC(L, L->top); /* 'luaV_concat' ensures correct top */\n vmbreak;\n }\n vmcase(OP_CLOSE) {\n Protect(luaF_close(L, ra, LUA_OK));\n vmbreak;\n }\n vmcase(OP_TBC) {\n /* create new to-be-closed upvalue */\n halfProtect(luaF_newtbcupval(L, ra));\n vmbreak;\n }\n vmcase(OP_JMP) {\n dojump(ci, i, 0);\n vmbreak;\n }\n vmcase(OP_EQ) {\n int cond;\n TValue *rb = vRB(i);\n Protect(cond = luaV_equalobj(L, s2v(ra), rb));\n docondjump();\n vmbreak;\n }\n vmcase(OP_LT) {\n op_order(L, l_lti, LTnum, lessthanothers);\n vmbreak;\n }\n vmcase(OP_LE) {\n op_order(L, l_lei, LEnum, lessequalothers);\n vmbreak;\n }\n vmcase(OP_EQK) {\n TValue *rb = KB(i);\n /* basic types do not use '__eq'; we can use raw equality */\n int cond = luaV_rawequalobj(s2v(ra), rb);\n docondjump();\n vmbreak;\n }\n vmcase(OP_EQI) {\n int cond;\n int im = GETARG_sB(i);\n if (ttisinteger(s2v(ra)))\n cond = (ivalue(s2v(ra)) == im);\n else if (ttisfloat(s2v(ra)))\n cond = luai_numeq(fltvalue(s2v(ra)), cast_num(im));\n else\n cond = 0; /* other types cannot be equal to a number */\n docondjump();\n vmbreak;\n }\n vmcase(OP_LTI) {\n op_orderI(L, l_lti, luai_numlt, 0, TM_LT);\n vmbreak;\n }\n vmcase(OP_LEI) {\n op_orderI(L, l_lei, luai_numle, 0, TM_LE);\n vmbreak;\n }\n vmcase(OP_GTI) {\n op_orderI(L, l_gti, luai_numgt, 1, TM_LT);\n vmbreak;\n }\n vmcase(OP_GEI) {\n op_orderI(L, l_gei, luai_numge, 1, TM_LE);\n vmbreak;\n }\n vmcase(OP_TEST) {\n int cond = !l_isfalse(s2v(ra));\n docondjump();\n vmbreak;\n }\n vmcase(OP_TESTSET) {\n TValue *rb = vRB(i);\n if (l_isfalse(rb) == GETARG_k(i))\n pc++;\n else {\n setobj2s(L, ra, rb);\n donextjump(ci);\n }\n vmbreak;\n }\n vmcase(OP_CALL) {\n int b = GETARG_B(i);\n int nresults = GETARG_C(i) - 1;\n if (b != 0) /* fixed number of arguments? */\n L->top = ra + b; /* top signals number of arguments */\n /* else previous instruction set top */\n ProtectNT(luaD_call(L, ra, nresults));\n vmbreak;\n }\n vmcase(OP_TAILCALL) {\n int b = GETARG_B(i); /* number of arguments + 1 (function) */\n int nparams1 = GETARG_C(i);\n /* delat is virtual 'func' - real 'func' (vararg functions) */\n int delta = (nparams1) ? ci->u.l.nextraargs + nparams1 : 0;\n if (b != 0)\n L->top = ra + b;\n else /* previous instruction set top */\n b = cast_int(L->top - ra);\n savepc(ci); /* some calls here can raise errors */\n if (TESTARG_k(i)) {\n /* close upvalues from current call; the compiler ensures\n that there are no to-be-closed variables here, so this\n call cannot change the stack */\n luaF_close(L, base, NOCLOSINGMETH);\n lua_assert(base == ci->func + 1);\n }\n while (!ttisfunction(s2v(ra))) { /* not a function? */\n luaD_tryfuncTM(L, ra); /* try '__call' metamethod */\n b++; /* there is now one extra argument */\n checkstackp(L, 1, ra);\n }\n if (!ttisLclosure(s2v(ra))) { /* C function? */\n luaD_call(L, ra, LUA_MULTRET); /* call it */\n updatetrap(ci);\n updatestack(ci); /* stack may have been relocated */\n ci->func -= delta;\n luaD_poscall(L, ci, cast_int(L->top - ra));\n return;\n }\n ci->func -= delta;\n luaD_pretailcall(L, ci, ra, b); /* prepare call frame */\n goto tailcall;\n }\n vmcase(OP_RETURN) {\n int n = GETARG_B(i) - 1; /* number of results */\n int nparams1 = GETARG_C(i);\n if (n < 0) /* not fixed? */\n n = cast_int(L->top - ra); /* get what is available */\n savepc(ci);\n if (TESTARG_k(i)) { /* may there be open upvalues? */\n if (L->top < ci->top)\n L->top = ci->top;\n luaF_close(L, base, LUA_OK);\n updatetrap(ci);\n updatestack(ci);\n }\n if (nparams1) /* vararg function? */\n ci->func -= ci->u.l.nextraargs + nparams1;\n L->top = ra + n; /* set call for 'luaD_poscall' */\n luaD_poscall(L, ci, n);\n return;\n }\n vmcase(OP_RETURN0) {\n if (L->hookmask) {\n L->top = ra;\n halfProtectNT(luaD_poscall(L, ci, 0)); /* no hurry... */\n }\n else { /* do the 'poscall' here */\n int nres = ci->nresults;\n L->ci = ci->previous; /* back to caller */\n L->top = base - 1;\n while (nres-- > 0)\n setnilvalue(s2v(L->top++)); /* all results are nil */\n }\n return;\n }\n vmcase(OP_RETURN1) {\n if (L->hookmask) {\n L->top = ra + 1;\n halfProtectNT(luaD_poscall(L, ci, 1)); /* no hurry... */\n }\n else { /* do the 'poscall' here */\n int nres = ci->nresults;\n L->ci = ci->previous; /* back to caller */\n if (nres == 0)\n L->top = base - 1; /* asked for no results */\n else {\n setobjs2s(L, base - 1, ra); /* at least this result */\n L->top = base;\n while (--nres > 0) /* complete missing results */\n setnilvalue(s2v(L->top++));\n }\n }\n return;\n }\n vmcase(OP_FORLOOP) {\n if (ttisinteger(s2v(ra + 2))) { /* integer loop? */\n lua_Unsigned count = l_castS2U(ivalue(s2v(ra + 1)));\n if (count > 0) { /* still more iterations? */\n lua_Integer step = ivalue(s2v(ra + 2));\n lua_Integer idx = ivalue(s2v(ra)); /* internal index */\n chgivalue(s2v(ra + 1), count - 1); /* update counter */\n idx = intop(+, idx, step); /* add step to index */\n chgivalue(s2v(ra), idx); /* update internal index */\n setivalue(s2v(ra + 3), idx); /* and control variable */\n pc -= GETARG_Bx(i); /* jump back */\n }\n }\n else if (floatforloop(ra)) /* float loop */\n pc -= GETARG_Bx(i); /* jump back */\n updatetrap(ci); /* allows a signal to break the loop */\n vmbreak;\n }\n vmcase(OP_FORPREP) {\n savestate(L, ci); /* in case of errors */\n if (forprep(L, ra))\n pc += GETARG_Bx(i) + 1; /* skip the loop */\n vmbreak;\n }\n vmcase(OP_TFORPREP) {\n /* create to-be-closed upvalue (if needed) */\n halfProtect(luaF_newtbcupval(L, ra + 3));\n pc += GETARG_Bx(i);\n i = *(pc++); /* go to next instruction */\n lua_assert(GET_OPCODE(i) == OP_TFORCALL && ra == RA(i));\n goto l_tforcall;\n }\n vmcase(OP_TFORCALL) {\n l_tforcall:\n /* 'ra' has the iterator function, 'ra + 1' has the state,\n 'ra + 2' has the control variable, and 'ra + 3' has the\n to-be-closed variable. The call will use the stack after\n these values (starting at 'ra + 4')\n */\n /* push function, state, and control variable */\n memcpy(ra + 4, ra, 3 * sizeof(*ra));\n L->top = ra + 4 + 3;\n ProtectNT(luaD_call(L, ra + 4, GETARG_C(i))); /* do the call */\n updatestack(ci); /* stack may have changed */\n i = *(pc++); /* go to next instruction */\n lua_assert(GET_OPCODE(i) == OP_TFORLOOP && ra == RA(i));\n goto l_tforloop;\n }\n vmcase(OP_TFORLOOP) {\n l_tforloop:\n if (!ttisnil(s2v(ra + 4))) { /* continue loop? */\n setobjs2s(L, ra + 2, ra + 4); /* save control variable */\n pc -= GETARG_Bx(i); /* jump back */\n }\n vmbreak;\n }\n vmcase(OP_SETLIST) {\n int n = GETARG_B(i);\n unsigned int last = GETARG_C(i);\n Table *h = hvalue(s2v(ra));\n if (n == 0)\n n = cast_int(L->top - ra) - 1; /* get up to the top */\n else\n L->top = ci->top; /* correct top in case of emergency GC */\n last += n;\n if (TESTARG_k(i)) {\n last += GETARG_Ax(*pc) * (MAXARG_C + 1);\n pc++;\n }\n if (last > luaH_realasize(h)) /* needs more space? */\n luaH_resizearray(L, h, last); /* preallocate it at once */\n for (; n > 0; n--) {\n TValue *val = s2v(ra + n);\n setobj2t(L, &h->array[last - 1], val);\n last--;\n luaC_barrierback(L, obj2gco(h), val);\n }\n vmbreak;\n }\n vmcase(OP_CLOSURE) {\n Proto *p = cl->p->p[GETARG_Bx(i)];\n halfProtect(pushclosure(L, p, cl->upvals, base, ra));\n checkGC(L, ra + 1);\n vmbreak;\n }\n vmcase(OP_VARARG) {\n int n = GETARG_C(i) - 1; /* required results */\n Protect(luaT_getvarargs(L, ci, ra, n));\n vmbreak;\n }\n vmcase(OP_VARARGPREP) {\n luaT_adjustvarargs(L, GETARG_A(i), ci, cl->p);\n updatetrap(ci);\n if (trap) {\n luaD_hookcall(L, ci);\n L->oldpc = pc + 1; /* next opcode will be seen as a \"new\" line */\n }\n updatebase(ci); /* function has new base after adjustment */\n vmbreak;\n }\n vmcase(OP_EXTRAARG) {\n lua_assert(0);\n vmbreak;\n }\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-125', 'CWE-787'], 'message': 'Fixed bugs of stack reallocation x GC\n\nMacro 'checkstackGC' was doing a GC step after resizing the stack;\nthe GC could shrink the stack and undo the resize. Moreover, macro\n'checkstackp' also does a GC step, which could remove the preallocated\nCallInfo when calling a function. (Its name has been changed to\n'checkstackGCp' to emphasize that it calls the GC.)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ReadFromRFBServer(rfbClient* client, char *out, unsigned int n)\n{\n#undef DEBUG_READ_EXACT\n#ifdef DEBUG_READ_EXACT\n\tchar* oout=out;\n\tunsigned int nn=n;\n\trfbClientLog(\"ReadFromRFBServer %d bytes\\n\",n);\n#endif\n\n /* Handle attempts to write to NULL out buffer that might occur\n when an outside malloc() fails. For instance, memcpy() to NULL\n results in undefined behaviour and probably memory corruption.*/\n if(!out)\n return FALSE;\n\n if (client->serverPort==-1) {\n /* vncrec playing */\n rfbVNCRec* rec = client->vncRec;\n struct timeval tv;\n\n if (rec->readTimestamp) {\n rec->readTimestamp = FALSE;\n if (!fread(&tv,sizeof(struct timeval),1,rec->file))\n return FALSE;\n\n tv.tv_sec = rfbClientSwap32IfLE (tv.tv_sec);\n tv.tv_usec = rfbClientSwap32IfLE (tv.tv_usec);\n\n if (rec->tv.tv_sec!=0 && !rec->doNotSleep) {\n struct timeval diff;\n diff.tv_sec = tv.tv_sec - rec->tv.tv_sec;\n diff.tv_usec = tv.tv_usec - rec->tv.tv_usec;\n if(diff.tv_usec<0) {\n\t diff.tv_sec--;\n\t diff.tv_usec+=1000000;\n }\n#ifndef WIN32\n sleep (diff.tv_sec);\n usleep (diff.tv_usec);\n#else\n\tSleep (diff.tv_sec * 1000 + diff.tv_usec/1000);\n#endif\n }\n\n rec->tv=tv;\n }\n \n return (fread(out,1,n,rec->file) != n ? FALSE : TRUE);\n }\n \n if (n <= client->buffered) {\n memcpy(out, client->bufoutptr, n);\n client->bufoutptr += n;\n client->buffered -= n;\n#ifdef DEBUG_READ_EXACT\n goto hexdump;\n#endif\n return TRUE;\n }\n\n memcpy(out, client->bufoutptr, client->buffered);\n\n out += client->buffered;\n n -= client->buffered;\n\n client->bufoutptr = client->buf;\n client->buffered = 0;\n\n if (n <= RFB_BUF_SIZE) {\n\n while (client->buffered < n) {\n int i;\n if (client->tlsSession)\n i = ReadFromTLS(client, client->buf + client->buffered, RFB_BUF_SIZE - client->buffered);\n else\n#ifdef LIBVNCSERVER_HAVE_SASL\n if (client->saslconn)\n i = ReadFromSASL(client, client->buf + client->buffered, RFB_BUF_SIZE - client->buffered);\n else {\n#endif /* LIBVNCSERVER_HAVE_SASL */\n i = read(client->sock, client->buf + client->buffered, RFB_BUF_SIZE - client->buffered);\n#ifdef WIN32\n\tif (i < 0) errno=WSAGetLastError();\n#endif\n#ifdef LIBVNCSERVER_HAVE_SASL\n }\n#endif\n \n if (i <= 0) {\n\tif (i < 0) {\n\t if (errno == EWOULDBLOCK || errno == EAGAIN) {\n\t /* TODO:\n\t ProcessXtEvents();\n\t */\n\t WaitForMessage(client, 100000);\n\t i = 0;\n\t } else {\n\t rfbClientErr(\"read (%d: %s)\\n\",errno,strerror(errno));\n\t return FALSE;\n\t }\n\t} else {\n\t if (errorMessageOnReadFailure) {\n\t rfbClientLog(\"VNC server closed connection\\n\");\n\t }\n\t return FALSE;\n\t}\n }\n client->buffered += i;\n }\n\n memcpy(out, client->bufoutptr, n);\n client->bufoutptr += n;\n client->buffered -= n;\n\n } else {\n\n while (n > 0) {\n int i;\n if (client->tlsSession)\n i = ReadFromTLS(client, out, n);\n else\n#ifdef LIBVNCSERVER_HAVE_SASL\n if (client->saslconn)\n i = ReadFromSASL(client, out, n);\n else\n#endif\n i = read(client->sock, out, n);\n\n if (i <= 0) {\n\tif (i < 0) {\n#ifdef WIN32\n\t errno=WSAGetLastError();\n#endif\n\t if (errno == EWOULDBLOCK || errno == EAGAIN) {\n\t /* TODO:\n\t ProcessXtEvents();\n\t */\n\t WaitForMessage(client, 100000);\n\t i = 0;\n\t } else {\n\t rfbClientErr(\"read (%s)\\n\",strerror(errno));\n\t return FALSE;\n\t }\n\t} else {\n\t if (errorMessageOnReadFailure) {\n\t rfbClientLog(\"VNC server closed connection\\n\");\n\t }\n\t return FALSE;\n\t}\n }\n out += i;\n n -= i;\n }\n }\n\n#ifdef DEBUG_READ_EXACT\nhexdump:\n { unsigned int ii;\n for(ii=0;ii \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-835'], 'message': 'libvncclient: handle half-open TCP connections\n\nWhen a connection is not reset properly at the TCP level (e.g. sudden\npower loss or process crash) the TCP connection becomes half-open and\nread() always returns -1 with errno = EAGAIN while select() always\nreturns 0. This leads to an infinite loop and can be fixed by closing\nthe connection after a certain number of retries (based on a timeout)\nhas been exceeded.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int luaG_traceexec (lua_State *L, const Instruction *pc) {\n CallInfo *ci = L->ci;\n lu_byte mask = L->hookmask;\n int counthook;\n if (!(mask & (LUA_MASKLINE | LUA_MASKCOUNT))) { /* no hooks? */\n ci->u.l.trap = 0; /* don't need to stop again */\n return 0; /* turn off 'trap' */\n }\n pc++; /* reference is always next instruction */\n ci->u.l.savedpc = pc; /* save 'pc' */\n counthook = (--L->hookcount == 0 && (mask & LUA_MASKCOUNT));\n if (counthook)\n resethookcount(L); /* reset count */\n else if (!(mask & LUA_MASKLINE))\n return 1; /* no line hook and count != 0; nothing to be done now */\n if (ci->callstatus & CIST_HOOKYIELD) { /* called hook last time? */\n ci->callstatus &= ~CIST_HOOKYIELD; /* erase mark */\n return 1; /* do not call hook again (VM yielded, so it did not move) */\n }\n if (!isIT(*(ci->u.l.savedpc - 1)))\n L->top = ci->top; /* prepare top */\n if (counthook)\n luaD_hook(L, LUA_HOOKCOUNT, -1, 0, 0); /* call count hook */\n if (mask & LUA_MASKLINE) {\n const Proto *p = ci_func(ci)->p;\n int npci = pcRel(pc, p);\n if (npci == 0 || /* call linehook when enter a new function, */\n pc <= L->oldpc || /* when jump back (loop), or when */\n changedline(p, pcRel(L->oldpc, p), npci)) { /* enter new line */\n int newline = luaG_getfuncline(p, npci);\n luaD_hook(L, LUA_HOOKLINE, newline, 0, 0); /* call line hook */\n }\n L->oldpc = pc; /* 'pc' of last call to line hook */\n }\n if (L->status == LUA_YIELD) { /* did hook yield? */\n if (counthook)\n L->hookcount = 1; /* undo decrement to zero */\n ci->u.l.savedpc--; /* undo increment (resume will increment it again) */\n ci->callstatus |= CIST_HOOKYIELD; /* mark that it yielded */\n luaD_throw(L, LUA_YIELD);\n }\n return 1; /* keep 'trap' on */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'Fixed bug: invalid 'oldpc' when returning to a function\n\nThe field 'L->oldpc' is not always updated when control returns to a\nfunction; an invalid value can seg. fault when computing 'changedline'.\n(One example is an error in a finalizer; control can return to\n'luaV_execute' without executing 'luaD_poscall'.) Instead of trying to\nfix all possible corner cases, it seems safer to be resilient to invalid\nvalues for 'oldpc'. Valid but wrong values at most cause an extra call\nto a line hook.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: _XimProtoGetICValues(\n XIC\t\t\t xic,\n XIMArg\t\t*arg)\n{\n Xic\t\t\t ic = (Xic)xic;\n Xim\t\t\t im = (Xim)ic->core.im;\n register XIMArg\t*p;\n register XIMArg\t*pp;\n register int\t n;\n CARD8\t\t*buf;\n CARD16\t\t*buf_s;\n INT16\t\t len;\n CARD32\t\t reply32[BUFSIZE/4];\n char\t\t*reply = (char *)reply32;\n XPointer\t\t preply = NULL;\n int\t\t\t buf_size;\n int\t\t\t ret_code;\n char\t\t*makeid_name;\n char\t\t*decode_name;\n CARD16\t\t*data = NULL;\n INT16\t\t data_len = 0;\n\n#ifndef XIM_CONNECTABLE\n if (!IS_IC_CONNECTED(ic))\n\treturn arg->name;\n#else\n if (!IS_IC_CONNECTED(ic)) {\n\tif (IS_CONNECTABLE(im)) {\n\t if (_XimConnectServer(im)) {\n\t\tif (!_XimReCreateIC(ic)) {\n\t\t _XimDelayModeSetAttr(im);\n\t return _XimDelayModeGetICValues(ic, arg);\n\t\t}\n\t } else {\n\t return _XimDelayModeGetICValues(ic, arg);\n\t }\n } else {\n\t return arg->name;\n }\n }\n#endif /* XIM_CONNECTABLE */\n\n for (n = 0, p = arg; p && p->name; p++) {\n\tn++;\n\tif ((strcmp(p->name, XNPreeditAttributes) == 0)\n\t || (strcmp(p->name, XNStatusAttributes) == 0)) {\n\t n++;\n\t for (pp = (XIMArg *)p->value; pp && pp->name; pp++)\n\t \tn++;\n\t}\n }\n\n if (!n)\n\treturn (char *)NULL;\n\n buf_size = sizeof(CARD16) * n;\n buf_size += XIM_HEADER_SIZE\n\t + sizeof(CARD16)\n\t + sizeof(CARD16)\n\t + sizeof(INT16)\n\t + XIM_PAD(2 + buf_size);\n\n if (!(buf = Xmalloc(buf_size)))\n\treturn arg->name;\n buf_s = (CARD16 *)&buf[XIM_HEADER_SIZE];\n\n makeid_name = _XimMakeICAttrIDList(ic, ic->private.proto.ic_resources,\n\t\t\t\tic->private.proto.ic_num_resources, arg,\n\t\t\t\t&buf_s[3], &len, XIM_GETICVALUES);\n\n if (len > 0) {\n\tbuf_s[0] = im->private.proto.imid;\t\t/* imid */\n\tbuf_s[1] = ic->private.proto.icid;\t\t/* icid */\n\tbuf_s[2] = len;\t\t\t\t/* length of ic-attr-id */\n\tlen += sizeof(INT16); /* sizeof length of attr */\n\tXIM_SET_PAD(&buf_s[2], len);\t\t/* pad */\n\tlen += sizeof(CARD16)\t\t\t/* sizeof imid */\n\t + sizeof(CARD16);\t\t\t/* sizeof icid */\n\n\t_XimSetHeader((XPointer)buf, XIM_GET_IC_VALUES, 0, &len);\n\tif (!(_XimWrite(im, len, (XPointer)buf))) {\n\t Xfree(buf);\n\t return arg->name;\n\t}\n\t_XimFlush(im);\n\tXfree(buf);\n\tbuf_size = BUFSIZE;\n\tret_code = _XimRead(im, &len, (XPointer)reply, buf_size,\n\t\t\t\t _XimGetICValuesCheck, (XPointer)ic);\n\tif (ret_code == XIM_TRUE) {\n\t preply = reply;\n\t} else if (ret_code == XIM_OVERFLOW) {\n\t if (len <= 0) {\n\t\tpreply = reply;\n\t } else {\n\t\tbuf_size = (int)len;\n\t\tpreply = Xmalloc(len);\n\t\tret_code = _XimRead(im, &len, preply, buf_size,\n\t\t\t\t_XimGetICValuesCheck, (XPointer)ic);\n\t\tif (ret_code != XIM_TRUE) {\n\t\t if (preply != reply)\n\t\t Xfree(preply);\n\t\t return arg->name;\n\t\t}\n\t }\n\t} else {\n\t return arg->name;\n\t}\n\tbuf_s = (CARD16 *)((char *)preply + XIM_HEADER_SIZE);\n\tif (*((CARD8 *)preply) == XIM_ERROR) {\n\t _XimProcError(im, 0, (XPointer)&buf_s[3]);\n\t if (reply != preply)\n\t\tXfree(preply);\n\t return arg->name;\n\t}\n\tdata = &buf_s[4];\n\tdata_len = buf_s[2];\n }\n else if (len < 0) {\n\treturn arg->name;\n }\n\n decode_name = _XimDecodeICATTRIBUTE(ic, ic->private.proto.ic_resources,\n\t\t\tic->private.proto.ic_num_resources, data, data_len,\n\t\t\targ, XIM_GETICVALUES);\n if (reply != preply)\n\tXfree(preply);\n\n if (decode_name)\n\treturn decode_name;\n else\n\treturn makeid_name;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Zero out buffers in functions\n\nIt looks like uninitialized stack or heap memory can leak\nout via padding bytes.\n\nSigned-off-by: Matthieu Herrb \nReviewed-by: Matthieu Herrb '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: _XimCountNumberOfAttr(\n INT16\t total,\n CARD16\t*attr,\n int\t\t*names_len)\n{\n unsigned int n;\n INT16\t len;\n INT16\t min_len = sizeof(CARD16)\t/* sizeof attribute ID */\n\t\t\t + sizeof(CARD16)\t/* sizeof type of value */\n\t\t\t + sizeof(INT16);\t/* sizeof length of attribute */\n\n n = 0;\n *names_len = 0;\n while (total > min_len) {\n\tlen = attr[2];\n\t*names_len += (len + 1);\n\tlen += (min_len + XIM_PAD(len + 2));\n\ttotal -= len;\n\tattr = (CARD16 *)((char *)attr + len);\n\tn++;\n }\n return n;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix signed length values in _XimGetAttributeID()\n\nThe lengths are unsigned according to the specification. Passing\nnegative values can lead to data corruption.\n\nSigned-off-by: Matthieu Herrb \nReviewed-by: Matthieu Herrb '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: shutdown_mib(void)\n{\n unload_all_mibs();\n if (tree_top) {\n if (tree_top->label)\n SNMP_FREE(tree_top->label);\n SNMP_FREE(tree_top);\n }\n tree_head = NULL;\n Mib = NULL;\n if (_mibindexes) {\n int i;\n for (i = 0; i < _mibindex; ++i)\n SNMP_FREE(_mibindexes[i]);\n free(_mibindexes);\n _mibindex = 0;\n _mibindex_max = 0;\n _mibindexes = NULL;\n }\n if (Prefix != NULL && Prefix != &Standard_Prefix[0])\n SNMP_FREE(Prefix);\n if (Prefix)\n Prefix = NULL;\n SNMP_FREE(confmibs);\n SNMP_FREE(confmibdir);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'CHANGES: snmpd: Stop reading and writing the mib_indexes/* files\n\nCaching directory contents is something the operating system should do\nand is not something Net-SNMP should do. Instead of storing a copy of\nthe directory contents in ${tmp_dir}/mib_indexes/${n}, always scan a\nMIB directory.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static h2_push_diary_entry *move_to_last(h2_push_diary *diary, apr_size_t idx)\n{\n h2_push_diary_entry *entries = (h2_push_diary_entry*)diary->entries->elts;\n h2_push_diary_entry e;\n apr_size_t lastidx = (apr_size_t)diary->entries->nelts;\n \n /* move entry[idx] to the end */\n if (idx+1 < lastidx) {\n e = entries[idx];\n memmove(entries+idx, entries+idx+1, sizeof(e) * (lastidx - idx));\n entries[lastidx] = e;\n }\n return &entries[lastidx];\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-444'], 'message': '* Removing support for abandoned draft of http-wg regarding cache-digests.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: dns_message_parse(dns_message_t *msg, isc_buffer_t *source,\n\t\t unsigned int options)\n{\n\tisc_region_t r;\n\tdns_decompress_t dctx;\n\tisc_result_t ret;\n\tuint16_t tmpflags;\n\tisc_buffer_t origsource;\n\tbool seen_problem;\n\tbool ignore_tc;\n\n\tREQUIRE(DNS_MESSAGE_VALID(msg));\n\tREQUIRE(source != NULL);\n\tREQUIRE(msg->from_to_wire == DNS_MESSAGE_INTENTPARSE);\n\n\tseen_problem = false;\n\tignore_tc = ((options & DNS_MESSAGEPARSE_IGNORETRUNCATION) != 0);\n\n\torigsource = *source;\n\n\tmsg->header_ok = 0;\n\tmsg->question_ok = 0;\n\n\tisc_buffer_remainingregion(source, &r);\n\tif (r.length < DNS_MESSAGE_HEADERLEN)\n\t\treturn (ISC_R_UNEXPECTEDEND);\n\n\tmsg->id = isc_buffer_getuint16(source);\n\ttmpflags = isc_buffer_getuint16(source);\n\tmsg->opcode = ((tmpflags & DNS_MESSAGE_OPCODE_MASK)\n\t\t >> DNS_MESSAGE_OPCODE_SHIFT);\n\tmsg->rcode = (dns_rcode_t)(tmpflags & DNS_MESSAGE_RCODE_MASK);\n\tmsg->flags = (tmpflags & DNS_MESSAGE_FLAG_MASK);\n\tmsg->counts[DNS_SECTION_QUESTION] = isc_buffer_getuint16(source);\n\tmsg->counts[DNS_SECTION_ANSWER] = isc_buffer_getuint16(source);\n\tmsg->counts[DNS_SECTION_AUTHORITY] = isc_buffer_getuint16(source);\n\tmsg->counts[DNS_SECTION_ADDITIONAL] = isc_buffer_getuint16(source);\n\n\tmsg->header_ok = 1;\n\tmsg->state = DNS_SECTION_QUESTION;\n\n\t/*\n\t * -1 means no EDNS.\n\t */\n\tdns_decompress_init(&dctx, -1, DNS_DECOMPRESS_ANY);\n\n\tdns_decompress_setmethods(&dctx, DNS_COMPRESS_GLOBAL14);\n\n\tret = getquestions(source, msg, &dctx, options);\n\tif (ret == ISC_R_UNEXPECTEDEND && ignore_tc)\n\t\tgoto truncated;\n\tif (ret == DNS_R_RECOVERABLE) {\n\t\tseen_problem = true;\n\t\tret = ISC_R_SUCCESS;\n\t}\n\tif (ret != ISC_R_SUCCESS)\n\t\treturn (ret);\n\tmsg->question_ok = 1;\n\n\tret = getsection(source, msg, &dctx, DNS_SECTION_ANSWER, options);\n\tif (ret == ISC_R_UNEXPECTEDEND && ignore_tc)\n\t\tgoto truncated;\n\tif (ret == DNS_R_RECOVERABLE) {\n\t\tseen_problem = true;\n\t\tret = ISC_R_SUCCESS;\n\t}\n\tif (ret != ISC_R_SUCCESS)\n\t\treturn (ret);\n\n\tret = getsection(source, msg, &dctx, DNS_SECTION_AUTHORITY, options);\n\tif (ret == ISC_R_UNEXPECTEDEND && ignore_tc)\n\t\tgoto truncated;\n\tif (ret == DNS_R_RECOVERABLE) {\n\t\tseen_problem = true;\n\t\tret = ISC_R_SUCCESS;\n\t}\n\tif (ret != ISC_R_SUCCESS)\n\t\treturn (ret);\n\n\tret = getsection(source, msg, &dctx, DNS_SECTION_ADDITIONAL, options);\n\tif (ret == ISC_R_UNEXPECTEDEND && ignore_tc)\n\t\tgoto truncated;\n\tif (ret == DNS_R_RECOVERABLE) {\n\t\tseen_problem = true;\n\t\tret = ISC_R_SUCCESS;\n\t}\n\tif (ret != ISC_R_SUCCESS)\n\t\treturn (ret);\n\n\tisc_buffer_remainingregion(source, &r);\n\tif (r.length != 0) {\n\t\tisc_log_write(dns_lctx, ISC_LOGCATEGORY_GENERAL,\n\t\t\t DNS_LOGMODULE_MESSAGE, ISC_LOG_DEBUG(3),\n\t\t\t \"message has %u byte(s) of trailing garbage\",\n\t\t\t r.length);\n\t}\n\n truncated:\n\tif ((options & DNS_MESSAGEPARSE_CLONEBUFFER) == 0)\n\t\tisc_buffer_usedregion(&origsource, &msg->saved);\n\telse {\n\t\tmsg->saved.length = isc_buffer_usedlength(&origsource);\n\t\tmsg->saved.base = isc_mem_get(msg->mctx, msg->saved.length);\n\t\tif (msg->saved.base == NULL)\n\t\t\treturn (ISC_R_NOMEMORY);\n\t\tmemmove(msg->saved.base, isc_buffer_base(&origsource),\n\t\t\tmsg->saved.length);\n\t\tmsg->free_saved = 1;\n\t}\n\n\tif (ret == ISC_R_UNEXPECTEDEND && ignore_tc)\n\t\treturn (DNS_R_RECOVERABLE);\n\tif (seen_problem == true)\n\t\treturn (DNS_R_RECOVERABLE);\n\treturn (ISC_R_SUCCESS);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617'], 'message': 'Always keep a copy of the message\n\nthis allows it to be available even when dns_message_parse()\nreturns a error.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: pkcs11rsa_verify(dst_context_t *dctx, const isc_region_t *sig) {\n\tCK_RV rv;\n\tpk11_context_t *pk11_ctx = dctx->ctxdata.pk11_ctx;\n\tisc_result_t ret = ISC_R_SUCCESS;\n\n\tPK11_CALL(pkcs_C_VerifyFinal,\n\t\t (pk11_ctx->session,\n\t\t (CK_BYTE_PTR) sig->base,\n\t\t (CK_ULONG) sig->length),\n\t\t DST_R_VERIFYFAILURE);\n\treturn (ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617'], 'message': 'Fix crash in pk11_numbits() when native-pkcs11 is used\n\nWhen pk11_numbits() is passed a user provided input that contains all\nzeroes (via crafted DNS message), it would crash with assertion\nfailure. Fix that by properly handling such input.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: okiibm_print_page1(gx_device_printer *pdev, gp_file *prn_stream, int y_9pin_high,\n const char *init_string, int init_length,\n const char *end_string, int end_length)\n{\n static const char graphics_modes_9[5] =\n {\n -1, 0 /*60*/, 1 /*120*/, -1, 3 /*240*/\n };\n\n int in_y_mult = (y_9pin_high ? 2 : 1);\n int line_size = gdev_mem_bytes_per_scan_line((gx_device *)pdev);\n /* Note that in_size is a multiple of 8. */\n int in_size = line_size * (8 * in_y_mult);\n byte *buf1 = (byte *)gs_malloc(pdev->memory, in_size, 1, \"okiibm_print_page(buf1)\");\n byte *buf2 = (byte *)gs_malloc(pdev->memory, in_size, 1, \"okiibm_print_page(buf2)\");\n byte *in = buf1;\n byte *out = buf2;\n int out_y_mult = 1;\n int x_dpi = pdev->x_pixels_per_inch;\n char start_graphics = graphics_modes_9[x_dpi / 60];\n int first_pass = (start_graphics == 3 ? 1 : 0);\n int last_pass = first_pass * 2;\n int y_passes = (y_9pin_high ? 2 : 1);\n int skip = 0, lnum = 0, pass, ypass;\n int y_step = 0;\n\n /* Check allocations */\n if ( buf1 == 0 || buf2 == 0 )\n {\tif ( buf1 )\n gs_free(pdev->memory, (char *)buf1, in_size, 1, \"okiibm_print_page(buf1)\");\n if ( buf2 )\n gs_free(pdev->memory, (char *)buf2, in_size, 1, \"okiibm_print_page(buf2)\");\n return_error(gs_error_VMerror);\n }\n\n /* Initialize the printer. */\n gp_fwrite(init_string, 1, init_length, prn_stream);\n\n /* Print lines of graphics */\n while ( lnum < pdev->height )\n {\n byte *in_data;\n byte *inp;\n byte *in_end;\n byte *out_end = NULL;\n int lcnt;\n\n /* Copy 1 scan line and test for all zero. */\n gdev_prn_get_bits(pdev, lnum, in, &in_data);\n if ( in_data[0] == 0 &&\n !memcmp((char *)in_data, (char *)in_data + 1, line_size - 1)\n )\n {\n lnum++;\n skip += 2 / in_y_mult;\n continue;\n }\n\n /*\n * Vertical tab to the appropriate position.\n * The skip count is in 1/144\" steps. If total\n * vertical request is not a multiple od 1/72\"\n * we need to make sure the page is actually\n * going to advance.\n */\n if ( skip & 1 )\n {\n int n = 1 + (y_step == 0 ? 1 : 0);\n gp_fprintf(prn_stream, \"\\033J%c\", n);\n y_step = (y_step + n) % 3;\n skip -= 1;\n }\n skip = skip / 2 * 3;\n while ( skip > 255 )\n {\n gp_fputs(\"\\033J\\377\", prn_stream);\n skip -= 255;\n }\n if ( skip )\n {\n gp_fprintf(prn_stream, \"\\033J%c\", skip);\n }\n\n /* Copy the the scan lines. */\n lcnt = gdev_prn_copy_scan_lines(pdev, lnum, in, in_size);\n if ( lcnt < 8 * in_y_mult )\n {\t/* Pad with lines of zeros. */\n memset(in + lcnt * line_size, 0,\n in_size - lcnt * line_size);\n }\n\n if ( y_9pin_high )\n {\t/* Shuffle the scan lines */\n byte *p;\n int i;\n static const char index[] =\n { 0, 2, 4, 6, 8, 10, 12, 14,\n 1, 3, 5, 7, 9, 11, 13, 15\n };\n for ( i = 0; i < 16; i++ )\n {\n memcpy( out + (i * line_size),\n in + (index[i] * line_size),\n line_size);\n }\n p = in;\n in = out;\n out = p;\n }\n\n for ( ypass = 0; ypass < y_passes; ypass++ )\n {\n for ( pass = first_pass; pass <= last_pass; pass++ )\n {\n /* We have to 'transpose' blocks of 8 pixels x 8 lines, */\n /* because that's how the printer wants the data. */\n\n if ( pass == first_pass )\n {\n out_end = out;\n inp = in;\n in_end = inp + line_size;\n\n for ( ; inp < in_end; inp++, out_end += 8 )\n {\n gdev_prn_transpose_8x8(inp + (ypass * 8 * line_size),\n line_size, out_end, 1);\n }\n /* Remove trailing 0s. */\n while ( out_end > out && out_end[-1] == 0 )\n {\n out_end--;\n }\n }\n\n /* Transfer whatever is left and print. */\n if ( out_end > out )\n {\n okiibm_output_run(out, (int)(out_end - out),\n out_y_mult, start_graphics,\n prn_stream, pass);\n }\n gp_fputc('\\r', prn_stream);\n }\n if ( ypass < y_passes - 1 )\n {\n int n = 1 + (y_step == 0 ? 1 : 0);\n gp_fprintf(prn_stream, \"\\033J%c\", n);\n y_step = (y_step + n) % 3;\n }\n }\n skip = 16 - y_passes + 1;\t\t/* no skip on last Y pass */\n lnum += 8 * in_y_mult;\n }\n\n /* Reinitialize the printer. */\n gp_fwrite(end_string, 1, end_length, prn_stream);\n gp_fflush(prn_stream);\n\n gs_free(pdev->memory, (char *)buf2, in_size, 1, \"okiibm_print_page(buf2)\");\n gs_free(pdev->memory, (char *)buf1, in_size, 1, \"okiibm_print_page(buf1)\");\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'Bug 701808: return error from okiibm_print_page1() if x_dpi too high.\n\nAvoids asan error in:\n ./sanbin/gs -dBATCH -dNOPAUSE -dSAFER -r599 -sOutputFile=tmp -sDEVICE=okiibm ../bug-701808.pdf'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: do_compose_group16(pdf14_buf *tos, pdf14_buf *nos, pdf14_buf *maskbuf,\n int x0, int x1, int y0, int y1, int n_chan, bool additive,\n const pdf14_nonseparable_blending_procs_t * pblend_procs,\n bool has_matte, bool overprint, gx_color_index drawn_comps,\n gs_memory_t *memory, gx_device *dev)\n{\n int num_spots = tos->num_spots;\n uint16_t alpha = tos->alpha;\n uint16_t shape = tos->shape;\n gs_blend_mode_t blend_mode = tos->blend_mode;\n uint16_t *tos_ptr =\n (uint16_t *)(void *)(tos->data + (x0 - tos->rect.p.x)*2 +\n (y0 - tos->rect.p.y) * tos->rowstride);\n uint16_t *nos_ptr =\n (uint16_t *)(void *)(nos->data + (x0 - nos->rect.p.x)*2 +\n (y0 - nos->rect.p.y) * nos->rowstride);\n uint16_t *mask_row_ptr = NULL;\n int tos_planestride = tos->planestride;\n int nos_planestride = nos->planestride;\n uint16_t mask_bg_alpha = 0; /* Quiet compiler. */\n bool tos_isolated = tos->isolated;\n bool nos_isolated = nos->isolated;\n bool nos_knockout = nos->knockout;\n uint16_t *nos_alpha_g_ptr;\n int tos_shape_offset = n_chan * tos_planestride;\n int tos_alpha_g_offset = tos_shape_offset + (tos->has_shape ? tos_planestride : 0);\n bool tos_has_tag = tos->has_tags;\n int tos_tag_offset = tos_planestride * (tos->n_planes - 1);\n int nos_shape_offset = n_chan * nos_planestride;\n int nos_alpha_g_offset = nos_shape_offset + (nos->has_shape ? nos_planestride : 0);\n int nos_tag_offset = nos_planestride * (nos->n_planes - 1);\n const uint16_t *mask_tr_fn = NULL; /* Quiet compiler. */\n bool has_mask = false;\n uint16_t *backdrop_ptr = NULL;\n pdf14_device *pdev = (pdf14_device *)dev;\n#if RAW_DUMP\n uint16_t *composed_ptr = NULL;\n int width = x1 - x0;\n#endif\n art_pdf_compose_group16_fn fn;\n\n if ((tos->n_chan == 0) || (nos->n_chan == 0))\n return;\n rect_merge(nos->dirty, tos->dirty);\n if (nos->has_tags)\n if_debug7m('v', memory,\n \"pdf14_pop_transparency_group y0 = %d, y1 = %d, w = %d, alpha = %d, shape = %d, tag = %d, bm = %d\\n\",\n y0, y1, x1 - x0, alpha, shape, dev->graphics_type_tag & ~GS_DEVICE_ENCODES_TAGS, blend_mode);\n else\n if_debug6m('v', memory,\n \"pdf14_pop_transparency_group y0 = %d, y1 = %d, w = %d, alpha = %d, shape = %d, bm = %d\\n\",\n y0, y1, x1 - x0, alpha, shape, blend_mode);\n if (!nos->has_shape)\n nos_shape_offset = 0;\n if (!nos->has_tags)\n nos_tag_offset = 0;\n if (nos->has_alpha_g) {\n nos_alpha_g_ptr = nos_ptr + (nos_alpha_g_offset>>1);\n } else\n nos_alpha_g_ptr = NULL;\n if (nos->backdrop != NULL) {\n backdrop_ptr =\n (uint16_t *)(void *)(nos->backdrop + (x0 - nos->rect.p.x)*2 +\n (y0 - nos->rect.p.y) * nos->rowstride);\n }\n if (blend_mode != BLEND_MODE_Compatible && blend_mode != BLEND_MODE_Normal)\n overprint = false;\n\n if (maskbuf != NULL) {\n unsigned int tmp;\n mask_tr_fn = (uint16_t *)maskbuf->transfer_fn;\n /* Make sure we are in the mask buffer */\n if (maskbuf->data != NULL) {\n mask_row_ptr =\n (uint16_t *)(void *)(maskbuf->data + (x0 - maskbuf->rect.p.x)*2 +\n (y0 - maskbuf->rect.p.y) * maskbuf->rowstride);\n has_mask = true;\n }\n /* We may have a case, where we are outside the maskbuf rect. */\n /* We would have avoided creating the maskbuf->data */\n /* In that case, we should use the background alpha value */\n /* See discussion on the BC entry in the PDF spec. */\n mask_bg_alpha = maskbuf->alpha;\n /* Adjust alpha by the mask background alpha. This is only used\n if we are outside the soft mask rect during the filling operation */\n mask_bg_alpha = interp16(mask_tr_fn, mask_bg_alpha);\n tmp = alpha * mask_bg_alpha + 0x8000;\n mask_bg_alpha = (tmp + (tmp >> 8)) >> 8;\n }\n n_chan--; /* Now the true number of colorants (i.e. not including alpha)*/\n#if RAW_DUMP\n composed_ptr = nos_ptr;\n dump_raw_buffer(memory, y1-y0, width, tos->n_planes, tos_planestride, tos->rowstride,\n \"bImageTOS\", (byte *)tos_ptr, tos->deep);\n dump_raw_buffer(memory, y1-y0, width, nos->n_planes, nos_planestride, nos->rowstride,\n \"cImageNOS\", (byte *)nos_ptr, tos->deep);\n if (maskbuf !=NULL && maskbuf->data != NULL) {\n dump_raw_buffer(memory, maskbuf->rect.q.y - maskbuf->rect.p.y,\n maskbuf->rect.q.x - maskbuf->rect.p.x, maskbuf->n_planes,\n maskbuf->planestride, maskbuf->rowstride, \"dMask\",\n maskbuf->data, maskbuf->deep);\n }\n#endif\n\n /* You might hope that has_mask iff maskbuf != NULL, but this is\n * not the case. Certainly we can see cases where maskbuf != NULL\n * and has_mask = 0. What's more, treating such cases as being\n * has_mask = 0 causes diffs. */\n#ifdef TRACK_COMPOSE_GROUPS\n {\n int code = 0;\n\n code += !!nos_knockout;\n code += (!!nos_isolated)<<1;\n code += (!!tos_isolated)<<2;\n code += (!!tos->has_shape)<<3;\n code += (!!tos_has_tag)<<4;\n code += (!!additive)<<5;\n code += (!!overprint)<<6;\n code += (!!has_mask || maskbuf != NULL)<<7;\n code += (!!has_matte)<<8;\n code += (backdrop_ptr != NULL)<<9;\n code += (num_spots != 0)<<10;\n code += blend_mode<<11;\n\n if (track_compose_groups == 0)\n {\n atexit(dump_track_compose_groups);\n track_compose_groups = 1;\n }\n compose_groups[code]++;\n }\n#endif\n\n /* We have tested the files on the cluster to see what percentage of\n * files/devices hit the different options. */\n if (nos_knockout)\n fn = &compose_group16_knockout; /* Small %ages, nothing more than 1.1% */\n else if (blend_mode != 0)\n fn = &compose_group16_nonknockout_blend; /* Small %ages, nothing more than 2% */\n else if (tos->has_shape == 0 && tos_has_tag == 0 && nos_isolated == 0 && nos_alpha_g_ptr == NULL &&\n nos_shape_offset == 0 && nos_tag_offset == 0 && backdrop_ptr == NULL && has_matte == 0 && num_spots == 0 &&\n overprint == 0) {\n /* Additive vs Subtractive makes no difference in normal blend mode with no spots */\n if (tos_isolated) {\n if (has_mask || maskbuf) {/* 7% */\n /* AirPrint test case hits this */\n if (maskbuf && maskbuf->rect.p.x <= x0 && maskbuf->rect.p.y <= y0 &&\n maskbuf->rect.q.x >= x1 && maskbuf->rect.q.y >= y1)\n fn = &compose_group16_nonknockout_nonblend_isolated_allmask_common;\n else\n fn = &compose_group16_nonknockout_nonblend_isolated_mask_common;\n } else /* 14% */\n fn = &compose_group16_nonknockout_nonblend_isolated_nomask_common;\n } else {\n if (has_mask || maskbuf) /* 4% */\n fn = &compose_group16_nonknockout_nonblend_nonisolated_mask_common;\n else /* 15% */\n fn = &compose_group16_nonknockout_nonblend_nonisolated_nomask_common;\n }\n } else\n fn = compose_group16_nonknockout_noblend_general;\n\n tos_planestride >>= 1;\n tos_shape_offset >>= 1;\n tos_alpha_g_offset >>= 1;\n tos_tag_offset >>= 1;\n nos_planestride >>= 1;\n nos_shape_offset >>= 1;\n nos_tag_offset >>= 1;\n fn(tos_ptr, tos_isolated, tos_planestride, tos->rowstride>>1, alpha, shape, blend_mode, tos->has_shape,\n tos_shape_offset, tos_alpha_g_offset, tos_tag_offset, tos_has_tag,\n nos_ptr, nos_isolated, nos_planestride, nos->rowstride>>1, nos_alpha_g_ptr, nos_knockout,\n nos_shape_offset, nos_tag_offset,\n mask_row_ptr, has_mask, maskbuf, mask_bg_alpha, mask_tr_fn,\n backdrop_ptr,\n has_matte, n_chan, additive, num_spots, overprint, drawn_comps, x0, y0, x1, y1,\n pblend_procs, pdev);\n\n#if RAW_DUMP\n dump_raw_buffer(memory, y1-y0, width, nos->n_planes, nos_planestride<<1, nos->rowstride,\n \"eComposed\", (byte *)composed_ptr, nos->deep);\n global_index++;\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Bug 701795: Segv due to image mask issue'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: jetp3852_print_page(gx_device_printer *pdev, gp_file *prn_stream)\n{\n#define DATA_SIZE (LINE_SIZE * 8)\n\n unsigned int cnt_2prn;\n unsigned int count,tempcnt;\n unsigned char vtp,cntc1,cntc2;\n int line_size_color_plane;\n\n byte data[DATA_SIZE];\n byte plane_data[LINE_SIZE * 3];\n\n /* Set initial condition for printer */\n gp_fputs(\"\\033@\",prn_stream);\n\n /* Send each scan line in turn */\n {\n int lnum;\n int line_size = gdev_mem_bytes_per_scan_line((gx_device *)pdev);\n int num_blank_lines = 0;\n\n if (line_size > DATA_SIZE) {\n emprintf2(pdev->memory, \"invalid resolution and/or width gives line_size = %d, max. is %d\\n\",\n line_size, DATA_SIZE);\n return_error(gs_error_rangecheck);\n }\n\n for ( lnum = 0; lnum < pdev->height; lnum++ ) {\n byte *end_data = data + line_size;\n gdev_prn_copy_scan_lines(pdev, lnum,\n (byte *)data, line_size);\n /* Remove trailing 0s. */\n while ( end_data > data && end_data[-1] == 0 )\n end_data--;\n if ( end_data == data ) {\n /* Blank line */\n num_blank_lines++;\n } else {\n int i;\n byte *odp;\n byte *row;\n\n /* Pad with 0s to fill out the last */\n /* block of 8 bytes. */\n memset(end_data, 0, 7);\n\n /* Transpose the data to get pixel planes. */\n for ( i = 0, odp = plane_data; i < DATA_SIZE;\n i += 8, odp++\n ) { /* The following is for 16-bit machines */\n#define spread3(c)\\\n { 0, c, c*0x100, c*0x101, c*0x10000L, c*0x10001L, c*0x10100L, c*0x10101L }\n static ulong spr40[8] = spread3(0x40);\n static ulong spr8[8] = spread3(8);\n static ulong spr2[8] = spread3(2);\n register byte *dp = data + i;\n register ulong pword =\n (spr40[dp[0]] << 1) +\n (spr40[dp[1]]) +\n (spr40[dp[2]] >> 1) +\n (spr8[dp[3]] << 1) +\n (spr8[dp[4]]) +\n (spr8[dp[5]] >> 1) +\n (spr2[dp[6]]) +\n (spr2[dp[7]] >> 1);\n odp[0] = (byte)(pword >> 16);\n odp[LINE_SIZE] = (byte)(pword >> 8);\n odp[LINE_SIZE*2] = (byte)(pword);\n }\n /* Skip blank lines if any */\n if ( num_blank_lines > 0 ) {\n /* Do \"dot skips\" */\n while(num_blank_lines > 255) {\n gp_fputs(\"\\033e\\377\",prn_stream);\n num_blank_lines -= 255;\n }\n vtp = num_blank_lines;\n gp_fprintf(prn_stream,\"\\033e%c\",vtp);\n num_blank_lines = 0;\n }\n\n /* Transfer raster graphics in the order R, G, B. */\n /* Apparently it is stored in B, G, R */\n /* Calculate the amount of data to send by what */\n /* Ghostscript tells us the scan line_size in (bytes) */\n\n count = line_size / 3;\n line_size_color_plane = count / 3;\n cnt_2prn = line_size_color_plane * 3 + 5;\n tempcnt = cnt_2prn;\n cntc1 = (tempcnt & 0xFF00) >> 8;\n cntc2 = (tempcnt & 0x00FF);\n gp_fprintf(prn_stream, \"\\033[O%c%c\\200\\037\",cntc2,cntc1);\n gp_fputc('\\000',prn_stream);\n gp_fputs(\"\\124\\124\",prn_stream);\n\n for ( row = plane_data + LINE_SIZE * 2, i = 0;\n i < 3; row -= LINE_SIZE, i++ ) {\n int jj;\n byte ctemp;\n odp = row;\n /* Complement bytes */\n for (jj=0; jj< line_size_color_plane; jj++) {\n ctemp = *odp;\n *odp++ = ~ctemp;\n }\n gp_fwrite(row, sizeof(byte),\n line_size_color_plane, prn_stream);\n }\n }\n }\n }\n\n /* eject page */\n gp_fputs(\"\\014\", prn_stream);\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'Bug 701815: avoid uninitialised bytes being >7, which broke indexing.\n\nFixes:\n ./sanbin/gs -dBATCH -dNOPAUSE -sOutputFile=tmp -sDEVICE=jetp3852 ../bug-701815.pdf'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: check_pidfile(void)\n{\n const char *pidfile = CNF_GetPidFile();\n FILE *in;\n int pid, count;\n \n in = fopen(pidfile, \"r\");\n if (!in)\n return;\n\n count = fscanf(in, \"%d\", &pid);\n fclose(in);\n \n if (count != 1)\n return;\n\n if (getsid(pid) < 0)\n return;\n\n LOG_FATAL(\"Another chronyd may already be running (pid=%d), check %s\",\n pid, pidfile);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59'], 'message': 'switch to new util file functions\n\nReplace all fopen(), rename(), and unlink() calls with the new util\nfunctions.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: CNF_ReadFile(const char *filename)\n{\n FILE *in;\n char line[2048];\n int i;\n\n in = fopen(filename, \"r\");\n if (!in) {\n LOG_FATAL(\"Could not open configuration file %s : %s\",\n filename, strerror(errno));\n return;\n }\n\n DEBUG_LOG(\"Reading %s\", filename);\n\n for (i = 1; fgets(line, sizeof(line), in); i++) {\n CNF_ParseLine(filename, i, line);\n }\n\n fclose(in);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59'], 'message': 'switch to new util file functions\n\nReplace all fopen(), rename(), and unlink() calls with the new util\nfunctions.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static TValue *trace_exit_cp(lua_State *L, lua_CFunction dummy, void *ud)\n{\n ExitDataCP *exd = (ExitDataCP *)ud;\n cframe_errfunc(L->cframe) = -1; /* Inherit error function. */\n /* Always catch error here. */\n cframe_nres(L->cframe) = -2*LUAI_MAXSTACK*(int)sizeof(TValue);\n exd->pc = lj_snap_restore(exd->J, exd->exptr);\n UNUSED(dummy);\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Call error function on rethrow after trace exit.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: HttpHeader::parse(const char *header_start, size_t hdrLen)\n{\n const char *field_ptr = header_start;\n const char *header_end = header_start + hdrLen; // XXX: remove\n int warnOnError = (Config.onoff.relaxed_header_parser <= 0 ? DBG_IMPORTANT : 2);\n\n PROF_start(HttpHeaderParse);\n\n assert(header_start && header_end);\n debugs(55, 7, \"parsing hdr: (\" << this << \")\" << std::endl << getStringPrefix(header_start, hdrLen));\n ++ HttpHeaderStats[owner].parsedCount;\n\n char *nulpos;\n if ((nulpos = (char*)memchr(header_start, '\\0', hdrLen))) {\n debugs(55, DBG_IMPORTANT, \"WARNING: HTTP header contains NULL characters {\" <<\n getStringPrefix(header_start, nulpos-header_start) << \"}\\nNULL\\n{\" << getStringPrefix(nulpos+1, hdrLen-(nulpos-header_start)-1));\n PROF_stop(HttpHeaderParse);\n clean();\n return 0;\n }\n\n Http::ContentLengthInterpreter clen(warnOnError);\n /* common format headers are \":[ws]\" lines delimited by .\n * continuation lines start with a (single) space or tab */\n while (field_ptr < header_end) {\n const char *field_start = field_ptr;\n const char *field_end;\n\n do {\n const char *this_line = field_ptr;\n field_ptr = (const char *)memchr(field_ptr, '\\n', header_end - field_ptr);\n\n if (!field_ptr) {\n // missing \n PROF_stop(HttpHeaderParse);\n clean();\n return 0;\n }\n\n field_end = field_ptr;\n\n ++field_ptr; /* Move to next line */\n\n if (field_end > this_line && field_end[-1] == '\\r') {\n --field_end; /* Ignore CR LF */\n\n if (owner == hoRequest && field_end > this_line) {\n bool cr_only = true;\n for (const char *p = this_line; p < field_end && cr_only; ++p) {\n if (*p != '\\r')\n cr_only = false;\n }\n if (cr_only) {\n debugs(55, DBG_IMPORTANT, \"SECURITY WARNING: Rejecting HTTP request with a CR+ \"\n \"header field to prevent request smuggling attacks: {\" <<\n getStringPrefix(header_start, hdrLen) << \"}\");\n PROF_stop(HttpHeaderParse);\n clean();\n return 0;\n }\n }\n }\n\n /* Barf on stray CR characters */\n if (memchr(this_line, '\\r', field_end - this_line)) {\n debugs(55, warnOnError, \"WARNING: suspicious CR characters in HTTP header {\" <<\n getStringPrefix(field_start, field_end-field_start) << \"}\");\n\n if (Config.onoff.relaxed_header_parser) {\n char *p = (char *) this_line; /* XXX Warning! This destroys original header content and violates specifications somewhat */\n\n while ((p = (char *)memchr(p, '\\r', field_end - p)) != NULL) {\n *p = ' ';\n ++p;\n }\n } else {\n PROF_stop(HttpHeaderParse);\n clean();\n return 0;\n }\n }\n\n if (this_line + 1 == field_end && this_line > field_start) {\n debugs(55, warnOnError, \"WARNING: Blank continuation line in HTTP header {\" <<\n getStringPrefix(header_start, hdrLen) << \"}\");\n PROF_stop(HttpHeaderParse);\n clean();\n return 0;\n }\n } while (field_ptr < header_end && (*field_ptr == ' ' || *field_ptr == '\\t'));\n\n if (field_start == field_end) {\n if (field_ptr < header_end) {\n debugs(55, warnOnError, \"WARNING: unparseable HTTP header field near {\" <<\n getStringPrefix(field_start, hdrLen-(field_start-header_start)) << \"}\");\n PROF_stop(HttpHeaderParse);\n clean();\n return 0;\n }\n\n break; /* terminating blank line */\n }\n\n const auto e = HttpHeaderEntry::parse(field_start, field_end, owner);\n if (!e) {\n debugs(55, warnOnError, \"WARNING: unparseable HTTP header field {\" <<\n getStringPrefix(field_start, field_end-field_start) << \"}\");\n debugs(55, warnOnError, \" in {\" << getStringPrefix(header_start, hdrLen) << \"}\");\n\n PROF_stop(HttpHeaderParse);\n clean();\n return 0;\n }\n\n if (e->id == Http::HdrType::CONTENT_LENGTH && !clen.checkField(e->value)) {\n delete e;\n\n if (Config.onoff.relaxed_header_parser)\n continue; // clen has printed any necessary warnings\n\n PROF_stop(HttpHeaderParse);\n clean();\n return 0;\n }\n\n if (e->id == Http::HdrType::OTHER && stringHasWhitespace(e->name.termedBuf())) {\n debugs(55, warnOnError, \"WARNING: found whitespace in HTTP header name {\" <<\n getStringPrefix(field_start, field_end-field_start) << \"}\");\n\n if (!Config.onoff.relaxed_header_parser) {\n delete e;\n PROF_stop(HttpHeaderParse);\n clean();\n return 0;\n }\n }\n\n addEntry(e);\n }\n\n if (clen.headerWideProblem) {\n debugs(55, warnOnError, \"WARNING: \" << clen.headerWideProblem <<\n \" Content-Length field values in\" <<\n Raw(\"header\", header_start, hdrLen));\n }\n\n if (chunked()) {\n // RFC 2616 section 4.4: ignore Content-Length with Transfer-Encoding\n // RFC 7230 section 3.3.3 #3: Transfer-Encoding overwrites Content-Length\n delById(Http::HdrType::CONTENT_LENGTH);\n // and clen state becomes irrelevant\n } else if (clen.sawBad) {\n // ensure our callers do not accidentally see bad Content-Length values\n delById(Http::HdrType::CONTENT_LENGTH);\n conflictingContentLength_ = true; // TODO: Rename to badContentLength_.\n } else if (clen.needsSanitizing) {\n // RFC 7230 section 3.3.2: MUST either reject or ... [sanitize];\n // ensure our callers see a clean Content-Length value or none at all\n delById(Http::HdrType::CONTENT_LENGTH);\n if (clen.sawGood) {\n putInt64(Http::HdrType::CONTENT_LENGTH, clen.value);\n debugs(55, 5, \"sanitized Content-Length to be \" << clen.value);\n }\n }\n\n PROF_stop(HttpHeaderParse);\n return 1; /* even if no fields where found, it is a valid header */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-444'], 'message': 'Enforce token characters for field-name (#700)\n\nRFC 7230 defines field-name as a token. Request splitting and cache\npoisoning attacks have used non-token characters to fool broken HTTP\nagents behind or in front of Squid for years. This change should\nsignificantly reduce that abuse.\n\nIf we discover exceptional situations that need special treatment, the\nrelaxed parser can allow them on a case-by-case basis (while being extra\ncareful about framing-related header fields), just like we already\ntolerate some header whitespace (e.g., between the response header\nfield-name and colon).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: fixExec2Error(int action,\n u_char * var_val,\n u_char var_val_type,\n size_t var_val_len,\n u_char * statP, oid * name, size_t name_len)\n{\n netsnmp_old_extend *exten = NULL;\n unsigned int idx;\n\n idx = name[name_len-1] -1;\n exten = &compatability_entries[ idx ];\n\n#ifndef NETSNMP_NO_WRITE_SUPPORT\n switch (action) {\n case MODE_SET_RESERVE1:\n if (var_val_type != ASN_INTEGER) {\n snmp_log(LOG_ERR, \"Wrong type != int\\n\");\n return SNMP_ERR_WRONGTYPE;\n }\n idx = *((long *) var_val);\n if (idx != 1) {\n snmp_log(LOG_ERR, \"Wrong value != 1\\n\");\n return SNMP_ERR_WRONGVALUE;\n }\n if (!exten || !exten->efix_entry) {\n snmp_log(LOG_ERR, \"No command to run\\n\");\n return SNMP_ERR_GENERR;\n }\n return SNMP_ERR_NOERROR;\n\n case MODE_SET_COMMIT:\n netsnmp_cache_check_and_reload( exten->efix_entry->cache );\n }\n#endif /* !NETSNMP_NO_WRITE_SUPPORT */\n return SNMP_ERR_NOERROR;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-269'], 'message': 'make the extend mib read-only by default'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ctnetlink_parse_tuple_filter(const struct nlattr * const cda[],\n\t\t\t struct nf_conntrack_tuple *tuple, u32 type,\n\t\t\t u_int8_t l3num, struct nf_conntrack_zone *zone,\n\t\t\t u_int32_t flags)\n{\n\tstruct nlattr *tb[CTA_TUPLE_MAX+1];\n\tint err;\n\n\tmemset(tuple, 0, sizeof(*tuple));\n\n\terr = nla_parse_nested_deprecated(tb, CTA_TUPLE_MAX, cda[type],\n\t\t\t\t\t tuple_nla_policy, NULL);\n\tif (err < 0)\n\t\treturn err;\n\n\n\ttuple->src.l3num = l3num;\n\n\tif (flags & CTA_FILTER_FLAG(CTA_IP_DST) ||\n\t flags & CTA_FILTER_FLAG(CTA_IP_SRC)) {\n\t\tif (!tb[CTA_TUPLE_IP])\n\t\t\treturn -EINVAL;\n\n\t\terr = ctnetlink_parse_tuple_ip(tb[CTA_TUPLE_IP], tuple, flags);\n\t\tif (err < 0)\n\t\t\treturn err;\n\t}\n\n\tif (flags & CTA_FILTER_FLAG(CTA_PROTO_NUM)) {\n\t\tif (!tb[CTA_TUPLE_PROTO])\n\t\t\treturn -EINVAL;\n\n\t\terr = ctnetlink_parse_tuple_proto(tb[CTA_TUPLE_PROTO], tuple, flags);\n\t\tif (err < 0)\n\t\t\treturn err;\n\t} else if (flags & CTA_FILTER_FLAG(ALL_CTA_PROTO)) {\n\t\t/* Can't manage proto flags without a protonum */\n\t\treturn -EINVAL;\n\t}\n\n\tif ((flags & CTA_FILTER_FLAG(CTA_TUPLE_ZONE)) && tb[CTA_TUPLE_ZONE]) {\n\t\tif (!zone)\n\t\t\treturn -EINVAL;\n\n\t\terr = ctnetlink_parse_tuple_zone(tb[CTA_TUPLE_ZONE],\n\t\t\t\t\t\t type, zone);\n\t\tif (err < 0)\n\t\t\treturn err;\n\t}\n\n\t/* orig and expect tuples get DIR_ORIGINAL */\n\tif (type == CTA_TUPLE_REPLY)\n\t\ttuple->dst.dir = IP_CT_DIR_REPLY;\n\telse\n\t\ttuple->dst.dir = IP_CT_DIR_ORIGINAL;\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'netfilter: ctnetlink: add a range check for l3/l4 protonum\n\nThe indexes to the nf_nat_l[34]protos arrays come from userspace. So\ncheck the tuple's family, e.g. l3num, when creating the conntrack in\norder to prevent an OOB memory access during setup. Here is an example\nkernel panic on 4.14.180 when userspace passes in an index greater than\nNFPROTO_NUMPROTO.\n\nInternal error: Oops - BUG: 0 [#1] PREEMPT SMP\nModules linked in:...\nProcess poc (pid: 5614, stack limit = 0x00000000a3933121)\nCPU: 4 PID: 5614 Comm: poc Tainted: G S W O 4.14.180-g051355490483\nHardware name: Qualcomm Technologies, Inc. SM8150 V2 PM8150 Google Inc. MSM\ntask: 000000002a3dfffe task.stack: 00000000a3933121\npc : __cfi_check_fail+0x1c/0x24\nlr : __cfi_check_fail+0x1c/0x24\n...\nCall trace:\n__cfi_check_fail+0x1c/0x24\nname_to_dev_t+0x0/0x468\nnfnetlink_parse_nat_setup+0x234/0x258\nctnetlink_parse_nat_setup+0x4c/0x228\nctnetlink_new_conntrack+0x590/0xc40\nnfnetlink_rcv_msg+0x31c/0x4d4\nnetlink_rcv_skb+0x100/0x184\nnfnetlink_rcv+0xf4/0x180\nnetlink_unicast+0x360/0x770\nnetlink_sendmsg+0x5a0/0x6a4\n___sys_sendmsg+0x314/0x46c\nSyS_sendmsg+0xb4/0x108\nel0_svc_naked+0x34/0x38\n\nThis crash is not happening since 5.4+, however, ctnetlink still\nallows for creating entries with unsupported layer 3 protocol number.\n\nFixes: c1d10adb4a521 (\"[NETFILTER]: Add ctnetlink port for nf_conntrack\")\nSigned-off-by: Will McVicker \n[pablo@netfilter.org: rebased original patch on top of nf.git]\nSigned-off-by: Pablo Neira Ayuso '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static BROTLI_INLINE uint32_t GetInsertBase(uint16_t inscode) {\n return kInsBase[inscode];\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'Update (#826)\n\n * IMPORTANT: decoder: fix potential overflow when input chunk is >2GiB\r\n * simplify max Huffman table size calculation\r\n * eliminate symbol duplicates (static arrays in .h files)\r\n * minor combing in research/ code'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void ppp_cp_parse_cr(struct net_device *dev, u16 pid, u8 id,\n\t\t\t unsigned int req_len, const u8 *data)\n{\n\tstatic u8 const valid_accm[6] = { LCP_OPTION_ACCM, 6, 0, 0, 0, 0 };\n\tconst u8 *opt;\n\tu8 *out;\n\tunsigned int len = req_len, nak_len = 0, rej_len = 0;\n\n\tif (!(out = kmalloc(len, GFP_ATOMIC))) {\n\t\tdev->stats.rx_dropped++;\n\t\treturn;\t/* out of memory, ignore CR packet */\n\t}\n\n\tfor (opt = data; len; len -= opt[1], opt += opt[1]) {\n\t\tif (len < 2 || len < opt[1]) {\n\t\t\tdev->stats.rx_errors++;\n\t\t\tkfree(out);\n\t\t\treturn; /* bad packet, drop silently */\n\t\t}\n\n\t\tif (pid == PID_LCP)\n\t\t\tswitch (opt[0]) {\n\t\t\tcase LCP_OPTION_MRU:\n\t\t\t\tcontinue; /* MRU always OK and > 1500 bytes? */\n\n\t\t\tcase LCP_OPTION_ACCM: /* async control character map */\n\t\t\t\tif (!memcmp(opt, valid_accm,\n\t\t\t\t\t sizeof(valid_accm)))\n\t\t\t\t\tcontinue;\n\t\t\t\tif (!rej_len) { /* NAK it */\n\t\t\t\t\tmemcpy(out + nak_len, valid_accm,\n\t\t\t\t\t sizeof(valid_accm));\n\t\t\t\t\tnak_len += sizeof(valid_accm);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase LCP_OPTION_MAGIC:\n\t\t\t\tif (opt[1] != 6 || (!opt[2] && !opt[3] &&\n\t\t\t\t\t\t !opt[4] && !opt[5]))\n\t\t\t\t\tbreak; /* reject invalid magic number */\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t/* reject this option */\n\t\tmemcpy(out + rej_len, opt, opt[1]);\n\t\trej_len += opt[1];\n\t}\n\n\tif (rej_len)\n\t\tppp_cp_event(dev, pid, RCR_BAD, CP_CONF_REJ, id, rej_len, out);\n\telse if (nak_len)\n\t\tppp_cp_event(dev, pid, RCR_BAD, CP_CONF_NAK, id, nak_len, out);\n\telse\n\t\tppp_cp_event(dev, pid, RCR_GOOD, CP_CONF_ACK, id, req_len, data);\n\n\tkfree(out);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'hdlc_ppp: add range checks in ppp_cp_parse_cr()\n\nThere are a couple bugs here:\n1) If opt[1] is zero then this results in a forever loop. If the value\n is less than 2 then it is invalid.\n2) It assumes that \"len\" is more than sizeof(valid_accm) or 6 which can\n result in memory corruption.\n\nIn the case of LCP_OPTION_ACCM, then we should check \"opt[1]\" instead\nof \"len\" because, if \"opt[1]\" is less than sizeof(valid_accm) then\n\"nak_len\" gets out of sync and it can lead to memory corruption in the\nnext iterations through the loop. In case of LCP_OPTION_MAGIC, the\nonly valid value for opt[1] is 6, but the code is trying to log invalid\ndata so we should only discard the data when \"len\" is less than 6\nbecause that leads to a read overflow.\n\nReported-by: ChenNan Of Chaitin Security Research Lab \nFixes: e022c2f07ae5 (\"WAN: new synchronous PPP implementation for generic HDLC.\")\nSigned-off-by: Dan Carpenter \nReviewed-by: Eric Dumazet \nReviewed-by: Greg Kroah-Hartman \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void vgacon_scrolldelta(struct vc_data *c, int lines)\n{\n\tint start, end, count, soff;\n\n\tif (!lines) {\n\t\tvgacon_restore_screen(c);\n\t\treturn;\n\t}\n\n\tif (!vgacon_scrollback_cur->data)\n\t\treturn;\n\n\tif (!vgacon_scrollback_cur->save) {\n\t\tvgacon_cursor(c, CM_ERASE);\n\t\tvgacon_save_screen(c);\n\t\tc->vc_origin = (unsigned long)c->vc_screenbuf;\n\t\tvgacon_scrollback_cur->save = 1;\n\t}\n\n\tvgacon_scrollback_cur->restore = 0;\n\tstart = vgacon_scrollback_cur->cur + lines;\n\tend = start + abs(lines);\n\n\tif (start < 0)\n\t\tstart = 0;\n\n\tif (start > vgacon_scrollback_cur->cnt)\n\t\tstart = vgacon_scrollback_cur->cnt;\n\n\tif (end < 0)\n\t\tend = 0;\n\n\tif (end > vgacon_scrollback_cur->cnt)\n\t\tend = vgacon_scrollback_cur->cnt;\n\n\tvgacon_scrollback_cur->cur = start;\n\tcount = end - start;\n\tsoff = vgacon_scrollback_cur->tail -\n\t\t((vgacon_scrollback_cur->cnt - end) * c->vc_size_row);\n\tsoff -= count * c->vc_size_row;\n\n\tif (soff < 0)\n\t\tsoff += vgacon_scrollback_cur->size;\n\n\tcount = vgacon_scrollback_cur->cnt - start;\n\n\tif (count > c->vc_rows)\n\t\tcount = c->vc_rows;\n\n\tif (count) {\n\t\tint copysize;\n\n\t\tint diff = c->vc_rows - count;\n\t\tvoid *d = (void *) c->vc_visible_origin;\n\t\tvoid *s = (void *) c->vc_screenbuf;\n\n\t\tcount *= c->vc_size_row;\n\t\t/* how much memory to end of buffer left? */\n\t\tcopysize = min(count, vgacon_scrollback_cur->size - soff);\n\t\tscr_memcpyw(d, vgacon_scrollback_cur->data + soff, copysize);\n\t\td += copysize;\n\t\tcount -= copysize;\n\n\t\tif (count) {\n\t\t\tscr_memcpyw(d, vgacon_scrollback_cur->data, count);\n\t\t\td += count;\n\t\t}\n\n\t\tif (diff)\n\t\t\tscr_memcpyw(d, s, diff * c->vc_size_row);\n\t} else\n\t\tvgacon_cursor(c, CM_MOVE);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'vgacon: remove software scrollback support\n\nYunhai Zhang recently fixed a VGA software scrollback bug in commit\nebfdfeeae8c0 (\"vgacon: Fix for missing check in scrollback handling\"),\nbut that then made people look more closely at some of this code, and\nthere were more problems on the vgacon side, but also the fbcon software\nscrollback.\n\nWe don't really have anybody who maintains this code - probably because\nnobody actually _uses_ it any more. Sure, people still use both VGA and\nthe framebuffer consoles, but they are no longer the main user\ninterfaces to the kernel, and haven't been for decades, so these kinds\nof extra features end up bitrotting and not really being used.\n\nSo rather than try to maintain a likely unused set of code, I'll just\naggressively remove it, and see if anybody even notices. Maybe there\nare people who haven't jumped on the whole GUI badnwagon yet, and think\nit's just a fad. And maybe those people use the scrollback code.\n\nIf that turns out to be the case, we can resurrect this again, once\nwe've found the sucker^Wmaintainer for it who actually uses it.\n\nReported-by: NopNop Nop \nTested-by: Willy Tarreau \nCc: \u5f20\u4e91\u6d77 \nAcked-by: Andy Lutomirski \nAcked-by: Willy Tarreau \nReviewed-by: Greg Kroah-Hartman \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static ssize_t do_rbd_remove(struct bus_type *bus,\n\t\t\t const char *buf,\n\t\t\t size_t count)\n{\n\tstruct rbd_device *rbd_dev = NULL;\n\tstruct list_head *tmp;\n\tint dev_id;\n\tchar opt_buf[6];\n\tbool force = false;\n\tint ret;\n\n\tdev_id = -1;\n\topt_buf[0] = '\\0';\n\tsscanf(buf, \"%d %5s\", &dev_id, opt_buf);\n\tif (dev_id < 0) {\n\t\tpr_err(\"dev_id out of range\\n\");\n\t\treturn -EINVAL;\n\t}\n\tif (opt_buf[0] != '\\0') {\n\t\tif (!strcmp(opt_buf, \"force\")) {\n\t\t\tforce = true;\n\t\t} else {\n\t\t\tpr_err(\"bad remove option at '%s'\\n\", opt_buf);\n\t\t\treturn -EINVAL;\n\t\t}\n\t}\n\n\tret = -ENOENT;\n\tspin_lock(&rbd_dev_list_lock);\n\tlist_for_each(tmp, &rbd_dev_list) {\n\t\trbd_dev = list_entry(tmp, struct rbd_device, node);\n\t\tif (rbd_dev->dev_id == dev_id) {\n\t\t\tret = 0;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (!ret) {\n\t\tspin_lock_irq(&rbd_dev->lock);\n\t\tif (rbd_dev->open_count && !force)\n\t\t\tret = -EBUSY;\n\t\telse if (test_and_set_bit(RBD_DEV_FLAG_REMOVING,\n\t\t\t\t\t &rbd_dev->flags))\n\t\t\tret = -EINPROGRESS;\n\t\tspin_unlock_irq(&rbd_dev->lock);\n\t}\n\tspin_unlock(&rbd_dev_list_lock);\n\tif (ret)\n\t\treturn ret;\n\n\tif (force) {\n\t\t/*\n\t\t * Prevent new IO from being queued and wait for existing\n\t\t * IO to complete/fail.\n\t\t */\n\t\tblk_mq_freeze_queue(rbd_dev->disk->queue);\n\t\tblk_set_queue_dying(rbd_dev->disk->queue);\n\t}\n\n\tdel_gendisk(rbd_dev->disk);\n\tspin_lock(&rbd_dev_list_lock);\n\tlist_del_init(&rbd_dev->node);\n\tspin_unlock(&rbd_dev_list_lock);\n\tdevice_del(&rbd_dev->dev);\n\n\trbd_dev_image_unlock(rbd_dev);\n\trbd_dev_device_release(rbd_dev);\n\trbd_dev_image_release(rbd_dev);\n\trbd_dev_destroy(rbd_dev);\n\treturn count;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-863'], 'message': 'rbd: require global CAP_SYS_ADMIN for mapping and unmapping\n\nIt turns out that currently we rely only on sysfs attribute\npermissions:\n\n $ ll /sys/bus/rbd/{add*,remove*}\n --w------- 1 root root 4096 Sep 3 20:37 /sys/bus/rbd/add\n --w------- 1 root root 4096 Sep 3 20:37 /sys/bus/rbd/add_single_major\n --w------- 1 root root 4096 Sep 3 20:37 /sys/bus/rbd/remove\n --w------- 1 root root 4096 Sep 3 20:38 /sys/bus/rbd/remove_single_major\n\nThis means that images can be mapped and unmapped (i.e. block devices\ncan be created and deleted) by a UID 0 process even after it drops all\nprivileges or by any process with CAP_DAC_OVERRIDE in its user namespace\nas long as UID 0 is mapped into that user namespace.\n\nBe consistent with other virtual block devices (loop, nbd, dm, md, etc)\nand require CAP_SYS_ADMIN in the initial user namespace for mapping and\nunmapping, and also for dumping the configuration string and refreshing\nthe image header.\n\nCc: stable@vger.kernel.org\nSigned-off-by: Ilya Dryomov \nReviewed-by: Jeff Layton '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool bt_att_cancel(struct bt_att *att, unsigned int id)\n{\n\tconst struct queue_entry *entry;\n\tstruct att_send_op *op;\n\n\tif (!att || !id)\n\t\treturn false;\n\n\t/* Lookuo request on each channel first */\n\tfor (entry = queue_get_entries(att->chans); entry;\n\t\t\t\t\t\tentry = entry->next) {\n\t\tstruct bt_att_chan *chan = entry->data;\n\n\t\tif (bt_att_chan_cancel(chan, id))\n\t\t\treturn true;\n\t}\n\n\top = queue_remove_if(att->req_queue, match_op_id, UINT_TO_PTR(id));\n\tif (op)\n\t\tgoto done;\n\n\top = queue_remove_if(att->ind_queue, match_op_id, UINT_TO_PTR(id));\n\tif (op)\n\t\tgoto done;\n\n\top = queue_remove_if(att->write_queue, match_op_id, UINT_TO_PTR(id));\n\tif (op)\n\t\tgoto done;\n\n\tif (!op)\n\t\treturn false;\n\ndone:\n\tdestroy_att_send_op(op);\n\n\twakeup_writer(att);\n\n\treturn true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'shared/att: Fix possible crash on disconnect\n\nIf there are pending request while disconnecting they would be notified\nbut clients may endup being freed in the proccess which will then be\ncalling bt_att_cancel to cancal its requests causing the following\ntrace:\n\nInvalid read of size 4\n at 0x1D894C: enable_ccc_callback (gatt-client.c:1627)\n by 0x1D247B: disc_att_send_op (att.c:417)\n by 0x1CCC17: queue_remove_all (queue.c:354)\n by 0x1D47B7: disconnect_cb (att.c:635)\n by 0x1E0707: watch_callback (io-glib.c:170)\n by 0x48E963B: g_main_context_dispatch (in /usr/lib/libglib-2.0.so.0.6400.4)\n by 0x48E9AC7: ??? (in /usr/lib/libglib-2.0.so.0.6400.4)\n by 0x48E9ECF: g_main_loop_run (in /usr/lib/libglib-2.0.so.0.6400.4)\n by 0x1E0E97: mainloop_run (mainloop-glib.c:79)\n by 0x1E13B3: mainloop_run_with_signal (mainloop-notify.c:201)\n by 0x12BC3B: main (main.c:770)\n Address 0x7d40a28 is 24 bytes inside a block of size 32 free'd\n at 0x484A2E0: free (vg_replace_malloc.c:540)\n by 0x1CCC17: queue_remove_all (queue.c:354)\n by 0x1CCC83: queue_destroy (queue.c:73)\n by 0x1D7DD7: bt_gatt_client_free (gatt-client.c:2209)\n by 0x16497B: batt_free (battery.c:77)\n by 0x16497B: batt_remove (battery.c:286)\n by 0x1A0013: service_remove (service.c:176)\n by 0x1A9B7B: device_remove_gatt_service (device.c:3691)\n by 0x1A9B7B: gatt_service_removed (device.c:3805)\n by 0x1CC90B: queue_foreach (queue.c:220)\n by 0x1DE27B: notify_service_changed.isra.0.part.0 (gatt-db.c:369)\n by 0x1DE387: notify_service_changed (gatt-db.c:361)\n by 0x1DE387: gatt_db_service_destroy (gatt-db.c:385)\n by 0x1DE3EF: gatt_db_remove_service (gatt-db.c:519)\n by 0x1D674F: discovery_op_complete (gatt-client.c:388)\n by 0x1D6877: discover_primary_cb (gatt-client.c:1260)\n by 0x1E220B: discovery_op_complete (gatt-helpers.c:628)\n by 0x1E249B: read_by_grp_type_cb (gatt-helpers.c:730)\n by 0x1D247B: disc_att_send_op (att.c:417)\n by 0x1CCC17: queue_remove_all (queue.c:354)\n by 0x1D47B7: disconnect_cb (att.c:635)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: dissect_fb_zero_tag(tvbuff_t *tvb, packet_info *pinfo, proto_tree *fb_zero_tree, guint offset, guint32 tag_number){\n guint32 tag_offset_start = offset + tag_number*4*2;\n guint32 tag_offset = 0, total_tag_len = 0;\n gint32 tag_len;\n\n while(tag_number){\n proto_tree *tag_tree, *ti_len, *ti_tag, *ti_type;\n guint32 offset_end, tag;\n const guint8* tag_str;\n\n ti_tag = proto_tree_add_item(fb_zero_tree, hf_fb_zero_tags, tvb, offset, 8, ENC_NA);\n tag_tree = proto_item_add_subtree(ti_tag, ett_fb_zero_tag_value);\n ti_type = proto_tree_add_item_ret_string(tag_tree, hf_fb_zero_tag_type, tvb, offset, 4, ENC_ASCII|ENC_NA, wmem_packet_scope(), &tag_str);\n tag = tvb_get_ntohl(tvb, offset);\n proto_item_append_text(ti_type, \" (%s)\", val_to_str(tag, tag_vals, \"Unknown\"));\n proto_item_append_text(ti_tag, \": %s (%s)\", tag_str, val_to_str(tag, tag_vals, \"Unknown\"));\n offset += 4;\n\n proto_tree_add_item(tag_tree, hf_fb_zero_tag_offset_end, tvb, offset, 4, ENC_LITTLE_ENDIAN);\n offset_end = tvb_get_letohl(tvb, offset);\n\n tag_len = offset_end - tag_offset;\n total_tag_len += tag_len;\n ti_len = proto_tree_add_uint(tag_tree, hf_fb_zero_tag_length, tvb, offset, 4, tag_len);\n proto_item_append_text(ti_tag, \" (l=%u)\", tag_len);\n proto_item_set_generated(ti_len);\n offset += 4;\n\n /* Fix issue with CRT.. (Fragmentation ?) */\n if( tag_len > tvb_reported_length_remaining(tvb, tag_offset_start + tag_offset)){\n tag_len = tvb_reported_length_remaining(tvb, tag_offset_start + tag_offset);\n offset_end = tag_offset + tag_len;\n expert_add_info(pinfo, ti_len, &ei_fb_zero_tag_length);\n }\n\n proto_tree_add_item(tag_tree, hf_fb_zero_tag_value, tvb, tag_offset_start + tag_offset, tag_len, ENC_NA);\n\n switch(tag){\n case TAG_SNI:\n proto_tree_add_item_ret_string(tag_tree, hf_fb_zero_tag_sni, tvb, tag_offset_start + tag_offset, tag_len, ENC_ASCII|ENC_NA, wmem_packet_scope(), &tag_str);\n proto_item_append_text(ti_tag, \": %s\", tag_str);\n tag_offset += tag_len;\n break;\n case TAG_VERS:\n proto_tree_add_item_ret_string(tag_tree, hf_fb_zero_tag_vers, tvb, tag_offset_start + tag_offset, 4, ENC_ASCII|ENC_NA, wmem_packet_scope(), &tag_str);\n proto_item_append_text(ti_tag, \": %s\", tag_str);\n tag_offset += 4;\n break;\n case TAG_SNO:\n proto_tree_add_item(tag_tree, hf_fb_zero_tag_sno, tvb, tag_offset_start + tag_offset, tag_len, ENC_NA);\n tag_offset += tag_len;\n break;\n case TAG_AEAD:\n while(offset_end - tag_offset >= 4){\n proto_tree *ti_aead;\n ti_aead = proto_tree_add_item(tag_tree, hf_fb_zero_tag_aead, tvb, tag_offset_start + tag_offset, 4, ENC_ASCII|ENC_NA);\n proto_item_append_text(ti_aead, \" (%s)\", val_to_str(tvb_get_ntohl(tvb, tag_offset_start + tag_offset), tag_aead_vals, \"Unknown\"));\n proto_item_append_text(ti_tag, \", %s\", val_to_str(tvb_get_ntohl(tvb, tag_offset_start + tag_offset), tag_aead_vals, \"Unknown\"));\n tag_offset += 4;\n }\n break;\n case TAG_SCID:\n proto_tree_add_item(tag_tree, hf_fb_zero_tag_scid, tvb, tag_offset_start + tag_offset, tag_len, ENC_NA);\n tag_offset += tag_len;\n break;\n case TAG_TIME:\n proto_tree_add_item(tag_tree, hf_fb_zero_tag_time, tvb, tag_offset_start + tag_offset, 4, ENC_LITTLE_ENDIAN);\n proto_item_append_text(ti_tag, \": %u\", tvb_get_letohl(tvb, tag_offset_start + tag_offset));\n tag_offset += 4;\n break;\n case TAG_ALPN:\n proto_tree_add_item_ret_string(tag_tree, hf_fb_zero_tag_alpn, tvb, tag_offset_start + tag_offset, 4, ENC_ASCII|ENC_NA, wmem_packet_scope(), &tag_str);\n proto_item_append_text(ti_tag, \": %s\", tag_str);\n tag_offset += 4;\n break;\n case TAG_PUBS:\n /*TODO FIX: 24 Length + Pubs key?.. ! */\n proto_tree_add_item(tag_tree, hf_fb_zero_tag_pubs, tvb, tag_offset_start + tag_offset, 2, ENC_LITTLE_ENDIAN);\n tag_offset += 2;\n while(offset_end - tag_offset >= 3){\n proto_tree_add_item(tag_tree, hf_fb_zero_tag_pubs, tvb, tag_offset_start + tag_offset, 3, ENC_LITTLE_ENDIAN);\n tag_offset += 3;\n }\n break;\n case TAG_KEXS:\n while(offset_end - tag_offset >= 4){\n proto_tree *ti_kexs;\n ti_kexs = proto_tree_add_item(tag_tree, hf_fb_zero_tag_kexs, tvb, tag_offset_start + tag_offset, 4, ENC_ASCII|ENC_NA);\n proto_item_append_text(ti_kexs, \" (%s)\", val_to_str(tvb_get_ntohl(tvb, tag_offset_start + tag_offset), tag_kexs_vals, \"Unknown\"));\n proto_item_append_text(ti_tag, \", %s\", val_to_str(tvb_get_ntohl(tvb, tag_offset_start + tag_offset), tag_kexs_vals, \"Unknown\"));\n tag_offset += 4;\n }\n break;\n case TAG_NONC:\n /*TODO: Enhance display: 32 bytes consisting of 4 bytes of timestamp (big-endian, UNIX epoch seconds), 8 bytes of server orbit and 20 bytes of random data. */\n proto_tree_add_item(tag_tree, hf_fb_zero_tag_nonc, tvb, tag_offset_start + tag_offset, 32, ENC_NA);\n tag_offset += 32;\n break;\n\n default:\n proto_tree_add_item(tag_tree, hf_fb_zero_tag_unknown, tvb, tag_offset_start + tag_offset, tag_len, ENC_NA);\n expert_add_info_format(pinfo, ti_tag, &ei_fb_zero_tag_undecoded,\n \"Dissector for FB Zero Tag\"\n \" %s (%s) code not implemented, Contact\"\n \" Wireshark developers if you want this supported\", tvb_get_string_enc(wmem_packet_scope(), tvb, offset-8, 4, ENC_ASCII|ENC_NA), val_to_str(tag, tag_vals, \"Unknown\"));\n tag_offset += tag_len;\n break;\n }\n\n if(tag_offset != offset_end){\n /* Wrong Tag len... */\n proto_tree_add_expert(tag_tree, pinfo, &ei_fb_zero_tag_unknown, tvb, tag_offset_start + tag_offset, offset_end - tag_offset);\n tag_offset = offset_end;\n }\n\n tag_number--;\n }\n return offset + total_tag_len;\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': 'FBZERO: Make sure our offset advances.\n\nMake sure our offset advances so that we don't infinitely loop.\nFixes #16887.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void agent_connect(UdscsConnection *conn)\n{\n struct agent_data *agent_data;\n agent_data = g_new0(struct agent_data, 1);\n GError *err = NULL;\n\n if (session_info) {\n PidUid pid_uid = vdagent_connection_get_peer_pid_uid(VDAGENT_CONNECTION(conn), &err);\n if (err || pid_uid.pid <= 0) {\n static const char msg[] = \"Could not get peer PID, disconnecting new client\";\n if (err) {\n syslog(LOG_ERR, \"%s: %s\", msg, err->message);\n g_error_free(err);\n } else {\n syslog(LOG_ERR, \"%s\", msg);\n }\n agent_data_destroy(agent_data);\n udscs_server_destroy_connection(server, conn);\n return;\n }\n\n agent_data->session = session_info_session_for_pid(session_info, pid_uid.pid);\n\n uid_t session_uid = session_info_uid_for_session(session_info, agent_data->session);\n\n /* Check that the UID of the PID did not change, this should be done after\n * computing the session to avoid race conditions.\n * This can happen as vdagent_connection_get_peer_pid_uid get information\n * from the time of creating the socket, but the process in the meantime\n * have been replaced */\n if (!check_uid_of_pid(pid_uid.pid, pid_uid.uid) ||\n /* Check that the user launching the Agent is the same as session one\n * or root user.\n * This prevents session hijacks from other users. */\n (pid_uid.uid != 0 && pid_uid.uid != session_uid)) {\n syslog(LOG_ERR, \"UID mismatch: UID=%u PID=%u suid=%u\", pid_uid.uid,\n pid_uid.pid, session_uid);\n agent_data_destroy(agent_data);\n udscs_server_destroy_connection(server, conn);\n return;\n }\n }\n\n g_object_set_data_full(G_OBJECT(conn), \"agent_data\", agent_data,\n (GDestroyNotify) agent_data_destroy);\n udscs_write(conn, VDAGENTD_VERSION, 0, 0,\n (uint8_t *)VERSION, strlen(VERSION) + 1);\n update_active_session_connection(conn);\n\n if (device_info) {\n forward_data_to_session_agent(VDAGENTD_GRAPHICS_DEVICE_INFO,\n (uint8_t *) device_info, device_info_size);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-770'], 'message': 'vdagentd: Limit number of agents per session to 1\n\nSigned-off-by: Frediano Ziglio \nAcked-by: Uri Lublin '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: CallResult Interpreter::interpretFunction(\n Runtime *runtime,\n InterpreterState &state) {\n // The interepter is re-entrant and also saves/restores its IP via the runtime\n // whenever a call out is made (see the CAPTURE_IP_* macros). As such, failure\n // to preserve the IP across calls to interpeterFunction() disrupt interpreter\n // calls further up the C++ callstack. The RAII utility class below makes sure\n // we always do this correctly.\n //\n // TODO: The IPs stored in the C++ callstack via this holder will generally be\n // the same as in the JS stack frames via the Saved IP field. We can probably\n // get rid of one of these redundant stores. Doing this isn't completely\n // trivial as there are currently cases where we re-enter the interpreter\n // without calling Runtime::saveCallerIPInStackFrame(), and there are features\n // (I think mostly the debugger + stack traces) which implicitly rely on\n // this behavior. At least their tests break if this behavior is not\n // preserved.\n struct IPSaver {\n IPSaver(Runtime *runtime)\n : ip_(runtime->getCurrentIP()), runtime_(runtime) {}\n\n ~IPSaver() {\n runtime_->setCurrentIP(ip_);\n }\n\n private:\n const Inst *ip_;\n Runtime *runtime_;\n };\n IPSaver ipSaver(runtime);\n\n#ifndef HERMES_ENABLE_DEBUGGER\n static_assert(!SingleStep, \"can't use single-step mode without the debugger\");\n#endif\n // Make sure that the cache can use an optimization by avoiding a branch to\n // access the property storage.\n static_assert(\n HiddenClass::kDictionaryThreshold <=\n SegmentedArray::kValueToSegmentThreshold,\n \"Cannot avoid branches in cache check if the dictionary \"\n \"crossover point is larger than the inline storage\");\n\n CodeBlock *curCodeBlock = state.codeBlock;\n const Inst *ip = nullptr;\n // Holds runtime->currentFrame_.ptr()-1 which is the first local\n // register. This eliminates the indirect load from Runtime and the -1 offset.\n PinnedHermesValue *frameRegs;\n // Strictness of current function.\n bool strictMode;\n // Default flags when accessing properties.\n PropOpFlags defaultPropOpFlags;\n\n// These CAPTURE_IP* macros should wrap around any major calls out of the\n// interpeter loop. They stash and retrieve the IP via the current Runtime\n// allowing the IP to be externally observed and even altered to change the flow\n// of execution. Explicitly saving AND restoring the IP from the Runtime in this\n// way means the C++ compiler will keep IP in a register within the rest of the\n// interpeter loop.\n//\n// When assertions are enabled we take the extra step of \"invalidating\" the IP\n// between captures so we can detect if it's erroneously accessed.\n//\n// In some cases we explicitly don't want to invalidate the IP and instead want\n// it to stay set. For this we use the *NO_INVALIDATE variants. This comes up\n// when we're performing a call operation which may re-enter the interpeter\n// loop, and so need the IP available for the saveCallerIPInStackFrame() call\n// when we next enter.\n#define CAPTURE_IP_ASSIGN_NO_INVALIDATE(dst, expr) \\\n runtime->setCurrentIP(ip); \\\n dst = expr; \\\n ip = runtime->getCurrentIP();\n\n#ifdef NDEBUG\n\n#define CAPTURE_IP(expr) \\\n runtime->setCurrentIP(ip); \\\n (void)expr; \\\n ip = runtime->getCurrentIP();\n\n#define CAPTURE_IP_ASSIGN(dst, expr) CAPTURE_IP_ASSIGN_NO_INVALIDATE(dst, expr)\n\n#else // !NDEBUG\n\n#define CAPTURE_IP(expr) \\\n runtime->setCurrentIP(ip); \\\n (void)expr; \\\n ip = runtime->getCurrentIP(); \\\n runtime->invalidateCurrentIP();\n\n#define CAPTURE_IP_ASSIGN(dst, expr) \\\n runtime->setCurrentIP(ip); \\\n dst = expr; \\\n ip = runtime->getCurrentIP(); \\\n runtime->invalidateCurrentIP();\n\n#endif // NDEBUG\n\n LLVM_DEBUG(dbgs() << \"interpretFunction() called\\n\");\n\n ScopedNativeDepthTracker depthTracker{runtime};\n if (LLVM_UNLIKELY(depthTracker.overflowed())) {\n return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack);\n }\n\n if (!SingleStep) {\n if (auto jitPtr = runtime->jitContext_.compile(runtime, curCodeBlock)) {\n return (*jitPtr)(runtime);\n }\n }\n\n GCScope gcScope(runtime);\n // Avoid allocating a handle dynamically by reusing this one.\n MutableHandle<> tmpHandle(runtime);\n CallResult res{ExecutionStatus::EXCEPTION};\n CallResult> resPH{ExecutionStatus::EXCEPTION};\n CallResult> resArgs{ExecutionStatus::EXCEPTION};\n CallResult boolRes{ExecutionStatus::EXCEPTION};\n\n // Mark the gcScope so we can clear all allocated handles.\n // Remember how many handles the scope has so we can clear them in the loop.\n static constexpr unsigned KEEP_HANDLES = 1;\n assert(\n gcScope.getHandleCountDbg() == KEEP_HANDLES &&\n \"scope has unexpected number of handles\");\n\n INIT_OPCODE_PROFILER;\n\n#if !defined(HERMESVM_PROFILER_EXTERN)\ntailCall:\n#endif\n PROFILER_ENTER_FUNCTION(curCodeBlock);\n\n#ifdef HERMES_ENABLE_DEBUGGER\n runtime->getDebugger().willEnterCodeBlock(curCodeBlock);\n#endif\n\n runtime->getCodeCoverageProfiler().markExecuted(runtime, curCodeBlock);\n\n // Update function executionCount_ count\n curCodeBlock->incrementExecutionCount();\n\n if (!SingleStep) {\n auto newFrame = runtime->setCurrentFrameToTopOfStack();\n runtime->saveCallerIPInStackFrame();\n#ifndef NDEBUG\n runtime->invalidateCurrentIP();\n#endif\n\n // Point frameRegs to the first register in the new frame. Note that at this\n // moment technically it points above the top of the stack, but we are never\n // going to access it.\n frameRegs = &newFrame.getFirstLocalRef();\n\n#ifndef NDEBUG\n LLVM_DEBUG(\n dbgs() << \"function entry: stackLevel=\" << runtime->getStackLevel()\n << \", argCount=\" << runtime->getCurrentFrame().getArgCount()\n << \", frameSize=\" << curCodeBlock->getFrameSize() << \"\\n\");\n\n LLVM_DEBUG(\n dbgs() << \" callee \"\n << DumpHermesValue(\n runtime->getCurrentFrame().getCalleeClosureOrCBRef())\n << \"\\n\");\n LLVM_DEBUG(\n dbgs() << \" this \"\n << DumpHermesValue(runtime->getCurrentFrame().getThisArgRef())\n << \"\\n\");\n for (uint32_t i = 0; i != runtime->getCurrentFrame()->getArgCount(); ++i) {\n LLVM_DEBUG(\n dbgs() << \" \" << llvh::format_decimal(i, 4) << \" \"\n << DumpHermesValue(runtime->getCurrentFrame().getArgRef(i))\n << \"\\n\");\n }\n#endif\n\n // Allocate the registers for the new frame.\n if (LLVM_UNLIKELY(!runtime->checkAndAllocStack(\n curCodeBlock->getFrameSize() +\n StackFrameLayout::CalleeExtraRegistersAtStart,\n HermesValue::encodeUndefinedValue())))\n goto stackOverflow;\n\n ip = (Inst const *)curCodeBlock->begin();\n\n // Check for invalid invocation.\n if (LLVM_UNLIKELY(curCodeBlock->getHeaderFlags().isCallProhibited(\n newFrame.isConstructorCall()))) {\n if (!newFrame.isConstructorCall()) {\n CAPTURE_IP(\n runtime->raiseTypeError(\"Class constructor invoked without new\"));\n } else {\n CAPTURE_IP(runtime->raiseTypeError(\"Function is not a constructor\"));\n }\n goto handleExceptionInParent;\n }\n } else {\n // Point frameRegs to the first register in the frame.\n frameRegs = &runtime->getCurrentFrame().getFirstLocalRef();\n ip = (Inst const *)(curCodeBlock->begin() + state.offset);\n }\n\n assert((const uint8_t *)ip < curCodeBlock->end() && \"CodeBlock is empty\");\n\n INIT_STATE_FOR_CODEBLOCK(curCodeBlock);\n\n#define BEFORE_OP_CODE \\\n { \\\n UPDATE_OPCODE_TIME_SPENT; \\\n HERMES_SLOW_ASSERT( \\\n curCodeBlock->contains(ip) && \"curCodeBlock must contain ip\"); \\\n HERMES_SLOW_ASSERT((printDebugInfo(curCodeBlock, frameRegs, ip), true)); \\\n HERMES_SLOW_ASSERT( \\\n gcScope.getHandleCountDbg() == KEEP_HANDLES && \\\n \"unaccounted handles were created\"); \\\n HERMES_SLOW_ASSERT(tmpHandle->isUndefined() && \"tmpHandle not cleared\"); \\\n RECORD_OPCODE_START_TIME; \\\n INC_OPCODE_COUNT; \\\n }\n\n#ifdef HERMESVM_INDIRECT_THREADING\n static void *opcodeDispatch[] = {\n#define DEFINE_OPCODE(name) &&case_##name,\n#include \"hermes/BCGen/HBC/BytecodeList.def\"\n &&case__last};\n\n#define CASE(name) case_##name:\n#define DISPATCH \\\n BEFORE_OP_CODE; \\\n if (SingleStep) { \\\n state.codeBlock = curCodeBlock; \\\n state.offset = CUROFFSET; \\\n return HermesValue::encodeUndefinedValue(); \\\n } \\\n goto *opcodeDispatch[(unsigned)ip->opCode]\n\n#else // HERMESVM_INDIRECT_THREADING\n\n#define CASE(name) case OpCode::name:\n#define DISPATCH \\\n if (SingleStep) { \\\n state.codeBlock = curCodeBlock; \\\n state.offset = CUROFFSET; \\\n return HermesValue::encodeUndefinedValue(); \\\n } \\\n continue\n\n#endif // HERMESVM_INDIRECT_THREADING\n\n#define RUN_DEBUGGER_ASYNC_BREAK(flags) \\\n do { \\\n CAPTURE_IP_ASSIGN( \\\n auto dRes, \\\n runDebuggerUpdatingState( \\\n (uint8_t)(flags) & \\\n (uint8_t)Runtime::AsyncBreakReasonBits::DebuggerExplicit \\\n ? Debugger::RunReason::AsyncBreakExplicit \\\n : Debugger::RunReason::AsyncBreakImplicit, \\\n runtime, \\\n curCodeBlock, \\\n ip, \\\n frameRegs)); \\\n if (dRes == ExecutionStatus::EXCEPTION) \\\n goto exception; \\\n } while (0)\n\n for (;;) {\n BEFORE_OP_CODE;\n\n#ifdef HERMESVM_INDIRECT_THREADING\n goto *opcodeDispatch[(unsigned)ip->opCode];\n#else\n switch (ip->opCode)\n#endif\n {\n const Inst *nextIP;\n uint32_t idVal;\n bool tryProp;\n uint32_t callArgCount;\n // This is HermesValue::getRaw(), since HermesValue cannot be assigned\n // to. It is meant to be used only for very short durations, in the\n // dispatch of call instructions, when there is definitely no possibility\n // of a GC.\n HermesValue::RawType callNewTarget;\n\n/// Handle an opcode \\p name with an out-of-line implementation in a function\n/// ExecutionStatus caseName(\n/// Runtime *,\n/// PinnedHermesValue *frameRegs,\n/// Inst *ip)\n#define CASE_OUTOFLINE(name) \\\n CASE(name) { \\\n CAPTURE_IP_ASSIGN(auto res, case##name(runtime, frameRegs, ip)); \\\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { \\\n goto exception; \\\n } \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n/// Implement a binary arithmetic instruction with a fast path where both\n/// operands are numbers.\n/// \\param name the name of the instruction. The fast path case will have a\n/// \"n\" appended to the name.\n/// \\param oper the C++ operator to use to actually perform the arithmetic\n/// operation.\n#define BINOP(name, oper) \\\n CASE(name) { \\\n if (LLVM_LIKELY(O2REG(name).isNumber() && O3REG(name).isNumber())) { \\\n /* Fast-path. */ \\\n CASE(name##N) { \\\n O1REG(name) = HermesValue::encodeDoubleValue( \\\n oper(O2REG(name).getNumber(), O3REG(name).getNumber())); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n } \\\n } \\\n CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O2REG(name)))); \\\n if (res == ExecutionStatus::EXCEPTION) \\\n goto exception; \\\n double left = res->getDouble(); \\\n CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O3REG(name)))); \\\n if (res == ExecutionStatus::EXCEPTION) \\\n goto exception; \\\n O1REG(name) = \\\n HermesValue::encodeDoubleValue(oper(left, res->getDouble())); \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n/// Implement a shift instruction with a fast path where both\n/// operands are numbers.\n/// \\param name the name of the instruction.\n/// \\param oper the C++ operator to use to actually perform the shift\n/// operation.\n/// \\param lConv the conversion function for the LHS of the expression.\n/// \\param lType the type of the LHS operand.\n/// \\param returnType the type of the return value.\n#define SHIFTOP(name, oper, lConv, lType, returnType) \\\n CASE(name) { \\\n if (LLVM_LIKELY( \\\n O2REG(name).isNumber() && \\\n O3REG(name).isNumber())) { /* Fast-path. */ \\\n auto lnum = static_cast( \\\n hermes::truncateToInt32(O2REG(name).getNumber())); \\\n auto rnum = static_cast( \\\n hermes::truncateToInt32(O3REG(name).getNumber())) & \\\n 0x1f; \\\n O1REG(name) = HermesValue::encodeDoubleValue( \\\n static_cast(lnum oper rnum)); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n } \\\n CAPTURE_IP_ASSIGN(res, lConv(runtime, Handle<>(&O2REG(name)))); \\\n if (res == ExecutionStatus::EXCEPTION) { \\\n goto exception; \\\n } \\\n auto lnum = static_cast(res->getNumber()); \\\n CAPTURE_IP_ASSIGN(res, toUInt32_RJS(runtime, Handle<>(&O3REG(name)))); \\\n if (res == ExecutionStatus::EXCEPTION) { \\\n goto exception; \\\n } \\\n auto rnum = static_cast(res->getNumber()) & 0x1f; \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n O1REG(name) = HermesValue::encodeDoubleValue( \\\n static_cast(lnum oper rnum)); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n/// Implement a binary bitwise instruction with a fast path where both\n/// operands are numbers.\n/// \\param name the name of the instruction.\n/// \\param oper the C++ operator to use to actually perform the bitwise\n/// operation.\n#define BITWISEBINOP(name, oper) \\\n CASE(name) { \\\n if (LLVM_LIKELY(O2REG(name).isNumber() && O3REG(name).isNumber())) { \\\n /* Fast-path. */ \\\n O1REG(name) = HermesValue::encodeDoubleValue( \\\n hermes::truncateToInt32(O2REG(name).getNumber()) \\\n oper hermes::truncateToInt32(O3REG(name).getNumber())); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n } \\\n CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O2REG(name)))); \\\n if (res == ExecutionStatus::EXCEPTION) { \\\n goto exception; \\\n } \\\n int32_t left = res->getNumberAs(); \\\n CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O3REG(name)))); \\\n if (res == ExecutionStatus::EXCEPTION) { \\\n goto exception; \\\n } \\\n O1REG(name) = \\\n HermesValue::encodeNumberValue(left oper res->getNumberAs()); \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n/// Implement a comparison instruction.\n/// \\param name the name of the instruction.\n/// \\param oper the C++ operator to use to actually perform the fast arithmetic\n/// comparison.\n/// \\param operFuncName function to call for the slow-path comparison.\n#define CONDOP(name, oper, operFuncName) \\\n CASE(name) { \\\n if (LLVM_LIKELY(O2REG(name).isNumber() && O3REG(name).isNumber())) { \\\n /* Fast-path. */ \\\n O1REG(name) = HermesValue::encodeBoolValue( \\\n O2REG(name).getNumber() oper O3REG(name).getNumber()); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n } \\\n CAPTURE_IP_ASSIGN( \\\n boolRes, \\\n operFuncName( \\\n runtime, Handle<>(&O2REG(name)), Handle<>(&O3REG(name)))); \\\n if (boolRes == ExecutionStatus::EXCEPTION) \\\n goto exception; \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n O1REG(name) = HermesValue::encodeBoolValue(boolRes.getValue()); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n/// Implement a comparison conditional jump with a fast path where both\n/// operands are numbers.\n/// \\param name the name of the instruction. The fast path case will have a\n/// \"N\" appended to the name.\n/// \\param suffix Optional suffix to be added to the end (e.g. Long)\n/// \\param oper the C++ operator to use to actually perform the fast arithmetic\n/// comparison.\n/// \\param operFuncName function to call for the slow-path comparison.\n/// \\param trueDest ip value if the conditional evaluates to true\n/// \\param falseDest ip value if the conditional evaluates to false\n#define JCOND_IMPL(name, suffix, oper, operFuncName, trueDest, falseDest) \\\n CASE(name##suffix) { \\\n if (LLVM_LIKELY( \\\n O2REG(name##suffix).isNumber() && \\\n O3REG(name##suffix).isNumber())) { \\\n /* Fast-path. */ \\\n CASE(name##N##suffix) { \\\n if (O2REG(name##N##suffix) \\\n .getNumber() oper O3REG(name##N##suffix) \\\n .getNumber()) { \\\n ip = trueDest; \\\n DISPATCH; \\\n } \\\n ip = falseDest; \\\n DISPATCH; \\\n } \\\n } \\\n CAPTURE_IP_ASSIGN( \\\n boolRes, \\\n operFuncName( \\\n runtime, \\\n Handle<>(&O2REG(name##suffix)), \\\n Handle<>(&O3REG(name##suffix)))); \\\n if (boolRes == ExecutionStatus::EXCEPTION) \\\n goto exception; \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n if (boolRes.getValue()) { \\\n ip = trueDest; \\\n DISPATCH; \\\n } \\\n ip = falseDest; \\\n DISPATCH; \\\n }\n\n/// Implement a strict equality conditional jump\n/// \\param name the name of the instruction.\n/// \\param suffix Optional suffix to be added to the end (e.g. Long)\n/// \\param trueDest ip value if the conditional evaluates to true\n/// \\param falseDest ip value if the conditional evaluates to false\n#define JCOND_STRICT_EQ_IMPL(name, suffix, trueDest, falseDest) \\\n CASE(name##suffix) { \\\n if (strictEqualityTest(O2REG(name##suffix), O3REG(name##suffix))) { \\\n ip = trueDest; \\\n DISPATCH; \\\n } \\\n ip = falseDest; \\\n DISPATCH; \\\n }\n\n/// Implement an equality conditional jump\n/// \\param name the name of the instruction.\n/// \\param suffix Optional suffix to be added to the end (e.g. Long)\n/// \\param trueDest ip value if the conditional evaluates to true\n/// \\param falseDest ip value if the conditional evaluates to false\n#define JCOND_EQ_IMPL(name, suffix, trueDest, falseDest) \\\n CASE(name##suffix) { \\\n CAPTURE_IP_ASSIGN( \\\n res, \\\n abstractEqualityTest_RJS( \\\n runtime, \\\n Handle<>(&O2REG(name##suffix)), \\\n Handle<>(&O3REG(name##suffix)))); \\\n if (res == ExecutionStatus::EXCEPTION) { \\\n goto exception; \\\n } \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n if (res->getBool()) { \\\n ip = trueDest; \\\n DISPATCH; \\\n } \\\n ip = falseDest; \\\n DISPATCH; \\\n }\n\n/// Implement the long and short forms of a conditional jump, and its negation.\n#define JCOND(name, oper, operFuncName) \\\n JCOND_IMPL( \\\n J##name, \\\n , \\\n oper, \\\n operFuncName, \\\n IPADD(ip->iJ##name.op1), \\\n NEXTINST(J##name)); \\\n JCOND_IMPL( \\\n J##name, \\\n Long, \\\n oper, \\\n operFuncName, \\\n IPADD(ip->iJ##name##Long.op1), \\\n NEXTINST(J##name##Long)); \\\n JCOND_IMPL( \\\n JNot##name, \\\n , \\\n oper, \\\n operFuncName, \\\n NEXTINST(JNot##name), \\\n IPADD(ip->iJNot##name.op1)); \\\n JCOND_IMPL( \\\n JNot##name, \\\n Long, \\\n oper, \\\n operFuncName, \\\n NEXTINST(JNot##name##Long), \\\n IPADD(ip->iJNot##name##Long.op1));\n\n/// Load a constant.\n/// \\param value is the value to store in the output register.\n#define LOAD_CONST(name, value) \\\n CASE(name) { \\\n O1REG(name) = value; \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n#define LOAD_CONST_CAPTURE_IP(name, value) \\\n CASE(name) { \\\n CAPTURE_IP_ASSIGN(O1REG(name), value); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n CASE(Mov) {\n O1REG(Mov) = O2REG(Mov);\n ip = NEXTINST(Mov);\n DISPATCH;\n }\n\n CASE(MovLong) {\n O1REG(MovLong) = O2REG(MovLong);\n ip = NEXTINST(MovLong);\n DISPATCH;\n }\n\n CASE(LoadParam) {\n if (LLVM_LIKELY(ip->iLoadParam.op2 <= FRAME.getArgCount())) {\n // index 0 must load 'this'. Index 1 the first argument, etc.\n O1REG(LoadParam) = FRAME.getArgRef((int32_t)ip->iLoadParam.op2 - 1);\n ip = NEXTINST(LoadParam);\n DISPATCH;\n }\n O1REG(LoadParam) = HermesValue::encodeUndefinedValue();\n ip = NEXTINST(LoadParam);\n DISPATCH;\n }\n\n CASE(LoadParamLong) {\n if (LLVM_LIKELY(ip->iLoadParamLong.op2 <= FRAME.getArgCount())) {\n // index 0 must load 'this'. Index 1 the first argument, etc.\n O1REG(LoadParamLong) =\n FRAME.getArgRef((int32_t)ip->iLoadParamLong.op2 - 1);\n ip = NEXTINST(LoadParamLong);\n DISPATCH;\n }\n O1REG(LoadParamLong) = HermesValue::encodeUndefinedValue();\n ip = NEXTINST(LoadParamLong);\n DISPATCH;\n }\n\n CASE(CoerceThisNS) {\n if (LLVM_LIKELY(O2REG(CoerceThisNS).isObject())) {\n O1REG(CoerceThisNS) = O2REG(CoerceThisNS);\n } else if (\n O2REG(CoerceThisNS).isNull() || O2REG(CoerceThisNS).isUndefined()) {\n O1REG(CoerceThisNS) = runtime->global_;\n } else {\n tmpHandle = O2REG(CoerceThisNS);\n nextIP = NEXTINST(CoerceThisNS);\n goto coerceThisSlowPath;\n }\n ip = NEXTINST(CoerceThisNS);\n DISPATCH;\n }\n CASE(LoadThisNS) {\n if (LLVM_LIKELY(FRAME.getThisArgRef().isObject())) {\n O1REG(LoadThisNS) = FRAME.getThisArgRef();\n } else if (\n FRAME.getThisArgRef().isNull() ||\n FRAME.getThisArgRef().isUndefined()) {\n O1REG(LoadThisNS) = runtime->global_;\n } else {\n tmpHandle = FRAME.getThisArgRef();\n nextIP = NEXTINST(LoadThisNS);\n goto coerceThisSlowPath;\n }\n ip = NEXTINST(LoadThisNS);\n DISPATCH;\n }\n coerceThisSlowPath : {\n CAPTURE_IP_ASSIGN(res, toObject(runtime, tmpHandle));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(CoerceThisNS) = res.getValue();\n tmpHandle.clear();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(ConstructLong) {\n callArgCount = (uint32_t)ip->iConstructLong.op3;\n nextIP = NEXTINST(ConstructLong);\n callNewTarget = O2REG(ConstructLong).getRaw();\n goto doCall;\n }\n CASE(CallLong) {\n callArgCount = (uint32_t)ip->iCallLong.op3;\n nextIP = NEXTINST(CallLong);\n callNewTarget = HermesValue::encodeUndefinedValue().getRaw();\n goto doCall;\n }\n\n // Note in Call1 through Call4, the first argument is 'this' which has\n // argument index -1.\n // Also note that we are writing to callNewTarget last, to avoid the\n // possibility of it being aliased by the arg writes.\n CASE(Call1) {\n callArgCount = 1;\n nextIP = NEXTINST(Call1);\n StackFramePtr fr{runtime->stackPointer_};\n fr.getArgRefUnsafe(-1) = O3REG(Call1);\n callNewTarget = HermesValue::encodeUndefinedValue().getRaw();\n goto doCall;\n }\n\n CASE(Call2) {\n callArgCount = 2;\n nextIP = NEXTINST(Call2);\n StackFramePtr fr{runtime->stackPointer_};\n fr.getArgRefUnsafe(-1) = O3REG(Call2);\n fr.getArgRefUnsafe(0) = O4REG(Call2);\n callNewTarget = HermesValue::encodeUndefinedValue().getRaw();\n goto doCall;\n }\n\n CASE(Call3) {\n callArgCount = 3;\n nextIP = NEXTINST(Call3);\n StackFramePtr fr{runtime->stackPointer_};\n fr.getArgRefUnsafe(-1) = O3REG(Call3);\n fr.getArgRefUnsafe(0) = O4REG(Call3);\n fr.getArgRefUnsafe(1) = O5REG(Call3);\n callNewTarget = HermesValue::encodeUndefinedValue().getRaw();\n goto doCall;\n }\n\n CASE(Call4) {\n callArgCount = 4;\n nextIP = NEXTINST(Call4);\n StackFramePtr fr{runtime->stackPointer_};\n fr.getArgRefUnsafe(-1) = O3REG(Call4);\n fr.getArgRefUnsafe(0) = O4REG(Call4);\n fr.getArgRefUnsafe(1) = O5REG(Call4);\n fr.getArgRefUnsafe(2) = O6REG(Call4);\n callNewTarget = HermesValue::encodeUndefinedValue().getRaw();\n goto doCall;\n }\n\n CASE(Construct) {\n callArgCount = (uint32_t)ip->iConstruct.op3;\n nextIP = NEXTINST(Construct);\n callNewTarget = O2REG(Construct).getRaw();\n goto doCall;\n }\n CASE(Call) {\n callArgCount = (uint32_t)ip->iCall.op3;\n nextIP = NEXTINST(Call);\n callNewTarget = HermesValue::encodeUndefinedValue().getRaw();\n // Fall through.\n }\n\n doCall : {\n#ifdef HERMES_ENABLE_DEBUGGER\n // Check for an async debugger request.\n if (uint8_t asyncFlags =\n runtime->testAndClearDebuggerAsyncBreakRequest()) {\n RUN_DEBUGGER_ASYNC_BREAK(asyncFlags);\n gcScope.flushToSmallCount(KEEP_HANDLES);\n DISPATCH;\n }\n#endif\n\n // Subtract 1 from callArgCount as 'this' is considered an argument in the\n // instruction, but not in the frame.\n CAPTURE_IP_ASSIGN_NO_INVALIDATE(\n auto newFrame,\n StackFramePtr::initFrame(\n runtime->stackPointer_,\n FRAME,\n ip,\n curCodeBlock,\n callArgCount - 1,\n O2REG(Call),\n HermesValue::fromRaw(callNewTarget)));\n (void)newFrame;\n\n SLOW_DEBUG(dumpCallArguments(dbgs(), runtime, newFrame));\n\n if (auto *func = dyn_vmcast(O2REG(Call))) {\n assert(!SingleStep && \"can't single-step a call\");\n\n#ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES\n runtime->pushCallStack(curCodeBlock, ip);\n#endif\n\n CodeBlock *calleeBlock = func->getCodeBlock();\n calleeBlock->lazyCompile(runtime);\n#if defined(HERMESVM_PROFILER_EXTERN)\n CAPTURE_IP_ASSIGN_NO_INVALIDATE(\n res, runtime->interpretFunction(calleeBlock));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(Call) = *res;\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n#else\n if (auto jitPtr = runtime->jitContext_.compile(runtime, calleeBlock)) {\n res = (*jitPtr)(runtime);\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))\n goto exception;\n O1REG(Call) = *res;\n SLOW_DEBUG(\n dbgs() << \"JIT return value r\" << (unsigned)ip->iCall.op1 << \"=\"\n << DumpHermesValue(O1REG(Call)) << \"\\n\");\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n curCodeBlock = calleeBlock;\n goto tailCall;\n#endif\n }\n CAPTURE_IP_ASSIGN_NO_INVALIDATE(\n resPH, Interpreter::handleCallSlowPath(runtime, &O2REG(Call)));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(Call) = std::move(resPH->get());\n SLOW_DEBUG(\n dbgs() << \"native return value r\" << (unsigned)ip->iCall.op1 << \"=\"\n << DumpHermesValue(O1REG(Call)) << \"\\n\");\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(CallDirect)\n CASE(CallDirectLongIndex) {\n#ifdef HERMES_ENABLE_DEBUGGER\n // Check for an async debugger request.\n if (uint8_t asyncFlags =\n runtime->testAndClearDebuggerAsyncBreakRequest()) {\n RUN_DEBUGGER_ASYNC_BREAK(asyncFlags);\n gcScope.flushToSmallCount(KEEP_HANDLES);\n DISPATCH;\n }\n#endif\n\n CAPTURE_IP_ASSIGN(\n CodeBlock * calleeBlock,\n ip->opCode == OpCode::CallDirect\n ? curCodeBlock->getRuntimeModule()->getCodeBlockMayAllocate(\n ip->iCallDirect.op3)\n : curCodeBlock->getRuntimeModule()->getCodeBlockMayAllocate(\n ip->iCallDirectLongIndex.op3));\n\n CAPTURE_IP_ASSIGN_NO_INVALIDATE(\n auto newFrame,\n StackFramePtr::initFrame(\n runtime->stackPointer_,\n FRAME,\n ip,\n curCodeBlock,\n (uint32_t)ip->iCallDirect.op2 - 1,\n HermesValue::encodeNativePointer(calleeBlock),\n HermesValue::encodeUndefinedValue()));\n (void)newFrame;\n\n LLVM_DEBUG(dumpCallArguments(dbgs(), runtime, newFrame));\n\n assert(!SingleStep && \"can't single-step a call\");\n\n calleeBlock->lazyCompile(runtime);\n#if defined(HERMESVM_PROFILER_EXTERN)\n CAPTURE_IP_ASSIGN_NO_INVALIDATE(\n res, runtime->interpretFunction(calleeBlock));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(CallDirect) = *res;\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = ip->opCode == OpCode::CallDirect ? NEXTINST(CallDirect)\n : NEXTINST(CallDirectLongIndex);\n DISPATCH;\n#else\n if (auto jitPtr = runtime->jitContext_.compile(runtime, calleeBlock)) {\n res = (*jitPtr)(runtime);\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))\n goto exception;\n O1REG(CallDirect) = *res;\n LLVM_DEBUG(\n dbgs() << \"JIT return value r\" << (unsigned)ip->iCallDirect.op1\n << \"=\" << DumpHermesValue(O1REG(Call)) << \"\\n\");\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = ip->opCode == OpCode::CallDirect ? NEXTINST(CallDirect)\n : NEXTINST(CallDirectLongIndex);\n DISPATCH;\n }\n curCodeBlock = calleeBlock;\n goto tailCall;\n#endif\n }\n\n CASE(CallBuiltin) {\n NativeFunction *nf =\n runtime->getBuiltinNativeFunction(ip->iCallBuiltin.op2);\n\n CAPTURE_IP_ASSIGN(\n auto newFrame,\n StackFramePtr::initFrame(\n runtime->stackPointer_,\n FRAME,\n ip,\n curCodeBlock,\n (uint32_t)ip->iCallBuiltin.op3 - 1,\n nf,\n false));\n // \"thisArg\" is implicitly assumed to \"undefined\".\n newFrame.getThisArgRef() = HermesValue::encodeUndefinedValue();\n\n SLOW_DEBUG(dumpCallArguments(dbgs(), runtime, newFrame));\n\n CAPTURE_IP_ASSIGN(resPH, NativeFunction::_nativeCall(nf, runtime));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION))\n goto exception;\n O1REG(CallBuiltin) = std::move(resPH->get());\n SLOW_DEBUG(\n dbgs() << \"native return value r\" << (unsigned)ip->iCallBuiltin.op1\n << \"=\" << DumpHermesValue(O1REG(CallBuiltin)) << \"\\n\");\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CallBuiltin);\n DISPATCH;\n }\n\n CASE(CompleteGenerator) {\n auto *innerFn = vmcast(\n runtime->getCurrentFrame().getCalleeClosure());\n innerFn->setState(GeneratorInnerFunction::State::Completed);\n ip = NEXTINST(CompleteGenerator);\n DISPATCH;\n }\n\n CASE(SaveGenerator) {\n nextIP = IPADD(ip->iSaveGenerator.op1);\n goto doSaveGen;\n }\n CASE(SaveGeneratorLong) {\n nextIP = IPADD(ip->iSaveGeneratorLong.op1);\n goto doSaveGen;\n }\n\n doSaveGen : {\n auto *innerFn = vmcast(\n runtime->getCurrentFrame().getCalleeClosure());\n\n innerFn->saveStack(runtime);\n innerFn->setNextIP(nextIP);\n innerFn->setState(GeneratorInnerFunction::State::SuspendedYield);\n ip = NEXTINST(SaveGenerator);\n DISPATCH;\n }\n\n CASE(StartGenerator) {\n auto *innerFn = vmcast(\n runtime->getCurrentFrame().getCalleeClosure());\n if (innerFn->getState() ==\n GeneratorInnerFunction::State::SuspendedStart) {\n nextIP = NEXTINST(StartGenerator);\n } else {\n nextIP = innerFn->getNextIP();\n innerFn->restoreStack(runtime);\n }\n innerFn->setState(GeneratorInnerFunction::State::Executing);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(ResumeGenerator) {\n auto *innerFn = vmcast(\n runtime->getCurrentFrame().getCalleeClosure());\n O1REG(ResumeGenerator) = innerFn->getResult();\n O2REG(ResumeGenerator) = HermesValue::encodeBoolValue(\n innerFn->getAction() == GeneratorInnerFunction::Action::Return);\n innerFn->clearResult(runtime);\n if (innerFn->getAction() == GeneratorInnerFunction::Action::Throw) {\n runtime->setThrownValue(O1REG(ResumeGenerator));\n goto exception;\n }\n ip = NEXTINST(ResumeGenerator);\n DISPATCH;\n }\n\n CASE(Ret) {\n#ifdef HERMES_ENABLE_DEBUGGER\n // Check for an async debugger request.\n if (uint8_t asyncFlags =\n runtime->testAndClearDebuggerAsyncBreakRequest()) {\n RUN_DEBUGGER_ASYNC_BREAK(asyncFlags);\n gcScope.flushToSmallCount(KEEP_HANDLES);\n DISPATCH;\n }\n#endif\n\n PROFILER_EXIT_FUNCTION(curCodeBlock);\n\n#ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES\n runtime->popCallStack();\n#endif\n\n // Store the return value.\n res = O1REG(Ret);\n\n ip = FRAME.getSavedIP();\n curCodeBlock = FRAME.getSavedCodeBlock();\n\n frameRegs =\n &runtime->restoreStackAndPreviousFrame(FRAME).getFirstLocalRef();\n\n SLOW_DEBUG(\n dbgs() << \"function exit: restored stackLevel=\"\n << runtime->getStackLevel() << \"\\n\");\n\n // Are we returning to native code?\n if (!curCodeBlock) {\n SLOW_DEBUG(dbgs() << \"function exit: returning to native code\\n\");\n return res;\n }\n\n// Return because of recursive calling structure\n#if defined(HERMESVM_PROFILER_EXTERN)\n return res;\n#endif\n\n INIT_STATE_FOR_CODEBLOCK(curCodeBlock);\n O1REG(Call) = res.getValue();\n ip = nextInstCall(ip);\n DISPATCH;\n }\n\n CASE(Catch) {\n assert(!runtime->thrownValue_.isEmpty() && \"Invalid thrown value\");\n assert(\n !isUncatchableError(runtime->thrownValue_) &&\n \"Uncatchable thrown value was caught\");\n O1REG(Catch) = runtime->thrownValue_;\n runtime->clearThrownValue();\n#ifdef HERMES_ENABLE_DEBUGGER\n // Signal to the debugger that we're done unwinding an exception,\n // and we can resume normal debugging flow.\n runtime->debugger_.finishedUnwindingException();\n#endif\n ip = NEXTINST(Catch);\n DISPATCH;\n }\n\n CASE(Throw) {\n runtime->thrownValue_ = O1REG(Throw);\n SLOW_DEBUG(\n dbgs() << \"Exception thrown: \"\n << DumpHermesValue(runtime->thrownValue_) << \"\\n\");\n goto exception;\n }\n\n CASE(ThrowIfUndefinedInst) {\n if (LLVM_UNLIKELY(O1REG(ThrowIfUndefinedInst).isUndefined())) {\n SLOW_DEBUG(\n dbgs() << \"Throwing ReferenceError for undefined variable\");\n CAPTURE_IP(runtime->raiseReferenceError(\n \"accessing an uninitialized variable\"));\n goto exception;\n }\n ip = NEXTINST(ThrowIfUndefinedInst);\n DISPATCH;\n }\n\n CASE(Debugger) {\n SLOW_DEBUG(dbgs() << \"debugger statement executed\\n\");\n#ifdef HERMES_ENABLE_DEBUGGER\n {\n if (!runtime->debugger_.isDebugging()) {\n // Only run the debugger if we're not already debugging.\n // Don't want to call it again and mess with its state.\n CAPTURE_IP_ASSIGN(\n auto res,\n runDebuggerUpdatingState(\n Debugger::RunReason::Opcode,\n runtime,\n curCodeBlock,\n ip,\n frameRegs));\n if (res == ExecutionStatus::EXCEPTION) {\n // If one of the internal steps threw,\n // then handle that here by jumping to where we're supposed to go.\n // If we're in mid-step, the breakpoint at the catch point\n // will have been set by the debugger.\n // We don't want to execute this instruction because it's already\n // thrown.\n goto exception;\n }\n }\n auto breakpointOpt = runtime->debugger_.getBreakpointLocation(ip);\n if (breakpointOpt.hasValue()) {\n // We're on a breakpoint but we're supposed to continue.\n curCodeBlock->uninstallBreakpointAtOffset(\n CUROFFSET, breakpointOpt->opCode);\n if (ip->opCode == OpCode::Debugger) {\n // Breakpointed a debugger instruction, so move past it\n // since we've already called the debugger on this instruction.\n ip = NEXTINST(Debugger);\n } else {\n InterpreterState newState{curCodeBlock, (uint32_t)CUROFFSET};\n CAPTURE_IP_ASSIGN(\n ExecutionStatus status, runtime->stepFunction(newState));\n curCodeBlock->installBreakpointAtOffset(CUROFFSET);\n if (status == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n curCodeBlock = newState.codeBlock;\n ip = newState.codeBlock->getOffsetPtr(newState.offset);\n INIT_STATE_FOR_CODEBLOCK(curCodeBlock);\n // Single-stepping should handle call stack management for us.\n frameRegs = &runtime->getCurrentFrame().getFirstLocalRef();\n }\n } else if (ip->opCode == OpCode::Debugger) {\n // No breakpoint here and we've already run the debugger,\n // just continue on.\n // If the current instruction is no longer a debugger instruction,\n // we're just going to keep executing from the current IP.\n ip = NEXTINST(Debugger);\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n }\n DISPATCH;\n#else\n ip = NEXTINST(Debugger);\n DISPATCH;\n#endif\n }\n\n CASE(AsyncBreakCheck) {\n if (LLVM_UNLIKELY(runtime->hasAsyncBreak())) {\n#ifdef HERMES_ENABLE_DEBUGGER\n if (uint8_t asyncFlags =\n runtime->testAndClearDebuggerAsyncBreakRequest()) {\n RUN_DEBUGGER_ASYNC_BREAK(asyncFlags);\n }\n#endif\n if (runtime->testAndClearTimeoutAsyncBreakRequest()) {\n CAPTURE_IP_ASSIGN(auto nRes, runtime->notifyTimeout());\n if (nRes == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n }\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n\n ip = NEXTINST(AsyncBreakCheck);\n DISPATCH;\n }\n\n CASE(ProfilePoint) {\n#ifdef HERMESVM_PROFILER_BB\n auto pointIndex = ip->iProfilePoint.op1;\n SLOW_DEBUG(llvh::dbgs() << \"ProfilePoint: \" << pointIndex << \"\\n\");\n CAPTURE_IP(runtime->getBasicBlockExecutionInfo().executeBlock(\n curCodeBlock, pointIndex));\n#endif\n ip = NEXTINST(ProfilePoint);\n DISPATCH;\n }\n\n CASE(Unreachable) {\n llvm_unreachable(\"Hermes bug: unreachable instruction\");\n }\n\n CASE(CreateClosure) {\n idVal = ip->iCreateClosure.op3;\n nextIP = NEXTINST(CreateClosure);\n goto createClosure;\n }\n CASE(CreateClosureLongIndex) {\n idVal = ip->iCreateClosureLongIndex.op3;\n nextIP = NEXTINST(CreateClosureLongIndex);\n goto createClosure;\n }\n createClosure : {\n auto *runtimeModule = curCodeBlock->getRuntimeModule();\n CAPTURE_IP_ASSIGN(\n O1REG(CreateClosure),\n JSFunction::create(\n runtime,\n runtimeModule->getDomain(runtime),\n Handle::vmcast(&runtime->functionPrototype),\n Handle::vmcast(&O2REG(CreateClosure)),\n runtimeModule->getCodeBlockMayAllocate(idVal))\n .getHermesValue());\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(CreateGeneratorClosure) {\n CAPTURE_IP_ASSIGN(\n auto res,\n createGeneratorClosure(\n runtime,\n curCodeBlock->getRuntimeModule(),\n ip->iCreateClosure.op3,\n Handle::vmcast(&O2REG(CreateGeneratorClosure))));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(CreateGeneratorClosure) = res->getHermesValue();\n res->invalidate();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CreateGeneratorClosure);\n DISPATCH;\n }\n CASE(CreateGeneratorClosureLongIndex) {\n CAPTURE_IP_ASSIGN(\n auto res,\n createGeneratorClosure(\n runtime,\n curCodeBlock->getRuntimeModule(),\n ip->iCreateClosureLongIndex.op3,\n Handle::vmcast(\n &O2REG(CreateGeneratorClosureLongIndex))));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(CreateGeneratorClosureLongIndex) = res->getHermesValue();\n res->invalidate();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CreateGeneratorClosureLongIndex);\n DISPATCH;\n }\n\n CASE(CreateGenerator) {\n CAPTURE_IP_ASSIGN(\n auto res,\n createGenerator_RJS(\n runtime,\n curCodeBlock->getRuntimeModule(),\n ip->iCreateGenerator.op3,\n Handle::vmcast(&O2REG(CreateGenerator)),\n FRAME.getNativeArgs()));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(CreateGenerator) = res->getHermesValue();\n res->invalidate();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CreateGenerator);\n DISPATCH;\n }\n CASE(CreateGeneratorLongIndex) {\n CAPTURE_IP_ASSIGN(\n auto res,\n createGenerator_RJS(\n runtime,\n curCodeBlock->getRuntimeModule(),\n ip->iCreateGeneratorLongIndex.op3,\n Handle::vmcast(&O2REG(CreateGeneratorLongIndex)),\n FRAME.getNativeArgs()));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(CreateGeneratorLongIndex) = res->getHermesValue();\n res->invalidate();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CreateGeneratorLongIndex);\n DISPATCH;\n }\n\n CASE(GetEnvironment) {\n // The currently executing function must exist, so get the environment.\n Environment *curEnv =\n FRAME.getCalleeClosureUnsafe()->getEnvironment(runtime);\n for (unsigned level = ip->iGetEnvironment.op2; level; --level) {\n assert(curEnv && \"invalid environment relative level\");\n curEnv = curEnv->getParentEnvironment(runtime);\n }\n O1REG(GetEnvironment) = HermesValue::encodeObjectValue(curEnv);\n ip = NEXTINST(GetEnvironment);\n DISPATCH;\n }\n\n CASE(CreateEnvironment) {\n tmpHandle = HermesValue::encodeObjectValue(\n FRAME.getCalleeClosureUnsafe()->getEnvironment(runtime));\n\n CAPTURE_IP_ASSIGN(\n res,\n Environment::create(\n runtime,\n tmpHandle->getPointer() ? Handle::vmcast(tmpHandle)\n : Handle::vmcast_or_null(\n &runtime->nullPointer_),\n curCodeBlock->getEnvironmentSize()));\n if (res == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n O1REG(CreateEnvironment) = *res;\n#ifdef HERMES_ENABLE_DEBUGGER\n FRAME.getDebugEnvironmentRef() = *res;\n#endif\n tmpHandle = HermesValue::encodeUndefinedValue();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CreateEnvironment);\n DISPATCH;\n }\n\n CASE(StoreToEnvironment) {\n vmcast(O1REG(StoreToEnvironment))\n ->slot(ip->iStoreToEnvironment.op2)\n .set(O3REG(StoreToEnvironment), &runtime->getHeap());\n ip = NEXTINST(StoreToEnvironment);\n DISPATCH;\n }\n CASE(StoreToEnvironmentL) {\n vmcast(O1REG(StoreToEnvironmentL))\n ->slot(ip->iStoreToEnvironmentL.op2)\n .set(O3REG(StoreToEnvironmentL), &runtime->getHeap());\n ip = NEXTINST(StoreToEnvironmentL);\n DISPATCH;\n }\n\n CASE(StoreNPToEnvironment) {\n vmcast(O1REG(StoreNPToEnvironment))\n ->slot(ip->iStoreNPToEnvironment.op2)\n .setNonPtr(O3REG(StoreNPToEnvironment), &runtime->getHeap());\n ip = NEXTINST(StoreNPToEnvironment);\n DISPATCH;\n }\n CASE(StoreNPToEnvironmentL) {\n vmcast(O1REG(StoreNPToEnvironmentL))\n ->slot(ip->iStoreNPToEnvironmentL.op2)\n .setNonPtr(O3REG(StoreNPToEnvironmentL), &runtime->getHeap());\n ip = NEXTINST(StoreNPToEnvironmentL);\n DISPATCH;\n }\n\n CASE(LoadFromEnvironment) {\n O1REG(LoadFromEnvironment) =\n vmcast(O2REG(LoadFromEnvironment))\n ->slot(ip->iLoadFromEnvironment.op3);\n ip = NEXTINST(LoadFromEnvironment);\n DISPATCH;\n }\n\n CASE(LoadFromEnvironmentL) {\n O1REG(LoadFromEnvironmentL) =\n vmcast(O2REG(LoadFromEnvironmentL))\n ->slot(ip->iLoadFromEnvironmentL.op3);\n ip = NEXTINST(LoadFromEnvironmentL);\n DISPATCH;\n }\n\n CASE(GetGlobalObject) {\n O1REG(GetGlobalObject) = runtime->global_;\n ip = NEXTINST(GetGlobalObject);\n DISPATCH;\n }\n\n CASE(GetNewTarget) {\n O1REG(GetNewTarget) = FRAME.getNewTargetRef();\n ip = NEXTINST(GetNewTarget);\n DISPATCH;\n }\n\n CASE(DeclareGlobalVar) {\n DefinePropertyFlags dpf =\n DefinePropertyFlags::getDefaultNewPropertyFlags();\n dpf.configurable = 0;\n // Do not overwrite existing globals with undefined.\n dpf.setValue = 0;\n\n CAPTURE_IP_ASSIGN(\n auto res,\n JSObject::defineOwnProperty(\n runtime->getGlobal(),\n runtime,\n ID(ip->iDeclareGlobalVar.op1),\n dpf,\n Runtime::getUndefinedValue(),\n PropOpFlags().plusThrowOnError()));\n if (res == ExecutionStatus::EXCEPTION) {\n assert(\n !runtime->getGlobal()->isProxyObject() &&\n \"global can't be a proxy object\");\n // If the property already exists, this should be a noop.\n // Instead of incurring the cost to check every time, do it\n // only if an exception is thrown, and swallow the exception\n // if it exists, since we didn't want to make the call,\n // anyway. This most likely means the property is\n // non-configurable.\n NamedPropertyDescriptor desc;\n CAPTURE_IP_ASSIGN(\n auto res,\n JSObject::getOwnNamedDescriptor(\n runtime->getGlobal(),\n runtime,\n ID(ip->iDeclareGlobalVar.op1),\n desc));\n if (!res) {\n goto exception;\n } else {\n runtime->clearThrownValue();\n }\n // fall through\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(DeclareGlobalVar);\n DISPATCH;\n }\n\n CASE(TryGetByIdLong) {\n tryProp = true;\n idVal = ip->iTryGetByIdLong.op4;\n nextIP = NEXTINST(TryGetByIdLong);\n goto getById;\n }\n CASE(GetByIdLong) {\n tryProp = false;\n idVal = ip->iGetByIdLong.op4;\n nextIP = NEXTINST(GetByIdLong);\n goto getById;\n }\n CASE(GetByIdShort) {\n tryProp = false;\n idVal = ip->iGetByIdShort.op4;\n nextIP = NEXTINST(GetByIdShort);\n goto getById;\n }\n CASE(TryGetById) {\n tryProp = true;\n idVal = ip->iTryGetById.op4;\n nextIP = NEXTINST(TryGetById);\n goto getById;\n }\n CASE(GetById) {\n tryProp = false;\n idVal = ip->iGetById.op4;\n nextIP = NEXTINST(GetById);\n }\n getById : {\n ++NumGetById;\n // NOTE: it is safe to use OnREG(GetById) here because all instructions\n // have the same layout: opcode, registers, non-register operands, i.e.\n // they only differ in the width of the last \"identifier\" field.\n CallResult propRes{ExecutionStatus::EXCEPTION};\n if (LLVM_LIKELY(O2REG(GetById).isObject())) {\n auto *obj = vmcast(O2REG(GetById));\n auto cacheIdx = ip->iGetById.op3;\n auto *cacheEntry = curCodeBlock->getReadCacheEntry(cacheIdx);\n\n#ifdef HERMESVM_PROFILER_BB\n {\n HERMES_SLOW_ASSERT(\n gcScope.getHandleCountDbg() == KEEP_HANDLES &&\n \"unaccounted handles were created\");\n auto objHandle = runtime->makeHandle(obj);\n auto cacheHCPtr = vmcast_or_null(static_cast(\n cacheEntry->clazz.get(runtime, &runtime->getHeap())));\n CAPTURE_IP(runtime->recordHiddenClass(\n curCodeBlock, ip, ID(idVal), obj->getClass(runtime), cacheHCPtr));\n // obj may be moved by GC due to recordHiddenClass\n obj = objHandle.get();\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n#endif\n auto clazzGCPtr = obj->getClassGCPtr();\n#ifndef NDEBUG\n if (clazzGCPtr.get(runtime)->isDictionary())\n ++NumGetByIdDict;\n#else\n (void)NumGetByIdDict;\n#endif\n\n // If we have a cache hit, reuse the cached offset and immediately\n // return the property.\n if (LLVM_LIKELY(cacheEntry->clazz == clazzGCPtr.getStorageType())) {\n ++NumGetByIdCacheHits;\n CAPTURE_IP_ASSIGN(\n O1REG(GetById),\n JSObject::getNamedSlotValue(\n obj, runtime, cacheEntry->slot));\n ip = nextIP;\n DISPATCH;\n }\n auto id = ID(idVal);\n NamedPropertyDescriptor desc;\n CAPTURE_IP_ASSIGN(\n OptValue fastPathResult,\n JSObject::tryGetOwnNamedDescriptorFast(obj, runtime, id, desc));\n if (LLVM_LIKELY(\n fastPathResult.hasValue() && fastPathResult.getValue()) &&\n !desc.flags.accessor) {\n ++NumGetByIdFastPaths;\n\n // cacheIdx == 0 indicates no caching so don't update the cache in\n // those cases.\n auto *clazz = clazzGCPtr.getNonNull(runtime);\n if (LLVM_LIKELY(!clazz->isDictionaryNoCache()) &&\n LLVM_LIKELY(cacheIdx != hbc::PROPERTY_CACHING_DISABLED)) {\n#ifdef HERMES_SLOW_DEBUG\n if (cacheEntry->clazz &&\n cacheEntry->clazz != clazzGCPtr.getStorageType())\n ++NumGetByIdCacheEvicts;\n#else\n (void)NumGetByIdCacheEvicts;\n#endif\n // Cache the class, id and property slot.\n cacheEntry->clazz = clazzGCPtr.getStorageType();\n cacheEntry->slot = desc.slot;\n }\n\n CAPTURE_IP_ASSIGN(\n O1REG(GetById), JSObject::getNamedSlotValue(obj, runtime, desc));\n ip = nextIP;\n DISPATCH;\n }\n\n // The cache may also be populated via the prototype of the object.\n // This value is only reliable if the fast path was a definite\n // not-found.\n if (fastPathResult.hasValue() && !fastPathResult.getValue() &&\n !obj->isProxyObject()) {\n CAPTURE_IP_ASSIGN(JSObject * parent, obj->getParent(runtime));\n // TODO: This isLazy check is because a lazy object is reported as\n // having no properties and therefore cannot contain the property.\n // This check does not belong here, it should be merged into\n // tryGetOwnNamedDescriptorFast().\n if (parent &&\n cacheEntry->clazz == parent->getClassGCPtr().getStorageType() &&\n LLVM_LIKELY(!obj->isLazy())) {\n ++NumGetByIdProtoHits;\n CAPTURE_IP_ASSIGN(\n O1REG(GetById),\n JSObject::getNamedSlotValue(parent, runtime, cacheEntry->slot));\n ip = nextIP;\n DISPATCH;\n }\n }\n\n#ifdef HERMES_SLOW_DEBUG\n CAPTURE_IP_ASSIGN(\n JSObject * propObj,\n JSObject::getNamedDescriptor(\n Handle::vmcast(&O2REG(GetById)), runtime, id, desc));\n if (propObj) {\n if (desc.flags.accessor)\n ++NumGetByIdAccessor;\n else if (propObj != vmcast(O2REG(GetById)))\n ++NumGetByIdProto;\n } else {\n ++NumGetByIdNotFound;\n }\n#else\n (void)NumGetByIdAccessor;\n (void)NumGetByIdProto;\n (void)NumGetByIdNotFound;\n#endif\n#ifdef HERMES_SLOW_DEBUG\n auto *savedClass = cacheIdx != hbc::PROPERTY_CACHING_DISABLED\n ? cacheEntry->clazz.get(runtime, &runtime->getHeap())\n : nullptr;\n#endif\n ++NumGetByIdSlow;\n CAPTURE_IP_ASSIGN(\n resPH,\n JSObject::getNamed_RJS(\n Handle::vmcast(&O2REG(GetById)),\n runtime,\n id,\n !tryProp ? defaultPropOpFlags\n : defaultPropOpFlags.plusMustExist(),\n cacheIdx != hbc::PROPERTY_CACHING_DISABLED ? cacheEntry\n : nullptr));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n#ifdef HERMES_SLOW_DEBUG\n if (cacheIdx != hbc::PROPERTY_CACHING_DISABLED && savedClass &&\n cacheEntry->clazz.get(runtime, &runtime->getHeap()) != savedClass) {\n ++NumGetByIdCacheEvicts;\n }\n#endif\n } else {\n ++NumGetByIdTransient;\n assert(!tryProp && \"TryGetById can only be used on the global object\");\n /* Slow path. */\n CAPTURE_IP_ASSIGN(\n resPH,\n Interpreter::getByIdTransient_RJS(\n runtime, Handle<>(&O2REG(GetById)), ID(idVal)));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n }\n O1REG(GetById) = resPH->get();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(TryPutByIdLong) {\n tryProp = true;\n idVal = ip->iTryPutByIdLong.op4;\n nextIP = NEXTINST(TryPutByIdLong);\n goto putById;\n }\n CASE(PutByIdLong) {\n tryProp = false;\n idVal = ip->iPutByIdLong.op4;\n nextIP = NEXTINST(PutByIdLong);\n goto putById;\n }\n CASE(TryPutById) {\n tryProp = true;\n idVal = ip->iTryPutById.op4;\n nextIP = NEXTINST(TryPutById);\n goto putById;\n }\n CASE(PutById) {\n tryProp = false;\n idVal = ip->iPutById.op4;\n nextIP = NEXTINST(PutById);\n }\n putById : {\n ++NumPutById;\n if (LLVM_LIKELY(O1REG(PutById).isObject())) {\n auto *obj = vmcast(O1REG(PutById));\n auto cacheIdx = ip->iPutById.op3;\n auto *cacheEntry = curCodeBlock->getWriteCacheEntry(cacheIdx);\n\n#ifdef HERMESVM_PROFILER_BB\n {\n HERMES_SLOW_ASSERT(\n gcScope.getHandleCountDbg() == KEEP_HANDLES &&\n \"unaccounted handles were created\");\n auto objHandle = runtime->makeHandle(obj);\n auto cacheHCPtr = vmcast_or_null(static_cast(\n cacheEntry->clazz.get(runtime, &runtime->getHeap())));\n CAPTURE_IP(runtime->recordHiddenClass(\n curCodeBlock, ip, ID(idVal), obj->getClass(runtime), cacheHCPtr));\n // obj may be moved by GC due to recordHiddenClass\n obj = objHandle.get();\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n#endif\n auto clazzGCPtr = obj->getClassGCPtr();\n // If we have a cache hit, reuse the cached offset and immediately\n // return the property.\n if (LLVM_LIKELY(cacheEntry->clazz == clazzGCPtr.getStorageType())) {\n ++NumPutByIdCacheHits;\n CAPTURE_IP(JSObject::setNamedSlotValue(\n obj, runtime, cacheEntry->slot, O2REG(PutById)));\n ip = nextIP;\n DISPATCH;\n }\n auto id = ID(idVal);\n NamedPropertyDescriptor desc;\n CAPTURE_IP_ASSIGN(\n OptValue hasOwnProp,\n JSObject::tryGetOwnNamedDescriptorFast(obj, runtime, id, desc));\n if (LLVM_LIKELY(hasOwnProp.hasValue() && hasOwnProp.getValue()) &&\n !desc.flags.accessor && desc.flags.writable &&\n !desc.flags.internalSetter) {\n ++NumPutByIdFastPaths;\n\n // cacheIdx == 0 indicates no caching so don't update the cache in\n // those cases.\n auto *clazz = clazzGCPtr.getNonNull(runtime);\n if (LLVM_LIKELY(!clazz->isDictionary()) &&\n LLVM_LIKELY(cacheIdx != hbc::PROPERTY_CACHING_DISABLED)) {\n#ifdef HERMES_SLOW_DEBUG\n if (cacheEntry->clazz &&\n cacheEntry->clazz != clazzGCPtr.getStorageType())\n ++NumPutByIdCacheEvicts;\n#else\n (void)NumPutByIdCacheEvicts;\n#endif\n // Cache the class and property slot.\n cacheEntry->clazz = clazzGCPtr.getStorageType();\n cacheEntry->slot = desc.slot;\n }\n\n CAPTURE_IP(JSObject::setNamedSlotValue(\n obj, runtime, desc.slot, O2REG(PutById)));\n ip = nextIP;\n DISPATCH;\n }\n\n CAPTURE_IP_ASSIGN(\n auto putRes,\n JSObject::putNamed_RJS(\n Handle::vmcast(&O1REG(PutById)),\n runtime,\n id,\n Handle<>(&O2REG(PutById)),\n !tryProp ? defaultPropOpFlags\n : defaultPropOpFlags.plusMustExist()));\n if (LLVM_UNLIKELY(putRes == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n } else {\n ++NumPutByIdTransient;\n assert(!tryProp && \"TryPutById can only be used on the global object\");\n CAPTURE_IP_ASSIGN(\n auto retStatus,\n Interpreter::putByIdTransient_RJS(\n runtime,\n Handle<>(&O1REG(PutById)),\n ID(idVal),\n Handle<>(&O2REG(PutById)),\n strictMode));\n if (retStatus == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(GetByVal) {\n CallResult propRes{ExecutionStatus::EXCEPTION};\n if (LLVM_LIKELY(O2REG(GetByVal).isObject())) {\n CAPTURE_IP_ASSIGN(\n resPH,\n JSObject::getComputed_RJS(\n Handle::vmcast(&O2REG(GetByVal)),\n runtime,\n Handle<>(&O3REG(GetByVal))));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n } else {\n // This is the \"slow path\".\n CAPTURE_IP_ASSIGN(\n resPH,\n Interpreter::getByValTransient_RJS(\n runtime,\n Handle<>(&O2REG(GetByVal)),\n Handle<>(&O3REG(GetByVal))));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(GetByVal) = resPH->get();\n ip = NEXTINST(GetByVal);\n DISPATCH;\n }\n\n CASE(PutByVal) {\n if (LLVM_LIKELY(O1REG(PutByVal).isObject())) {\n CAPTURE_IP_ASSIGN(\n auto putRes,\n JSObject::putComputed_RJS(\n Handle::vmcast(&O1REG(PutByVal)),\n runtime,\n Handle<>(&O2REG(PutByVal)),\n Handle<>(&O3REG(PutByVal)),\n defaultPropOpFlags));\n if (LLVM_UNLIKELY(putRes == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n } else {\n // This is the \"slow path\".\n CAPTURE_IP_ASSIGN(\n auto retStatus,\n Interpreter::putByValTransient_RJS(\n runtime,\n Handle<>(&O1REG(PutByVal)),\n Handle<>(&O2REG(PutByVal)),\n Handle<>(&O3REG(PutByVal)),\n strictMode));\n if (LLVM_UNLIKELY(retStatus == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(PutByVal);\n DISPATCH;\n }\n\n CASE(PutOwnByIndexL) {\n nextIP = NEXTINST(PutOwnByIndexL);\n idVal = ip->iPutOwnByIndexL.op3;\n goto putOwnByIndex;\n }\n CASE(PutOwnByIndex) {\n nextIP = NEXTINST(PutOwnByIndex);\n idVal = ip->iPutOwnByIndex.op3;\n }\n putOwnByIndex : {\n tmpHandle = HermesValue::encodeDoubleValue(idVal);\n CAPTURE_IP(JSObject::defineOwnComputedPrimitive(\n Handle::vmcast(&O1REG(PutOwnByIndex)),\n runtime,\n tmpHandle,\n DefinePropertyFlags::getDefaultNewPropertyFlags(),\n Handle<>(&O2REG(PutOwnByIndex))));\n gcScope.flushToSmallCount(KEEP_HANDLES);\n tmpHandle.clear();\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(GetPNameList) {\n CAPTURE_IP_ASSIGN(\n auto pRes, handleGetPNameList(runtime, frameRegs, ip));\n if (LLVM_UNLIKELY(pRes == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(GetPNameList);\n DISPATCH;\n }\n\n CASE(GetNextPName) {\n {\n assert(\n vmisa(O2REG(GetNextPName)) &&\n \"GetNextPName's second op must be BigStorage\");\n auto obj = Handle::vmcast(&O3REG(GetNextPName));\n auto arr = Handle::vmcast(&O2REG(GetNextPName));\n uint32_t idx = O4REG(GetNextPName).getNumber();\n uint32_t size = O5REG(GetNextPName).getNumber();\n MutableHandle propObj{runtime};\n // Loop until we find a property which is present.\n while (idx < size) {\n tmpHandle = arr->at(idx);\n ComputedPropertyDescriptor desc;\n CAPTURE_IP(JSObject::getComputedPrimitiveDescriptor(\n obj, runtime, tmpHandle, propObj, desc));\n if (LLVM_LIKELY(propObj))\n break;\n ++idx;\n }\n if (idx < size) {\n // We must return the property as a string\n if (tmpHandle->isNumber()) {\n CAPTURE_IP_ASSIGN(auto status, toString_RJS(runtime, tmpHandle));\n assert(\n status == ExecutionStatus::RETURNED &&\n \"toString on number cannot fail\");\n tmpHandle = status->getHermesValue();\n }\n O1REG(GetNextPName) = tmpHandle.get();\n O4REG(GetNextPName) = HermesValue::encodeNumberValue(idx + 1);\n } else {\n O1REG(GetNextPName) = HermesValue::encodeUndefinedValue();\n }\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n tmpHandle.clear();\n ip = NEXTINST(GetNextPName);\n DISPATCH;\n }\n\n CASE(ToNumber) {\n if (LLVM_LIKELY(O2REG(ToNumber).isNumber())) {\n O1REG(ToNumber) = O2REG(ToNumber);\n ip = NEXTINST(ToNumber);\n } else {\n CAPTURE_IP_ASSIGN(\n res, toNumber_RJS(runtime, Handle<>(&O2REG(ToNumber))));\n if (res == ExecutionStatus::EXCEPTION)\n goto exception;\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(ToNumber) = res.getValue();\n ip = NEXTINST(ToNumber);\n }\n DISPATCH;\n }\n\n CASE(ToInt32) {\n CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O2REG(ToInt32))));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))\n goto exception;\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(ToInt32) = res.getValue();\n ip = NEXTINST(ToInt32);\n DISPATCH;\n }\n\n CASE(AddEmptyString) {\n if (LLVM_LIKELY(O2REG(AddEmptyString).isString())) {\n O1REG(AddEmptyString) = O2REG(AddEmptyString);\n ip = NEXTINST(AddEmptyString);\n } else {\n CAPTURE_IP_ASSIGN(\n res,\n toPrimitive_RJS(\n runtime,\n Handle<>(&O2REG(AddEmptyString)),\n PreferredType::NONE));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))\n goto exception;\n tmpHandle = res.getValue();\n CAPTURE_IP_ASSIGN(auto strRes, toString_RJS(runtime, tmpHandle));\n if (LLVM_UNLIKELY(strRes == ExecutionStatus::EXCEPTION))\n goto exception;\n tmpHandle.clear();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(AddEmptyString) = strRes->getHermesValue();\n ip = NEXTINST(AddEmptyString);\n }\n DISPATCH;\n }\n\n CASE(Jmp) {\n ip = IPADD(ip->iJmp.op1);\n DISPATCH;\n }\n CASE(JmpLong) {\n ip = IPADD(ip->iJmpLong.op1);\n DISPATCH;\n }\n CASE(JmpTrue) {\n if (toBoolean(O2REG(JmpTrue)))\n ip = IPADD(ip->iJmpTrue.op1);\n else\n ip = NEXTINST(JmpTrue);\n DISPATCH;\n }\n CASE(JmpTrueLong) {\n if (toBoolean(O2REG(JmpTrueLong)))\n ip = IPADD(ip->iJmpTrueLong.op1);\n else\n ip = NEXTINST(JmpTrueLong);\n DISPATCH;\n }\n CASE(JmpFalse) {\n if (!toBoolean(O2REG(JmpFalse)))\n ip = IPADD(ip->iJmpFalse.op1);\n else\n ip = NEXTINST(JmpFalse);\n DISPATCH;\n }\n CASE(JmpFalseLong) {\n if (!toBoolean(O2REG(JmpFalseLong)))\n ip = IPADD(ip->iJmpFalseLong.op1);\n else\n ip = NEXTINST(JmpFalseLong);\n DISPATCH;\n }\n CASE(JmpUndefined) {\n if (O2REG(JmpUndefined).isUndefined())\n ip = IPADD(ip->iJmpUndefined.op1);\n else\n ip = NEXTINST(JmpUndefined);\n DISPATCH;\n }\n CASE(JmpUndefinedLong) {\n if (O2REG(JmpUndefinedLong).isUndefined())\n ip = IPADD(ip->iJmpUndefinedLong.op1);\n else\n ip = NEXTINST(JmpUndefinedLong);\n DISPATCH;\n }\n CASE(Add) {\n if (LLVM_LIKELY(\n O2REG(Add).isNumber() &&\n O3REG(Add).isNumber())) { /* Fast-path. */\n CASE(AddN) {\n O1REG(Add) = HermesValue::encodeDoubleValue(\n O2REG(Add).getNumber() + O3REG(Add).getNumber());\n ip = NEXTINST(Add);\n DISPATCH;\n }\n }\n CAPTURE_IP_ASSIGN(\n res,\n addOp_RJS(runtime, Handle<>(&O2REG(Add)), Handle<>(&O3REG(Add))));\n if (res == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(Add) = res.getValue();\n ip = NEXTINST(Add);\n DISPATCH;\n }\n\n CASE(BitNot) {\n if (LLVM_LIKELY(O2REG(BitNot).isNumber())) { /* Fast-path. */\n O1REG(BitNot) = HermesValue::encodeDoubleValue(\n ~hermes::truncateToInt32(O2REG(BitNot).getNumber()));\n ip = NEXTINST(BitNot);\n DISPATCH;\n }\n CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O2REG(BitNot))));\n if (res == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(BitNot) = HermesValue::encodeDoubleValue(\n ~static_cast(res->getNumber()));\n ip = NEXTINST(BitNot);\n DISPATCH;\n }\n\n CASE(GetArgumentsLength) {\n // If the arguments object hasn't been created yet.\n if (O2REG(GetArgumentsLength).isUndefined()) {\n O1REG(GetArgumentsLength) =\n HermesValue::encodeNumberValue(FRAME.getArgCount());\n ip = NEXTINST(GetArgumentsLength);\n DISPATCH;\n }\n // The arguments object has been created, so this is a regular property\n // get.\n assert(\n O2REG(GetArgumentsLength).isObject() &&\n \"arguments lazy register is not an object\");\n CAPTURE_IP_ASSIGN(\n resPH,\n JSObject::getNamed_RJS(\n Handle::vmcast(&O2REG(GetArgumentsLength)),\n runtime,\n Predefined::getSymbolID(Predefined::length)));\n if (resPH == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(GetArgumentsLength) = resPH->get();\n ip = NEXTINST(GetArgumentsLength);\n DISPATCH;\n }\n\n CASE(GetArgumentsPropByVal) {\n // If the arguments object hasn't been created yet and we have a\n // valid integer index, we use the fast path.\n if (O3REG(GetArgumentsPropByVal).isUndefined()) {\n // If this is an integer index.\n if (auto index = toArrayIndexFastPath(O2REG(GetArgumentsPropByVal))) {\n // Is this an existing argument?\n if (*index < FRAME.getArgCount()) {\n O1REG(GetArgumentsPropByVal) = FRAME.getArgRef(*index);\n ip = NEXTINST(GetArgumentsPropByVal);\n DISPATCH;\n }\n }\n }\n // Slow path.\n CAPTURE_IP_ASSIGN(\n auto res,\n getArgumentsPropByValSlowPath_RJS(\n runtime,\n &O3REG(GetArgumentsPropByVal),\n &O2REG(GetArgumentsPropByVal),\n FRAME.getCalleeClosureHandleUnsafe(),\n strictMode));\n if (res == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(GetArgumentsPropByVal) = res->getHermesValue();\n ip = NEXTINST(GetArgumentsPropByVal);\n DISPATCH;\n }\n\n CASE(ReifyArguments) {\n // If the arguments object was already created, do nothing.\n if (!O1REG(ReifyArguments).isUndefined()) {\n assert(\n O1REG(ReifyArguments).isObject() &&\n \"arguments lazy register is not an object\");\n ip = NEXTINST(ReifyArguments);\n DISPATCH;\n }\n CAPTURE_IP_ASSIGN(\n resArgs,\n reifyArgumentsSlowPath(\n runtime, FRAME.getCalleeClosureHandleUnsafe(), strictMode));\n if (LLVM_UNLIKELY(resArgs == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(ReifyArguments) = resArgs->getHermesValue();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(ReifyArguments);\n DISPATCH;\n }\n\n CASE(NewObject) {\n // Create a new object using the built-in constructor. Note that the\n // built-in constructor is empty, so we don't actually need to call\n // it.\n CAPTURE_IP_ASSIGN(\n O1REG(NewObject), JSObject::create(runtime).getHermesValue());\n assert(\n gcScope.getHandleCountDbg() == KEEP_HANDLES &&\n \"Should not create handles.\");\n ip = NEXTINST(NewObject);\n DISPATCH;\n }\n CASE(NewObjectWithParent) {\n CAPTURE_IP_ASSIGN(\n O1REG(NewObjectWithParent),\n JSObject::create(\n runtime,\n O2REG(NewObjectWithParent).isObject()\n ? Handle::vmcast(&O2REG(NewObjectWithParent))\n : O2REG(NewObjectWithParent).isNull()\n ? Runtime::makeNullHandle()\n : Handle::vmcast(&runtime->objectPrototype))\n .getHermesValue());\n assert(\n gcScope.getHandleCountDbg() == KEEP_HANDLES &&\n \"Should not create handles.\");\n ip = NEXTINST(NewObjectWithParent);\n DISPATCH;\n }\n\n CASE(NewObjectWithBuffer) {\n CAPTURE_IP_ASSIGN(\n resPH,\n Interpreter::createObjectFromBuffer(\n runtime,\n curCodeBlock,\n ip->iNewObjectWithBuffer.op3,\n ip->iNewObjectWithBuffer.op4,\n ip->iNewObjectWithBuffer.op5));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(NewObjectWithBuffer) = resPH->get();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(NewObjectWithBuffer);\n DISPATCH;\n }\n\n CASE(NewObjectWithBufferLong) {\n CAPTURE_IP_ASSIGN(\n resPH,\n Interpreter::createObjectFromBuffer(\n runtime,\n curCodeBlock,\n ip->iNewObjectWithBufferLong.op3,\n ip->iNewObjectWithBufferLong.op4,\n ip->iNewObjectWithBufferLong.op5));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(NewObjectWithBufferLong) = resPH->get();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(NewObjectWithBufferLong);\n DISPATCH;\n }\n\n CASE(NewArray) {\n // Create a new array using the built-in constructor. Note that the\n // built-in constructor is empty, so we don't actually need to call\n // it.\n CAPTURE_IP_ASSIGN(\n auto createRes,\n JSArray::create(runtime, ip->iNewArray.op2, ip->iNewArray.op2));\n if (createRes == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n O1REG(NewArray) = createRes->getHermesValue();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(NewArray);\n DISPATCH;\n }\n\n CASE(NewArrayWithBuffer) {\n CAPTURE_IP_ASSIGN(\n resPH,\n Interpreter::createArrayFromBuffer(\n runtime,\n curCodeBlock,\n ip->iNewArrayWithBuffer.op2,\n ip->iNewArrayWithBuffer.op3,\n ip->iNewArrayWithBuffer.op4));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(NewArrayWithBuffer) = resPH->get();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n tmpHandle.clear();\n ip = NEXTINST(NewArrayWithBuffer);\n DISPATCH;\n }\n\n CASE(NewArrayWithBufferLong) {\n CAPTURE_IP_ASSIGN(\n resPH,\n Interpreter::createArrayFromBuffer(\n runtime,\n curCodeBlock,\n ip->iNewArrayWithBufferLong.op2,\n ip->iNewArrayWithBufferLong.op3,\n ip->iNewArrayWithBufferLong.op4));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(NewArrayWithBufferLong) = resPH->get();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n tmpHandle.clear();\n ip = NEXTINST(NewArrayWithBufferLong);\n DISPATCH;\n }\n\n CASE(CreateThis) {\n // Registers: output, prototype, closure.\n if (LLVM_UNLIKELY(!vmisa(O3REG(CreateThis)))) {\n CAPTURE_IP(runtime->raiseTypeError(\"constructor is not callable\"));\n goto exception;\n }\n CAPTURE_IP_ASSIGN(\n auto res,\n Callable::newObject(\n Handle::vmcast(&O3REG(CreateThis)),\n runtime,\n Handle::vmcast(\n O2REG(CreateThis).isObject() ? &O2REG(CreateThis)\n : &runtime->objectPrototype)));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(CreateThis) = res->getHermesValue();\n ip = NEXTINST(CreateThis);\n DISPATCH;\n }\n\n CASE(SelectObject) {\n // Registers: output, thisObject, constructorReturnValue.\n O1REG(SelectObject) = O3REG(SelectObject).isObject()\n ? O3REG(SelectObject)\n : O2REG(SelectObject);\n ip = NEXTINST(SelectObject);\n DISPATCH;\n }\n\n CASE(Eq)\n CASE(Neq) {\n CAPTURE_IP_ASSIGN(\n res,\n abstractEqualityTest_RJS(\n runtime, Handle<>(&O2REG(Eq)), Handle<>(&O3REG(Eq))));\n if (res == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(Eq) = ip->opCode == OpCode::Eq\n ? res.getValue()\n : HermesValue::encodeBoolValue(!res->getBool());\n ip = NEXTINST(Eq);\n DISPATCH;\n }\n CASE(StrictEq) {\n O1REG(StrictEq) = HermesValue::encodeBoolValue(\n strictEqualityTest(O2REG(StrictEq), O3REG(StrictEq)));\n ip = NEXTINST(StrictEq);\n DISPATCH;\n }\n CASE(StrictNeq) {\n O1REG(StrictNeq) = HermesValue::encodeBoolValue(\n !strictEqualityTest(O2REG(StrictNeq), O3REG(StrictNeq)));\n ip = NEXTINST(StrictNeq);\n DISPATCH;\n }\n CASE(Not) {\n O1REG(Not) = HermesValue::encodeBoolValue(!toBoolean(O2REG(Not)));\n ip = NEXTINST(Not);\n DISPATCH;\n }\n CASE(Negate) {\n if (LLVM_LIKELY(O2REG(Negate).isNumber())) {\n O1REG(Negate) =\n HermesValue::encodeDoubleValue(-O2REG(Negate).getNumber());\n } else {\n CAPTURE_IP_ASSIGN(\n res, toNumber_RJS(runtime, Handle<>(&O2REG(Negate))));\n if (res == ExecutionStatus::EXCEPTION)\n goto exception;\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(Negate) = HermesValue::encodeDoubleValue(-res->getNumber());\n }\n ip = NEXTINST(Negate);\n DISPATCH;\n }\n CASE(TypeOf) {\n CAPTURE_IP_ASSIGN(\n O1REG(TypeOf), typeOf(runtime, Handle<>(&O2REG(TypeOf))));\n ip = NEXTINST(TypeOf);\n DISPATCH;\n }\n CASE(Mod) {\n // We use fmod here for simplicity. Theoretically fmod behaves slightly\n // differently than the ECMAScript Spec. fmod applies round-towards-zero\n // for the remainder when it's not representable by a double; while the\n // spec requires round-to-nearest. As an example, 5 % 0.7 will give\n // 0.10000000000000031 using fmod, but using the rounding style\n // described\n // by the spec, the output should really be 0.10000000000000053.\n // Such difference can be ignored in practice.\n if (LLVM_LIKELY(O2REG(Mod).isNumber() && O3REG(Mod).isNumber())) {\n /* Fast-path. */\n O1REG(Mod) = HermesValue::encodeDoubleValue(\n std::fmod(O2REG(Mod).getNumber(), O3REG(Mod).getNumber()));\n ip = NEXTINST(Mod);\n DISPATCH;\n }\n CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O2REG(Mod))));\n if (res == ExecutionStatus::EXCEPTION)\n goto exception;\n double left = res->getDouble();\n CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O3REG(Mod))));\n if (res == ExecutionStatus::EXCEPTION)\n goto exception;\n O1REG(Mod) =\n HermesValue::encodeDoubleValue(std::fmod(left, res->getDouble()));\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(Mod);\n DISPATCH;\n }\n CASE(InstanceOf) {\n CAPTURE_IP_ASSIGN(\n auto result,\n instanceOfOperator_RJS(\n runtime,\n Handle<>(&O2REG(InstanceOf)),\n Handle<>(&O3REG(InstanceOf))));\n if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(InstanceOf) = HermesValue::encodeBoolValue(*result);\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(InstanceOf);\n DISPATCH;\n }\n CASE(IsIn) {\n {\n if (LLVM_UNLIKELY(!O3REG(IsIn).isObject())) {\n CAPTURE_IP(runtime->raiseTypeError(\n \"right operand of 'in' is not an object\"));\n goto exception;\n }\n CAPTURE_IP_ASSIGN(\n auto cr,\n JSObject::hasComputed(\n Handle::vmcast(&O3REG(IsIn)),\n runtime,\n Handle<>(&O2REG(IsIn))));\n if (cr == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n O1REG(IsIn) = HermesValue::encodeBoolValue(*cr);\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(IsIn);\n DISPATCH;\n }\n\n CASE(PutNewOwnByIdShort) {\n nextIP = NEXTINST(PutNewOwnByIdShort);\n idVal = ip->iPutNewOwnByIdShort.op3;\n goto putOwnById;\n }\n CASE(PutNewOwnNEByIdLong)\n CASE(PutNewOwnByIdLong) {\n nextIP = NEXTINST(PutNewOwnByIdLong);\n idVal = ip->iPutNewOwnByIdLong.op3;\n goto putOwnById;\n }\n CASE(PutNewOwnNEById)\n CASE(PutNewOwnById) {\n nextIP = NEXTINST(PutNewOwnById);\n idVal = ip->iPutNewOwnById.op3;\n }\n putOwnById : {\n assert(\n O1REG(PutNewOwnById).isObject() &&\n \"Object argument of PutNewOwnById must be an object\");\n CAPTURE_IP_ASSIGN(\n auto res,\n JSObject::defineNewOwnProperty(\n Handle::vmcast(&O1REG(PutNewOwnById)),\n runtime,\n ID(idVal),\n ip->opCode <= OpCode::PutNewOwnByIdLong\n ? PropertyFlags::defaultNewNamedPropertyFlags()\n : PropertyFlags::nonEnumerablePropertyFlags(),\n Handle<>(&O2REG(PutNewOwnById))));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(DelByIdLong) {\n idVal = ip->iDelByIdLong.op3;\n nextIP = NEXTINST(DelByIdLong);\n goto DelById;\n }\n\n CASE(DelById) {\n idVal = ip->iDelById.op3;\n nextIP = NEXTINST(DelById);\n }\n DelById : {\n if (LLVM_LIKELY(O2REG(DelById).isObject())) {\n CAPTURE_IP_ASSIGN(\n auto status,\n JSObject::deleteNamed(\n Handle::vmcast(&O2REG(DelById)),\n runtime,\n ID(idVal),\n defaultPropOpFlags));\n if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(DelById) = HermesValue::encodeBoolValue(status.getValue());\n } else {\n // This is the \"slow path\".\n CAPTURE_IP_ASSIGN(res, toObject(runtime, Handle<>(&O2REG(DelById))));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n // If an exception is thrown, likely we are trying to convert\n // undefined/null to an object. Passing over the name of the property\n // so that we could emit more meaningful error messages.\n CAPTURE_IP(amendPropAccessErrorMsgWithPropName(\n runtime, Handle<>(&O2REG(DelById)), \"delete\", ID(idVal)));\n goto exception;\n }\n tmpHandle = res.getValue();\n CAPTURE_IP_ASSIGN(\n auto status,\n JSObject::deleteNamed(\n Handle::vmcast(tmpHandle),\n runtime,\n ID(idVal),\n defaultPropOpFlags));\n if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(DelById) = HermesValue::encodeBoolValue(status.getValue());\n tmpHandle.clear();\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(DelByVal) {\n if (LLVM_LIKELY(O2REG(DelByVal).isObject())) {\n CAPTURE_IP_ASSIGN(\n auto status,\n JSObject::deleteComputed(\n Handle::vmcast(&O2REG(DelByVal)),\n runtime,\n Handle<>(&O3REG(DelByVal)),\n defaultPropOpFlags));\n if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(DelByVal) = HermesValue::encodeBoolValue(status.getValue());\n } else {\n // This is the \"slow path\".\n CAPTURE_IP_ASSIGN(res, toObject(runtime, Handle<>(&O2REG(DelByVal))));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n tmpHandle = res.getValue();\n CAPTURE_IP_ASSIGN(\n auto status,\n JSObject::deleteComputed(\n Handle::vmcast(tmpHandle),\n runtime,\n Handle<>(&O3REG(DelByVal)),\n defaultPropOpFlags));\n if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(DelByVal) = HermesValue::encodeBoolValue(status.getValue());\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n tmpHandle.clear();\n ip = NEXTINST(DelByVal);\n DISPATCH;\n }\n CASE(CreateRegExp) {\n {\n // Create the RegExp object.\n CAPTURE_IP_ASSIGN(auto re, JSRegExp::create(runtime));\n // Initialize the regexp.\n CAPTURE_IP_ASSIGN(\n auto pattern,\n runtime->makeHandle(curCodeBlock->getRuntimeModule()\n ->getStringPrimFromStringIDMayAllocate(\n ip->iCreateRegExp.op2)));\n CAPTURE_IP_ASSIGN(\n auto flags,\n runtime->makeHandle(curCodeBlock->getRuntimeModule()\n ->getStringPrimFromStringIDMayAllocate(\n ip->iCreateRegExp.op3)));\n CAPTURE_IP_ASSIGN(\n auto bytecode,\n curCodeBlock->getRuntimeModule()->getRegExpBytecodeFromRegExpID(\n ip->iCreateRegExp.op4));\n CAPTURE_IP_ASSIGN(\n auto initRes,\n JSRegExp::initialize(re, runtime, pattern, flags, bytecode));\n if (LLVM_UNLIKELY(initRes == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n // Done, return the new object.\n O1REG(CreateRegExp) = re.getHermesValue();\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CreateRegExp);\n DISPATCH;\n }\n\n CASE(SwitchImm) {\n if (LLVM_LIKELY(O1REG(SwitchImm).isNumber())) {\n double numVal = O1REG(SwitchImm).getNumber();\n uint32_t uintVal = (uint32_t)numVal;\n if (LLVM_LIKELY(numVal == uintVal) && // Only integers.\n LLVM_LIKELY(uintVal >= ip->iSwitchImm.op4) && // Bounds checking.\n LLVM_LIKELY(uintVal <= ip->iSwitchImm.op5)) // Bounds checking.\n {\n // Calculate the offset into the bytecode where the jump table for\n // this SwitchImm starts.\n const uint8_t *tablestart = (const uint8_t *)llvh::alignAddr(\n (const uint8_t *)ip + ip->iSwitchImm.op2, sizeof(uint32_t));\n\n // Read the offset from the table.\n // Must be signed to account for backwards branching.\n const int32_t *loc =\n (const int32_t *)tablestart + uintVal - ip->iSwitchImm.op4;\n\n ip = IPADD(*loc);\n DISPATCH;\n }\n }\n // Wrong type or out of range, jump to default.\n ip = IPADD(ip->iSwitchImm.op3);\n DISPATCH;\n }\n LOAD_CONST(\n LoadConstUInt8,\n HermesValue::encodeDoubleValue(ip->iLoadConstUInt8.op2));\n LOAD_CONST(\n LoadConstInt, HermesValue::encodeDoubleValue(ip->iLoadConstInt.op2));\n LOAD_CONST(\n LoadConstDouble,\n HermesValue::encodeDoubleValue(ip->iLoadConstDouble.op2));\n LOAD_CONST_CAPTURE_IP(\n LoadConstString,\n HermesValue::encodeStringValue(\n curCodeBlock->getRuntimeModule()\n ->getStringPrimFromStringIDMayAllocate(\n ip->iLoadConstString.op2)));\n LOAD_CONST_CAPTURE_IP(\n LoadConstStringLongIndex,\n HermesValue::encodeStringValue(\n curCodeBlock->getRuntimeModule()\n ->getStringPrimFromStringIDMayAllocate(\n ip->iLoadConstStringLongIndex.op2)));\n LOAD_CONST(LoadConstUndefined, HermesValue::encodeUndefinedValue());\n LOAD_CONST(LoadConstNull, HermesValue::encodeNullValue());\n LOAD_CONST(LoadConstTrue, HermesValue::encodeBoolValue(true));\n LOAD_CONST(LoadConstFalse, HermesValue::encodeBoolValue(false));\n LOAD_CONST(LoadConstZero, HermesValue::encodeDoubleValue(0));\n BINOP(Sub, doSub);\n BINOP(Mul, doMult);\n BINOP(Div, doDiv);\n BITWISEBINOP(BitAnd, &);\n BITWISEBINOP(BitOr, |);\n BITWISEBINOP(BitXor, ^);\n // For LShift, we need to use toUInt32 first because lshift on negative\n // numbers is undefined behavior in theory.\n SHIFTOP(LShift, <<, toUInt32_RJS, uint32_t, int32_t);\n SHIFTOP(RShift, >>, toInt32_RJS, int32_t, int32_t);\n SHIFTOP(URshift, >>, toUInt32_RJS, uint32_t, uint32_t);\n CONDOP(Less, <, lessOp_RJS);\n CONDOP(LessEq, <=, lessEqualOp_RJS);\n CONDOP(Greater, >, greaterOp_RJS);\n CONDOP(GreaterEq, >=, greaterEqualOp_RJS);\n JCOND(Less, <, lessOp_RJS);\n JCOND(LessEqual, <=, lessEqualOp_RJS);\n JCOND(Greater, >, greaterOp_RJS);\n JCOND(GreaterEqual, >=, greaterEqualOp_RJS);\n\n JCOND_STRICT_EQ_IMPL(\n JStrictEqual, , IPADD(ip->iJStrictEqual.op1), NEXTINST(JStrictEqual));\n JCOND_STRICT_EQ_IMPL(\n JStrictEqual,\n Long,\n IPADD(ip->iJStrictEqualLong.op1),\n NEXTINST(JStrictEqualLong));\n JCOND_STRICT_EQ_IMPL(\n JStrictNotEqual,\n ,\n NEXTINST(JStrictNotEqual),\n IPADD(ip->iJStrictNotEqual.op1));\n JCOND_STRICT_EQ_IMPL(\n JStrictNotEqual,\n Long,\n NEXTINST(JStrictNotEqualLong),\n IPADD(ip->iJStrictNotEqualLong.op1));\n\n JCOND_EQ_IMPL(JEqual, , IPADD(ip->iJEqual.op1), NEXTINST(JEqual));\n JCOND_EQ_IMPL(\n JEqual, Long, IPADD(ip->iJEqualLong.op1), NEXTINST(JEqualLong));\n JCOND_EQ_IMPL(\n JNotEqual, , NEXTINST(JNotEqual), IPADD(ip->iJNotEqual.op1));\n JCOND_EQ_IMPL(\n JNotEqual,\n Long,\n NEXTINST(JNotEqualLong),\n IPADD(ip->iJNotEqualLong.op1));\n\n CASE_OUTOFLINE(PutOwnByVal);\n CASE_OUTOFLINE(PutOwnGetterSetterByVal);\n CASE_OUTOFLINE(DirectEval);\n\n CASE_OUTOFLINE(IteratorBegin);\n CASE_OUTOFLINE(IteratorNext);\n CASE(IteratorClose) {\n if (LLVM_UNLIKELY(O1REG(IteratorClose).isObject())) {\n // The iterator must be closed if it's still an object.\n // That means it was never an index and is not done iterating (a state\n // which is indicated by `undefined`).\n CAPTURE_IP_ASSIGN(\n auto res,\n iteratorClose(\n runtime,\n Handle::vmcast(&O1REG(IteratorClose)),\n Runtime::getEmptyValue()));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n if (ip->iIteratorClose.op2 &&\n !isUncatchableError(runtime->thrownValue_)) {\n // Ignore inner exception.\n runtime->clearThrownValue();\n } else {\n goto exception;\n }\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n }\n ip = NEXTINST(IteratorClose);\n DISPATCH;\n }\n\n CASE(_last) {\n llvm_unreachable(\"Invalid opcode _last\");\n }\n }\n\n llvm_unreachable(\"unreachable\");\n\n // We arrive here if we couldn't allocate the registers for the current frame.\n stackOverflow:\n CAPTURE_IP(runtime->raiseStackOverflow(\n Runtime::StackOverflowKind::JSRegisterStack));\n\n // We arrive here when we raised an exception in a callee, but we don't want\n // the callee to be able to handle it.\n handleExceptionInParent:\n // Restore the caller code block and IP.\n curCodeBlock = FRAME.getSavedCodeBlock();\n ip = FRAME.getSavedIP();\n\n // Pop to the previous frame where technically the error happened.\n frameRegs =\n &runtime->restoreStackAndPreviousFrame(FRAME).getFirstLocalRef();\n\n // If we are coming from native code, return.\n if (!curCodeBlock)\n return ExecutionStatus::EXCEPTION;\n\n// Return because of recursive calling structure\n#ifdef HERMESVM_PROFILER_EXTERN\n return ExecutionStatus::EXCEPTION;\n#endif\n // Handle the exception.\n exception:\n UPDATE_OPCODE_TIME_SPENT;\n assert(\n !runtime->thrownValue_.isEmpty() &&\n \"thrownValue unavailable at exception\");\n\n bool catchable = true;\n // If this is an Error object that was thrown internally, it didn't have\n // access to the current codeblock and IP, so collect the stack trace here.\n if (auto *jsError = dyn_vmcast(runtime->thrownValue_)) {\n catchable = jsError->catchable();\n if (!jsError->getStackTrace()) {\n // Temporarily clear the thrown value for following operations.\n CAPTURE_IP_ASSIGN(\n auto errorHandle,\n runtime->makeHandle(vmcast(runtime->thrownValue_)));\n runtime->clearThrownValue();\n\n CAPTURE_IP(JSError::recordStackTrace(\n errorHandle, runtime, false, curCodeBlock, ip));\n\n // Restore the thrown value.\n runtime->setThrownValue(errorHandle.getHermesValue());\n }\n }\n\n gcScope.flushToSmallCount(KEEP_HANDLES);\n tmpHandle.clear();\n\n#ifdef HERMES_ENABLE_DEBUGGER\n if (SingleStep) {\n // If we're single stepping, don't bother with any more checks,\n // and simply signal that we should continue execution with an exception.\n state.codeBlock = curCodeBlock;\n state.offset = CUROFFSET;\n return ExecutionStatus::EXCEPTION;\n }\n\n using PauseOnThrowMode = facebook::hermes::debugger::PauseOnThrowMode;\n auto mode = runtime->debugger_.getPauseOnThrowMode();\n if (mode != PauseOnThrowMode::None) {\n if (!runtime->debugger_.isDebugging()) {\n // Determine whether the PauseOnThrowMode requires us to stop here.\n bool caught =\n runtime->debugger_\n .findCatchTarget(InterpreterState(curCodeBlock, CUROFFSET))\n .hasValue();\n bool shouldStop = mode == PauseOnThrowMode::All ||\n (mode == PauseOnThrowMode::Uncaught && !caught);\n if (shouldStop) {\n // When runDebugger is invoked after an exception,\n // stepping should never happen internally.\n // Any step is a step to an exception handler, which we do\n // directly here in the interpreter.\n // Thus, the result state should be the same as the input state.\n InterpreterState tmpState{curCodeBlock, (uint32_t)CUROFFSET};\n CAPTURE_IP_ASSIGN(\n ExecutionStatus resultStatus,\n runtime->debugger_.runDebugger(\n Debugger::RunReason::Exception, tmpState));\n (void)resultStatus;\n assert(\n tmpState == InterpreterState(curCodeBlock, CUROFFSET) &&\n \"not allowed to step internally in a pauseOnThrow\");\n gcScope.flushToSmallCount(KEEP_HANDLES);\n }\n }\n }\n#endif\n\n int32_t handlerOffset = 0;\n\n // If the exception is not catchable, skip found catch blocks.\n while (((handlerOffset = curCodeBlock->findCatchTargetOffset(CUROFFSET)) ==\n -1) ||\n !catchable) {\n PROFILER_EXIT_FUNCTION(curCodeBlock);\n\n#ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES\n runtime->popCallStack();\n#endif\n\n // Restore the code block and IP.\n curCodeBlock = FRAME.getSavedCodeBlock();\n ip = FRAME.getSavedIP();\n\n // Pop a stack frame.\n frameRegs =\n &runtime->restoreStackAndPreviousFrame(FRAME).getFirstLocalRef();\n\n SLOW_DEBUG(\n dbgs() << \"function exit with exception: restored stackLevel=\"\n << runtime->getStackLevel() << \"\\n\");\n\n // Are we returning to native code?\n if (!curCodeBlock) {\n SLOW_DEBUG(\n dbgs()\n << \"function exit with exception: returning to native code\\n\");\n return ExecutionStatus::EXCEPTION;\n }\n\n assert(\n isCallType(ip->opCode) &&\n \"return address is not Call-type instruction\");\n\n// Return because of recursive calling structure\n#ifdef HERMESVM_PROFILER_EXTERN\n return ExecutionStatus::EXCEPTION;\n#endif\n }\n\n INIT_STATE_FOR_CODEBLOCK(curCodeBlock);\n\n ip = IPADD(handlerOffset - CUROFFSET);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-670', 'CWE-703'], 'message': 'Fix CVE-2020-1914 by using NEXTINST for SaveGeneratorLong\n\nSummary:\nIf `SaveGeneratorLong` was emitted, it would accidentally jump to the\nwrong next instruction, based on how long SaveGenerator was.\n\nMake a callout function to handle the common case, and handle the dispatch\nwithin each case of the interpreter loop.\n\nFixes CVE-2020-1914\n\nReviewed By: neildhar\n\nDifferential Revision: D24024242\n\nfbshipit-source-id: 3bcb88daa740f0d50e91771a49eb212551ce8bd8'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline void handle_socket_receive_known(\n\tfastd_socket_t *sock, const fastd_peer_address_t *local_addr, const fastd_peer_address_t *remote_addr,\n\tfastd_peer_t *peer, fastd_buffer_t *buffer) {\n\tif (!fastd_peer_may_connect(peer)) {\n\t\tfastd_buffer_free(buffer);\n\t\treturn;\n\t}\n\n\tconst uint8_t *packet_type = buffer->data;\n\n\tswitch (*packet_type) {\n\tcase PACKET_DATA:\n\t\tif (!fastd_peer_is_established(peer) || !fastd_peer_address_equal(&peer->local_address, local_addr)) {\n\t\t\tfastd_buffer_free(buffer);\n\n\t\t\tif (!backoff_unknown(remote_addr)) {\n\t\t\t\tpr_debug(\"unexpectedly received payload data from %P[%I]\", peer, remote_addr);\n\t\t\t\tconf.protocol->handshake_init(sock, local_addr, remote_addr, NULL);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tconf.protocol->handle_recv(peer, buffer);\n\t\tbreak;\n\n\tcase PACKET_HANDSHAKE:\n\t\tfastd_handshake_handle(sock, local_addr, remote_addr, peer, buffer);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617', 'CWE-119', 'CWE-284'], 'message': 'receive: fix buffer leak when receiving invalid packets\n\nFor fastd versions before v20, this was just a memory leak (which could\nstill be used for DoS, as it's remotely triggerable). With the new\nbuffer management of fastd v20, this will trigger an assertion failure\ninstead as soon as the buffer pool is empty.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void __init xen_init_IRQ(void)\n{\n\tint ret = -EINVAL;\n\tevtchn_port_t evtchn;\n\n\tif (fifo_events)\n\t\tret = xen_evtchn_fifo_init();\n\tif (ret < 0)\n\t\txen_evtchn_2l_init();\n\n\tcpuhp_setup_state_nocalls(CPUHP_XEN_EVTCHN_PREPARE,\n\t\t\t\t \"xen/evtchn:prepare\",\n\t\t\t\t xen_evtchn_cpu_prepare, xen_evtchn_cpu_dead);\n\n\tevtchn_to_irq = kcalloc(EVTCHN_ROW(xen_evtchn_max_channels()),\n\t\t\t\tsizeof(*evtchn_to_irq), GFP_KERNEL);\n\tBUG_ON(!evtchn_to_irq);\n\n\t/* No event channels are 'live' right now. */\n\tfor (evtchn = 0; evtchn < xen_evtchn_nr_channels(); evtchn++)\n\t\tmask_evtchn(evtchn);\n\n\tpirq_needs_eoi = pirq_needs_eoi_flag;\n\n#ifdef CONFIG_X86\n\tif (xen_pv_domain()) {\n\t\tif (xen_initial_domain())\n\t\t\tpci_xen_initial_domain();\n\t}\n\tif (xen_feature(XENFEAT_hvm_callback_vector)) {\n\t\txen_setup_callback_vector();\n\t\txen_alloc_callback_vector();\n\t}\n\n\tif (xen_hvm_domain()) {\n\t\tnative_init_IRQ();\n\t\t/* pci_xen_hvm_init must be called after native_init_IRQ so that\n\t\t * __acpi_register_gsi can point at the right function */\n\t\tpci_xen_hvm_init();\n\t} else {\n\t\tint rc;\n\t\tstruct physdev_pirq_eoi_gmfn eoi_gmfn;\n\n\t\tpirq_eoi_map = (void *)__get_free_page(GFP_KERNEL|__GFP_ZERO);\n\t\teoi_gmfn.gmfn = virt_to_gfn(pirq_eoi_map);\n\t\trc = HYPERVISOR_physdev_op(PHYSDEVOP_pirq_eoi_gmfn_v2, &eoi_gmfn);\n\t\tif (rc != 0) {\n\t\t\tfree_page((unsigned long) pirq_eoi_map);\n\t\t\tpirq_eoi_map = NULL;\n\t\t} else\n\t\t\tpirq_needs_eoi = pirq_check_eoi_map;\n\t}\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'xen/events: defer eoi in case of excessive number of events\n\nIn case rogue guests are sending events at high frequency it might\nhappen that xen_evtchn_do_upcall() won't stop processing events in\ndom0. As this is done in irq handling a crash might be the result.\n\nIn order to avoid that, delay further inter-domain events after some\ntime in xen_evtchn_do_upcall() by forcing eoi processing into a\nworker on the same cpu, thus inhibiting new events coming in.\n\nThe time after which eoi processing is to be delayed is configurable\nvia a new module parameter \"event_loop_timeout\" which specifies the\nmaximum event loop time in jiffies (default: 2, the value was chosen\nafter some tests showing that a value of 2 was the lowest with an\nonly slight drop of dom0 network throughput while multiple guests\nperformed an event storm).\n\nHow long eoi processing will be delayed can be specified via another\nparameter \"event_eoi_delay\" (again in jiffies, default 10, again the\nvalue was chosen after testing with different delay values).\n\nThis is part of XSA-332.\n\nCc: stable@vger.kernel.org\nReported-by: Julien Grall \nSigned-off-by: Juergen Gross \nReviewed-by: Stefano Stabellini \nReviewed-by: Wei Liu '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: MagickExport MagickBooleanType SetImageAlphaChannel(Image *image,\n const AlphaChannelOption alpha_type,ExceptionInfo *exception)\n{\n CacheView\n *image_view;\n\n MagickBooleanType\n status;\n\n ssize_t\n y;\n\n assert(image != (Image *) NULL);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"...\");\n assert(image->signature == MagickCoreSignature);\n status=MagickTrue;\n switch (alpha_type)\n {\n case ActivateAlphaChannel:\n {\n image->alpha_trait=BlendPixelTrait;\n break;\n }\n case AssociateAlphaChannel:\n {\n /*\n Associate alpha.\n */\n status=SetImageStorageClass(image,DirectClass,exception);\n if (status == MagickFalse)\n break;\n image_view=AcquireAuthenticCacheView(image,exception);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static) shared(status) \\\n magick_number_threads(image,image,image->rows,1)\n#endif\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;\n\n register ssize_t\n x;\n\n if (status == MagickFalse)\n continue;\n q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,\n exception);\n if (q == (Quantum *) NULL)\n {\n status=MagickFalse;\n continue;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n double\n gamma;\n\n register ssize_t\n i;\n\n gamma=QuantumScale*GetPixelAlpha(image,q);\n for (i=0; i < (ssize_t) GetPixelChannels(image); i++)\n {\n PixelChannel channel = GetPixelChannelChannel(image,i);\n PixelTrait traits = GetPixelChannelTraits(image,channel);\n if (channel == AlphaPixelChannel)\n continue;\n if ((traits & UpdatePixelTrait) == 0)\n continue;\n q[i]=ClampToQuantum(gamma*q[i]);\n }\n q+=GetPixelChannels(image);\n }\n if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)\n status=MagickFalse;\n }\n image_view=DestroyCacheView(image_view);\n image->alpha_trait=CopyPixelTrait;\n return(status);\n }\n case BackgroundAlphaChannel:\n {\n /*\n Set transparent pixels to background color.\n */\n if (image->alpha_trait == UndefinedPixelTrait)\n break;\n status=SetImageStorageClass(image,DirectClass,exception);\n if (status == MagickFalse)\n break;\n image_view=AcquireAuthenticCacheView(image,exception);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static) shared(status) \\\n magick_number_threads(image,image,image->rows,1)\n#endif\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;\n\n register ssize_t\n x;\n\n if (status == MagickFalse)\n continue;\n q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,\n exception);\n if (q == (Quantum *) NULL)\n {\n status=MagickFalse;\n continue;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (GetPixelAlpha(image,q) == TransparentAlpha)\n {\n SetPixelViaPixelInfo(image,&image->background_color,q);\n SetPixelChannel(image,AlphaPixelChannel,TransparentAlpha,q);\n }\n q+=GetPixelChannels(image);\n }\n if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)\n status=MagickFalse;\n }\n image_view=DestroyCacheView(image_view);\n return(status);\n }\n case CopyAlphaChannel:\n {\n image->alpha_trait=UpdatePixelTrait;\n status=CompositeImage(image,image,IntensityCompositeOp,MagickTrue,0,0,\n exception);\n break;\n }\n case DeactivateAlphaChannel:\n {\n if (image->alpha_trait == UndefinedPixelTrait)\n status=SetImageAlpha(image,OpaqueAlpha,exception);\n image->alpha_trait=CopyPixelTrait;\n break;\n }\n case DisassociateAlphaChannel:\n {\n /*\n Disassociate alpha.\n */\n status=SetImageStorageClass(image,DirectClass,exception);\n if (status == MagickFalse)\n break;\n image->alpha_trait=BlendPixelTrait;\n image_view=AcquireAuthenticCacheView(image,exception);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static) shared(status) \\\n magick_number_threads(image,image,image->rows,1)\n#endif\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;\n\n register ssize_t\n x;\n\n if (status == MagickFalse)\n continue;\n q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,\n exception);\n if (q == (Quantum *) NULL)\n {\n status=MagickFalse;\n continue;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n double\n gamma,\n Sa;\n\n register ssize_t\n i;\n\n Sa=QuantumScale*GetPixelAlpha(image,q);\n gamma=PerceptibleReciprocal(Sa);\n for (i=0; i < (ssize_t) GetPixelChannels(image); i++)\n {\n PixelChannel channel = GetPixelChannelChannel(image,i);\n PixelTrait traits = GetPixelChannelTraits(image,channel);\n if (channel == AlphaPixelChannel)\n continue;\n if ((traits & UpdatePixelTrait) == 0)\n continue;\n q[i]=ClampToQuantum(gamma*q[i]);\n }\n q+=GetPixelChannels(image);\n }\n if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)\n status=MagickFalse;\n }\n image_view=DestroyCacheView(image_view);\n image->alpha_trait=UndefinedPixelTrait;\n return(status);\n }\n case DiscreteAlphaChannel:\n {\n if (image->alpha_trait == UndefinedPixelTrait)\n status=SetImageAlpha(image,OpaqueAlpha,exception);\n image->alpha_trait=UpdatePixelTrait;\n break;\n }\n case ExtractAlphaChannel:\n {\n status=CompositeImage(image,image,AlphaCompositeOp,MagickTrue,0,0,\n exception);\n image->alpha_trait=UndefinedPixelTrait;\n break;\n }\n case OffAlphaChannel:\n {\n image->alpha_trait=UndefinedPixelTrait;\n break;\n }\n case OnAlphaChannel:\n {\n if (image->alpha_trait == UndefinedPixelTrait)\n status=SetImageAlpha(image,OpaqueAlpha,exception);\n image->alpha_trait=BlendPixelTrait;\n break;\n }\n case OpaqueAlphaChannel:\n {\n status=SetImageAlpha(image,OpaqueAlpha,exception);\n break;\n }\n case RemoveAlphaChannel:\n {\n /*\n Remove transparency.\n */\n if (image->alpha_trait == UndefinedPixelTrait)\n break;\n status=SetImageStorageClass(image,DirectClass,exception);\n if (status == MagickFalse)\n break;\n image_view=AcquireAuthenticCacheView(image,exception);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static) shared(status) \\\n magick_number_threads(image,image,image->rows,1)\n#endif\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;\n\n register ssize_t\n x;\n\n if (status == MagickFalse)\n continue;\n q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,\n exception);\n if (q == (Quantum *) NULL)\n {\n status=MagickFalse;\n continue;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n FlattenPixelInfo(image,&image->background_color,\n image->background_color.alpha,q,(double) GetPixelAlpha(image,q),q);\n q+=GetPixelChannels(image);\n }\n if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)\n status=MagickFalse;\n }\n image_view=DestroyCacheView(image_view);\n image->alpha_trait=image->background_color.alpha_trait;\n break;\n }\n case SetAlphaChannel:\n {\n if (image->alpha_trait == UndefinedPixelTrait)\n status=SetImageAlpha(image,OpaqueAlpha,exception);\n break;\n }\n case ShapeAlphaChannel:\n {\n /*\n Remove transparency.\n */\n image->alpha_trait=BlendPixelTrait;\n status=SetImageStorageClass(image,DirectClass,exception);\n if (status == MagickFalse)\n break;\n image_view=AcquireAuthenticCacheView(image,exception);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static) shared(status) \\\n magick_number_threads(image,image,image->rows,1)\n#endif\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n PixelInfo\n background;\n\n register Quantum\n *magick_restrict q;\n\n register ssize_t\n x;\n\n if (status == MagickFalse)\n continue;\n q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,\n exception);\n if (q == (Quantum *) NULL)\n {\n status=MagickFalse;\n continue;\n }\n ConformPixelInfo(image,&image->background_color,&background,exception);\n background.alpha_trait=BlendPixelTrait;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n background.alpha=GetPixelIntensity(image,q);\n SetPixelViaPixelInfo(image,&background,q);\n q+=GetPixelChannels(image);\n }\n if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)\n status=MagickFalse;\n }\n image_view=DestroyCacheView(image_view);\n break;\n }\n case TransparentAlphaChannel:\n {\n status=SetImageAlpha(image,TransparentAlpha,exception);\n break;\n }\n case UndefinedAlphaChannel:\n break;\n }\n if (status == MagickFalse)\n return(status);\n (void) SetPixelChannelMask(image,image->channel_mask);\n return(SyncImagePixelCache(image,exception));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1724'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline double MagickRound(double x)\n{\n /*\n Round the fraction to nearest integer.\n */\n if ((x-floor(x)) < (ceil(x)-x))\n return(floor(x));\n return(ceil(x));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1731'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void sunkbd_reinit(struct work_struct *work)\n{\n\tstruct sunkbd *sunkbd = container_of(work, struct sunkbd, tq);\n\n\twait_event_interruptible_timeout(sunkbd->wait, sunkbd->reset >= 0, HZ);\n\n\tserio_write(sunkbd->serio, SUNKBD_CMD_SETLED);\n\tserio_write(sunkbd->serio,\n\t\t(!!test_bit(LED_CAPSL, sunkbd->dev->led) << 3) |\n\t\t(!!test_bit(LED_SCROLLL, sunkbd->dev->led) << 2) |\n\t\t(!!test_bit(LED_COMPOSE, sunkbd->dev->led) << 1) |\n\t\t !!test_bit(LED_NUML, sunkbd->dev->led));\n\tserio_write(sunkbd->serio,\n\t\tSUNKBD_CMD_NOCLICK - !!test_bit(SND_CLICK, sunkbd->dev->snd));\n\tserio_write(sunkbd->serio,\n\t\tSUNKBD_CMD_BELLOFF - !!test_bit(SND_BELL, sunkbd->dev->snd));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Input: sunkbd - avoid use-after-free in teardown paths\n\nWe need to make sure we cancel the reinit work before we tear down the\ndriver structures.\n\nReported-by: Bodong Zhao \nTested-by: Bodong Zhao \nCc: stable@vger.kernel.org\nSigned-off-by: Dmitry Torokhov '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: input_csi_dispatch_sgr_colon(struct input_ctx *ictx, u_int i)\n{\n\tstruct grid_cell\t*gc = &ictx->cell.cell;\n\tchar\t\t\t*s = ictx->param_list[i].str, *copy, *ptr, *out;\n\tint\t\t\t p[8];\n\tu_int\t\t\t n;\n\tconst char\t\t*errstr;\n\n\tfor (n = 0; n < nitems(p); n++)\n\t\tp[n] = -1;\n\tn = 0;\n\n\tptr = copy = xstrdup(s);\n\twhile ((out = strsep(&ptr, \":\")) != NULL) {\n\t\tif (*out != '\\0') {\n\t\t\tp[n++] = strtonum(out, 0, INT_MAX, &errstr);\n\t\t\tif (errstr != NULL || n == nitems(p)) {\n\t\t\t\tfree(copy);\n\t\t\t\treturn;\n\t\t\t}\n\t\t} else\n\t\t\tn++;\n\t\tlog_debug(\"%s: %u = %d\", __func__, n - 1, p[n - 1]);\n\t}\n\tfree(copy);\n\n\tif (n == 0)\n\t\treturn;\n\tif (p[0] == 4) {\n\t\tif (n != 2)\n\t\t\treturn;\n\t\tswitch (p[1]) {\n\t\tcase 0:\n\t\t\tgc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tgc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;\n\t\t\tgc->attr |= GRID_ATTR_UNDERSCORE;\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tgc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;\n\t\t\tgc->attr |= GRID_ATTR_UNDERSCORE_2;\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tgc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;\n\t\t\tgc->attr |= GRID_ATTR_UNDERSCORE_3;\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\tgc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;\n\t\t\tgc->attr |= GRID_ATTR_UNDERSCORE_4;\n\t\t\tbreak;\n\t\tcase 5:\n\t\t\tgc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;\n\t\t\tgc->attr |= GRID_ATTR_UNDERSCORE_5;\n\t\t\tbreak;\n\t\t}\n\t\treturn;\n\t}\n\tif (n < 2 || (p[0] != 38 && p[0] != 48 && p[0] != 58))\n\t\treturn;\n\tswitch (p[1]) {\n\tcase 2:\n\t\tif (n < 3)\n\t\t\tbreak;\n\t\tif (n == 5)\n\t\t\ti = 2;\n\t\telse\n\t\t\ti = 3;\n\t\tif (n < i + 3)\n\t\t\tbreak;\n\t\tinput_csi_dispatch_sgr_rgb_do(ictx, p[0], p[i], p[i + 1],\n\t\t p[i + 2]);\n\t\tbreak;\n\tcase 5:\n\t\tif (n < 3)\n\t\t\tbreak;\n\t\tinput_csi_dispatch_sgr_256_do(ictx, p[0], p[2]);\n\t\tbreak;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Do not write after the end of the array and overwrite the stack when\ncolon-separated SGR sequences contain empty arguments. Reported by Sergey\nNizovtsev.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadTXTImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n char\n colorspace[MagickPathExtent],\n text[MagickPathExtent];\n\n double\n max_value,\n x_offset,\n y_offset;\n\n Image\n *image;\n\n PixelInfo\n pixel;\n\n MagickBooleanType\n status;\n\n QuantumAny\n range;\n\n register ssize_t\n i,\n x;\n\n register Quantum\n *q;\n\n ssize_t\n count,\n type,\n y;\n\n unsigned long\n depth,\n height,\n width;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n (void) memset(text,0,sizeof(text));\n (void) ReadBlobString(image,text);\n if (LocaleNCompare((char *) text,MagickTXTID,strlen(MagickTXTID)) != 0)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n x_offset=(-1.0);\n y_offset=(-1.0);\n do\n {\n width=0;\n height=0;\n max_value=0.0;\n *colorspace='\\0';\n count=(ssize_t) sscanf(text+32,\"%lu,%lu,%lf,%32s\",&width,&height,&max_value,\n colorspace);\n if ((count != 4) || (width == 0) || (height == 0) || (max_value == 0.0))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n image->columns=width;\n image->rows=height;\n if ((max_value == 0.0) || (max_value > 18446744073709551615.0))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n for (depth=1; (GetQuantumRange(depth)+1.0) < max_value; depth++) ;\n image->depth=depth;\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status != MagickFalse)\n status=ResetImagePixels(image,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n LocaleLower(colorspace);\n i=(ssize_t) strlen(colorspace)-1;\n image->alpha_trait=UndefinedPixelTrait;\n if ((i > 0) && (colorspace[i] == 'a'))\n {\n colorspace[i]='\\0';\n image->alpha_trait=BlendPixelTrait;\n }\n type=ParseCommandOption(MagickColorspaceOptions,MagickFalse,colorspace);\n if (type < 0)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n (void) SetImageColorspace(image,(ColorspaceType) type,exception);\n (void) SetImageBackgroundColor(image,exception);\n GetPixelInfo(image,&pixel);\n range=GetQuantumRange(image->depth);\n status=MagickTrue;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n double\n alpha,\n black,\n blue,\n green,\n red;\n\n if (status == MagickFalse)\n break;\n red=0.0;\n green=0.0;\n blue=0.0;\n black=0.0;\n alpha=0.0;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (ReadBlobString(image,text) == (char *) NULL)\n {\n status=MagickFalse;\n break;\n }\n switch (image->colorspace)\n {\n case LinearGRAYColorspace:\n case GRAYColorspace:\n {\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n count=(ssize_t) sscanf(text,\"%lf,%lf: (%lf%*[%,]%lf%*[%,]\",\n &x_offset,&y_offset,&red,&alpha);\n green=red;\n blue=red;\n break;\n }\n count=(ssize_t) sscanf(text,\"%lf,%lf: (%lf%*[%,]\",&x_offset,\n &y_offset,&red);\n green=red;\n blue=red;\n break;\n }\n case CMYKColorspace:\n {\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n count=(ssize_t) sscanf(text,\n \"%lf,%lf: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]\",\n &x_offset,&y_offset,&red,&green,&blue,&black,&alpha);\n break;\n }\n count=(ssize_t) sscanf(text,\n \"%lf,%lf: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]\",&x_offset,\n &y_offset,&red,&green,&blue,&black);\n break;\n }\n default:\n {\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n count=(ssize_t) sscanf(text,\n \"%lf,%lf: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]\",\n &x_offset,&y_offset,&red,&green,&blue,&alpha);\n break;\n }\n count=(ssize_t) sscanf(text,\"%lf,%lf: (%lf%*[%,]%lf%*[%,]%lf%*[%,]\",\n &x_offset,&y_offset,&red,&green,&blue);\n break;\n }\n }\n if (strchr(text,'%') != (char *) NULL)\n {\n red*=0.01*range;\n green*=0.01*range;\n blue*=0.01*range;\n black*=0.01*range;\n alpha*=0.01*range;\n }\n if (image->colorspace == LabColorspace)\n {\n green+=(range+1)/2.0;\n blue+=(range+1)/2.0;\n }\n pixel.red=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (red+0.5),\n range);\n pixel.green=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (green+0.5),\n range);\n pixel.blue=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (blue+0.5),\n range);\n pixel.black=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (black+0.5),\n range);\n pixel.alpha=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (alpha+0.5),\n range);\n q=GetAuthenticPixels(image,(ssize_t) x_offset,(ssize_t) y_offset,1,1,\n exception);\n if (q == (Quantum *) NULL)\n continue;\n SetPixelViaPixelInfo(image,&pixel,q);\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n {\n status=MagickFalse;\n break;\n }\n }\n }\n if (status == MagickFalse)\n break;\n *text='\\0';\n (void) ReadBlobString(image,text);\n if (LocaleNCompare((char *) text,MagickTXTID,strlen(MagickTXTID)) == 0)\n {\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image,exception);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n GetBlobSize(image));\n if (status == MagickFalse)\n break;\n }\n } while (LocaleNCompare((char *) text,MagickTXTID,strlen(MagickTXTID)) == 0);\n (void) CloseBlob(image);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1719'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static MagickRealType ApplyEvaluateOperator(RandomInfo *random_info,\n const Quantum pixel,const MagickEvaluateOperator op,\n const MagickRealType value)\n{\n MagickRealType\n result;\n\n result=0.0;\n switch (op)\n {\n case UndefinedEvaluateOperator:\n break;\n case AbsEvaluateOperator:\n {\n result=(MagickRealType) fabs((double) (pixel+value));\n break;\n }\n case AddEvaluateOperator:\n {\n result=(MagickRealType) (pixel+value);\n break;\n }\n case AddModulusEvaluateOperator:\n {\n /*\n This returns a 'floored modulus' of the addition which is a\n positive result. It differs from % or fmod() which returns a\n 'truncated modulus' result, where floor() is replaced by trunc()\n and could return a negative result (which is clipped).\n */\n result=pixel+value;\n result-=(QuantumRange+1.0)*floor((double) result/(QuantumRange+1.0));\n break;\n }\n case AndEvaluateOperator:\n {\n result=(MagickRealType) ((size_t) pixel & (size_t) (value+0.5));\n break;\n }\n case CosineEvaluateOperator:\n {\n result=(MagickRealType) (QuantumRange*(0.5*cos((double) (2.0*MagickPI*\n QuantumScale*pixel*value))+0.5));\n break;\n }\n case DivideEvaluateOperator:\n {\n result=pixel/(value == 0.0 ? 1.0 : value);\n break;\n }\n case ExponentialEvaluateOperator:\n {\n result=(MagickRealType) (QuantumRange*exp((double) (value*QuantumScale*\n pixel)));\n break;\n }\n case GaussianNoiseEvaluateOperator:\n {\n result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,\n GaussianNoise,value);\n break;\n }\n case ImpulseNoiseEvaluateOperator:\n {\n result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,\n ImpulseNoise,value);\n break;\n }\n case LaplacianNoiseEvaluateOperator:\n {\n result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,\n LaplacianNoise,value);\n break;\n }\n case LeftShiftEvaluateOperator:\n {\n result=(MagickRealType) ((size_t) pixel << (size_t) (value+0.5));\n break;\n }\n case LogEvaluateOperator:\n {\n if ((QuantumScale*pixel) >= MagickEpsilon)\n result=(MagickRealType) (QuantumRange*log((double) (QuantumScale*value*\n pixel+1.0))/log((double) (value+1.0)));\n break;\n }\n case MaxEvaluateOperator:\n {\n result=(MagickRealType) EvaluateMax((double) pixel,value);\n break;\n }\n case MeanEvaluateOperator:\n {\n result=(MagickRealType) (pixel+value);\n break;\n }\n case MedianEvaluateOperator:\n {\n result=(MagickRealType) (pixel+value);\n break;\n }\n case MinEvaluateOperator:\n {\n result=(MagickRealType) MagickMin((double) pixel,value);\n break;\n }\n case MultiplicativeNoiseEvaluateOperator:\n {\n result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,\n MultiplicativeGaussianNoise,value);\n break;\n }\n case MultiplyEvaluateOperator:\n {\n result=(MagickRealType) (value*pixel);\n break;\n }\n case OrEvaluateOperator:\n {\n result=(MagickRealType) ((size_t) pixel | (size_t) (value+0.5));\n break;\n }\n case PoissonNoiseEvaluateOperator:\n {\n result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,\n PoissonNoise,value);\n break;\n }\n case PowEvaluateOperator:\n {\n result=(MagickRealType) (QuantumRange*pow((double) (QuantumScale*pixel),\n (double) value));\n break;\n }\n case RightShiftEvaluateOperator:\n {\n result=(MagickRealType) ((size_t) pixel >> (size_t) (value+0.5));\n break;\n }\n case RootMeanSquareEvaluateOperator:\n {\n result=(MagickRealType) (pixel*pixel+value);\n break;\n }\n case SetEvaluateOperator:\n {\n result=value;\n break;\n }\n case SineEvaluateOperator:\n {\n result=(MagickRealType) (QuantumRange*(0.5*sin((double) (2.0*MagickPI*\n QuantumScale*pixel*value))+0.5));\n break;\n }\n case SubtractEvaluateOperator:\n {\n result=(MagickRealType) (pixel-value);\n break;\n }\n case SumEvaluateOperator:\n {\n result=(MagickRealType) (pixel+value);\n break;\n }\n case ThresholdEvaluateOperator:\n {\n result=(MagickRealType) (((MagickRealType) pixel <= value) ? 0 :\n QuantumRange);\n break;\n }\n case ThresholdBlackEvaluateOperator:\n {\n result=(MagickRealType) (((MagickRealType) pixel <= value) ? 0 : pixel);\n break;\n }\n case ThresholdWhiteEvaluateOperator:\n {\n result=(MagickRealType) (((MagickRealType) pixel > value) ? QuantumRange :\n pixel);\n break;\n }\n case UniformNoiseEvaluateOperator:\n {\n result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,\n UniformNoise,value);\n break;\n }\n case XorEvaluateOperator:\n {\n result=(MagickRealType) ((size_t) pixel ^ (size_t) (value+0.5));\n break;\n }\n }\n return(result);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-190'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1735'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline unsigned int ScaleQuantumToMap(const Quantum quantum)\n{\n if (quantum <= 0.0)\n return(0UL);\n if ((quantum/281479271743489.0) >= MaxMap)\n return((unsigned int) MaxMap);\n return((unsigned int) (quantum/281479271743489.0+0.5));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1751'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline MagickSizeType ScaleQuantumToLongLong(const Quantum quantum)\n{\n#if !defined(MAGICKCORE_HDRI_SUPPORT)\n return((MagickSizeType) (MagickULLConstant(4294967297)*quantum));\n#else\n if (quantum <= 0.0)\n return(0UL);\n if ((4294967297.0*quantum) >= 18446744073709551615.0)\n return(MagickULLConstant(18446744073709551615));\n return((MagickSizeType) (4294967297.0*quantum+0.5));\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1751'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: wsrep_cb_status_t wsrep_sst_donate_cb (void* app_ctx, void* recv_ctx,\n const void* msg, size_t msg_len,\n const wsrep_gtid_t* current_gtid,\n const char* state, size_t state_len,\n bool bypass)\n{\n /* This will be reset when sync callback is called.\n * Should we set wsrep_ready to FALSE here too? */\n local_status.set(WSREP_MEMBER_DONOR);\n\n const char* method = (char*)msg;\n size_t method_len = strlen (method);\n const char* data = method + method_len + 1;\n\n char uuid_str[37];\n wsrep_uuid_print (¤t_gtid->uuid, uuid_str, sizeof(uuid_str));\n\n wsp::env env(NULL);\n if (env.error())\n {\n WSREP_ERROR(\"wsrep_sst_donate_cb(): env var ctor failed: %d\", -env.error());\n return WSREP_CB_FAILURE;\n }\n\n int ret;\n if ((ret= sst_append_auth_env(env, sst_auth_real)))\n {\n WSREP_ERROR(\"wsrep_sst_donate_cb(): appending auth env failed: %d\", ret);\n return WSREP_CB_FAILURE;\n }\n\n if (!strcmp (WSREP_SST_MYSQLDUMP, method))\n {\n ret = sst_donate_mysqldump(data, ¤t_gtid->uuid, uuid_str,\n current_gtid->seqno, bypass, env());\n }\n else\n {\n ret = sst_donate_other(method, data, uuid_str,\n current_gtid->seqno, bypass, env());\n }\n\n return (ret >= 0 ? WSREP_CB_SUCCESS : WSREP_CB_FAILURE);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-77'], 'message': 'codership/mysql-wsrep-bugs#758 Donor uses invalid SST methods'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: lldp_decode(struct lldpd *cfg, char *frame, int s,\n struct lldpd_hardware *hardware,\n struct lldpd_chassis **newchassis, struct lldpd_port **newport)\n{\n\tstruct lldpd_chassis *chassis;\n\tstruct lldpd_port *port;\n\tconst char lldpaddr[] = LLDP_MULTICAST_ADDR;\n\tconst char dot1[] = LLDP_TLV_ORG_DOT1;\n\tconst char dot3[] = LLDP_TLV_ORG_DOT3;\n\tconst char med[] = LLDP_TLV_ORG_MED;\n\tconst char dcbx[] = LLDP_TLV_ORG_DCBX;\n\tunsigned char orgid[3];\n\tint length, gotend = 0, ttl_received = 0;\n\tint tlv_size, tlv_type, tlv_subtype;\n\tu_int8_t *pos, *tlv;\n\tchar *b;\n#ifdef ENABLE_DOT1\n\tstruct lldpd_vlan *vlan = NULL;\n\tint vlan_len;\n\tstruct lldpd_ppvid *ppvid;\n\tstruct lldpd_pi *pi = NULL;\n#endif\n\tstruct lldpd_mgmt *mgmt;\n\tint af;\n\tu_int8_t addr_str_length, addr_str_buffer[32];\n\tu_int8_t addr_family, addr_length, *addr_ptr, iface_subtype;\n\tu_int32_t iface_number, iface;\n#ifdef ENABLE_CUSTOM\n\tstruct lldpd_custom *custom = NULL;\n#endif\n\n\tlog_debug(\"lldp\", \"receive LLDP PDU on %s\",\n\t hardware->h_ifname);\n\n\tif ((chassis = calloc(1, sizeof(struct lldpd_chassis))) == NULL) {\n\t\tlog_warn(\"lldp\", \"failed to allocate remote chassis\");\n\t\treturn -1;\n\t}\n\tTAILQ_INIT(&chassis->c_mgmt);\n\tif ((port = calloc(1, sizeof(struct lldpd_port))) == NULL) {\n\t\tlog_warn(\"lldp\", \"failed to allocate remote port\");\n\t\tfree(chassis);\n\t\treturn -1;\n\t}\n#ifdef ENABLE_DOT1\n\tTAILQ_INIT(&port->p_vlans);\n\tTAILQ_INIT(&port->p_ppvids);\n\tTAILQ_INIT(&port->p_pids);\n#endif\n#ifdef ENABLE_CUSTOM\n\tTAILQ_INIT(&port->p_custom_list);\n#endif\n\n\tlength = s;\n\tpos = (u_int8_t*)frame;\n\n\tif (length < 2*ETHER_ADDR_LEN + sizeof(u_int16_t)) {\n\t\tlog_warnx(\"lldp\", \"too short frame received on %s\", hardware->h_ifname);\n\t\tgoto malformed;\n\t}\n\tif (PEEK_CMP(lldpaddr, ETHER_ADDR_LEN) != 0) {\n\t\tlog_info(\"lldp\", \"frame not targeted at LLDP multicast address received on %s\",\n\t\t hardware->h_ifname);\n\t\tgoto malformed;\n\t}\n\tPEEK_DISCARD(ETHER_ADDR_LEN);\t/* Skip source address */\n\tif (PEEK_UINT16 != ETHERTYPE_LLDP) {\n\t\tlog_info(\"lldp\", \"non LLDP frame received on %s\",\n\t\t hardware->h_ifname);\n\t\tgoto malformed;\n\t}\n\n\twhile (length && (!gotend)) {\n\t\tif (length < 2) {\n\t\t\tlog_warnx(\"lldp\", \"tlv header too short received on %s\",\n\t\t\t hardware->h_ifname);\n\t\t\tgoto malformed;\n\t\t}\n\t\ttlv_size = PEEK_UINT16;\n\t\ttlv_type = tlv_size >> 9;\n\t\ttlv_size = tlv_size & 0x1ff;\n\t\t(void)PEEK_SAVE(tlv);\n\t\tif (length < tlv_size) {\n\t\t\tlog_warnx(\"lldp\", \"frame too short for tlv received on %s\",\n\t\t\t hardware->h_ifname);\n\t\t\tgoto malformed;\n\t\t}\n\t\tswitch (tlv_type) {\n\t\tcase LLDP_TLV_END:\n\t\t\tif (tlv_size != 0) {\n\t\t\t\tlog_warnx(\"lldp\", \"lldp end received with size not null on %s\",\n\t\t\t\t hardware->h_ifname);\n\t\t\t\tgoto malformed;\n\t\t\t}\n\t\t\tif (length)\n\t\t\t\tlog_debug(\"lldp\", \"extra data after lldp end on %s\",\n\t\t\t\t hardware->h_ifname);\n\t\t\tgotend = 1;\n\t\t\tbreak;\n\t\tcase LLDP_TLV_CHASSIS_ID:\n\t\tcase LLDP_TLV_PORT_ID:\n\t\t\tCHECK_TLV_SIZE(2, \"Port Id\");\n\t\t\ttlv_subtype = PEEK_UINT8;\n\t\t\tif ((tlv_subtype == 0) || (tlv_subtype > 7)) {\n\t\t\t\tlog_warnx(\"lldp\", \"unknown subtype for tlv id received on %s\",\n\t\t\t\t hardware->h_ifname);\n\t\t\t\tgoto malformed;\n\t\t\t}\n\t\t\tif ((b = (char *)calloc(1, tlv_size - 1)) == NULL) {\n\t\t\t\tlog_warn(\"lldp\", \"unable to allocate memory for id tlv \"\n\t\t\t\t \"received on %s\",\n\t\t\t\t hardware->h_ifname);\n\t\t\t\tgoto malformed;\n\t\t\t}\n\t\t\tPEEK_BYTES(b, tlv_size - 1);\n\t\t\tif (tlv_type == LLDP_TLV_PORT_ID) {\n\t\t\t\tport->p_id_subtype = tlv_subtype;\n\t\t\t\tport->p_id = b;\n\t\t\t\tport->p_id_len = tlv_size - 1;\n\t\t\t} else {\n\t\t\t\tchassis->c_id_subtype = tlv_subtype;\n\t\t\t\tchassis->c_id = b;\n\t\t\t\tchassis->c_id_len = tlv_size - 1;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase LLDP_TLV_TTL:\n\t\t\tCHECK_TLV_SIZE(2, \"TTL\");\n\t\t\tchassis->c_ttl = PEEK_UINT16;\n\t\t\tttl_received = 1;\n\t\t\tbreak;\n\t\tcase LLDP_TLV_PORT_DESCR:\n\t\tcase LLDP_TLV_SYSTEM_NAME:\n\t\tcase LLDP_TLV_SYSTEM_DESCR:\n\t\t\tif (tlv_size < 1) {\n\t\t\t\tlog_debug(\"lldp\", \"empty tlv received on %s\",\n\t\t\t\t hardware->h_ifname);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif ((b = (char *)calloc(1, tlv_size + 1)) == NULL) {\n\t\t\t\tlog_warn(\"lldp\", \"unable to allocate memory for string tlv \"\n\t\t\t\t \"received on %s\",\n\t\t\t\t hardware->h_ifname);\n\t\t\t\tgoto malformed;\n\t\t\t}\n\t\t\tPEEK_BYTES(b, tlv_size);\n\t\t\tif (tlv_type == LLDP_TLV_PORT_DESCR)\n\t\t\t\tport->p_descr = b;\n\t\t\telse if (tlv_type == LLDP_TLV_SYSTEM_NAME)\n\t\t\t\tchassis->c_name = b;\n\t\t\telse chassis->c_descr = b;\n\t\t\tbreak;\n\t\tcase LLDP_TLV_SYSTEM_CAP:\n\t\t\tCHECK_TLV_SIZE(4, \"System capabilities\");\n\t\t\tchassis->c_cap_available = PEEK_UINT16;\n\t\t\tchassis->c_cap_enabled = PEEK_UINT16;\n\t\t\tbreak;\n\t\tcase LLDP_TLV_MGMT_ADDR:\n\t\t\tCHECK_TLV_SIZE(1, \"Management address\");\n\t\t\taddr_str_length = PEEK_UINT8;\n\t\t\tif (addr_str_length > sizeof(addr_str_buffer)) {\n\t\t\t\tlog_warnx(\"lldp\", \"too large management address on %s\",\n\t\t\t\t hardware->h_ifname);\n\t\t\t\tgoto malformed;\n\t\t\t}\n\t\t\tCHECK_TLV_SIZE(1 + addr_str_length, \"Management address\");\n\t\t\tPEEK_BYTES(addr_str_buffer, addr_str_length);\n\t\t\taddr_length = addr_str_length - 1;\n\t\t\taddr_family = addr_str_buffer[0];\n\t\t\taddr_ptr = &addr_str_buffer[1];\n\t\t\tCHECK_TLV_SIZE(1 + addr_str_length + 5, \"Management address\");\n\t\t\tiface_subtype = PEEK_UINT8;\n\t\t\tiface_number = PEEK_UINT32;\n\n\t\t\taf = lldpd_af_from_lldp_proto(addr_family);\n\t\t\tif (af == LLDPD_AF_UNSPEC)\n\t\t\t\tbreak;\n\t\t\tif (iface_subtype == LLDP_MGMT_IFACE_IFINDEX)\n\t\t\t\tiface = iface_number;\n\t\t\telse\n\t\t\t\tiface = 0;\n\t\t\tmgmt = lldpd_alloc_mgmt(af, addr_ptr, addr_length, iface);\n\t\t\tif (mgmt == NULL) {\n\t\t\t\tassert(errno == ENOMEM);\n\t\t\t\tlog_warn(\"lldp\", \"unable to allocate memory \"\n\t\t\t\t \"for management address\");\n\t\t\t\tgoto malformed;\n\t\t\t}\n\t\t\tTAILQ_INSERT_TAIL(&chassis->c_mgmt, mgmt, m_entries);\n\t\t\tbreak;\n\t\tcase LLDP_TLV_ORG:\n\t\t\tCHECK_TLV_SIZE(1 + (int)sizeof(orgid), \"Organisational\");\n\t\t\tPEEK_BYTES(orgid, sizeof(orgid));\n\t\t\ttlv_subtype = PEEK_UINT8;\n\t\t\tif (memcmp(dot1, orgid, sizeof(orgid)) == 0) {\n#ifndef ENABLE_DOT1\n\t\t\t\thardware->h_rx_unrecognized_cnt++;\n#else\n\t\t\t\t/* Dot1 */\n\t\t\t\tswitch (tlv_subtype) {\n\t\t\t\tcase LLDP_TLV_DOT1_VLANNAME:\n\t\t\t\t\tCHECK_TLV_SIZE(7, \"VLAN\");\n\t\t\t\t\tif ((vlan = (struct lldpd_vlan *)calloc(1,\n\t\t\t\t\t\t sizeof(struct lldpd_vlan))) == NULL) {\n\t\t\t\t\t\tlog_warn(\"lldp\", \"unable to alloc vlan \"\n\t\t\t\t\t\t \"structure for \"\n\t\t\t\t\t\t \"tlv received on %s\",\n\t\t\t\t\t\t hardware->h_ifname);\n\t\t\t\t\t\tgoto malformed;\n\t\t\t\t\t}\n\t\t\t\t\tvlan->v_vid = PEEK_UINT16;\n\t\t\t\t\tvlan_len = PEEK_UINT8;\n\t\t\t\t\tCHECK_TLV_SIZE(7 + vlan_len, \"VLAN\");\n\t\t\t\t\tif ((vlan->v_name =\n\t\t\t\t\t\t(char *)calloc(1, vlan_len + 1)) == NULL) {\n\t\t\t\t\t\tlog_warn(\"lldp\", \"unable to alloc vlan name for \"\n\t\t\t\t\t\t \"tlv received on %s\",\n\t\t\t\t\t\t hardware->h_ifname);\n\t\t\t\t\t\tgoto malformed;\n\t\t\t\t\t}\n\t\t\t\t\tPEEK_BYTES(vlan->v_name, vlan_len);\n\t\t\t\t\tTAILQ_INSERT_TAIL(&port->p_vlans,\n\t\t\t\t\t vlan, v_entries);\n\t\t\t\t\tvlan = NULL;\n\t\t\t\t\tbreak;\n\t\t\t\tcase LLDP_TLV_DOT1_PVID:\n\t\t\t\t\tCHECK_TLV_SIZE(6, \"PVID\");\n\t\t\t\t\tport->p_pvid = PEEK_UINT16;\n\t\t\t\t\tbreak;\n\t\t\t\tcase LLDP_TLV_DOT1_PPVID:\n\t\t\t\t\tCHECK_TLV_SIZE(7, \"PPVID\");\n\t\t\t\t\t/* validation needed */\n\t\t\t\t\t/* PPVID has to be unique if more than\n\t\t\t\t\t one PPVID TLVs are received - \n\t\t\t\t\t discard if duplicate */\n\t\t\t\t\t/* if support bit is not set and \n\t\t\t\t\t enabled bit is set - PPVID TLV is\n\t\t\t\t\t considered error and discarded */\n\t\t\t\t\t/* if PPVID > 4096 - bad and discard */\n\t\t\t\t\tif ((ppvid = (struct lldpd_ppvid *)calloc(1,\n\t\t\t\t\t\t sizeof(struct lldpd_ppvid))) == NULL) {\n\t\t\t\t\t\tlog_warn(\"lldp\", \"unable to alloc ppvid \"\n\t\t\t\t\t\t \"structure for \"\n\t\t\t\t\t\t \"tlv received on %s\",\n\t\t\t\t\t\t hardware->h_ifname);\n\t\t\t\t\t\tgoto malformed;\n\t\t\t\t\t}\n\t\t\t\t\tppvid->p_cap_status = PEEK_UINT8;\n\t\t\t\t\tppvid->p_ppvid = PEEK_UINT16;\t\n\t\t\t\t\tTAILQ_INSERT_TAIL(&port->p_ppvids,\n\t\t\t\t\t ppvid, p_entries);\n\t\t\t\t\tbreak;\n\t\t\t\tcase LLDP_TLV_DOT1_PI:\n\t\t\t\t\t/* validation needed */\n\t\t\t\t\t/* PI has to be unique if more than \n\t\t\t\t\t one PI TLVs are received - discard\n\t\t\t\t\t if duplicate ?? */\n\t\t\t\t\tCHECK_TLV_SIZE(5, \"PI\");\n\t\t\t\t\tif ((pi = (struct lldpd_pi *)calloc(1,\n\t\t\t\t\t\t sizeof(struct lldpd_pi))) == NULL) {\n\t\t\t\t\t\tlog_warn(\"lldp\", \"unable to alloc PI \"\n\t\t\t\t\t\t \"structure for \"\n\t\t\t\t\t\t \"tlv received on %s\",\n\t\t\t\t\t\t hardware->h_ifname);\n\t\t\t\t\t\tgoto malformed;\n\t\t\t\t\t}\n\t\t\t\t\tpi->p_pi_len = PEEK_UINT8;\n\t\t\t\t\tCHECK_TLV_SIZE(5 + pi->p_pi_len, \"PI\");\n\t\t\t\t\tif ((pi->p_pi =\n\t\t\t\t\t\t(char *)calloc(1, pi->p_pi_len)) == NULL) {\n\t\t\t\t\t\tlog_warn(\"lldp\", \"unable to alloc pid name for \"\n\t\t\t\t\t\t \"tlv received on %s\",\n\t\t\t\t\t\t hardware->h_ifname);\n\t\t\t\t\t\tgoto malformed;\n\t\t\t\t\t}\n\t\t\t\t\tPEEK_BYTES(pi->p_pi, pi->p_pi_len);\n\t\t\t\t\tTAILQ_INSERT_TAIL(&port->p_pids,\n\t\t\t\t\t pi, p_entries);\n\t\t\t\t\tpi = NULL;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\t/* Unknown Dot1 TLV, ignore it */\n\t\t\t\t\thardware->h_rx_unrecognized_cnt++;\n\t\t\t\t}\n#endif\n\t\t\t} else if (memcmp(dot3, orgid, sizeof(orgid)) == 0) {\n#ifndef ENABLE_DOT3\n\t\t\t\thardware->h_rx_unrecognized_cnt++;\n#else\n\t\t\t\t/* Dot3 */\n\t\t\t\tswitch (tlv_subtype) {\n\t\t\t\tcase LLDP_TLV_DOT3_MAC:\n\t\t\t\t\tCHECK_TLV_SIZE(9, \"MAC/PHY\");\n\t\t\t\t\tport->p_macphy.autoneg_support = PEEK_UINT8;\n\t\t\t\t\tport->p_macphy.autoneg_enabled =\n\t\t\t\t\t (port->p_macphy.autoneg_support & 0x2) >> 1;\n\t\t\t\t\tport->p_macphy.autoneg_support =\n\t\t\t\t\t port->p_macphy.autoneg_support & 0x1;\n\t\t\t\t\tport->p_macphy.autoneg_advertised =\n\t\t\t\t\t PEEK_UINT16;\n\t\t\t\t\tport->p_macphy.mau_type = PEEK_UINT16;\n\t\t\t\t\tbreak;\n\t\t\t\tcase LLDP_TLV_DOT3_LA:\n\t\t\t\t\tCHECK_TLV_SIZE(9, \"Link aggregation\");\n\t\t\t\t\tPEEK_DISCARD_UINT8;\n\t\t\t\t\tport->p_aggregid = PEEK_UINT32;\n\t\t\t\t\tbreak;\n\t\t\t\tcase LLDP_TLV_DOT3_MFS:\n\t\t\t\t\tCHECK_TLV_SIZE(6, \"MFS\");\n\t\t\t\t\tport->p_mfs = PEEK_UINT16;\n\t\t\t\t\tbreak;\n\t\t\t\tcase LLDP_TLV_DOT3_POWER:\n\t\t\t\t\tCHECK_TLV_SIZE(7, \"Power\");\n\t\t\t\t\tport->p_power.devicetype = PEEK_UINT8;\n\t\t\t\t\tport->p_power.supported =\n\t\t\t\t\t\t(port->p_power.devicetype & 0x2) >> 1;\n\t\t\t\t\tport->p_power.enabled =\n\t\t\t\t\t\t(port->p_power.devicetype & 0x4) >> 2;\n\t\t\t\t\tport->p_power.paircontrol =\n\t\t\t\t\t\t(port->p_power.devicetype & 0x8) >> 3;\n\t\t\t\t\tport->p_power.devicetype =\n\t\t\t\t\t\t(port->p_power.devicetype & 0x1)?\n\t\t\t\t\t\tLLDP_DOT3_POWER_PSE:LLDP_DOT3_POWER_PD;\n\t\t\t\t\tport->p_power.pairs = PEEK_UINT8;\n\t\t\t\t\tport->p_power.class = PEEK_UINT8;\n\t\t\t\t\t/* 802.3at? */\n\t\t\t\t\tif (tlv_size >= 12) {\n\t\t\t\t\t\tport->p_power.powertype = PEEK_UINT8;\n\t\t\t\t\t\tport->p_power.source =\n\t\t\t\t\t\t (port->p_power.powertype & (1<<5 | 1<<4)) >> 4;\n\t\t\t\t\t\tport->p_power.priority =\n\t\t\t\t\t\t (port->p_power.powertype & (1<<1 | 1<<0));\n\t\t\t\t\t\tport->p_power.powertype =\n\t\t\t\t\t\t (port->p_power.powertype & (1<<7))?\n\t\t\t\t\t\t LLDP_DOT3_POWER_8023AT_TYPE1:\n\t\t\t\t\t\t LLDP_DOT3_POWER_8023AT_TYPE2;\n\t\t\t\t\t\tport->p_power.requested = PEEK_UINT16;\n\t\t\t\t\t\tport->p_power.allocated = PEEK_UINT16;\n\t\t\t\t\t} else\n\t\t\t\t\t\tport->p_power.powertype =\n\t\t\t\t\t\t LLDP_DOT3_POWER_8023AT_OFF;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\t/* Unknown Dot3 TLV, ignore it */\n\t\t\t\t\thardware->h_rx_unrecognized_cnt++;\n\t\t\t\t}\n#endif\n\t\t\t} else if (memcmp(med, orgid, sizeof(orgid)) == 0) {\n\t\t\t\t/* LLDP-MED */\n#ifndef ENABLE_LLDPMED\n\t\t\t\thardware->h_rx_unrecognized_cnt++;\n#else\n\t\t\t\tu_int32_t policy;\n\t\t\t\tunsigned loctype;\n\t\t\t\tunsigned power;\n\n\t\t\t\tswitch (tlv_subtype) {\n\t\t\t\tcase LLDP_TLV_MED_CAP:\n\t\t\t\t\tCHECK_TLV_SIZE(7, \"LLDP-MED capabilities\");\n\t\t\t\t\tchassis->c_med_cap_available = PEEK_UINT16;\n\t\t\t\t\tchassis->c_med_type = PEEK_UINT8;\n\t\t\t\t\tport->p_med_cap_enabled |=\n\t\t\t\t\t LLDP_MED_CAP_CAP;\n\t\t\t\t\tbreak;\n\t\t\t\tcase LLDP_TLV_MED_POLICY:\n\t\t\t\t\tCHECK_TLV_SIZE(8, \"LLDP-MED policy\");\n\t\t\t\t\tpolicy = PEEK_UINT32;\n\t\t\t\t\tif (((policy >> 24) < 1) ||\n\t\t\t\t\t ((policy >> 24) > LLDP_MED_APPTYPE_LAST)) {\n\t\t\t\t\t\tlog_info(\"lldp\", \"unknown policy field %d \"\n\t\t\t\t\t\t \"received on %s\",\n\t\t\t\t\t\t policy,\n\t\t\t\t\t\t hardware->h_ifname);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tport->p_med_policy[(policy >> 24) - 1].type =\n\t\t\t\t\t (policy >> 24);\n\t\t\t\t\tport->p_med_policy[(policy >> 24) - 1].unknown =\n\t\t\t\t\t ((policy & 0x800000) != 0);\n\t\t\t\t\tport->p_med_policy[(policy >> 24) - 1].tagged =\n\t\t\t\t\t ((policy & 0x400000) != 0);\n\t\t\t\t\tport->p_med_policy[(policy >> 24) - 1].vid =\n\t\t\t\t\t (policy & 0x001FFE00) >> 9;\n\t\t\t\t\tport->p_med_policy[(policy >> 24) - 1].priority =\n\t\t\t\t\t (policy & 0x1C0) >> 6;\n\t\t\t\t\tport->p_med_policy[(policy >> 24) - 1].dscp =\n\t\t\t\t\t policy & 0x3F;\n\t\t\t\t\tport->p_med_cap_enabled |=\n\t\t\t\t\t LLDP_MED_CAP_POLICY;\n\t\t\t\t\tbreak;\n\t\t\t\tcase LLDP_TLV_MED_LOCATION:\n\t\t\t\t\tCHECK_TLV_SIZE(5, \"LLDP-MED Location\");\n\t\t\t\t\tloctype = PEEK_UINT8;\n\t\t\t\t\tif ((loctype < 1) ||\n\t\t\t\t\t (loctype > LLDP_MED_LOCFORMAT_LAST)) {\n\t\t\t\t\t\tlog_info(\"lldp\", \"unknown location type \"\n\t\t\t\t\t\t \"received on %s\",\n\t\t\t\t\t\t hardware->h_ifname);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tif ((port->p_med_location[loctype - 1].data =\n\t\t\t\t\t\t(char*)malloc(tlv_size - 5)) == NULL) {\n\t\t\t\t\t\tlog_warn(\"lldp\", \"unable to allocate memory \"\n\t\t\t\t\t\t \"for LLDP-MED location for \"\n\t\t\t\t\t\t \"frame received on %s\",\n\t\t\t\t\t\t hardware->h_ifname);\n\t\t\t\t\t\tgoto malformed;\n\t\t\t\t\t}\n\t\t\t\t\tPEEK_BYTES(port->p_med_location[loctype - 1].data,\n\t\t\t\t\t tlv_size - 5);\n\t\t\t\t\tport->p_med_location[loctype - 1].data_len =\n\t\t\t\t\t tlv_size - 5;\n\t\t\t\t\tport->p_med_location[loctype - 1].format = loctype;\n\t\t\t\t\tport->p_med_cap_enabled |=\n\t\t\t\t\t LLDP_MED_CAP_LOCATION;\n\t\t\t\t\tbreak;\n\t\t\t\tcase LLDP_TLV_MED_MDI:\n\t\t\t\t\tCHECK_TLV_SIZE(7, \"LLDP-MED PoE-MDI\");\n\t\t\t\t\tpower = PEEK_UINT8;\n\t\t\t\t\tswitch (power & 0xC0) {\n\t\t\t\t\tcase 0x0:\n\t\t\t\t\t\tport->p_med_power.devicetype = LLDP_MED_POW_TYPE_PSE;\n\t\t\t\t\t\tport->p_med_cap_enabled |=\n\t\t\t\t\t\t LLDP_MED_CAP_MDI_PSE;\n\t\t\t\t\t\tswitch (power & 0x30) {\n\t\t\t\t\t\tcase 0x0:\n\t\t\t\t\t\t\tport->p_med_power.source =\n\t\t\t\t\t\t\t LLDP_MED_POW_SOURCE_UNKNOWN;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 0x10:\n\t\t\t\t\t\t\tport->p_med_power.source =\n\t\t\t\t\t\t\t LLDP_MED_POW_SOURCE_PRIMARY;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 0x20:\n\t\t\t\t\t\t\tport->p_med_power.source =\n\t\t\t\t\t\t\t LLDP_MED_POW_SOURCE_BACKUP;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tport->p_med_power.source =\n\t\t\t\t\t\t\t LLDP_MED_POW_SOURCE_RESERVED;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 0x40:\n\t\t\t\t\t\tport->p_med_power.devicetype = LLDP_MED_POW_TYPE_PD;\n\t\t\t\t\t\tport->p_med_cap_enabled |=\n\t\t\t\t\t\t LLDP_MED_CAP_MDI_PD;\n\t\t\t\t\t\tswitch (power & 0x30) {\n\t\t\t\t\t\tcase 0x0:\n\t\t\t\t\t\t\tport->p_med_power.source =\n\t\t\t\t\t\t\t LLDP_MED_POW_SOURCE_UNKNOWN;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 0x10:\n\t\t\t\t\t\t\tport->p_med_power.source =\n\t\t\t\t\t\t\t LLDP_MED_POW_SOURCE_PSE;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 0x20:\n\t\t\t\t\t\t\tport->p_med_power.source =\n\t\t\t\t\t\t\t LLDP_MED_POW_SOURCE_LOCAL;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tport->p_med_power.source =\n\t\t\t\t\t\t\t LLDP_MED_POW_SOURCE_BOTH;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tport->p_med_power.devicetype =\n\t\t\t\t\t\t LLDP_MED_POW_TYPE_RESERVED;\n\t\t\t\t\t}\n\t\t\t\t\tif ((power & 0x0F) > LLDP_MED_POW_PRIO_LOW)\n\t\t\t\t\t\tport->p_med_power.priority =\n\t\t\t\t\t\t LLDP_MED_POW_PRIO_UNKNOWN;\n\t\t\t\t\telse\n\t\t\t\t\t\tport->p_med_power.priority =\n\t\t\t\t\t\t power & 0x0F;\n\t\t\t\t\tport->p_med_power.val = PEEK_UINT16;\n\t\t\t\t\tbreak;\n\t\t\t\tcase LLDP_TLV_MED_IV_HW:\n\t\t\t\tcase LLDP_TLV_MED_IV_SW:\n\t\t\t\tcase LLDP_TLV_MED_IV_FW:\n\t\t\t\tcase LLDP_TLV_MED_IV_SN:\n\t\t\t\tcase LLDP_TLV_MED_IV_MANUF:\n\t\t\t\tcase LLDP_TLV_MED_IV_MODEL:\n\t\t\t\tcase LLDP_TLV_MED_IV_ASSET:\n\t\t\t\t\tif (tlv_size <= 4)\n\t\t\t\t\t\tb = NULL;\n\t\t\t\t\telse {\n\t\t\t\t\t\tif ((b = (char*)malloc(tlv_size - 3)) ==\n\t\t\t\t\t\t NULL) {\n\t\t\t\t\t\t\tlog_warn(\"lldp\", \"unable to allocate \"\n\t\t\t\t\t\t\t \"memory for LLDP-MED \"\n\t\t\t\t\t\t\t \"inventory for frame \"\n\t\t\t\t\t\t\t \"received on %s\",\n\t\t\t\t\t\t\t hardware->h_ifname);\n\t\t\t\t\t\t\tgoto malformed;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tPEEK_BYTES(b, tlv_size - 4);\n\t\t\t\t\t\tb[tlv_size - 4] = '\\0';\n\t\t\t\t\t}\n\t\t\t\t\tswitch (tlv_subtype) {\n\t\t\t\t\tcase LLDP_TLV_MED_IV_HW:\n\t\t\t\t\t\tchassis->c_med_hw = b;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase LLDP_TLV_MED_IV_FW:\n\t\t\t\t\t\tchassis->c_med_fw = b;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase LLDP_TLV_MED_IV_SW:\n\t\t\t\t\t\tchassis->c_med_sw = b;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase LLDP_TLV_MED_IV_SN:\n\t\t\t\t\t\tchassis->c_med_sn = b;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase LLDP_TLV_MED_IV_MANUF:\n\t\t\t\t\t\tchassis->c_med_manuf = b;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase LLDP_TLV_MED_IV_MODEL:\n\t\t\t\t\t\tchassis->c_med_model = b;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase LLDP_TLV_MED_IV_ASSET:\n\t\t\t\t\t\tchassis->c_med_asset = b;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tport->p_med_cap_enabled |=\n\t\t\t\t\t LLDP_MED_CAP_IV;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\t/* Unknown LLDP MED, ignore it */\n\t\t\t\t\thardware->h_rx_unrecognized_cnt++;\n\t\t\t\t}\n#endif /* ENABLE_LLDPMED */\n\t\t\t} else if (memcmp(dcbx, orgid, sizeof(orgid)) == 0) {\n\t\t\t\tlog_debug(\"lldp\", \"unsupported DCBX tlv received on %s - ignore\",\n\t\t\t\t hardware->h_ifname);\n\t\t\t\thardware->h_rx_unrecognized_cnt++;\n\t\t\t} else {\n\t\t\t\tlog_debug(\"lldp\", \"unknown org tlv [%02x:%02x:%02x] received on %s\",\n\t\t\t\t orgid[0], orgid[1], orgid[2],\n\t\t\t\t hardware->h_ifname);\n\t\t\t\thardware->h_rx_unrecognized_cnt++;\n#ifdef ENABLE_CUSTOM\n\t\t\t\tcustom = (struct lldpd_custom*)calloc(1, sizeof(struct lldpd_custom));\n\t\t\t\tif (!custom) {\n\t\t\t\t\tlog_warn(\"lldp\",\n\t\t\t\t\t \"unable to allocate memory for custom TLV\");\n\t\t\t\t\tgoto malformed;\n\t\t\t\t}\n\t\t\t\tcustom->oui_info_len = tlv_size > 4 ? tlv_size - 4 : 0;\n\t\t\t\tmemcpy(custom->oui, orgid, sizeof(custom->oui));\n\t\t\t\tcustom->subtype = tlv_subtype;\n\t\t\t\tif (custom->oui_info_len > 0) {\n\t\t\t\t\tcustom->oui_info = malloc(custom->oui_info_len);\n\t\t\t\t\tif (!custom->oui_info) {\n\t\t\t\t\t\tlog_warn(\"lldp\",\n\t\t\t\t\t\t \"unable to allocate memory for custom TLV data\");\n\t\t\t\t\t\tgoto malformed;\n\t\t\t\t\t}\n\t\t\t\t\tPEEK_BYTES(custom->oui_info, custom->oui_info_len);\n\t\t\t\t}\n\t\t\t\tTAILQ_INSERT_TAIL(&port->p_custom_list, custom, next);\n\t\t\t\tcustom = NULL;\n#endif\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tlog_warnx(\"lldp\", \"unknown tlv (%d) received on %s\",\n\t\t\t tlv_type, hardware->h_ifname);\n\t\t\tgoto malformed;\n\t\t}\n\t\tif (pos > tlv + tlv_size) {\n\t\t\tlog_warnx(\"lldp\", \"BUG: already past TLV!\");\n\t\t\tgoto malformed;\n\t\t}\n\t\tPEEK_DISCARD(tlv + tlv_size - pos);\n\t}\n\n\t/* Some random check */\n\tif ((chassis->c_id == NULL) ||\n\t (port->p_id == NULL) ||\n\t (!ttl_received) ||\n\t (gotend == 0)) {\n\t\tlog_warnx(\"lldp\", \"some mandatory tlv are missing for frame received on %s\",\n\t\t hardware->h_ifname);\n\t\tgoto malformed;\n\t}\n\t*newchassis = chassis;\n\t*newport = port;\n\treturn 1;\nmalformed:\n#ifdef ENABLE_CUSTOM\n\tfree(custom);\n#endif\n#ifdef ENABLE_DOT1\n\tfree(vlan);\n\tfree(pi);\n#endif\n\tlldpd_chassis_cleanup(chassis, 1);\n\tlldpd_port_cleanup(port, 1);\n\tfree(port);\n\treturn -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617', 'CWE-703'], 'message': 'protocols: don't use assert on paths that can be reached\n\nMalformed packets should not make lldpd crash. Ensure we can handle them\nby not using assert() in this part.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static double ApplyEvaluateOperator(RandomInfo *random_info,const Quantum pixel,\n const MagickEvaluateOperator op,const double value)\n{\n double\n result;\n\n result=0.0;\n switch (op)\n {\n case UndefinedEvaluateOperator:\n break;\n case AbsEvaluateOperator:\n {\n result=(double) fabs((double) (pixel+value));\n break;\n }\n case AddEvaluateOperator:\n {\n result=(double) (pixel+value);\n break;\n }\n case AddModulusEvaluateOperator:\n {\n /*\n This returns a 'floored modulus' of the addition which is a positive\n result. It differs from % or fmod() that returns a 'truncated modulus'\n result, where floor() is replaced by trunc() and could return a\n negative result (which is clipped).\n */\n result=pixel+value;\n result-=(QuantumRange+1.0)*floor((double) result/(QuantumRange+1.0));\n break;\n }\n case AndEvaluateOperator:\n {\n result=(double) ((ssize_t) pixel & (ssize_t) (value+0.5));\n break;\n }\n case CosineEvaluateOperator:\n {\n result=(double) (QuantumRange*(0.5*cos((double) (2.0*MagickPI*\n QuantumScale*pixel*value))+0.5));\n break;\n }\n case DivideEvaluateOperator:\n {\n result=pixel/(value == 0.0 ? 1.0 : value);\n break;\n }\n case ExponentialEvaluateOperator:\n {\n result=(double) (QuantumRange*exp((double) (value*QuantumScale*pixel)));\n break;\n }\n case GaussianNoiseEvaluateOperator:\n {\n result=(double) GenerateDifferentialNoise(random_info,pixel,\n GaussianNoise,value);\n break;\n }\n case ImpulseNoiseEvaluateOperator:\n {\n result=(double) GenerateDifferentialNoise(random_info,pixel,ImpulseNoise,\n value);\n break;\n }\n case LaplacianNoiseEvaluateOperator:\n {\n result=(double) GenerateDifferentialNoise(random_info,pixel,\n LaplacianNoise,value);\n break;\n }\n case LeftShiftEvaluateOperator:\n {\n result=(double) ((ssize_t) pixel << (ssize_t) (value+0.5));\n break;\n }\n case LogEvaluateOperator:\n {\n if ((QuantumScale*pixel) >= MagickEpsilon)\n result=(double) (QuantumRange*log((double) (QuantumScale*value*pixel+\n 1.0))/log((double) (value+1.0)));\n break;\n }\n case MaxEvaluateOperator:\n {\n result=(double) EvaluateMax((double) pixel,value);\n break;\n }\n case MeanEvaluateOperator:\n {\n result=(double) (pixel+value);\n break;\n }\n case MedianEvaluateOperator:\n {\n result=(double) (pixel+value);\n break;\n }\n case MinEvaluateOperator:\n {\n result=(double) MagickMin((double) pixel,value);\n break;\n }\n case MultiplicativeNoiseEvaluateOperator:\n {\n result=(double) GenerateDifferentialNoise(random_info,pixel,\n MultiplicativeGaussianNoise,value);\n break;\n }\n case MultiplyEvaluateOperator:\n {\n result=(double) (value*pixel);\n break;\n }\n case OrEvaluateOperator:\n {\n result=(double) ((ssize_t) pixel | (ssize_t) (value+0.5));\n break;\n }\n case PoissonNoiseEvaluateOperator:\n {\n result=(double) GenerateDifferentialNoise(random_info,pixel,PoissonNoise,\n value);\n break;\n }\n case PowEvaluateOperator:\n {\n if (pixel < 0)\n result=(double) -(QuantumRange*pow((double) -(QuantumScale*pixel),\n (double) value));\n else\n result=(double) (QuantumRange*pow((double) (QuantumScale*pixel),\n (double) value));\n break;\n }\n case RightShiftEvaluateOperator:\n {\n result=(double) ((ssize_t) pixel >> (ssize_t) (value+0.5));\n break;\n }\n case RootMeanSquareEvaluateOperator:\n {\n result=(double) (pixel*pixel+value);\n break;\n }\n case SetEvaluateOperator:\n {\n result=value;\n break;\n }\n case SineEvaluateOperator:\n {\n result=(double) (QuantumRange*(0.5*sin((double) (2.0*MagickPI*\n QuantumScale*pixel*value))+0.5));\n break;\n }\n case SubtractEvaluateOperator:\n {\n result=(double) (pixel-value);\n break;\n }\n case SumEvaluateOperator:\n {\n result=(double) (pixel+value);\n break;\n }\n case ThresholdEvaluateOperator:\n {\n result=(double) (((double) pixel <= value) ? 0 : QuantumRange);\n break;\n }\n case ThresholdBlackEvaluateOperator:\n {\n result=(double) (((double) pixel <= value) ? 0 : pixel);\n break;\n }\n case ThresholdWhiteEvaluateOperator:\n {\n result=(double) (((double) pixel > value) ? QuantumRange : pixel);\n break;\n }\n case UniformNoiseEvaluateOperator:\n {\n result=(double) GenerateDifferentialNoise(random_info,pixel,UniformNoise,\n value);\n break;\n }\n case XorEvaluateOperator:\n {\n result=(double) ((ssize_t) pixel ^ (ssize_t) (value+0.5));\n break;\n }\n }\n return(result);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1743'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ares_parse_aaaa_reply(const unsigned char *abuf, int alen,\n struct hostent **host, struct ares_addr6ttl *addrttls,\n int *naddrttls)\n{\n struct ares_addrinfo ai;\n struct ares_addrinfo_node *next;\n struct ares_addrinfo_cname *next_cname;\n char **aliases = NULL;\n char *question_hostname = NULL;\n struct hostent *hostent = NULL;\n struct ares_in6_addr *addrs = NULL;\n int naliases = 0, naddrs = 0, alias = 0, i;\n int cname_ttl = INT_MAX;\n int status;\n\n memset(&ai, 0, sizeof(ai));\n\n status = ares__parse_into_addrinfo2(abuf, alen, &question_hostname, &ai);\n if (status != ARES_SUCCESS)\n {\n ares_free(question_hostname);\n\n if (naddrttls)\n {\n *naddrttls = 0;\n }\n\n return status;\n }\n\n hostent = ares_malloc(sizeof(struct hostent));\n if (!hostent)\n {\n goto enomem;\n }\n\n next = ai.nodes;\n while (next)\n {\n if(next->ai_family == AF_INET6)\n {\n ++naddrs;\n }\n next = next->ai_next;\n }\n\n next_cname = ai.cnames;\n while (next_cname)\n {\n if(next_cname->alias)\n ++naliases;\n next_cname = next_cname->next;\n }\n\n aliases = ares_malloc((naliases + 1) * sizeof(char *));\n if (!aliases)\n {\n goto enomem;\n }\n\n if (naliases)\n {\n next_cname = ai.cnames;\n while (next_cname)\n {\n if(next_cname->alias)\n aliases[alias++] = strdup(next_cname->alias);\n if(next_cname->ttl < cname_ttl)\n cname_ttl = next_cname->ttl;\n next_cname = next_cname->next;\n }\n }\n\n aliases[alias] = NULL;\n\n hostent->h_addr_list = ares_malloc((naddrs + 1) * sizeof(char *));\n if (!hostent->h_addr_list)\n {\n goto enomem;\n }\n\n for (i = 0; i < naddrs + 1; ++i)\n {\n hostent->h_addr_list[i] = NULL;\n }\n\n if (ai.cnames)\n {\n hostent->h_name = strdup(ai.cnames->name);\n ares_free(question_hostname);\n }\n else\n {\n hostent->h_name = question_hostname;\n }\n\n hostent->h_aliases = aliases;\n hostent->h_addrtype = AF_INET6;\n hostent->h_length = sizeof(struct ares_in6_addr);\n\n if (naddrs)\n {\n addrs = ares_malloc(naddrs * sizeof(struct ares_in6_addr));\n if (!addrs)\n {\n goto enomem;\n }\n\n i = 0;\n next = ai.nodes;\n while (next)\n {\n if(next->ai_family == AF_INET6)\n {\n hostent->h_addr_list[i] = (char*)&addrs[i];\n memcpy(hostent->h_addr_list[i],\n &(CARES_INADDR_CAST(struct sockaddr_in6 *, next->ai_addr)->sin6_addr),\n sizeof(struct ares_in6_addr));\n if (naddrttls && i < *naddrttls)\n {\n if(next->ai_ttl > cname_ttl)\n addrttls[i].ttl = cname_ttl;\n else\n addrttls[i].ttl = next->ai_ttl;\n\n memcpy(&addrttls[i].ip6addr,\n &(CARES_INADDR_CAST(struct sockaddr_in6 *, next->ai_addr)->sin6_addr),\n sizeof(struct ares_in6_addr));\n }\n ++i;\n }\n next = next->ai_next;\n }\n\n if (i == 0)\n {\n ares_free(addrs);\n }\n }\n\n if (host)\n {\n *host = hostent;\n }\n else\n {\n ares_free_hostent(hostent);\n }\n\n if (naddrttls)\n {\n *naddrttls = naddrs;\n }\n\n ares__freeaddrinfo_cnames(ai.cnames);\n ares__freeaddrinfo_nodes(ai.nodes);\n return ARES_SUCCESS;\n\nenomem:\n ares_free(aliases);\n ares_free(hostent);\n ares__freeaddrinfo_cnames(ai.cnames);\n ares__freeaddrinfo_nodes(ai.nodes);\n ares_free(question_hostname);\n return ARES_ENOMEM;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': 'ares_parse_{a,aaaa}_reply could return larger *naddrttls than passed in\n\nIf there are more ttls returned than the maximum provided by the requestor, then\nthe *naddrttls response would be larger than the actual number of elements in\nthe addrttls array.\n\nThis bug could lead to invalid memory accesses in applications using c-ares.\n\nThis behavior appeared to break with PR #257\n\nFixes: #371\nReported By: Momtchil Momtchev (@mmomtchev)\nFix By: Brad House (@bradh352)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void pdf_get_version(FILE *fp, pdf_t *pdf)\n{\n char *header, *c;\n\n header = get_header(fp);\n\n /* Locate version string start and make sure we dont go past header */\n if ((c = strstr(header, \"%PDF-\")) && \n (c + strlen(\"%PDF-M.m\") + 2))\n {\n pdf->pdf_major_version = atoi(c + strlen(\"%PDF-\"));\n pdf->pdf_minor_version = atoi(c + strlen(\"%PDF-M.\"));\n }\n\n free(header);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Update header validation checks.\n\nThanks to yifengchen-cc for identifying this.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void getElemMatchOrPushdownDescendants(MatchExpression* node, std::vector* out) {\n if (node->getTag() && node->getTag()->getType() == TagType::OrPushdownTag) {\n out->push_back(node);\n } else if (node->matchType() == MatchExpression::ELEM_MATCH_OBJECT ||\n node->matchType() == MatchExpression::AND) {\n for (size_t i = 0; i < node->numChildren(); ++i) {\n getElemMatchOrPushdownDescendants(node->getChild(i), out);\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-834'], 'message': 'SERVER-38164 $or pushdown optimization does not correctly handle $not within an $elemMatch'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: Milliseconds _calculateStaleness(const TopologyDescriptionPtr& topologyDescription,\n const ServerDescriptionPtr& serverDescription) {\n if (serverDescription->getType() != ServerType::kRSSecondary)\n return Milliseconds(0);\n\n const Date_t& lastWriteDate = serverDescription->getLastWriteDate()\n ? *serverDescription->getLastWriteDate()\n : Date_t::min();\n\n if (topologyDescription->getType() == TopologyType::kReplicaSetWithPrimary) {\n // (S.lastUpdateTime - S.lastWriteDate) - (P.lastUpdateTime - P.lastWriteDate) +\n // heartbeatFrequencyMS\n\n // topologyType == kReplicaSetWithPrimary implies the validity of the primary server\n // description.\n const auto primary = topologyDescription->getPrimary();\n invariant(primary);\n const auto& primaryDescription = *primary;\n\n const auto& primaryLastWriteDate = primaryDescription->getLastWriteDate()\n ? *primaryDescription->getLastWriteDate()\n : Date_t::min();\n\n auto result = (serverDescription->getLastUpdateTime() - lastWriteDate) -\n (primaryDescription->getLastUpdateTime() - primaryLastWriteDate) +\n _config.getHeartBeatFrequency();\n return duration_cast(result);\n } else if (topologyDescription->getType() == TopologyType::kReplicaSetNoPrimary) {\n // SMax.lastWriteDate - S.lastWriteDate + heartbeatFrequencyMS\n Date_t maxLastWriteDate = Date_t::min();\n\n // identify secondary with max last write date.\n for (const auto& s : topologyDescription->getServers()) {\n if (s->getType() != ServerType::kRSSecondary)\n continue;\n\n const auto& sLastWriteDate =\n s->getLastWriteDate() ? *s->getLastWriteDate() : Date_t::min();\n\n if (sLastWriteDate > maxLastWriteDate) {\n maxLastWriteDate = sLastWriteDate;\n }\n }\n\n auto result = (maxLastWriteDate - lastWriteDate) + _config.getHeartBeatFrequency();\n return duration_cast(result);\n } else {\n // Not a replica set\n return Milliseconds(0);\n }\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-755'], 'message': 'SERVER-50170 fix max staleness read preference parameter for server selection'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void SdamServerSelector::_getCandidateServers(std::vector* result,\n const TopologyDescriptionPtr topologyDescription,\n const ReadPreferenceSetting& criteria) {\n // when querying the primary we don't need to consider tags\n bool shouldTagFilter = true;\n\n // TODO SERVER-46499: check to see if we want to enforce minOpTime at all since\n // it was effectively optional in the original implementation.\n if (!criteria.minOpTime.isNull()) {\n auto eligibleServers = topologyDescription->findServers([](const ServerDescriptionPtr& s) {\n return (s->getType() == ServerType::kRSPrimary ||\n s->getType() == ServerType::kRSSecondary);\n });\n\n auto beginIt = eligibleServers.begin();\n auto endIt = eligibleServers.end();\n auto maxIt = std::max_element(beginIt,\n endIt,\n [topologyDescription](const ServerDescriptionPtr& left,\n const ServerDescriptionPtr& right) {\n return left->getOpTime() < right->getOpTime();\n });\n if (maxIt != endIt) {\n auto maxOpTime = (*maxIt)->getOpTime();\n if (maxOpTime && maxOpTime < criteria.minOpTime) {\n // ignore minOpTime\n const_cast(criteria) = ReadPreferenceSetting(criteria.pref);\n }\n }\n }\n\n switch (criteria.pref) {\n case ReadPreference::Nearest:\n *result = topologyDescription->findServers(nearestFilter(criteria));\n break;\n\n case ReadPreference::SecondaryOnly:\n *result = topologyDescription->findServers(secondaryFilter(criteria));\n break;\n\n case ReadPreference::PrimaryOnly: {\n const auto primaryCriteria = ReadPreferenceSetting(criteria.pref);\n *result = topologyDescription->findServers(primaryFilter(primaryCriteria));\n shouldTagFilter = false;\n break;\n }\n\n case ReadPreference::PrimaryPreferred: {\n // ignore tags and max staleness for primary query\n auto primaryCriteria = ReadPreferenceSetting(ReadPreference::PrimaryOnly);\n _getCandidateServers(result, topologyDescription, primaryCriteria);\n if (result->size()) {\n shouldTagFilter = false;\n break;\n }\n\n // keep tags and maxStaleness for secondary query\n auto secondaryCriteria = criteria;\n secondaryCriteria.pref = ReadPreference::SecondaryOnly;\n _getCandidateServers(result, topologyDescription, secondaryCriteria);\n break;\n }\n\n case ReadPreference::SecondaryPreferred: {\n // keep tags and maxStaleness for secondary query\n auto secondaryCriteria = criteria;\n secondaryCriteria.pref = ReadPreference::SecondaryOnly;\n _getCandidateServers(result, topologyDescription, secondaryCriteria);\n if (result->size()) {\n break;\n }\n\n // ignore tags and maxStaleness for primary query\n shouldTagFilter = false;\n auto primaryCriteria = ReadPreferenceSetting(ReadPreference::PrimaryOnly);\n _getCandidateServers(result, topologyDescription, primaryCriteria);\n break;\n }\n\n default:\n MONGO_UNREACHABLE\n }\n\n if (shouldTagFilter) {\n filterTags(result, criteria.tags);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-755'], 'message': 'SERVER-50170 fix max staleness read preference parameter for server selection'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static long snd_rawmidi_kernel_write1(struct snd_rawmidi_substream *substream,\n\t\t\t\t const unsigned char __user *userbuf,\n\t\t\t\t const unsigned char *kernelbuf,\n\t\t\t\t long count)\n{\n\tunsigned long flags;\n\tlong count1, result;\n\tstruct snd_rawmidi_runtime *runtime = substream->runtime;\n\tunsigned long appl_ptr;\n\n\tif (!kernelbuf && !userbuf)\n\t\treturn -EINVAL;\n\tif (snd_BUG_ON(!runtime->buffer))\n\t\treturn -EINVAL;\n\n\tresult = 0;\n\tspin_lock_irqsave(&runtime->lock, flags);\n\tif (substream->append) {\n\t\tif ((long)runtime->avail < count) {\n\t\t\tspin_unlock_irqrestore(&runtime->lock, flags);\n\t\t\treturn -EAGAIN;\n\t\t}\n\t}\n\twhile (count > 0 && runtime->avail > 0) {\n\t\tcount1 = runtime->buffer_size - runtime->appl_ptr;\n\t\tif (count1 > count)\n\t\t\tcount1 = count;\n\t\tif (count1 > (long)runtime->avail)\n\t\t\tcount1 = runtime->avail;\n\n\t\t/* update runtime->appl_ptr before unlocking for userbuf */\n\t\tappl_ptr = runtime->appl_ptr;\n\t\truntime->appl_ptr += count1;\n\t\truntime->appl_ptr %= runtime->buffer_size;\n\t\truntime->avail -= count1;\n\n\t\tif (kernelbuf)\n\t\t\tmemcpy(runtime->buffer + appl_ptr,\n\t\t\t kernelbuf + result, count1);\n\t\telse if (userbuf) {\n\t\t\tspin_unlock_irqrestore(&runtime->lock, flags);\n\t\t\tif (copy_from_user(runtime->buffer + appl_ptr,\n\t\t\t\t\t userbuf + result, count1)) {\n\t\t\t\tspin_lock_irqsave(&runtime->lock, flags);\n\t\t\t\tresult = result > 0 ? result : -EFAULT;\n\t\t\t\tgoto __end;\n\t\t\t}\n\t\t\tspin_lock_irqsave(&runtime->lock, flags);\n\t\t}\n\t\tresult += count1;\n\t\tcount -= count1;\n\t}\n __end:\n\tcount1 = runtime->avail < runtime->buffer_size;\n\tspin_unlock_irqrestore(&runtime->lock, flags);\n\tif (count1)\n\t\tsnd_rawmidi_output_trigger(substream, 1);\n\treturn result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'ALSA: rawmidi: Fix racy buffer resize under concurrent accesses\n\nThe rawmidi core allows user to resize the runtime buffer via ioctl,\nand this may lead to UAF when performed during concurrent reads or\nwrites: the read/write functions unlock the runtime lock temporarily\nduring copying form/to user-space, and that's the race window.\n\nThis patch fixes the hole by introducing a reference counter for the\nruntime buffer read/write access and returns -EBUSY error when the\nresize is performed concurrently against read/write.\n\nNote that the ref count field is a simple integer instead of\nrefcount_t here, since the all contexts accessing the buffer is\nbasically protected with a spinlock, hence we need no expensive atomic\nops. Also, note that this busy check is needed only against read /\nwrite functions, and not in receive/transmit callbacks; the race can\nhappen only at the spinlock hole mentioned in the above, while the\nwhole function is protected for receive / transmit callbacks.\n\nReported-by: butt3rflyh4ck \nCc: \nLink: https://lore.kernel.org/r/CAFcO6XMWpUVK_yzzCpp8_XP7+=oUpQvuBeCbMffEDkpe8jWrfg@mail.gmail.com\nLink: https://lore.kernel.org/r/s5heerw3r5z.wl-tiwai@suse.de\nSigned-off-by: Takashi Iwai '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int pin_rcv_pages(struct hfi1_filedata *fd, struct tid_user_buf *tidbuf)\n{\n\tint pinned;\n\tunsigned int npages;\n\tunsigned long vaddr = tidbuf->vaddr;\n\tstruct page **pages = NULL;\n\tstruct hfi1_devdata *dd = fd->uctxt->dd;\n\n\t/* Get the number of pages the user buffer spans */\n\tnpages = num_user_pages(vaddr, tidbuf->length);\n\tif (!npages)\n\t\treturn -EINVAL;\n\n\tif (npages > fd->uctxt->expected_count) {\n\t\tdd_dev_err(dd, \"Expected buffer too big\\n\");\n\t\treturn -EINVAL;\n\t}\n\n\t/* Allocate the array of struct page pointers needed for pinning */\n\tpages = kcalloc(npages, sizeof(*pages), GFP_KERNEL);\n\tif (!pages)\n\t\treturn -ENOMEM;\n\n\t/*\n\t * Pin all the pages of the user buffer. If we can't pin all the\n\t * pages, accept the amount pinned so far and program only that.\n\t * User space knows how to deal with partially programmed buffers.\n\t */\n\tif (!hfi1_can_pin_pages(dd, fd->mm, fd->tid_n_pinned, npages)) {\n\t\tkfree(pages);\n\t\treturn -ENOMEM;\n\t}\n\n\tpinned = hfi1_acquire_user_pages(fd->mm, vaddr, npages, true, pages);\n\tif (pinned <= 0) {\n\t\tkfree(pages);\n\t\treturn pinned;\n\t}\n\ttidbuf->pages = pages;\n\ttidbuf->npages = npages;\n\tfd->tid_n_pinned += pinned;\n\treturn pinned;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'IB/hfi1: Ensure correct mm is used at all times\n\nTwo earlier bug fixes have created a security problem in the hfi1\ndriver. One fix aimed to solve an issue where current->mm was not valid\nwhen closing the hfi1 cdev. It attempted to do this by saving a cached\nvalue of the current->mm pointer at file open time. This is a problem if\nanother process with access to the FD calls in via write() or ioctl() to\npin pages via the hfi driver. The other fix tried to solve a use after\nfree by taking a reference on the mm.\n\nTo fix this correctly we use the existing cached value of the mm in the\nmmu notifier. Now we can check in the insert, evict, etc. routines that\ncurrent->mm matched what the notifier was registered for. If not, then\ndon't allow access. The register of the mmu notifier will save the mm\npointer.\n\nSince in do_exit() the exit_mm() is called before exit_files(), which\nwould call our close routine a reference is needed on the mm. We rely on\nthe mmgrab done by the registration of the notifier, whereas before it was\nexplicit. The mmu notifier deregistration happens when the user context is\ntorn down, the creation of which triggered the registration.\n\nAlso of note is we do not do any explicit work to protect the interval\ntree notifier. It doesn't seem that this is going to be needed since we\naren't actually doing anything with current->mm. The interval tree\nnotifier stuff still has a FIXME noted from a previous commit that will be\naddressed in a follow on patch.\n\nCc: \nFixes: e0cf75deab81 (\"IB/hfi1: Fix mm_struct use after free\")\nFixes: 3faa3d9a308e (\"IB/hfi1: Make use of mm consistent\")\nLink: https://lore.kernel.org/r/20201125210112.104301.51331.stgit@awfm-01.aw.intel.com\nSuggested-by: Jann Horn \nReported-by: Jason Gunthorpe \nReviewed-by: Ira Weiny \nReviewed-by: Mike Marciniszyn \nSigned-off-by: Dennis Dalessandro \nSigned-off-by: Jason Gunthorpe '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void hfi1_mmu_rb_remove(struct mmu_rb_handler *handler,\n\t\t\tstruct mmu_rb_node *node)\n{\n\tunsigned long flags;\n\n\t/* Validity of handler and node pointers has been checked by caller. */\n\ttrace_hfi1_mmu_rb_remove(node->addr, node->len);\n\tspin_lock_irqsave(&handler->lock, flags);\n\t__mmu_int_rb_remove(node, &handler->root);\n\tlist_del(&node->list); /* remove from LRU list */\n\tspin_unlock_irqrestore(&handler->lock, flags);\n\n\thandler->ops->remove(handler->ops_arg, node);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'IB/hfi1: Ensure correct mm is used at all times\n\nTwo earlier bug fixes have created a security problem in the hfi1\ndriver. One fix aimed to solve an issue where current->mm was not valid\nwhen closing the hfi1 cdev. It attempted to do this by saving a cached\nvalue of the current->mm pointer at file open time. This is a problem if\nanother process with access to the FD calls in via write() or ioctl() to\npin pages via the hfi driver. The other fix tried to solve a use after\nfree by taking a reference on the mm.\n\nTo fix this correctly we use the existing cached value of the mm in the\nmmu notifier. Now we can check in the insert, evict, etc. routines that\ncurrent->mm matched what the notifier was registered for. If not, then\ndon't allow access. The register of the mmu notifier will save the mm\npointer.\n\nSince in do_exit() the exit_mm() is called before exit_files(), which\nwould call our close routine a reference is needed on the mm. We rely on\nthe mmgrab done by the registration of the notifier, whereas before it was\nexplicit. The mmu notifier deregistration happens when the user context is\ntorn down, the creation of which triggered the registration.\n\nAlso of note is we do not do any explicit work to protect the interval\ntree notifier. It doesn't seem that this is going to be needed since we\naren't actually doing anything with current->mm. The interval tree\nnotifier stuff still has a FIXME noted from a previous commit that will be\naddressed in a follow on patch.\n\nCc: \nFixes: e0cf75deab81 (\"IB/hfi1: Fix mm_struct use after free\")\nFixes: 3faa3d9a308e (\"IB/hfi1: Make use of mm consistent\")\nLink: https://lore.kernel.org/r/20201125210112.104301.51331.stgit@awfm-01.aw.intel.com\nSuggested-by: Jann Horn \nReported-by: Jason Gunthorpe \nReviewed-by: Ira Weiny \nReviewed-by: Mike Marciniszyn \nSigned-off-by: Dennis Dalessandro \nSigned-off-by: Jason Gunthorpe '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t *\n p_code_block)\n{\n OPJ_UINT32 l_data_size;\n\n /* +1 is needed for https://github.com/uclouvain/openjpeg/issues/835 */\n /* and actually +2 required for https://github.com/uclouvain/openjpeg/issues/982 */\n /* TODO: is there a theoretical upper-bound for the compressed code */\n /* block size ? */\n l_data_size = 2 + (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) *\n (p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32));\n\n if (l_data_size > p_code_block->data_size) {\n if (p_code_block->data) {\n /* We refer to data - 1 since below we incremented it */\n opj_free(p_code_block->data - 1);\n }\n p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size + 1);\n if (! p_code_block->data) {\n p_code_block->data_size = 0U;\n return OPJ_FALSE;\n }\n p_code_block->data_size = l_data_size;\n\n /* We reserve the initial byte as a fake byte to a non-FF value */\n /* and increment the data pointer, so that opj_mqc_init_enc() */\n /* can do bp = data - 1, and opj_mqc_byteout() can safely dereference */\n /* it. */\n p_code_block->data[0] = 0;\n p_code_block->data += 1; /*why +1 ?*/\n }\n return OPJ_TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-122'], 'message': 'Encoder: grow buffer size in opj_tcd_code_block_enc_allocate_data() to avoid write heap buffer overflow in opj_mqc_flush (fixes #1283)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int con_font_op(struct vc_data *vc, struct console_font_op *op)\n{\n\tswitch (op->op) {\n\tcase KD_FONT_OP_SET:\n\t\treturn con_font_set(vc, op);\n\tcase KD_FONT_OP_GET:\n\t\treturn con_font_get(vc, op);\n\tcase KD_FONT_OP_SET_DEFAULT:\n\t\treturn con_font_default(vc, op);\n\tcase KD_FONT_OP_COPY:\n\t\treturn con_font_copy(vc, op);\n\t}\n\treturn -ENOSYS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'vt: Disable KD_FONT_OP_COPY\n\nIt's buggy:\n\nOn Fri, Nov 06, 2020 at 10:30:08PM +0800, Minh Yuan wrote:\n> We recently discovered a slab-out-of-bounds read in fbcon in the latest\n> kernel ( v5.10-rc2 for now ). The root cause of this vulnerability is that\n> \"fbcon_do_set_font\" did not handle \"vc->vc_font.data\" and\n> \"vc->vc_font.height\" correctly, and the patch\n> for VT_RESIZEX can't handle this\n> issue.\n>\n> Specifically, we use KD_FONT_OP_SET to set a small font.data for tty6, and\n> use KD_FONT_OP_SET again to set a large font.height for tty1. After that,\n> we use KD_FONT_OP_COPY to assign tty6's vc_font.data to tty1's vc_font.data\n> in \"fbcon_do_set_font\", while tty1 retains the original larger\n> height. Obviously, this will cause an out-of-bounds read, because we can\n> access a smaller vc_font.data with a larger vc_font.height.\n\nFurther there was only one user ever.\n- Android's loadfont, busybox and console-tools only ever use OP_GET\n and OP_SET\n- fbset documentation only mentions the kernel cmdline font: option,\n not anything else.\n- systemd used OP_COPY before release 232 published in Nov 2016\n\nNow unfortunately the crucial report seems to have gone down with\ngmane, and the commit message doesn't say much. But the pull request\nhints at OP_COPY being broken\n\nhttps://github.com/systemd/systemd/pull/3651\n\nSo in other words, this never worked, and the only project which\nfoolishly every tried to use it, realized that rather quickly too.\n\nInstead of trying to fix security issues here on dead code by adding\nmissing checks, fix the entire thing by removing the functionality.\n\nNote that systemd code using the OP_COPY function ignored the return\nvalue, so it doesn't matter what we're doing here really - just in\ncase a lone server somewhere happens to be extremely unlucky and\nrunning an affected old version of systemd. The relevant code from\nfont_copy_to_all_vcs() in systemd was:\n\n\t/* copy font from active VT, where the font was uploaded to */\n\tcfo.op = KD_FONT_OP_COPY;\n\tcfo.height = vcs.v_active-1; /* tty1 == index 0 */\n\t(void) ioctl(vcfd, KDFONTOP, &cfo);\n\nNote this just disables the ioctl, garbage collecting the now unused\ncallbacks is left for -next.\n\nv2: Tetsuo found the old mail, which allowed me to find it on another\narchive. Add the link too.\n\nAcked-by: Peilin Ye \nReported-by: Minh Yuan \nReferences: https://lists.freedesktop.org/archives/systemd-devel/2016-June/036935.html\nReferences: https://github.com/systemd/systemd/pull/3651\nCc: Greg KH \nCc: Peilin Ye \nCc: Tetsuo Handa \nSigned-off-by: Daniel Vetter \nLink: https://lore.kernel.org/r/20201108153806.3140315-1-daniel.vetter@ffwll.ch\nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int __do_munmap(struct mm_struct *mm, unsigned long start, size_t len,\n\t\tstruct list_head *uf, bool downgrade)\n{\n\tunsigned long end;\n\tstruct vm_area_struct *vma, *prev, *last;\n\n\tif ((offset_in_page(start)) || start > TASK_SIZE || len > TASK_SIZE-start)\n\t\treturn -EINVAL;\n\n\tlen = PAGE_ALIGN(len);\n\tend = start + len;\n\tif (len == 0)\n\t\treturn -EINVAL;\n\n\t/*\n\t * arch_unmap() might do unmaps itself. It must be called\n\t * and finish any rbtree manipulation before this code\n\t * runs and also starts to manipulate the rbtree.\n\t */\n\tarch_unmap(mm, start, end);\n\n\t/* Find the first overlapping VMA */\n\tvma = find_vma(mm, start);\n\tif (!vma)\n\t\treturn 0;\n\tprev = vma->vm_prev;\n\t/* we have start < vma->vm_end */\n\n\t/* if it doesn't overlap, we have nothing.. */\n\tif (vma->vm_start >= end)\n\t\treturn 0;\n\n\t/*\n\t * If we need to split any vma, do it now to save pain later.\n\t *\n\t * Note: mremap's move_vma VM_ACCOUNT handling assumes a partially\n\t * unmapped vm_area_struct will remain in use: so lower split_vma\n\t * places tmp vma above, and higher split_vma places tmp vma below.\n\t */\n\tif (start > vma->vm_start) {\n\t\tint error;\n\n\t\t/*\n\t\t * Make sure that map_count on return from munmap() will\n\t\t * not exceed its limit; but let map_count go just above\n\t\t * its limit temporarily, to help free resources as expected.\n\t\t */\n\t\tif (end < vma->vm_end && mm->map_count >= sysctl_max_map_count)\n\t\t\treturn -ENOMEM;\n\n\t\terror = __split_vma(mm, vma, start, 0);\n\t\tif (error)\n\t\t\treturn error;\n\t\tprev = vma;\n\t}\n\n\t/* Does it split the last one? */\n\tlast = find_vma(mm, end);\n\tif (last && end > last->vm_start) {\n\t\tint error = __split_vma(mm, last, end, 1);\n\t\tif (error)\n\t\t\treturn error;\n\t}\n\tvma = prev ? prev->vm_next : mm->mmap;\n\n\tif (unlikely(uf)) {\n\t\t/*\n\t\t * If userfaultfd_unmap_prep returns an error the vmas\n\t\t * will remain splitted, but userland will get a\n\t\t * highly unexpected error anyway. This is no\n\t\t * different than the case where the first of the two\n\t\t * __split_vma fails, but we don't undo the first\n\t\t * split, despite we could. This is unlikely enough\n\t\t * failure that it's not worth optimizing it for.\n\t\t */\n\t\tint error = userfaultfd_unmap_prep(vma, start, end, uf);\n\t\tif (error)\n\t\t\treturn error;\n\t}\n\n\t/*\n\t * unlock any mlock()ed ranges before detaching vmas\n\t */\n\tif (mm->locked_vm) {\n\t\tstruct vm_area_struct *tmp = vma;\n\t\twhile (tmp && tmp->vm_start < end) {\n\t\t\tif (tmp->vm_flags & VM_LOCKED) {\n\t\t\t\tmm->locked_vm -= vma_pages(tmp);\n\t\t\t\tmunlock_vma_pages_all(tmp);\n\t\t\t}\n\n\t\t\ttmp = tmp->vm_next;\n\t\t}\n\t}\n\n\t/* Detach vmas from rbtree */\n\tdetach_vmas_to_be_unmapped(mm, vma, prev, end);\n\n\tif (downgrade)\n\t\tmmap_write_downgrade(mm);\n\n\tunmap_region(mm, vma, prev, start, end);\n\n\t/* Fix up all other VM information */\n\tremove_vma_list(mm, vma);\n\n\treturn downgrade ? 1 : 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'mm/mmap.c: close race between munmap() and expand_upwards()/downwards()\n\nVMA with VM_GROWSDOWN or VM_GROWSUP flag set can change their size under\nmmap_read_lock(). It can lead to race with __do_munmap():\n\n\tThread A\t\t\tThread B\n__do_munmap()\n detach_vmas_to_be_unmapped()\n mmap_write_downgrade()\n\t\t\t\texpand_downwards()\n\t\t\t\t vma->vm_start = address;\n\t\t\t\t // The VMA now overlaps with\n\t\t\t\t // VMAs detached by the Thread A\n\t\t\t\t// page fault populates expanded part\n\t\t\t\t// of the VMA\n unmap_region()\n // Zaps pagetables partly\n // populated by Thread B\n\nSimilar race exists for expand_upwards().\n\nThe fix is to avoid downgrading mmap_lock in __do_munmap() if detached\nVMAs are next to VM_GROWSDOWN or VM_GROWSUP VMA.\n\n[akpm@linux-foundation.org: s/mmap_sem/mmap_lock/ in comment]\n\nFixes: dd2283f2605e (\"mm: mmap: zap pages with read mmap_sem in munmap\")\nReported-by: Jann Horn \nSigned-off-by: Kirill A. Shutemov \nSigned-off-by: Andrew Morton \nReviewed-by: Yang Shi \nAcked-by: Vlastimil Babka \nCc: Oleg Nesterov \nCc: Matthew Wilcox \nCc: \t[4.20+]\nLink: http://lkml.kernel.org/r/20200709105309.42495-1-kirill.shutemov@linux.intel.com\nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: move_next_session (P11KitIter *iter)\n{\n\tCK_ULONG session_flags;\n\tCK_ULONG num_slots;\n\tCK_INFO minfo;\n\tCK_RV rv;\n\n\tCOROUTINE_BEGIN (move_next_session);\n\n\tfinish_slot (iter);\n\n\t/* If we have no more slots, then move to next module */\n\twhile (iter->saw_slots >= iter->num_slots) {\n\t\tfinish_module (iter);\n\n\t\t/* Iter is finished */\n\t\tif (iter->modules->num == 0)\n\t\t\treturn finish_iterating (iter, CKR_CANCEL);\n\n\t\titer->module = iter->modules->elem[0];\n\t\tp11_array_remove (iter->modules, 0);\n\n\t\t/* Skip module if it doesn't match uri */\n\t\tassert (iter->module != NULL);\n\t\trv = (iter->module->C_GetInfo) (&minfo);\n\t\tif (rv != CKR_OK || !p11_match_uri_module_info (&iter->match_module, &minfo))\n\t\t\tcontinue;\n\n\t\tif (iter->with_modules) {\n\t\t\titer->kind = P11_KIT_ITER_KIND_MODULE;\n\t\t\tCOROUTINE_RETURN (move_next_session, 1, CKR_OK);\n\t\t}\n\n\t\tif (iter->with_slots || iter->with_tokens || iter->with_objects) {\n\t\t\tCK_SLOT_ID *slots;\n\n\t\t\trv = (iter->module->C_GetSlotList) (CK_TRUE, NULL, &num_slots);\n\t\t\tif (rv != CKR_OK)\n\t\t\t\treturn finish_iterating (iter, rv);\n\n\t\t\tslots = realloc (iter->slots, sizeof (CK_SLOT_ID) * (num_slots + 1));\n\t\t\treturn_val_if_fail (slots != NULL, CKR_HOST_MEMORY);\n\t\t\titer->slots = slots;\n\n\t\t\trv = (iter->module->C_GetSlotList) (CK_TRUE, iter->slots, &num_slots);\n\t\t\tif (rv != CKR_OK)\n\t\t\t\treturn finish_iterating (iter, rv);\n\n\t\t\titer->num_slots = num_slots;\n\t\t\tassert (iter->saw_slots == 0);\n\t\t}\n\t}\n\n\t/* Move to the next slot, and open a session on it */\n\twhile ((iter->with_slots || iter->with_tokens || iter->with_objects) &&\n\t iter->saw_slots < iter->num_slots) {\n\t\titer->slot = iter->slots[iter->saw_slots++];\n\n\t\tassert (iter->module != NULL);\n\t\tif (iter->match_slot_id != (CK_SLOT_ID)-1 && iter->slot != iter->match_slot_id)\n\t\t\tcontinue;\n\t\trv = (iter->module->C_GetSlotInfo) (iter->slot, &iter->slot_info);\n\t\tif (rv != CKR_OK || !p11_match_uri_slot_info (&iter->match_slot, &iter->slot_info))\n\t\t\tcontinue;\n\t\tif (iter->with_slots) {\n\t\t\titer->kind = P11_KIT_ITER_KIND_SLOT;\n\t\t\tCOROUTINE_RETURN (move_next_session, 2, CKR_OK);\n\t\t}\n\t\trv = (iter->module->C_GetTokenInfo) (iter->slot, &iter->token_info);\n\t\tif (rv != CKR_OK || !p11_match_uri_token_info (&iter->match_token, &iter->token_info))\n\t\t\tcontinue;\n\t\tif (iter->with_tokens) {\n\t\t\titer->kind = P11_KIT_ITER_KIND_TOKEN;\n\t\t\tCOROUTINE_RETURN (move_next_session, 3, CKR_OK);\n\t\t}\n\n\t\tsession_flags = CKF_SERIAL_SESSION;\n\n\t\t/* Skip if the read/write on a read-only token */\n\t\tif (iter->want_writable && (iter->token_info.flags & CKF_WRITE_PROTECTED) == 0)\n\t\t\tsession_flags |= CKF_RW_SESSION;\n\n\t\trv = (iter->module->C_OpenSession) (iter->slot, session_flags,\n\t\t NULL, NULL, &iter->session);\n\t\tif (rv != CKR_OK)\n\t\t\treturn finish_iterating (iter, rv);\n\n\t\tif (iter->session != 0) {\n\t\t\titer->move_next_session_state = 0;\n\t\t\titer->kind = P11_KIT_ITER_KIND_UNKNOWN;\n\t\t\treturn CKR_OK;\n\t\t}\n\t}\n\n\tCOROUTINE_END (move_next_session);\n\n\t/* Otherwise try again */\n\titer->move_next_session_state = 0;\n\treturn move_next_session (iter);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Check for arithmetic overflows before allocating'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void ring_buffer_reset_online_cpus(struct trace_buffer *buffer)\n{\n\tstruct ring_buffer_per_cpu *cpu_buffer;\n\tint cpu;\n\n\tfor_each_online_buffer_cpu(buffer, cpu) {\n\t\tcpu_buffer = buffer->buffers[cpu];\n\n\t\tatomic_inc(&cpu_buffer->resize_disabled);\n\t\tatomic_inc(&cpu_buffer->record_disabled);\n\t}\n\n\t/* Make sure all commits have finished */\n\tsynchronize_rcu();\n\n\tfor_each_online_buffer_cpu(buffer, cpu) {\n\t\tcpu_buffer = buffer->buffers[cpu];\n\n\t\treset_disabled_cpu_buffer(cpu_buffer);\n\n\t\tatomic_dec(&cpu_buffer->record_disabled);\n\t\tatomic_dec(&cpu_buffer->resize_disabled);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'tracing: Fix race in trace_open and buffer resize call\n\nBelow race can come, if trace_open and resize of\ncpu buffer is running parallely on different cpus\nCPUX CPUY\n\t\t\t\t ring_buffer_resize\n\t\t\t\t atomic_read(&buffer->resize_disabled)\ntracing_open\ntracing_reset_online_cpus\nring_buffer_reset_cpu\nrb_reset_cpu\n\t\t\t\t rb_update_pages\n\t\t\t\t remove/insert pages\nresetting pointer\n\nThis race can cause data abort or some times infinte loop in\nrb_remove_pages and rb_insert_pages while checking pages\nfor sanity.\n\nTake buffer lock to fix this.\n\nLink: https://lkml.kernel.org/r/1601976833-24377-1-git-send-email-gkohli@codeaurora.org\n\nCc: stable@vger.kernel.org\nFixes: b23d7a5f4a07a (\"ring-buffer: speed up buffer resets by avoiding synchronize_rcu for each CPU\")\nSigned-off-by: Gaurav Kohli \nSigned-off-by: Steven Rostedt (VMware) '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void __do_SAK(struct tty_struct *tty)\n{\n#ifdef TTY_SOFT_SAK\n\ttty_hangup(tty);\n#else\n\tstruct task_struct *g, *p;\n\tstruct pid *session;\n\tint\t\ti;\n\n\tif (!tty)\n\t\treturn;\n\tsession = tty->session;\n\n\ttty_ldisc_flush(tty);\n\n\ttty_driver_flush_buffer(tty);\n\n\tread_lock(&tasklist_lock);\n\t/* Kill the entire session */\n\tdo_each_pid_task(session, PIDTYPE_SID, p) {\n\t\ttty_notice(tty, \"SAK: killed process %d (%s): by session\\n\",\n\t\t\t task_pid_nr(p), p->comm);\n\t\tgroup_send_sig_info(SIGKILL, SEND_SIG_PRIV, p, PIDTYPE_SID);\n\t} while_each_pid_task(session, PIDTYPE_SID, p);\n\n\t/* Now kill any processes that happen to have the tty open */\n\tdo_each_thread(g, p) {\n\t\tif (p->signal->tty == tty) {\n\t\t\ttty_notice(tty, \"SAK: killed process %d (%s): by controlling tty\\n\",\n\t\t\t\t task_pid_nr(p), p->comm);\n\t\t\tgroup_send_sig_info(SIGKILL, SEND_SIG_PRIV, p, PIDTYPE_SID);\n\t\t\tcontinue;\n\t\t}\n\t\ttask_lock(p);\n\t\ti = iterate_fd(p->files, 0, this_tty, tty);\n\t\tif (i != 0) {\n\t\t\ttty_notice(tty, \"SAK: killed process %d (%s): by fd#%d\\n\",\n\t\t\t\t task_pid_nr(p), p->comm, i - 1);\n\t\t\tgroup_send_sig_info(SIGKILL, SEND_SIG_PRIV, p, PIDTYPE_SID);\n\t\t}\n\t\ttask_unlock(p);\n\t} while_each_thread(g, p);\n\tread_unlock(&tasklist_lock);\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'tty: Fix ->session locking\n\nCurrently, locking of ->session is very inconsistent; most places\nprotect it using the legacy tty mutex, but disassociate_ctty(),\n__do_SAK(), tiocspgrp() and tiocgsid() don't.\nTwo of the writers hold the ctrl_lock (because they already need it for\n->pgrp), but __proc_set_tty() doesn't do that yet.\n\nOn a PREEMPT=y system, an unprivileged user can theoretically abuse\nthis broken locking to read 4 bytes of freed memory via TIOCGSID if\ntiocgsid() is preempted long enough at the right point. (Other things\nmight also go wrong, especially if root-only ioctls are involved; I'm\nnot sure about that.)\n\nChange the locking on ->session such that:\n\n - tty_lock() is held by all writers: By making disassociate_ctty()\n hold it. This should be fine because the same lock can already be\n taken through the call to tty_vhangup_session().\n The tricky part is that we need to shorten the area covered by\n siglock to be able to take tty_lock() without ugly retry logic; as\n far as I can tell, this should be fine, since nothing in the\n signal_struct is touched in the `if (tty)` branch.\n - ctrl_lock is held by all writers: By changing __proc_set_tty() to\n hold the lock a little longer.\n - All readers that aren't holding tty_lock() hold ctrl_lock: By\n adding locking to tiocgsid() and __do_SAK(), and expanding the area\n covered by ctrl_lock in tiocspgrp().\n\nCc: stable@kernel.org\nSigned-off-by: Jann Horn \nReviewed-by: Jiri Slaby \nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadPDFImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n char\n command[MagickPathExtent],\n *density,\n filename[MagickPathExtent],\n input_filename[MagickPathExtent],\n message[MagickPathExtent],\n *options,\n postscript_filename[MagickPathExtent];\n\n const char\n *option;\n\n const DelegateInfo\n *delegate_info;\n\n GeometryInfo\n geometry_info;\n\n Image\n *image,\n *next,\n *pdf_image;\n\n ImageInfo\n *read_info;\n\n int\n file;\n\n MagickBooleanType\n fitPage,\n status;\n\n MagickStatusType\n flags;\n\n PDFInfo\n pdf_info;\n\n PointInfo\n delta;\n\n RectangleInfo\n page;\n\n register ssize_t\n i;\n\n size_t\n scene;\n\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n /*\n Open image file.\n */\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n status=AcquireUniqueSymbolicLink(image_info->filename,input_filename);\n if (status == MagickFalse)\n {\n ThrowFileException(exception,FileOpenError,\"UnableToCreateTemporaryFile\",\n image_info->filename);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Set the page density.\n */\n delta.x=DefaultResolution;\n delta.y=DefaultResolution;\n if ((image->resolution.x == 0.0) || (image->resolution.y == 0.0))\n {\n flags=ParseGeometry(PSDensityGeometry,&geometry_info);\n image->resolution.x=geometry_info.rho;\n image->resolution.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->resolution.y=image->resolution.x;\n }\n if (image_info->density != (char *) NULL)\n {\n flags=ParseGeometry(image_info->density,&geometry_info);\n image->resolution.x=geometry_info.rho;\n image->resolution.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->resolution.y=image->resolution.x;\n }\n (void) memset(&page,0,sizeof(page));\n (void) ParseAbsoluteGeometry(PSPageGeometry,&page);\n if (image_info->page != (char *) NULL)\n (void) ParseAbsoluteGeometry(image_info->page,&page);\n page.width=(size_t) ((ssize_t) ceil((double) (page.width*\n image->resolution.x/delta.x)-0.5));\n page.height=(size_t) ((ssize_t) ceil((double) (page.height*\n image->resolution.y/delta.y)-0.5));\n /*\n Determine page geometry from the PDF media box.\n */\n ReadPDFInfo(image_info,image,&pdf_info,exception);\n (void) CloseBlob(image);\n /*\n Set PDF render geometry.\n */\n if ((fabs(pdf_info.bounds.x2-pdf_info.bounds.x1) >= MagickEpsilon) &&\n (fabs(pdf_info.bounds.y2-pdf_info.bounds.y1) >= MagickEpsilon))\n {\n (void) FormatImageProperty(image,\"pdf:HiResBoundingBox\",\n \"%gx%g%+.15g%+.15g\",pdf_info.bounds.x2-pdf_info.bounds.x1,\n pdf_info.bounds.y2-pdf_info.bounds.y1,pdf_info.bounds.x1,\n pdf_info.bounds.y1);\n page.width=(size_t) ((ssize_t) ceil((double) ((pdf_info.bounds.x2-\n pdf_info.bounds.x1)*image->resolution.x/delta.x)-0.5));\n page.height=(size_t) ((ssize_t) ceil((double) ((pdf_info.bounds.y2-\n pdf_info.bounds.y1)*image->resolution.y/delta.y)-0.5));\n }\n fitPage=MagickFalse;\n option=GetImageOption(image_info,\"pdf:fit-page\");\n if (option != (char *) NULL)\n {\n char\n *page_geometry;\n\n page_geometry=GetPageGeometry(option);\n flags=ParseMetaGeometry(page_geometry,&page.x,&page.y,&page.width,\n &page.height);\n page_geometry=DestroyString(page_geometry);\n if (flags == NoValue)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),OptionError,\n \"InvalidGeometry\",\"`%s'\",option);\n CleanupPDFInfo(&pdf_info);\n image=DestroyImage(image);\n return((Image *) NULL);\n }\n page.width=(size_t) ((ssize_t) ceil((double) (page.width*\n image->resolution.x/delta.x)-0.5));\n page.height=(size_t) ((ssize_t) ceil((double) (page.height*\n image->resolution.y/delta.y)-0.5));\n fitPage=MagickTrue;\n }\n if ((fabs(pdf_info.angle) == 90.0) || (fabs(pdf_info.angle) == 270.0))\n {\n size_t\n swap;\n\n swap=page.width;\n page.width=page.height;\n page.height=swap;\n }\n if (IssRGBCompatibleColorspace(image_info->colorspace) != MagickFalse)\n pdf_info.cmyk=MagickFalse;\n /*\n Create Ghostscript control file.\n */\n file=AcquireUniqueFileResource(postscript_filename);\n if (file == -1)\n {\n ThrowFileException(exception,FileOpenError,\"UnableToCreateTemporaryFile\",\n image_info->filename);\n CleanupPDFInfo(&pdf_info);\n image=DestroyImage(image);\n return((Image *) NULL);\n }\n if (write(file,\" \",1) != 1)\n {\n file=close(file)-1;\n (void) RelinquishUniqueFileResource(postscript_filename);\n CleanupPDFInfo(&pdf_info);\n image=DestroyImage(image);\n return((Image *) NULL);\n }\n file=close(file)-1;\n /*\n Render Postscript with the Ghostscript delegate.\n */\n if (image_info->monochrome != MagickFalse)\n delegate_info=GetDelegateInfo(\"ps:mono\",(char *) NULL,exception);\n else\n if (pdf_info.cmyk != MagickFalse)\n delegate_info=GetDelegateInfo(\"ps:cmyk\",(char *) NULL,exception);\n else\n delegate_info=GetDelegateInfo(\"ps:alpha\",(char *) NULL,exception);\n if (delegate_info == (const DelegateInfo *) NULL)\n {\n (void) RelinquishUniqueFileResource(postscript_filename);\n CleanupPDFInfo(&pdf_info);\n image=DestroyImage(image);\n return((Image *) NULL);\n }\n density=AcquireString(\"\");\n options=AcquireString(\"\");\n (void) FormatLocaleString(density,MagickPathExtent,\"%gx%g\",\n image->resolution.x,image->resolution.y);\n if ((image_info->page != (char *) NULL) || (fitPage != MagickFalse))\n (void) FormatLocaleString(options,MagickPathExtent,\"-g%.20gx%.20g \",(double)\n page.width,(double) page.height);\n if (fitPage != MagickFalse)\n (void) ConcatenateMagickString(options,\"-dPSFitPage \",MagickPathExtent);\n if (pdf_info.cropbox != MagickFalse)\n (void) ConcatenateMagickString(options,\"-dUseCropBox \",MagickPathExtent);\n if (pdf_info.trimbox != MagickFalse)\n (void) ConcatenateMagickString(options,\"-dUseTrimBox \",MagickPathExtent);\n option=GetImageOption(image_info,\"pdf:stop-on-error\");\n if (IsStringTrue(option) != MagickFalse)\n (void) ConcatenateMagickString(options,\"-dPDFSTOPONERROR \",\n MagickPathExtent);\n option=GetImageOption(image_info,\"pdf:interpolate\");\n if (IsStringTrue(option) != MagickFalse)\n (void) ConcatenateMagickString(options,\"-dInterpolateControl=-1 \",\n MagickPathExtent);\n option=GetImageOption(image_info,\"authenticate\");\n if ((option != (char *) NULL) &&\n (strpbrk(option,\"&;<>|\\\"'\") == (char *) NULL))\n {\n char\n passphrase[MagickPathExtent];\n\n (void) FormatLocaleString(passphrase,MagickPathExtent,\n \"\\\"-sPDFPassword=%s\\\" \",option);\n (void) ConcatenateMagickString(options,passphrase,MagickPathExtent);\n }\n read_info=CloneImageInfo(image_info);\n *read_info->magick='\\0';\n if (read_info->number_scenes != 0)\n {\n char\n pages[MagickPathExtent];\n\n (void) FormatLocaleString(pages,MagickPathExtent,\"-dFirstPage=%.20g \"\n \"-dLastPage=%.20g\",(double) read_info->scene+1,(double)\n (read_info->scene+read_info->number_scenes));\n (void) ConcatenateMagickString(options,pages,MagickPathExtent);\n read_info->number_scenes=0;\n if (read_info->scenes != (char *) NULL)\n *read_info->scenes='\\0';\n }\n (void) CopyMagickString(filename,read_info->filename,MagickPathExtent);\n (void) AcquireUniqueFilename(filename);\n (void) RelinquishUniqueFileResource(filename);\n (void) ConcatenateMagickString(filename,\"%d\",MagickPathExtent);\n (void) FormatLocaleString(command,MagickPathExtent,\n GetDelegateCommands(delegate_info),\n read_info->antialias != MagickFalse ? 4 : 1,\n read_info->antialias != MagickFalse ? 4 : 1,density,options,filename,\n postscript_filename,input_filename);\n options=DestroyString(options);\n density=DestroyString(density);\n *message='\\0';\n status=InvokeGhostscriptDelegate(read_info->verbose,command,message,\n exception);\n (void) RelinquishUniqueFileResource(postscript_filename);\n (void) RelinquishUniqueFileResource(input_filename);\n pdf_image=(Image *) NULL;\n if (status == MagickFalse)\n for (i=1; ; i++)\n {\n (void) InterpretImageFilename(image_info,image,filename,(int) i,\n read_info->filename,exception);\n if (IsGhostscriptRendered(read_info->filename) == MagickFalse)\n break;\n (void) RelinquishUniqueFileResource(read_info->filename);\n }\n else\n for (i=1; ; i++)\n {\n (void) InterpretImageFilename(image_info,image,filename,(int) i,\n read_info->filename,exception);\n if (IsGhostscriptRendered(read_info->filename) == MagickFalse)\n break;\n read_info->blob=NULL;\n read_info->length=0;\n next=ReadImage(read_info,exception);\n (void) RelinquishUniqueFileResource(read_info->filename);\n if (next == (Image *) NULL)\n break;\n AppendImageToList(&pdf_image,next);\n }\n read_info=DestroyImageInfo(read_info);\n if (pdf_image == (Image *) NULL)\n {\n if (*message != '\\0')\n (void) ThrowMagickException(exception,GetMagickModule(),DelegateError,\n \"PDFDelegateFailed\",\"`%s'\",message);\n CleanupPDFInfo(&pdf_info);\n image=DestroyImage(image);\n return((Image *) NULL);\n }\n if (LocaleCompare(pdf_image->magick,\"BMP\") == 0)\n {\n Image\n *cmyk_image;\n\n cmyk_image=ConsolidateCMYKImages(pdf_image,exception);\n if (cmyk_image != (Image *) NULL)\n {\n pdf_image=DestroyImageList(pdf_image);\n pdf_image=cmyk_image;\n }\n }\n if (pdf_info.profile != (StringInfo *) NULL)\n {\n char\n *profile;\n\n (void) SetImageProfile(image,\"xmp\",pdf_info.profile,exception);\n profile=(char *) GetStringInfoDatum(pdf_info.profile);\n if (strstr(profile,\"Adobe Illustrator\") != (char *) NULL)\n (void) CopyMagickString(image->magick,\"AI\",MagickPathExtent);\n }\n CleanupPDFInfo(&pdf_info);\n if (image_info->number_scenes != 0)\n {\n Image\n *clone_image;\n\n /*\n Add place holder images to meet the subimage specification requirement.\n */\n for (i=0; i < (ssize_t) image_info->scene; i++)\n {\n clone_image=CloneImage(pdf_image,1,1,MagickTrue,exception);\n if (clone_image != (Image *) NULL)\n PrependImageToList(&pdf_image,clone_image);\n }\n }\n do\n {\n (void) CopyMagickString(pdf_image->filename,filename,MagickPathExtent);\n (void) CopyMagickString(pdf_image->magick,image->magick,MagickPathExtent);\n pdf_image->page=page;\n (void) CloneImageProfiles(pdf_image,image);\n (void) CloneImageProperties(pdf_image,image);\n next=SyncNextImageInList(pdf_image);\n if (next != (Image *) NULL)\n pdf_image=next;\n } while (next != (Image *) NULL);\n image=DestroyImage(image);\n scene=0;\n for (next=GetFirstImageInList(pdf_image); next != (Image *) NULL; )\n {\n next->scene=scene++;\n next=GetNextImageInList(next);\n }\n return(GetFirstImageInList(pdf_image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-91'], 'message': 'fix shell injection vulnerability via the -authenticate option'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: opj_pi_iterator_t *opj_pi_create_decode(opj_image_t *p_image,\n opj_cp_t *p_cp,\n OPJ_UINT32 p_tile_no)\n{\n OPJ_UINT32 numcomps = p_image->numcomps;\n\n /* loop */\n OPJ_UINT32 pino;\n OPJ_UINT32 compno, resno;\n\n /* to store w, h, dx and dy fro all components and resolutions */\n OPJ_UINT32 * l_tmp_data;\n OPJ_UINT32 ** l_tmp_ptr;\n\n /* encoding prameters to set */\n OPJ_UINT32 l_max_res;\n OPJ_UINT32 l_max_prec;\n OPJ_UINT32 l_tx0, l_tx1, l_ty0, l_ty1;\n OPJ_UINT32 l_dx_min, l_dy_min;\n OPJ_UINT32 l_bound;\n OPJ_UINT32 l_step_p, l_step_c, l_step_r, l_step_l ;\n OPJ_UINT32 l_data_stride;\n\n /* pointers */\n opj_pi_iterator_t *l_pi = 00;\n opj_tcp_t *l_tcp = 00;\n const opj_tccp_t *l_tccp = 00;\n opj_pi_comp_t *l_current_comp = 00;\n opj_image_comp_t * l_img_comp = 00;\n opj_pi_iterator_t * l_current_pi = 00;\n OPJ_UINT32 * l_encoding_value_ptr = 00;\n\n /* preconditions in debug */\n assert(p_cp != 00);\n assert(p_image != 00);\n assert(p_tile_no < p_cp->tw * p_cp->th);\n\n /* initializations */\n l_tcp = &p_cp->tcps[p_tile_no];\n l_bound = l_tcp->numpocs + 1;\n\n l_data_stride = 4 * OPJ_J2K_MAXRLVLS;\n l_tmp_data = (OPJ_UINT32*)opj_malloc(\n l_data_stride * numcomps * sizeof(OPJ_UINT32));\n if\n (! l_tmp_data) {\n return 00;\n }\n l_tmp_ptr = (OPJ_UINT32**)opj_malloc(\n numcomps * sizeof(OPJ_UINT32 *));\n if\n (! l_tmp_ptr) {\n opj_free(l_tmp_data);\n return 00;\n }\n\n /* memory allocation for pi */\n l_pi = opj_pi_create(p_image, p_cp, p_tile_no);\n if (!l_pi) {\n opj_free(l_tmp_data);\n opj_free(l_tmp_ptr);\n return 00;\n }\n\n l_encoding_value_ptr = l_tmp_data;\n /* update pointer array */\n for\n (compno = 0; compno < numcomps; ++compno) {\n l_tmp_ptr[compno] = l_encoding_value_ptr;\n l_encoding_value_ptr += l_data_stride;\n }\n /* get encoding parameters */\n opj_get_all_encoding_parameters(p_image, p_cp, p_tile_no, &l_tx0, &l_tx1,\n &l_ty0, &l_ty1, &l_dx_min, &l_dy_min, &l_max_prec, &l_max_res, l_tmp_ptr);\n\n /* step calculations */\n l_step_p = 1;\n l_step_c = l_max_prec * l_step_p;\n l_step_r = numcomps * l_step_c;\n l_step_l = l_max_res * l_step_r;\n\n /* set values for first packet iterator */\n l_current_pi = l_pi;\n\n /* memory allocation for include */\n /* prevent an integer overflow issue */\n /* 0 < l_tcp->numlayers < 65536 c.f. opj_j2k_read_cod in j2k.c */\n l_current_pi->include = 00;\n if (l_step_l <= (UINT_MAX / (l_tcp->numlayers + 1U))) {\n l_current_pi->include_size = (l_tcp->numlayers + 1U) * l_step_l;\n l_current_pi->include = (OPJ_INT16*) opj_calloc(\n l_current_pi->include_size, sizeof(OPJ_INT16));\n }\n\n if (!l_current_pi->include) {\n opj_free(l_tmp_data);\n opj_free(l_tmp_ptr);\n opj_pi_destroy(l_pi, l_bound);\n return 00;\n }\n\n /* special treatment for the first packet iterator */\n l_current_comp = l_current_pi->comps;\n l_img_comp = p_image->comps;\n l_tccp = l_tcp->tccps;\n\n l_current_pi->tx0 = l_tx0;\n l_current_pi->ty0 = l_ty0;\n l_current_pi->tx1 = l_tx1;\n l_current_pi->ty1 = l_ty1;\n\n /*l_current_pi->dx = l_img_comp->dx;*/\n /*l_current_pi->dy = l_img_comp->dy;*/\n\n l_current_pi->step_p = l_step_p;\n l_current_pi->step_c = l_step_c;\n l_current_pi->step_r = l_step_r;\n l_current_pi->step_l = l_step_l;\n\n /* allocation for components and number of components has already been calculated by opj_pi_create */\n for\n (compno = 0; compno < numcomps; ++compno) {\n opj_pi_resolution_t *l_res = l_current_comp->resolutions;\n l_encoding_value_ptr = l_tmp_ptr[compno];\n\n l_current_comp->dx = l_img_comp->dx;\n l_current_comp->dy = l_img_comp->dy;\n /* resolutions have already been initialized */\n for\n (resno = 0; resno < l_current_comp->numresolutions; resno++) {\n l_res->pdx = *(l_encoding_value_ptr++);\n l_res->pdy = *(l_encoding_value_ptr++);\n l_res->pw = *(l_encoding_value_ptr++);\n l_res->ph = *(l_encoding_value_ptr++);\n ++l_res;\n }\n ++l_current_comp;\n ++l_img_comp;\n ++l_tccp;\n }\n ++l_current_pi;\n\n for (pino = 1 ; pino < l_bound ; ++pino) {\n l_current_comp = l_current_pi->comps;\n l_img_comp = p_image->comps;\n l_tccp = l_tcp->tccps;\n\n l_current_pi->tx0 = l_tx0;\n l_current_pi->ty0 = l_ty0;\n l_current_pi->tx1 = l_tx1;\n l_current_pi->ty1 = l_ty1;\n /*l_current_pi->dx = l_dx_min;*/\n /*l_current_pi->dy = l_dy_min;*/\n l_current_pi->step_p = l_step_p;\n l_current_pi->step_c = l_step_c;\n l_current_pi->step_r = l_step_r;\n l_current_pi->step_l = l_step_l;\n\n /* allocation for components and number of components has already been calculated by opj_pi_create */\n for\n (compno = 0; compno < numcomps; ++compno) {\n opj_pi_resolution_t *l_res = l_current_comp->resolutions;\n l_encoding_value_ptr = l_tmp_ptr[compno];\n\n l_current_comp->dx = l_img_comp->dx;\n l_current_comp->dy = l_img_comp->dy;\n /* resolutions have already been initialized */\n for\n (resno = 0; resno < l_current_comp->numresolutions; resno++) {\n l_res->pdx = *(l_encoding_value_ptr++);\n l_res->pdy = *(l_encoding_value_ptr++);\n l_res->pw = *(l_encoding_value_ptr++);\n l_res->ph = *(l_encoding_value_ptr++);\n ++l_res;\n }\n ++l_current_comp;\n ++l_img_comp;\n ++l_tccp;\n }\n /* special treatment*/\n l_current_pi->include = (l_current_pi - 1)->include;\n l_current_pi->include_size = (l_current_pi - 1)->include_size;\n ++l_current_pi;\n }\n opj_free(l_tmp_data);\n l_tmp_data = 00;\n opj_free(l_tmp_ptr);\n l_tmp_ptr = 00;\n if\n (l_tcp->POC) {\n opj_pi_update_decode_poc(l_pi, l_tcp, l_max_prec, l_max_res);\n } else {\n opj_pi_update_decode_not_poc(l_pi, l_tcp, l_max_prec, l_max_res);\n }\n return l_pi;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-122'], 'message': 'pi.c: avoid out of bounds access with POC (refs https://github.com/uclouvain/openjpeg/issues/1293#issuecomment-737122836)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void encode_help_display(void)\n{\n fprintf(stdout,\n \"\\nThis is the opj_compress utility from the OpenJPEG project.\\n\"\n \"It compresses various image formats with the JPEG 2000 algorithm.\\n\"\n \"It has been compiled against openjp2 library v%s.\\n\\n\", opj_version());\n\n fprintf(stdout, \"Default encoding options:\\n\");\n fprintf(stdout, \"-------------------------\\n\");\n fprintf(stdout, \"\\n\");\n fprintf(stdout, \" * Lossless\\n\");\n fprintf(stdout, \" * 1 tile\\n\");\n fprintf(stdout, \" * RGB->YCC conversion if at least 3 components\\n\");\n fprintf(stdout, \" * Size of precinct : 2^15 x 2^15 (means 1 precinct)\\n\");\n fprintf(stdout, \" * Size of code-block : 64 x 64\\n\");\n fprintf(stdout, \" * Number of resolutions: 6\\n\");\n fprintf(stdout, \" * No SOP marker in the codestream\\n\");\n fprintf(stdout, \" * No EPH marker in the codestream\\n\");\n fprintf(stdout, \" * No sub-sampling in x or y direction\\n\");\n fprintf(stdout, \" * No mode switch activated\\n\");\n fprintf(stdout, \" * Progression order: LRCP\\n\");\n#ifdef FIXME_INDEX\n fprintf(stdout, \" * No index file\\n\");\n#endif /* FIXME_INDEX */\n fprintf(stdout, \" * No ROI upshifted\\n\");\n fprintf(stdout, \" * No offset of the origin of the image\\n\");\n fprintf(stdout, \" * No offset of the origin of the tiles\\n\");\n fprintf(stdout, \" * Reversible DWT 5-3\\n\");\n /* UniPG>> */\n#ifdef USE_JPWL\n fprintf(stdout, \" * No JPWL protection\\n\");\n#endif /* USE_JPWL */\n /* <\\n\");\n fprintf(stdout, \" Input file\\n\");\n fprintf(stdout,\n \" Known extensions are \\n\");\n fprintf(stdout, \" If used, '-o ' must be provided\\n\");\n fprintf(stdout, \"-o \\n\");\n fprintf(stdout, \" Output file (accepted extensions are j2k or jp2).\\n\");\n fprintf(stdout, \"-ImgDir \\n\");\n fprintf(stdout, \" Image file Directory path (example ../Images) \\n\");\n fprintf(stdout, \" When using this option -OutFor must be used\\n\");\n fprintf(stdout, \"-OutFor \\n\");\n fprintf(stdout, \" Output format for compressed files.\\n\");\n fprintf(stdout, \" Required only if -ImgDir is used\\n\");\n fprintf(stdout,\n \"-F ,,,,{s,u}@x:...:x\\n\");\n fprintf(stdout, \" Characteristics of the raw input image\\n\");\n fprintf(stdout,\n \" If subsampling is omitted, 1x1 is assumed for all components\\n\");\n fprintf(stdout, \" Example: -F 512,512,3,8,u@1x1:2x2:2x2\\n\");\n fprintf(stdout,\n \" for raw 512x512 image with 4:2:0 subsampling\\n\");\n fprintf(stdout, \" Required only if RAW or RAWL input file is provided.\\n\");\n fprintf(stdout, \"\\n\");\n fprintf(stdout, \"Optional Parameters:\\n\");\n fprintf(stdout, \"\\n\");\n fprintf(stdout, \"-h\\n\");\n fprintf(stdout, \" Display the help information.\\n\");\n fprintf(stdout, \"-r ,,...\\n\");\n fprintf(stdout, \" Different compression ratios for successive layers.\\n\");\n fprintf(stdout,\n \" The rate specified for each quality level is the desired\\n\");\n fprintf(stdout, \" compression factor (use 1 for lossless)\\n\");\n fprintf(stdout, \" Decreasing ratios required.\\n\");\n fprintf(stdout, \" Example: -r 20,10,1 means \\n\");\n fprintf(stdout, \" quality layer 1: compress 20x, \\n\");\n fprintf(stdout, \" quality layer 2: compress 10x \\n\");\n fprintf(stdout, \" quality layer 3: compress lossless\\n\");\n fprintf(stdout, \" Options -r and -q cannot be used together.\\n\");\n fprintf(stdout, \"-q ,,,...\\n\");\n fprintf(stdout, \" Different psnr for successive layers (-q 30,40,50).\\n\");\n fprintf(stdout, \" Increasing PSNR values required, except 0 which can\\n\");\n fprintf(stdout, \" be used for the last layer to indicate it is lossless.\\n\");\n fprintf(stdout, \" Options -r and -q cannot be used together.\\n\");\n fprintf(stdout, \"-n \\n\");\n fprintf(stdout, \" Number of resolutions.\\n\");\n fprintf(stdout,\n \" It corresponds to the number of DWT decompositions +1. \\n\");\n fprintf(stdout, \" Default: 6.\\n\");\n fprintf(stdout, \"-b ,\\n\");\n fprintf(stdout,\n \" Code-block size. The dimension must respect the constraint \\n\");\n fprintf(stdout,\n \" defined in the JPEG-2000 standard (no dimension smaller than 4 \\n\");\n fprintf(stdout,\n \" or greater than 1024, no code-block with more than 4096 coefficients).\\n\");\n fprintf(stdout, \" The maximum value authorized is 64x64. \\n\");\n fprintf(stdout, \" Default: 64x64.\\n\");\n fprintf(stdout,\n \"-c [,],[,],...\\n\");\n fprintf(stdout, \" Precinct size. Values specified must be power of 2. \\n\");\n fprintf(stdout,\n \" Multiple records may be supplied, in which case the first record refers\\n\");\n fprintf(stdout,\n \" to the highest resolution level and subsequent records to lower \\n\");\n fprintf(stdout,\n \" resolution levels. The last specified record is halved successively for each \\n\");\n fprintf(stdout, \" remaining lower resolution levels.\\n\");\n fprintf(stdout, \" Default: 2^15x2^15 at each resolution.\\n\");\n fprintf(stdout, \"-t ,\\n\");\n fprintf(stdout, \" Tile size.\\n\");\n fprintf(stdout,\n \" Default: the dimension of the whole image, thus only one tile.\\n\");\n fprintf(stdout, \"-p \\n\");\n fprintf(stdout, \" Progression order.\\n\");\n fprintf(stdout, \" Default: LRCP.\\n\");\n fprintf(stdout, \"-s \\n\");\n fprintf(stdout, \" Subsampling factor.\\n\");\n fprintf(stdout, \" Subsampling bigger than 2 can produce error\\n\");\n fprintf(stdout, \" Default: no subsampling.\\n\");\n fprintf(stdout,\n \"-POC //...\\n\");\n fprintf(stdout, \" Progression order change.\\n\");\n fprintf(stdout,\n \" The syntax of a progression order change is the following:\\n\");\n fprintf(stdout,\n \" T=,,,,,\\n\");\n fprintf(stdout, \" Example: -POC T1=0,0,1,5,3,CPRL/T1=5,0,1,6,3,CPRL\\n\");\n fprintf(stdout, \"-SOP\\n\");\n fprintf(stdout, \" Write SOP marker before each packet.\\n\");\n fprintf(stdout, \"-EPH\\n\");\n fprintf(stdout, \" Write EPH marker after each header packet.\\n\");\n fprintf(stdout, \"-M \\n\");\n fprintf(stdout, \" Mode switch.\\n\");\n fprintf(stdout, \" [1=BYPASS(LAZY) 2=RESET 4=RESTART(TERMALL)\\n\");\n fprintf(stdout, \" 8=VSC 16=ERTERM(SEGTERM) 32=SEGMARK(SEGSYM)]\\n\");\n fprintf(stdout, \" Indicate multiple modes by adding their values.\\n\");\n fprintf(stdout,\n \" Example: RESTART(4) + RESET(2) + SEGMARK(32) => -M 38\\n\");\n fprintf(stdout, \"-TP \\n\");\n fprintf(stdout, \" Divide packets of every tile into tile-parts.\\n\");\n fprintf(stdout,\n \" Division is made by grouping Resolutions (R), Layers (L)\\n\");\n fprintf(stdout, \" or Components (C).\\n\");\n#ifdef FIXME_INDEX\n fprintf(stdout, \"-x \\n\");\n fprintf(stdout, \" Create an index file.\\n\");\n#endif /*FIXME_INDEX*/\n fprintf(stdout, \"-ROI c=,U=\\n\");\n fprintf(stdout, \" Quantization indices upshifted for a component. \\n\");\n fprintf(stdout,\n \" Warning: This option does not implement the usual ROI (Region of Interest).\\n\");\n fprintf(stdout,\n \" It should be understood as a 'Component of Interest'. It offers the \\n\");\n fprintf(stdout,\n \" possibility to upshift the value of a component during quantization step.\\n\");\n fprintf(stdout,\n \" The value after c= is the component number [0, 1, 2, ...] and the value \\n\");\n fprintf(stdout,\n \" after U= is the value of upshifting. U must be in the range [0, 37].\\n\");\n fprintf(stdout, \"-d \\n\");\n fprintf(stdout, \" Offset of the origin of the image.\\n\");\n fprintf(stdout, \"-T \\n\");\n fprintf(stdout, \" Offset of the origin of the tiles.\\n\");\n fprintf(stdout, \"-I\\n\");\n fprintf(stdout, \" Use the irreversible DWT 9-7.\\n\");\n fprintf(stdout, \"-mct <0|1|2>\\n\");\n fprintf(stdout,\n \" Explicitly specifies if a Multiple Component Transform has to be used.\\n\");\n fprintf(stdout, \" 0: no MCT ; 1: RGB->YCC conversion ; 2: custom MCT.\\n\");\n fprintf(stdout,\n \" If custom MCT, \\\"-m\\\" option has to be used (see hereunder).\\n\");\n fprintf(stdout,\n \" By default, RGB->YCC conversion is used if there are 3 components or more,\\n\");\n fprintf(stdout, \" no conversion otherwise.\\n\");\n fprintf(stdout, \"-m \\n\");\n fprintf(stdout,\n \" Use array-based MCT, values are coma separated, line by line\\n\");\n fprintf(stdout,\n \" No specific separators between lines, no space allowed between values.\\n\");\n fprintf(stdout,\n \" If this option is used, it automatically sets \\\"-mct\\\" option to 2.\\n\");\n fprintf(stdout, \"-cinema2K <24|48>\\n\");\n fprintf(stdout, \" Digital Cinema 2K profile compliant codestream.\\n\");\n fprintf(stdout,\n \"\tNeed to specify the frames per second for a 2K resolution.\\n\");\n fprintf(stdout, \" Only 24 or 48 fps are currently allowed.\\n\");\n fprintf(stdout, \"-cinema4K\\n\");\n fprintf(stdout, \" Digital Cinema 4K profile compliant codestream.\\n\");\n fprintf(stdout, \"\tFrames per second not required. Default value is 24fps.\\n\");\n fprintf(stdout, \"-IMF [,mainlevel=X][,sublevel=Y][,framerate=FPS]\\n\");\n fprintf(stdout, \" Interoperable Master Format compliant codestream.\\n\");\n fprintf(stdout, \" =2K, 4K, 8K, 2K_R, 4K_R or 8K_R.\\n\");\n fprintf(stdout, \" X >= 0 and X <= 11.\\n\");\n fprintf(stdout, \" Y >= 0 and Y <= 9.\\n\");\n fprintf(stdout,\n \" framerate > 0 may be specified to enhance checks and set maximum bit rate when Y > 0.\\n\");\n fprintf(stdout, \"-jpip\\n\");\n fprintf(stdout, \" Write jpip codestream index box in JP2 output file.\\n\");\n fprintf(stdout, \" Currently supports only RPCL order.\\n\");\n fprintf(stdout, \"-C \\n\");\n fprintf(stdout, \" Add in the comment marker segment.\\n\");\n /* UniPG>> */\n#ifdef USE_JPWL\n fprintf(stdout, \"-W \\n\");\n fprintf(stdout, \" Adoption of JPWL (Part 11) capabilities (-W params)\\n\");\n fprintf(stdout,\n \" The field can be written and repeated in any order:\\n\");\n fprintf(stdout, \" [h<=type>,s<=method>,a=,...\\n\");\n fprintf(stdout, \" ...,z=,g=,p<=type>]\\n\");\n fprintf(stdout,\n \" h selects the header error protection (EPB): 'type' can be\\n\");\n fprintf(stdout,\n \" [0=none 1,absent=predefined 16=CRC-16 32=CRC-32 37-128=RS]\\n\");\n fprintf(stdout,\n \" if 'tilepart' is absent, it is for main and tile headers\\n\");\n fprintf(stdout, \" if 'tilepart' is present, it applies from that tile\\n\");\n fprintf(stdout,\n \" onwards, up to the next h<> spec, or to the last tilepart\\n\");\n fprintf(stdout, \" in the codestream (max. %d specs)\\n\",\n JPWL_MAX_NO_TILESPECS);\n fprintf(stdout,\n \" p selects the packet error protection (EEP/UEP with EPBs)\\n\");\n fprintf(stdout, \" to be applied to raw data: 'type' can be\\n\");\n fprintf(stdout,\n \" [0=none 1,absent=predefined 16=CRC-16 32=CRC-32 37-128=RS]\\n\");\n fprintf(stdout,\n \" if 'tilepart:pack' is absent, it is from tile 0, packet 0\\n\");\n fprintf(stdout,\n \" if 'tilepart:pack' is present, it applies from that tile\\n\");\n fprintf(stdout,\n \" and that packet onwards, up to the next packet spec\\n\");\n fprintf(stdout,\n \" or to the last packet in the last tilepart in the stream\\n\");\n fprintf(stdout, \" (max. %d specs)\\n\", JPWL_MAX_NO_PACKSPECS);\n fprintf(stdout,\n \" s enables sensitivity data insertion (ESD): 'method' can be\\n\");\n fprintf(stdout,\n \" [-1=NO ESD 0=RELATIVE ERROR 1=MSE 2=MSE REDUCTION 3=PSNR\\n\");\n fprintf(stdout, \" 4=PSNR INCREMENT 5=MAXERR 6=TSE 7=RESERVED]\\n\");\n fprintf(stdout, \" if 'tilepart' is absent, it is for main header only\\n\");\n fprintf(stdout, \" if 'tilepart' is present, it applies from that tile\\n\");\n fprintf(stdout,\n \" onwards, up to the next s<> spec, or to the last tilepart\\n\");\n fprintf(stdout, \" in the codestream (max. %d specs)\\n\",\n JPWL_MAX_NO_TILESPECS);\n fprintf(stdout, \" g determines the addressing mode: can be\\n\");\n fprintf(stdout, \" [0=PACKET 1=BYTE RANGE 2=PACKET RANGE]\\n\");\n fprintf(stdout,\n \" a determines the size of data addressing: can be\\n\");\n fprintf(stdout,\n \" 2/4 bytes (small/large codestreams). If not set, auto-mode\\n\");\n fprintf(stdout,\n \" z determines the size of sensitivity values: can be\\n\");\n fprintf(stdout,\n \" 1/2 bytes, for the transformed pseudo-floating point value\\n\");\n fprintf(stdout, \" ex.:\\n\");\n fprintf(stdout,\n \" h,h0=64,h3=16,h5=32,p0=78,p0:24=56,p1,p3:0=0,p3:20=32,s=0,\\n\");\n fprintf(stdout, \" s0=6,s3=-1,a=0,g=1,z=1\\n\");\n fprintf(stdout, \" means\\n\");\n fprintf(stdout,\n \" predefined EPB in MH, rs(64,32) from TPH 0 to TPH 2,\\n\");\n fprintf(stdout,\n \" CRC-16 in TPH 3 and TPH 4, CRC-32 in remaining TPHs,\\n\");\n fprintf(stdout, \" UEP rs(78,32) for packets 0 to 23 of tile 0,\\n\");\n fprintf(stdout,\n \" UEP rs(56,32) for packs. 24 to the last of tilepart 0,\\n\");\n fprintf(stdout, \" UEP rs default for packets of tilepart 1,\\n\");\n fprintf(stdout, \" no UEP for packets 0 to 19 of tilepart 3,\\n\");\n fprintf(stdout,\n \" UEP CRC-32 for packs. 20 of tilepart 3 to last tilepart,\\n\");\n fprintf(stdout, \" relative sensitivity ESD for MH,\\n\");\n fprintf(stdout,\n \" TSE ESD from TPH 0 to TPH 2, byte range with automatic\\n\");\n fprintf(stdout,\n \" size of addresses and 1 byte for each sensitivity value\\n\");\n fprintf(stdout, \" ex.:\\n\");\n fprintf(stdout, \" h,s,p\\n\");\n fprintf(stdout, \" means\\n\");\n fprintf(stdout,\n \" default protection to headers (MH and TPHs) as well as\\n\");\n fprintf(stdout, \" data packets, one ESD in MH\\n\");\n fprintf(stdout,\n \" N.B.: use the following recommendations when specifying\\n\");\n fprintf(stdout, \" the JPWL parameters list\\n\");\n fprintf(stdout,\n \" - when you use UEP, always pair the 'p' option with 'h'\\n\");\n#endif /* USE_JPWL */\n /* < \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Add support for generation of PLT markers in encoder\n\n* -PLT switch added to opj_compress\n* Add a opj_encoder_set_extra_options() function that\n accepts a PLT=YES option, and could be expanded later\n for other uses.\n\n-------\n\nTesting with a Sentinel2 10m band, T36JTT_20160914T074612_B02.jp2,\ncoming from S2A_MSIL1C_20160914T074612_N0204_R135_T36JTT_20160914T081456.SAFE\n\nDecompress it to TIFF:\n```\nopj_uncompress -i T36JTT_20160914T074612_B02.jp2 -o T36JTT_20160914T074612_B02.tif\n```\n\nRecompress it with similar parameters as original:\n```\nopj_compress -n 5 -c [256,256],[256,256],[256,256],[256,256],[256,256] -t 1024,1024 -PLT -i T36JTT_20160914T074612_B02.tif -o T36JTT_20160914T074612_B02_PLT.jp2\n```\n\nDump codestream detail with GDAL dump_jp2.py utility (https://github.com/OSGeo/gdal/blob/master/gdal/swig/python/samples/dump_jp2.py)\n```\npython dump_jp2.py T36JTT_20160914T074612_B02.jp2 > /tmp/dump_sentinel2_ori.txt\npython dump_jp2.py T36JTT_20160914T074612_B02_PLT.jp2 > /tmp/dump_sentinel2_openjpeg_plt.txt\n```\n\nThe diff between both show very similar structure, and identical number of packets in PLT markers\n\nNow testing with Kakadu (KDU803_Demo_Apps_for_Linux-x86-64_200210)\n\nFull file decompression:\n```\nkdu_expand -i T36JTT_20160914T074612_B02_PLT.jp2 -o tmp.tif\n\nConsumed 121 tile-part(s) from a total of 121 tile(s).\nConsumed 80,318,806 codestream bytes (excluding any file format) = 5.329697\nbits/pel.\nProcessed using the multi-threaded environment, with\n 8 parallel threads of execution\n```\n\nPartial decompresson (presumably using PLT markers):\n```\nkdu_expand -i T36JTT_20160914T074612_B02.jp2 -o tmp.pgm -region \"{0.5,0.5},{0.01,0.01}\"\nkdu_expand -i T36JTT_20160914T074612_B02_PLT.jp2 -o tmp2.pgm -region \"{0.5,0.5},{0.01,0.01}\"\ndiff tmp.pgm tmp2.pgm && echo \"same !\"\n```\n\n-------\n\nFunded by ESA for S2-MPC project'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ipv4_sanity_check(const struct ip_header *nh, size_t size,\n int *ip_lenp, uint16_t *tot_lenp)\n{\n int ip_len;\n uint16_t tot_len;\n\n if (OVS_UNLIKELY(size < IP_HEADER_LEN)) {\n return false;\n }\n ip_len = IP_IHL(nh->ip_ihl_ver) * 4;\n\n if (OVS_UNLIKELY(ip_len < IP_HEADER_LEN || size < ip_len)) {\n return false;\n }\n\n tot_len = ntohs(nh->ip_tot_len);\n if (OVS_UNLIKELY(tot_len > size || ip_len > tot_len ||\n size - tot_len > UINT8_MAX)) {\n return false;\n }\n\n *ip_lenp = ip_len;\n *tot_lenp = tot_len;\n\n return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': 'flow: Support extra padding length.\n\nAlthough not required, padding can be optionally added until\nthe packet length is MTU bytes. A packet with extra padding\ncurrently fails sanity checks.\n\nVulnerability: CVE-2020-35498\nFixes: fa8d9001a624 (\"miniflow_extract: Properly handle small IP packets.\")\nReported-by: Joakim Hindersson \nAcked-by: Ilya Maximets \nSigned-off-by: Flavio Leitner \nSigned-off-by: Ilya Maximets '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void esp_do_dma(ESPState *s)\n{\n uint32_t len, cmdlen;\n int to_device = ((s->rregs[ESP_RSTAT] & 7) == STAT_DO);\n uint8_t buf[ESP_CMDFIFO_SZ];\n\n len = esp_get_tc(s);\n if (s->do_cmd) {\n /*\n * handle_ti_cmd() case: esp_do_dma() is called only from\n * handle_ti_cmd() with do_cmd != NULL (see the assert())\n */\n cmdlen = fifo8_num_used(&s->cmdfifo);\n trace_esp_do_dma(cmdlen, len);\n if (s->dma_memory_read) {\n s->dma_memory_read(s->dma_opaque, buf, len);\n fifo8_push_all(&s->cmdfifo, buf, len);\n } else {\n s->pdma_cb = do_dma_pdma_cb;\n esp_raise_drq(s);\n return;\n }\n trace_esp_handle_ti_cmd(cmdlen);\n s->ti_size = 0;\n if ((s->rregs[ESP_RSTAT] & 7) == STAT_CD) {\n /* No command received */\n if (s->cmdfifo_cdb_offset == fifo8_num_used(&s->cmdfifo)) {\n return;\n }\n\n /* Command has been received */\n s->do_cmd = 0;\n do_cmd(s);\n } else {\n /*\n * Extra message out bytes received: update cmdfifo_cdb_offset\n * and then switch to commmand phase\n */\n s->cmdfifo_cdb_offset = fifo8_num_used(&s->cmdfifo);\n s->rregs[ESP_RSTAT] = STAT_TC | STAT_CD;\n s->rregs[ESP_RSEQ] = SEQ_CD;\n s->rregs[ESP_RINTR] |= INTR_BS;\n esp_raise_irq(s);\n }\n return;\n }\n if (s->async_len == 0) {\n /* Defer until data is available. */\n return;\n }\n if (len > s->async_len) {\n len = s->async_len;\n }\n if (to_device) {\n if (s->dma_memory_read) {\n s->dma_memory_read(s->dma_opaque, s->async_buf, len);\n } else {\n s->pdma_cb = do_dma_pdma_cb;\n esp_raise_drq(s);\n return;\n }\n } else {\n if (s->dma_memory_write) {\n s->dma_memory_write(s->dma_opaque, s->async_buf, len);\n } else {\n /* Adjust TC for any leftover data in the FIFO */\n if (!fifo8_is_empty(&s->fifo)) {\n esp_set_tc(s, esp_get_tc(s) - fifo8_num_used(&s->fifo));\n }\n\n /* Copy device data to FIFO */\n len = MIN(len, fifo8_num_free(&s->fifo));\n fifo8_push_all(&s->fifo, s->async_buf, len);\n s->async_buf += len;\n s->async_len -= len;\n s->ti_size -= len;\n\n /*\n * MacOS toolbox uses a TI length of 16 bytes for all commands, so\n * commands shorter than this must be padded accordingly\n */\n if (len < esp_get_tc(s) && esp_get_tc(s) <= ESP_FIFO_SZ) {\n while (fifo8_num_used(&s->fifo) < ESP_FIFO_SZ) {\n esp_fifo_push(s, 0);\n len++;\n }\n }\n\n esp_set_tc(s, esp_get_tc(s) - len);\n s->pdma_cb = do_dma_pdma_cb;\n esp_raise_drq(s);\n\n /* Indicate transfer to FIFO is complete */\n s->rregs[ESP_RSTAT] |= STAT_TC;\n return;\n }\n }\n esp_set_tc(s, esp_get_tc(s) - len);\n s->async_buf += len;\n s->async_len -= len;\n if (to_device) {\n s->ti_size += len;\n } else {\n s->ti_size -= len;\n }\n if (s->async_len == 0) {\n scsi_req_continue(s->current_req);\n /*\n * If there is still data to be read from the device then\n * complete the DMA operation immediately. Otherwise defer\n * until the scsi layer has completed.\n */\n if (to_device || esp_get_tc(s) != 0 || s->ti_size == 0) {\n return;\n }\n }\n\n /* Partially filled a scsi buffer. Complete immediately. */\n esp_dma_done(s);\n esp_lower_drq(s);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'esp: always check current_req is not NULL before use in DMA callbacks\n\nAfter issuing a SCSI command the SCSI layer can call the SCSIBusInfo .cancel\ncallback which resets both current_req and current_dev to NULL. If any data\nis left in the transfer buffer (async_len != 0) then the next TI (Transfer\nInformation) command will attempt to reference the NULL pointer causing a\nsegfault.\n\nBuglink: https://bugs.launchpad.net/qemu/+bug/1910723\nBuglink: https://bugs.launchpad.net/qemu/+bug/1909247\nSigned-off-by: Mark Cave-Ayland \nTested-by: Alexander Bulekov \nMessage-Id: <20210407195801.685-2-mark.cave-ayland@ilande.co.uk>'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static uint8_t esp_pdma_read(ESPState *s)\n{\n uint8_t val;\n\n if (s->do_cmd) {\n val = esp_cmdfifo_pop(s);\n } else {\n val = esp_fifo_pop(s);\n }\n\n return val;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'esp: consolidate esp_cmdfifo_pop() into esp_fifo_pop()\n\nEach FIFO currently has its own pop functions with the only difference being\nthe capacity check. The original reason for this was that the fifo8\nimplementation doesn't have a formal API for retrieving the FIFO capacity,\nhowever there are multiple examples within QEMU where the capacity field is\naccessed directly.\n\nChange esp_fifo_pop() to access the FIFO capacity directly and then consolidate\nesp_cmdfifo_pop() into esp_fifo_pop().\n\nSigned-off-by: Mark Cave-Ayland \nReviewed-by: Philippe Mathieu-Daud\u00e9 \nTested-by: Alexander Bulekov \nMessage-Id: <20210407195801.685-5-mark.cave-ayland@ilande.co.uk>'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void esp_do_dma(ESPState *s)\n{\n uint32_t len, cmdlen;\n int to_device = ((s->rregs[ESP_RSTAT] & 7) == STAT_DO);\n uint8_t buf[ESP_CMDFIFO_SZ];\n\n len = esp_get_tc(s);\n if (s->do_cmd) {\n /*\n * handle_ti_cmd() case: esp_do_dma() is called only from\n * handle_ti_cmd() with do_cmd != NULL (see the assert())\n */\n cmdlen = fifo8_num_used(&s->cmdfifo);\n trace_esp_do_dma(cmdlen, len);\n if (s->dma_memory_read) {\n s->dma_memory_read(s->dma_opaque, buf, len);\n fifo8_push_all(&s->cmdfifo, buf, len);\n } else {\n s->pdma_cb = do_dma_pdma_cb;\n esp_raise_drq(s);\n return;\n }\n trace_esp_handle_ti_cmd(cmdlen);\n s->ti_size = 0;\n if ((s->rregs[ESP_RSTAT] & 7) == STAT_CD) {\n /* No command received */\n if (s->cmdfifo_cdb_offset == fifo8_num_used(&s->cmdfifo)) {\n return;\n }\n\n /* Command has been received */\n s->do_cmd = 0;\n do_cmd(s);\n } else {\n /*\n * Extra message out bytes received: update cmdfifo_cdb_offset\n * and then switch to commmand phase\n */\n s->cmdfifo_cdb_offset = fifo8_num_used(&s->cmdfifo);\n s->rregs[ESP_RSTAT] = STAT_TC | STAT_CD;\n s->rregs[ESP_RSEQ] = SEQ_CD;\n s->rregs[ESP_RINTR] |= INTR_BS;\n esp_raise_irq(s);\n }\n return;\n }\n if (!s->current_req) {\n return;\n }\n if (s->async_len == 0) {\n /* Defer until data is available. */\n return;\n }\n if (len > s->async_len) {\n len = s->async_len;\n }\n if (to_device) {\n if (s->dma_memory_read) {\n s->dma_memory_read(s->dma_opaque, s->async_buf, len);\n } else {\n s->pdma_cb = do_dma_pdma_cb;\n esp_raise_drq(s);\n return;\n }\n } else {\n if (s->dma_memory_write) {\n s->dma_memory_write(s->dma_opaque, s->async_buf, len);\n } else {\n /* Adjust TC for any leftover data in the FIFO */\n if (!fifo8_is_empty(&s->fifo)) {\n esp_set_tc(s, esp_get_tc(s) - fifo8_num_used(&s->fifo));\n }\n\n /* Copy device data to FIFO */\n len = MIN(len, fifo8_num_free(&s->fifo));\n fifo8_push_all(&s->fifo, s->async_buf, len);\n s->async_buf += len;\n s->async_len -= len;\n s->ti_size -= len;\n\n /*\n * MacOS toolbox uses a TI length of 16 bytes for all commands, so\n * commands shorter than this must be padded accordingly\n */\n if (len < esp_get_tc(s) && esp_get_tc(s) <= ESP_FIFO_SZ) {\n while (fifo8_num_used(&s->fifo) < ESP_FIFO_SZ) {\n esp_fifo_push(&s->fifo, 0);\n len++;\n }\n }\n\n esp_set_tc(s, esp_get_tc(s) - len);\n s->pdma_cb = do_dma_pdma_cb;\n esp_raise_drq(s);\n\n /* Indicate transfer to FIFO is complete */\n s->rregs[ESP_RSTAT] |= STAT_TC;\n return;\n }\n }\n esp_set_tc(s, esp_get_tc(s) - len);\n s->async_buf += len;\n s->async_len -= len;\n if (to_device) {\n s->ti_size += len;\n } else {\n s->ti_size -= len;\n }\n if (s->async_len == 0) {\n scsi_req_continue(s->current_req);\n /*\n * If there is still data to be read from the device then\n * complete the DMA operation immediately. Otherwise defer\n * until the scsi layer has completed.\n */\n if (to_device || esp_get_tc(s) != 0 || s->ti_size == 0) {\n return;\n }\n }\n\n /* Partially filled a scsi buffer. Complete immediately. */\n esp_dma_done(s);\n esp_lower_drq(s);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'esp: don't overflow cmdfifo if TC is larger than the cmdfifo size\n\nIf a guest transfers the message out/command phase data using DMA with a TC\nthat is larger than the cmdfifo size then the cmdfifo overflows triggering\nan assert. Limit the size of the transfer to the free space available in\ncmdfifo.\n\nBuglink: https://bugs.launchpad.net/qemu/+bug/1919036\nSigned-off-by: Mark Cave-Ayland \nReviewed-by: Philippe Mathieu-Daud\u00e9 \nTested-by: Alexander Bulekov \nMessage-Id: <20210407195801.685-10-mark.cave-ayland@ilande.co.uk>'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: filter_session_io(struct io *io, int evt, void *arg)\n{\n\tstruct filter_session *fs = arg;\n\tchar *line = NULL;\n\tssize_t len;\n\n\tlog_trace(TRACE_IO, \"filter session: %p: %s %s\", fs, io_strevent(evt),\n\t io_strio(io));\n\n\tswitch (evt) {\n\tcase IO_DATAIN:\n\tnextline:\n\t\tline = io_getline(fs->io, &len);\n\t\t/* No complete line received */\n\t\tif (line == NULL)\n\t\t\treturn;\n\n\t\tfilter_data(fs->id, line);\n\n\t\tgoto nextline;\n\n\tcase IO_DISCONNECTED:\n\t\tio_free(fs->io);\n\t\tfs->io = NULL;\n\t\tbreak;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'smtpd's filter state machine can prematurely release resources\nleading to a crash. From gilles@'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int DCTStream::getChars(int nChars, unsigned char *buffer)\n{\n for (int i = 0; i < nChars;) {\n if (current == limit) {\n if (!readLine())\n return i;\n }\n int left = limit - current;\n if (nChars < left)\n left = nChars;\n memcpy(buffer + i, current, left);\n current += left;\n i += left;\n }\n return nChars;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix DCTStream::getChars we're reading past the buffer check\n\nI wonder how this had never crashed before :S\n\nFixes #1011'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: MagickExport double GenerateDifferentialNoise(RandomInfo *random_info,\n const Quantum pixel,const NoiseType noise_type,const MagickRealType attenuate)\n{\n#define SigmaUniform (attenuate*0.015625)\n#define SigmaGaussian (attenuate*0.015625)\n#define SigmaImpulse (attenuate*0.1)\n#define SigmaLaplacian (attenuate*0.0390625)\n#define SigmaMultiplicativeGaussian (attenuate*0.5)\n#define SigmaPoisson (attenuate*12.5)\n#define SigmaRandom (attenuate)\n#define TauGaussian (attenuate*0.078125)\n\n double\n alpha,\n beta,\n noise,\n sigma;\n\n alpha=GetPseudoRandomValue(random_info);\n switch (noise_type)\n {\n case UniformNoise:\n default:\n {\n noise=(double) (pixel+QuantumRange*SigmaUniform*(alpha-0.5));\n break;\n }\n case GaussianNoise:\n {\n double\n gamma,\n tau;\n\n if (fabs(alpha) < MagickEpsilon)\n alpha=1.0;\n beta=GetPseudoRandomValue(random_info);\n gamma=sqrt(-2.0*log(alpha));\n sigma=gamma*cos((double) (2.0*MagickPI*beta));\n tau=gamma*sin((double) (2.0*MagickPI*beta));\n noise=(double) (pixel+sqrt((double) pixel)*SigmaGaussian*sigma+\n QuantumRange*TauGaussian*tau);\n break;\n }\n case ImpulseNoise:\n {\n if (alpha < (SigmaImpulse/2.0))\n noise=0.0;\n else\n if (alpha >= (1.0-(SigmaImpulse/2.0)))\n noise=(double) QuantumRange;\n else\n noise=(double) pixel;\n break;\n }\n case LaplacianNoise:\n {\n if (alpha <= 0.5)\n {\n if (alpha <= MagickEpsilon)\n noise=(double) (pixel-QuantumRange);\n else\n noise=(double) (pixel+QuantumRange*SigmaLaplacian*log(2.0*alpha)+\n 0.5);\n break;\n }\n beta=1.0-alpha;\n if (beta <= (0.5*MagickEpsilon))\n noise=(double) (pixel+QuantumRange);\n else\n noise=(double) (pixel-QuantumRange*SigmaLaplacian*log(2.0*beta)+0.5);\n break;\n }\n case MultiplicativeGaussianNoise:\n {\n sigma=1.0;\n if (alpha > MagickEpsilon)\n sigma=sqrt(-2.0*log(alpha));\n beta=GetPseudoRandomValue(random_info);\n noise=(double) (pixel+pixel*SigmaMultiplicativeGaussian*sigma*\n cos((double) (2.0*MagickPI*beta))/2.0);\n break;\n }\n case PoissonNoise:\n {\n double\n poisson;\n\n ssize_t\n i;\n\n poisson=exp(-SigmaPoisson*QuantumScale*pixel);\n for (i=0; alpha > poisson; i++)\n {\n beta=GetPseudoRandomValue(random_info);\n alpha*=beta;\n }\n noise=(double) (QuantumRange*i/SigmaPoisson);\n break;\n }\n case RandomNoise:\n {\n noise=(double) (QuantumRange*SigmaRandom*alpha);\n break;\n }\n }\n return(noise);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-369'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/3077'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: flatpak_context_load_metadata (FlatpakContext *context,\n GKeyFile *metakey,\n GError **error)\n{\n gboolean remove;\n g_auto(GStrv) groups = NULL;\n gsize i;\n\n if (g_key_file_has_key (metakey, FLATPAK_METADATA_GROUP_CONTEXT, FLATPAK_METADATA_KEY_SHARED, NULL))\n {\n g_auto(GStrv) shares = g_key_file_get_string_list (metakey, FLATPAK_METADATA_GROUP_CONTEXT,\n FLATPAK_METADATA_KEY_SHARED, NULL, error);\n if (shares == NULL)\n return FALSE;\n\n for (i = 0; shares[i] != NULL; i++)\n {\n FlatpakContextShares share;\n\n share = flatpak_context_share_from_string (parse_negated (shares[i], &remove), NULL);\n if (share == 0)\n g_debug (\"Unknown share type %s\", shares[i]);\n else\n {\n if (remove)\n flatpak_context_remove_shares (context, share);\n else\n flatpak_context_add_shares (context, share);\n }\n }\n }\n\n if (g_key_file_has_key (metakey, FLATPAK_METADATA_GROUP_CONTEXT, FLATPAK_METADATA_KEY_SOCKETS, NULL))\n {\n g_auto(GStrv) sockets = g_key_file_get_string_list (metakey, FLATPAK_METADATA_GROUP_CONTEXT,\n FLATPAK_METADATA_KEY_SOCKETS, NULL, error);\n if (sockets == NULL)\n return FALSE;\n\n for (i = 0; sockets[i] != NULL; i++)\n {\n FlatpakContextSockets socket = flatpak_context_socket_from_string (parse_negated (sockets[i], &remove), NULL);\n if (socket == 0)\n g_debug (\"Unknown socket type %s\", sockets[i]);\n else\n {\n if (remove)\n flatpak_context_remove_sockets (context, socket);\n else\n flatpak_context_add_sockets (context, socket);\n }\n }\n }\n\n if (g_key_file_has_key (metakey, FLATPAK_METADATA_GROUP_CONTEXT, FLATPAK_METADATA_KEY_DEVICES, NULL))\n {\n g_auto(GStrv) devices = g_key_file_get_string_list (metakey, FLATPAK_METADATA_GROUP_CONTEXT,\n FLATPAK_METADATA_KEY_DEVICES, NULL, error);\n if (devices == NULL)\n return FALSE;\n\n\n for (i = 0; devices[i] != NULL; i++)\n {\n FlatpakContextDevices device = flatpak_context_device_from_string (parse_negated (devices[i], &remove), NULL);\n if (device == 0)\n g_debug (\"Unknown device type %s\", devices[i]);\n else\n {\n if (remove)\n flatpak_context_remove_devices (context, device);\n else\n flatpak_context_add_devices (context, device);\n }\n }\n }\n\n if (g_key_file_has_key (metakey, FLATPAK_METADATA_GROUP_CONTEXT, FLATPAK_METADATA_KEY_FEATURES, NULL))\n {\n g_auto(GStrv) features = g_key_file_get_string_list (metakey, FLATPAK_METADATA_GROUP_CONTEXT,\n FLATPAK_METADATA_KEY_FEATURES, NULL, error);\n if (features == NULL)\n return FALSE;\n\n\n for (i = 0; features[i] != NULL; i++)\n {\n FlatpakContextFeatures feature = flatpak_context_feature_from_string (parse_negated (features[i], &remove), NULL);\n if (feature == 0)\n g_debug (\"Unknown feature type %s\", features[i]);\n else\n {\n if (remove)\n flatpak_context_remove_features (context, feature);\n else\n flatpak_context_add_features (context, feature);\n }\n }\n }\n\n if (g_key_file_has_key (metakey, FLATPAK_METADATA_GROUP_CONTEXT, FLATPAK_METADATA_KEY_FILESYSTEMS, NULL))\n {\n g_auto(GStrv) filesystems = g_key_file_get_string_list (metakey, FLATPAK_METADATA_GROUP_CONTEXT,\n FLATPAK_METADATA_KEY_FILESYSTEMS, NULL, error);\n if (filesystems == NULL)\n return FALSE;\n\n for (i = 0; filesystems[i] != NULL; i++)\n {\n const char *fs = parse_negated (filesystems[i], &remove);\n g_autofree char *filesystem = NULL;\n FlatpakFilesystemMode mode;\n\n if (!flatpak_context_parse_filesystem (fs, &filesystem, &mode, NULL))\n g_debug (\"Unknown filesystem type %s\", filesystems[i]);\n else\n {\n if (remove)\n flatpak_context_take_filesystem (context, g_steal_pointer (&filesystem),\n FLATPAK_FILESYSTEM_MODE_NONE);\n else\n flatpak_context_take_filesystem (context, g_steal_pointer (&filesystem), mode);\n }\n }\n }\n\n if (g_key_file_has_key (metakey, FLATPAK_METADATA_GROUP_CONTEXT, FLATPAK_METADATA_KEY_PERSISTENT, NULL))\n {\n g_auto(GStrv) persistent = g_key_file_get_string_list (metakey, FLATPAK_METADATA_GROUP_CONTEXT,\n FLATPAK_METADATA_KEY_PERSISTENT, NULL, error);\n if (persistent == NULL)\n return FALSE;\n\n for (i = 0; persistent[i] != NULL; i++)\n flatpak_context_set_persistent (context, persistent[i]);\n }\n\n if (g_key_file_has_group (metakey, FLATPAK_METADATA_GROUP_SESSION_BUS_POLICY))\n {\n g_auto(GStrv) keys = NULL;\n gsize keys_count;\n\n keys = g_key_file_get_keys (metakey, FLATPAK_METADATA_GROUP_SESSION_BUS_POLICY, &keys_count, NULL);\n for (i = 0; i < keys_count; i++)\n {\n const char *key = keys[i];\n g_autofree char *value = g_key_file_get_string (metakey, FLATPAK_METADATA_GROUP_SESSION_BUS_POLICY, key, NULL);\n FlatpakPolicy policy;\n\n if (!flatpak_verify_dbus_name (key, error))\n return FALSE;\n\n policy = flatpak_policy_from_string (value, NULL);\n if ((int) policy != -1)\n flatpak_context_set_session_bus_policy (context, key, policy);\n }\n }\n\n if (g_key_file_has_group (metakey, FLATPAK_METADATA_GROUP_SYSTEM_BUS_POLICY))\n {\n g_auto(GStrv) keys = NULL;\n gsize keys_count;\n\n keys = g_key_file_get_keys (metakey, FLATPAK_METADATA_GROUP_SYSTEM_BUS_POLICY, &keys_count, NULL);\n for (i = 0; i < keys_count; i++)\n {\n const char *key = keys[i];\n g_autofree char *value = g_key_file_get_string (metakey, FLATPAK_METADATA_GROUP_SYSTEM_BUS_POLICY, key, NULL);\n FlatpakPolicy policy;\n\n if (!flatpak_verify_dbus_name (key, error))\n return FALSE;\n\n policy = flatpak_policy_from_string (value, NULL);\n if ((int) policy != -1)\n flatpak_context_set_system_bus_policy (context, key, policy);\n }\n }\n\n if (g_key_file_has_group (metakey, FLATPAK_METADATA_GROUP_ENVIRONMENT))\n {\n g_auto(GStrv) keys = NULL;\n gsize keys_count;\n\n keys = g_key_file_get_keys (metakey, FLATPAK_METADATA_GROUP_ENVIRONMENT, &keys_count, NULL);\n for (i = 0; i < keys_count; i++)\n {\n const char *key = keys[i];\n g_autofree char *value = g_key_file_get_string (metakey, FLATPAK_METADATA_GROUP_ENVIRONMENT, key, NULL);\n\n flatpak_context_set_env_var (context, key, value);\n }\n }\n\n groups = g_key_file_get_groups (metakey, NULL);\n for (i = 0; groups[i] != NULL; i++)\n {\n const char *group = groups[i];\n const char *subsystem;\n int j;\n\n if (g_str_has_prefix (group, FLATPAK_METADATA_GROUP_PREFIX_POLICY))\n {\n g_auto(GStrv) keys = NULL;\n subsystem = group + strlen (FLATPAK_METADATA_GROUP_PREFIX_POLICY);\n keys = g_key_file_get_keys (metakey, group, NULL, NULL);\n for (j = 0; keys != NULL && keys[j] != NULL; j++)\n {\n const char *key = keys[j];\n g_autofree char *policy_key = g_strdup_printf (\"%s.%s\", subsystem, key);\n g_auto(GStrv) values = NULL;\n int k;\n\n values = g_key_file_get_string_list (metakey, group, key, NULL, NULL);\n for (k = 0; values != NULL && values[k] != NULL; k++)\n flatpak_context_apply_generic_policy (context, policy_key,\n values[k]);\n }\n }\n }\n\n return TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-74'], 'message': 'context: Add --unset-env option and a corresponding override\n\nThis follows up from GHSA-4ppf-fxf6-vxg2 to fix missing functionality\nthat I noticed while resolving that vulnerability, but is not required\nfor fixing the vulnerability.\n\nSigned-off-by: Simon McVittie '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: parse_args(int argc, char **argv, int *old_optind, int *nargc, char ***nargv,\n struct sudo_settings **settingsp, char ***env_addp)\n{\n struct environment extra_env;\n int mode = 0;\t\t/* what mode is sudo to be run in? */\n int flags = 0;\t\t/* mode flags */\n int valid_flags = DEFAULT_VALID_FLAGS;\n int ch, i;\n char *cp;\n const char *progname;\n int proglen;\n debug_decl(parse_args, SUDO_DEBUG_ARGS);\n\n /* Is someone trying something funny? */\n if (argc <= 0)\n\tusage();\n\n /* Pass progname to plugin so it can call initprogname() */\n progname = getprogname();\n sudo_settings[ARG_PROGNAME].value = progname;\n\n /* First, check to see if we were invoked as \"sudoedit\". */\n proglen = strlen(progname);\n if (proglen > 4 && strcmp(progname + proglen - 4, \"edit\") == 0) {\n\tprogname = \"sudoedit\";\n\tmode = MODE_EDIT;\n\tsudo_settings[ARG_SUDOEDIT].value = \"true\";\n }\n\n /* Load local IP addresses and masks. */\n if (get_net_ifs(&cp) > 0)\n\tsudo_settings[ARG_NET_ADDRS].value = cp;\n\n /* Set max_groups from sudo.conf. */\n i = sudo_conf_max_groups();\n if (i != -1) {\n\tif (asprintf(&cp, \"%d\", i) == -1)\n\t sudo_fatalx(U_(\"%s: %s\"), __func__, U_(\"unable to allocate memory\"));\n\tsudo_settings[ARG_MAX_GROUPS].value = cp;\n }\n\n /* Returns true if the last option string was \"-h\" */\n#define got_host_flag\t(optind > 1 && argv[optind - 1][0] == '-' && \\\n\t argv[optind - 1][1] == 'h' && argv[optind - 1][2] == '\\0')\n\n /* Returns true if the last option string was \"--\" */\n#define got_end_of_args\t(optind > 1 && argv[optind - 1][0] == '-' && \\\n\t argv[optind - 1][1] == '-' && argv[optind - 1][2] == '\\0')\n\n /* Returns true if next option is an environment variable */\n#define is_envar (optind < argc && argv[optind][0] != '/' && \\\n\t strchr(argv[optind], '=') != NULL)\n\n /* Space for environment variables is lazy allocated. */\n memset(&extra_env, 0, sizeof(extra_env));\n\n /* XXX - should fill in settings at the end to avoid dupes */\n for (;;) {\n\t/*\n\t * Some trickiness is required to allow environment variables\n\t * to be interspersed with command line options.\n\t */\n\tif ((ch = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {\n\t switch (ch) {\n\t\tcase 'A':\n\t\t SET(tgetpass_flags, TGP_ASKPASS);\n\t\t break;\n#ifdef HAVE_BSD_AUTH_H\n\t\tcase 'a':\n\t\t assert(optarg != NULL);\n\t\t if (*optarg == '\\0')\n\t\t\tusage();\n\t\t if (sudo_settings[ARG_BSDAUTH_TYPE].value != NULL)\n\t\t\tusage();\n\t\t sudo_settings[ARG_BSDAUTH_TYPE].value = optarg;\n\t\t break;\n#endif\n\t\tcase 'b':\n\t\t SET(flags, MODE_BACKGROUND);\n\t\t break;\n\t\tcase 'B':\n\t\t SET(tgetpass_flags, TGP_BELL);\n\t\t break;\n\t\tcase 'C':\n\t\t assert(optarg != NULL);\n\t\t if (sudo_strtonum(optarg, 3, INT_MAX, NULL) == 0) {\n\t\t\tsudo_warnx(\"%s\",\n\t\t\t U_(\"the argument to -C must be a number greater than or equal to 3\"));\n\t\t\tusage();\n\t\t }\n\t\t if (sudo_settings[ARG_CLOSEFROM].value != NULL)\n\t\t\tusage();\n\t\t sudo_settings[ARG_CLOSEFROM].value = optarg;\n\t\t break;\n#ifdef HAVE_LOGIN_CAP_H\n\t\tcase 'c':\n\t\t assert(optarg != NULL);\n\t\t if (*optarg == '\\0')\n\t\t\tusage();\n\t\t if (sudo_settings[ARG_LOGIN_CLASS].value != NULL)\n\t\t\tusage();\n\t\t sudo_settings[ARG_LOGIN_CLASS].value = optarg;\n\t\t break;\n#endif\n\t\tcase 'D':\n\t\t assert(optarg != NULL);\n\t\t if (*optarg == '\\0')\n\t\t\tusage();\n\t\t if (sudo_settings[ARG_CWD].value != NULL)\n\t\t\tusage();\n\t\t sudo_settings[ARG_CWD].value = optarg;\n\t\t break;\n\t\tcase 'E':\n\t\t /*\n\t\t * Optional argument is a comma-separated list of\n\t\t * environment variables to preserve.\n\t\t * If not present, preserve everything.\n\t\t */\n\t\t if (optarg == NULL) {\n\t\t\tsudo_settings[ARG_PRESERVE_ENVIRONMENT].value = \"true\";\n\t\t\tSET(flags, MODE_PRESERVE_ENV);\n\t\t } else {\n\t\t\tparse_env_list(&extra_env, optarg);\n\t\t }\n\t\t break;\n\t\tcase 'e':\n\t\t if (mode && mode != MODE_EDIT)\n\t\t\tusage_excl();\n\t\t mode = MODE_EDIT;\n\t\t sudo_settings[ARG_SUDOEDIT].value = \"true\";\n\t\t valid_flags = MODE_NONINTERACTIVE;\n\t\t break;\n\t\tcase 'g':\n\t\t assert(optarg != NULL);\n\t\t if (*optarg == '\\0')\n\t\t\tusage();\n\t\t if (sudo_settings[ARG_RUNAS_GROUP].value != NULL)\n\t\t\tusage();\n\t\t sudo_settings[ARG_RUNAS_GROUP].value = optarg;\n\t\t break;\n\t\tcase 'H':\n\t\t sudo_settings[ARG_SET_HOME].value = \"true\";\n\t\t break;\n\t\tcase 'h':\n\t\t if (optarg == NULL) {\n\t\t\t/*\n\t\t\t * Optional args support -hhostname, not -h hostname.\n\t\t\t * If we see a non-option after the -h flag, treat as\n\t\t\t * remote host and bump optind to skip over it.\n\t\t\t */\n\t\t\tif (got_host_flag && argv[optind] != NULL &&\n\t\t\t argv[optind][0] != '-' && !is_envar) {\n\t\t\t if (sudo_settings[ARG_REMOTE_HOST].value != NULL)\n\t\t\t\tusage();\n\t\t\t sudo_settings[ARG_REMOTE_HOST].value = argv[optind++];\n\t\t\t continue;\n\t\t\t}\n\t\t\tif (mode && mode != MODE_HELP) {\n\t\t\t if (strcmp(progname, \"sudoedit\") != 0)\n\t\t\t\tusage_excl();\n\t\t\t}\n\t\t\tmode = MODE_HELP;\n\t\t\tvalid_flags = 0;\n\t\t\tbreak;\n\t\t }\n\t\t FALLTHROUGH;\n\t\tcase OPT_HOSTNAME:\n\t\t assert(optarg != NULL);\n\t\t if (*optarg == '\\0')\n\t\t\tusage();\n\t\t if (sudo_settings[ARG_REMOTE_HOST].value != NULL)\n\t\t\tusage();\n\t\t sudo_settings[ARG_REMOTE_HOST].value = optarg;\n\t\t break;\n\t\tcase 'i':\n\t\t sudo_settings[ARG_LOGIN_SHELL].value = \"true\";\n\t\t SET(flags, MODE_LOGIN_SHELL);\n\t\t break;\n\t\tcase 'k':\n\t\t sudo_settings[ARG_IGNORE_TICKET].value = \"true\";\n\t\t break;\n\t\tcase 'K':\n\t\t sudo_settings[ARG_IGNORE_TICKET].value = \"true\";\n\t\t if (mode && mode != MODE_KILL)\n\t\t\tusage_excl();\n\t\t mode = MODE_KILL;\n\t\t valid_flags = 0;\n\t\t break;\n\t\tcase 'l':\n\t\t if (mode) {\n\t\t\tif (mode == MODE_LIST)\n\t\t\t SET(flags, MODE_LONG_LIST);\n\t\t\telse\n\t\t\t usage_excl();\n\t\t }\n\t\t mode = MODE_LIST;\n\t\t valid_flags = MODE_NONINTERACTIVE|MODE_LONG_LIST;\n\t\t break;\n\t\tcase 'n':\n\t\t SET(flags, MODE_NONINTERACTIVE);\n\t\t sudo_settings[ARG_NONINTERACTIVE].value = \"true\";\n\t\t break;\n\t\tcase 'P':\n\t\t sudo_settings[ARG_PRESERVE_GROUPS].value = \"true\";\n\t\t break;\n\t\tcase 'p':\n\t\t /* An empty prompt is allowed. */\n\t\t assert(optarg != NULL);\n\t\t if (sudo_settings[ARG_PROMPT].value != NULL)\n\t\t\tusage();\n\t\t sudo_settings[ARG_PROMPT].value = optarg;\n\t\t break;\n\t\tcase 'R':\n\t\t assert(optarg != NULL);\n\t\t if (*optarg == '\\0')\n\t\t\tusage();\n\t\t if (sudo_settings[ARG_CHROOT].value != NULL)\n\t\t\tusage();\n\t\t sudo_settings[ARG_CHROOT].value = optarg;\n\t\t break;\n#ifdef HAVE_SELINUX\n\t\tcase 'r':\n\t\t assert(optarg != NULL);\n\t\t if (*optarg == '\\0')\n\t\t\tusage();\n\t\t if (sudo_settings[ARG_SELINUX_ROLE].value != NULL)\n\t\t\tusage();\n\t\t sudo_settings[ARG_SELINUX_ROLE].value = optarg;\n\t\t break;\n\t\tcase 't':\n\t\t assert(optarg != NULL);\n\t\t if (*optarg == '\\0')\n\t\t\tusage();\n\t\t if (sudo_settings[ARG_SELINUX_TYPE].value != NULL)\n\t\t\tusage();\n\t\t sudo_settings[ARG_SELINUX_TYPE].value = optarg;\n\t\t break;\n#endif\n\t\tcase 'T':\n\t\t /* Plugin determines whether empty timeout is allowed. */\n\t\t assert(optarg != NULL);\n\t\t if (sudo_settings[ARG_TIMEOUT].value != NULL)\n\t\t\tusage();\n\t\t sudo_settings[ARG_TIMEOUT].value = optarg;\n\t\t break;\n\t\tcase 'S':\n\t\t SET(tgetpass_flags, TGP_STDIN);\n\t\t break;\n\t\tcase 's':\n\t\t sudo_settings[ARG_USER_SHELL].value = \"true\";\n\t\t SET(flags, MODE_SHELL);\n\t\t break;\n\t\tcase 'U':\n\t\t assert(optarg != NULL);\n\t\t if (list_user != NULL || *optarg == '\\0')\n\t\t\tusage();\n\t\t list_user = optarg;\n\t\t break;\n\t\tcase 'u':\n\t\t assert(optarg != NULL);\n\t\t if (*optarg == '\\0')\n\t\t\tusage();\n\t\t if (sudo_settings[ARG_RUNAS_USER].value != NULL)\n\t\t\tusage();\n\t\t sudo_settings[ARG_RUNAS_USER].value = optarg;\n\t\t break;\n\t\tcase 'v':\n\t\t if (mode && mode != MODE_VALIDATE)\n\t\t\tusage_excl();\n\t\t mode = MODE_VALIDATE;\n\t\t valid_flags = MODE_NONINTERACTIVE;\n\t\t break;\n\t\tcase 'V':\n\t\t if (mode && mode != MODE_VERSION)\n\t\t\tusage_excl();\n\t\t mode = MODE_VERSION;\n\t\t valid_flags = 0;\n\t\t break;\n\t\tdefault:\n\t\t usage();\n\t }\n\t} else if (!got_end_of_args && is_envar) {\n\t /* Insert key=value pair, crank optind and resume getopt. */\n\t env_insert(&extra_env, argv[optind]);\n\t optind++;\n\t} else {\n\t /* Not an option or an environment variable -- we're done. */\n\t break;\n\t}\n }\n\n argc -= optind;\n argv += optind;\n *old_optind = optind;\n\n if (!mode) {\n\t/* Defer -k mode setting until we know whether it is a flag or not */\n\tif (sudo_settings[ARG_IGNORE_TICKET].value != NULL) {\n\t if (argc == 0 && !(flags & (MODE_SHELL|MODE_LOGIN_SHELL))) {\n\t\tmode = MODE_INVALIDATE;\t/* -k by itself */\n\t\tsudo_settings[ARG_IGNORE_TICKET].value = NULL;\n\t\tvalid_flags = 0;\n\t }\n\t}\n\tif (!mode)\n\t mode = MODE_RUN;\t\t/* running a command */\n }\n\n if (argc > 0 && mode == MODE_LIST)\n\tmode = MODE_CHECK;\n\n if (ISSET(flags, MODE_LOGIN_SHELL)) {\n\tif (ISSET(flags, MODE_SHELL)) {\n\t sudo_warnx(\"%s\",\n\t\tU_(\"you may not specify both the -i and -s options\"));\n\t usage();\n\t}\n\tif (ISSET(flags, MODE_PRESERVE_ENV)) {\n\t sudo_warnx(\"%s\",\n\t\tU_(\"you may not specify both the -i and -E options\"));\n\t usage();\n\t}\n\tSET(flags, MODE_SHELL);\n }\n if ((flags & valid_flags) != flags)\n\tusage();\n if (mode == MODE_EDIT &&\n (ISSET(flags, MODE_PRESERVE_ENV) || extra_env.env_len != 0)) {\n\tif (ISSET(mode, MODE_PRESERVE_ENV))\n\t sudo_warnx(\"%s\", U_(\"the -E option is not valid in edit mode\"));\n\tif (extra_env.env_len != 0)\n\t sudo_warnx(\"%s\",\n\t\tU_(\"you may not specify environment variables in edit mode\"));\n\tusage();\n }\n if ((sudo_settings[ARG_RUNAS_USER].value != NULL ||\n\t sudo_settings[ARG_RUNAS_GROUP].value != NULL) &&\n\t!ISSET(mode, MODE_EDIT | MODE_RUN | MODE_CHECK | MODE_VALIDATE)) {\n\tusage();\n }\n if (list_user != NULL && mode != MODE_LIST && mode != MODE_CHECK) {\n\tsudo_warnx(\"%s\",\n\t U_(\"the -U option may only be used with the -l option\"));\n\tusage();\n }\n if (ISSET(tgetpass_flags, TGP_STDIN) && ISSET(tgetpass_flags, TGP_ASKPASS)) {\n\tsudo_warnx(\"%s\", U_(\"the -A and -S options may not be used together\"));\n\tusage();\n }\n if ((argc == 0 && mode == MODE_EDIT) ||\n\t(argc > 0 && !ISSET(mode, MODE_RUN | MODE_EDIT | MODE_CHECK)))\n\tusage();\n if (argc == 0 && mode == MODE_RUN && !ISSET(flags, MODE_SHELL)) {\n\tSET(flags, (MODE_IMPLIED_SHELL | MODE_SHELL));\n\tsudo_settings[ARG_IMPLIED_SHELL].value = \"true\";\n }\n#ifdef ENABLE_SUDO_PLUGIN_API\n sudo_settings[ARG_PLUGIN_DIR].value = sudo_conf_plugin_dir_path();\n#endif\n\n if (mode == MODE_HELP)\n\thelp();\n\n /*\n * For shell mode we need to rewrite argv\n */\n if (ISSET(mode, MODE_RUN) && ISSET(flags, MODE_SHELL)) {\n\tchar **av, *cmnd = NULL;\n\tint ac = 1;\n\n\tif (argc != 0) {\n\t /* shell -c \"command\" */\n\t char *src, *dst;\n\t size_t cmnd_size = (size_t) (argv[argc - 1] - argv[0]) +\n\t\tstrlen(argv[argc - 1]) + 1;\n\n\t cmnd = dst = reallocarray(NULL, cmnd_size, 2);\n\t if (cmnd == NULL)\n\t\tsudo_fatalx(U_(\"%s: %s\"), __func__, U_(\"unable to allocate memory\"));\n\t if (!gc_add(GC_PTR, cmnd))\n\t\texit(EXIT_FAILURE);\n\n\t for (av = argv; *av != NULL; av++) {\n\t\tfor (src = *av; *src != '\\0'; src++) {\n\t\t /* quote potential meta characters */\n\t\t if (!isalnum((unsigned char)*src) && *src != '_' && *src != '-' && *src != '$')\n\t\t\t*dst++ = '\\\\';\n\t\t *dst++ = *src;\n\t\t}\n\t\t*dst++ = ' ';\n\t }\n\t if (cmnd != dst)\n\t\tdst--; /* replace last space with a NUL */\n\t *dst = '\\0';\n\n\t ac += 2; /* -c cmnd */\n\t}\n\n\tav = reallocarray(NULL, ac + 1, sizeof(char *));\n\tif (av == NULL)\n\t sudo_fatalx(U_(\"%s: %s\"), __func__, U_(\"unable to allocate memory\"));\n\tif (!gc_add(GC_PTR, av))\n\t exit(EXIT_FAILURE);\n\n\tav[0] = (char *)user_details.shell; /* plugin may override shell */\n\tif (cmnd != NULL) {\n\t av[1] = \"-c\";\n\t av[2] = cmnd;\n\t}\n\tav[ac] = NULL;\n\n\targv = av;\n\targc = ac;\n }\n\n /*\n * For sudoedit we need to rewrite argv\n */\n if (mode == MODE_EDIT) {\n#if defined(HAVE_SETRESUID) || defined(HAVE_SETREUID) || defined(HAVE_SETEUID)\n\tchar **av;\n\tint ac;\n\n\tav = reallocarray(NULL, argc + 2, sizeof(char *));\n\tif (av == NULL)\n\t sudo_fatalx(U_(\"%s: %s\"), __func__, U_(\"unable to allocate memory\"));\n\tif (!gc_add(GC_PTR, av))\n\t exit(EXIT_FAILURE);\n\n\t/* Must have the command in argv[0]. */\n\tav[0] = \"sudoedit\";\n\tfor (ac = 0; argv[ac] != NULL; ac++) {\n\t av[ac + 1] = argv[ac];\n\t}\n\tav[++ac] = NULL;\n\n\targv = av;\n\targc = ac;\n#else\n\tsudo_fatalx(\"%s\", U_(\"sudoedit is not supported on this platform\"));\n#endif\n }\n\n *settingsp = sudo_settings;\n *env_addp = extra_env.envp;\n *nargc = argc;\n *nargv = argv;\n debug_return_int(mode | flags);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-193'], 'message': 'Reset valid_flags to MODE_NONINTERACTIVE for sudoedit.\nThis is consistent with how the -e option is handled.\nAlso reject -H and -P flags for sudoedit as was done in sudo 1.7.\nFound by Qualys, this is part of the fix for CVE-2021-3156.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int uvc_scan_chain_backward(struct uvc_video_chain *chain,\n\tstruct uvc_entity **_entity)\n{\n\tstruct uvc_entity *entity = *_entity;\n\tstruct uvc_entity *term;\n\tint id = -EINVAL, i;\n\n\tswitch (UVC_ENTITY_TYPE(entity)) {\n\tcase UVC_VC_EXTENSION_UNIT:\n\tcase UVC_VC_PROCESSING_UNIT:\n\t\tid = entity->baSourceID[0];\n\t\tbreak;\n\n\tcase UVC_VC_SELECTOR_UNIT:\n\t\t/* Single-input selector units are ignored. */\n\t\tif (entity->bNrInPins == 1) {\n\t\t\tid = entity->baSourceID[0];\n\t\t\tbreak;\n\t\t}\n\n\t\tif (uvc_trace_param & UVC_TRACE_PROBE)\n\t\t\tprintk(KERN_CONT \" <- IT\");\n\n\t\tchain->selector = entity;\n\t\tfor (i = 0; i < entity->bNrInPins; ++i) {\n\t\t\tid = entity->baSourceID[i];\n\t\t\tterm = uvc_entity_by_id(chain->dev, id);\n\t\t\tif (term == NULL || !UVC_ENTITY_IS_ITERM(term)) {\n\t\t\t\tuvc_trace(UVC_TRACE_DESCR, \"Selector unit %d \"\n\t\t\t\t\t\"input %d isn't connected to an \"\n\t\t\t\t\t\"input terminal\\n\", entity->id, i);\n\t\t\t\treturn -1;\n\t\t\t}\n\n\t\t\tif (uvc_trace_param & UVC_TRACE_PROBE)\n\t\t\t\tprintk(KERN_CONT \" %d\", term->id);\n\n\t\t\tlist_add_tail(&term->chain, &chain->entities);\n\t\t\tuvc_scan_chain_forward(chain, term, entity);\n\t\t}\n\n\t\tif (uvc_trace_param & UVC_TRACE_PROBE)\n\t\t\tprintk(KERN_CONT \"\\n\");\n\n\t\tid = 0;\n\t\tbreak;\n\n\tcase UVC_ITT_VENDOR_SPECIFIC:\n\tcase UVC_ITT_CAMERA:\n\tcase UVC_ITT_MEDIA_TRANSPORT_INPUT:\n\tcase UVC_OTT_VENDOR_SPECIFIC:\n\tcase UVC_OTT_DISPLAY:\n\tcase UVC_OTT_MEDIA_TRANSPORT_OUTPUT:\n\tcase UVC_TT_STREAMING:\n\t\tid = UVC_ENTITY_IS_OTERM(entity) ? entity->baSourceID[0] : 0;\n\t\tbreak;\n\t}\n\n\tif (id <= 0) {\n\t\t*_entity = NULL;\n\t\treturn id;\n\t}\n\n\tentity = uvc_entity_by_id(chain->dev, id);\n\tif (entity == NULL) {\n\t\tuvc_trace(UVC_TRACE_DESCR, \"Found reference to \"\n\t\t\t\"unknown entity %d.\\n\", id);\n\t\treturn -EINVAL;\n\t}\n\n\t*_entity = entity;\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-269'], 'message': 'media: uvcvideo: Avoid cyclic entity chains due to malformed USB descriptors\n\nWay back in 2017, fuzzing the 4.14-rc2 USB stack with syzkaller kicked\nup the following WARNING from the UVC chain scanning code:\n\n | list_add double add: new=ffff880069084010, prev=ffff880069084010,\n | next=ffff880067d22298.\n | ------------[ cut here ]------------\n | WARNING: CPU: 1 PID: 1846 at lib/list_debug.c:31 __list_add_valid+0xbd/0xf0\n | Modules linked in:\n | CPU: 1 PID: 1846 Comm: kworker/1:2 Not tainted\n | 4.14.0-rc2-42613-g1488251d1a98 #238\n | Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011\n | Workqueue: usb_hub_wq hub_event\n | task: ffff88006b01ca40 task.stack: ffff880064358000\n | RIP: 0010:__list_add_valid+0xbd/0xf0 lib/list_debug.c:29\n | RSP: 0018:ffff88006435ddd0 EFLAGS: 00010286\n | RAX: 0000000000000058 RBX: ffff880067d22298 RCX: 0000000000000000\n | RDX: 0000000000000058 RSI: ffffffff85a58800 RDI: ffffed000c86bbac\n | RBP: ffff88006435dde8 R08: 1ffff1000c86ba52 R09: 0000000000000000\n | R10: 0000000000000002 R11: 0000000000000000 R12: ffff880069084010\n | R13: ffff880067d22298 R14: ffff880069084010 R15: ffff880067d222a0\n | FS: 0000000000000000(0000) GS:ffff88006c900000(0000) knlGS:0000000000000000\n | CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033\n | CR2: 0000000020004ff2 CR3: 000000006b447000 CR4: 00000000000006e0\n | Call Trace:\n | __list_add ./include/linux/list.h:59\n | list_add_tail+0x8c/0x1b0 ./include/linux/list.h:92\n | uvc_scan_chain_forward.isra.8+0x373/0x416\n | drivers/media/usb/uvc/uvc_driver.c:1471\n | uvc_scan_chain drivers/media/usb/uvc/uvc_driver.c:1585\n | uvc_scan_device drivers/media/usb/uvc/uvc_driver.c:1769\n | uvc_probe+0x77f2/0x8f00 drivers/media/usb/uvc/uvc_driver.c:2104\n\nLooking into the output from usbmon, the interesting part is the\nfollowing data packet:\n\n ffff880069c63e00 30710169 C Ci:1:002:0 0 143 = 09028f00 01030080\n 00090403 00000e01 00000924 03000103 7c003328 010204db\n\nIf we drop the lead configuration and interface descriptors, we're left\nwith an output terminal descriptor describing a generic display:\n\n /* Output terminal descriptor */\n buf[0]\t09\n buf[1]\t24\n buf[2]\t03\t/* UVC_VC_OUTPUT_TERMINAL */\n buf[3]\t00\t/* ID */\n buf[4]\t01\t/* type == 0x0301 (UVC_OTT_DISPLAY) */\n buf[5]\t03\n buf[6]\t7c\n buf[7]\t00\t/* source ID refers to self! */\n buf[8]\t33\n\nThe problem with this descriptor is that it is self-referential: the\nsource ID of 0 matches itself! This causes the 'struct uvc_entity'\nrepresenting the display to be added to its chain list twice during\n'uvc_scan_chain()': once via 'uvc_scan_chain_entity()' when it is\nprocessed directly from the 'dev->entities' list and then again\nimmediately afterwards when trying to follow the source ID in\n'uvc_scan_chain_forward()'\n\nAdd a check before adding an entity to a chain list to ensure that the\nentity is not already part of a chain.\n\nLink: https://lore.kernel.org/linux-media/CAAeHK+z+Si69jUR+N-SjN9q4O+o5KFiNManqEa-PjUta7EOb7A@mail.gmail.com/\n\nCc: \nFixes: c0efd232929c (\"V4L/DVB (8145a): USB Video Class driver\")\nReported-by: Andrey Konovalov \nSigned-off-by: Will Deacon \nSigned-off-by: Laurent Pinchart \nSigned-off-by: Mauro Carvalho Chehab '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: decompress_lz4(tvbuff_t *tvb _U_, packet_info *pinfo, int offset _U_, guint32 length _U_, tvbuff_t **decompressed_tvb _U_, int *decompressed_offset _U_)\n{\n col_append_str(pinfo->cinfo, COL_INFO, \" [lz4 decompression unsupported]\");\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'Kafka: Limit our decompression size.\n\nDon't assume that the Internet has our best interests at heart when it\ngives us the size of our decompression buffer. Assign an arbitrary limit\nof 50 MB.\n\nThis fixes #16739 in that it takes care of\n\n** (process:17681): WARNING **: 20:03:07.440: Dissector bug, protocol Kafka, in packet 31: ../epan/proto.c:7043: failed assertion \"end >= fi->start\"\n\nwhich is different from the original error output. It looks like *that*\nmight have taken care of in one of the other recent Kafka bug fixes.\n\nThe decompression routines return a success or failure status. Use\ngbooleans instead of ints for that.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static gboolean compare_by_coherent_set_key(gconstpointer a, gconstpointer b) {\n const coherent_set_key * guid_a = (const coherent_set_key *)a;\n const coherent_set_key * guid_b = (const coherent_set_key *)b;\n return memcmp(guid_a, guid_b, sizeof(coherent_set_key)) == 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'RTPS: Fixup our coherent set map.\n\ncoherent_set_tracking.coherent_set_registry_map uses a struct as a key,\nbut the hash and comparison routines treat keys as a sequence of bytes.\nMake sure every key byte is initialized. Fixes #16994.\n\nCall wmem_strong_hash on our key in coherent_set_key_hash_by_key instead\nof creating and leaking a GBytes struct.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int mt_touch_input_mapping(struct hid_device *hdev, struct hid_input *hi,\n\t\tstruct hid_field *field, struct hid_usage *usage,\n\t\tunsigned long **bit, int *max, struct mt_application *app)\n{\n\tstruct mt_device *td = hid_get_drvdata(hdev);\n\tstruct mt_class *cls = &td->mtclass;\n\tint code;\n\tstruct hid_usage *prev_usage = NULL;\n\n\t/*\n\t * Model touchscreens providing buttons as touchpads.\n\t */\n\tif (field->application == HID_DG_TOUCHSCREEN &&\n\t (usage->hid & HID_USAGE_PAGE) == HID_UP_BUTTON) {\n\t\tapp->mt_flags |= INPUT_MT_POINTER;\n\t\ttd->inputmode_value = MT_INPUTMODE_TOUCHPAD;\n\t}\n\n\t/* count the buttons on touchpads */\n\tif ((usage->hid & HID_USAGE_PAGE) == HID_UP_BUTTON)\n\t\tapp->buttons_count++;\n\n\tif (usage->usage_index)\n\t\tprev_usage = &field->usage[usage->usage_index - 1];\n\n\tswitch (usage->hid & HID_USAGE_PAGE) {\n\n\tcase HID_UP_GENDESK:\n\t\tswitch (usage->hid) {\n\t\tcase HID_GD_X:\n\t\t\tif (prev_usage && (prev_usage->hid == usage->hid)) {\n\t\t\t\tcode = ABS_MT_TOOL_X;\n\t\t\t\tMT_STORE_FIELD(cx);\n\t\t\t} else {\n\t\t\t\tcode = ABS_MT_POSITION_X;\n\t\t\t\tMT_STORE_FIELD(x);\n\t\t\t}\n\n\t\t\tset_abs(hi->input, code, field, cls->sn_move);\n\n\t\t\t/*\n\t\t\t * A system multi-axis that exports X and Y has a high\n\t\t\t * chance of being used directly on a surface\n\t\t\t */\n\t\t\tif (field->application == HID_GD_SYSTEM_MULTIAXIS) {\n\t\t\t\t__set_bit(INPUT_PROP_DIRECT,\n\t\t\t\t\t hi->input->propbit);\n\t\t\t\tinput_set_abs_params(hi->input,\n\t\t\t\t\t\t ABS_MT_TOOL_TYPE,\n\t\t\t\t\t\t MT_TOOL_DIAL,\n\t\t\t\t\t\t MT_TOOL_DIAL, 0, 0);\n\t\t\t}\n\n\t\t\treturn 1;\n\t\tcase HID_GD_Y:\n\t\t\tif (prev_usage && (prev_usage->hid == usage->hid)) {\n\t\t\t\tcode = ABS_MT_TOOL_Y;\n\t\t\t\tMT_STORE_FIELD(cy);\n\t\t\t} else {\n\t\t\t\tcode = ABS_MT_POSITION_Y;\n\t\t\t\tMT_STORE_FIELD(y);\n\t\t\t}\n\n\t\t\tset_abs(hi->input, code, field, cls->sn_move);\n\n\t\t\treturn 1;\n\t\t}\n\t\treturn 0;\n\n\tcase HID_UP_DIGITIZER:\n\t\tswitch (usage->hid) {\n\t\tcase HID_DG_INRANGE:\n\t\t\tif (app->quirks & MT_QUIRK_HOVERING) {\n\t\t\t\tinput_set_abs_params(hi->input,\n\t\t\t\t\tABS_MT_DISTANCE, 0, 1, 0, 0);\n\t\t\t}\n\t\t\tMT_STORE_FIELD(inrange_state);\n\t\t\treturn 1;\n\t\tcase HID_DG_CONFIDENCE:\n\t\t\tif (cls->name == MT_CLS_WIN_8 &&\n\t\t\t\t(field->application == HID_DG_TOUCHPAD ||\n\t\t\t\t field->application == HID_DG_TOUCHSCREEN))\n\t\t\t\tapp->quirks |= MT_QUIRK_CONFIDENCE;\n\n\t\t\tif (app->quirks & MT_QUIRK_CONFIDENCE)\n\t\t\t\tinput_set_abs_params(hi->input,\n\t\t\t\t\t\t ABS_MT_TOOL_TYPE,\n\t\t\t\t\t\t MT_TOOL_FINGER,\n\t\t\t\t\t\t MT_TOOL_PALM, 0, 0);\n\n\t\t\tMT_STORE_FIELD(confidence_state);\n\t\t\treturn 1;\n\t\tcase HID_DG_TIPSWITCH:\n\t\t\tif (field->application != HID_GD_SYSTEM_MULTIAXIS)\n\t\t\t\tinput_set_capability(hi->input,\n\t\t\t\t\t\t EV_KEY, BTN_TOUCH);\n\t\t\tMT_STORE_FIELD(tip_state);\n\t\t\treturn 1;\n\t\tcase HID_DG_CONTACTID:\n\t\t\tMT_STORE_FIELD(contactid);\n\t\t\tapp->touches_by_report++;\n\t\t\treturn 1;\n\t\tcase HID_DG_WIDTH:\n\t\t\tif (!(app->quirks & MT_QUIRK_NO_AREA))\n\t\t\t\tset_abs(hi->input, ABS_MT_TOUCH_MAJOR, field,\n\t\t\t\t\tcls->sn_width);\n\t\t\tMT_STORE_FIELD(w);\n\t\t\treturn 1;\n\t\tcase HID_DG_HEIGHT:\n\t\t\tif (!(app->quirks & MT_QUIRK_NO_AREA)) {\n\t\t\t\tset_abs(hi->input, ABS_MT_TOUCH_MINOR, field,\n\t\t\t\t\tcls->sn_height);\n\n\t\t\t\t/*\n\t\t\t\t * Only set ABS_MT_ORIENTATION if it is not\n\t\t\t\t * already set by the HID_DG_AZIMUTH usage.\n\t\t\t\t */\n\t\t\t\tif (!test_bit(ABS_MT_ORIENTATION,\n\t\t\t\t\t\thi->input->absbit))\n\t\t\t\t\tinput_set_abs_params(hi->input,\n\t\t\t\t\t\tABS_MT_ORIENTATION, 0, 1, 0, 0);\n\t\t\t}\n\t\t\tMT_STORE_FIELD(h);\n\t\t\treturn 1;\n\t\tcase HID_DG_TIPPRESSURE:\n\t\t\tset_abs(hi->input, ABS_MT_PRESSURE, field,\n\t\t\t\tcls->sn_pressure);\n\t\t\tMT_STORE_FIELD(p);\n\t\t\treturn 1;\n\t\tcase HID_DG_SCANTIME:\n\t\t\tinput_set_capability(hi->input, EV_MSC, MSC_TIMESTAMP);\n\t\t\tapp->scantime = &field->value[usage->usage_index];\n\t\t\tapp->scantime_logical_max = field->logical_maximum;\n\t\t\treturn 1;\n\t\tcase HID_DG_CONTACTCOUNT:\n\t\t\tapp->have_contact_count = true;\n\t\t\tapp->raw_cc = &field->value[usage->usage_index];\n\t\t\treturn 1;\n\t\tcase HID_DG_AZIMUTH:\n\t\t\t/*\n\t\t\t * Azimuth has the range of [0, MAX) representing a full\n\t\t\t * revolution. Set ABS_MT_ORIENTATION to a quarter of\n\t\t\t * MAX according the definition of ABS_MT_ORIENTATION\n\t\t\t */\n\t\t\tinput_set_abs_params(hi->input, ABS_MT_ORIENTATION,\n\t\t\t\t-field->logical_maximum / 4,\n\t\t\t\tfield->logical_maximum / 4,\n\t\t\t\tcls->sn_move ?\n\t\t\t\tfield->logical_maximum / cls->sn_move : 0, 0);\n\t\t\tMT_STORE_FIELD(a);\n\t\t\treturn 1;\n\t\tcase HID_DG_CONTACTMAX:\n\t\t\t/* contact max are global to the report */\n\t\t\treturn -1;\n\t\tcase HID_DG_TOUCH:\n\t\t\t/* Legacy devices use TIPSWITCH and not TOUCH.\n\t\t\t * Let's just ignore this field. */\n\t\t\treturn -1;\n\t\t}\n\t\t/* let hid-input decide for the others */\n\t\treturn 0;\n\n\tcase HID_UP_BUTTON:\n\t\tcode = BTN_MOUSE + ((usage->hid - 1) & HID_USAGE);\n\t\t/*\n\t\t * MS PTP spec says that external buttons left and right have\n\t\t * usages 2 and 3.\n\t\t */\n\t\tif ((app->quirks & MT_QUIRK_WIN8_PTP_BUTTONS) &&\n\t\t field->application == HID_DG_TOUCHPAD &&\n\t\t (usage->hid & HID_USAGE) > 1)\n\t\t\tcode--;\n\n\t\tif (field->application == HID_GD_SYSTEM_MULTIAXIS)\n\t\t\tcode = BTN_0 + ((usage->hid - 1) & HID_USAGE);\n\n\t\thid_map_usage(hi, usage, bit, max, EV_KEY, code);\n\t\tinput_set_capability(hi->input, EV_KEY, code);\n\t\treturn 1;\n\n\tcase 0xff000000:\n\t\t/* we do not want to map these: no input-oriented meaning */\n\t\treturn -1;\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'HID: core: Sanitize event code and type when mapping input\n\nWhen calling into hid_map_usage(), the passed event code is\nblindly stored as is, even if it doesn't fit in the associated bitmap.\n\nThis event code can come from a variety of sources, including devices\nmasquerading as input devices, only a bit more \"programmable\".\n\nInstead of taking the event code at face value, check that it actually\nfits the corresponding bitmap, and if it doesn't:\n- spit out a warning so that we know which device is acting up\n- NULLify the bitmap pointer so that we catch unexpected uses\n\nCode paths that can make use of untrusted inputs can now check\nthat the mapping was indeed correct and bail out if not.\n\nCc: stable@vger.kernel.org\nSigned-off-by: Marc Zyngier \nSigned-off-by: Benjamin Tissoires '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: authzValidate(\n\tSyntax *syntax,\n\tstruct berval *in )\n{\n\tstruct berval\tbv;\n\tint\t\trc = LDAP_INVALID_SYNTAX;\n\tLDAPURLDesc\t*ludp = NULL;\n\tint\t\tscope = -1;\n\n\t/*\n\t * 1) \n\t * 2) dn[.{exact|children|subtree|onelevel}]:{*|}\n\t * 3) dn.regex:\n\t * 4) u[.mech[/realm]]:\n\t * 5) group[/[/]]:\n\t * 6) \n\t */\n\n\tassert( in != NULL );\n\tassert( !BER_BVISNULL( in ) );\n\n\tDebug( LDAP_DEBUG_TRACE,\n\t\t\"authzValidate: parsing %s\\n\", in->bv_val, 0, 0 );\n\n\t/*\n\t * 2) dn[.{exact|children|subtree|onelevel}]:{*|}\n\t * 3) dn.regex:\n\t *\n\t * must pass DN normalization\n\t */\n\tif ( !strncasecmp( in->bv_val, \"dn\", STRLENOF( \"dn\" ) ) ) {\n\t\tbv.bv_val = in->bv_val + STRLENOF( \"dn\" );\n\n\t\tif ( bv.bv_val[ 0 ] == '.' ) {\n\t\t\tbv.bv_val++;\n\n\t\t\tif ( !strncasecmp( bv.bv_val, \"exact:\", STRLENOF( \"exact:\" ) ) ) {\n\t\t\t\tbv.bv_val += STRLENOF( \"exact:\" );\n\t\t\t\tscope = LDAP_X_SCOPE_EXACT;\n\n\t\t\t} else if ( !strncasecmp( bv.bv_val, \"regex:\", STRLENOF( \"regex:\" ) ) ) {\n\t\t\t\tbv.bv_val += STRLENOF( \"regex:\" );\n\t\t\t\tscope = LDAP_X_SCOPE_REGEX;\n\n\t\t\t} else if ( !strncasecmp( bv.bv_val, \"children:\", STRLENOF( \"children:\" ) ) ) {\n\t\t\t\tbv.bv_val += STRLENOF( \"children:\" );\n\t\t\t\tscope = LDAP_X_SCOPE_CHILDREN;\n\n\t\t\t} else if ( !strncasecmp( bv.bv_val, \"subtree:\", STRLENOF( \"subtree:\" ) ) ) {\n\t\t\t\tbv.bv_val += STRLENOF( \"subtree:\" );\n\t\t\t\tscope = LDAP_X_SCOPE_SUBTREE;\n\n\t\t\t} else if ( !strncasecmp( bv.bv_val, \"onelevel:\", STRLENOF( \"onelevel:\" ) ) ) {\n\t\t\t\tbv.bv_val += STRLENOF( \"onelevel:\" );\n\t\t\t\tscope = LDAP_X_SCOPE_ONELEVEL;\n\n\t\t\t} else {\n\t\t\t\treturn LDAP_INVALID_SYNTAX;\n\t\t\t}\n\n\t\t} else {\n\t\t\tif ( bv.bv_val[ 0 ] != ':' ) {\n\t\t\t\treturn LDAP_INVALID_SYNTAX;\n\t\t\t}\n\t\t\tscope = LDAP_X_SCOPE_EXACT;\n\t\t\tbv.bv_val++;\n\t\t}\n\n\t\tbv.bv_val += strspn( bv.bv_val, \" \" );\n\t\t/* jump here in case no type specification was present\n\t\t * and uri was not an URI... HEADS-UP: assuming EXACT */\nis_dn:\t\tbv.bv_len = in->bv_len - ( bv.bv_val - in->bv_val );\n\n\t\t/* a single '*' means any DN without using regexes */\n\t\tif ( ber_bvccmp( &bv, '*' ) ) {\n\t\t\t/* LDAP_X_SCOPE_USERS */\n\t\t\treturn LDAP_SUCCESS;\n\t\t}\n\n\t\tswitch ( scope ) {\n\t\tcase LDAP_X_SCOPE_EXACT:\n\t\tcase LDAP_X_SCOPE_CHILDREN:\n\t\tcase LDAP_X_SCOPE_SUBTREE:\n\t\tcase LDAP_X_SCOPE_ONELEVEL:\n\t\t\treturn dnValidate( NULL, &bv );\n\n\t\tcase LDAP_X_SCOPE_REGEX:\n\t\t\treturn LDAP_SUCCESS;\n\t\t}\n\n\t\treturn rc;\n\n\t/*\n\t * 4) u[.mech[/realm]]:\n\t */\n\t} else if ( ( in->bv_val[ 0 ] == 'u' || in->bv_val[ 0 ] == 'U' )\n\t\t\t&& ( in->bv_val[ 1 ] == ':' \n\t\t\t\t|| in->bv_val[ 1 ] == '/' \n\t\t\t\t|| in->bv_val[ 1 ] == '.' ) )\n\t{\n\t\tchar\t\tbuf[ SLAP_LDAPDN_MAXLEN ];\n\t\tstruct berval\tid,\n\t\t\t\tuser = BER_BVNULL,\n\t\t\t\trealm = BER_BVNULL,\n\t\t\t\tmech = BER_BVNULL;\n\n\t\tif ( sizeof( buf ) <= in->bv_len ) {\n\t\t\treturn LDAP_INVALID_SYNTAX;\n\t\t}\n\n\t\tid.bv_len = in->bv_len;\n\t\tid.bv_val = buf;\n\t\tstrncpy( buf, in->bv_val, sizeof( buf ) );\n\n\t\trc = slap_parse_user( &id, &user, &realm, &mech );\n\t\tif ( rc != LDAP_SUCCESS ) {\n\t\t\treturn LDAP_INVALID_SYNTAX;\n\t\t}\n\n\t\treturn rc;\n\n\t/*\n\t * 5) group[/groupClass[/memberAttr]]:\n\t *\n\t * defaults to \"groupOfNames\"\n\t * defaults to \"member\"\n\t * \n\t * must pass DN normalization\n\t */\n\t} else if ( strncasecmp( in->bv_val, \"group\", STRLENOF( \"group\" ) ) == 0 )\n\t{\n\t\tstruct berval\tgroup_dn = BER_BVNULL,\n\t\t\t\tgroup_oc = BER_BVNULL,\n\t\t\t\tmember_at = BER_BVNULL;\n\n\t\tbv.bv_val = in->bv_val + STRLENOF( \"group\" );\n\t\tbv.bv_len = in->bv_len - STRLENOF( \"group\" );\n\t\tgroup_dn.bv_val = ber_bvchr( &bv, ':' );\n\t\tif ( group_dn.bv_val == NULL ) {\n\t\t\t/* last chance: assume it's a(n exact) DN ... */\n\t\t\tbv.bv_val = in->bv_val;\n\t\t\tscope = LDAP_X_SCOPE_EXACT;\n\t\t\tgoto is_dn;\n\t\t}\n\t\t\n\t\t/*\n\t\t * FIXME: we assume that \"member\" and \"groupOfNames\"\n\t\t * are present in schema...\n\t\t */\n\t\tif ( bv.bv_val[ 0 ] == '/' ) {\n\t\t\tgroup_oc.bv_val = &bv.bv_val[ 1 ];\n\t\t\tgroup_oc.bv_len = group_dn.bv_val - group_oc.bv_val;\n\n\t\t\tmember_at.bv_val = ber_bvchr( &group_oc, '/' );\n\t\t\tif ( member_at.bv_val ) {\n\t\t\t\tAttributeDescription\t*ad = NULL;\n\t\t\t\tconst char\t\t*text = NULL;\n\n\t\t\t\tgroup_oc.bv_len = member_at.bv_val - group_oc.bv_val;\n\t\t\t\tmember_at.bv_val++;\n\t\t\t\tmember_at.bv_len = group_dn.bv_val - member_at.bv_val;\n\t\t\t\trc = slap_bv2ad( &member_at, &ad, &text );\n\t\t\t\tif ( rc != LDAP_SUCCESS ) {\n\t\t\t\t\treturn rc;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ( oc_bvfind( &group_oc ) == NULL ) {\n\t\t\t\treturn LDAP_INVALID_SYNTAX;\n\t\t\t}\n\t\t}\n\n\t\tgroup_dn.bv_val++;\n\t\tgroup_dn.bv_len = in->bv_len - ( group_dn.bv_val - in->bv_val );\n\n\t\trc = dnValidate( NULL, &group_dn );\n\t\tif ( rc != LDAP_SUCCESS ) {\n\t\t\treturn rc;\n\t\t}\n\n\t\treturn rc;\n\t}\n\n\t/*\n\t * ldap:///???\n\t * ::= {base|one|subtree}\n\t *\n\t * defaults to \"base\"\n\t * must pass DN normalization\n\t * must pass str2filter()\n\t */\n\trc = ldap_url_parse( in->bv_val, &ludp );\n\tswitch ( rc ) {\n\tcase LDAP_URL_SUCCESS:\n\t\t/* FIXME: the check is pedantic, but I think it's necessary,\n\t\t * because people tend to use things like ldaps:// which\n\t\t * gives the idea SSL is being used. Maybe we could\n\t\t * accept ldapi:// as well, but the point is that we use\n\t\t * an URL as an easy means to define bits of a search with\n\t\t * little parsing.\n\t\t */\n\t\tif ( strcasecmp( ludp->lud_scheme, \"ldap\" ) != 0 ) {\n\t\t\t/*\n\t\t\t * must be ldap:///\n\t\t\t */\n\t\t\trc = LDAP_INVALID_SYNTAX;\n\t\t\tgoto done;\n\t\t}\n\t\tbreak;\n\n\tcase LDAP_URL_ERR_BADSCHEME:\n\t\t/*\n\t\t * last chance: assume it's a(n exact) DN ...\n\t\t *\n\t\t * NOTE: must pass DN normalization\n\t\t */\n\t\tldap_free_urldesc( ludp );\n\t\tbv.bv_val = in->bv_val;\n\t\tscope = LDAP_X_SCOPE_EXACT;\n\t\tgoto is_dn;\n\n\tdefault:\n\t\trc = LDAP_INVALID_SYNTAX;\n\t\tgoto done;\n\t}\n\n\tif ( ( ludp->lud_host && *ludp->lud_host )\n\t\t|| ludp->lud_attrs || ludp->lud_exts )\n\t{\n\t\t/* host part must be empty */\n\t\t/* attrs and extensions parts must be empty */\n\t\trc = LDAP_INVALID_SYNTAX;\n\t\tgoto done;\n\t}\n\n\t/* Grab the filter */\n\tif ( ludp->lud_filter ) {\n\t\tFilter\t*f = str2filter( ludp->lud_filter );\n\t\tif ( f == NULL ) {\n\t\t\trc = LDAP_INVALID_SYNTAX;\n\t\t\tgoto done;\n\t\t}\n\t\tfilter_free( f );\n\t}\n\n\t/* Grab the searchbase */\n\tassert( ludp->lud_dn != NULL );\n\tber_str2bv( ludp->lud_dn, 0, 0, &bv );\n\trc = dnValidate( NULL, &bv );\n\ndone:\n\tldap_free_urldesc( ludp );\n\treturn( rc );\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617'], 'message': 'ITS#9406, #9407 remove saslauthz asserts'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ldap_X509dn2bv( void *x509_name, struct berval *bv, LDAPDN_rewrite_func *func,\n\tunsigned flags )\n{\n\tLDAPDN\tnewDN;\n\tLDAPRDN\tnewRDN;\n\tLDAPAVA *newAVA, *baseAVA;\n\tBerElementBuffer berbuf;\n\tBerElement *ber = (BerElement *)&berbuf;\n\tchar oids[8192], *oidptr = oids, *oidbuf = NULL;\n\tvoid *ptrs[2048];\n\tchar *dn_end, *rdn_end;\n\tint i, navas, nrdns, rc = LDAP_SUCCESS;\n\tsize_t dnsize, oidrem = sizeof(oids), oidsize = 0;\n\tint csize;\n\tber_tag_t tag;\n\tber_len_t len;\n\toid_name *oidname;\n\n\tstruct berval\tOid, Val, oid2, *in = x509_name;\n\n\tassert( bv != NULL );\n\n\tbv->bv_len = 0;\n\tbv->bv_val = NULL;\n\n\tnavas = 0;\n\tnrdns = 0;\n\n\t/* A DN is a SEQUENCE of RDNs. An RDN is a SET of AVAs.\n\t * An AVA is a SEQUENCE of attr and value.\n\t * Count the number of AVAs and RDNs\n\t */\n\tber_init2( ber, in, LBER_USE_DER );\n\ttag = ber_peek_tag( ber, &len );\n\tif ( tag != LBER_SEQUENCE )\n\t\treturn LDAP_DECODING_ERROR;\n\n\tfor ( tag = ber_first_element( ber, &len, &dn_end );\n\t\ttag == LBER_SET;\n\t\ttag = ber_next_element( ber, &len, dn_end )) {\n\t\tnrdns++;\n\t\tfor ( tag = ber_first_element( ber, &len, &rdn_end );\n\t\t\ttag == LBER_SEQUENCE;\n\t\t\ttag = ber_next_element( ber, &len, rdn_end )) {\n\t\t\ttag = ber_skip_tag( ber, &len );\n\t\t\tber_skip_data( ber, len );\n\t\t\tnavas++;\n\t\t}\n\t}\n\n\t/* Rewind and prepare to extract */\n\tber_rewind( ber );\n\ttag = ber_first_element( ber, &len, &dn_end );\n\tif ( tag == LBER_DEFAULT )\n\t\treturn LDAP_DECODING_ERROR;\n\n\t/* Allocate the DN/RDN/AVA stuff as a single block */ \n\tdnsize = sizeof(LDAPRDN) * (nrdns+1);\n\tdnsize += sizeof(LDAPAVA *) * (navas+nrdns);\n\tdnsize += sizeof(LDAPAVA) * navas;\n\tif (dnsize > sizeof(ptrs)) {\n\t\tnewDN = (LDAPDN)LDAP_MALLOC( dnsize );\n\t\tif ( newDN == NULL )\n\t\t\treturn LDAP_NO_MEMORY;\n\t} else {\n\t\tnewDN = (LDAPDN)(char *)ptrs;\n\t}\n\n\tnewDN[nrdns] = NULL;\n\tnewRDN = (LDAPRDN)(newDN + nrdns+1);\n\tnewAVA = (LDAPAVA *)(newRDN + navas + nrdns);\n\tbaseAVA = newAVA;\n\n\tfor ( i = nrdns - 1; i >= 0; i-- ) {\n\t\tnewDN[i] = newRDN;\n\n\t\tfor ( tag = ber_first_element( ber, &len, &rdn_end );\n\t\t\ttag == LBER_SEQUENCE;\n\t\t\ttag = ber_next_element( ber, &len, rdn_end )) {\n\n\t\t\t*newRDN++ = newAVA;\n\t\t\ttag = ber_skip_tag( ber, &len );\n\t\t\ttag = ber_get_stringbv( ber, &Oid, LBER_BV_NOTERM );\n\t\t\tif ( tag != LBER_TAG_OID ) {\n\t\t\t\trc = LDAP_DECODING_ERROR;\n\t\t\t\tgoto nomem;\n\t\t\t}\n\n\t\t\toid2.bv_val = oidptr;\n\t\t\toid2.bv_len = oidrem;\n\t\t\tif ( ber_decode_oid( &Oid, &oid2 ) < 0 ) {\n\t\t\t\trc = LDAP_DECODING_ERROR;\n\t\t\t\tgoto nomem;\n\t\t\t}\n\t\t\toidname = find_oid( &oid2 );\n\t\t\tif ( !oidname ) {\n\t\t\t\tnewAVA->la_attr = oid2;\n\t\t\t\toidptr += oid2.bv_len + 1;\n\t\t\t\toidrem -= oid2.bv_len + 1;\n\n\t\t\t\t/* Running out of OID buffer space? */\n\t\t\t\tif (oidrem < 128) {\n\t\t\t\t\tif ( oidsize == 0 ) {\n\t\t\t\t\t\toidsize = sizeof(oids) * 2;\n\t\t\t\t\t\toidrem = oidsize;\n\t\t\t\t\t\toidbuf = LDAP_MALLOC( oidsize );\n\t\t\t\t\t\tif ( oidbuf == NULL ) goto nomem;\n\t\t\t\t\t\toidptr = oidbuf;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tchar *old = oidbuf;\n\t\t\t\t\t\toidbuf = LDAP_REALLOC( oidbuf, oidsize*2 );\n\t\t\t\t\t\tif ( oidbuf == NULL ) goto nomem;\n\t\t\t\t\t\t/* Buffer moved! Fix AVA pointers */\n\t\t\t\t\t\tif ( old != oidbuf ) {\n\t\t\t\t\t\t\tLDAPAVA *a;\n\t\t\t\t\t\t\tlong dif = oidbuf - old;\n\n\t\t\t\t\t\t\tfor (a=baseAVA; a<=newAVA; a++){\n\t\t\t\t\t\t\t\tif (a->la_attr.bv_val >= old &&\n\t\t\t\t\t\t\t\t\ta->la_attr.bv_val <= (old + oidsize))\n\t\t\t\t\t\t\t\t\ta->la_attr.bv_val += dif;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\toidptr = oidbuf + oidsize - oidrem;\n\t\t\t\t\t\toidrem += oidsize;\n\t\t\t\t\t\toidsize *= 2;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif ( func ) {\n\t\t\t\t\tnewAVA->la_attr = oidname->oid;\n\t\t\t\t} else {\n\t\t\t\t\tnewAVA->la_attr = oidname->name;\n\t\t\t\t}\n\t\t\t}\n\t\t\tnewAVA->la_private = NULL;\n\t\t\tnewAVA->la_flags = LDAP_AVA_STRING;\n\t\t\ttag = ber_get_stringbv( ber, &Val, LBER_BV_NOTERM );\n\t\t\tswitch(tag) {\n\t\t\tcase LBER_TAG_UNIVERSAL:\n\t\t\t\t/* This uses 32-bit ISO 10646-1 */\n\t\t\t\tcsize = 4; goto to_utf8;\n\t\t\tcase LBER_TAG_BMP:\n\t\t\t\t/* This uses 16-bit ISO 10646-1 */\n\t\t\t\tcsize = 2; goto to_utf8;\n\t\t\tcase LBER_TAG_TELETEX:\n\t\t\t\t/* This uses 8-bit, assume ISO 8859-1 */\n\t\t\t\tcsize = 1;\nto_utf8:\t\trc = ldap_ucs_to_utf8s( &Val, csize, &newAVA->la_value );\n\t\t\t\tnewAVA->la_flags |= LDAP_AVA_NONPRINTABLE;\nallocd:\n\t\t\t\tnewAVA->la_flags |= LDAP_AVA_FREE_VALUE;\n\t\t\t\tif (rc != LDAP_SUCCESS) goto nomem;\n\t\t\t\tbreak;\n\t\t\tcase LBER_TAG_UTF8:\n\t\t\t\tnewAVA->la_flags |= LDAP_AVA_NONPRINTABLE;\n\t\t\t\t/* This is already in UTF-8 encoding */\n\t\t\tcase LBER_TAG_IA5:\n\t\t\tcase LBER_TAG_PRINTABLE:\n\t\t\t\t/* These are always 7-bit strings */\n\t\t\t\tnewAVA->la_value = Val;\n\t\t\t\tbreak;\n\t\t\tcase LBER_BITSTRING:\n\t\t\t\t/* X.690 bitString value converted to RFC4517 Bit String */\n\t\t\t\trc = der_to_ldap_BitString( &Val, &newAVA->la_value );\n\t\t\t\tgoto allocd;\n\t\t\tdefault:\n\t\t\t\t/* Not a string type at all */\n\t\t\t\tnewAVA->la_flags = 0;\n\t\t\t\tnewAVA->la_value = Val;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tnewAVA++;\n\t\t}\n\t\t*newRDN++ = NULL;\n\t\ttag = ber_next_element( ber, &len, dn_end );\n\t}\n\t\t\n\tif ( func ) {\n\t\trc = func( newDN, flags, NULL );\n\t\tif ( rc != LDAP_SUCCESS )\n\t\t\tgoto nomem;\n\t}\n\n\trc = ldap_dn2bv_x( newDN, bv, LDAP_DN_FORMAT_LDAPV3, NULL );\n\nnomem:\n\tfor (;baseAVA < newAVA; baseAVA++) {\n\t\tif (baseAVA->la_flags & LDAP_AVA_FREE_ATTR)\n\t\t\tLDAP_FREE( baseAVA->la_attr.bv_val );\n\t\tif (baseAVA->la_flags & LDAP_AVA_FREE_VALUE)\n\t\t\tLDAP_FREE( baseAVA->la_value.bv_val );\n\t}\n\n\tif ( oidsize != 0 )\n\t\tLDAP_FREE( oidbuf );\n\tif ( newDN != (LDAPDN)(char *) ptrs )\n\t\tLDAP_FREE( newDN );\n\treturn rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-843'], 'message': 'ITS#9425 add more checks to ldap_X509dn2bv'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadTIFFImage(const ImageInfo *image_info,\n ExceptionInfo *exception)\n{\n#define ThrowTIFFException(severity,message) \\\n{ \\\n if (pixel_info != (MemoryInfo *) NULL) \\\n pixel_info=RelinquishVirtualMemory(pixel_info); \\\n if (quantum_info != (QuantumInfo *) NULL) \\\n quantum_info=DestroyQuantumInfo(quantum_info); \\\n TIFFClose(tiff); \\\n ThrowReaderException(severity,message); \\\n}\n\n const char\n *option;\n\n float\n *chromaticity,\n x_position,\n y_position,\n x_resolution,\n y_resolution;\n\n Image\n *image;\n\n int\n tiff_status;\n\n MagickBooleanType\n more_frames,\n status;\n\n MagickSizeType\n number_pixels;\n\n MemoryInfo\n *pixel_info = (MemoryInfo *) NULL;\n\n QuantumInfo\n *quantum_info;\n\n QuantumType\n quantum_type;\n\n register ssize_t\n i;\n\n size_t\n pad;\n\n ssize_t\n y;\n\n TIFF\n *tiff;\n\n TIFFMethodType\n method;\n\n uint16\n compress_tag,\n bits_per_sample,\n endian,\n extra_samples,\n interlace,\n max_sample_value,\n min_sample_value,\n orientation,\n pages,\n photometric,\n *sample_info,\n sample_format,\n samples_per_pixel,\n units,\n value;\n\n uint32\n height,\n rows_per_strip,\n width;\n\n unsigned char\n *pixels;\n\n void\n *sans[2] = { NULL, NULL };\n\n /*\n Open image.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n (void) SetMagickThreadValue(tiff_exception,exception);\n tiff=TIFFClientOpen(image->filename,\"rb\",(thandle_t) image,TIFFReadBlob,\n TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,\n TIFFUnmapBlob);\n if (tiff == (TIFF *) NULL)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n if (exception->severity > ErrorException)\n {\n TIFFClose(tiff);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n if (image_info->number_scenes != 0)\n {\n /*\n Generate blank images for subimage specification (e.g. image.tif[4].\n We need to check the number of directores because it is possible that\n the subimage(s) are stored in the photoshop profile.\n */\n if (image_info->scene < (size_t) TIFFNumberOfDirectories(tiff))\n {\n for (i=0; i < (ssize_t) image_info->scene; i++)\n {\n status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;\n if (status == MagickFalse)\n {\n TIFFClose(tiff);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n AcquireNextImage(image_info,image,exception);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n TIFFClose(tiff);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n }\n }\n }\n more_frames=MagickTrue;\n do\n {\n /* TIFFPrintDirectory(tiff,stdout,MagickFalse); */\n photometric=PHOTOMETRIC_RGB;\n if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) ||\n (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric,sans) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag,sans) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian,sans) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace,sans) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel,sans) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample,sans) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format,sans) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value,sans) != 1) ||\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value,sans) != 1))\n {\n TIFFClose(tiff);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n if (((sample_format != SAMPLEFORMAT_IEEEFP) || (bits_per_sample != 64)) &&\n ((bits_per_sample <= 0) || (bits_per_sample > 32)))\n {\n TIFFClose(tiff);\n ThrowReaderException(CorruptImageError,\"UnsupportedBitsPerPixel\");\n }\n if (sample_format == SAMPLEFORMAT_IEEEFP)\n (void) SetImageProperty(image,\"quantum:format\",\"floating-point\",\n exception);\n switch (photometric)\n {\n case PHOTOMETRIC_MINISBLACK:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"min-is-black\",\n exception);\n break;\n }\n case PHOTOMETRIC_MINISWHITE:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"min-is-white\",\n exception);\n break;\n }\n case PHOTOMETRIC_PALETTE:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"palette\",exception);\n break;\n }\n case PHOTOMETRIC_RGB:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"RGB\",exception);\n break;\n }\n case PHOTOMETRIC_CIELAB:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"CIELAB\",exception);\n break;\n }\n case PHOTOMETRIC_LOGL:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"CIE Log2(L)\",\n exception);\n break;\n }\n case PHOTOMETRIC_LOGLUV:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"LOGLUV\",exception);\n break;\n }\n#if defined(PHOTOMETRIC_MASK)\n case PHOTOMETRIC_MASK:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"MASK\",exception);\n break;\n }\n#endif\n case PHOTOMETRIC_SEPARATED:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"separated\",exception);\n break;\n }\n case PHOTOMETRIC_YCBCR:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"YCBCR\",exception);\n break;\n }\n default:\n {\n (void) SetImageProperty(image,\"tiff:photometric\",\"unknown\",exception);\n break;\n }\n }\n if (image->debug != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Geometry: %ux%u\",\n (unsigned int) width,(unsigned int) height);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Interlace: %u\",\n interlace);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"Bits per sample: %u\",bits_per_sample);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"Min sample value: %u\",min_sample_value);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"Max sample value: %u\",max_sample_value);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Photometric \"\n \"interpretation: %s\",GetImageProperty(image,\"tiff:photometric\",\n exception));\n }\n image->columns=(size_t) width;\n image->rows=(size_t) height;\n image->depth=(size_t) bits_per_sample;\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Image depth: %.20g\",\n (double) image->depth);\n image->endian=MSBEndian;\n if (endian == FILLORDER_LSB2MSB)\n image->endian=LSBEndian;\n#if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN)\n if (TIFFIsBigEndian(tiff) == 0)\n {\n (void) SetImageProperty(image,\"tiff:endian\",\"lsb\",exception);\n image->endian=LSBEndian;\n }\n else\n {\n (void) SetImageProperty(image,\"tiff:endian\",\"msb\",exception);\n image->endian=MSBEndian;\n }\n#endif\n if ((photometric == PHOTOMETRIC_MINISBLACK) ||\n (photometric == PHOTOMETRIC_MINISWHITE))\n image->colorspace=GRAYColorspace;\n if (photometric == PHOTOMETRIC_SEPARATED)\n image->colorspace=CMYKColorspace;\n if (photometric == PHOTOMETRIC_CIELAB)\n image->colorspace=LabColorspace;\n if ((photometric == PHOTOMETRIC_YCBCR) && (compress_tag != COMPRESSION_JPEG))\n image->colorspace=YCbCrColorspace;\n status=TIFFGetProfiles(tiff,image,exception);\n if (status == MagickFalse)\n {\n TIFFClose(tiff);\n return(DestroyImageList(image));\n }\n status=TIFFGetProperties(tiff,image,exception);\n if (status == MagickFalse)\n {\n TIFFClose(tiff);\n return(DestroyImageList(image));\n }\n option=GetImageOption(image_info,\"tiff:exif-properties\");\n if (IsStringFalse(option) == MagickFalse) /* enabled by default */\n TIFFGetEXIFProperties(tiff,image,exception);\n if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution,sans) == 1) &&\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution,sans) == 1))\n {\n image->resolution.x=x_resolution;\n image->resolution.y=y_resolution;\n }\n if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units,sans,sans) == 1)\n {\n if (units == RESUNIT_INCH)\n image->units=PixelsPerInchResolution;\n if (units == RESUNIT_CENTIMETER)\n image->units=PixelsPerCentimeterResolution;\n }\n if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position,sans) == 1) &&\n (TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position,sans) == 1))\n {\n image->page.x=(ssize_t) ceil(x_position*image->resolution.x-0.5);\n image->page.y=(ssize_t) ceil(y_position*image->resolution.y-0.5);\n }\n if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation,sans) == 1)\n image->orientation=(OrientationType) orientation;\n if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1)\n {\n if ((chromaticity != (float *) NULL) && (*chromaticity != 0.0))\n {\n image->chromaticity.white_point.x=chromaticity[0];\n image->chromaticity.white_point.y=chromaticity[1];\n }\n }\n if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1)\n {\n if ((chromaticity != (float *) NULL) && (*chromaticity != 0.0))\n {\n image->chromaticity.red_primary.x=chromaticity[0];\n image->chromaticity.red_primary.y=chromaticity[1];\n image->chromaticity.green_primary.x=chromaticity[2];\n image->chromaticity.green_primary.y=chromaticity[3];\n image->chromaticity.blue_primary.x=chromaticity[4];\n image->chromaticity.blue_primary.y=chromaticity[5];\n }\n }\n#if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)\n if ((compress_tag != COMPRESSION_NONE) &&\n (TIFFIsCODECConfigured(compress_tag) == 0))\n {\n TIFFClose(tiff);\n ThrowReaderException(CoderError,\"CompressNotSupported\");\n }\n#endif\n switch (compress_tag)\n {\n case COMPRESSION_NONE: image->compression=NoCompression; break;\n case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break;\n case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break;\n case COMPRESSION_JPEG:\n {\n image->compression=JPEGCompression;\n#if defined(JPEG_SUPPORT)\n {\n char\n sampling_factor[MagickPathExtent];\n\n uint16\n horizontal,\n vertical;\n\n tiff_status=TIFFGetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,&horizontal,\n &vertical);\n if (tiff_status == 1)\n {\n (void) FormatLocaleString(sampling_factor,MagickPathExtent,\n \"%dx%d\",horizontal,vertical);\n (void) SetImageProperty(image,\"jpeg:sampling-factor\",\n sampling_factor,exception);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"Sampling Factors: %s\",sampling_factor);\n }\n }\n#endif\n break;\n }\n case COMPRESSION_OJPEG: image->compression=JPEGCompression; break;\n#if defined(COMPRESSION_LZMA)\n case COMPRESSION_LZMA: image->compression=LZMACompression; break;\n#endif\n case COMPRESSION_LZW: image->compression=LZWCompression; break;\n case COMPRESSION_DEFLATE: image->compression=ZipCompression; break;\n case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break;\n#if defined(COMPRESSION_WEBP)\n case COMPRESSION_WEBP: image->compression=WebPCompression; break;\n#endif\n#if defined(COMPRESSION_ZSTD)\n case COMPRESSION_ZSTD: image->compression=ZstdCompression; break;\n#endif\n default: image->compression=RLECompression; break;\n }\n quantum_info=(QuantumInfo *) NULL;\n if ((photometric == PHOTOMETRIC_PALETTE) &&\n (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize))\n {\n size_t\n colors;\n\n colors=(size_t) GetQuantumRange(bits_per_sample)+1;\n if (AcquireImageColormap(image,colors,exception) == MagickFalse)\n {\n TIFFClose(tiff);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n }\n value=(unsigned short) image->scene;\n if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages,sans) == 1)\n image->scene=value;\n if (image->storage_class == PseudoClass)\n {\n size_t\n range;\n\n uint16\n *blue_colormap,\n *green_colormap,\n *red_colormap;\n\n /*\n Initialize colormap.\n */\n tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap,\n &green_colormap,&blue_colormap);\n if (tiff_status == 1)\n {\n if ((red_colormap != (uint16 *) NULL) &&\n (green_colormap != (uint16 *) NULL) &&\n (blue_colormap != (uint16 *) NULL))\n {\n range=255; /* might be old style 8-bit colormap */\n for (i=0; i < (ssize_t) image->colors; i++)\n if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) ||\n (blue_colormap[i] >= 256))\n {\n range=65535;\n break;\n }\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n image->colormap[i].red=ClampToQuantum(((double)\n QuantumRange*red_colormap[i])/range);\n image->colormap[i].green=ClampToQuantum(((double)\n QuantumRange*green_colormap[i])/range);\n image->colormap[i].blue=ClampToQuantum(((double)\n QuantumRange*blue_colormap[i])/range);\n }\n }\n }\n }\n if (image_info->ping != MagickFalse)\n {\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n goto next_tiff_frame;\n }\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n {\n TIFFClose(tiff);\n return(DestroyImageList(image));\n }\n status=SetImageColorspace(image,image->colorspace,exception);\n status&=ResetImagePixels(image,exception);\n if (status == MagickFalse)\n {\n TIFFClose(tiff);\n return(DestroyImageList(image));\n }\n /*\n Allocate memory for the image and pixel buffer.\n */\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n if (sample_format == SAMPLEFORMAT_UINT)\n status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat);\n if (sample_format == SAMPLEFORMAT_INT)\n status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat);\n if (sample_format == SAMPLEFORMAT_IEEEFP)\n status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);\n if (status == MagickFalse)\n ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n status=MagickTrue;\n switch (photometric)\n {\n case PHOTOMETRIC_MINISBLACK:\n {\n quantum_info->min_is_white=MagickFalse;\n break;\n }\n case PHOTOMETRIC_MINISWHITE:\n {\n quantum_info->min_is_white=MagickTrue;\n break;\n }\n default:\n break;\n }\n extra_samples=0;\n tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples,\n &sample_info,sans);\n if (tiff_status == 1)\n {\n (void) SetImageProperty(image,\"tiff:alpha\",\"unspecified\",exception);\n if (extra_samples == 0)\n {\n if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB))\n image->alpha_trait=BlendPixelTrait;\n }\n else\n for (i=0; i < extra_samples; i++)\n {\n image->alpha_trait=BlendPixelTrait;\n if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA)\n {\n SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha);\n (void) SetImageProperty(image,\"tiff:alpha\",\"associated\",\n exception);\n }\n else\n if (sample_info[i] == EXTRASAMPLE_UNASSALPHA)\n {\n SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha);\n (void) SetImageProperty(image,\"tiff:alpha\",\"unassociated\",\n exception);\n }\n }\n }\n if (image->alpha_trait != UndefinedPixelTrait)\n (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);\n if (samples_per_pixel > MaxPixelChannels)\n {\n TIFFClose(tiff);\n ThrowReaderException(CorruptImageError,\"MaximumChannelsExceeded\");\n }\n method=ReadGenericMethod;\n rows_per_strip=(uint32) image->rows;\n if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1)\n {\n char\n buffer[MagickPathExtent];\n\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%u\",\n (unsigned int) rows_per_strip);\n (void) SetImageProperty(image,\"tiff:rows-per-strip\",buffer,exception);\n method=ReadStripMethod;\n if (rows_per_strip > (uint32) image->rows)\n rows_per_strip=(uint32) image->rows;\n }\n if (TIFFIsTiled(tiff) != MagickFalse)\n {\n uint32\n columns,\n rows;\n\n if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) ||\n (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1))\n ThrowTIFFException(CoderError,\"ImageIsNotTiled\");\n if ((AcquireMagickResource(WidthResource,columns) == MagickFalse) ||\n (AcquireMagickResource(HeightResource,rows) == MagickFalse))\n ThrowTIFFException(ImageError,\"WidthOrHeightExceedsLimit\");\n method=ReadTileMethod;\n }\n if (image->compression == JPEGCompression)\n method=GetJPEGMethod(image,tiff,photometric,bits_per_sample,\n samples_per_pixel);\n if (photometric == PHOTOMETRIC_LOGLUV)\n method=ReadGenericMethod;\n quantum_info->endian=LSBEndian;\n quantum_type=RGBQuantum;\n if (TIFFScanlineSize(tiff) <= 0)\n ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n if ((1.0*TIFFScanlineSize(tiff)) > (2.53*GetBlobSize(image)))\n ThrowTIFFException(CorruptImageError,\"InsufficientImageDataInFile\");\n number_pixels=MagickMax(TIFFScanlineSize(tiff),MagickMax((ssize_t)\n image->columns*samples_per_pixel*pow(2.0,ceil(log(bits_per_sample)/\n log(2.0))),image->columns*rows_per_strip));\n pixel_info=AcquireVirtualMemory(number_pixels,sizeof(uint32));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n (void) memset(pixels,0,number_pixels*sizeof(uint32));\n quantum_type=IndexQuantum;\n pad=(size_t) MagickMax((ssize_t) samples_per_pixel-1,0);\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n if (image->storage_class == PseudoClass)\n quantum_type=IndexAlphaQuantum;\n else\n quantum_type=samples_per_pixel == 1 ? AlphaQuantum : GrayAlphaQuantum;\n }\n else\n if (image->storage_class != PseudoClass)\n quantum_type=GrayQuantum;\n if ((samples_per_pixel > 2) && (interlace != PLANARCONFIG_SEPARATE))\n {\n pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0);\n quantum_type=RGBQuantum;\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n quantum_type=RGBAQuantum;\n pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);\n }\n if (image->colorspace == CMYKColorspace)\n {\n pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);\n quantum_type=CMYKQuantum;\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n quantum_type=CMYKAQuantum;\n pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0);\n }\n }\n status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));\n if (status == MagickFalse)\n ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n switch (method)\n {\n case ReadYCCKMethod:\n {\n /*\n Convert YCC TIFF image.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;\n\n register ssize_t\n x;\n\n unsigned char\n *p;\n\n tiff_status=TIFFReadPixels(tiff,0,y,(char *) pixels);\n if (tiff_status == -1)\n break;\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n p=pixels;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelCyan(image,ScaleCharToQuantum(ClampYCC((double) *p+\n (1.402*(double) *(p+2))-179.456)),q);\n SetPixelMagenta(image,ScaleCharToQuantum(ClampYCC((double) *p-\n (0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+\n 135.45984)),q);\n SetPixelYellow(image,ScaleCharToQuantum(ClampYCC((double) *p+\n (1.772*(double) *(p+1))-226.816)),q);\n SetPixelBlack(image,ScaleCharToQuantum((unsigned char) *(p+3)),q);\n q+=GetPixelChannels(image);\n p+=4;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n break;\n }\n case ReadStripMethod:\n {\n register unsigned char\n *p;\n\n size_t\n extent;\n\n ssize_t\n stride,\n strip_id;\n\n tsize_t\n strip_size;\n\n unsigned char\n *strip_pixels;\n\n /*\n Convert stripped TIFF image.\n */\n extent=TIFFStripSize(tiff);\n#if defined(TIFF_VERSION_BIG)\n extent+=image->columns*sizeof(uint64);\n#else\n extent+=image->columns*sizeof(uint32);\n#endif\n strip_pixels=(unsigned char *) AcquireQuantumMemory(extent,\n sizeof(*strip_pixels));\n if (strip_pixels == (unsigned char *) NULL)\n ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) memset(strip_pixels,0,extent*sizeof(*strip_pixels));\n stride=TIFFVStripSize(tiff,1);\n strip_id=0;\n p=strip_pixels;\n for (i=0; i < (ssize_t) samples_per_pixel; i++)\n {\n size_t\n rows_remaining;\n\n switch (i)\n {\n case 0: break;\n case 1: quantum_type=GreenQuantum; break;\n case 2: quantum_type=BlueQuantum; break;\n case 3:\n {\n if (image->colorspace == CMYKColorspace)\n quantum_type=BlackQuantum;\n break;\n }\n case 4: quantum_type=AlphaQuantum; break;\n }\n rows_remaining=0;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;\n\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n if (rows_remaining == 0)\n {\n strip_size=TIFFReadEncodedStrip(tiff,strip_id,strip_pixels,\n TIFFStripSize(tiff));\n if (strip_size == -1)\n break;\n rows_remaining=rows_per_strip;\n if ((y+rows_per_strip) > image->rows)\n rows_remaining=(rows_per_strip-(y+rows_per_strip-\n image->rows));\n p=strip_pixels;\n strip_id++;\n }\n (void) ImportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,quantum_type,p,exception);\n p+=stride;\n rows_remaining--;\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n if ((samples_per_pixel > 1) && (interlace != PLANARCONFIG_SEPARATE))\n break;\n }\n strip_pixels=(unsigned char *) RelinquishMagickMemory(strip_pixels);\n break;\n }\n case ReadTileMethod:\n {\n register unsigned char\n *p;\n\n size_t\n extent;\n\n uint32\n columns,\n rows;\n\n unsigned char\n *tile_pixels;\n\n /*\n Convert tiled TIFF image.\n */\n if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) ||\n (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1))\n ThrowTIFFException(CoderError,\"ImageIsNotTiled\");\n number_pixels=(MagickSizeType) columns*rows;\n if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse)\n ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n extent=TIFFTileSize(tiff);\n#if defined(TIFF_VERSION_BIG)\n extent+=columns*sizeof(uint64);\n#else\n extent+=columns*sizeof(uint32);\n#endif\n tile_pixels=(unsigned char *) AcquireQuantumMemory(extent,\n sizeof(*tile_pixels));\n if (tile_pixels == (unsigned char *) NULL)\n ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) memset(tile_pixels,0,extent*sizeof(*tile_pixels));\n for (i=0; i < (ssize_t) samples_per_pixel; i++)\n {\n switch (i)\n {\n case 0: break;\n case 1: quantum_type=GreenQuantum; break;\n case 2: quantum_type=BlueQuantum; break;\n case 3:\n {\n if (image->colorspace == CMYKColorspace)\n quantum_type=BlackQuantum;\n break;\n }\n case 4: quantum_type=AlphaQuantum; break;\n }\n for (y=0; y < (ssize_t) image->rows; y+=rows)\n {\n register ssize_t\n x;\n\n size_t\n rows_remaining;\n\n rows_remaining=image->rows-y;\n if ((ssize_t) (y+rows) < (ssize_t) image->rows)\n rows_remaining=rows;\n for (x=0; x < (ssize_t) image->columns; x+=columns)\n {\n size_t\n columns_remaining,\n row;\n\n columns_remaining=image->columns-x;\n if ((ssize_t) (x+columns) < (ssize_t) image->columns)\n columns_remaining=columns;\n if (TIFFReadTile(tiff,tile_pixels,(uint32) x,(uint32) y,0,i) == 0)\n break;\n p=tile_pixels;\n for (row=0; row < rows_remaining; row++)\n {\n register Quantum\n *magick_restrict q;\n\n q=GetAuthenticPixels(image,x,y+row,columns_remaining,1,\n exception);\n if (q == (Quantum *) NULL)\n break;\n (void) ImportQuantumPixels(image,(CacheView *) NULL,\n quantum_info,quantum_type,p,exception);\n p+=TIFFTileRowSize(tiff);\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n }\n }\n if ((samples_per_pixel > 1) && (interlace != PLANARCONFIG_SEPARATE))\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) i,\n samples_per_pixel);\n if (status == MagickFalse)\n break;\n }\n }\n tile_pixels=(unsigned char *) RelinquishMagickMemory(tile_pixels);\n break;\n }\n case ReadGenericMethod:\n default:\n {\n MemoryInfo\n *generic_info = (MemoryInfo * ) NULL;\n\n register uint32\n *p;\n\n uint32\n *pixels;\n\n /*\n Convert generic TIFF image.\n */\n if (HeapOverflowSanityCheck(image->rows,sizeof(*pixels)) != MagickFalse)\n ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n number_pixels=(MagickSizeType) image->columns*image->rows;\n number_pixels+=image->columns*sizeof(uint32);\n generic_info=AcquireVirtualMemory(number_pixels,sizeof(uint32));\n if (generic_info == (MemoryInfo *) NULL)\n ThrowTIFFException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=(uint32 *) GetVirtualMemoryBlob(generic_info);\n (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32)\n image->rows,(uint32 *) pixels,0);\n p=pixels+(image->columns*image->rows)-1;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register ssize_t\n x;\n\n register Quantum\n *magick_restrict q;\n\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n q+=GetPixelChannels(image)*(image->columns-1);\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelRed(image,ScaleCharToQuantum((unsigned char)\n TIFFGetR(*p)),q);\n SetPixelGreen(image,ScaleCharToQuantum((unsigned char)\n TIFFGetG(*p)),q);\n SetPixelBlue(image,ScaleCharToQuantum((unsigned char)\n TIFFGetB(*p)),q);\n if (image->alpha_trait != UndefinedPixelTrait)\n SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)\n TIFFGetA(*p)),q);\n p--;\n q-=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n generic_info=RelinquishVirtualMemory(generic_info);\n break;\n }\n }\n pixel_info=RelinquishVirtualMemory(pixel_info);\n SetQuantumImageType(image,quantum_type);\n next_tiff_frame:\n if (quantum_info != (QuantumInfo *) NULL)\n quantum_info=DestroyQuantumInfo(quantum_info);\n if (photometric == PHOTOMETRIC_CIELAB)\n DecodeLabImage(image,exception);\n if ((photometric == PHOTOMETRIC_LOGL) ||\n (photometric == PHOTOMETRIC_MINISBLACK) ||\n (photometric == PHOTOMETRIC_MINISWHITE))\n {\n image->type=GrayscaleType;\n if (bits_per_sample == 1)\n image->type=BilevelType;\n }\n /*\n Proceed to next image.\n */\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n more_frames=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;\n if (more_frames != MagickFalse)\n {\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image,exception);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n status=MagickFalse;\n break;\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,image->scene-1,\n image->scene);\n if (status == MagickFalse)\n break;\n }\n } while ((status != MagickFalse) && (more_frames != MagickFalse));\n TIFFClose(tiff);\n if (status != MagickFalse)\n TIFFReadPhotoshopLayers(image_info,image,exception);\n if ((image_info->number_scenes != 0) &&\n (image_info->scene >= GetImageListLength(image)))\n status=MagickFalse;\n if (status == MagickFalse)\n return(DestroyImageList(image));\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-122'], 'message': 'possible TIFF related-heap buffer overflow (alert & POC by Hardik Shah)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: NOEXPORT void print_cipher(CLI *c) { /* print negotiated cipher */\n SSL_CIPHER *cipher;\n#ifndef OPENSSL_NO_COMP\n const COMP_METHOD *compression, *expansion;\n#endif\n\n if(c->opt->log_levelopt->option.client ? \"connected\" : \"accepted\",\n SSL_session_reused(c->ssl) && !c->flag.psk ?\n \"previous session reused\" : \"new session negotiated\");\n\n cipher=(SSL_CIPHER *)SSL_get_current_cipher(c->ssl);\n s_log(LOG_INFO, \"%s ciphersuite: %s (%d-bit encryption)\",\n SSL_get_version(c->ssl), SSL_CIPHER_get_name(cipher),\n SSL_CIPHER_get_bits(cipher, NULL));\n\n#ifndef OPENSSL_NO_COMP\n compression=SSL_get_current_compression(c->ssl);\n expansion=SSL_get_current_expansion(c->ssl);\n s_log(compression||expansion ? LOG_INFO : LOG_DEBUG,\n \"Compression: %s, expansion: %s\",\n compression ? SSL_COMP_get_name(compression) : \"null\",\n expansion ? SSL_COMP_get_name(expansion) : \"null\");\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-295'], 'message': 'stunnel-5.57'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: DH *get_dh2048(void)\n{\n static unsigned char dhp_2048[] = {\n 0xD5, 0x75, 0xF1, 0x23, 0xC1, 0x81, 0x4B, 0x44, 0x23, 0xBE,\n 0x97, 0x81, 0x7A, 0xDA, 0x97, 0x1F, 0x1F, 0x0D, 0xD5, 0xEC,\n 0xC5, 0x5F, 0x86, 0x42, 0x7F, 0x38, 0xA3, 0x95, 0xEE, 0xA0,\n 0x52, 0x2C, 0xB7, 0x20, 0x29, 0xC1, 0xC7, 0xE6, 0x8E, 0x6F,\n 0xE5, 0xC1, 0x0D, 0xDD, 0x8A, 0xEF, 0x8D, 0xE7, 0xA8, 0x63,\n 0xB4, 0xF7, 0x58, 0x32, 0x0E, 0x24, 0xAC, 0x30, 0x94, 0xF5,\n 0xC7, 0x02, 0x81, 0x1B, 0xC7, 0x68, 0xE5, 0x71, 0xD7, 0x1E,\n 0x3D, 0xE4, 0x2E, 0x2F, 0xC0, 0x0A, 0xED, 0x34, 0xAC, 0xC0,\n 0x1F, 0x0A, 0x56, 0xA4, 0x12, 0x02, 0xFD, 0x68, 0xD2, 0x4D,\n 0x5E, 0x0A, 0x5D, 0x78, 0xE3, 0xA0, 0x85, 0x75, 0xD2, 0xA9,\n 0xC1, 0xF2, 0xAD, 0x65, 0x11, 0xDE, 0xE8, 0x05, 0x68, 0x36,\n 0x4C, 0x92, 0x99, 0x21, 0xB9, 0x69, 0xD0, 0x6F, 0xD8, 0xA3,\n 0xEA, 0x35, 0x13, 0x93, 0xDC, 0x1B, 0x13, 0x16, 0xB2, 0x15,\n 0x8E, 0x10, 0x22, 0xCE, 0x01, 0x1F, 0x1C, 0x09, 0x86, 0xD5,\n 0xE7, 0xCB, 0xCF, 0xFA, 0xED, 0x2F, 0xE2, 0x3A, 0x65, 0x14,\n 0xC9, 0xFA, 0x70, 0x99, 0xF7, 0xE0, 0x30, 0xBF, 0x7F, 0xEA,\n 0x84, 0x14, 0x8A, 0x51, 0xC9, 0xE9, 0x85, 0x73, 0x7F, 0xA1,\n 0xB0, 0xC3, 0x33, 0x9A, 0xAB, 0x69, 0x4E, 0x75, 0xFB, 0x12,\n 0xB0, 0x9E, 0xB1, 0xD9, 0xD1, 0xB9, 0x32, 0x1D, 0xC6, 0xD9,\n 0x2C, 0xAA, 0xB0, 0xC5, 0x3E, 0x69, 0x56, 0xA2, 0xB3, 0xA2,\n 0x81, 0xCA, 0x9D, 0x77, 0xBB, 0x52, 0x44, 0xA2, 0xED, 0xE0,\n 0xF0, 0x2A, 0x81, 0x85, 0x90, 0xB6, 0x04, 0x60, 0xEB, 0x09,\n 0x72, 0x08, 0x44, 0xAF, 0x28, 0xF5, 0x15, 0x34, 0x87, 0x5C,\n 0x8A, 0xB4, 0x5B, 0x15, 0x6A, 0xAD, 0x27, 0x4E, 0xA0, 0xDE,\n 0x99, 0x22, 0xCF, 0xAB, 0x4C, 0xFD, 0x75, 0x10, 0x5D, 0xFF,\n 0xE8, 0x81, 0x50, 0xC4, 0xC0, 0x4B\n };\n static unsigned char dhg_2048[] = {\n 0x02\n };\n DH *dh = DH_new();\n BIGNUM *p, *g;\n\n if (dh == NULL)\n return NULL;\n p = BN_bin2bn(dhp_2048, sizeof(dhp_2048), NULL);\n g = BN_bin2bn(dhg_2048, sizeof(dhg_2048), NULL);\n if (p == NULL || g == NULL\n || !DH_set0_pqg(dh, p, NULL, g)) {\n DH_free(dh);\n BN_free(p);\n BN_free(g);\n return NULL;\n }\n return dh;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-295'], 'message': 'stunnel-5.57'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: NOEXPORT void reload_config() {\n static int delay=10; /* 10ms */\n#ifdef HAVE_CHROOT\n struct stat sb;\n#endif /* HAVE_CHROOT */\n\n if(options_parse(CONF_RELOAD)) {\n s_log(LOG_ERR, \"Failed to reload the configuration file\");\n return;\n }\n unbind_ports();\n log_flush(LOG_MODE_BUFFER);\n#ifdef HAVE_CHROOT\n /* we don't close SINK_SYSLOG if chroot is enabled and\n * there is no /dev/log inside it, which could allow\n * openlog(3) to reopen the syslog socket later */\n if(global_options.chroot_dir && stat(\"/dev/log\", &sb))\n log_close(SINK_OUTFILE);\n else\n#endif /* HAVE_CHROOT */\n log_close(SINK_SYSLOG|SINK_OUTFILE);\n /* there is no race condition here:\n * client threads are not allowed to use global options */\n options_free();\n options_apply();\n /* we hope that a sane openlog(3) implementation won't\n * attempt to reopen /dev/log if it's already open */\n log_open(SINK_SYSLOG|SINK_OUTFILE);\n log_flush(LOG_MODE_CONFIGURED);\n ui_config_reloaded();\n /* we use \"|\" instead of \"||\" to attempt initialization of both subsystems */\n if(bind_ports() | exec_connect_start()) {\n s_poll_sleep(delay/1000, delay%1000); /* sleep to avoid log trashing */\n signal_post(SIGNAL_RELOAD_CONFIG); /* retry */\n delay*=2;\n if(delay > 10000) /* 10s */\n delay=10000;\n } else {\n delay=10; /* 10ms */\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-295'], 'message': 'stunnel-5.57'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int node_is_equal_ex(xmlNodePtr node, char *name, char *ns)\n{\n\tif (name == NULL || strcmp((char*)node->name, name) == 0) {\n\t\tif (ns) {\n\t\t\txmlNsPtr nsPtr = node_find_ns(node);\n\t\t\tif (nsPtr) {\n\t\t\t\treturn (strcmp((char*)nsPtr->href, ns) == 0);\n\t\t\t} else {\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t}\n\t\treturn TRUE;\n\t}\n\treturn FALSE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fix bug #80672 - Null Dereference in SoapClient'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: rpmRC hdrblobRead(FD_t fd, int magic, int exact_size, rpmTagVal regionTag, hdrblob blob, char **emsg)\n{\n int32_t block[4];\n int32_t *bs = (magic != 0) ? &block[0] : &block[2];\n int blen = (magic != 0) ? sizeof(block) : sizeof(block) / 2;\n int32_t il;\n int32_t dl;\n int32_t * ei = NULL;\n size_t uc;\n size_t nb;\n rpmRC rc = RPMRC_FAIL;\t\t/* assume failure */\n int xx;\n int32_t il_max = HEADER_TAGS_MAX;\n int32_t dl_max = HEADER_DATA_MAX;\n\n if (regionTag == RPMTAG_HEADERSIGNATURES) {\n\til_max = 32;\n\tdl_max = 64 * 1024 * 1024;\n }\n\n memset(block, 0, sizeof(block));\n if ((xx = Freadall(fd, bs, blen)) != blen) {\n\trasprintf(emsg,\n\t\t_(\"hdr size(%d): BAD, read returned %d\"), blen, xx);\n\tgoto exit;\n }\n if (magic && memcmp(block, rpm_header_magic, sizeof(rpm_header_magic))) {\n\trasprintf(emsg, _(\"hdr magic: BAD\"));\n\tgoto exit;\n }\n il = ntohl(block[2]);\n if (hdrchkRange(il_max, il)) {\n\trasprintf(emsg, _(\"hdr tags: BAD, no. of tags(%d) out of range\"), il);\n\tgoto exit;\n }\n dl = ntohl(block[3]);\n if (hdrchkRange(dl_max, dl)) {\n\trasprintf(emsg, _(\"hdr data: BAD, no. of bytes(%d) out of range\"), dl);\n\tgoto exit;\n }\n\n nb = (il * sizeof(struct entryInfo_s)) + dl;\n uc = sizeof(il) + sizeof(dl) + nb;\n ei = xmalloc(uc);\n ei[0] = block[2];\n ei[1] = block[3];\n if ((xx = Freadall(fd, (char *)&ei[2], nb)) != nb) {\n\trasprintf(emsg, _(\"hdr blob(%zd): BAD, read returned %d\"), nb, xx);\n\tgoto exit;\n }\n\n if (regionTag == RPMTAG_HEADERSIGNATURES) {\n\tsize_t sigSize = uc + sizeof(rpm_header_magic);\n\tsize_t pad = (8 - (sigSize % 8)) % 8;\n\tsize_t trc;\n\tif (pad && (trc = Freadall(fd, block, pad)) != pad) {\n\t rasprintf(emsg, _(\"sigh pad(%zd): BAD, read %zd bytes\"), pad, trc);\n\t goto exit;\n\t}\n }\n\n rc = hdrblobInit(ei, uc, regionTag, exact_size, blob, emsg);\n\nexit:\n if (rc != RPMRC_OK) {\n\tfree(ei);\n\tblob->ei = NULL;\n\tif (emsg && *emsg && regionTag == RPMTAG_HEADERSIGNATURES) {\n\t /* rstrscat() cannot handle overlap even if it claims so */\n\t char *tmp = rstrscat(NULL, _(\"signature \"), *emsg, NULL);\n\t free(*emsg);\n\t *emsg = tmp;\n\t}\n }\n\n return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'hdrblobInit() needs bounds checks too\n\nUsers can pass untrusted data to hdrblobInit() and it must be robust\nagainst this.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: issuerAndThisUpdateCheck(\n\tstruct berval *in,\n\tstruct berval *is,\n\tstruct berval *tu,\n\tvoid *ctx )\n{\n\tint numdquotes = 0;\n\tstruct berval x = *in;\n\tstruct berval ni = BER_BVNULL;\n\t/* Parse GSER format */ \n\tenum {\n\t\tHAVE_NONE = 0x0,\n\t\tHAVE_ISSUER = 0x1,\n\t\tHAVE_THISUPDATE = 0x2,\n\t\tHAVE_ALL = ( HAVE_ISSUER | HAVE_THISUPDATE )\n\t} have = HAVE_NONE;\n\n\n\tif ( in->bv_len < STRLENOF( \"{issuer \\\"\\\",thisUpdate \\\"YYMMDDhhmmssZ\\\"}\" ) ) return LDAP_INVALID_SYNTAX;\n\n\tif ( in->bv_val[0] != '{' || in->bv_val[in->bv_len-1] != '}' ) {\n\t\treturn LDAP_INVALID_SYNTAX;\n\t}\n\n\tx.bv_val++;\n\tx.bv_len -= STRLENOF(\"{}\");\n\n\tdo {\n\t\t/* eat leading spaces */\n\t\tfor ( ; (x.bv_val[0] == ' ') && x.bv_len; x.bv_val++, x.bv_len-- ) {\n\t\t\t/* empty */;\n\t\t}\n\n\t\t/* should be at issuer or thisUpdate */\n\t\tif ( strncasecmp( x.bv_val, \"issuer\", STRLENOF(\"issuer\") ) == 0 ) {\n\t\t\tif ( have & HAVE_ISSUER ) return LDAP_INVALID_SYNTAX;\n\n\t\t\t/* parse issuer */\n\t\t\tx.bv_val += STRLENOF(\"issuer\");\n\t\t\tx.bv_len -= STRLENOF(\"issuer\");\n\n\t\t\tif ( x.bv_val[0] != ' ' ) return LDAP_INVALID_SYNTAX;\n\t\t\tx.bv_val++;\n\t\t\tx.bv_len--;\n\n\t\t\t/* eat leading spaces */\n\t\t\tfor ( ; (x.bv_val[0] == ' ') && x.bv_len; x.bv_val++, x.bv_len-- ) {\n\t\t\t\t/* empty */;\n\t\t\t}\n\n\t\t\t/* For backward compatibility, this part is optional */\n\t\t\tif ( strncasecmp( x.bv_val, \"rdnSequence:\", STRLENOF(\"rdnSequence:\") ) != 0 ) {\n\t\t\t\treturn LDAP_INVALID_SYNTAX;\n\t\t\t}\n\t\t\tx.bv_val += STRLENOF(\"rdnSequence:\");\n\t\t\tx.bv_len -= STRLENOF(\"rdnSequence:\");\n\n\t\t\tif ( x.bv_val[0] != '\"' ) return LDAP_INVALID_SYNTAX;\n\t\t\tx.bv_val++;\n\t\t\tx.bv_len--;\n\n\t\t\tis->bv_val = x.bv_val;\n\t\t\tis->bv_len = 0;\n\n\t\t\tfor ( ; is->bv_len < x.bv_len; ) {\n\t\t\t\tif ( is->bv_val[is->bv_len] != '\"' ) {\n\t\t\t\t\tis->bv_len++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif ( is->bv_val[is->bv_len+1] == '\"' ) {\n\t\t\t\t\t/* double dquote */\n\t\t\t\t\tnumdquotes++;\n\t\t\t\t\tis->bv_len += 2;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tx.bv_val += is->bv_len + 1;\n\t\t\tx.bv_len -= is->bv_len + 1;\n\n\t\t\thave |= HAVE_ISSUER;\n\n\t\t} else if ( strncasecmp( x.bv_val, \"thisUpdate\", STRLENOF(\"thisUpdate\") ) == 0 )\n\t\t{\n\t\t\tif ( have & HAVE_THISUPDATE ) return LDAP_INVALID_SYNTAX;\n\n\t\t\t/* parse thisUpdate */\n\t\t\tx.bv_val += STRLENOF(\"thisUpdate\");\n\t\t\tx.bv_len -= STRLENOF(\"thisUpdate\");\n\n\t\t\tif ( x.bv_val[0] != ' ' ) return LDAP_INVALID_SYNTAX;\n\t\t\tx.bv_val++;\n\t\t\tx.bv_len--;\n\n\t\t\t/* eat leading spaces */\n\t\t\tfor ( ; (x.bv_val[0] == ' ') && x.bv_len; x.bv_val++, x.bv_len-- ) {\n\t\t\t\t/* empty */;\n\t\t\t}\n\n\t\t\tif ( !x.bv_len || x.bv_val[0] != '\"' ) return LDAP_INVALID_SYNTAX;\n\t\t\tx.bv_val++;\n\t\t\tx.bv_len--;\n\n\t\t\ttu->bv_val = x.bv_val;\n\t\t\ttu->bv_len = 0;\n\n\t\t\tfor ( ; tu->bv_len < x.bv_len; tu->bv_len++ ) {\n\t\t\t\tif ( tu->bv_val[tu->bv_len] == '\"' ) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tx.bv_val += tu->bv_len + 1;\n\t\t\tx.bv_len -= tu->bv_len + 1;\n\n\t\t\thave |= HAVE_THISUPDATE;\n\n\t\t} else {\n\t\t\treturn LDAP_INVALID_SYNTAX;\n\t\t}\n\n\t\t/* eat leading spaces */\n\t\tfor ( ; (x.bv_val[0] == ' ') && x.bv_len; x.bv_val++, x.bv_len-- ) {\n\t\t\t/* empty */;\n\t\t}\n\n\t\tif ( have == HAVE_ALL ) {\n\t\t\tbreak;\n\t\t}\n\n\t\tif ( x.bv_val[0] != ',' ) {\n\t\t\treturn LDAP_INVALID_SYNTAX;\n\t\t}\n\n\t\tx.bv_val++;\n\t\tx.bv_len--;\n\t} while ( 1 );\n\n\t/* should have no characters left... */\n\tif ( x.bv_len ) return LDAP_INVALID_SYNTAX;\n\n\tif ( numdquotes == 0 ) {\n\t\tber_dupbv_x( &ni, is, ctx );\n\n\t} else {\n\t\tber_len_t src, dst;\n\n\t\tni.bv_len = is->bv_len - numdquotes;\n\t\tni.bv_val = ber_memalloc_x( ni.bv_len + 1, ctx );\n\t\tfor ( src = 0, dst = 0; src < is->bv_len; src++, dst++ ) {\n\t\t\tif ( is->bv_val[src] == '\"' ) {\n\t\t\t\tsrc++;\n\t\t\t}\n\t\t\tni.bv_val[dst] = is->bv_val[src];\n\t\t}\n\t\tni.bv_val[dst] = '\\0';\n\t}\n\t\t\n\t*is = ni;\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617'], 'message': 'ITS#9454 fix issuerAndThisUpdateCheck'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int iscsi_conn_get_addr_param(struct sockaddr_storage *addr,\n\t\t\t enum iscsi_param param, char *buf)\n{\n\tstruct sockaddr_in6 *sin6 = NULL;\n\tstruct sockaddr_in *sin = NULL;\n\tint len;\n\n\tswitch (addr->ss_family) {\n\tcase AF_INET:\n\t\tsin = (struct sockaddr_in *)addr;\n\t\tbreak;\n\tcase AF_INET6:\n\t\tsin6 = (struct sockaddr_in6 *)addr;\n\t\tbreak;\n\tdefault:\n\t\treturn -EINVAL;\n\t}\n\n\tswitch (param) {\n\tcase ISCSI_PARAM_CONN_ADDRESS:\n\tcase ISCSI_HOST_PARAM_IPADDRESS:\n\t\tif (sin)\n\t\t\tlen = sprintf(buf, \"%pI4\\n\", &sin->sin_addr.s_addr);\n\t\telse\n\t\t\tlen = sprintf(buf, \"%pI6\\n\", &sin6->sin6_addr);\n\t\tbreak;\n\tcase ISCSI_PARAM_CONN_PORT:\n\tcase ISCSI_PARAM_LOCAL_PORT:\n\t\tif (sin)\n\t\t\tlen = sprintf(buf, \"%hu\\n\", be16_to_cpu(sin->sin_port));\n\t\telse\n\t\t\tlen = sprintf(buf, \"%hu\\n\",\n\t\t\t\t be16_to_cpu(sin6->sin6_port));\n\t\tbreak;\n\tdefault:\n\t\treturn -EINVAL;\n\t}\n\n\treturn len;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'scsi: iscsi: Ensure sysfs attributes are limited to PAGE_SIZE\n\nAs the iSCSI parameters are exported back through sysfs, it should be\nenforcing that they never are more than PAGE_SIZE (which should be more\nthan enough) before accepting updates through netlink.\n\nChange all iSCSI sysfs attributes to use sysfs_emit().\n\nCc: stable@vger.kernel.org\nReported-by: Adam Nichols \nReviewed-by: Lee Duncan \nReviewed-by: Greg Kroah-Hartman \nReviewed-by: Mike Christie \nSigned-off-by: Chris Leech \nSigned-off-by: Martin K. Petersen '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void __guc_ads_init(struct intel_guc *guc)\n{\n\tstruct intel_gt *gt = guc_to_gt(guc);\n\tstruct __guc_ads_blob *blob = guc->ads_blob;\n\tconst u32 skipped_size = LRC_PPHWSP_SZ * PAGE_SIZE + LR_HW_CONTEXT_SIZE;\n\tu32 base;\n\tu8 engine_class;\n\n\t/* GuC scheduling policies */\n\tguc_policies_init(&blob->policies);\n\n\t/*\n\t * GuC expects a per-engine-class context image and size\n\t * (minus hwsp and ring context). The context image will be\n\t * used to reinitialize engines after a reset. It must exist\n\t * and be pinned in the GGTT, so that the address won't change after\n\t * we have told GuC where to find it. The context size will be used\n\t * to validate that the LRC base + size fall within allowed GGTT.\n\t */\n\tfor (engine_class = 0; engine_class <= MAX_ENGINE_CLASS; ++engine_class) {\n\t\tif (engine_class == OTHER_CLASS)\n\t\t\tcontinue;\n\t\t/*\n\t\t * TODO: Set context pointer to default state to allow\n\t\t * GuC to re-init guilty contexts after internal reset.\n\t\t */\n\t\tblob->ads.golden_context_lrca[engine_class] = 0;\n\t\tblob->ads.eng_state_size[engine_class] =\n\t\t\tintel_engine_context_size(guc_to_gt(guc),\n\t\t\t\t\t\t engine_class) -\n\t\t\tskipped_size;\n\t}\n\n\t/* System info */\n\tblob->system_info.slice_enabled = hweight8(gt->info.sseu.slice_mask);\n\tblob->system_info.rcs_enabled = 1;\n\tblob->system_info.bcs_enabled = 1;\n\n\tblob->system_info.vdbox_enable_mask = VDBOX_MASK(gt);\n\tblob->system_info.vebox_enable_mask = VEBOX_MASK(gt);\n\tblob->system_info.vdbox_sfc_support_mask = gt->info.vdbox_sfc_access;\n\n\tbase = intel_guc_ggtt_offset(guc, guc->ads_vma);\n\n\t/* Clients info */\n\tguc_ct_pool_entries_init(blob->ct_pool, ARRAY_SIZE(blob->ct_pool));\n\n\tblob->clients_info.clients_num = 1;\n\tblob->clients_info.ct_pool_addr = base + ptr_offset(blob, ct_pool);\n\tblob->clients_info.ct_pool_count = ARRAY_SIZE(blob->ct_pool);\n\n\t/* ADS */\n\tblob->ads.scheduler_policies = base + ptr_offset(blob, policies);\n\tblob->ads.reg_state_buffer = base + ptr_offset(blob, reg_state_buffer);\n\tblob->ads.reg_state_addr = base + ptr_offset(blob, reg_state);\n\tblob->ads.gt_system_info = base + ptr_offset(blob, system_info);\n\tblob->ads.clients_info = base + ptr_offset(blob, clients_info);\n\n\ti915_gem_object_flush_map(guc->ads_vma->obj);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-190'], 'message': 'drm/i915/guc: Update to use firmware v49.0.1\n\nThe latest GuC firmware includes a number of interface changes that\nrequire driver updates to match.\n\n* Starting from Gen11, the ID to be provided to GuC needs to contain\n the engine class in bits [0..2] and the instance in bits [3..6].\n\n NOTE: this patch breaks pointer dereferences in some existing GuC\n functions that use the guc_id to dereference arrays but these functions\n are not used for now as we have GuC submission disabled and we will\n update these functions in follow up patch which requires new IDs.\n\n* The new GuC requires the additional data structure (ADS) and associated\n 'private_data' pointer to be setup. This is basically a scratch area\n of memory that the GuC owns. The size is read from the CSS header.\n\n* There is now a physical to logical engine mapping table in the ADS\n which needs to be configured in order for the firmware to load. For\n now, the table is initialised with a 1 to 1 mapping.\n\n* GUC_CTL_CTXINFO has been removed from the initialization params.\n\n* reg_state_buffer is maintained internally by the GuC as part of\n the private data.\n\n* The ADS layout has changed significantly. This patch updates the\n shared structure and also adds better documentation of the layout.\n\n* While i915 does not use GuC doorbells, the firmware now requires\n that some initialisation is done.\n\n* The number of engine classes and instances supported in the ADS has\n been increased.\n\nSigned-off-by: John Harrison \nSigned-off-by: Matthew Brost \nSigned-off-by: Daniele Ceraolo Spurio \nSigned-off-by: Oscar Mateo \nSigned-off-by: Michel Thierry \nSigned-off-by: Rodrigo Vivi \nSigned-off-by: Michal Wajdeczko \nCc: Michal Winiarski \nCc: Tomasz Lis \nCc: Joonas Lahtinen \nReviewed-by: Daniele Ceraolo Spurio \nSigned-off-by: Joonas Lahtinen \nLink: https://patchwork.freedesktop.org/patch/msgid/20201028145826.2949180-2-John.C.Harrison@Intel.com'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void t2p_read_tiff_size(T2P* t2p, TIFF* input){\n\n\tuint64* sbc=NULL;\n#if defined(JPEG_SUPPORT) || defined (OJPEG_SUPPORT)\n\tunsigned char* jpt=NULL;\n\ttstrip_t i=0;\n\ttstrip_t stripcount=0;\n#endif\n uint64 k = 0;\n\n\tif(t2p->pdf_transcode == T2P_TRANSCODE_RAW){\n#ifdef CCITT_SUPPORT\n\t\tif(t2p->pdf_compression == T2P_COMPRESS_G4 ){\n\t\t\tTIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc);\n if (sbc[0] != (uint64)(tmsize_t)sbc[0]) {\n TIFFError(TIFF2PDF_MODULE, \"Integer overflow\");\n t2p->t2p_error = T2P_ERR_ERROR;\n }\n\t\t\tt2p->tiff_datasize=(tmsize_t)sbc[0];\n\t\t\treturn;\n\t\t}\n#endif\n#ifdef ZIP_SUPPORT\n\t\tif(t2p->pdf_compression == T2P_COMPRESS_ZIP){\n\t\t\tTIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc);\n if (sbc[0] != (uint64)(tmsize_t)sbc[0]) {\n TIFFError(TIFF2PDF_MODULE, \"Integer overflow\");\n t2p->t2p_error = T2P_ERR_ERROR;\n }\n\t\t\tt2p->tiff_datasize=(tmsize_t)sbc[0];\n\t\t\treturn;\n\t\t}\n#endif\n#ifdef OJPEG_SUPPORT\n\t\tif(t2p->tiff_compression == COMPRESSION_OJPEG){\n\t\t\tif(!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc)){\n\t\t\t\tTIFFError(TIFF2PDF_MODULE, \n\t\t\t\t\t\"Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS\",\n\t\t\t\t\tTIFFFileName(input));\n\t\t\t\tt2p->t2p_error = T2P_ERR_ERROR;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tstripcount=TIFFNumberOfStrips(input);\n\t\t\tfor(i=0;itiff_dataoffset))){\n\t\t\t\tif(t2p->tiff_dataoffset != 0){\n\t\t\t\t\tif(TIFFGetField(input, TIFFTAG_JPEGIFBYTECOUNT, &(t2p->tiff_datasize))!=0){\n\t\t\t\t\t\tif((uint64)t2p->tiff_datasize < k) {\n\t\t\t\t\t\t\tTIFFWarning(TIFF2PDF_MODULE, \n\t\t\t\t\t\t\t\t\"Input file %s has short JPEG interchange file byte count\", \n\t\t\t\t\t\t\t\tTIFFFileName(input));\n\t\t\t\t\t\t\tt2p->pdf_ojpegiflength=t2p->tiff_datasize;\n\t\t\t\t\t\t\tk = checkAdd64(k, t2p->tiff_datasize, t2p);\n\t\t\t\t\t\t\tk = checkAdd64(k, 6, t2p);\n\t\t\t\t\t\t\tk = checkAdd64(k, stripcount, t2p);\n\t\t\t\t\t\t\tk = checkAdd64(k, stripcount, t2p);\n\t\t\t\t\t\t\tt2p->tiff_datasize = (tsize_t) k;\n\t\t\t\t\t\t\tif ((uint64) t2p->tiff_datasize != k) {\n\t\t\t\t\t\t\t\tTIFFError(TIFF2PDF_MODULE, \"Integer overflow\");\n\t\t\t\t\t\t\t\tt2p->t2p_error = T2P_ERR_ERROR;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}else {\n\t\t\t\t\t\tTIFFError(TIFF2PDF_MODULE, \n\t\t\t\t\t\t\t\"Input file %s missing field: TIFFTAG_JPEGIFBYTECOUNT\",\n\t\t\t\t\t\t\tTIFFFileName(input));\n\t\t\t\t\t\t\tt2p->t2p_error = T2P_ERR_ERROR;\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tk = checkAdd64(k, stripcount, t2p);\n\t\t\tk = checkAdd64(k, stripcount, t2p);\n\t\t\tk = checkAdd64(k, 2048, t2p);\n\t\t\tt2p->tiff_datasize = (tsize_t) k;\n\t\t\tif ((uint64) t2p->tiff_datasize != k) {\n\t\t\t\tTIFFError(TIFF2PDF_MODULE, \"Integer overflow\");\n\t\t\t\tt2p->t2p_error = T2P_ERR_ERROR;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n#endif\n#ifdef JPEG_SUPPORT\n\t\tif(t2p->tiff_compression == COMPRESSION_JPEG) {\n\t\t\tuint32 count = 0;\n\t\t\tif(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0 ){\n\t\t\t\tif(count > 4){\n\t\t\t\t\tk += count;\n\t\t\t\t\tk -= 2; /* don't use EOI of header */\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tk = 2; /* SOI for first strip */\n\t\t\t}\n\t\t\tstripcount=TIFFNumberOfStrips(input);\n\t\t\tif(!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc)){\n\t\t\t\tTIFFError(TIFF2PDF_MODULE, \n\t\t\t\t\t\"Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS\",\n\t\t\t\t\tTIFFFileName(input));\n\t\t\t\tt2p->t2p_error = T2P_ERR_ERROR;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfor(i=0;itiff_datasize = (tsize_t) k;\n\t\t\tif ((uint64) t2p->tiff_datasize != k) {\n\t\t\t\tTIFFError(TIFF2PDF_MODULE, \"Integer overflow\");\n\t\t\t\tt2p->t2p_error = T2P_ERR_ERROR;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n#endif\n\t\t(void) 0;\n\t}\n\tk = checkMultiply64(TIFFScanlineSize(input), t2p->tiff_length, t2p);\n\tif(t2p->tiff_planar==PLANARCONFIG_SEPARATE){\n\t\tk = checkMultiply64(k, t2p->tiff_samplesperpixel, t2p);\n\t}\n\tif (k == 0) {\n\t\t/* Assume we had overflow inside TIFFScanlineSize */\n\t\tt2p->t2p_error = T2P_ERR_ERROR;\n\t}\n\n\tt2p->tiff_datasize = (tsize_t) k;\n\tif ((uint64) t2p->tiff_datasize != k) {\n\t\tTIFFError(TIFF2PDF_MODULE, \"Integer overflow\");\n\t\tt2p->t2p_error = T2P_ERR_ERROR;\n\t}\n\n\treturn;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'tiff2pdf.c: properly calculate datasize when saving to JPEG YCbCr\n\nfixes #220'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void *zmalloc_no_tcache(size_t size) {\n void *ptr = mallocx(size+PREFIX_SIZE, MALLOCX_TCACHE_NONE);\n if (!ptr) zmalloc_oom_handler(size);\n update_zmalloc_stat_alloc(zmalloc_size(ptr));\n return ptr;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix integer overflow (CVE-2021-21309). (#8522)\n\nOn 32-bit systems, setting the proto-max-bulk-len config parameter to a high value may result with integer overflow and a subsequent heap overflow when parsing an input bulk (CVE-2021-21309).\r\n\r\nThis fix has two parts:\r\n\r\nSet a reasonable limit to the config parameter.\r\nAdd additional checks to prevent the problem in other potential but unknown code paths.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline void net_tx_pkt_sendv(struct NetTxPkt *pkt,\n NetClientState *nc, const struct iovec *iov, int iov_cnt)\n{\n if (pkt->is_loopback) {\n nc->info->receive_iov(nc, iov, iov_cnt);\n } else {\n qemu_sendv_packet(nc, iov, iov_cnt);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': 'tx_pkt: switch to use qemu_receive_packet_iov() for loopback\n\nThis patch switches to use qemu_receive_receive_iov() which can detect\nreentrancy and return early.\n\nThis is intended to address CVE-2021-3416.\n\nCc: Prasad J Pandit \nCc: qemu-stable@nongnu.org\nReviewed-by: Philippe Mathieu-Daud\u00e9 \nSigned-off-by: Jason Wang '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void lo_write_buf(fuse_req_t req, fuse_ino_t ino,\n struct fuse_bufvec *in_buf, off_t off,\n struct fuse_file_info *fi)\n{\n (void)ino;\n ssize_t res;\n struct fuse_bufvec out_buf = FUSE_BUFVEC_INIT(fuse_buf_size(in_buf));\n bool cap_fsetid_dropped = false;\n\n out_buf.buf[0].flags = FUSE_BUF_IS_FD | FUSE_BUF_FD_SEEK;\n out_buf.buf[0].fd = lo_fi_fd(req, fi);\n out_buf.buf[0].pos = off;\n\n fuse_log(FUSE_LOG_DEBUG,\n \"lo_write_buf(ino=%\" PRIu64 \", size=%zd, off=%lu kill_priv=%d)\\n\",\n ino, out_buf.buf[0].size, (unsigned long)off, fi->kill_priv);\n\n /*\n * If kill_priv is set, drop CAP_FSETID which should lead to kernel\n * clearing setuid/setgid on file. Note, for WRITE, we need to do\n * this even if killpriv_v2 is not enabled. fuse direct write path\n * relies on this.\n */\n if (fi->kill_priv) {\n res = drop_effective_cap(\"FSETID\", &cap_fsetid_dropped);\n if (res != 0) {\n fuse_reply_err(req, res);\n return;\n }\n }\n\n res = fuse_buf_copy(&out_buf, in_buf);\n if (res < 0) {\n fuse_reply_err(req, -res);\n } else {\n fuse_reply_write(req, (size_t)res);\n }\n\n if (cap_fsetid_dropped) {\n res = gain_effective_cap(\"FSETID\");\n if (res) {\n fuse_log(FUSE_LOG_ERR, \"Failed to gain CAP_FSETID\\n\");\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-281'], 'message': 'virtiofs: drop remapped security.capability xattr as needed\n\nOn Linux, the 'security.capability' xattr holds a set of\ncapabilities that can change when an executable is run, giving\na limited form of privilege escalation to those programs that\nthe writer of the file deemed worthy.\n\nAny write causes the 'security.capability' xattr to be dropped,\nstopping anyone from gaining privilege by modifying a blessed\nfile.\n\nFuse relies on the daemon to do this dropping, and in turn the\ndaemon relies on the host kernel to drop the xattr for it. However,\nwith the addition of -o xattrmap, the xattr that the guest\nstores its capabilities in is now not the same as the one that\nthe host kernel automatically clears.\n\nWhere the mapping changes 'security.capability', explicitly clear\nthe remapped name to preserve the same behaviour.\n\nThis bug is assigned CVE-2021-20263.\n\nSigned-off-by: Dr. David Alan Gilbert \nReviewed-by: Vivek Goyal '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: _decodeStripYCbCr(Imaging im, ImagingCodecState state, TIFF *tiff) {\n // To avoid dealing with YCbCr subsampling, let libtiff handle it\n // Use a TIFFRGBAImage wrapping the tiff image, and let libtiff handle\n // all of the conversion. Metadata read from the TIFFRGBAImage could\n // be different from the metadata that the base tiff returns.\n\n INT32 strip_row;\n UINT8 *new_data;\n UINT32 rows_per_strip, row_byte_size, rows_to_read;\n int ret;\n TIFFRGBAImage img;\n char emsg[1024] = \"\";\n\n ret = TIFFGetFieldDefaulted(tiff, TIFFTAG_ROWSPERSTRIP, &rows_per_strip);\n if (ret != 1) {\n rows_per_strip = state->ysize;\n }\n TRACE((\"RowsPerStrip: %u \\n\", rows_per_strip));\n\n if (!(TIFFRGBAImageOK(tiff, emsg) && TIFFRGBAImageBegin(&img, tiff, 0, emsg))) {\n TRACE((\"Decode error, msg: %s\", emsg));\n state->errcode = IMAGING_CODEC_BROKEN;\n // nothing to clean up, just return\n return -1;\n }\n\n img.req_orientation = ORIENTATION_TOPLEFT;\n img.col_offset = 0;\n\n if (state->xsize != img.width || state->ysize != img.height) {\n TRACE(\n (\"Inconsistent Image Error: %d =? %d, %d =? %d\",\n state->xsize,\n img.width,\n state->ysize,\n img.height));\n state->errcode = IMAGING_CODEC_BROKEN;\n goto decodeycbcr_err;\n }\n\n /* overflow check for row byte size */\n if (INT_MAX / 4 < img.width) {\n state->errcode = IMAGING_CODEC_MEMORY;\n goto decodeycbcr_err;\n }\n\n // TiffRGBAImages are 32bits/pixel.\n row_byte_size = img.width * 4;\n\n /* overflow check for realloc */\n if (INT_MAX / row_byte_size < rows_per_strip) {\n state->errcode = IMAGING_CODEC_MEMORY;\n goto decodeycbcr_err;\n }\n\n state->bytes = rows_per_strip * row_byte_size;\n\n TRACE((\"StripSize: %d \\n\", state->bytes));\n\n /* realloc to fit whole strip */\n /* malloc check above */\n new_data = realloc(state->buffer, state->bytes);\n if (!new_data) {\n state->errcode = IMAGING_CODEC_MEMORY;\n goto decodeycbcr_err;\n }\n\n state->buffer = new_data;\n\n for (; state->y < state->ysize; state->y += rows_per_strip) {\n img.row_offset = state->y;\n rows_to_read = min(rows_per_strip, img.height - state->y);\n\n if (TIFFRGBAImageGet(&img, (UINT32 *)state->buffer, img.width, rows_to_read) ==\n -1) {\n TRACE((\"Decode Error, y: %d\\n\", state->y));\n state->errcode = IMAGING_CODEC_BROKEN;\n goto decodeycbcr_err;\n }\n\n TRACE((\"Decoded strip for row %d \\n\", state->y));\n\n // iterate over each row in the strip and stuff data into image\n for (strip_row = 0;\n strip_row < min((INT32)rows_per_strip, state->ysize - state->y);\n strip_row++) {\n TRACE((\"Writing data into line %d ; \\n\", state->y + strip_row));\n\n // UINT8 * bbb = state->buffer + strip_row * (state->bytes /\n // rows_per_strip); TRACE((\"chars: %x %x %x %x\\n\", ((UINT8 *)bbb)[0],\n // ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3]));\n\n state->shuffle(\n (UINT8 *)im->image[state->y + state->yoff + strip_row] +\n state->xoff * im->pixelsize,\n state->buffer + strip_row * row_byte_size,\n state->xsize);\n }\n }\n\ndecodeycbcr_err:\n TIFFRGBAImageEnd(&img);\n if (state->errcode != 0) {\n return -1;\n }\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Incorrect error code checking in TiffDecode.c\n\n* since Pillow 8.1.0\n* CVE-2021-25289'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: virtual Status explain(OperationContext* opCtx,\n const std::string& dbname,\n const BSONObj& cmdObj,\n ExplainOptions::Verbosity verbosity,\n BSONObjBuilder* out) const {\n const bool isExplain = true;\n Lock::DBLock dbLock(opCtx, dbname, MODE_IS);\n auto nss = parseNsOrUUID(opCtx, dbname, cmdObj);\n auto request = CountRequest::parseFromBSON(nss, cmdObj, isExplain);\n if (!request.isOK()) {\n return request.getStatus();\n }\n\n // Acquire the db read lock.\n AutoGetCollectionOrViewForReadCommand ctx(\n opCtx, request.getValue().getNs(), std::move(dbLock));\n Collection* collection = ctx.getCollection();\n\n if (ctx.getView()) {\n ctx.releaseLocksForView();\n\n auto viewAggregation = request.getValue().asAggregationCommand();\n if (!viewAggregation.isOK()) {\n return viewAggregation.getStatus();\n }\n\n auto viewAggRequest = AggregationRequest::parseFromBSON(\n request.getValue().getNs(), viewAggregation.getValue(), verbosity);\n if (!viewAggRequest.isOK()) {\n return viewAggRequest.getStatus();\n }\n\n return runAggregate(opCtx,\n viewAggRequest.getValue().getNamespaceString(),\n viewAggRequest.getValue(),\n viewAggregation.getValue(),\n *out);\n }\n\n // Prevent chunks from being cleaned up during yields - this allows us to only check the\n // version on initial entry into count.\n auto rangePreserver =\n CollectionShardingState::get(opCtx, request.getValue().getNs())->getMetadata();\n\n auto statusWithPlanExecutor = getExecutorCount(opCtx,\n collection,\n request.getValue(),\n true, // explain\n PlanExecutor::YIELD_AUTO);\n if (!statusWithPlanExecutor.isOK()) {\n return statusWithPlanExecutor.getStatus();\n }\n\n auto exec = std::move(statusWithPlanExecutor.getValue());\n\n Explain::explainStages(exec.get(), collection, verbosity, out);\n return Status::OK();\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'SERVER-38275 ban explain with UUID'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static pj_status_t dlg_create_request_throw( pjsip_dialog *dlg,\n\t\t\t\t\t const pjsip_method *method,\n\t\t\t\t\t int cseq,\n\t\t\t\t\t pjsip_tx_data **p_tdata )\n{\n pjsip_tx_data *tdata;\n pjsip_contact_hdr *contact;\n pjsip_route_hdr *route, *end_list;\n pj_status_t status;\n\n /* Contact Header field.\n * Contact can only be present in requests that establish dialog (in the\n * core SIP spec, only INVITE).\n */\n if (pjsip_method_creates_dialog(method))\n\tcontact = dlg->local.contact;\n else\n\tcontact = NULL;\n\n /*\n * Create the request by cloning from the headers in the\n * dialog.\n */\n status = pjsip_endpt_create_request_from_hdr(dlg->endpt,\n\t\t\t\t\t\t method,\n\t\t\t\t\t\t dlg->target,\n\t\t\t\t\t\t dlg->local.info,\n\t\t\t\t\t\t dlg->remote.info,\n\t\t\t\t\t\t contact,\n\t\t\t\t\t\t dlg->call_id,\n\t\t\t\t\t\t cseq,\n\t\t\t\t\t\t NULL,\n\t\t\t\t\t\t &tdata);\n if (status != PJ_SUCCESS)\n\treturn status;\n\n /* Put this dialog in tdata's mod_data */\n tdata->mod_data[dlg->ua->id] = dlg;\n\n /* Just copy dialog route-set to Route header.\n * The transaction will do the processing as specified in Section 12.2.1\n * of RFC 3261 in function tsx_process_route() in sip_transaction.c.\n */\n route = dlg->route_set.next;\n end_list = &dlg->route_set;\n for (; route != end_list; route = route->next ) {\n\tpjsip_route_hdr *r;\n\tr = (pjsip_route_hdr*) pjsip_hdr_shallow_clone( tdata->pool, route );\n\tpjsip_routing_hdr_set_route(r);\n\tpjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)r);\n }\n\n /* Copy authorization headers, if request is not ACK or CANCEL. */\n if (method->id != PJSIP_ACK_METHOD && method->id != PJSIP_CANCEL_METHOD) {\n\tstatus = pjsip_auth_clt_init_req( &dlg->auth_sess, tdata );\n\tif (status != PJ_SUCCESS)\n\t return status;\n }\n\n /* Done. */\n *p_tdata = tdata;\n\n return PJ_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-297', 'CWE-295'], 'message': 'Merge pull request from GHSA-8hcp-hm38-mfph\n\n* Check hostname during TLS transport selection\n\n* revision based on feedback\n\n* remove the code in create_request that has been moved'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: MultiPartInputFile::initialize()\n{\n readMagicNumberAndVersionField(*_data->is, _data->version);\n \n bool multipart = isMultiPart(_data->version);\n bool tiled = isTiled(_data->version);\n\n //\n // Multipart files don't have and shouldn't have the tiled bit set.\n //\n\n if (tiled && multipart)\n throw IEX_NAMESPACE::InputExc (\"Multipart files cannot have the tiled bit set\");\n\n \n int pos = 0;\n while (true)\n {\n Header header;\n header.readFrom(*_data->is, _data->version);\n\n //\n // If we read nothing then we stop reading.\n //\n\n if (header.readsNothing())\n {\n pos++;\n break;\n }\n\n _data->_headers.push_back(header);\n \n if(multipart == false)\n break;\n }\n\n //\n // Perform usual check on headers.\n //\n\n for (size_t i = 0; i < _data->_headers.size(); i++)\n {\n //\n // Silently invent a type if the file is a single part regular image.\n //\n\n if( _data->_headers[i].hasType() == false )\n {\n if(multipart)\n\n throw IEX_NAMESPACE::ArgExc (\"Every header in a multipart file should have a type\");\n \n _data->_headers[i].setType(tiled ? TILEDIMAGE : SCANLINEIMAGE);\n }\n else\n {\n \n //\n // Silently fix the header type if it's wrong\n // (happens when a regular Image file written by EXR_2.0 is rewritten by an older library,\n // so doesn't effect deep image types)\n //\n\n if(!multipart && !isNonImage(_data->version))\n {\n _data->_headers[i].setType(tiled ? TILEDIMAGE : SCANLINEIMAGE);\n }\n }\n \n\n \n if( _data->_headers[i].hasName() == false )\n {\n if(multipart)\n throw IEX_NAMESPACE::ArgExc (\"Every header in a multipart file should have a name\");\n }\n \n if (isTiled(_data->_headers[i].type()))\n _data->_headers[i].sanityCheck(true, multipart);\n else\n _data->_headers[i].sanityCheck(false, multipart);\n }\n\n //\n // Check name uniqueness.\n //\n\n if (multipart)\n {\n set names;\n for (size_t i = 0; i < _data->_headers.size(); i++)\n {\n \n if (names.find(_data->_headers[i].name()) != names.end())\n {\n throw IEX_NAMESPACE::InputExc (\"Header name \" + _data->_headers[i].name() +\n \" is not a unique name.\");\n }\n names.insert(_data->_headers[i].name());\n }\n }\n \n //\n // Check shared attributes compliance.\n //\n\n if (multipart && strictSharedAttribute)\n {\n for (size_t i = 1; i < _data->_headers.size(); i++)\n {\n vector attrs;\n if (_data->checkSharedAttributesValues (_data->_headers[0], _data->_headers[i], attrs))\n {\n string attrNames;\n for (size_t j=0; j_headers[i].name() +\n \" has non-conforming shared attributes: \"+\n attrNames);\n }\n }\n }\n\n //\n // Create InputParts and read chunk offset tables.\n //\n \n for (size_t i = 0; i < _data->_headers.size(); i++)\n _data->parts.push_back(\n new InputPartData(_data, _data->_headers[i], i, _data->numThreads, _data->version));\n\n _data->readChunkOffsetTables(_data->reconstructChunkOffsetTable);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'add sanity check for reading multipart files with no parts (#840)\n\nSigned-off-by: Peter Hillman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: l_int32 main(int argc,\n char **argv)\n{\nL_DEWARP *dew1, *dew2;\nL_DEWARPA *dewa;\nPIX *pixs, *pixn, *pixg, *pixb, *pixd, *pixt1, *pixt2;\nPIX *pixs2, *pixn2, *pixg2, *pixb2, *pixd2;\n\n setLeptDebugOK(1);\n lept_mkdir(\"lept/model\");\n\n/* pixs = pixRead(\"1555.007.jpg\"); */\n pixs = pixRead(\"cat.035.jpg\");\n/* pixs = pixRead(\"cat.010.jpg\"); */\n\n /* Normalize for varying background and binarize */\n pixn = pixBackgroundNormSimple(pixs, NULL, NULL);\n pixg = pixConvertRGBToGray(pixn, 0.5, 0.3, 0.2);\n pixb = pixThresholdToBinary(pixg, 130);\n\n /* Run the basic functions */\n dewa = dewarpaCreate(2, 30, 1, 10, 30);\n dewarpaUseBothArrays(dewa, 1);\n dew1 = dewarpCreate(pixb, 35);\n dewarpaInsertDewarp(dewa, dew1);\n dewarpBuildPageModel(dew1, \"/tmp/lept/model/dewarp_model1.pdf\");\n dewarpaApplyDisparity(dewa, 35, pixg, 200, 0, 0, &pixd,\n \"/tmp/lept/model/dewarp_apply1.pdf\");\n\n /* Write out some of the files to be imaged */\n lept_rmdir(\"lept/dewtest\");\n lept_mkdir(\"lept/dewtest\");\n pixWrite(\"/tmp/lept/dewtest/001.jpg\", pixs, IFF_JFIF_JPEG);\n pixWrite(\"/tmp/lept/dewtest/002.jpg\", pixn, IFF_JFIF_JPEG);\n pixWrite(\"/tmp/lept/dewtest/003.jpg\", pixg, IFF_JFIF_JPEG);\n pixWrite(\"/tmp/lept/dewtest/004.png\", pixb, IFF_TIFF_G4);\n pixWrite(\"/tmp/lept/dewtest/005.jpg\", pixd, IFF_JFIF_JPEG);\n pixt1 = pixRead(\"/tmp/lept/dewmod/0020.png\");\n pixWrite(\"/tmp/lept/dewtest/006.png\", pixt1, IFF_PNG);\n pixDestroy(&pixt1);\n pixt1 = pixRead(\"/tmp/lept/dewmod/0030.png\");\n pixWrite(\"/tmp/lept/dewtest/007.png\", pixt1, IFF_PNG);\n pixDestroy(&pixt1);\n pixt1 = pixRead(\"/tmp/lept/dewmod/0060.png\");\n pixWrite(\"/tmp/lept/dewtest/008.png\", pixt1, IFF_PNG);\n pixDestroy(&pixt1);\n pixt1 = pixRead(\"/tmp/lept/dewmod/0070.png\");\n pixWrite(\"/tmp/lept/dewtest/009.png\", pixt1, IFF_PNG);\n pixDestroy(&pixt1);\n pixt1 = pixRead(\"/tmp/lept/dewapply/002.png\");\n pixWrite(\"/tmp/lept/dewtest/010.png\", pixt1, IFF_PNG);\n pixDestroy(&pixt1);\n pixt1 = pixRead(\"/tmp/lept/dewapply/003.png\");\n pixWrite(\"/tmp/lept/dewtest/011.png\", pixt1, IFF_PNG);\n pixt2 = pixThresholdToBinary(pixt1, 130);\n pixWrite(\"/tmp/lept/dewtest/012.png\", pixt2, IFF_TIFF_G4);\n pixDestroy(&pixt1);\n pixDestroy(&pixt2);\n pixt1 = pixRead(\"/tmp/lept/dewmod/0041.png\");\n pixWrite(\"/tmp/lept/dewtest/013.png\", pixt1, IFF_PNG);\n pixDestroy(&pixt1);\n pixt1 = pixRead(\"/tmp/lept/dewmod/0042.png\");\n pixWrite(\"/tmp/lept/dewtest/014.png\", pixt1, IFF_PNG);\n pixDestroy(&pixt1);\n pixt1 = pixRead(\"/tmp/lept/dewmod/0051.png\");\n pixWrite(\"/tmp/lept/dewtest/015.png\", pixt1, IFF_PNG);\n pixDestroy(&pixt1);\n pixt1 = pixRead(\"/tmp/lept/dewmod/0052.png\");\n pixWrite(\"/tmp/lept/dewtest/016.png\", pixt1, IFF_PNG);\n pixDestroy(&pixt1);\n\n /* Normalize another image, that may not have enough textlines\n * to build an accurate model */\n/* pixs2 = pixRead(\"1555.003.jpg\"); */\n pixs2 = pixRead(\"cat.007.jpg\");\n/* pixs2 = pixRead(\"cat.014.jpg\"); */\n pixn2 = pixBackgroundNormSimple(pixs2, NULL, NULL);\n pixg2 = pixConvertRGBToGray(pixn2, 0.5, 0.3, 0.2);\n pixb2 = pixThresholdToBinary(pixg2, 130);\n\n /* Apply the previous disparity model to this image */\n dew2 = dewarpCreate(pixb2, 7);\n dewarpaInsertDewarp(dewa, dew2);\n dewarpaInsertRefModels(dewa, 0, 1);\n dewarpaInfo(stderr, dewa);\n dewarpaApplyDisparity(dewa, 7, pixg2, 200, 0, 0, &pixd2,\n \"/tmp/lept/model/dewarp_apply2.pdf\");\n dewarpaDestroy(&dewa);\n\n /* Write out files for the second image */\n pixWrite(\"/tmp/lept/dewtest/017.jpg\", pixs2, IFF_JFIF_JPEG);\n pixWrite(\"/tmp/lept/dewtest/018.jpg\", pixg2, IFF_JFIF_JPEG);\n pixWrite(\"/tmp/lept/dewtest/019.png\", pixb2, IFF_TIFF_G4);\n pixWrite(\"/tmp/lept/dewtest/020.jpg\", pixd2, IFF_JFIF_JPEG);\n pixt1 = pixRead(\"/tmp/lept/dewmod/0060.png\");\n pixWrite(\"/tmp/lept/dewtest/021.png\", pixt1, IFF_PNG);\n pixDestroy(&pixt1);\n pixt1 = pixRead(\"/tmp/lept/dewapply/002.png\");\n pixWrite(\"/tmp/lept/dewtest/022.png\", pixt1, IFF_PNG);\n pixt2 = pixThresholdToBinary(pixt1, 130);\n pixWrite(\"/tmp/lept/dewtest/023.png\", pixt2, IFF_TIFF_G4);\n pixDestroy(&pixt1);\n pixDestroy(&pixt2);\n pixt1 = pixRead(\"/tmp/lept/dewmod/0070.png\");\n pixWrite(\"/tmp/lept/dewtest/024.png\", pixt1, IFF_PNG);\n pixDestroy(&pixt1);\n pixt1 = pixRead(\"/tmp/lept/dewapply/003.png\");\n pixWrite(\"/tmp/lept/dewtest/025.png\", pixt1, IFF_PNG);\n pixt2 = pixThresholdToBinary(pixt1, 130);\n pixWrite(\"/tmp/lept/dewtest/026.png\", pixt2, IFF_TIFF_G4);\n pixDestroy(&pixt1);\n pixDestroy(&pixt2);\n\n /* Generate the big pdf file */\n convertFilesToPdf(\"/tmp/lept/dewtest\", NULL, 135, 1.0, 0, 0, \"Dewarp Test\",\n \"/tmp/lept/dewarptest1.pdf\");\n lept_stderr(\"pdf file made: /tmp/lept/model/dewarptest1.pdf\\n\");\n\n lept_rmdir(\"lept/dewmod\");\n lept_rmdir(\"lept/dewtest\");\n pixDestroy(&pixs);\n pixDestroy(&pixn);\n pixDestroy(&pixg);\n pixDestroy(&pixb);\n pixDestroy(&pixd);\n pixDestroy(&pixs2);\n pixDestroy(&pixn2);\n pixDestroy(&pixg2);\n pixDestroy(&pixb2);\n pixDestroy(&pixd2);\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Issue 23654 in oss-fuzz: Heap-buffer-overflow in pixReadFromTiffStream\n * Increase scanline buffer for reading gray+alpha and converting to RGBA'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: _lasso_check_assertion_issuer(LassoSaml2Assertion *assertion, const gchar *provider_id)\n{\n\tif (! LASSO_SAML2_ASSERTION(assertion) || ! provider_id)\n\t\treturn FALSE;\n\n\tif (! assertion->Issuer || ! assertion->Issuer->content)\n\t\treturn FALSE;\n\n\treturn lasso_strisequal(assertion->Issuer->content,provider_id);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-347'], 'message': 'Fix signature checking on unsigned response with multiple assertions\n\nCVE-2021-28091 : when AuthnResponse messages are not signed (which is\npermitted by the specifiation), all assertion's signatures should be\nchecked, but currently after the first signed assertion is checked all\nfollowing assertions are accepted without checking their signature, and\nthe last one is considered the main assertion.\n\nThis patch :\n* check signatures from all assertions if the message is not signed,\n* refuse messages with assertion from different issuers than the one on\n the message, to prevent assertion bundling event if they are signed.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static ssize_t add_slot_store(struct kobject *kobj, struct kobj_attribute *attr,\n\t\t\t const char *buf, size_t nbytes)\n{\n\tchar drc_name[MAX_DRC_NAME_LEN];\n\tchar *end;\n\tint rc;\n\n\tif (nbytes >= MAX_DRC_NAME_LEN)\n\t\treturn 0;\n\n\tmemcpy(drc_name, buf, nbytes);\n\n\tend = strchr(drc_name, '\\n');\n\tif (!end)\n\t\tend = &drc_name[nbytes];\n\t*end = '\\0';\n\n\trc = dlpar_add_slot(drc_name);\n\tif (rc)\n\t\treturn rc;\n\n\treturn nbytes;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'PCI: rpadlpar: Fix potential drc_name corruption in store functions\n\nBoth add_slot_store() and remove_slot_store() try to fix up the\ndrc_name copied from the store buffer by placing a NUL terminator at\nnbyte + 1 or in place of a '\\n' if present. However, the static buffer\nthat we copy the drc_name data into is not zeroed and can contain\nanything past the n-th byte.\n\nThis is problematic if a '\\n' byte appears in that buffer after nbytes\nand the string copied into the store buffer was not NUL terminated to\nstart with as the strchr() search for a '\\n' byte will mark this\nincorrectly as the end of the drc_name string resulting in a drc_name\nstring that contains garbage data after the n-th byte.\n\nAdditionally it will cause us to overwrite that '\\n' byte on the stack\nwith NUL, potentially corrupting data on the stack.\n\nThe following debugging shows an example of the drmgr utility writing\n\"PHB 4543\" to the add_slot sysfs attribute, but add_slot_store()\nlogging a corrupted string value.\n\n drmgr: drmgr: -c phb -a -s PHB 4543 -d 1\n add_slot_store: drc_name = PHB 4543\u00b0|<82>!, rc = -19\n\nFix this by using strscpy() instead of memcpy() to ensure the string\nis NUL terminated when copied into the static drc_name buffer.\nFurther, since the string is now NUL terminated the code only needs to\nchange '\\n' to '\\0' when present.\n\nCc: stable@vger.kernel.org\nSigned-off-by: Tyrel Datwyler \n[mpe: Reformat change log and add mention of possible stack corruption]\nSigned-off-by: Michael Ellerman \nLink: https://lore.kernel.org/r/20210315214821.452959-1-tyreld@linux.ibm.com'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int ossl_init(void)\n{\n#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \\\n !defined(LIBRESSL_VERSION_NUMBER)\n const uint64_t flags =\n#ifdef OPENSSL_INIT_ENGINE_ALL_BUILTIN\n /* not present in BoringSSL */\n OPENSSL_INIT_ENGINE_ALL_BUILTIN |\n#endif\n#ifdef CURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG\n OPENSSL_INIT_NO_LOAD_CONFIG |\n#else\n OPENSSL_INIT_LOAD_CONFIG |\n#endif\n 0;\n OPENSSL_init_ssl(flags, NULL);\n#else\n OPENSSL_load_builtin_modules();\n\n#ifdef USE_OPENSSL_ENGINE\n ENGINE_load_builtin_engines();\n#endif\n\n/* CONF_MFLAGS_DEFAULT_SECTION was introduced some time between 0.9.8b and\n 0.9.8e */\n#ifndef CONF_MFLAGS_DEFAULT_SECTION\n#define CONF_MFLAGS_DEFAULT_SECTION 0x0\n#endif\n\n#ifndef CURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG\n CONF_modules_load_file(NULL, NULL,\n CONF_MFLAGS_DEFAULT_SECTION|\n CONF_MFLAGS_IGNORE_MISSING_FILE);\n#endif\n\n /* Lets get nice error messages */\n SSL_load_error_strings();\n\n /* Init the global ciphers and digests */\n if(!SSLeay_add_ssl_algorithms())\n return 0;\n\n OpenSSL_add_all_algorithms();\n#endif\n\n Curl_tls_keylog_open();\n\n /* Initialize the extra data indexes */\n if(ossl_get_ssl_data_index() < 0 || ossl_get_ssl_conn_index() < 0 ||\n ossl_get_ssl_sockindex_index() < 0)\n return 0;\n\n return 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-290'], 'message': 'vtls: add 'isproxy' argument to Curl_ssl_get/addsessionid()\n\nTo make sure we set and extract the correct session.\n\nReported-by: Mingtao Yang\nBug: https://curl.se/docs/CVE-2021-22890.html\n\nCVE-2021-22890'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static CURLcode bearssl_connect_step1(struct Curl_easy *data,\n struct connectdata *conn, int sockindex)\n{\n struct ssl_connect_data *connssl = &conn->ssl[sockindex];\n struct ssl_backend_data *backend = connssl->backend;\n const char * const ssl_cafile = SSL_CONN_CONFIG(CAfile);\n#ifndef CURL_DISABLE_PROXY\n const char *hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :\n conn->host.name;\n#else\n const char *hostname = conn->host.name;\n#endif\n const bool verifypeer = SSL_CONN_CONFIG(verifypeer);\n const bool verifyhost = SSL_CONN_CONFIG(verifyhost);\n CURLcode ret;\n unsigned version_min, version_max;\n#ifdef ENABLE_IPV6\n struct in6_addr addr;\n#else\n struct in_addr addr;\n#endif\n\n switch(SSL_CONN_CONFIG(version)) {\n case CURL_SSLVERSION_SSLv2:\n failf(data, \"BearSSL does not support SSLv2\");\n return CURLE_SSL_CONNECT_ERROR;\n case CURL_SSLVERSION_SSLv3:\n failf(data, \"BearSSL does not support SSLv3\");\n return CURLE_SSL_CONNECT_ERROR;\n case CURL_SSLVERSION_TLSv1_0:\n version_min = BR_TLS10;\n version_max = BR_TLS10;\n break;\n case CURL_SSLVERSION_TLSv1_1:\n version_min = BR_TLS11;\n version_max = BR_TLS11;\n break;\n case CURL_SSLVERSION_TLSv1_2:\n version_min = BR_TLS12;\n version_max = BR_TLS12;\n break;\n case CURL_SSLVERSION_DEFAULT:\n case CURL_SSLVERSION_TLSv1:\n version_min = BR_TLS10;\n version_max = BR_TLS12;\n break;\n default:\n failf(data, \"BearSSL: unknown CURLOPT_SSLVERSION\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n\n if(ssl_cafile) {\n ret = load_cafile(ssl_cafile, &backend->anchors, &backend->anchors_len);\n if(ret != CURLE_OK) {\n if(verifypeer) {\n failf(data, \"error setting certificate verify locations.\"\n \" CAfile: %s\", ssl_cafile);\n return ret;\n }\n infof(data, \"error setting certificate verify locations,\"\n \" continuing anyway:\\n\");\n }\n }\n\n /* initialize SSL context */\n br_ssl_client_init_full(&backend->ctx, &backend->x509.minimal,\n backend->anchors, backend->anchors_len);\n br_ssl_engine_set_versions(&backend->ctx.eng, version_min, version_max);\n br_ssl_engine_set_buffer(&backend->ctx.eng, backend->buf,\n sizeof(backend->buf), 1);\n\n /* initialize X.509 context */\n backend->x509.vtable = &x509_vtable;\n backend->x509.verifypeer = verifypeer;\n backend->x509.verifyhost = verifyhost;\n br_ssl_engine_set_x509(&backend->ctx.eng, &backend->x509.vtable);\n\n if(SSL_SET_OPTION(primary.sessionid)) {\n void *session;\n\n Curl_ssl_sessionid_lock(data);\n if(!Curl_ssl_getsessionid(data, conn, &session, NULL, sockindex)) {\n br_ssl_engine_set_session_parameters(&backend->ctx.eng, session);\n infof(data, \"BearSSL: re-using session ID\\n\");\n }\n Curl_ssl_sessionid_unlock(data);\n }\n\n if(conn->bits.tls_enable_alpn) {\n int cur = 0;\n\n /* NOTE: when adding more protocols here, increase the size of the\n * protocols array in `struct ssl_backend_data`.\n */\n\n#ifdef USE_NGHTTP2\n if(data->state.httpversion >= CURL_HTTP_VERSION_2\n#ifndef CURL_DISABLE_PROXY\n && (!SSL_IS_PROXY() || !conn->bits.tunnel_proxy)\n#endif\n ) {\n backend->protocols[cur++] = NGHTTP2_PROTO_VERSION_ID;\n infof(data, \"ALPN, offering %s\\n\", NGHTTP2_PROTO_VERSION_ID);\n }\n#endif\n\n backend->protocols[cur++] = ALPN_HTTP_1_1;\n infof(data, \"ALPN, offering %s\\n\", ALPN_HTTP_1_1);\n\n br_ssl_engine_set_protocol_names(&backend->ctx.eng,\n backend->protocols, cur);\n }\n\n if((1 == Curl_inet_pton(AF_INET, hostname, &addr))\n#ifdef ENABLE_IPV6\n || (1 == Curl_inet_pton(AF_INET6, hostname, &addr))\n#endif\n ) {\n if(verifyhost) {\n failf(data, \"BearSSL: \"\n \"host verification of IP address is not supported\");\n return CURLE_PEER_FAILED_VERIFICATION;\n }\n hostname = NULL;\n }\n\n if(!br_ssl_client_reset(&backend->ctx, hostname, 0))\n return CURLE_FAILED_INIT;\n backend->active = TRUE;\n\n connssl->connecting_state = ssl_connect_2;\n\n return CURLE_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-290'], 'message': 'vtls: add 'isproxy' argument to Curl_ssl_get/addsessionid()\n\nTo make sure we set and extract the correct session.\n\nReported-by: Mingtao Yang\nBug: https://curl.se/docs/CVE-2021-22890.html\n\nCVE-2021-22890'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: test_main (void)\n{\n /* Test cases for the smaller groups, verified with a\n proof-of-concept implementation done for Yubico AB. */\n test_ecdsa (&_nettle_secp_192r1,\n\t \"DC51D3866A15BACDE33D96F992FCA99D\"\n\t \"A7E6EF0934E70975\", /* z */\n\n\t \"9E56F509196784D963D1C0A401510EE7\"\n\t \"ADA3DCC5DEE04B15\", /* k */\n\n\t SHEX(\"BA7816BF8F01CFEA414140DE5DAE2223\"\n\t\t \"B00361A396177A9C\"), /* h */\n\n\t \"8c478db6a5c131540cebc739f9c0a9a8\"\n\t \"c720c2abdd14a891\", /* r */\n\n\t \"a91fb738f9f175d72f9c98527e881c36\"\n\t \"8de68cb55ffe589\"); /* s */\n\n test_ecdsa (&_nettle_secp_224r1,\n\t \"446df0a771ed58403ca9cb316e617f6b\"\n\t \"158420465d00a69601e22858\", /* z */\n\n\t \"4c13f1905ad7eb201178bc08e0c9267b\"\n\t \"4751c15d5e1831ca214c33f4\", /* z */\n\n\t SHEX(\"1b28a611fe62ab3649350525d06703ba\"\n\t\t \"4b979a1e543566fd5caa85c6\"), /* h */\n\n\t \"2cc280778f3d067df6d3adbe3a6aad63\"\n\t \"bc75f08f5c5f915411902a99\", /* r */ \n\n\t \"d0f069fd0f108eb07b7bbc54c8d6c88d\"\n\t \"f2715c38a95c31a2b486995f\"); /* s */\n\n /* From RFC 4754 */\n test_ecdsa (&_nettle_secp_256r1,\n\t \"DC51D386 6A15BACD E33D96F9 92FCA99D\"\n\t \"A7E6EF09 34E70975 59C27F16 14C88A7F\", /* z */\n\n\t \"9E56F509 196784D9 63D1C0A4 01510EE7\"\n\t \"ADA3DCC5 DEE04B15 4BF61AF1 D5A6DECE\", /* k */\n\n\t SHEX(\"BA7816BF 8F01CFEA 414140DE 5DAE2223\"\n\t\t \"B00361A3 96177A9C B410FF61 F20015AD\"), /* h */\n\t \n\t \"CB28E099 9B9C7715 FD0A80D8 E47A7707\"\n\t \"9716CBBF 917DD72E 97566EA1 C066957C\", /* r */\n\t \"86FA3BB4 E26CAD5B F90B7F81 899256CE\"\n\t \"7594BB1E A0C89212 748BFF3B 3D5B0315\"); /* s */\n\n test_ecdsa (&_nettle_secp_384r1,\n\t \"0BEB6466 34BA8773 5D77AE48 09A0EBEA\"\n\t \"865535DE 4C1E1DCB 692E8470 8E81A5AF\"\n\t \"62E528C3 8B2A81B3 5309668D 73524D9F\", /* z */\n\n\t \"B4B74E44 D71A13D5 68003D74 89908D56\"\n\t \"4C7761E2 29C58CBF A1895009 6EB7463B\"\n\t \"854D7FA9 92F934D9 27376285 E63414FA\", /* k */\n\n\t SHEX(\"CB00753F 45A35E8B B5A03D69 9AC65007\"\n\t\t \"272C32AB 0EDED163 1A8B605A 43FF5BED\"\n\t\t \"8086072B A1E7CC23 58BAECA1 34C825A7\"), /* h */\n\n\t \"FB017B91 4E291494 32D8BAC2 9A514640\"\n\t \"B46F53DD AB2C6994 8084E293 0F1C8F7E\"\n\t \"08E07C9C 63F2D21A 07DCB56A 6AF56EB3\", /* r */\n\t \"B263A130 5E057F98 4D38726A 1B468741\"\n\t \"09F417BC A112674C 528262A4 0A629AF1\"\n\t \"CBB9F516 CE0FA7D2 FF630863 A00E8B9F\"); /* s*/\n\n test_ecdsa (&_nettle_secp_521r1,\n\t \"0065FDA3 409451DC AB0A0EAD 45495112\"\n\t \"A3D813C1 7BFD34BD F8C1209D 7DF58491\"\n\t \"20597779 060A7FF9 D704ADF7 8B570FFA\"\n\t \"D6F062E9 5C7E0C5D 5481C5B1 53B48B37\"\n\t \"5FA1\", /* z */\n\t \n\t \"00C1C2B3 05419F5A 41344D7E 4359933D\"\n\t \"734096F5 56197A9B 244342B8 B62F46F9\"\n\t \"373778F9 DE6B6497 B1EF825F F24F42F9\"\n\t \"B4A4BD73 82CFC337 8A540B1B 7F0C1B95\"\n\t \"6C2F\", /* k */\n\n\t SHEX(\"DDAF35A1 93617ABA CC417349 AE204131\"\n\t\t \"12E6FA4E 89A97EA2 0A9EEEE6 4B55D39A\"\n\t\t \"2192992A 274FC1A8 36BA3C23 A3FEEBBD\"\n\t\t \"454D4423 643CE80E 2A9AC94F A54CA49F\"), /* h */\n\n\t \"0154FD38 36AF92D0 DCA57DD5 341D3053\"\n\t \"988534FD E8318FC6 AAAAB68E 2E6F4339\"\n\t \"B19F2F28 1A7E0B22 C269D93C F8794A92\"\n\t \"78880ED7 DBB8D936 2CAEACEE 54432055\"\n\t \"2251\", /* r */\n\t \"017705A7 030290D1 CEB605A9 A1BB03FF\"\n\t \"9CDD521E 87A696EC 926C8C10 C8362DF4\"\n\t \"97536710 1F67D1CF 9BCCBF2F 3D239534\"\n\t \"FA509E70 AAC851AE 01AAC68D 62F86647\"\n\t \"2660\"); /* s */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix bug in ecc_ecdsa_verify.\n\n* ecc-ecdsa-verify.c (ecc_ecdsa_verify): Use ecc_mod_mul_canonical\nto compute the scalars used for ecc multiplication.\n* testsuite/ecdsa-verify-test.c (test_main): Add test case that\ntriggers an assert on 64-bit platforms, without above fix.\n* testsuite/ecdsa-sign-test.c (test_main): Test case generating\nthe same signature.\n\n(cherry picked from commit 2397757b3f95fcae1e2d3011bf99ca5b5438378f)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: size_t zmalloc_size(void *ptr) {\n void *realptr = (char*)ptr-PREFIX_SIZE;\n size_t size = *((size_t*)realptr);\n /* Assume at least that all the allocations are padded at sizeof(long) by\n * the underlying allocator. */\n if (size&(sizeof(long)-1)) size += sizeof(long)-(size&(sizeof(long)-1));\n return size+PREFIX_SIZE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix wrong zmalloc_size() assumption. (#7963)\n\nWhen using a system with no malloc_usable_size(), zmalloc_size() assumed\r\nthat the heap allocator always returns blocks that are long-padded.\r\n\r\nThis may not always be the case, and will result with zmalloc_size()\r\nreturning a size that is bigger than allocated. At least in one case\r\nthis leads to out of bound write, process crash and a potential security\r\nvulnerability.\r\n\r\nEffectively this does not affect the vast majority of users, who use\r\njemalloc or glibc.\r\n\r\nThis problem along with a (different) fix was reported by Drew DeVault.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int check_btf_info(struct bpf_verifier_env *env,\n\t\t\t const union bpf_attr *attr,\n\t\t\t union bpf_attr __user *uattr)\n{\n\tstruct btf *btf;\n\tint err;\n\n\tif (!attr->func_info_cnt && !attr->line_info_cnt) {\n\t\tif (check_abnormal_return(env))\n\t\t\treturn -EINVAL;\n\t\treturn 0;\n\t}\n\n\tbtf = btf_get_by_fd(attr->prog_btf_fd);\n\tif (IS_ERR(btf))\n\t\treturn PTR_ERR(btf);\n\tenv->prog->aux->btf = btf;\n\n\terr = check_btf_func(env, attr, uattr);\n\tif (err)\n\t\treturn err;\n\n\terr = check_btf_line(env, attr, uattr);\n\tif (err)\n\t\treturn err;\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-307'], 'message': 'bpf: Dont allow vmlinux BTF to be used in map_create and prog_load.\n\nThe syzbot got FD of vmlinux BTF and passed it into map_create which caused\ncrash in btf_type_id_size() when it tried to access resolved_ids. The vmlinux\nBTF doesn't have 'resolved_ids' and 'resolved_sizes' initialized to save\nmemory. To avoid such issues disallow using vmlinux BTF in prog_load and\nmap_create commands.\n\nFixes: 5329722057d4 (\"bpf: Assign ID to vmlinux BTF and return extra info for BTF in GET_OBJ_INFO\")\nReported-by: syzbot+8bab8ed346746e7540e8@syzkaller.appspotmail.com\nSigned-off-by: Alexei Starovoitov \nSigned-off-by: Daniel Borkmann \nAcked-by: Yonghong Song \nLink: https://lore.kernel.org/bpf/20210307225248.79031-1-alexei.starovoitov@gmail.com'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void inline ConvertXYZToJzazbz(const double X,const double Y,\n const double Z,const double white_luminance,double *Jz,double *az,double *bz)\n{\n#define Jzazbz_b 1.15 /* https://observablehq.com/@jrus/jzazbz */\n#define Jzazbz_g 0.66\n#define Jzazbz_c1 (3424.0/4096.0)\n#define Jzazbz_c2 (2413.0/128.0)\n#define Jzazbz_c3 (2392.0/128.0)\n#define Jzazbz_n (2610.0/16384.0)\n#define Jzazbz_p (1.7*2523.0/32.0)\n#define Jzazbz_d (-0.56)\n#define Jzazbz_d0 (1.6295499532821566e-11)\n\n double\n gamma,\n Iz,\n L,\n Lp,\n M,\n Mp,\n S,\n Sp,\n Xp,\n Yp,\n Zp;\n\n Xp=(Jzazbz_b*X-Z*(Jzazbz_b-1));\n Yp=(Jzazbz_g*Y-X*(Jzazbz_g-1));\n Zp=Z;\n L=0.41478972*Xp+0.579999*Yp+0.0146480*Zp;\n M=(-0.2015100)*Xp+1.120649*Yp+0.0531008*Zp;\n S=(-0.0166008)*Xp+0.264800*Yp+0.6684799*Zp;\n gamma=pow(L/white_luminance,Jzazbz_n);\n Lp=pow((Jzazbz_c1+Jzazbz_c2*gamma)/(1.0+Jzazbz_c3*gamma),Jzazbz_p);\n gamma=pow(M/white_luminance,Jzazbz_n);\n Mp=pow((Jzazbz_c1+Jzazbz_c2*gamma)/(1.0+Jzazbz_c3*gamma),Jzazbz_p);\n gamma=pow(S/white_luminance,Jzazbz_n);\n Sp=pow((Jzazbz_c1+Jzazbz_c2*gamma)/(1.0+Jzazbz_c3*gamma),Jzazbz_p);\n Iz=0.5*Lp+0.5*Mp;\n *az=3.52400*Lp-4.066708*Mp+0.542708*Sp+0.5;\n *bz=0.199076*Lp+1.096799*Mp-1.295875*Sp+0.5;\n *Jz=((Jzazbz_d+1.0)*Iz)/(Jzazbz_d*Iz+1.0)-Jzazbz_d0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-369'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/3295'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: MagickExport MagickBooleanType PasskeyEncipherImage(Image *image,\n const StringInfo *passkey,ExceptionInfo *exception)\n{\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n (void) passkey;\n ThrowBinaryException(ImageError,\"CipherSupportNotEnabled\",image->filename);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-369'], 'message': 'possible divide by zero + clear buffers'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: readTile(T& in, bool reduceMemory , bool reduceTime)\n{\n bool threw = false;\n try\n {\n const Box2i& dw = in.header().dataWindow();\n\n int w = dw.max.x - dw.min.x + 1;\n int h = dw.max.y - dw.min.y + 1;\n int dwx = dw.min.x;\n int dwy = dw.min.y;\n int numXLevels = in.numXLevels();\n int numYLevels = in.numYLevels();\n\n const TileDescription& td = in.header().tileDescription();\n\n\n if (reduceMemory && w > (1 << 10))\n {\n return false;\n }\n\n FrameBuffer i;\n // read all channels present (later channels will overwrite earlier ones)\n vector halfChannels(w);\n vector floatChannels(w);\n vector uintChannels(w);\n\n int channelIndex = 0;\n const ChannelList& channelList = in.header().channels();\n for (ChannelList::ConstIterator c = channelList.begin() ; c != channelList.end() ; ++c )\n {\n switch (channelIndex % 3)\n {\n case 0 : i.insert(c.name(),Slice(HALF, (char*)&halfChannels[-dwx] , sizeof(half) , 0 , c.channel().xSampling , c.channel().ySampling ));\n break;\n case 1 : i.insert(c.name(),Slice(FLOAT, (char*)&floatChannels[-dwx] , sizeof(float) , 0 , c.channel().xSampling , c.channel().ySampling));\n case 2 : i.insert(c.name(),Slice(UINT, (char*)&uintChannels[-dwx] , sizeof(unsigned int) , 0 , c.channel().xSampling , c.channel().ySampling));\n break;\n }\n channelIndex ++;\n }\n\n in.setFrameBuffer (i);\n\n\n //\n // limit to 2,000 tiles\n //\n size_t step = 1;\n\n if (reduceTime && in.numXTiles(0) * in.numYTiles(0) > 2000)\n {\n step = max(1, (in.numXTiles(0) * in.numYTiles(0)) / 2000 );\n }\n\n\n\n size_t tileIndex =0;\n bool isRipMap = td.mode == RIPMAP_LEVELS;\n\n //\n // read all tiles from all levels.\n //\n for (int ylevel = 0; ylevel < numYLevels; ++ylevel )\n {\n for (int xlevel = 0; xlevel < numXLevels; ++xlevel )\n {\n for(int y = 0 ; y < in.numYTiles(ylevel) ; ++y )\n {\n for(int x = 0 ; x < in.numXTiles(xlevel) ; ++x )\n {\n if(tileIndex % step == 0)\n {\n try\n {\n in.readTile ( x, y, xlevel , ylevel);\n }\n catch(...)\n {\n //\n // for one level and mipmapped images,\n // xlevel must match ylevel,\n // otherwise an exception is thrown\n // ignore that exception\n //\n if (isRipMap || xlevel==ylevel)\n {\n threw = true;\n }\n }\n }\n tileIndex++;\n }\n }\n }\n }\n }\n catch(...)\n {\n threw = true;\n }\n\n return threw;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Handle xsampling and bad seekg() calls in exrcheck (#872)\n\n* fix exrcheck xsampling!=1\r\n\r\nSigned-off-by: Peter Hillman \r\n\r\n* fix handling bad seekg() calls in exrcheck\r\n\r\nSigned-off-by: Peter Hillman \r\n\r\n* fix deeptile detection in multipart files\r\n\r\nSigned-off-by: Peter Hillman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void sctp_close(struct sock *sk, long timeout)\n{\n\tstruct net *net = sock_net(sk);\n\tstruct sctp_endpoint *ep;\n\tstruct sctp_association *asoc;\n\tstruct list_head *pos, *temp;\n\tunsigned int data_was_unread;\n\n\tpr_debug(\"%s: sk:%p, timeout:%ld\\n\", __func__, sk, timeout);\n\n\tlock_sock_nested(sk, SINGLE_DEPTH_NESTING);\n\tsk->sk_shutdown = SHUTDOWN_MASK;\n\tinet_sk_set_state(sk, SCTP_SS_CLOSING);\n\n\tep = sctp_sk(sk)->ep;\n\n\t/* Clean up any skbs sitting on the receive queue. */\n\tdata_was_unread = sctp_queue_purge_ulpevents(&sk->sk_receive_queue);\n\tdata_was_unread += sctp_queue_purge_ulpevents(&sctp_sk(sk)->pd_lobby);\n\n\t/* Walk all associations on an endpoint. */\n\tlist_for_each_safe(pos, temp, &ep->asocs) {\n\t\tasoc = list_entry(pos, struct sctp_association, asocs);\n\n\t\tif (sctp_style(sk, TCP)) {\n\t\t\t/* A closed association can still be in the list if\n\t\t\t * it belongs to a TCP-style listening socket that is\n\t\t\t * not yet accepted. If so, free it. If not, send an\n\t\t\t * ABORT or SHUTDOWN based on the linger options.\n\t\t\t */\n\t\t\tif (sctp_state(asoc, CLOSED)) {\n\t\t\t\tsctp_association_free(asoc);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tif (data_was_unread || !skb_queue_empty(&asoc->ulpq.lobby) ||\n\t\t !skb_queue_empty(&asoc->ulpq.reasm) ||\n\t\t !skb_queue_empty(&asoc->ulpq.reasm_uo) ||\n\t\t (sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime)) {\n\t\t\tstruct sctp_chunk *chunk;\n\n\t\t\tchunk = sctp_make_abort_user(asoc, NULL, 0);\n\t\t\tsctp_primitive_ABORT(net, asoc, chunk);\n\t\t} else\n\t\t\tsctp_primitive_SHUTDOWN(net, asoc, NULL);\n\t}\n\n\t/* On a TCP-style socket, block for at most linger_time if set. */\n\tif (sctp_style(sk, TCP) && timeout)\n\t\tsctp_wait_for_close(sk, timeout);\n\n\t/* This will run the backlog queue. */\n\trelease_sock(sk);\n\n\t/* Supposedly, no process has access to the socket, but\n\t * the net layers still may.\n\t * Also, sctp_destroy_sock() needs to be called with addr_wq_lock\n\t * held and that should be grabbed before socket lock.\n\t */\n\tspin_lock_bh(&net->sctp.addr_wq_lock);\n\tbh_lock_sock_nested(sk);\n\n\t/* Hold the sock, since sk_common_release() will put sock_put()\n\t * and we have just a little more cleanup.\n\t */\n\tsock_hold(sk);\n\tsk_common_release(sk);\n\n\tbh_unlock_sock(sk);\n\tspin_unlock_bh(&net->sctp.addr_wq_lock);\n\n\tsock_put(sk);\n\n\tSCTP_DBG_OBJCNT_DEC(sock);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'net/sctp: fix race condition in sctp_destroy_sock\n\nIf sctp_destroy_sock is called without sock_net(sk)->sctp.addr_wq_lock\nheld and sp->do_auto_asconf is true, then an element is removed\nfrom the auto_asconf_splist without any proper locking.\n\nThis can happen in the following functions:\n1. In sctp_accept, if sctp_sock_migrate fails.\n2. In inet_create or inet6_create, if there is a bpf program\n attached to BPF_CGROUP_INET_SOCK_CREATE which denies\n creation of the sctp socket.\n\nThe bug is fixed by acquiring addr_wq_lock in sctp_destroy_sock\ninstead of sctp_close.\n\nThis addresses CVE-2021-23133.\n\nReported-by: Or Cohen \nReviewed-by: Xin Long \nFixes: 610236587600 (\"bpf: Add new cgroup attach type to enable sock modifications\")\nSigned-off-by: Or Cohen \nAcked-by: Marcelo Ricardo Leitner \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int fuse_open_common(struct inode *inode, struct file *file, bool isdir)\n{\n\tstruct fuse_mount *fm = get_fuse_mount(inode);\n\tstruct fuse_conn *fc = fm->fc;\n\tint err;\n\tbool is_wb_truncate = (file->f_flags & O_TRUNC) &&\n\t\t\t fc->atomic_o_trunc &&\n\t\t\t fc->writeback_cache;\n\tbool dax_truncate = (file->f_flags & O_TRUNC) &&\n\t\t\t fc->atomic_o_trunc && FUSE_IS_DAX(inode);\n\n\terr = generic_file_open(inode, file);\n\tif (err)\n\t\treturn err;\n\n\tif (is_wb_truncate || dax_truncate) {\n\t\tinode_lock(inode);\n\t\tfuse_set_nowrite(inode);\n\t}\n\n\tif (dax_truncate) {\n\t\tdown_write(&get_fuse_inode(inode)->i_mmap_sem);\n\t\terr = fuse_dax_break_layouts(inode, 0, 0);\n\t\tif (err)\n\t\t\tgoto out;\n\t}\n\n\terr = fuse_do_open(fm, get_node_id(inode), file, isdir);\n\tif (!err)\n\t\tfuse_finish_open(inode, file);\n\nout:\n\tif (dax_truncate)\n\t\tup_write(&get_fuse_inode(inode)->i_mmap_sem);\n\n\tif (is_wb_truncate | dax_truncate) {\n\t\tfuse_release_nowrite(inode);\n\t\tinode_unlock(inode);\n\t}\n\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-459'], 'message': 'fuse: fix bad inode\n\nJan Kara's analysis of the syzbot report (edited):\n\n The reproducer opens a directory on FUSE filesystem, it then attaches\n dnotify mark to the open directory. After that a fuse_do_getattr() call\n finds that attributes returned by the server are inconsistent, and calls\n make_bad_inode() which, among other things does:\n\n inode->i_mode = S_IFREG;\n\n This then confuses dnotify which doesn't tear down its structures\n properly and eventually crashes.\n\nAvoid calling make_bad_inode() on a live inode: switch to a private flag on\nthe fuse inode. Also add the test to ops which the bad_inode_ops would\nhave caught.\n\nThis bug goes back to the initial merge of fuse in 2.6.14...\n\nReported-by: syzbot+f427adf9324b92652ccc@syzkaller.appspotmail.com\nSigned-off-by: Miklos Szeredi \nTested-by: Jan Kara \nCc: '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int create_new_entry(struct fuse_mount *fm, struct fuse_args *args,\n\t\t\t struct inode *dir, struct dentry *entry,\n\t\t\t umode_t mode)\n{\n\tstruct fuse_entry_out outarg;\n\tstruct inode *inode;\n\tstruct dentry *d;\n\tint err;\n\tstruct fuse_forget_link *forget;\n\n\tforget = fuse_alloc_forget();\n\tif (!forget)\n\t\treturn -ENOMEM;\n\n\tmemset(&outarg, 0, sizeof(outarg));\n\targs->nodeid = get_node_id(dir);\n\targs->out_numargs = 1;\n\targs->out_args[0].size = sizeof(outarg);\n\targs->out_args[0].value = &outarg;\n\terr = fuse_simple_request(fm, args);\n\tif (err)\n\t\tgoto out_put_forget_req;\n\n\terr = -EIO;\n\tif (invalid_nodeid(outarg.nodeid) || fuse_invalid_attr(&outarg.attr))\n\t\tgoto out_put_forget_req;\n\n\tif ((outarg.attr.mode ^ mode) & S_IFMT)\n\t\tgoto out_put_forget_req;\n\n\tinode = fuse_iget(dir->i_sb, outarg.nodeid, outarg.generation,\n\t\t\t &outarg.attr, entry_attr_timeout(&outarg), 0);\n\tif (!inode) {\n\t\tfuse_queue_forget(fm->fc, forget, outarg.nodeid, 1);\n\t\treturn -ENOMEM;\n\t}\n\tkfree(forget);\n\n\td_drop(entry);\n\td = d_splice_alias(inode, entry);\n\tif (IS_ERR(d))\n\t\treturn PTR_ERR(d);\n\n\tif (d) {\n\t\tfuse_change_entry_timeout(d, &outarg);\n\t\tdput(d);\n\t} else {\n\t\tfuse_change_entry_timeout(entry, &outarg);\n\t}\n\tfuse_dir_changed(dir);\n\treturn 0;\n\n out_put_forget_req:\n\tkfree(forget);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-459'], 'message': 'fuse: fix bad inode\n\nJan Kara's analysis of the syzbot report (edited):\n\n The reproducer opens a directory on FUSE filesystem, it then attaches\n dnotify mark to the open directory. After that a fuse_do_getattr() call\n finds that attributes returned by the server are inconsistent, and calls\n make_bad_inode() which, among other things does:\n\n inode->i_mode = S_IFREG;\n\n This then confuses dnotify which doesn't tear down its structures\n properly and eventually crashes.\n\nAvoid calling make_bad_inode() on a live inode: switch to a private flag on\nthe fuse inode. Also add the test to ops which the bad_inode_ops would\nhave caught.\n\nThis bug goes back to the initial merge of fuse in 2.6.14...\n\nReported-by: syzbot+f427adf9324b92652ccc@syzkaller.appspotmail.com\nSigned-off-by: Miklos Szeredi \nTested-by: Jan Kara \nCc: '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int fuse_atomic_open(struct inode *dir, struct dentry *entry,\n\t\t\t struct file *file, unsigned flags,\n\t\t\t umode_t mode)\n{\n\tint err;\n\tstruct fuse_conn *fc = get_fuse_conn(dir);\n\tstruct dentry *res = NULL;\n\n\tif (d_in_lookup(entry)) {\n\t\tres = fuse_lookup(dir, entry, 0);\n\t\tif (IS_ERR(res))\n\t\t\treturn PTR_ERR(res);\n\n\t\tif (res)\n\t\t\tentry = res;\n\t}\n\n\tif (!(flags & O_CREAT) || d_really_is_positive(entry))\n\t\tgoto no_open;\n\n\t/* Only creates */\n\tfile->f_mode |= FMODE_CREATED;\n\n\tif (fc->no_create)\n\t\tgoto mknod;\n\n\terr = fuse_create_open(dir, entry, file, flags, mode);\n\tif (err == -ENOSYS) {\n\t\tfc->no_create = 1;\n\t\tgoto mknod;\n\t}\nout_dput:\n\tdput(res);\n\treturn err;\n\nmknod:\n\terr = fuse_mknod(dir, entry, mode, 0);\n\tif (err)\n\t\tgoto out_dput;\nno_open:\n\treturn finish_no_open(file, res);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-459'], 'message': 'fuse: fix bad inode\n\nJan Kara's analysis of the syzbot report (edited):\n\n The reproducer opens a directory on FUSE filesystem, it then attaches\n dnotify mark to the open directory. After that a fuse_do_getattr() call\n finds that attributes returned by the server are inconsistent, and calls\n make_bad_inode() which, among other things does:\n\n inode->i_mode = S_IFREG;\n\n This then confuses dnotify which doesn't tear down its structures\n properly and eventually crashes.\n\nAvoid calling make_bad_inode() on a live inode: switch to a private flag on\nthe fuse inode. Also add the test to ops which the bad_inode_ops would\nhave caught.\n\nThis bug goes back to the initial merge of fuse in 2.6.14...\n\nReported-by: syzbot+f427adf9324b92652ccc@syzkaller.appspotmail.com\nSigned-off-by: Miklos Szeredi \nTested-by: Jan Kara \nCc: '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int __vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)\n{\n\tstruct vcpu_vmx *vmx = to_vmx(vcpu);\n\tunion vmx_exit_reason exit_reason = vmx->exit_reason;\n\tu32 vectoring_info = vmx->idt_vectoring_info;\n\tu16 exit_handler_index;\n\n\t/*\n\t * Flush logged GPAs PML buffer, this will make dirty_bitmap more\n\t * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before\n\t * querying dirty_bitmap, we only need to kick all vcpus out of guest\n\t * mode as if vcpus is in root mode, the PML buffer must has been\n\t * flushed already. Note, PML is never enabled in hardware while\n\t * running L2.\n\t */\n\tif (enable_pml && !is_guest_mode(vcpu))\n\t\tvmx_flush_pml_buffer(vcpu);\n\n\t/*\n\t * We should never reach this point with a pending nested VM-Enter, and\n\t * more specifically emulation of L2 due to invalid guest state (see\n\t * below) should never happen as that means we incorrectly allowed a\n\t * nested VM-Enter with an invalid vmcs12.\n\t */\n\tWARN_ON_ONCE(vmx->nested.nested_run_pending);\n\n\t/* If guest state is invalid, start emulating */\n\tif (vmx->emulation_required)\n\t\treturn handle_invalid_guest_state(vcpu);\n\n\tif (is_guest_mode(vcpu)) {\n\t\t/*\n\t\t * PML is never enabled when running L2, bail immediately if a\n\t\t * PML full exit occurs as something is horribly wrong.\n\t\t */\n\t\tif (exit_reason.basic == EXIT_REASON_PML_FULL)\n\t\t\tgoto unexpected_vmexit;\n\n\t\t/*\n\t\t * The host physical addresses of some pages of guest memory\n\t\t * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC\n\t\t * Page). The CPU may write to these pages via their host\n\t\t * physical address while L2 is running, bypassing any\n\t\t * address-translation-based dirty tracking (e.g. EPT write\n\t\t * protection).\n\t\t *\n\t\t * Mark them dirty on every exit from L2 to prevent them from\n\t\t * getting out of sync with dirty tracking.\n\t\t */\n\t\tnested_mark_vmcs12_pages_dirty(vcpu);\n\n\t\tif (nested_vmx_reflect_vmexit(vcpu))\n\t\t\treturn 1;\n\t}\n\n\tif (exit_reason.failed_vmentry) {\n\t\tdump_vmcs();\n\t\tvcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;\n\t\tvcpu->run->fail_entry.hardware_entry_failure_reason\n\t\t\t= exit_reason.full;\n\t\tvcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;\n\t\treturn 0;\n\t}\n\n\tif (unlikely(vmx->fail)) {\n\t\tdump_vmcs();\n\t\tvcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;\n\t\tvcpu->run->fail_entry.hardware_entry_failure_reason\n\t\t\t= vmcs_read32(VM_INSTRUCTION_ERROR);\n\t\tvcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;\n\t\treturn 0;\n\t}\n\n\t/*\n\t * Note:\n\t * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by\n\t * delivery event since it indicates guest is accessing MMIO.\n\t * The vm-exit can be triggered again after return to guest that\n\t * will cause infinite loop.\n\t */\n\tif ((vectoring_info & VECTORING_INFO_VALID_MASK) &&\n\t (exit_reason.basic != EXIT_REASON_EXCEPTION_NMI &&\n\t exit_reason.basic != EXIT_REASON_EPT_VIOLATION &&\n\t exit_reason.basic != EXIT_REASON_PML_FULL &&\n\t exit_reason.basic != EXIT_REASON_APIC_ACCESS &&\n\t exit_reason.basic != EXIT_REASON_TASK_SWITCH)) {\n\t\tvcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;\n\t\tvcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;\n\t\tvcpu->run->internal.ndata = 3;\n\t\tvcpu->run->internal.data[0] = vectoring_info;\n\t\tvcpu->run->internal.data[1] = exit_reason.full;\n\t\tvcpu->run->internal.data[2] = vcpu->arch.exit_qualification;\n\t\tif (exit_reason.basic == EXIT_REASON_EPT_MISCONFIG) {\n\t\t\tvcpu->run->internal.ndata++;\n\t\t\tvcpu->run->internal.data[3] =\n\t\t\t\tvmcs_read64(GUEST_PHYSICAL_ADDRESS);\n\t\t}\n\t\tvcpu->run->internal.data[vcpu->run->internal.ndata++] =\n\t\t\tvcpu->arch.last_vmentry_cpu;\n\t\treturn 0;\n\t}\n\n\tif (unlikely(!enable_vnmi &&\n\t\t vmx->loaded_vmcs->soft_vnmi_blocked)) {\n\t\tif (!vmx_interrupt_blocked(vcpu)) {\n\t\t\tvmx->loaded_vmcs->soft_vnmi_blocked = 0;\n\t\t} else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&\n\t\t\t vcpu->arch.nmi_pending) {\n\t\t\t/*\n\t\t\t * This CPU don't support us in finding the end of an\n\t\t\t * NMI-blocked window if the guest runs with IRQs\n\t\t\t * disabled. So we pull the trigger after 1 s of\n\t\t\t * futile waiting, but inform the user about this.\n\t\t\t */\n\t\t\tprintk(KERN_WARNING \"%s: Breaking out of NMI-blocked \"\n\t\t\t \"state on VCPU %d after 1 s timeout\\n\",\n\t\t\t __func__, vcpu->vcpu_id);\n\t\t\tvmx->loaded_vmcs->soft_vnmi_blocked = 0;\n\t\t}\n\t}\n\n\tif (exit_fastpath != EXIT_FASTPATH_NONE)\n\t\treturn 1;\n\n\tif (exit_reason.basic >= kvm_vmx_max_exit_handlers)\n\t\tgoto unexpected_vmexit;\n#ifdef CONFIG_RETPOLINE\n\tif (exit_reason.basic == EXIT_REASON_MSR_WRITE)\n\t\treturn kvm_emulate_wrmsr(vcpu);\n\telse if (exit_reason.basic == EXIT_REASON_PREEMPTION_TIMER)\n\t\treturn handle_preemption_timer(vcpu);\n\telse if (exit_reason.basic == EXIT_REASON_INTERRUPT_WINDOW)\n\t\treturn handle_interrupt_window(vcpu);\n\telse if (exit_reason.basic == EXIT_REASON_EXTERNAL_INTERRUPT)\n\t\treturn handle_external_interrupt(vcpu);\n\telse if (exit_reason.basic == EXIT_REASON_HLT)\n\t\treturn kvm_emulate_halt(vcpu);\n\telse if (exit_reason.basic == EXIT_REASON_EPT_MISCONFIG)\n\t\treturn handle_ept_misconfig(vcpu);\n#endif\n\n\texit_handler_index = array_index_nospec((u16)exit_reason.basic,\n\t\t\t\t\t\tkvm_vmx_max_exit_handlers);\n\tif (!kvm_vmx_exit_handlers[exit_handler_index])\n\t\tgoto unexpected_vmexit;\n\n\treturn kvm_vmx_exit_handlers[exit_handler_index](vcpu);\n\nunexpected_vmexit:\n\tvcpu_unimpl(vcpu, \"vmx: unexpected exit reason 0x%x\\n\",\n\t\t exit_reason.full);\n\tdump_vmcs();\n\tvcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;\n\tvcpu->run->internal.suberror =\n\t\t\tKVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;\n\tvcpu->run->internal.ndata = 2;\n\tvcpu->run->internal.data[0] = exit_reason.full;\n\tvcpu->run->internal.data[1] = vcpu->arch.last_vmentry_cpu;\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'KVM: VMX: Don't use vcpu->run->internal.ndata as an array index\n\n__vmx_handle_exit() uses vcpu->run->internal.ndata as an index for\nan array access. Since vcpu->run is (can be) mapped to a user address\nspace with a writer permission, the 'ndata' could be updated by the\nuser process at anytime (the user process can set it to outside the\nbounds of the array).\nSo, it is not safe that __vmx_handle_exit() uses the 'ndata' that way.\n\nFixes: 1aa561b1a4c0 (\"kvm: x86: Add \"last CPU\" to some KVM_EXIT information\")\nSigned-off-by: Reiji Watanabe \nReviewed-by: Jim Mattson \nMessage-Id: <20210413154739.490299-1-reijiw@google.com>\nCc: stable@vger.kernel.org\nSigned-off-by: Paolo Bonzini '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TEST_F(HttpConnectionManagerConfigTest, NormalizePathDefault) {\n const std::string yaml_string = R\"EOF(\n stat_prefix: ingress_http\n route_config:\n name: local_route\n http_filters:\n - name: envoy.filters.http.router\n )EOF\";\n\n EXPECT_CALL(context_.runtime_loader_.snapshot_, featureEnabled(_, An()))\n .WillOnce(Invoke(&context_.runtime_loader_.snapshot_,\n &Runtime::MockSnapshot::featureEnabledDefault));\n HttpConnectionManagerConfig config(parseHttpConnectionManagerFromYaml(yaml_string), context_,\n date_provider_, route_config_provider_manager_,\n scoped_routes_config_provider_manager_, http_tracer_manager_,\n filter_config_provider_manager_);\n#ifdef ENVOY_NORMALIZE_PATH_BY_DEFAULT\n EXPECT_TRUE(config.shouldNormalizePath());\n#else\n EXPECT_FALSE(config.shouldNormalizePath());\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-22'], 'message': 'Implement handling of escaped slash characters in URL path\n\nFixes: CVE-2021-29492\n\nSigned-off-by: Yan Avlasov '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int dissect_CPMSetBindings(tvbuff_t *tvb, packet_info *pinfo, proto_tree *parent_tree, gboolean in, void *private_data)\n{\n\tgint offset = 16;\n\tstruct CPMSetBindingsIn request;\n\n\tcol_append_str(pinfo->cinfo, COL_INFO, \"SetBindings\");\n\tif (in) {\n\n\t\tstruct mswsp_ct *ct = NULL;\n\t\tstruct message_data *data = NULL;\n\t\tproto_item *ti;\n\t\tproto_tree *tree, *pad_tree;\n\t\tguint32 size, num, n;\n\t\tgint64 column_size;\n\n\t\tti = proto_tree_add_item(parent_tree, hf_mswsp_msg, tvb, offset, -1, ENC_NA);\n\t\ttree = proto_item_add_subtree(ti, ett_mswsp_msg);\n\n\t\tproto_item_set_text(ti, \"SetBindingsIn\");\n\n\t\tpad_tree = proto_tree_add_subtree(tree, tvb, offset, 0, ett_mswsp_pad, &ti, \"Padding\");\n\n\t\tproto_tree_add_item(tree, hf_mswsp_msg_cpmsetbinding_hcursor, tvb, offset, 4, ENC_LITTLE_ENDIAN);\n\t\trequest.hcursor = tvb_get_letohl(tvb, offset);\n\t\toffset += 4;\n\t\trequest.brow = tvb_get_letohl(tvb, offset);\n\t\tproto_tree_add_item(tree, hf_mswsp_msg_cpmsetbinding_cbrow, tvb, offset, 4, ENC_LITTLE_ENDIAN);\n\t\toffset += 4;\n\n\t\tsize = tvb_get_letohl(tvb, offset);\n\t\trequest.bbindingdesc = size;\n\t\tproto_tree_add_item(tree, hf_mswsp_msg_cpmsetbinding_desc, tvb, offset, 4, ENC_LITTLE_ENDIAN);\n\t\toffset += 4;\n\n\t\trequest.dummy = tvb_get_letohl(tvb, offset);\n\t\tproto_tree_add_item(tree, hf_mswsp_msg_cpmsetbinding_dummy, tvb, offset, 4, ENC_LITTLE_ENDIAN);\n\t\toffset += 4;\n\n\t\tnum = tvb_get_letohl(tvb, offset);\n\t\trequest.ccolumns = num;\n\t\tti = proto_tree_add_item(tree, hf_mswsp_msg_cpmsetbinding_ccolumns, tvb, offset, 4, ENC_LITTLE_ENDIAN);\n\t\toffset += 4;\n\n\t\tproto_tree_add_item(tree, hf_mswsp_msg_cpmsetbinding_acolumns, tvb, offset, size-4, ENC_NA);\n\n\t\t/* Sanity check size value */\n\t\tcolumn_size = num*MIN_CTABLECOL_SIZE;\n\t\tif (column_size > tvb_reported_length_remaining(tvb, offset))\n\t\t{\n\t\t\texpert_add_info(pinfo, ti, &ei_mswsp_msg_cpmsetbinding_ccolumns);\n\t\t\treturn tvb_reported_length(tvb);\n\t\t}\n\n\t\tct = get_create_converstation_data(pinfo);\n\n\t\trequest.acolumns = (struct CTableColumn*)wmem_alloc(wmem_file_scope(),\n\t\t\t\t\t\t sizeof(struct CTableColumn) * num);\n\t\tfor (n=0; ncontent.bindingsin = request;\n\t\t}\n\n\t} else { /* server only returns status with header */\n\t}\n\n\treturn tvb_reported_length(tvb);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-770'], 'message': 'MS-WSP: Don't allocate huge amounts of memory.\n\nAdd a couple of memory allocation sanity checks, one of which\nfixes #17331.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void dname_pkt_copy(sldns_buffer* pkt, uint8_t* to, uint8_t* dname)\n{\n\t/* copy over the dname and decompress it at the same time */\n\tsize_t len = 0;\n\tuint8_t lablen;\n\tlablen = *dname++;\n\twhile(lablen) {\n\t\tif(LABEL_IS_PTR(lablen)) {\n\t\t\t/* follow pointer */\n\t\t\tdname = sldns_buffer_at(pkt, PTR_OFFSET(lablen, *dname));\n\t\t\tlablen = *dname++;\n\t\t\tcontinue;\n\t\t}\n\t\tlog_assert(lablen <= LDNS_MAX_LABELLEN);\n\t\tlen += (size_t)lablen+1;\n\t\tif(len >= LDNS_MAX_DOMAINLEN) {\n\t\t\t*to = 0; /* end the result prematurely */\n\t\t\tlog_err(\"bad dname in dname_pkt_copy\");\n\t\t\treturn;\n\t\t}\n\t\t*to++ = lablen;\n\t\tmemmove(to, dname, lablen);\n\t\tdname += lablen;\n\t\tto += lablen;\n\t\tlablen = *dname++;\n\t}\n\t/* copy last \\0 */\n\t*to = 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617'], 'message': '- Fix Assert Causing DoS in dname_pkt_copy(),\n reported by X41 D-Sec.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int flb_gzip_compress(void *in_data, size_t in_len,\n void **out_data, size_t *out_len)\n{\n int flush;\n int status;\n int footer_start;\n uint8_t *pb;\n size_t out_size;\n void *out_buf;\n z_stream strm;\n mz_ulong crc;\n\n out_size = in_len + 32;\n out_buf = flb_malloc(out_size);\n if (!out_buf) {\n flb_errno();\n flb_error(\"[gzip] could not allocate outgoing buffer\");\n return -1;\n }\n\n /* Initialize streaming buffer context */\n memset(&strm, '\\0', sizeof(strm));\n strm.zalloc = Z_NULL;\n strm.zfree = Z_NULL;\n strm.opaque = Z_NULL;\n strm.next_in = in_data;\n strm.avail_in = in_len;\n strm.total_out = 0;\n\n /* Deflate mode */\n deflateInit2(&strm, Z_DEFAULT_COMPRESSION,\n Z_DEFLATED, -Z_DEFAULT_WINDOW_BITS, 9, Z_DEFAULT_STRATEGY);\n\n /*\n * Miniz don't support GZip format directly, instead we will:\n *\n * - append manual GZip magic bytes\n * - deflate raw content\n * - append manual CRC32 data\n */\n gzip_header(out_buf);\n\n /* Header offset */\n pb = (uint8_t *) out_buf + FLB_GZIP_HEADER_OFFSET;\n\n flush = Z_NO_FLUSH;\n while (1) {\n strm.next_out = pb + strm.total_out;\n strm.avail_out = out_size - (pb - (uint8_t *) out_buf);\n\n if (strm.avail_in == 0) {\n flush = Z_FINISH;\n }\n\n status = deflate(&strm, flush);\n if (status == Z_STREAM_END) {\n break;\n }\n else if (status != Z_OK) {\n deflateEnd(&strm);\n return -1;\n }\n }\n\n if (deflateEnd(&strm) != Z_OK) {\n flb_free(out_buf);\n return -1;\n }\n *out_len = strm.total_out;\n\n /* Construct the gzip checksum (CRC32 footer) */\n footer_start = FLB_GZIP_HEADER_OFFSET + *out_len;\n pb = (uint8_t *) out_buf + footer_start;\n\n crc = mz_crc32(MZ_CRC32_INIT, in_data, in_len);\n *pb++ = crc & 0xFF;\n *pb++ = (crc >> 8) & 0xFF;\n *pb++ = (crc >> 16) & 0xFF;\n *pb++ = (crc >> 24) & 0xFF;\n *pb++ = in_len & 0xFF;\n *pb++ = (in_len >> 8) & 0xFF;\n *pb++ = (in_len >> 16) & 0xFF;\n *pb++ = (in_len >> 24) & 0xFF;\n\n /* Set the real buffer size for the caller */\n *out_len += FLB_GZIP_HEADER_OFFSET + 8;\n *out_data = out_buf;\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'gzip: fix compression size calculation (oss-fuzz 27261)\n\nSigned-off-by: davkor '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void assertInvalidProjection(const char* queryStr, const char* projStr) {\n BSONObj query = fromjson(queryStr);\n BSONObj projObj = fromjson(projStr);\n QueryTestServiceContext serviceCtx;\n auto opCtx = serviceCtx.makeOperationContext();\n const boost::intrusive_ptr expCtx(\n new ExpressionContext(opCtx.get(), std::unique_ptr(nullptr), kTestNss));\n StatusWithMatchExpression statusWithMatcher =\n MatchExpressionParser::parse(query, std::move(expCtx));\n ASSERT_OK(statusWithMatcher.getStatus());\n std::unique_ptr queryMatchExpr = std::move(statusWithMatcher.getValue());\n ASSERT_THROWS(\n projection_ast::parse(expCtx, projObj, queryMatchExpr.get(), query, ProjectionPolicies{}),\n DBException);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-732'], 'message': 'SERVER-53929 Add stricter parser checks around positional projection'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: Http::Stream::getNextRangeOffset() const\n{\n debugs (33, 5, \"range: \" << http->request->range <<\n \"; http offset \" << http->out.offset <<\n \"; reply \" << reply);\n\n // XXX: This method is called from many places, including pullData() which\n // may be called before prepareReply() [on some Squid-generated errors].\n // Hence, we may not even know yet whether we should honor/do ranges.\n\n if (http->request->range) {\n /* offset in range specs does not count the prefix of an http msg */\n /* check: reply was parsed and range iterator was initialized */\n assert(http->range_iter.valid);\n /* filter out data according to range specs */\n assert(canPackMoreRanges());\n {\n assert(http->range_iter.currentSpec());\n /* offset of still missing data */\n int64_t start = http->range_iter.currentSpec()->offset +\n http->range_iter.currentSpec()->length -\n http->range_iter.debt();\n debugs(33, 3, \"clientPackMoreRanges: in: offset: \" << http->out.offset);\n debugs(33, 3, \"clientPackMoreRanges: out:\"\n \" start: \" << start <<\n \" spec[\" << http->range_iter.pos - http->request->range->begin() << \"]:\" <<\n \" [\" << http->range_iter.currentSpec()->offset <<\n \", \" << http->range_iter.currentSpec()->offset +\n http->range_iter.currentSpec()->length << \"),\"\n \" len: \" << http->range_iter.currentSpec()->length <<\n \" debt: \" << http->range_iter.debt());\n if (http->range_iter.currentSpec()->length != -1)\n assert(http->out.offset <= start); /* we did not miss it */\n\n return start;\n }\n\n } else if (reply && reply->contentRange()) {\n /* request does not have ranges, but reply does */\n /* TODO: should use range_iter_pos on reply, as soon as reply->content_range\n * becomes HttpHdrRange rather than HttpHdrRangeSpec.\n */\n return http->out.offset + reply->contentRange()->spec.offset;\n }\n\n return http->out.offset;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Handle more partial responses (#791)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool pyc_is_code(ut8 b, ut32 magic) {\n\tif ((magic == 0x00949494 || magic == 0x0099be2a || magic == 0x0099be3a || magic == 0x00999901) && (pyc_is_object ((b & ~FLAG_REF), TYPE_CODE_v0))) {\n\t\t//TYPE_CODE_V0 for Python < 1.0\n\t\treturn true;\n\t}\n\tif (pyc_is_object ((b & ~FLAG_REF), TYPE_CODE_v1)) {\n\t\treturn true;\n\t}\n\treturn false;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'Fix #18679 - UAF when parsing corrupted pyc files ##bin'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void cipso_v4_doi_putdef(struct cipso_v4_doi *doi_def)\n{\n\tif (!doi_def)\n\t\treturn;\n\n\tif (!refcount_dec_and_test(&doi_def->refcount))\n\t\treturn;\n\tspin_lock(&cipso_v4_doi_list_lock);\n\tlist_del_rcu(&doi_def->list);\n\tspin_unlock(&cipso_v4_doi_list_lock);\n\n\tcipso_v4_cache_invalidate();\n\tcall_rcu(&doi_def->rcu, cipso_v4_doi_free_rcu);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'cipso,calipso: resolve a number of problems with the DOI refcounts\n\nThe current CIPSO and CALIPSO refcounting scheme for the DOI\ndefinitions is a bit flawed in that we:\n\n1. Don't correctly match gets/puts in netlbl_cipsov4_list().\n2. Decrement the refcount on each attempt to remove the DOI from the\n DOI list, only removing it from the list once the refcount drops\n to zero.\n\nThis patch fixes these problems by adding the missing \"puts\" to\nnetlbl_cipsov4_list() and introduces a more conventional, i.e.\nnot-buggy, refcounting mechanism to the DOI definitions. Upon the\naddition of a DOI to the DOI list, it is initialized with a refcount\nof one, removing a DOI from the list removes it from the list and\ndrops the refcount by one; \"gets\" and \"puts\" behave as expected with\nrespect to refcounts, increasing and decreasing the DOI's refcount by\none.\n\nFixes: b1edeb102397 (\"netlabel: Replace protocol/NetLabel linking with refrerence counts\")\nFixes: d7cce01504a0 (\"netlabel: Add support for removing a CALIPSO DOI.\")\nReported-by: syzbot+9ec037722d2603a9f52e@syzkaller.appspotmail.com\nSigned-off-by: Paul Moore \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: XSetIconName (\n register Display *dpy,\n Window w,\n _Xconst char *icon_name)\n{\n return XChangeProperty(dpy, w, XA_WM_ICON_NAME, XA_STRING, 8,\n PropModeReplace, (_Xconst unsigned char *)icon_name,\n\t\t\t icon_name ? (int) strlen(icon_name) : 0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'Reject string longer than USHRT_MAX before sending them on the wire\n\nThe X protocol uses CARD16 values to represent the length so\nthis would overflow.\n\nCVE-2021-31535\n\nSigned-off-by: Matthieu Herrb '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: char **XListFontsWithInfo(\nregister Display *dpy,\n_Xconst char *pattern, /* null-terminated */\nint maxNames,\nint *actualCount,\t/* RETURN */\nXFontStruct **info)\t/* RETURN */\n{\n unsigned long nbytes;\n unsigned long reply_left;\t/* unused data left in reply buffer */\n register int i;\n register XFontStruct *fs;\n unsigned int size = 0;\n XFontStruct *finfo = NULL;\n char **flist = NULL;\n xListFontsWithInfoReply reply;\n register xListFontsReq *req;\n int j;\n\n LockDisplay(dpy);\n GetReq(ListFontsWithInfo, req);\n req->maxNames = maxNames;\n nbytes = req->nbytes = pattern ? (CARD16) strlen (pattern) : 0;\n req->length += (nbytes + 3) >> 2;\n _XSend (dpy, pattern, nbytes);\n /* use _XSend instead of Data, since subsequent _XReply will flush buffer */\n\n for (i = 0; ; i++) {\n\tif (!_XReply (dpy, (xReply *) &reply,\n\t\t ((SIZEOF(xListFontsWithInfoReply) -\n\t\t\tSIZEOF(xGenericReply)) >> 2), xFalse)) {\n\t reply.nameLength = 0; /* avoid trying to read more replies */\n\t reply_left = 0;\n\t goto badmem;\n\t}\n\treply_left = reply.length -\n\t ((SIZEOF(xListFontsWithInfoReply) -\tSIZEOF(xGenericReply)) >> 2);\n\tif (reply.nameLength == 0) {\n\t _XEatDataWords(dpy, reply_left);\n\t break;\n\t}\n\tif (reply.nReplies >= (INT_MAX - i)) /* avoid overflowing size */\n\t goto badmem;\n\tif ((i + reply.nReplies) >= size) {\n\t size = i + reply.nReplies + 1;\n\n\t if (size >= (INT_MAX / sizeof(XFontStruct)))\n\t\tgoto badmem;\n\n\t if (finfo) {\n\t\tXFontStruct * tmp_finfo;\n\t\tchar ** tmp_flist;\n\n\t\ttmp_finfo = Xreallocarray (finfo, size, sizeof(XFontStruct));\n\t\tif (tmp_finfo)\n\t\t finfo = tmp_finfo;\n\t\telse\n\t\t goto badmem;\n\n\t\ttmp_flist = Xreallocarray (flist, size + 1, sizeof(char *));\n\t\tif (tmp_flist)\n\t\t flist = tmp_flist;\n\t\telse\n\t\t goto badmem;\n\t }\n\t else {\n\t\tif (! (finfo = Xmallocarray(size, sizeof(XFontStruct))))\n\t\t goto clearwire;\n\t\tif (! (flist = Xmallocarray(size + 1, sizeof(char *)))) {\n\t\t Xfree(finfo);\n\t\t goto clearwire;\n\t\t}\n\t }\n\t}\n\tfs = &finfo[i];\n\n\tfs->ext_data \t\t= NULL;\n\tfs->per_char\t\t= NULL;\n\tfs->fid \t\t= None;\n\tfs->direction \t\t= reply.drawDirection;\n\tfs->min_char_or_byte2\t= reply.minCharOrByte2;\n\tfs->max_char_or_byte2 \t= reply.maxCharOrByte2;\n\tfs->min_byte1 \t\t= reply.minByte1;\n\tfs->max_byte1 \t\t= reply.maxByte1;\n\tfs->default_char\t= reply.defaultChar;\n\tfs->all_chars_exist \t= reply.allCharsExist;\n\tfs->ascent \t\t= cvtINT16toInt (reply.fontAscent);\n\tfs->descent \t\t= cvtINT16toInt (reply.fontDescent);\n\n\t/* XXX the next two statements won't work if short isn't 16 bits */\n\tfs->min_bounds = * (XCharStruct *) &reply.minBounds;\n\tfs->max_bounds = * (XCharStruct *) &reply.maxBounds;\n\n\tfs->n_properties = reply.nFontProps;\n\tfs->properties = NULL;\n\tif (fs->n_properties > 0) {\n\t /* nFontProps is a CARD16 */\n\t nbytes = reply.nFontProps * SIZEOF(xFontProp);\n\t if ((nbytes >> 2) <= reply_left) {\n\t\tfs->properties = Xmallocarray (reply.nFontProps,\n sizeof(XFontProp));\n\t }\n\t if (! fs->properties)\n\t\tgoto badmem;\n\t _XRead32 (dpy, (long *)fs->properties, nbytes);\n\t reply_left -= (nbytes >> 2);\n\t}\n\n\t/* nameLength is a CARD8 */\n\tnbytes = reply.nameLength + 1;\n\tif (!i)\n\t nbytes++; /* make first string 1 byte longer, to match XListFonts */\n\tflist[i] = Xmalloc (nbytes);\n\tif (! flist[i]) {\n\t if (finfo[i].properties) Xfree(finfo[i].properties);\n\t goto badmem;\n\t}\n\tif (!i) {\n\t *flist[0] = 0; /* zero to distinguish from XListFonts */\n\t flist[0]++;\n\t}\n\tflist[i][reply.nameLength] = '\\0';\n\t_XReadPad (dpy, flist[i], (long) reply.nameLength);\n }\n *info = finfo;\n *actualCount = i;\n if (flist)\n\tflist[i] = NULL; /* required in case XFreeFontNames is called */\n UnlockDisplay(dpy);\n SyncHandle();\n return (flist);\n\n\n badmem:\n /* Free all memory allocated by this function. */\n for (j=(i-1); (j >= 0); j--) {\n if (j == 0)\n flist[j]--; /* was incremented above */\n Xfree(flist[j]);\n if (finfo[j].properties) Xfree(finfo[j].properties);\n }\n Xfree(flist);\n Xfree(finfo);\n\n clearwire:\n /* Clear the wire. */\n _XEatDataWords(dpy, reply_left);\n while ((reply.nameLength != 0) &&\n\t _XReply(dpy, (xReply *) &reply,\n\t\t ((SIZEOF(xListFontsWithInfoReply) - SIZEOF(xGenericReply))\n\t\t >> 2), xTrue));\n UnlockDisplay(dpy);\n SyncHandle();\n *info = NULL;\n *actualCount = 0;\n return (char **) NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'Reject string longer than USHRT_MAX before sending them on the wire\n\nThe X protocol uses CARD16 values to represent the length so\nthis would overflow.\n\nCVE-2021-31535\n\nSigned-off-by: Matthieu Herrb '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: HeaderLookupTable_t::lookup (const char *buf, const std::size_t len) const {\n const HeaderTableRecord *r = HttpHeaderHashTable::lookup(buf, len);\n if (!r)\n return BadHdr;\n return *r;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-116', 'CWE-79'], 'message': 'Merge pull request from GHSA-jjq6-mh2h-g39h'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void Curl_attach_connnection(struct Curl_easy *data,\n struct connectdata *conn)\n{\n DEBUGASSERT(!data->conn);\n DEBUGASSERT(conn);\n data->conn = conn;\n Curl_llist_insert_next(&conn->easyq, conn->easyq.tail, data,\n &data->conn_queue);\n if(conn->handler->attach)\n conn->handler->attach(data, conn);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-295'], 'message': 'openssl: associate/detach the transfer from connection\n\nCVE-2021-22901\n\nBug: https://curl.se/docs/CVE-2021-22901.html'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: lyxml_parse_elem(struct ly_ctx *ctx, const char *data, unsigned int *len, struct lyxml_elem *parent, int options)\n{\n const char *c = data, *start, *e;\n const char *lws; /* leading white space for handling mixed content */\n int uc;\n char *str;\n char *prefix = NULL;\n unsigned int prefix_len = 0;\n struct lyxml_elem *elem = NULL, *child;\n struct lyxml_attr *attr;\n unsigned int size;\n int nons_flag = 0, closed_flag = 0;\n\n *len = 0;\n\n if (*c != '<') {\n return NULL;\n }\n\n /* locate element name */\n c++;\n e = c;\n\n uc = lyxml_getutf8(ctx, e, &size);\n if (!is_xmlnamestartchar(uc)) {\n LOGVAL(ctx, LYE_XML_INVAL, LY_VLOG_NONE, NULL, \"NameStartChar of the element\");\n return NULL;\n }\n e += size;\n uc = lyxml_getutf8(ctx, e, &size);\n while (is_xmlnamechar(uc)) {\n if (*e == ':') {\n if (prefix_len) {\n LOGVAL(ctx, LYE_XML_INVAL, LY_VLOG_NONE, NULL, \"element name, multiple colons found\");\n goto error;\n }\n /* element in a namespace */\n start = e + 1;\n\n /* look for the prefix in namespaces */\n prefix_len = e - c;\n LY_CHECK_ERR_GOTO(prefix, LOGVAL(ctx, LYE_XML_INCHAR, LY_VLOG_NONE, NULL, e), error);\n prefix = malloc((prefix_len + 1) * sizeof *prefix);\n LY_CHECK_ERR_GOTO(!prefix, LOGMEM(ctx), error);\n memcpy(prefix, c, prefix_len);\n prefix[prefix_len] = '\\0';\n c = start;\n }\n e += size;\n uc = lyxml_getutf8(ctx, e, &size);\n }\n if (!*e) {\n LOGVAL(ctx, LYE_EOF, LY_VLOG_NONE, NULL);\n free(prefix);\n return NULL;\n }\n\n /* allocate element structure */\n elem = calloc(1, sizeof *elem);\n LY_CHECK_ERR_RETURN(!elem, free(prefix); LOGMEM(ctx), NULL);\n\n elem->next = NULL;\n elem->prev = elem;\n if (parent) {\n lyxml_add_child(ctx, parent, elem);\n }\n\n /* store the name into the element structure */\n elem->name = lydict_insert(ctx, c, e - c);\n c = e;\n\nprocess:\n ign_xmlws(c);\n if (!strncmp(\"/>\", c, 2)) {\n /* we are done, it was EmptyElemTag */\n c += 2;\n elem->content = lydict_insert(ctx, \"\", 0);\n closed_flag = 1;\n } else if (*c == '>') {\n /* process element content */\n c++;\n lws = NULL;\n\n while (*c) {\n if (!strncmp(c, \"child) {\n /* leading white spaces were actually content */\n goto store_content;\n }\n\n /* Etag */\n c += 2;\n /* get name and check it */\n e = c;\n uc = lyxml_getutf8(ctx, e, &size);\n if (!is_xmlnamestartchar(uc)) {\n LOGVAL(ctx, LYE_XML_INVAL, LY_VLOG_XML, elem, \"NameStartChar of the element\");\n goto error;\n }\n e += size;\n uc = lyxml_getutf8(ctx, e, &size);\n while (is_xmlnamechar(uc)) {\n if (*e == ':') {\n /* element in a namespace */\n start = e + 1;\n\n /* look for the prefix in namespaces */\n if (!prefix || memcmp(prefix, c, e - c)) {\n LOGVAL(ctx, LYE_SPEC, LY_VLOG_XML, elem,\n \"Invalid (different namespaces) opening (%s) and closing element tags.\", elem->name);\n goto error;\n }\n c = start;\n }\n e += size;\n uc = lyxml_getutf8(ctx, e, &size);\n }\n if (!*e) {\n LOGVAL(ctx, LYE_EOF, LY_VLOG_NONE, NULL);\n goto error;\n }\n\n /* check that it corresponds to opening tag */\n size = e - c;\n str = malloc((size + 1) * sizeof *str);\n LY_CHECK_ERR_GOTO(!str, LOGMEM(ctx), error);\n memcpy(str, c, e - c);\n str[e - c] = '\\0';\n if (size != strlen(elem->name) || memcmp(str, elem->name, size)) {\n LOGVAL(ctx, LYE_SPEC, LY_VLOG_XML, elem,\n \"Invalid (mixed names) opening (%s) and closing (%s) element tags.\", elem->name, str);\n free(str);\n goto error;\n }\n free(str);\n c = e;\n\n ign_xmlws(c);\n if (*c != '>') {\n LOGVAL(ctx, LYE_SPEC, LY_VLOG_XML, elem, \"Data after closing element tag \\\"%s\\\".\", elem->name);\n goto error;\n }\n c++;\n if (!(elem->flags & LYXML_ELEM_MIXED) && !elem->content) {\n /* there was no content, but we don't want NULL (only if mixed content) */\n elem->content = lydict_insert(ctx, \"\", 0);\n }\n closed_flag = 1;\n break;\n\n } else if (!strncmp(c, \"\", &size)) {\n goto error;\n }\n c += size;\n } else if (!strncmp(c, \"\", &size)) {\n goto error;\n }\n c += size;\n } else if (!strncmp(c, \"flags & LYXML_ELEM_MIXED) {\n /* we have a mixed content */\n goto store_content;\n } else {\n /* leading white spaces were only formatting */\n lws = NULL;\n }\n }\n if (elem->content) {\n /* we have a mixed content */\n if (options & LYXML_PARSE_NOMIXEDCONTENT) {\n LOGVAL(ctx, LYE_XML_INVAL, LY_VLOG_XML, elem, \"XML element with mixed content\");\n goto error;\n }\n child = calloc(1, sizeof *child);\n LY_CHECK_ERR_GOTO(!child, LOGMEM(ctx), error);\n child->content = elem->content;\n elem->content = NULL;\n lyxml_add_child(ctx, elem, child);\n elem->flags |= LYXML_ELEM_MIXED;\n }\n child = lyxml_parse_elem(ctx, c, &size, elem, options);\n if (!child) {\n goto error;\n }\n c += size; /* move after processed child element */\n } else if (is_xmlws(*c)) {\n lws = c;\n ign_xmlws(c);\n } else {\nstore_content:\n /* store text content */\n if (lws) {\n /* process content including the leading white spaces */\n c = lws;\n lws = NULL;\n }\n str = parse_text(ctx, c, '<', &size);\n if (!str && !size) {\n goto error;\n }\n elem->content = lydict_insert_zc(ctx, str);\n c += size; /* move after processed text content */\n\n if (elem->child) {\n /* we have a mixed content */\n if (options & LYXML_PARSE_NOMIXEDCONTENT) {\n LOGVAL(ctx, LYE_XML_INVAL, LY_VLOG_XML, elem, \"XML element with mixed content\");\n goto error;\n }\n child = calloc(1, sizeof *child);\n LY_CHECK_ERR_GOTO(!child, LOGMEM(ctx), error);\n child->content = elem->content;\n elem->content = NULL;\n lyxml_add_child(ctx, elem, child);\n elem->flags |= LYXML_ELEM_MIXED;\n }\n }\n }\n } else {\n /* process attribute */\n attr = parse_attr(ctx, c, &size, elem);\n if (!attr) {\n goto error;\n }\n c += size; /* move after processed attribute */\n\n /* check namespace */\n if (attr->type == LYXML_ATTR_NS) {\n if ((!prefix || !prefix[0]) && !attr->name) {\n if (attr->value) {\n /* default prefix */\n elem->ns = (struct lyxml_ns *)attr;\n } else {\n /* xmlns=\"\" -> no namespace */\n nons_flag = 1;\n }\n } else if (prefix && prefix[0] && attr->name && !strncmp(attr->name, prefix, prefix_len + 1)) {\n /* matching namespace with prefix */\n elem->ns = (struct lyxml_ns *)attr;\n }\n }\n\n /* go back to finish element processing */\n goto process;\n }\n\n *len = c - data;\n\n if (!closed_flag) {\n LOGVAL(ctx, LYE_XML_MISS, LY_VLOG_XML, elem, \"closing element tag\", elem->name);\n goto error;\n }\n\n /* resolve all attribute prefixes */\n LY_TREE_FOR(elem->attr, attr) {\n if (attr->type == LYXML_ATTR_STD_UNRES) {\n str = (char *)attr->ns;\n attr->ns = lyxml_get_ns(elem, str);\n free(str);\n attr->type = LYXML_ATTR_STD;\n }\n }\n\n if (!elem->ns && !nons_flag && parent) {\n elem->ns = lyxml_get_ns(parent, prefix_len ? prefix : NULL);\n }\n free(prefix);\n return elem;\n\nerror:\n lyxml_free(ctx, elem);\n free(prefix);\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-674'], 'message': 'common FEATURE add a hard limit for recursion\n\nFixes #1453'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: read_yin_rpc_action(struct lys_module *module, struct lys_node *parent, struct lyxml_elem *yin,\n int options, struct unres_schema *unres)\n{\n struct ly_ctx *ctx = module->ctx;\n struct lyxml_elem *sub, *next, root;\n struct lys_node *node = NULL;\n struct lys_node *retval;\n struct lys_node_rpc_action *rpc;\n int r;\n int c_tpdf = 0, c_ftrs = 0, c_input = 0, c_output = 0, c_ext = 0;\n void *reallocated;\n\n if (!strcmp(yin->name, \"action\") && (module->version < 2)) {\n LOGVAL(ctx, LYE_INSTMT, LY_VLOG_LYS, parent, \"action\");\n return NULL;\n }\n\n /* init */\n memset(&root, 0, sizeof root);\n\n rpc = calloc(1, sizeof *rpc);\n LY_CHECK_ERR_RETURN(!rpc, LOGMEM(ctx), NULL);\n\n rpc->nodetype = (!strcmp(yin->name, \"rpc\") ? LYS_RPC : LYS_ACTION);\n rpc->prev = (struct lys_node *)rpc;\n retval = (struct lys_node *)rpc;\n\n if (read_yin_common(module, parent, retval, LYEXT_PAR_NODE, yin, OPT_IDENT | OPT_MODULE, unres)) {\n goto error;\n }\n\n LOGDBG(LY_LDGYIN, \"parsing %s statement \\\"%s\\\"\", yin->name, retval->name);\n\n /* insert the node into the schema tree */\n if (lys_node_addchild(parent, lys_main_module(module), retval, options)) {\n goto error;\n }\n\n /* process rpc's specific children */\n LY_TREE_FOR_SAFE(yin->child, next, sub) {\n if (strcmp(sub->ns->value, LY_NSYIN)) {\n /* extension */\n YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_ext, retval->ext_size, \"extensions\",\n rpc->nodetype == LYS_RPC ? \"rpc\" : \"action\", error);\n c_ext++;\n continue;\n } else if (!strcmp(sub->name, \"input\")) {\n if (c_input) {\n LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, yin->name);\n goto error;\n }\n c_input++;\n lyxml_unlink_elem(ctx, sub, 2);\n lyxml_add_child(ctx, &root, sub);\n } else if (!strcmp(sub->name, \"output\")) {\n if (c_output) {\n LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, yin->name);\n goto error;\n }\n c_output++;\n lyxml_unlink_elem(ctx, sub, 2);\n lyxml_add_child(ctx, &root, sub);\n\n /* data statements */\n } else if (!strcmp(sub->name, \"grouping\")) {\n lyxml_unlink_elem(ctx, sub, 2);\n lyxml_add_child(ctx, &root, sub);\n\n /* array counters */\n } else if (!strcmp(sub->name, \"typedef\")) {\n YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_tpdf, rpc->tpdf_size, \"typedefs\",\n rpc->nodetype == LYS_RPC ? \"rpc\" : \"action\", error);\n c_tpdf++;\n } else if (!strcmp(sub->name, \"if-feature\")) {\n YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_ftrs, retval->iffeature_size, \"if-features\",\n rpc->nodetype == LYS_RPC ? \"rpc\" : \"action\", error);\n c_ftrs++;\n } else {\n LOGVAL(ctx, LYE_INSTMT, LY_VLOG_LYS, retval, sub->name);\n goto error;\n }\n }\n\n /* middle part - process nodes with cardinality of 0..n except the data nodes */\n if (c_tpdf) {\n rpc->tpdf = calloc(c_tpdf, sizeof *rpc->tpdf);\n LY_CHECK_ERR_GOTO(!rpc->tpdf, LOGMEM(ctx), error);\n }\n if (c_ftrs) {\n rpc->iffeature = calloc(c_ftrs, sizeof *rpc->iffeature);\n LY_CHECK_ERR_GOTO(!rpc->iffeature, LOGMEM(ctx), error);\n }\n if (c_ext) {\n /* some extensions may be already present from the substatements */\n reallocated = realloc(retval->ext, (c_ext + retval->ext_size) * sizeof *retval->ext);\n LY_CHECK_ERR_GOTO(!reallocated, LOGMEM(ctx), error);\n retval->ext = reallocated;\n\n /* init memory */\n memset(&retval->ext[retval->ext_size], 0, c_ext * sizeof *retval->ext);\n }\n\n LY_TREE_FOR_SAFE(yin->child, next, sub) {\n if (strcmp(sub->ns->value, LY_NSYIN)) {\n /* extension */\n r = lyp_yin_fill_ext(retval, LYEXT_PAR_NODE, 0, 0, module, sub, &retval->ext, &retval->ext_size, unres);\n if (r) {\n goto error;\n }\n } else if (!strcmp(sub->name, \"typedef\")) {\n r = fill_yin_typedef(module, retval, sub, &rpc->tpdf[rpc->tpdf_size], unres);\n rpc->tpdf_size++;\n if (r) {\n goto error;\n }\n } else if (!strcmp(sub->name, \"if-feature\")) {\n r = fill_yin_iffeature(retval, 0, sub, &rpc->iffeature[rpc->iffeature_size], unres);\n rpc->iffeature_size++;\n if (r) {\n goto error;\n }\n }\n }\n\n lyp_reduce_ext_list(&retval->ext, retval->ext_size, c_ext + retval->ext_size);\n\n /* last part - process data nodes */\n LY_TREE_FOR_SAFE(root.child, next, sub) {\n if (!strcmp(sub->name, \"grouping\")) {\n node = read_yin_grouping(module, retval, sub, options, unres);\n } else if (!strcmp(sub->name, \"input\") || !strcmp(sub->name, \"output\")) {\n node = read_yin_input_output(module, retval, sub, options, unres);\n }\n if (!node) {\n goto error;\n }\n\n lyxml_free(ctx, sub);\n }\n\n return retval;\n\nerror:\n lys_node_free(retval, NULL, 0);\n while (root.child) {\n lyxml_free(ctx, root.child);\n }\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617'], 'message': 'schema tree BUGFIX freeing nodes with no module set\n\nContext must be passed explicitly for these cases.\nFixes #1452'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: read_yin_input_output(struct lys_module *module, struct lys_node *parent, struct lyxml_elem *yin,\n int options, struct unres_schema *unres)\n{\n struct ly_ctx *ctx = module->ctx;\n struct lyxml_elem *sub, *next, root;\n struct lys_node *node = NULL;\n struct lys_node *retval = NULL;\n struct lys_node_inout *inout;\n int r;\n int c_tpdf = 0, c_must = 0, c_ext = 0;\n\n /* init */\n memset(&root, 0, sizeof root);\n\n inout = calloc(1, sizeof *inout);\n LY_CHECK_ERR_RETURN(!inout, LOGMEM(ctx), NULL);\n inout->prev = (struct lys_node *)inout;\n\n if (!strcmp(yin->name, \"input\")) {\n inout->nodetype = LYS_INPUT;\n inout->name = lydict_insert(ctx, \"input\", 0);\n } else if (!strcmp(yin->name, \"output\")) {\n inout->nodetype = LYS_OUTPUT;\n inout->name = lydict_insert(ctx, \"output\", 0);\n } else {\n LOGINT(ctx);\n free(inout);\n goto error;\n }\n\n retval = (struct lys_node *)inout;\n retval->module = module;\n\n LOGDBG(LY_LDGYIN, \"parsing %s statement \\\"%s\\\"\", yin->name, retval->name);\n\n /* insert the node into the schema tree */\n if (lys_node_addchild(parent, lys_main_module(module), retval, options)) {\n goto error;\n }\n\n /* data statements */\n LY_TREE_FOR_SAFE(yin->child, next, sub) {\n if (!sub->ns) {\n /* garbage */\n lyxml_free(ctx, sub);\n } else if (strcmp(sub->ns->value, LY_NSYIN)) {\n /* extension */\n YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_ext, retval->ext_size, \"extensions\",\n inout->nodetype == LYS_INPUT ? \"input\" : \"output\", error);\n c_ext++;\n } else if (!strcmp(sub->name, \"container\") ||\n !strcmp(sub->name, \"leaf-list\") ||\n !strcmp(sub->name, \"leaf\") ||\n !strcmp(sub->name, \"list\") ||\n !strcmp(sub->name, \"choice\") ||\n !strcmp(sub->name, \"uses\") ||\n !strcmp(sub->name, \"grouping\") ||\n !strcmp(sub->name, \"anyxml\") ||\n !strcmp(sub->name, \"anydata\")) {\n lyxml_unlink_elem(ctx, sub, 2);\n lyxml_add_child(ctx, &root, sub);\n\n /* array counters */\n } else if (!strcmp(sub->name, \"typedef\")) {\n YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_tpdf, inout->tpdf_size, \"typedefs\",\n inout->nodetype == LYS_INPUT ? \"input\" : \"output\", error);\n c_tpdf++;\n\n } else if ((module->version >= 2) && !strcmp(sub->name, \"must\")) {\n YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_must, inout->must_size, \"musts\",\n inout->nodetype == LYS_INPUT ? \"input\" : \"output\", error);\n c_must++;\n\n } else {\n LOGVAL(ctx, LYE_INSTMT, LY_VLOG_LYS, retval, sub->name);\n goto error;\n }\n }\n\n if (!root.child) {\n LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, retval, \"schema-node\", strnodetype(retval->nodetype));\n goto error;\n }\n\n /* middle part - process nodes with cardinality of 0..n except the data nodes */\n if (c_tpdf) {\n inout->tpdf = calloc(c_tpdf, sizeof *inout->tpdf);\n LY_CHECK_ERR_GOTO(!inout->tpdf, LOGMEM(ctx), error);\n }\n if (c_must) {\n inout->must = calloc(c_must, sizeof *inout->must);\n LY_CHECK_ERR_GOTO(!inout->must, LOGMEM(ctx), error);\n }\n if (c_ext) {\n inout->ext = calloc(c_ext, sizeof *inout->ext);\n LY_CHECK_ERR_GOTO(!inout->ext, LOGMEM(ctx), error);\n }\n\n LY_TREE_FOR_SAFE(yin->child, next, sub) {\n if (strcmp(sub->ns->value, LY_NSYIN)) {\n /* extension */\n r = lyp_yin_fill_ext(retval, LYEXT_PAR_NODE, 0, 0, module, sub, &retval->ext, &retval->ext_size, unres);\n if (r) {\n goto error;\n }\n } else if (!strcmp(sub->name, \"must\")) {\n r = fill_yin_must(module, sub, &inout->must[inout->must_size], unres);\n inout->must_size++;\n if (r) {\n goto error;\n }\n } else { /* typedef */\n r = fill_yin_typedef(module, retval, sub, &inout->tpdf[inout->tpdf_size], unres);\n inout->tpdf_size++;\n if (r) {\n goto error;\n }\n }\n }\n\n lyp_reduce_ext_list(&retval->ext, retval->ext_size, c_ext + retval->ext_size);\n\n /* last part - process data nodes */\n options |= LYS_PARSE_OPT_CFG_IGNORE;\n LY_TREE_FOR_SAFE(root.child, next, sub) {\n if (!strcmp(sub->name, \"container\")) {\n node = read_yin_container(module, retval, sub, options, unres);\n } else if (!strcmp(sub->name, \"leaf-list\")) {\n node = read_yin_leaflist(module, retval, sub, options, unres);\n } else if (!strcmp(sub->name, \"leaf\")) {\n node = read_yin_leaf(module, retval, sub, options, unres);\n } else if (!strcmp(sub->name, \"list\")) {\n node = read_yin_list(module, retval, sub, options, unres);\n } else if (!strcmp(sub->name, \"choice\")) {\n node = read_yin_choice(module, retval, sub, options, unres);\n } else if (!strcmp(sub->name, \"uses\")) {\n node = read_yin_uses(module, retval, sub, options, unres);\n } else if (!strcmp(sub->name, \"grouping\")) {\n node = read_yin_grouping(module, retval, sub, options, unres);\n } else if (!strcmp(sub->name, \"anyxml\")) {\n node = read_yin_anydata(module, retval, sub, LYS_ANYXML, options, unres);\n } else if (!strcmp(sub->name, \"anydata\")) {\n node = read_yin_anydata(module, retval, sub, LYS_ANYDATA, options, unres);\n }\n if (!node) {\n goto error;\n }\n\n lyxml_free(ctx, sub);\n }\n\n /* check XPath dependencies */\n if (!(ctx->models.flags & LY_CTX_TRUSTED) && inout->must) {\n if (options & LYS_PARSE_OPT_INGRP) {\n if (lyxp_node_check_syntax(retval)) {\n goto error;\n }\n } else {\n if (unres_schema_add_node(module, unres, retval, UNRES_XPATH, NULL) == -1) {\n goto error;\n }\n }\n }\n\n return retval;\n\nerror:\n lys_node_free(retval, NULL, 0);\n while (root.child) {\n lyxml_free(ctx, root.child);\n }\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617'], 'message': 'schema tree BUGFIX freeing nodes with no module set\n\nContext must be passed explicitly for these cases.\nFixes #1452'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int identity_count(void *v, const char *key, const char *val)\n{\n int *count = v;\n *count += strlen(key) * 3 + strlen(val) * 3 + 1;\n return 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'mod_session: account for the '&' in identity_concat().\n\ngit-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1887052 13f79535-47bb-0310-9956-ffa450edef68'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: rsa_decrypt_tr(const struct rsa_public_key *pub,\n\t const struct rsa_private_key *key,\n\t void *random_ctx, nettle_random_func *random,\n\t size_t *length, uint8_t *message,\n\t const mpz_t gibberish)\n{\n TMP_GMP_DECL (m, mp_limb_t);\n TMP_GMP_DECL (em, uint8_t);\n mp_size_t key_limb_size;\n int res;\n\n key_limb_size = NETTLE_OCTET_SIZE_TO_LIMB_SIZE(key->size);\n\n TMP_GMP_ALLOC (m, key_limb_size);\n TMP_GMP_ALLOC (em, key->size);\n\n res = _rsa_sec_compute_root_tr (pub, key, random_ctx, random, m,\n\t\t\t\t mpz_limbs_read(gibberish),\n\t\t\t\t mpz_size(gibberish));\n\n mpn_get_base256 (em, key->size, m, key_limb_size);\n\n res &= _pkcs1_sec_decrypt_variable (length, message, key->size, em);\n\n TMP_GMP_FREE (em);\n TMP_GMP_FREE (m);\n return res;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Change _rsa_sec_compute_root_tr to take a fix input size.\n\nImproves consistency with _rsa_sec_compute_root, and fixes zero-input bug.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static bool io_rw_reissue(struct io_kiocb *req, long res)\n{\n#ifdef CONFIG_BLOCK\n\tint ret;\n\n\tif ((res != -EAGAIN && res != -EOPNOTSUPP) || io_wq_current_is_worker())\n\t\treturn false;\n\n\tinit_task_work(&req->task_work, io_rw_resubmit);\n\tret = io_req_task_work_add(req, &req->task_work);\n\tif (!ret)\n\t\treturn true;\n#endif\n\treturn false;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'io_uring: hold 'ctx' reference around task_work queue + execute\n\nWe're holding the request reference, but we need to go one higher\nto ensure that the ctx remains valid after the request has finished.\nIf the ring is closed with pending task_work inflight, and the\ngiven io_kiocb finishes sync during issue, then we need a reference\nto the ring itself around the task_work execution cycle.\n\nCc: stable@vger.kernel.org # v5.7+\nReported-by: syzbot+9b260fc33297966f5a8e@syzkaller.appspotmail.com\nSigned-off-by: Jens Axboe '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int validate_tmpl(int nr, struct xfrm_user_tmpl *ut, u16 family)\n{\n\tu16 prev_family;\n\tint i;\n\n\tif (nr > XFRM_MAX_DEPTH)\n\t\treturn -EINVAL;\n\n\tprev_family = family;\n\n\tfor (i = 0; i < nr; i++) {\n\t\t/* We never validated the ut->family value, so many\n\t\t * applications simply leave it at zero. The check was\n\t\t * never made and ut->family was ignored because all\n\t\t * templates could be assumed to have the same family as\n\t\t * the policy itself. Now that we will have ipv4-in-ipv6\n\t\t * and ipv6-in-ipv4 tunnels, this is no longer true.\n\t\t */\n\t\tif (!ut[i].family)\n\t\t\tut[i].family = family;\n\n\t\tswitch (ut[i].mode) {\n\t\tcase XFRM_MODE_TUNNEL:\n\t\tcase XFRM_MODE_BEET:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (ut[i].family != prev_family)\n\t\t\t\treturn -EINVAL;\n\t\t\tbreak;\n\t\t}\n\t\tif (ut[i].mode >= XFRM_MODE_MAX)\n\t\t\treturn -EINVAL;\n\n\t\tprev_family = ut[i].family;\n\n\t\tswitch (ut[i].family) {\n\t\tcase AF_INET:\n\t\t\tbreak;\n#if IS_ENABLED(CONFIG_IPV6)\n\t\tcase AF_INET6:\n\t\t\tbreak;\n#endif\n\t\tdefault:\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t\tswitch (ut[i].id.proto) {\n\t\tcase IPPROTO_AH:\n\t\tcase IPPROTO_ESP:\n\t\tcase IPPROTO_COMP:\n#if IS_ENABLED(CONFIG_IPV6)\n\t\tcase IPPROTO_ROUTING:\n\t\tcase IPPROTO_DSTOPTS:\n#endif\n\t\tcase IPSEC_PROTO_ANY:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'xfrm: clean up xfrm protocol checks\n\nIn commit 6a53b7593233 (\"xfrm: check id proto in validate_tmpl()\")\nI introduced a check for xfrm protocol, but according to Herbert\nIPSEC_PROTO_ANY should only be used as a wildcard for lookup, so\nit should be removed from validate_tmpl().\n\nAnd, IPSEC_PROTO_ANY is expected to only match 3 IPSec-specific\nprotocols, this is why xfrm_state_flush() could still miss\nIPPROTO_ROUTING, which leads that those entries are left in\nnet->xfrm.state_all before exit net. Fix this by replacing\nIPSEC_PROTO_ANY with zero.\n\nThis patch also extracts the check from validate_tmpl() to\nxfrm_id_proto_valid() and uses it in parse_ipsecrequest().\nWith this, no other protocols should be added into xfrm.\n\nFixes: 6a53b7593233 (\"xfrm: check id proto in validate_tmpl()\")\nReported-by: syzbot+0bf0519d6e0de15914fe@syzkaller.appspotmail.com\nCc: Steffen Klassert \nCc: Herbert Xu \nSigned-off-by: Cong Wang \nAcked-by: Herbert Xu \nSigned-off-by: Steffen Klassert '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void ucma_move_events(struct ucma_context *ctx, struct ucma_file *file)\n{\n\tstruct ucma_event *uevent, *tmp;\n\n\tlist_for_each_entry_safe(uevent, tmp, &ctx->file->event_list, list)\n\t\tif (uevent->ctx == ctx)\n\t\t\tlist_move_tail(&uevent->list, &file->event_list);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'RDMA/ucma: Rework ucma_migrate_id() to avoid races with destroy\n\nucma_destroy_id() assumes that all things accessing the ctx will do so via\nthe xarray. This assumption violated only in the case the FD is being\nclosed, then the ctx is reached via the ctx_list. Normally this is OK\nsince ucma_destroy_id() cannot run concurrenty with release(), however\nwith ucma_migrate_id() is involved this can violated as the close of the\n2nd FD can run concurrently with destroy on the first:\n\n CPU0 CPU1\n ucma_destroy_id(fda)\n ucma_migrate_id(fda -> fdb)\n ucma_get_ctx()\n xa_lock()\n _ucma_find_context()\n xa_erase()\n xa_unlock()\n xa_lock()\n ctx->file = new_file\n list_move()\n xa_unlock()\n ucma_put_ctx()\n\n ucma_close(fdb)\n _destroy_id()\n kfree(ctx)\n\n _destroy_id()\n wait_for_completion()\n // boom, ctx was freed\n\nThe ctx->file must be modified under the handler and xa_lock, and prior to\nmodification the ID must be rechecked that it is still reachable from\ncur_file, ie there is no parallel destroy or migrate.\n\nTo make this work remove the double locking and streamline the control\nflow. The double locking was obsoleted by the handler lock now directly\npreventing new uevents from being created, and the ctx_list cannot be read\nwhile holding fgets on both files. Removing the double locking also\nremoves the need to check for the same file.\n\nFixes: 88314e4dda1e (\"RDMA/cma: add support for rdma_migrate_id()\")\nLink: https://lore.kernel.org/r/0-v1-05c5a4090305+3a872-ucma_syz_migrate_jgg@nvidia.com\nReported-and-tested-by: syzbot+cc6fc752b3819e082d0c@syzkaller.appspotmail.com\nSigned-off-by: Jason Gunthorpe '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: errno_t sssctl_logs_fetch(struct sss_cmdline *cmdline,\n struct sss_tool_ctx *tool_ctx,\n void *pvt)\n{\n const char *file;\n const char *cmd;\n errno_t ret;\n\n /* Parse command line. */\n ret = sss_tool_popt_ex(cmdline, NULL, SSS_TOOL_OPT_OPTIONAL, NULL, NULL,\n \"FILE\", \"Output file\", &file, NULL);\n if (ret != EOK) {\n DEBUG(SSSDBG_CRIT_FAILURE, \"Unable to parse command arguments\\n\");\n return ret;\n }\n\n cmd = talloc_asprintf(tool_ctx, \"tar -czf %s %s\", file, LOG_FILES);\n if (cmd == NULL) {\n ERROR(\"Out of memory!\");\n }\n\n PRINT(\"Archiving log files into %s...\\n\", file);\n ret = sssctl_run_command(cmd);\n if (ret != EOK) {\n ERROR(\"Unable to archive log files\\n\");\n return ret;\n }\n\n return EOK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-78'], 'message': 'TOOLS: replace system() with execvp() to avoid execution of user supplied command\n\n:relnote: A flaw was found in SSSD, where the sssctl command was\nvulnerable to shell command injection via the logs-fetch and\ncache-expire subcommands. This flaw allows an attacker to trick\nthe root user into running a specially crafted sssctl command,\nsuch as via sudo, to gain root access. The highest threat from this\nvulnerability is to confidentiality, integrity, as well as system\navailability.\nThis patch fixes a flaw by replacing system() with execvp().\n\n:fixes: CVE-2021-3621\n\nReviewed-by: Pavel B\u0159ezina '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: size_t olm_pk_decrypt(\n OlmPkDecryption * decryption,\n void const * ephemeral_key, size_t ephemeral_key_length,\n void const * mac, size_t mac_length,\n void * ciphertext, size_t ciphertext_length,\n void * plaintext, size_t max_plaintext_length\n) {\n if (max_plaintext_length\n < olm_pk_max_plaintext_length(decryption, ciphertext_length)) {\n decryption->last_error =\n OlmErrorCode::OLM_OUTPUT_BUFFER_TOO_SMALL;\n return std::size_t(-1);\n }\n\n struct _olm_curve25519_public_key ephemeral;\n olm::decode_base64(\n (const uint8_t*)ephemeral_key, ephemeral_key_length,\n (uint8_t *)ephemeral.public_key\n );\n olm::SharedKey secret;\n _olm_crypto_curve25519_shared_secret(&decryption->key_pair, &ephemeral, secret);\n uint8_t raw_mac[MAC_LENGTH];\n olm::decode_base64((const uint8_t*)mac, olm::encode_base64_length(MAC_LENGTH), raw_mac);\n size_t raw_ciphertext_length = olm::decode_base64_length(ciphertext_length);\n olm::decode_base64((const uint8_t *)ciphertext, ciphertext_length, (uint8_t *)ciphertext);\n size_t result = _olm_cipher_aes_sha_256_ops.decrypt(\n olm_pk_cipher,\n secret, sizeof(secret),\n (uint8_t *) raw_mac, MAC_LENGTH,\n (const uint8_t *) ciphertext, raw_ciphertext_length,\n (uint8_t *) plaintext, max_plaintext_length\n );\n if (result == std::size_t(-1)) {\n // we already checked the buffer sizes, so the only error that decrypt\n // will return is if the MAC is incorrect\n decryption->last_error =\n OlmErrorCode::OLM_BAD_MESSAGE_MAC;\n return std::size_t(-1);\n } else {\n return result;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'olm_pk_decrypt: Ensure inputs are of correct length.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void cil_reset_classperms_set(struct cil_classperms_set *cp_set)\n{\n\tcil_reset_classpermission(cp_set->set);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'libsepol/cil: cil_reset_classperms_set() should not reset classpermission\n\nIn struct cil_classperms_set, the set field is a pointer to a\nstruct cil_classpermission which is looked up in the symbol table.\nSince the cil_classperms_set does not create the cil_classpermission,\nit should not reset it.\n\nSet the set field to NULL instead of resetting the classpermission\nthat it points to.\n\nSigned-off-by: James Carter '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: translate_compat_table(struct net *net,\n\t\t struct xt_table_info **pinfo,\n\t\t void **pentry0,\n\t\t const struct compat_ip6t_replace *compatr)\n{\n\tunsigned int i, j;\n\tstruct xt_table_info *newinfo, *info;\n\tvoid *pos, *entry0, *entry1;\n\tstruct compat_ip6t_entry *iter0;\n\tstruct ip6t_replace repl;\n\tunsigned int size;\n\tint ret;\n\n\tinfo = *pinfo;\n\tentry0 = *pentry0;\n\tsize = compatr->size;\n\tinfo->number = compatr->num_entries;\n\n\tj = 0;\n\txt_compat_lock(AF_INET6);\n\tret = xt_compat_init_offsets(AF_INET6, compatr->num_entries);\n\tif (ret)\n\t\tgoto out_unlock;\n\t/* Walk through entries, checking offsets. */\n\txt_entry_foreach(iter0, entry0, compatr->size) {\n\t\tret = check_compat_entry_size_and_hooks(iter0, info, &size,\n\t\t\t\t\t\t\tentry0,\n\t\t\t\t\t\t\tentry0 + compatr->size);\n\t\tif (ret != 0)\n\t\t\tgoto out_unlock;\n\t\t++j;\n\t}\n\n\tret = -EINVAL;\n\tif (j != compatr->num_entries)\n\t\tgoto out_unlock;\n\n\tret = -ENOMEM;\n\tnewinfo = xt_alloc_table_info(size);\n\tif (!newinfo)\n\t\tgoto out_unlock;\n\n\tnewinfo->number = compatr->num_entries;\n\tfor (i = 0; i < NF_INET_NUMHOOKS; i++) {\n\t\tnewinfo->hook_entry[i] = compatr->hook_entry[i];\n\t\tnewinfo->underflow[i] = compatr->underflow[i];\n\t}\n\tentry1 = newinfo->entries;\n\tpos = entry1;\n\tsize = compatr->size;\n\txt_entry_foreach(iter0, entry0, compatr->size)\n\t\tcompat_copy_entry_from_user(iter0, &pos, &size,\n\t\t\t\t\t newinfo, entry1);\n\n\t/* all module references in entry0 are now gone. */\n\txt_compat_flush_offsets(AF_INET6);\n\txt_compat_unlock(AF_INET6);\n\n\tmemcpy(&repl, compatr, sizeof(*compatr));\n\n\tfor (i = 0; i < NF_INET_NUMHOOKS; i++) {\n\t\trepl.hook_entry[i] = newinfo->hook_entry[i];\n\t\trepl.underflow[i] = newinfo->underflow[i];\n\t}\n\n\trepl.num_counters = 0;\n\trepl.counters = NULL;\n\trepl.size = newinfo->size;\n\tret = translate_table(net, newinfo, entry1, &repl);\n\tif (ret)\n\t\tgoto free_newinfo;\n\n\t*pinfo = newinfo;\n\t*pentry0 = entry1;\n\txt_free_table_info(info);\n\treturn 0;\n\nfree_newinfo:\n\txt_free_table_info(newinfo);\n\treturn ret;\nout_unlock:\n\txt_compat_flush_offsets(AF_INET6);\n\txt_compat_unlock(AF_INET6);\n\txt_entry_foreach(iter0, entry0, compatr->size) {\n\t\tif (j-- == 0)\n\t\t\tbreak;\n\t\tcompat_release_entry(iter0);\n\t}\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'netfilter: x_tables: fix compat match/target pad out-of-bound write\n\nxt_compat_match/target_from_user doesn't check that zeroing the area\nto start of next rule won't write past end of allocated ruleset blob.\n\nRemove this code and zero the entire blob beforehand.\n\nReported-by: syzbot+cfc0247ac173f597aaaa@syzkaller.appspotmail.com\nReported-by: Andy Nguyen \nFixes: 9fa492cdc160c (\"[NETFILTER]: x_tables: simplify compat API\")\nSigned-off-by: Florian Westphal \nSigned-off-by: Pablo Neira Ayuso '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int xt_compat_match(void *match, void **dstptr, int *size, int convert)\n{\n\tstruct xt_match *m;\n\tstruct compat_xt_entry_match *pcompat_m;\n\tstruct xt_entry_match *pm;\n\tu_int16_t msize;\n\tint off, ret;\n\n\tret = 0;\n\tm = ((struct xt_entry_match *)match)->u.kernel.match;\n\toff = XT_ALIGN(m->matchsize) - COMPAT_XT_ALIGN(m->matchsize);\n\tswitch (convert) {\n\t\tcase COMPAT_TO_USER:\n\t\t\tpm = (struct xt_entry_match *)match;\n\t\t\tmsize = pm->u.user.match_size;\n\t\t\tif (copy_to_user(*dstptr, pm, msize)) {\n\t\t\t\tret = -EFAULT;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tmsize -= off;\n\t\t\tif (put_user(msize, (u_int16_t *)*dstptr))\n\t\t\t\tret = -EFAULT;\n\t\t\t*size -= off;\n\t\t\t*dstptr += msize;\n\t\t\tbreak;\n\t\tcase COMPAT_FROM_USER:\n\t\t\tpcompat_m = (struct compat_xt_entry_match *)match;\n\t\t\tpm = (struct xt_entry_match *)*dstptr;\n\t\t\tmsize = pcompat_m->u.user.match_size;\n\t\t\tmemcpy(pm, pcompat_m, msize);\n\t\t\tmsize += off;\n\t\t\tpm->u.user.match_size = msize;\n\t\t\t*size += off;\n\t\t\t*dstptr += msize;\n\t\t\tbreak;\n\t\tcase COMPAT_CALC_SIZE:\n\t\t\t*size += off;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tret = -ENOPROTOOPT;\n\t\t\tbreak;\n\t}\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': '[NETFILTER]: x_tables: simplify compat API\n\nSplit the xt_compat_match/xt_compat_target into smaller type-safe functions\nperforming just one operation. Handle all alignment and size-related\nconversions centrally in these function instead of requiring each module to\nimplement a full-blown conversion function. Replace ->compat callback by\n->compat_from_user and ->compat_to_user callbacks, responsible for\nconverting just a single private structure.\n\nSigned-off-by: Patrick McHardy \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: convert(\n Imaging imOut, Imaging imIn, const char *mode, ImagingPalette palette, int dither) {\n ImagingSectionCookie cookie;\n ImagingShuffler convert;\n int y;\n\n if (!imIn) {\n return (Imaging)ImagingError_ModeError();\n }\n\n if (!mode) {\n /* Map palette image to full depth */\n if (!imIn->palette) {\n return (Imaging)ImagingError_ModeError();\n }\n mode = imIn->palette->mode;\n } else {\n /* Same mode? */\n if (!strcmp(imIn->mode, mode)) {\n return ImagingCopy2(imOut, imIn);\n }\n }\n\n /* test for special conversions */\n\n if (strcmp(imIn->mode, \"P\") == 0 || strcmp(imIn->mode, \"PA\") == 0) {\n return frompalette(imOut, imIn, mode);\n }\n\n if (strcmp(mode, \"P\") == 0 || strcmp(mode, \"PA\") == 0) {\n return topalette(imOut, imIn, mode, palette, dither);\n }\n\n if (dither && strcmp(mode, \"1\") == 0) {\n return tobilevel(imOut, imIn, dither);\n }\n\n /* standard conversion machinery */\n\n convert = NULL;\n\n for (y = 0; converters[y].from; y++) {\n if (!strcmp(imIn->mode, converters[y].from) &&\n !strcmp(mode, converters[y].to)) {\n convert = converters[y].convert;\n break;\n }\n }\n\n if (!convert) {\n#ifdef notdef\n return (Imaging)ImagingError_ValueError(\"conversion not supported\");\n#else\n static char buf[100];\n sprintf(buf, \"conversion from %.10s to %.10s not supported\", imIn->mode, mode);\n return (Imaging)ImagingError_ValueError(buf);\n#endif\n }\n\n imOut = ImagingNew2Dirty(mode, imOut, imIn);\n if (!imOut) {\n return NULL;\n }\n\n ImagingSectionEnter(&cookie);\n for (y = 0; y < imIn->ysize; y++) {\n (*convert)((UINT8 *)imOut->image[y], (UINT8 *)imIn->image[y], imIn->xsize);\n }\n ImagingSectionLeave(&cookie);\n\n return imOut;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'Use snprintf instead of sprintf'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void recalc_intercepts(struct vcpu_svm *svm)\n{\n\tstruct vmcb_control_area *c, *h, *g;\n\tunsigned int i;\n\n\tvmcb_mark_dirty(svm->vmcb, VMCB_INTERCEPTS);\n\n\tif (!is_guest_mode(&svm->vcpu))\n\t\treturn;\n\n\tc = &svm->vmcb->control;\n\th = &svm->vmcb01.ptr->control;\n\tg = &svm->nested.ctl;\n\n\tfor (i = 0; i < MAX_INTERCEPT; i++)\n\t\tc->intercepts[i] = h->intercepts[i];\n\n\tif (g->int_ctl & V_INTR_MASKING_MASK) {\n\t\t/* We only want the cr8 intercept bits of L1 */\n\t\tvmcb_clr_intercept(c, INTERCEPT_CR8_READ);\n\t\tvmcb_clr_intercept(c, INTERCEPT_CR8_WRITE);\n\n\t\t/*\n\t\t * Once running L2 with HF_VINTR_MASK, EFLAGS.IF does not\n\t\t * affect any interrupt we may want to inject; therefore,\n\t\t * interrupt window vmexits are irrelevant to L0.\n\t\t */\n\t\tvmcb_clr_intercept(c, INTERCEPT_VINTR);\n\t}\n\n\t/* We don't want to see VMMCALLs from a nested guest */\n\tvmcb_clr_intercept(c, INTERCEPT_VMMCALL);\n\n\tfor (i = 0; i < MAX_INTERCEPT; i++)\n\t\tc->intercepts[i] |= g->intercepts[i];\n\n\t/* If SMI is not intercepted, ignore guest SMI intercept as well */\n\tif (!intercept_smi)\n\t\tvmcb_clr_intercept(c, INTERCEPT_SMI);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-862'], 'message': 'KVM: nSVM: always intercept VMLOAD/VMSAVE when nested (CVE-2021-3656)\n\nIf L1 disables VMLOAD/VMSAVE intercepts, and doesn't enable\nVirtual VMLOAD/VMSAVE (currently not supported for the nested hypervisor),\nthen VMLOAD/VMSAVE must operate on the L1 physical memory, which is only\npossible by making L0 intercept these instructions.\n\nFailure to do so allowed the nested guest to run VMLOAD/VMSAVE unintercepted,\nand thus read/write portions of the host physical memory.\n\nFixes: 89c8a4984fc9 (\"KVM: SVM: Enable Virtual VMLOAD VMSAVE feature\")\n\nSuggested-by: Paolo Bonzini \nSigned-off-by: Maxim Levitsky \nSigned-off-by: Paolo Bonzini '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int discovery_stop(struct discovery_client *client)\n{\n\tstruct btd_adapter *adapter = client->adapter;\n\tstruct mgmt_cp_stop_discovery cp;\n\n\t/* Check if there are more client discovering */\n\tif (g_slist_next(adapter->discovery_list)) {\n\t\tdiscovery_remove(client);\n\t\tupdate_discovery_filter(adapter);\n\t\treturn 0;\n\t}\n\n\tif (adapter->discovery_discoverable)\n\t\tset_discovery_discoverable(adapter, false);\n\n\t/*\n\t * In the idle phase of a discovery, there is no need to stop it\n\t * and so it is enough to send out the signal and just return.\n\t */\n\tif (adapter->discovery_enable == 0x00) {\n\t\tdiscovery_remove(client);\n\t\tadapter->discovering = false;\n\t\tg_dbus_emit_property_changed(dbus_conn, adapter->path,\n\t\t\t\t\tADAPTER_INTERFACE, \"Discovering\");\n\n\t\ttrigger_passive_scanning(adapter);\n\n\t\treturn 0;\n\t}\n\n\tcp.type = adapter->discovery_type;\n\tadapter->client = client;\n\n\tmgmt_send(adapter->mgmt, MGMT_OP_STOP_DISCOVERY,\n\t\t\tadapter->dev_id, sizeof(cp), &cp,\n\t\t\tstop_discovery_complete, adapter, NULL);\n\n\treturn -EINPROGRESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-862', 'CWE-863'], 'message': 'adapter: Fix storing discoverable setting\n\ndiscoverable setting shall only be store when changed via Discoverable\nproperty and not when discovery client set it as that be considered\ntemporary just for the lifetime of the discovery.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int32_t gcd(int a, int b)\n{\n if (a == 0 && b == 0) {\n return 1;\n }\n\n if (a == 0) return b;\n if (b == 0) return a;\n\n int32_t h;\n\n do {\n h = a % b;\n a = b;\n b = h;\n } while (b != 0);\n\n return a;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'force fraction to a limited resolution to finally solve those pesky numerical edge cases'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static char *oidc_cache_get_hashed_key(request_rec *r, const char *passphrase,\n\t\tconst char *key) {\n\tchar *input = apr_psprintf(r->pool, \"%s:%s\", passphrase, key);\n\tchar *output = NULL;\n\tif (oidc_util_hash_string_and_base64url_encode(r, OIDC_JOSE_ALG_SHA256,\n\t\t\tinput, &output) == FALSE) {\n\t\toidc_error(r,\n\t\t\t\t\"oidc_util_hash_string_and_base64url_encode returned an error\");\n\t\treturn NULL;\n\t}\n\treturn output;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-330'], 'message': 'use encrypted JWTs for storing encrypted cache contents\n\n- avoid using static AAD/IV; thanks @niebardzo\n- bump to 2.4.9-dev\n\nSigned-off-by: Hans Zandbelt '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static pj_bool_t ssock_on_accept_complete (pj_ssl_sock_t *ssock_parent,\n\t\t\t\t\t pj_sock_t newsock,\n\t\t\t\t\t void *newconn,\n\t\t\t\t\t const pj_sockaddr_t *src_addr,\n\t\t\t\t\t int src_addr_len,\n\t\t\t\t\t pj_status_t accept_status)\n{\n pj_ssl_sock_t *ssock;\n#ifndef SSL_SOCK_IMP_USE_OWN_NETWORK\n pj_activesock_cb asock_cb;\n#endif\n pj_activesock_cfg asock_cfg;\n unsigned i;\n pj_status_t status;\n\n#ifndef SSL_SOCK_IMP_USE_OWN_NETWORK\n PJ_UNUSED_ARG(newconn);\n#endif\n\n if (accept_status != PJ_SUCCESS) {\n\tif (ssock_parent->param.cb.on_accept_complete2) {\n\t (*ssock_parent->param.cb.on_accept_complete2)(ssock_parent, NULL,\n\t\t\t\t\t\t \t src_addr,\n\t\t\t\t\t\t \t src_addr_len,\n\t\t\t\t\t\t \t accept_status);\n\t}\n\treturn PJ_TRUE;\n }\n\n /* Create new SSL socket instance */\n status = pj_ssl_sock_create(ssock_parent->pool,\n\t\t\t\t&ssock_parent->newsock_param, &ssock);\n if (status != PJ_SUCCESS)\n\tgoto on_return;\n\n /* Update new SSL socket attributes */\n ssock->sock = newsock;\n ssock->parent = ssock_parent;\n ssock->is_server = PJ_TRUE;\n if (ssock_parent->cert) {\n\tstatus = pj_ssl_sock_set_certificate(ssock, ssock->pool, \n\t\t\t\t\t ssock_parent->cert);\n\tif (status != PJ_SUCCESS)\n\t goto on_return;\n }\n\n /* Set local address */\n ssock->addr_len = src_addr_len;\n pj_sockaddr_cp(&ssock->local_addr, &ssock_parent->local_addr);\n\n /* Set remote address */\n pj_sockaddr_cp(&ssock->rem_addr, src_addr);\n\n /* Create SSL context */\n status = ssl_create(ssock);\n if (status != PJ_SUCCESS)\n\tgoto on_return;\n\n /* Prepare read buffer */\n ssock->asock_rbuf = (void**)pj_pool_calloc(ssock->pool, \n\t\t\t\t\t ssock->param.async_cnt,\n\t\t\t\t\t sizeof(void*));\n if (!ssock->asock_rbuf)\n return PJ_ENOMEM;\n\n for (i = 0; iparam.async_cnt; ++i) {\n\tssock->asock_rbuf[i] = (void*) pj_pool_alloc(\n\t\t\t\t\t ssock->pool, \n\t\t\t\t\t ssock->param.read_buffer_size + \n\t\t\t\t\t sizeof(read_data_t*));\n if (!ssock->asock_rbuf[i])\n return PJ_ENOMEM;\n }\n\n /* If listener socket has group lock, automatically create group lock\n * for the new socket.\n */\n if (ssock_parent->param.grp_lock) {\n\tpj_grp_lock_t *glock;\n\n\tstatus = pj_grp_lock_create(ssock->pool, NULL, &glock);\n\tif (status != PJ_SUCCESS)\n\t goto on_return;\n\n\tpj_grp_lock_add_ref(glock);\n\tasock_cfg.grp_lock = ssock->param.grp_lock = glock;\n\tpj_grp_lock_add_handler(ssock->param.grp_lock, ssock->pool, ssock,\n\t\t\t\tssl_on_destroy);\n }\n\n#ifdef SSL_SOCK_IMP_USE_OWN_NETWORK\n status = network_setup_connection(ssock, newconn);\n if (status != PJ_SUCCESS)\n\tgoto on_return;\n\n#else\n /* Apply QoS, if specified */\n status = pj_sock_apply_qos2(ssock->sock, ssock->param.qos_type,\n\t\t\t\t&ssock->param.qos_params, 1, \n\t\t\t\tssock->pool->obj_name, NULL);\n if (status != PJ_SUCCESS && !ssock->param.qos_ignore_error)\n\tgoto on_return;\n\n /* Apply socket options, if specified */\n if (ssock->param.sockopt_params.cnt) {\n\tstatus = pj_sock_setsockopt_params(ssock->sock, \n\t\t\t\t\t &ssock->param.sockopt_params);\n\tif (status != PJ_SUCCESS && !ssock->param.sockopt_ignore_error)\n\t goto on_return;\n }\n\n /* Create active socket */\n pj_activesock_cfg_default(&asock_cfg);\n asock_cfg.async_cnt = ssock->param.async_cnt;\n asock_cfg.concurrency = ssock->param.concurrency;\n asock_cfg.whole_data = PJ_TRUE;\n\n pj_bzero(&asock_cb, sizeof(asock_cb));\n asock_cb.on_data_read = asock_on_data_read;\n asock_cb.on_data_sent = asock_on_data_sent;\n\n status = pj_activesock_create(ssock->pool,\n\t\t\t\t ssock->sock, \n\t\t\t\t ssock->param.sock_type,\n\t\t\t\t &asock_cfg,\n\t\t\t\t ssock->param.ioqueue, \n\t\t\t\t &asock_cb,\n\t\t\t\t ssock,\n\t\t\t\t &ssock->asock);\n\n if (status != PJ_SUCCESS)\n\tgoto on_return;\n\n /* Start read */\n status = pj_activesock_start_read2(ssock->asock, ssock->pool, \n\t\t\t\t (unsigned)ssock->param.read_buffer_size,\n\t\t\t\t ssock->asock_rbuf,\n\t\t\t\t PJ_IOQUEUE_ALWAYS_ASYNC);\n if (status != PJ_SUCCESS)\n\tgoto on_return;\n#endif\n\n /* Update local address */\n status = get_localaddr(ssock, &ssock->local_addr, &ssock->addr_len);\n if (status != PJ_SUCCESS) {\n\t/* This fails on few envs, e.g: win IOCP, just tolerate this and\n\t * use parent local address instead.\n\t */\n\tpj_sockaddr_cp(&ssock->local_addr, &ssock_parent->local_addr);\n }\n\n /* Prepare write/send state */\n pj_assert(ssock->send_buf.max_len == 0);\n ssock->send_buf.buf = (char*)\n\t\t\t pj_pool_alloc(ssock->pool, \n\t\t\t\t\tssock->param.send_buffer_size);\n if (!ssock->send_buf.buf)\n return PJ_ENOMEM;\n\n ssock->send_buf.max_len = ssock->param.send_buffer_size;\n ssock->send_buf.start = ssock->send_buf.buf;\n ssock->send_buf.len = 0;\n\n /* Start handshake timer */\n if (ssock->param.timer_heap && (ssock->param.timeout.sec != 0 ||\n\tssock->param.timeout.msec != 0))\n {\n\tpj_assert(ssock->timer.id == TIMER_NONE);\n\tstatus = pj_timer_heap_schedule_w_grp_lock(ssock->param.timer_heap, \n\t\t\t\t\t\t &ssock->timer,\n\t\t\t\t\t\t &ssock->param.timeout,\n\t\t\t\t\t\t TIMER_HANDSHAKE_TIMEOUT,\n\t\t\t\t\t\t ssock->param.grp_lock);\n\tif (status != PJ_SUCCESS) {\n\t ssock->timer.id = TIMER_NONE;\n\t status = PJ_SUCCESS;\n\t}\n }\n\n /* Start SSL handshake */\n ssock->ssl_state = SSL_STATE_HANDSHAKING;\n ssl_set_state(ssock, PJ_TRUE);\n status = ssl_do_handshake(ssock);\n\non_return:\n if (ssock && status != PJ_EPENDING) {\n\ton_handshake_complete(ssock, status);\n }\n\n /* Must return PJ_TRUE whatever happened, as we must continue listening */\n return PJ_TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362', 'CWE-703'], 'message': 'Merge pull request from GHSA-cv8x-p47p-99wr\n\n* - Avoid SSL socket parent/listener getting destroyed during handshake by increasing parent's reference count.\n- Add missing SSL socket close when the newly accepted SSL socket is discarded in SIP TLS transport.\n\n* - Fix silly mistake: accepted active socket created without group lock in SSL socket.\n- Replace assertion with normal validation check of SSL socket instance in OpenSSL verification callback (verify_cb()) to avoid crash, e.g: if somehow race condition with SSL socket destroy happens or OpenSSL application data index somehow gets corrupted.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static struct port_buffer *get_inbuf(struct port *port)\n{\n\tstruct port_buffer *buf;\n\tunsigned int len;\n\n\tif (port->inbuf)\n\t\treturn port->inbuf;\n\n\tbuf = virtqueue_get_buf(port->in_vq, &len);\n\tif (buf) {\n\t\tbuf->len = len;\n\t\tbuf->offset = 0;\n\t\tport->stats.bytes_received += len;\n\t}\n\treturn buf;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'virtio_console: Assure used length from device is limited\n\nThe buf->len might come from an untrusted device. This\nensures the value would not exceed the size of the buffer\nto avoid data corruption or loss.\n\nSigned-off-by: Xie Yongji \nAcked-by: Jason Wang \nLink: https://lore.kernel.org/r/20210525125622.1203-1-xieyongji@bytedance.com\nSigned-off-by: Michael S. Tsirkin '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: get_next_reel (int tape_des)\n{\n static int reel_number = 1;\n FILE *tty_in;\t\t\t/* File for interacting with user. */\n FILE *tty_out;\t\t/* File for interacting with user. */\n int old_tape_des;\n char *next_archive_name;\n dynamic_string new_name;\n char *str_res;\n\n ds_init (&new_name, 128);\n\n /* Open files for interactive communication. */\n tty_in = fopen (TTY_NAME, \"r\");\n if (tty_in == NULL)\n error (PAXEXIT_FAILURE, errno, TTY_NAME);\n tty_out = fopen (TTY_NAME, \"w\");\n if (tty_out == NULL)\n error (PAXEXIT_FAILURE, errno, TTY_NAME);\n\n old_tape_des = tape_des;\n tape_offline (tape_des);\n rmtclose (tape_des);\n\n /* Give message and wait for carrage return. User should hit carrage return\n only after loading the next tape. */\n ++reel_number;\n if (new_media_message)\n fprintf (tty_out, \"%s\", new_media_message);\n else if (new_media_message_with_number)\n fprintf (tty_out, \"%s%d%s\", new_media_message_with_number, reel_number,\n\t new_media_message_after_number);\n else if (archive_name)\n fprintf (tty_out, _(\"Found end of tape. Load next tape and press RETURN. \"));\n else\n fprintf (tty_out, _(\"Found end of tape. To continue, type device/file name when ready.\\n\"));\n\n fflush (tty_out);\n\n if (archive_name)\n {\n int c;\n\n do\n\tc = getc (tty_in);\n while (c != EOF && c != '\\n');\n\n tape_des = open_archive (archive_name);\n if (tape_des == -1)\n\topen_error (archive_name);\n }\n else\n {\n do\n\t{\n\t if (tape_des < 0)\n\t {\n\t fprintf (tty_out,\n\t\t _(\"To continue, type device/file name when ready.\\n\"));\n\t fflush (tty_out);\n\t }\n\n\t str_res = ds_fgets (tty_in, &new_name);\n\t if (str_res == NULL || str_res[0] == '\\0')\n\t exit (PAXEXIT_FAILURE);\n\t next_archive_name = str_res;\n\n\t tape_des = open_archive (next_archive_name);\n\t if (tape_des == -1)\n\t open_error (next_archive_name);\n\t}\n while (tape_des < 0);\n }\n\n /* We have to make sure that `tape_des' has not changed its value even\n though we closed it and reopened it, since there are local\n copies of it in other routines. This works fine on Unix (even with\n rmtread and rmtwrite) since open will always return the lowest\n available file descriptor and we haven't closed any files (e.g.,\n stdin, stdout or stderr) that were opened before we originally opened\n the archive. */\n\n if (tape_des != old_tape_des)\n error (PAXEXIT_FAILURE, 0, _(\"internal error: tape descriptor changed from %d to %d\"),\n\t old_tape_des, tape_des);\n\n free (new_name.ds_string);\n fclose (tty_in);\n fclose (tty_out);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Rewrite dynamic string support.\n\n* src/dstring.c (ds_init): Take a single argument.\n(ds_free): New function.\n(ds_resize): Take a single argument. Use x2nrealloc to expand\nthe storage.\n(ds_reset,ds_append,ds_concat,ds_endswith): New function.\n(ds_fgetstr): Rewrite. In particular, this fixes integer overflow.\n* src/dstring.h (dynamic_string): Keep both the allocated length\n(ds_size) and index of the next free byte in the string (ds_idx).\n(ds_init,ds_resize): Change signature.\n(ds_len): New macro.\n(ds_free,ds_reset,ds_append,ds_concat,ds_endswith): New protos.\n* src/copyin.c: Use new ds_ functions.\n* src/copyout.c: Likewise.\n* src/copypass.c: Likewise.\n* src/util.c: Likewise.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: max3421_select_and_start_urb(struct usb_hcd *hcd)\n{\n\tstruct spi_device *spi = to_spi_device(hcd->self.controller);\n\tstruct max3421_hcd *max3421_hcd = hcd_to_max3421(hcd);\n\tstruct urb *urb, *curr_urb = NULL;\n\tstruct max3421_ep *max3421_ep;\n\tint epnum, force_toggles = 0;\n\tstruct usb_host_endpoint *ep;\n\tstruct list_head *pos;\n\tunsigned long flags;\n\n\tspin_lock_irqsave(&max3421_hcd->lock, flags);\n\n\tfor (;\n\t max3421_hcd->sched_pass < SCHED_PASS_DONE;\n\t ++max3421_hcd->sched_pass)\n\t\tlist_for_each(pos, &max3421_hcd->ep_list) {\n\t\t\turb = NULL;\n\t\t\tmax3421_ep = container_of(pos, struct max3421_ep,\n\t\t\t\t\t\t ep_list);\n\t\t\tep = max3421_ep->ep;\n\n\t\t\tswitch (usb_endpoint_type(&ep->desc)) {\n\t\t\tcase USB_ENDPOINT_XFER_ISOC:\n\t\t\tcase USB_ENDPOINT_XFER_INT:\n\t\t\t\tif (max3421_hcd->sched_pass !=\n\t\t\t\t SCHED_PASS_PERIODIC)\n\t\t\t\t\tcontinue;\n\t\t\t\tbreak;\n\n\t\t\tcase USB_ENDPOINT_XFER_CONTROL:\n\t\t\tcase USB_ENDPOINT_XFER_BULK:\n\t\t\t\tif (max3421_hcd->sched_pass !=\n\t\t\t\t SCHED_PASS_NON_PERIODIC)\n\t\t\t\t\tcontinue;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (list_empty(&ep->urb_list))\n\t\t\t\tcontinue;\t/* nothing to do */\n\t\t\turb = list_first_entry(&ep->urb_list, struct urb,\n\t\t\t\t\t urb_list);\n\t\t\tif (urb->unlinked) {\n\t\t\t\tdev_dbg(&spi->dev, \"%s: URB %p unlinked=%d\",\n\t\t\t\t\t__func__, urb, urb->unlinked);\n\t\t\t\tmax3421_hcd->curr_urb = urb;\n\t\t\t\tmax3421_hcd->urb_done = 1;\n\t\t\t\tspin_unlock_irqrestore(&max3421_hcd->lock,\n\t\t\t\t\t\t flags);\n\t\t\t\treturn 1;\n\t\t\t}\n\n\t\t\tswitch (usb_endpoint_type(&ep->desc)) {\n\t\t\tcase USB_ENDPOINT_XFER_CONTROL:\n\t\t\t\t/*\n\t\t\t\t * Allow one control transaction per\n\t\t\t\t * frame per endpoint:\n\t\t\t\t */\n\t\t\t\tif (frame_diff(max3421_ep->last_active,\n\t\t\t\t\t max3421_hcd->frame_number) == 0)\n\t\t\t\t\tcontinue;\n\t\t\t\tbreak;\n\n\t\t\tcase USB_ENDPOINT_XFER_BULK:\n\t\t\t\tif (max3421_ep->retransmit\n\t\t\t\t && (frame_diff(max3421_ep->last_active,\n\t\t\t\t\t\t max3421_hcd->frame_number)\n\t\t\t\t\t== 0))\n\t\t\t\t\t/*\n\t\t\t\t\t * We already tried this EP\n\t\t\t\t\t * during this frame and got a\n\t\t\t\t\t * NAK or error; wait for next frame\n\t\t\t\t\t */\n\t\t\t\t\tcontinue;\n\t\t\t\tbreak;\n\n\t\t\tcase USB_ENDPOINT_XFER_ISOC:\n\t\t\tcase USB_ENDPOINT_XFER_INT:\n\t\t\t\tif (frame_diff(max3421_hcd->frame_number,\n\t\t\t\t\t max3421_ep->last_active)\n\t\t\t\t < urb->interval)\n\t\t\t\t\t/*\n\t\t\t\t\t * We already processed this\n\t\t\t\t\t * end-point in the current\n\t\t\t\t\t * frame\n\t\t\t\t\t */\n\t\t\t\t\tcontinue;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t/* move current ep to tail: */\n\t\t\tlist_move_tail(pos, &max3421_hcd->ep_list);\n\t\t\tcurr_urb = urb;\n\t\t\tgoto done;\n\t\t}\ndone:\n\tif (!curr_urb) {\n\t\tspin_unlock_irqrestore(&max3421_hcd->lock, flags);\n\t\treturn 0;\n\t}\n\n\turb = max3421_hcd->curr_urb = curr_urb;\n\tepnum = usb_endpoint_num(&urb->ep->desc);\n\tif (max3421_ep->retransmit)\n\t\t/* restart (part of) a USB transaction: */\n\t\tmax3421_ep->retransmit = 0;\n\telse {\n\t\t/* start USB transaction: */\n\t\tif (usb_endpoint_xfer_control(&ep->desc)) {\n\t\t\t/*\n\t\t\t * See USB 2.0 spec section 8.6.1\n\t\t\t * Initialization via SETUP Token:\n\t\t\t */\n\t\t\tusb_settoggle(urb->dev, epnum, 0, 1);\n\t\t\tusb_settoggle(urb->dev, epnum, 1, 1);\n\t\t\tmax3421_ep->pkt_state = PKT_STATE_SETUP;\n\t\t\tforce_toggles = 1;\n\t\t} else\n\t\t\tmax3421_ep->pkt_state = PKT_STATE_TRANSFER;\n\t}\n\n\tspin_unlock_irqrestore(&max3421_hcd->lock, flags);\n\n\tmax3421_ep->last_active = max3421_hcd->frame_number;\n\tmax3421_set_address(hcd, urb->dev, epnum, force_toggles);\n\tmax3421_set_speed(hcd, urb->dev);\n\tmax3421_next_transfer(hcd, 0);\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'usb: max-3421: Prevent corruption of freed memory\n\nThe MAX-3421 USB driver remembers the state of the USB toggles for a\ndevice/endpoint. To save SPI writes, this was only done when a new\ndevice/endpoint was being used. Unfortunately, if the old device was\nremoved, this would cause writes to freed memory.\n\nTo fix this, a simpler scheme is used. The toggles are read from\nhardware when a URB is completed, and the toggles are always written to\nhardware when any URB transaction is started. This will cause a few more\nSPI transactions, but no causes kernel panics.\n\nFixes: 2d53139f3162 (\"Add support for using a MAX3421E chip as a host driver.\")\nCc: stable \nSigned-off-by: Mark Tomlinson \nLink: https://lore.kernel.org/r/20210625031456.8632-1-mark.tomlinson@alliedtelesis.co.nz\nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: __htab_map_lookup_and_delete_batch(struct bpf_map *map,\n\t\t\t\t const union bpf_attr *attr,\n\t\t\t\t union bpf_attr __user *uattr,\n\t\t\t\t bool do_delete, bool is_lru_map,\n\t\t\t\t bool is_percpu)\n{\n\tstruct bpf_htab *htab = container_of(map, struct bpf_htab, map);\n\tu32 bucket_cnt, total, key_size, value_size, roundup_key_size;\n\tvoid *keys = NULL, *values = NULL, *value, *dst_key, *dst_val;\n\tvoid __user *uvalues = u64_to_user_ptr(attr->batch.values);\n\tvoid __user *ukeys = u64_to_user_ptr(attr->batch.keys);\n\tvoid __user *ubatch = u64_to_user_ptr(attr->batch.in_batch);\n\tu32 batch, max_count, size, bucket_size;\n\tstruct htab_elem *node_to_free = NULL;\n\tu64 elem_map_flags, map_flags;\n\tstruct hlist_nulls_head *head;\n\tstruct hlist_nulls_node *n;\n\tunsigned long flags = 0;\n\tbool locked = false;\n\tstruct htab_elem *l;\n\tstruct bucket *b;\n\tint ret = 0;\n\n\telem_map_flags = attr->batch.elem_flags;\n\tif ((elem_map_flags & ~BPF_F_LOCK) ||\n\t ((elem_map_flags & BPF_F_LOCK) && !map_value_has_spin_lock(map)))\n\t\treturn -EINVAL;\n\n\tmap_flags = attr->batch.flags;\n\tif (map_flags)\n\t\treturn -EINVAL;\n\n\tmax_count = attr->batch.count;\n\tif (!max_count)\n\t\treturn 0;\n\n\tif (put_user(0, &uattr->batch.count))\n\t\treturn -EFAULT;\n\n\tbatch = 0;\n\tif (ubatch && copy_from_user(&batch, ubatch, sizeof(batch)))\n\t\treturn -EFAULT;\n\n\tif (batch >= htab->n_buckets)\n\t\treturn -ENOENT;\n\n\tkey_size = htab->map.key_size;\n\troundup_key_size = round_up(htab->map.key_size, 8);\n\tvalue_size = htab->map.value_size;\n\tsize = round_up(value_size, 8);\n\tif (is_percpu)\n\t\tvalue_size = size * num_possible_cpus();\n\ttotal = 0;\n\t/* while experimenting with hash tables with sizes ranging from 10 to\n\t * 1000, it was observed that a bucket can have upto 5 entries.\n\t */\n\tbucket_size = 5;\n\nalloc:\n\t/* We cannot do copy_from_user or copy_to_user inside\n\t * the rcu_read_lock. Allocate enough space here.\n\t */\n\tkeys = kvmalloc(key_size * bucket_size, GFP_USER | __GFP_NOWARN);\n\tvalues = kvmalloc(value_size * bucket_size, GFP_USER | __GFP_NOWARN);\n\tif (!keys || !values) {\n\t\tret = -ENOMEM;\n\t\tgoto after_loop;\n\t}\n\nagain:\n\tbpf_disable_instrumentation();\n\trcu_read_lock();\nagain_nocopy:\n\tdst_key = keys;\n\tdst_val = values;\n\tb = &htab->buckets[batch];\n\thead = &b->head;\n\t/* do not grab the lock unless need it (bucket_cnt > 0). */\n\tif (locked) {\n\t\tret = htab_lock_bucket(htab, b, batch, &flags);\n\t\tif (ret)\n\t\t\tgoto next_batch;\n\t}\n\n\tbucket_cnt = 0;\n\thlist_nulls_for_each_entry_rcu(l, n, head, hash_node)\n\t\tbucket_cnt++;\n\n\tif (bucket_cnt && !locked) {\n\t\tlocked = true;\n\t\tgoto again_nocopy;\n\t}\n\n\tif (bucket_cnt > (max_count - total)) {\n\t\tif (total == 0)\n\t\t\tret = -ENOSPC;\n\t\t/* Note that since bucket_cnt > 0 here, it is implicit\n\t\t * that the locked was grabbed, so release it.\n\t\t */\n\t\thtab_unlock_bucket(htab, b, batch, flags);\n\t\trcu_read_unlock();\n\t\tbpf_enable_instrumentation();\n\t\tgoto after_loop;\n\t}\n\n\tif (bucket_cnt > bucket_size) {\n\t\tbucket_size = bucket_cnt;\n\t\t/* Note that since bucket_cnt > 0 here, it is implicit\n\t\t * that the locked was grabbed, so release it.\n\t\t */\n\t\thtab_unlock_bucket(htab, b, batch, flags);\n\t\trcu_read_unlock();\n\t\tbpf_enable_instrumentation();\n\t\tkvfree(keys);\n\t\tkvfree(values);\n\t\tgoto alloc;\n\t}\n\n\t/* Next block is only safe to run if you have grabbed the lock */\n\tif (!locked)\n\t\tgoto next_batch;\n\n\thlist_nulls_for_each_entry_safe(l, n, head, hash_node) {\n\t\tmemcpy(dst_key, l->key, key_size);\n\n\t\tif (is_percpu) {\n\t\t\tint off = 0, cpu;\n\t\t\tvoid __percpu *pptr;\n\n\t\t\tpptr = htab_elem_get_ptr(l, map->key_size);\n\t\t\tfor_each_possible_cpu(cpu) {\n\t\t\t\tbpf_long_memcpy(dst_val + off,\n\t\t\t\t\t\tper_cpu_ptr(pptr, cpu), size);\n\t\t\t\toff += size;\n\t\t\t}\n\t\t} else {\n\t\t\tvalue = l->key + roundup_key_size;\n\t\t\tif (elem_map_flags & BPF_F_LOCK)\n\t\t\t\tcopy_map_value_locked(map, dst_val, value,\n\t\t\t\t\t\t true);\n\t\t\telse\n\t\t\t\tcopy_map_value(map, dst_val, value);\n\t\t\tcheck_and_init_map_lock(map, dst_val);\n\t\t}\n\t\tif (do_delete) {\n\t\t\thlist_nulls_del_rcu(&l->hash_node);\n\n\t\t\t/* bpf_lru_push_free() will acquire lru_lock, which\n\t\t\t * may cause deadlock. See comments in function\n\t\t\t * prealloc_lru_pop(). Let us do bpf_lru_push_free()\n\t\t\t * after releasing the bucket lock.\n\t\t\t */\n\t\t\tif (is_lru_map) {\n\t\t\t\tl->batch_flink = node_to_free;\n\t\t\t\tnode_to_free = l;\n\t\t\t} else {\n\t\t\t\tfree_htab_elem(htab, l);\n\t\t\t}\n\t\t}\n\t\tdst_key += key_size;\n\t\tdst_val += value_size;\n\t}\n\n\thtab_unlock_bucket(htab, b, batch, flags);\n\tlocked = false;\n\n\twhile (node_to_free) {\n\t\tl = node_to_free;\n\t\tnode_to_free = node_to_free->batch_flink;\n\t\tbpf_lru_push_free(&htab->lru, &l->lru_node);\n\t}\n\nnext_batch:\n\t/* If we are not copying data, we can go to next bucket and avoid\n\t * unlocking the rcu.\n\t */\n\tif (!bucket_cnt && (batch + 1 < htab->n_buckets)) {\n\t\tbatch++;\n\t\tgoto again_nocopy;\n\t}\n\n\trcu_read_unlock();\n\tbpf_enable_instrumentation();\n\tif (bucket_cnt && (copy_to_user(ukeys + total * key_size, keys,\n\t key_size * bucket_cnt) ||\n\t copy_to_user(uvalues + total * value_size, values,\n\t value_size * bucket_cnt))) {\n\t\tret = -EFAULT;\n\t\tgoto after_loop;\n\t}\n\n\ttotal += bucket_cnt;\n\tbatch++;\n\tif (batch >= htab->n_buckets) {\n\t\tret = -ENOENT;\n\t\tgoto after_loop;\n\t}\n\tgoto again;\n\nafter_loop:\n\tif (ret == -EFAULT)\n\t\tgoto out;\n\n\t/* copy # of entries and next batch */\n\tubatch = u64_to_user_ptr(attr->batch.out_batch);\n\tif (copy_to_user(ubatch, &batch, sizeof(batch)) ||\n\t put_user(total, &uattr->batch.count))\n\t\tret = -EFAULT;\n\nout:\n\tkvfree(keys);\n\tkvfree(values);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'bpf: Fix integer overflow involving bucket_size\n\nIn __htab_map_lookup_and_delete_batch(), hash buckets are iterated\nover to count the number of elements in each bucket (bucket_size).\nIf bucket_size is large enough, the multiplication to calculate\nkvmalloc() size could overflow, resulting in out-of-bounds write\nas reported by KASAN:\n\n [...]\n [ 104.986052] BUG: KASAN: vmalloc-out-of-bounds in __htab_map_lookup_and_delete_batch+0x5ce/0xb60\n [ 104.986489] Write of size 4194224 at addr ffffc9010503be70 by task crash/112\n [ 104.986889]\n [ 104.987193] CPU: 0 PID: 112 Comm: crash Not tainted 5.14.0-rc4 #13\n [ 104.987552] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.13.0-1ubuntu1.1 04/01/2014\n [ 104.988104] Call Trace:\n [ 104.988410] dump_stack_lvl+0x34/0x44\n [ 104.988706] print_address_description.constprop.0+0x21/0x140\n [ 104.988991] ? __htab_map_lookup_and_delete_batch+0x5ce/0xb60\n [ 104.989327] ? __htab_map_lookup_and_delete_batch+0x5ce/0xb60\n [ 104.989622] kasan_report.cold+0x7f/0x11b\n [ 104.989881] ? __htab_map_lookup_and_delete_batch+0x5ce/0xb60\n [ 104.990239] kasan_check_range+0x17c/0x1e0\n [ 104.990467] memcpy+0x39/0x60\n [ 104.990670] __htab_map_lookup_and_delete_batch+0x5ce/0xb60\n [ 104.990982] ? __wake_up_common+0x4d/0x230\n [ 104.991256] ? htab_of_map_free+0x130/0x130\n [ 104.991541] bpf_map_do_batch+0x1fb/0x220\n [...]\n\nIn hashtable, if the elements' keys have the same jhash() value, the\nelements will be put into the same bucket. By putting a lot of elements\ninto a single bucket, the value of bucket_size can be increased to\ntrigger the integer overflow.\n\nTriggering the overflow is possible for both callers with CAP_SYS_ADMIN\nand callers without CAP_SYS_ADMIN.\n\nIt will be trivial for a caller with CAP_SYS_ADMIN to intentionally\nreach this overflow by enabling BPF_F_ZERO_SEED. As this flag will set\nthe random seed passed to jhash() to 0, it will be easy for the caller\nto prepare keys which will be hashed into the same value, and thus put\nall the elements into the same bucket.\n\nIf the caller does not have CAP_SYS_ADMIN, BPF_F_ZERO_SEED cannot be\nused. However, it will be still technically possible to trigger the\noverflow, by guessing the random seed value passed to jhash() (32bit)\nand repeating the attempt to trigger the overflow. In this case,\nthe probability to trigger the overflow will be low and will take\na very long time.\n\nFix the integer overflow by calling kvmalloc_array() instead of\nkvmalloc() to allocate memory.\n\nFixes: 057996380a42 (\"bpf: Add batch ops to all htab bpf map\")\nSigned-off-by: Tatsuhiko Yasumatsu \nSigned-off-by: Daniel Borkmann \nLink: https://lore.kernel.org/bpf/20210806150419.109658-1-th.yasumatsu@gmail.com'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static bool nested_vmcb_checks(struct vcpu_svm *svm, struct vmcb *vmcb12)\n{\n\tbool vmcb12_lma;\n\n\tif ((vmcb12->save.efer & EFER_SVME) == 0)\n\t\treturn false;\n\n\tif (((vmcb12->save.cr0 & X86_CR0_CD) == 0) && (vmcb12->save.cr0 & X86_CR0_NW))\n\t\treturn false;\n\n\tif (!kvm_dr6_valid(vmcb12->save.dr6) || !kvm_dr7_valid(vmcb12->save.dr7))\n\t\treturn false;\n\n\tvmcb12_lma = (vmcb12->save.efer & EFER_LME) && (vmcb12->save.cr0 & X86_CR0_PG);\n\n\tif (!vmcb12_lma) {\n\t\tif (vmcb12->save.cr4 & X86_CR4_PAE) {\n\t\t\tif (vmcb12->save.cr3 & MSR_CR3_LEGACY_PAE_RESERVED_MASK)\n\t\t\t\treturn false;\n\t\t} else {\n\t\t\tif (vmcb12->save.cr3 & MSR_CR3_LEGACY_RESERVED_MASK)\n\t\t\t\treturn false;\n\t\t}\n\t} else {\n\t\tif (!(vmcb12->save.cr4 & X86_CR4_PAE) ||\n\t\t !(vmcb12->save.cr0 & X86_CR0_PE) ||\n\t\t (vmcb12->save.cr3 & MSR_CR3_LONG_MBZ_MASK))\n\t\t\treturn false;\n\t}\n\tif (kvm_valid_cr4(&svm->vcpu, vmcb12->save.cr4))\n\t\treturn false;\n\n\treturn nested_vmcb_check_controls(&vmcb12->control);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'KVM: SVM: load control fields from VMCB12 before checking them\n\nAvoid races between check and use of the nested VMCB controls. This\nfor example ensures that the VMRUN intercept is always reflected to the\nnested hypervisor, instead of being processed by the host. Without this\npatch, it is possible to end up with svm->nested.hsave pointing to\nthe MSR permission bitmap for nested guests.\n\nThis bug is CVE-2021-29657.\n\nReported-by: Felix Wilhelm \nCc: stable@vger.kernel.org\nFixes: 2fcf4876ada (\"KVM: nSVM: implement on demand allocation of the nested state\")\nSigned-off-by: Paolo Bonzini '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static struct dir *squashfs_opendir(unsigned int block_start, unsigned int offset,\n\tstruct inode **i)\n{\n\tstruct squashfs_dir_header dirh;\n\tchar buffer[sizeof(struct squashfs_dir_entry) + SQUASHFS_NAME_LEN + 1]\n\t\t__attribute__((aligned));\n\tstruct squashfs_dir_entry *dire = (struct squashfs_dir_entry *) buffer;\n\tlong long start;\n\tlong long bytes;\n\tint dir_count, size;\n\tstruct dir_ent *new_dir;\n\tstruct dir *dir;\n\n\tTRACE(\"squashfs_opendir: inode start block %d, offset %d\\n\",\n\t\tblock_start, offset);\n\n\t*i = read_inode(block_start, offset);\n\n\tdir = malloc(sizeof(struct dir));\n\tif(dir == NULL)\n\t\tEXIT_UNSQUASH(\"squashfs_opendir: malloc failed!\\n\");\n\n\tdir->dir_count = 0;\n\tdir->cur_entry = 0;\n\tdir->mode = (*i)->mode;\n\tdir->uid = (*i)->uid;\n\tdir->guid = (*i)->gid;\n\tdir->mtime = (*i)->time;\n\tdir->xattr = (*i)->xattr;\n\tdir->dirs = NULL;\n\n\tif ((*i)->data == 3)\n\t\t/*\n\t\t * if the directory is empty, skip the unnecessary\n\t\t * lookup_entry, this fixes the corner case with\n\t\t * completely empty filesystems where lookup_entry correctly\n\t\t * returning -1 is incorrectly treated as an error\n\t\t */\n\t\treturn dir;\n\n\tstart = sBlk.s.directory_table_start + (*i)->start;\n\tbytes = lookup_entry(directory_table_hash, start);\n\n\tif(bytes == -1)\n\t\tEXIT_UNSQUASH(\"squashfs_opendir: directory block %lld not \"\n\t\t\t\"found!\\n\", start);\n\n\tbytes += (*i)->offset;\n\tsize = (*i)->data + bytes - 3;\n\n\twhile(bytes < size) {\t\t\t\n\t\tSQUASHFS_SWAP_DIR_HEADER(directory_table + bytes, &dirh);\n\t\n\t\tdir_count = dirh.count + 1;\n\t\tTRACE(\"squashfs_opendir: Read directory header @ byte position \"\n\t\t\t\"%d, %d directory entries\\n\", bytes, dir_count);\n\t\tbytes += sizeof(dirh);\n\n\t\t/* dir_count should never be larger than SQUASHFS_DIR_COUNT */\n\t\tif(dir_count > SQUASHFS_DIR_COUNT) {\n\t\t\tERROR(\"File system corrupted: too many entries in directory\\n\");\n\t\t\tgoto corrupted;\n\t\t}\n\n\t\twhile(dir_count--) {\n\t\t\tSQUASHFS_SWAP_DIR_ENTRY(directory_table + bytes, dire);\n\n\t\t\tbytes += sizeof(*dire);\n\n\t\t\t/* size should never be SQUASHFS_NAME_LEN or larger */\n\t\t\tif(dire->size >= SQUASHFS_NAME_LEN) {\n\t\t\t\tERROR(\"File system corrupted: filename too long\\n\");\n\t\t\t\tgoto corrupted;\n\t\t\t}\n\n\t\t\tmemcpy(dire->name, directory_table + bytes,\n\t\t\t\tdire->size + 1);\n\t\t\tdire->name[dire->size + 1] = '\\0';\n\t\t\tTRACE(\"squashfs_opendir: directory entry %s, inode \"\n\t\t\t\t\"%d:%d, type %d\\n\", dire->name,\n\t\t\t\tdirh.start_block, dire->offset, dire->type);\n\t\t\tif((dir->dir_count % DIR_ENT_SIZE) == 0) {\n\t\t\t\tnew_dir = realloc(dir->dirs, (dir->dir_count +\n\t\t\t\t\tDIR_ENT_SIZE) * sizeof(struct dir_ent));\n\t\t\t\tif(new_dir == NULL)\n\t\t\t\t\tEXIT_UNSQUASH(\"squashfs_opendir: \"\n\t\t\t\t\t\t\"realloc failed!\\n\");\n\t\t\t\tdir->dirs = new_dir;\n\t\t\t}\n\t\t\tstrcpy(dir->dirs[dir->dir_count].name, dire->name);\n\t\t\tdir->dirs[dir->dir_count].start_block =\n\t\t\t\tdirh.start_block;\n\t\t\tdir->dirs[dir->dir_count].offset = dire->offset;\n\t\t\tdir->dirs[dir->dir_count].type = dire->type;\n\t\t\tdir->dir_count ++;\n\t\t\tbytes += dire->size + 1;\n\t\t}\n\t}\n\n\treturn dir;\n\ncorrupted:\n\tfree(dir->dirs);\n\tfree(dir);\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-22'], 'message': 'Unsquashfs: fix write outside destination directory exploit\n\nAn issue on Github (https://github.com/plougher/squashfs-tools/issues/72)\nshows how some specially crafted Squashfs filesystems containing\ninvalid file names (with '/' and ..) can cause Unsquashfs to write\nfiles outside of the destination directory.\n\nThis commit fixes this exploit by checking all names for\nvalidity.\n\nIn doing so I have also added checks for '.' and for names that\nare shorter than they should be (names in the file system should\nnot have '\\0' terminators).\n\nSigned-off-by: Phillip Lougher '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: dissect_dnp3_message(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_)\n{\n proto_item *ti, *tdl, *tc, *hidden_item;\n proto_tree *dnp3_tree, *dl_tree, *field_tree;\n int offset = 0, temp_offset = 0;\n gboolean dl_prm;\n guint8 dl_len, dl_ctl, dl_func;\n const gchar *func_code_str;\n guint16 dl_dst, dl_src, calc_dl_crc;\n\n /* Make entries in Protocol column and Info column on summary display */\n col_set_str(pinfo->cinfo, COL_PROTOCOL, \"DNP 3.0\");\n col_clear(pinfo->cinfo, COL_INFO);\n\n /* Skip \"0x0564\" header bytes */\n temp_offset += 2;\n\n dl_len = tvb_get_guint8(tvb, temp_offset);\n temp_offset += 1;\n\n dl_ctl = tvb_get_guint8(tvb, temp_offset);\n temp_offset += 1;\n\n dl_dst = tvb_get_letohs(tvb, temp_offset);\n temp_offset += 2;\n\n dl_src = tvb_get_letohs(tvb, temp_offset);\n\n dl_func = dl_ctl & DNP3_CTL_FUNC;\n dl_prm = dl_ctl & DNP3_CTL_PRM;\n func_code_str = val_to_str(dl_func, dl_prm ? dnp3_ctl_func_pri_vals : dnp3_ctl_func_sec_vals,\n \"Unknown function (0x%02x)\");\n\n /* Make sure source and dest are always in the info column */\n col_append_fstr(pinfo->cinfo, COL_INFO, \"from %u to %u\", dl_src, dl_dst);\n col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL, \"len=%u, %s\", dl_len, func_code_str);\n\n /* create display subtree for the protocol */\n ti = proto_tree_add_item(tree, proto_dnp3, tvb, offset, -1, ENC_NA);\n dnp3_tree = proto_item_add_subtree(ti, ett_dnp3);\n\n /* Create Subtree for Data Link Layer */\n dl_tree = proto_tree_add_subtree_format(dnp3_tree, tvb, offset, DNP_HDR_LEN, ett_dnp3_dl, &tdl,\n \"Data Link Layer, Len: %u, From: %u, To: %u, \", dl_len, dl_src, dl_dst);\n if (dl_prm) {\n if (dl_ctl & DNP3_CTL_DIR) proto_item_append_text(tdl, \"DIR, \");\n if (dl_ctl & DNP3_CTL_PRM) proto_item_append_text(tdl, \"PRM, \");\n if (dl_ctl & DNP3_CTL_FCB) proto_item_append_text(tdl, \"FCB, \");\n if (dl_ctl & DNP3_CTL_FCV) proto_item_append_text(tdl, \"FCV, \");\n }\n else {\n if (dl_ctl & DNP3_CTL_DIR) proto_item_append_text(tdl, \"DIR, \");\n if (dl_ctl & DNP3_CTL_PRM) proto_item_append_text(tdl, \"PRM, \");\n if (dl_ctl & DNP3_CTL_RES) proto_item_append_text(tdl, \"RES, \");\n if (dl_ctl & DNP3_CTL_DFC) proto_item_append_text(tdl, \"DFC, \");\n }\n proto_item_append_text(tdl, \"%s\", func_code_str);\n\n /* start bytes */\n proto_tree_add_item(dl_tree, hf_dnp3_start, tvb, offset, 2, ENC_BIG_ENDIAN);\n offset += 2;\n\n /* add length field */\n proto_tree_add_item(dl_tree, hf_dnp3_len, tvb, offset, 1, ENC_BIG_ENDIAN);\n offset += 1;\n\n /* Add Control Byte Subtree */\n tc = proto_tree_add_uint_format_value(dl_tree, hf_dnp3_ctl, tvb, offset, 1, dl_ctl,\n \"0x%02x (\", dl_ctl);\n /* Add Text to Control Byte Subtree Header */\n if (dl_prm) {\n if (dl_ctl & DNP3_CTL_DIR) proto_item_append_text(tc, \"DIR, \");\n if (dl_ctl & DNP3_CTL_PRM) proto_item_append_text(tc, \"PRM, \");\n if (dl_ctl & DNP3_CTL_FCB) proto_item_append_text(tc, \"FCB, \");\n if (dl_ctl & DNP3_CTL_FCV) proto_item_append_text(tc, \"FCV, \");\n }\n else {\n if (dl_ctl & DNP3_CTL_DIR) proto_item_append_text(tc, \"DIR, \");\n if (dl_ctl & DNP3_CTL_PRM) proto_item_append_text(tc, \"PRM, \");\n if (dl_ctl & DNP3_CTL_RES) proto_item_append_text(tc, \"RES, \");\n if (dl_ctl & DNP3_CTL_DFC) proto_item_append_text(tc, \"DFC, \");\n }\n proto_item_append_text(tc, \"%s)\", func_code_str );\n field_tree = proto_item_add_subtree(tc, ett_dnp3_dl_ctl);\n\n /* Add Control Byte Subtree Items */\n if (dl_prm) {\n proto_tree_add_item(field_tree, hf_dnp3_ctl_dir, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_prm, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_fcb, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_fcv, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_prifunc, tvb, offset, 1, ENC_BIG_ENDIAN);\n }\n else {\n proto_tree_add_item(field_tree, hf_dnp3_ctl_dir, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_prm, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_dfc, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_secfunc, tvb, offset, 1, ENC_BIG_ENDIAN);\n }\n offset += 1;\n\n /* add destination and source addresses */\n proto_tree_add_item(dl_tree, hf_dnp3_dst, tvb, offset, 2, ENC_LITTLE_ENDIAN);\n hidden_item = proto_tree_add_item(dl_tree, hf_dnp3_addr, tvb, offset, 2, ENC_LITTLE_ENDIAN);\n proto_item_set_hidden(hidden_item);\n offset += 2;\n proto_tree_add_item(dl_tree, hf_dnp3_src, tvb, offset, 2, ENC_LITTLE_ENDIAN);\n hidden_item = proto_tree_add_item(dl_tree, hf_dnp3_addr, tvb, offset, 2, ENC_LITTLE_ENDIAN);\n proto_item_set_hidden(hidden_item);\n offset += 2;\n\n /* and header CRC */\n calc_dl_crc = calculateCRCtvb(tvb, 0, DNP_HDR_LEN - 2);\n proto_tree_add_checksum(dl_tree, tvb, offset, hf_dnp3_data_hdr_crc,\n hf_dnp3_data_hdr_crc_status, &ei_dnp3_data_hdr_crc_incorrect,\n pinfo, calc_dl_crc, ENC_LITTLE_ENDIAN, PROTO_CHECKSUM_VERIFY);\n offset += 2;\n\n /* If the DataLink function is 'Request Link Status' or 'Status of Link',\n or 'Reset Link' we don't expect any Transport or Application Layer Data\n NOTE: This code should probably check what DOES have TR or AL data */\n if ((dl_func != DL_FUNC_LINK_STAT) && (dl_func != DL_FUNC_STAT_LINK) &&\n (dl_func != DL_FUNC_RESET_LINK) && (dl_func != DL_FUNC_ACK))\n {\n proto_tree *data_tree;\n proto_item *data_ti;\n guint8 tr_ctl, tr_seq;\n gboolean tr_fir, tr_fin;\n guint8 *al_buffer, *al_buffer_ptr;\n guint8 data_len;\n int data_start = offset;\n int tl_offset;\n gboolean crc_OK = FALSE;\n tvbuff_t *next_tvb;\n guint i;\n static int * const transport_flags[] = {\n &hf_dnp3_tr_fin,\n &hf_dnp3_tr_fir,\n &hf_dnp3_tr_seq,\n NULL\n };\n\n /* get the transport layer byte */\n tr_ctl = tvb_get_guint8(tvb, offset);\n tr_seq = tr_ctl & DNP3_TR_SEQ;\n tr_fir = tr_ctl & DNP3_TR_FIR;\n tr_fin = tr_ctl & DNP3_TR_FIN;\n\n /* Add Transport Layer Tree */\n tc = proto_tree_add_bitmask(dnp3_tree, tvb, offset, hf_dnp3_tr_ctl, ett_dnp3_tr_ctl, transport_flags, ENC_BIG_ENDIAN);\n proto_item_append_text(tc, \"(\");\n if (tr_fir) proto_item_append_text(tc, \"FIR, \");\n if (tr_fin) proto_item_append_text(tc, \"FIN, \");\n proto_item_append_text(tc, \"Sequence %u)\", tr_seq);\n\n /* Add data chunk tree */\n data_tree = proto_tree_add_subtree(dnp3_tree, tvb, offset, -1, ett_dnp3_dl_data, &data_ti, \"Data Chunks\");\n\n /* extract the application layer data, validating the CRCs */\n\n /* XXX - check for dl_len <= 5 */\n data_len = dl_len - 5;\n al_buffer = (guint8 *)wmem_alloc(pinfo->pool, data_len);\n al_buffer_ptr = al_buffer;\n i = 0;\n tl_offset = 1; /* skip the initial transport layer byte when assembling chunks for the application layer tvb */\n while (data_len > 0)\n {\n guint8 chk_size;\n const guint8 *chk_ptr;\n proto_tree *chk_tree;\n proto_item *chk_len_ti;\n guint16 calc_crc, act_crc;\n\n chk_size = MIN(data_len, AL_MAX_CHUNK_SIZE);\n chk_ptr = tvb_get_ptr(tvb, offset, chk_size);\n memcpy(al_buffer_ptr, chk_ptr + tl_offset, chk_size - tl_offset);\n al_buffer_ptr += chk_size - tl_offset;\n\n chk_tree = proto_tree_add_subtree_format(data_tree, tvb, offset, chk_size + 2, ett_dnp3_dl_chunk, NULL, \"Data Chunk: %u\", i);\n proto_tree_add_item(chk_tree, hf_dnp3_data_chunk, tvb, offset, chk_size, ENC_NA);\n chk_len_ti = proto_tree_add_uint(chk_tree, hf_dnp3_data_chunk_len, tvb, offset, 0, chk_size);\n proto_item_set_generated(chk_len_ti);\n\n offset += chk_size;\n\n calc_crc = calculateCRC(chk_ptr, chk_size);\n proto_tree_add_checksum(chk_tree, tvb, offset, hf_dnp3_data_chunk_crc,\n hf_dnp3_data_chunk_crc_status, &ei_dnp3_data_chunk_crc_incorrect,\n pinfo, calc_crc, ENC_LITTLE_ENDIAN, PROTO_CHECKSUM_VERIFY);\n act_crc = tvb_get_letohs(tvb, offset);\n offset += 2;\n crc_OK = calc_crc == act_crc;\n if (!crc_OK)\n {\n /* Don't trust the rest of the data, get out of here */\n break;\n }\n data_len -= chk_size;\n i++;\n tl_offset = 0; /* copy all the data in the rest of the chunks */\n }\n proto_item_set_len(data_ti, offset - data_start);\n\n /* if crc OK, set up new tvb */\n if (crc_OK)\n {\n tvbuff_t *al_tvb;\n gboolean save_fragmented;\n\n al_tvb = tvb_new_child_real_data(tvb, al_buffer, (guint) (al_buffer_ptr-al_buffer), (gint) (al_buffer_ptr-al_buffer));\n\n /* Check for fragmented packet */\n save_fragmented = pinfo->fragmented;\n\n /* Reassemble AL fragments */\n static guint al_max_fragments = 60;\n static guint al_fragment_aging = 64; /* sequence numbers only 6 bit */\n fragment_head *frag_al = NULL;\n pinfo->fragmented = TRUE;\n if (!pinfo->fd->visited)\n {\n frag_al = fragment_add_seq_single_aging(&al_reassembly_table,\n al_tvb, 0, pinfo, tr_seq, NULL,\n tvb_reported_length(al_tvb), /* As this is a constructed tvb, all of it is ok */\n tr_fir, tr_fin,\n al_max_fragments, al_fragment_aging);\n }\n else\n {\n frag_al = fragment_get_reassembled_id(&al_reassembly_table, pinfo, tr_seq);\n }\n next_tvb = process_reassembled_data(al_tvb, 0, pinfo,\n \"Reassembled DNP 3.0 Application Layer message\", frag_al, &dnp3_frag_items,\n NULL, dnp3_tree);\n\n if (frag_al)\n {\n if (pinfo->num == frag_al->reassembled_in && pinfo->curr_layer_num == frag_al->reas_in_layer_num)\n {\n /* As a complete AL message will have cleared the info column,\n make sure source and dest are always in the info column */\n //col_append_fstr(pinfo->cinfo, COL_INFO, \"from %u to %u\", dl_src, dl_dst);\n //col_set_fence(pinfo->cinfo, COL_INFO);\n dissect_dnp3_al(next_tvb, pinfo, dnp3_tree);\n }\n else\n {\n /* Lock any column info set by the DL and TL */\n col_set_fence(pinfo->cinfo, COL_INFO);\n col_append_fstr(pinfo->cinfo, COL_INFO,\n \" (Application Layer fragment %u, reassembled in packet %u)\",\n tr_seq, frag_al->reassembled_in);\n proto_tree_add_item(dnp3_tree, hf_al_frag_data, al_tvb, 0, -1, ENC_NA);\n }\n }\n else\n {\n col_append_fstr(pinfo->cinfo, COL_INFO,\n \" (Application Layer Unreassembled fragment %u)\",\n tr_seq);\n proto_tree_add_item(dnp3_tree, hf_al_frag_data, al_tvb, 0, -1, ENC_NA);\n }\n\n pinfo->fragmented = save_fragmented;\n }\n else\n {\n /* CRC error - throw away the data. */\n next_tvb = NULL;\n }\n }\n\n /* Set the length of the message */\n proto_item_set_len(ti, offset);\n return offset;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': 'dnp: plug a memory leak.\n\nIf we're throwing away the data, *throw away the data* - free it, as\nwe're not using it as the backing data for a tvbuff.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: mswin_printer_fopen(gx_io_device * iodev, const char *fname, const char *access,\n gp_file ** pfile, char *rfname, uint rnamelen, gs_memory_t *mem)\n{\n DWORD version = GetVersion();\n HANDLE hprinter;\n int pipeh[2];\n uintptr_t tid;\n HANDLE hthread;\n char pname[gp_file_name_sizeof];\n uintptr_t *ptid = &((tid_t *)(iodev->state))->tid;\n gs_lib_ctx_t *ctx = mem->gs_lib_ctx;\n gs_fs_list_t *fs = ctx->core->fs;\n\n if (gp_validate_path(mem, fname, access) != 0)\n return gs_error_invalidfileaccess;\n\n /* First we try the open_printer method. */\n /* Note that the loop condition here ensures we don't\n * trigger on the last registered fs entry (our standard\n * 'file' one). */\n if (access[0] == 'w' || access[0] == 'a')\n {\n *pfile = NULL;\n for (fs = ctx->core->fs; fs != NULL && fs->next != NULL; fs = fs->next)\n {\n int code = 0;\n if (fs->fs.open_printer)\n code = fs->fs.open_printer(mem, fs->secret, fname, 1, pfile);\n if (code < 0)\n return code;\n if (*pfile != NULL)\n return code;\n }\n } else\n return gs_error_invalidfileaccess;\n\n /* If nothing claimed that, then continue with the\n * standard MS way of working. */\n\n /* Win32s supports neither pipes nor Win32 printers. */\n if (((HIWORD(version) & 0x8000) != 0) &&\n ((HIWORD(version) & 0x4000) == 0))\n return_error(gs_error_invalidfileaccess);\n\n /* Make sure that printer exists. */\n if (!gp_OpenPrinter((LPTSTR)fname, &hprinter))\n return_error(gs_error_invalidfileaccess);\n ClosePrinter(hprinter);\n\n *pfile = gp_file_FILE_alloc(mem);\n if (*pfile == NULL)\n return_error(gs_error_VMerror);\n\n /* Create a pipe to connect a FILE pointer to a Windows printer. */\n if (_pipe(pipeh, 4096, _O_BINARY) != 0) {\n gp_file_dealloc(*pfile);\n *pfile = NULL;\n return_error(gs_fopen_errno_to_code(errno));\n }\n\n if (gp_file_FILE_set(*pfile, fdopen(pipeh[1], (char *)access), NULL)) {\n *pfile = NULL;\n close(pipeh[0]);\n close(pipeh[1]);\n return_error(gs_fopen_errno_to_code(errno));\n }\n\n /* start a thread to read the pipe */\n tid = _beginthread(&mswin_printer_thread, 32768, (void *)(intptr_t)(pipeh[0]));\n if (tid == -1) {\n gp_fclose(*pfile);\n *pfile = NULL;\n close(pipeh[0]);\n return_error(gs_error_invalidfileaccess);\n }\n /* Duplicate thread handle so we can wait on it\n * even if original handle is closed by CRTL\n * when the thread finishes.\n */\n if (!DuplicateHandle(GetCurrentProcess(), (HANDLE)tid,\n GetCurrentProcess(), &hthread,\n 0, FALSE, DUPLICATE_SAME_ACCESS)) {\n gp_fclose(*pfile);\n *pfile = NULL;\n return_error(gs_error_invalidfileaccess);\n }\n *ptid = (uintptr_t)hthread;\n\n /* Give the name of the printer to the thread by writing\n * it to the pipe. This is avoids elaborate thread\n * synchronisation code.\n */\n strncpy(pname, fname, sizeof(pname));\n gp_fwrite(pname, 1, sizeof(pname), *pfile);\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Bug 704342: Include device specifier strings in access validation\n\nfor the \"%pipe%\", %handle%\" and %printer% io devices.\n\nWe previously validated only the part after the \"%pipe%\" Postscript device\nspecifier, but this proved insufficient.\n\nThis rebuilds the original file name string, and validates it complete. The\nslight complication for \"%pipe%\" is it can be reached implicitly using\n\"|\" so we have to check both prefixes.\n\nAddresses CVE-2021-3781'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static struct dir *squashfs_opendir(unsigned int block_start, unsigned int offset,\n\tstruct inode **i)\n{\n\tstruct squashfs_dir_header dirh;\n\tchar buffer[sizeof(struct squashfs_dir_entry) + SQUASHFS_NAME_LEN + 1]\n\t\t__attribute__((aligned));\n\tstruct squashfs_dir_entry *dire = (struct squashfs_dir_entry *) buffer;\n\tlong long start;\n\tint bytes = 0, dir_count, size, res;\n\tstruct dir_ent *ent, *cur_ent = NULL;\n\tstruct dir *dir;\n\n\tTRACE(\"squashfs_opendir: inode start block %d, offset %d\\n\",\n\t\tblock_start, offset);\n\n\t*i = read_inode(block_start, offset);\n\n\tdir = malloc(sizeof(struct dir));\n\tif(dir == NULL)\n\t\tMEM_ERROR();\n\n\tdir->dir_count = 0;\n\tdir->cur_entry = NULL;\n\tdir->mode = (*i)->mode;\n\tdir->uid = (*i)->uid;\n\tdir->guid = (*i)->gid;\n\tdir->mtime = (*i)->time;\n\tdir->xattr = (*i)->xattr;\n\tdir->dirs = NULL;\n\n\tif ((*i)->data == 3)\n\t\t/*\n\t\t * if the directory is empty, skip the unnecessary\n\t\t * lookup_entry, this fixes the corner case with\n\t\t * completely empty filesystems where lookup_entry correctly\n\t\t * returning -1 is incorrectly treated as an error\n\t\t */\n\t\treturn dir;\n\n\tstart = sBlk.s.directory_table_start + (*i)->start;\n\toffset = (*i)->offset;\n\tsize = (*i)->data + bytes - 3;\n\n\twhile(bytes < size) {\t\t\t\n\t\tres = read_directory_data(&dirh, &start, &offset, sizeof(dirh));\n\t\tif(res == FALSE)\n\t\t\tgoto corrupted;\n\n\t\tSQUASHFS_INSWAP_DIR_HEADER(&dirh);\n\t\n\t\tdir_count = dirh.count + 1;\n\t\tTRACE(\"squashfs_opendir: Read directory header @ byte position \"\n\t\t\t\"%d, %d directory entries\\n\", bytes, dir_count);\n\t\tbytes += sizeof(dirh);\n\n\t\t/* dir_count should never be larger than SQUASHFS_DIR_COUNT */\n\t\tif(dir_count > SQUASHFS_DIR_COUNT) {\n\t\t\tERROR(\"File system corrupted: too many entries in directory\\n\");\n\t\t\tgoto corrupted;\n\t\t}\n\n\t\twhile(dir_count--) {\n\t\t\tres = read_directory_data(dire, &start, &offset, sizeof(*dire));\n\t\t\tif(res == FALSE)\n\t\t\t\tgoto corrupted;\n\n\t\t\tSQUASHFS_INSWAP_DIR_ENTRY(dire);\n\n\t\t\tbytes += sizeof(*dire);\n\n\t\t\t/* size should never be SQUASHFS_NAME_LEN or larger */\n\t\t\tif(dire->size >= SQUASHFS_NAME_LEN) {\n\t\t\t\tERROR(\"File system corrupted: filename too long\\n\");\n\t\t\t\tgoto corrupted;\n\t\t\t}\n\n\t\t\tres = read_directory_data(dire->name, &start, &offset,\n\t\t\t\t\t\t\t\tdire->size + 1);\n\t\t\tif(res == FALSE)\n\t\t\t\tgoto corrupted;\n\n\t\t\tdire->name[dire->size + 1] = '\\0';\n\n\t\t\t/* check name for invalid characters (i.e /, ., ..) */\n\t\t\tif(check_name(dire->name, dire->size + 1) == FALSE) {\n\t\t\t\tERROR(\"File system corrupted: invalid characters in name\\n\");\n\t\t\t\tgoto corrupted;\n\t\t\t}\n\n\t\t\tTRACE(\"squashfs_opendir: directory entry %s, inode \"\n\t\t\t\t\"%d:%d, type %d\\n\", dire->name,\n\t\t\t\tdirh.start_block, dire->offset, dire->type);\n\n\t\t\tent = malloc(sizeof(struct dir_ent));\n\t\t\tif(ent == NULL)\n\t\t\t\tMEM_ERROR();\n\n\t\t\tent->name = strdup(dire->name);\n\t\t\tent->start_block = dirh.start_block;\n\t\t\tent->offset = dire->offset;\n\t\t\tent->type = dire->type;\n\t\t\tent->next = NULL;\n\t\t\tif(cur_ent == NULL)\n\t\t\t\tdir->dirs = ent;\n\t\t\telse\n\t\t\t\tcur_ent->next = ent;\n\t\t\tcur_ent = ent;\n\t\t\tdir->dir_count ++;\n\t\t\tbytes += dire->size + 1;\n\t\t}\n\t}\n\n\treturn dir;\n\ncorrupted:\n\tsquashfs_closedir(dir);\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-59', 'CWE-22'], 'message': 'Unsquashfs: additional write outside destination directory exploit fix\n\nAn issue on github (https://github.com/plougher/squashfs-tools/issues/72)\nshowed how some specially crafted Squashfs filesystems containing\ninvalid file names (with '/' and '..') can cause Unsquashfs to write\nfiles outside of the destination directory.\n\nSince then it has been shown that specially crafted Squashfs filesystems\nthat contain a symbolic link pointing outside of the destination directory,\ncoupled with an identically named file within the same directory, can\ncause Unsquashfs to write files outside of the destination directory.\n\nSpecifically the symbolic link produces a pathname pointing outside\nof the destination directory, which is then followed when writing the\nduplicate identically named file within the directory.\n\nThis commit fixes this exploit by explictly checking for duplicate\nfilenames within a directory. As directories in v2.1, v3.x, and v4.0\nfilesystems are sorted, this is achieved by checking for consecutively\nidentical filenames. Additionally directories are checked to\nensure they are sorted, to avoid attempts to evade the duplicate\ncheck.\n\nVersion 1.x and 2.0 filesystems (where the directories were unsorted)\nare sorted and then the above duplicate filename check is applied.\n\nSigned-off-by: Phillip Lougher '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: connection_ap_handshake_rewrite_and_attach(entry_connection_t *conn,\n origin_circuit_t *circ,\n crypt_path_t *cpath)\n{\n socks_request_t *socks = conn->socks_request;\n const or_options_t *options = get_options();\n connection_t *base_conn = ENTRY_TO_CONN(conn);\n time_t now = time(NULL);\n rewrite_result_t rr;\n\n /* First we'll do the rewrite part. Let's see if we get a reasonable\n * answer.\n */\n memset(&rr, 0, sizeof(rr));\n connection_ap_handshake_rewrite(conn,&rr);\n\n if (rr.should_close) {\n /* connection_ap_handshake_rewrite told us to close the connection:\n * either because it sent back an answer, or because it sent back an\n * error */\n connection_mark_unattached_ap(conn, rr.end_reason);\n if (END_STREAM_REASON_DONE == (rr.end_reason & END_STREAM_REASON_MASK))\n return 0;\n else\n return -1;\n }\n\n const time_t map_expires = rr.map_expires;\n const int automap = rr.automap;\n const addressmap_entry_source_t exit_source = rr.exit_source;\n\n /* Now see whether the hostname is bogus. This could happen because of an\n * onion hostname whose format we don't recognize. */\n hostname_type_t addresstype;\n if (!parse_extended_hostname(socks->address, &addresstype)) {\n control_event_client_status(LOG_WARN, \"SOCKS_BAD_HOSTNAME HOSTNAME=%s\",\n escaped(socks->address));\n if (addresstype == BAD_HOSTNAME) {\n conn->socks_request->socks_extended_error_code = SOCKS5_HS_BAD_ADDRESS;\n }\n connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);\n return -1;\n }\n\n /* If this is a .exit hostname, strip off the .name.exit part, and\n * see whether we're willing to connect there, and and otherwise handle the\n * .exit address.\n *\n * We'll set chosen_exit_name and/or close the connection as appropriate.\n */\n if (addresstype == EXIT_HOSTNAME) {\n /* If StrictNodes is not set, then .exit overrides ExcludeNodes but\n * not ExcludeExitNodes. */\n routerset_t *excludeset = options->StrictNodes ?\n options->ExcludeExitNodesUnion_ : options->ExcludeExitNodes;\n const node_t *node = NULL;\n\n /* If this .exit was added by an AUTOMAP, then it came straight from\n * a user. That's not safe. */\n if (exit_source == ADDRMAPSRC_AUTOMAP) {\n /* Whoops; this one is stale. It must have gotten added earlier?\n * (Probably this is not possible, since AllowDotExit no longer\n * exists.) */\n log_warn(LD_APP,\"Stale automapped address for '%s.exit'. Refusing.\",\n safe_str_client(socks->address));\n control_event_client_status(LOG_WARN, \"SOCKS_BAD_HOSTNAME HOSTNAME=%s\",\n escaped(socks->address));\n connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);\n tor_assert_nonfatal_unreached();\n return -1;\n }\n\n /* Double-check to make sure there are no .exits coming from\n * impossible/weird sources. */\n if (exit_source == ADDRMAPSRC_DNS || exit_source == ADDRMAPSRC_NONE) {\n /* It shouldn't be possible to get a .exit address from any of these\n * sources. */\n log_warn(LD_BUG,\"Address '%s.exit', with impossible source for the \"\n \".exit part. Refusing.\",\n safe_str_client(socks->address));\n control_event_client_status(LOG_WARN, \"SOCKS_BAD_HOSTNAME HOSTNAME=%s\",\n escaped(socks->address));\n connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);\n return -1;\n }\n\n tor_assert(!automap);\n\n /* Now, find the character before the .(name) part.\n * (The \".exit\" part got stripped off by \"parse_extended_hostname\").\n *\n * We're going to put the exit name into conn->chosen_exit_name, and\n * look up a node correspondingly. */\n char *s = strrchr(socks->address,'.');\n if (s) {\n /* The address was of the form \"(stuff).(name).exit */\n if (s[1] != '\\0') {\n /* Looks like a real .exit one. */\n conn->chosen_exit_name = tor_strdup(s+1);\n node = node_get_by_nickname(conn->chosen_exit_name, 0);\n\n if (exit_source == ADDRMAPSRC_TRACKEXIT) {\n /* We 5 tries before it expires the addressmap */\n conn->chosen_exit_retries = TRACKHOSTEXITS_RETRIES;\n }\n *s = 0;\n } else {\n /* Oops, the address was (stuff)..exit. That's not okay. */\n log_warn(LD_APP,\"Malformed exit address '%s.exit'. Refusing.\",\n safe_str_client(socks->address));\n control_event_client_status(LOG_WARN, \"SOCKS_BAD_HOSTNAME HOSTNAME=%s\",\n escaped(socks->address));\n connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);\n return -1;\n }\n } else {\n /* It looks like they just asked for \"foo.exit\". That's a special\n * form that means (foo's address).foo.exit. */\n\n conn->chosen_exit_name = tor_strdup(socks->address);\n node = node_get_by_nickname(conn->chosen_exit_name, 0);\n if (node) {\n *socks->address = 0;\n node_get_address_string(node, socks->address, sizeof(socks->address));\n }\n }\n\n /* Now make sure that the chosen exit exists... */\n if (!node) {\n log_warn(LD_APP,\n \"Unrecognized relay in exit address '%s.exit'. Refusing.\",\n safe_str_client(socks->address));\n connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);\n return -1;\n }\n /* ...and make sure that it isn't excluded. */\n if (routerset_contains_node(excludeset, node)) {\n log_warn(LD_APP,\n \"Excluded relay in exit address '%s.exit'. Refusing.\",\n safe_str_client(socks->address));\n connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);\n return -1;\n }\n /* XXXX-1090 Should we also allow foo.bar.exit if ExitNodes is set and\n Bar is not listed in it? I say yes, but our revised manpage branch\n implies no. */\n }\n\n /* Now, we handle everything that isn't a .onion address. */\n if (addresstype != ONION_V2_HOSTNAME && addresstype != ONION_V3_HOSTNAME) {\n /* Not a hidden-service request. It's either a hostname or an IP,\n * possibly with a .exit that we stripped off. We're going to check\n * if we're allowed to connect/resolve there, and then launch the\n * appropriate request. */\n\n /* Check for funny characters in the address. */\n if (address_is_invalid_destination(socks->address, 1)) {\n control_event_client_status(LOG_WARN, \"SOCKS_BAD_HOSTNAME HOSTNAME=%s\",\n escaped(socks->address));\n log_warn(LD_APP,\n \"Destination '%s' seems to be an invalid hostname. Failing.\",\n safe_str_client(socks->address));\n connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);\n return -1;\n }\n\n /* socks->address is a non-onion hostname or IP address.\n * If we can't do any non-onion requests, refuse the connection.\n * If we have a hostname but can't do DNS, refuse the connection.\n * If we have an IP address, but we can't use that address family,\n * refuse the connection.\n *\n * If we can do DNS requests, and we can use at least one address family,\n * then we have to resolve the address first. Then we'll know if it\n * resolves to a usable address family. */\n\n /* First, check if all non-onion traffic is disabled */\n if (!conn->entry_cfg.dns_request && !conn->entry_cfg.ipv4_traffic\n && !conn->entry_cfg.ipv6_traffic) {\n log_warn(LD_APP, \"Refusing to connect to non-hidden-service hostname \"\n \"or IP address %s because Port has OnionTrafficOnly set (or \"\n \"NoDNSRequest, NoIPv4Traffic, and NoIPv6Traffic).\",\n safe_str_client(socks->address));\n connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);\n return -1;\n }\n\n /* Then check if we have a hostname or IP address, and whether DNS or\n * the IP address family are permitted. Reject if not. */\n tor_addr_t dummy_addr;\n int socks_family = tor_addr_parse(&dummy_addr, socks->address);\n /* family will be -1 for a non-onion hostname that's not an IP */\n if (socks_family == -1) {\n if (!conn->entry_cfg.dns_request) {\n log_warn(LD_APP, \"Refusing to connect to hostname %s \"\n \"because Port has NoDNSRequest set.\",\n safe_str_client(socks->address));\n connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);\n return -1;\n }\n } else if (socks_family == AF_INET) {\n if (!conn->entry_cfg.ipv4_traffic) {\n log_warn(LD_APP, \"Refusing to connect to IPv4 address %s because \"\n \"Port has NoIPv4Traffic set.\",\n safe_str_client(socks->address));\n connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);\n return -1;\n }\n } else if (socks_family == AF_INET6) {\n if (!conn->entry_cfg.ipv6_traffic) {\n log_warn(LD_APP, \"Refusing to connect to IPv6 address %s because \"\n \"Port has NoIPv6Traffic set.\",\n safe_str_client(socks->address));\n connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);\n return -1;\n }\n } else {\n tor_assert_nonfatal_unreached_once();\n }\n\n /* See if this is a hostname lookup that we can answer immediately.\n * (For example, an attempt to look up the IP address for an IP address.)\n */\n if (socks->command == SOCKS_COMMAND_RESOLVE) {\n tor_addr_t answer;\n /* Reply to resolves immediately if we can. */\n if (tor_addr_parse(&answer, socks->address) >= 0) {/* is it an IP? */\n /* remember _what_ is supposed to have been resolved. */\n strlcpy(socks->address, rr.orig_address, sizeof(socks->address));\n connection_ap_handshake_socks_resolved_addr(conn, &answer, -1,\n map_expires);\n connection_mark_unattached_ap(conn,\n END_STREAM_REASON_DONE |\n END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);\n return 0;\n }\n tor_assert(!automap);\n rep_hist_note_used_resolve(now); /* help predict this next time */\n } else if (socks->command == SOCKS_COMMAND_CONNECT) {\n /* Now see if this is a connect request that we can reject immediately */\n\n tor_assert(!automap);\n /* Don't allow connections to port 0. */\n if (socks->port == 0) {\n log_notice(LD_APP,\"Application asked to connect to port 0. Refusing.\");\n connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);\n return -1;\n }\n /* You can't make connections to internal addresses, by default.\n * Exceptions are begindir requests (where the address is meaningless),\n * or cases where you've hand-configured a particular exit, thereby\n * making the local address meaningful. */\n if (options->ClientRejectInternalAddresses &&\n !conn->use_begindir && !conn->chosen_exit_name && !circ) {\n /* If we reach this point then we don't want to allow internal\n * addresses. Check if we got one. */\n tor_addr_t addr;\n if (tor_addr_hostname_is_local(socks->address) ||\n (tor_addr_parse(&addr, socks->address) >= 0 &&\n tor_addr_is_internal(&addr, 0))) {\n /* If this is an explicit private address with no chosen exit node,\n * then we really don't want to try to connect to it. That's\n * probably an error. */\n if (conn->is_transparent_ap) {\n#define WARN_INTRVL_LOOP 300\n static ratelim_t loop_warn_limit = RATELIM_INIT(WARN_INTRVL_LOOP);\n char *m;\n if ((m = rate_limit_log(&loop_warn_limit, approx_time()))) {\n log_warn(LD_NET,\n \"Rejecting request for anonymous connection to private \"\n \"address %s on a TransPort or NATDPort. Possible loop \"\n \"in your NAT rules?%s\", safe_str_client(socks->address),\n m);\n tor_free(m);\n }\n } else {\n#define WARN_INTRVL_PRIV 300\n static ratelim_t priv_warn_limit = RATELIM_INIT(WARN_INTRVL_PRIV);\n char *m;\n if ((m = rate_limit_log(&priv_warn_limit, approx_time()))) {\n log_warn(LD_NET,\n \"Rejecting SOCKS request for anonymous connection to \"\n \"private address %s.%s\",\n safe_str_client(socks->address),m);\n tor_free(m);\n }\n }\n connection_mark_unattached_ap(conn, END_STREAM_REASON_PRIVATE_ADDR);\n return -1;\n }\n } /* end \"if we should check for internal addresses\" */\n\n /* Okay. We're still doing a CONNECT, and it wasn't a private\n * address. Here we do special handling for literal IP addresses,\n * to see if we should reject this preemptively, and to set up\n * fields in conn->entry_cfg to tell the exit what AF we want. */\n {\n tor_addr_t addr;\n /* XXX Duplicate call to tor_addr_parse. */\n if (tor_addr_parse(&addr, socks->address) >= 0) {\n /* If we reach this point, it's an IPv4 or an IPv6 address. */\n sa_family_t family = tor_addr_family(&addr);\n\n if ((family == AF_INET && ! conn->entry_cfg.ipv4_traffic) ||\n (family == AF_INET6 && ! conn->entry_cfg.ipv6_traffic)) {\n /* You can't do an IPv4 address on a v6-only socks listener,\n * or vice versa. */\n log_warn(LD_NET, \"Rejecting SOCKS request for an IP address \"\n \"family that this listener does not support.\");\n connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);\n return -1;\n } else if (family == AF_INET6 && socks->socks_version == 4) {\n /* You can't make a socks4 request to an IPv6 address. Socks4\n * doesn't support that. */\n log_warn(LD_NET, \"Rejecting SOCKS4 request for an IPv6 address.\");\n connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);\n return -1;\n } else if (socks->socks_version == 4 &&\n !conn->entry_cfg.ipv4_traffic) {\n /* You can't do any kind of Socks4 request when IPv4 is forbidden.\n *\n * XXX raise this check outside the enclosing block? */\n log_warn(LD_NET, \"Rejecting SOCKS4 request on a listener with \"\n \"no IPv4 traffic supported.\");\n connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);\n return -1;\n } else if (family == AF_INET6) {\n /* Tell the exit: we won't accept any ipv4 connection to an IPv6\n * address. */\n conn->entry_cfg.ipv4_traffic = 0;\n } else if (family == AF_INET) {\n /* Tell the exit: we won't accept any ipv6 connection to an IPv4\n * address. */\n conn->entry_cfg.ipv6_traffic = 0;\n }\n }\n }\n\n /* we never allow IPv6 answers on socks4. (TODO: Is this smart?) */\n if (socks->socks_version == 4)\n conn->entry_cfg.ipv6_traffic = 0;\n\n /* Still handling CONNECT. Now, check for exit enclaves. (Which we\n * don't do on BEGIN_DIR, or when there is a chosen exit.)\n *\n * TODO: Should we remove this? Exit enclaves are nutty and don't\n * work very well\n */\n if (!conn->use_begindir && !conn->chosen_exit_name && !circ) {\n /* see if we can find a suitable enclave exit */\n const node_t *r =\n router_find_exact_exit_enclave(socks->address, socks->port);\n if (r) {\n log_info(LD_APP,\n \"Redirecting address %s to exit at enclave router %s\",\n safe_str_client(socks->address), node_describe(r));\n /* use the hex digest, not nickname, in case there are two\n routers with this nickname */\n conn->chosen_exit_name =\n tor_strdup(hex_str(r->identity, DIGEST_LEN));\n conn->chosen_exit_optional = 1;\n }\n }\n\n /* Still handling CONNECT: warn or reject if it's using a dangerous\n * port. */\n if (!conn->use_begindir && !conn->chosen_exit_name && !circ)\n if (consider_plaintext_ports(conn, socks->port) < 0)\n return -1;\n\n /* Remember the port so that we will predict that more requests\n there will happen in the future. */\n if (!conn->use_begindir) {\n /* help predict this next time */\n rep_hist_note_used_port(now, socks->port);\n }\n } else if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {\n rep_hist_note_used_resolve(now); /* help predict this next time */\n /* no extra processing needed */\n } else {\n /* We should only be doing CONNECT, RESOLVE, or RESOLVE_PTR! */\n tor_fragile_assert();\n }\n\n /* Okay. At this point we've set chosen_exit_name if needed, rewritten the\n * address, and decided not to reject it for any number of reasons. Now\n * mark the connection as waiting for a circuit, and try to attach it!\n */\n base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;\n\n /* If we were given a circuit to attach to, try to attach. Otherwise,\n * try to find a good one and attach to that. */\n int rv;\n if (circ) {\n rv = connection_ap_handshake_attach_chosen_circuit(conn, circ, cpath);\n } else {\n /* We'll try to attach it at the next event loop, or whenever\n * we call connection_ap_attach_pending() */\n connection_ap_mark_as_pending_circuit(conn);\n rv = 0;\n }\n\n /* If the above function returned 0 then we're waiting for a circuit.\n * if it returned 1, we're attached. Both are okay. But if it returned\n * -1, there was an error, so make sure the connection is marked, and\n * return -1. */\n if (rv < 0) {\n if (!base_conn->marked_for_close)\n connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);\n return -1;\n }\n\n return 0;\n } else {\n /* If we get here, it's a request for a .onion address! */\n tor_assert(addresstype == ONION_V2_HOSTNAME ||\n addresstype == ONION_V3_HOSTNAME);\n tor_assert(!automap);\n return connection_ap_handle_onion(conn, socks, circ, addresstype);\n }\n\n return 0; /* unreached but keeps the compiler happy */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-532'], 'message': 'Log warning when connecting to soon-to-be-deprecated v2 onions.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ldbRepl(lua_State *lua) {\n sds *argv;\n int argc;\n\n /* We continue processing commands until a command that should return\n * to the Lua interpreter is found. */\n while(1) {\n while((argv = ldbReplParseCommand(&argc)) == NULL) {\n char buf[1024];\n int nread = connRead(ldb.conn,buf,sizeof(buf));\n if (nread <= 0) {\n /* Make sure the script runs without user input since the\n * client is no longer connected. */\n ldb.step = 0;\n ldb.bpcount = 0;\n return C_ERR;\n }\n ldb.cbuf = sdscatlen(ldb.cbuf,buf,nread);\n }\n\n /* Flush the old buffer. */\n sdsfree(ldb.cbuf);\n ldb.cbuf = sdsempty();\n\n /* Execute the command. */\n if (!strcasecmp(argv[0],\"h\") || !strcasecmp(argv[0],\"help\")) {\nldbLog(sdsnew(\"Redis Lua debugger help:\"));\nldbLog(sdsnew(\"[h]elp Show this help.\"));\nldbLog(sdsnew(\"[s]tep Run current line and stop again.\"));\nldbLog(sdsnew(\"[n]ext Alias for step.\"));\nldbLog(sdsnew(\"[c]continue Run till next breakpoint.\"));\nldbLog(sdsnew(\"[l]list List source code around current line.\"));\nldbLog(sdsnew(\"[l]list [line] List source code around [line].\"));\nldbLog(sdsnew(\" line = 0 means: current position.\"));\nldbLog(sdsnew(\"[l]list [line] [ctx] In this form [ctx] specifies how many lines\"));\nldbLog(sdsnew(\" to show before/after [line].\"));\nldbLog(sdsnew(\"[w]hole List all source code. Alias for 'list 1 1000000'.\"));\nldbLog(sdsnew(\"[p]rint Show all the local variables.\"));\nldbLog(sdsnew(\"[p]rint Show the value of the specified variable.\"));\nldbLog(sdsnew(\" Can also show global vars KEYS and ARGV.\"));\nldbLog(sdsnew(\"[b]reak Show all breakpoints.\"));\nldbLog(sdsnew(\"[b]reak Add a breakpoint to the specified line.\"));\nldbLog(sdsnew(\"[b]reak - Remove breakpoint from the specified line.\"));\nldbLog(sdsnew(\"[b]reak 0 Remove all breakpoints.\"));\nldbLog(sdsnew(\"[t]race Show a backtrace.\"));\nldbLog(sdsnew(\"[e]eval Execute some Lua code (in a different callframe).\"));\nldbLog(sdsnew(\"[r]edis Execute a Redis command.\"));\nldbLog(sdsnew(\"[m]axlen [len] Trim logged Redis replies and Lua var dumps to len.\"));\nldbLog(sdsnew(\" Specifying zero as means unlimited.\"));\nldbLog(sdsnew(\"[a]bort Stop the execution of the script. In sync\"));\nldbLog(sdsnew(\" mode dataset changes will be retained.\"));\nldbLog(sdsnew(\"\"));\nldbLog(sdsnew(\"Debugger functions you can call from Lua scripts:\"));\nldbLog(sdsnew(\"redis.debug() Produce logs in the debugger console.\"));\nldbLog(sdsnew(\"redis.breakpoint() Stop execution like if there was a breakpoint in the\"));\nldbLog(sdsnew(\" next line of code.\"));\n ldbSendLogs();\n } else if (!strcasecmp(argv[0],\"s\") || !strcasecmp(argv[0],\"step\") ||\n !strcasecmp(argv[0],\"n\") || !strcasecmp(argv[0],\"next\")) {\n ldb.step = 1;\n break;\n } else if (!strcasecmp(argv[0],\"c\") || !strcasecmp(argv[0],\"continue\")){\n break;\n } else if (!strcasecmp(argv[0],\"t\") || !strcasecmp(argv[0],\"trace\")) {\n ldbTrace(lua);\n ldbSendLogs();\n } else if (!strcasecmp(argv[0],\"m\") || !strcasecmp(argv[0],\"maxlen\")) {\n ldbMaxlen(argv,argc);\n ldbSendLogs();\n } else if (!strcasecmp(argv[0],\"b\") || !strcasecmp(argv[0],\"break\")) {\n ldbBreak(argv,argc);\n ldbSendLogs();\n } else if (!strcasecmp(argv[0],\"e\") || !strcasecmp(argv[0],\"eval\")) {\n ldbEval(lua,argv,argc);\n ldbSendLogs();\n } else if (!strcasecmp(argv[0],\"a\") || !strcasecmp(argv[0],\"abort\")) {\n lua_pushstring(lua, \"script aborted for user request\");\n lua_error(lua);\n } else if (argc > 1 &&\n (!strcasecmp(argv[0],\"r\") || !strcasecmp(argv[0],\"redis\"))) {\n ldbRedis(lua,argv,argc);\n ldbSendLogs();\n } else if ((!strcasecmp(argv[0],\"p\") || !strcasecmp(argv[0],\"print\"))) {\n if (argc == 2)\n ldbPrint(lua,argv[1]);\n else\n ldbPrintAll(lua);\n ldbSendLogs();\n } else if (!strcasecmp(argv[0],\"l\") || !strcasecmp(argv[0],\"list\")){\n int around = ldb.currentline, ctx = 5;\n if (argc > 1) {\n int num = atoi(argv[1]);\n if (num > 0) around = num;\n }\n if (argc > 2) ctx = atoi(argv[2]);\n ldbList(around,ctx);\n ldbSendLogs();\n } else if (!strcasecmp(argv[0],\"w\") || !strcasecmp(argv[0],\"whole\")){\n ldbList(1,1000000);\n ldbSendLogs();\n } else {\n ldbLog(sdsnew(\" Unknown Redis Lua debugger command or \"\n \"wrong number of arguments.\"));\n ldbSendLogs();\n }\n\n /* Free the command vector. */\n sdsfreesplitres(argv,argc);\n }\n\n /* Free the current command argv if we break inside the while loop. */\n sdsfreesplitres(argv,argc);\n return C_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-125'], 'message': 'Fix protocol parsing on 'ldbReplParseCommand' (CVE-2021-32672)\n\nThe protocol parsing on 'ldbReplParseCommand' (LUA debugging)\nAssumed protocol correctness. This means that if the following\nis given:\n*1\n$100\ntest\nThe parser will try to read additional 94 unallocated bytes after\nthe client buffer.\nThis commit fixes this issue by validating that there are actually enough\nbytes to read. It also limits the amount of data that can be sent by\nthe debugger client to 1M so the client will not be able to explode\nthe memory.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int lpEncodeGetType(unsigned char *ele, uint32_t size, unsigned char *intenc, uint64_t *enclen) {\n int64_t v;\n if (lpStringToInt64((const char*)ele, size, &v)) {\n if (v >= 0 && v <= 127) {\n /* Single byte 0-127 integer. */\n intenc[0] = v;\n *enclen = 1;\n } else if (v >= -4096 && v <= 4095) {\n /* 13 bit integer. */\n if (v < 0) v = ((int64_t)1<<13)+v;\n intenc[0] = (v>>8)|LP_ENCODING_13BIT_INT;\n intenc[1] = v&0xff;\n *enclen = 2;\n } else if (v >= -32768 && v <= 32767) {\n /* 16 bit integer. */\n if (v < 0) v = ((int64_t)1<<16)+v;\n intenc[0] = LP_ENCODING_16BIT_INT;\n intenc[1] = v&0xff;\n intenc[2] = v>>8;\n *enclen = 3;\n } else if (v >= -8388608 && v <= 8388607) {\n /* 24 bit integer. */\n if (v < 0) v = ((int64_t)1<<24)+v;\n intenc[0] = LP_ENCODING_24BIT_INT;\n intenc[1] = v&0xff;\n intenc[2] = (v>>8)&0xff;\n intenc[3] = v>>16;\n *enclen = 4;\n } else if (v >= -2147483648 && v <= 2147483647) {\n /* 32 bit integer. */\n if (v < 0) v = ((int64_t)1<<32)+v;\n intenc[0] = LP_ENCODING_32BIT_INT;\n intenc[1] = v&0xff;\n intenc[2] = (v>>8)&0xff;\n intenc[3] = (v>>16)&0xff;\n intenc[4] = v>>24;\n *enclen = 5;\n } else {\n /* 64 bit integer. */\n uint64_t uv = v;\n intenc[0] = LP_ENCODING_64BIT_INT;\n intenc[1] = uv&0xff;\n intenc[2] = (uv>>8)&0xff;\n intenc[3] = (uv>>16)&0xff;\n intenc[4] = (uv>>24)&0xff;\n intenc[5] = (uv>>32)&0xff;\n intenc[6] = (uv>>40)&0xff;\n intenc[7] = (uv>>48)&0xff;\n intenc[8] = uv>>56;\n *enclen = 9;\n }\n return LP_ENCODING_INT;\n } else {\n if (size < 64) *enclen = 1+size;\n else if (size < 4096) *enclen = 2+size;\n else *enclen = 5+size;\n return LP_ENCODING_STRING;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix ziplist and listpack overflows and truncations (CVE-2021-32627, CVE-2021-32628)\n\n- fix possible heap corruption in ziplist and listpack resulting by trying to\n allocate more than the maximum size of 4GB.\n- prevent ziplist (hash and zset) from reaching size of above 1GB, will be\n converted to HT encoding, that's not a useful size.\n- prevent listpack (stream) from reaching size of above 1GB.\n- XADD will start a new listpack if the new record may cause the previous\n listpack to grow over 1GB.\n- XADD will respond with an error if a single stream record is over 1GB\n- List type (ziplist in quicklist) was truncating strings that were over 4GB,\n now it'll respond with an error.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int streamAppendItem(stream *s, robj **argv, int64_t numfields, streamID *added_id, streamID *use_id) {\n \n /* Generate the new entry ID. */\n streamID id;\n if (use_id)\n id = *use_id;\n else\n streamNextID(&s->last_id,&id);\n\n /* Check that the new ID is greater than the last entry ID\n * or return an error. Automatically generated IDs might\n * overflow (and wrap-around) when incrementing the sequence \n part. */\n if (streamCompareID(&id,&s->last_id) <= 0) return C_ERR;\n\n /* Add the new entry. */\n raxIterator ri;\n raxStart(&ri,s->rax);\n raxSeek(&ri,\"$\",NULL,0);\n\n size_t lp_bytes = 0; /* Total bytes in the tail listpack. */\n unsigned char *lp = NULL; /* Tail listpack pointer. */\n\n /* Get a reference to the tail node listpack. */\n if (raxNext(&ri)) {\n lp = ri.data;\n lp_bytes = lpBytes(lp);\n }\n raxStop(&ri);\n\n /* We have to add the key into the radix tree in lexicographic order,\n * to do so we consider the ID as a single 128 bit number written in\n * big endian, so that the most significant bytes are the first ones. */\n uint64_t rax_key[2]; /* Key in the radix tree containing the listpack.*/\n streamID master_id; /* ID of the master entry in the listpack. */\n\n /* Create a new listpack and radix tree node if needed. Note that when\n * a new listpack is created, we populate it with a \"master entry\". This\n * is just a set of fields that is taken as references in order to compress\n * the stream entries that we'll add inside the listpack.\n *\n * Note that while we use the first added entry fields to create\n * the master entry, the first added entry is NOT represented in the master\n * entry, which is a stand alone object. But of course, the first entry\n * will compress well because it's used as reference.\n *\n * The master entry is composed like in the following example:\n *\n * +-------+---------+------------+---------+--/--+---------+---------+-+\n * | count | deleted | num-fields | field_1 | field_2 | ... | field_N |0|\n * +-------+---------+------------+---------+--/--+---------+---------+-+\n *\n * count and deleted just represent respectively the total number of\n * entries inside the listpack that are valid, and marked as deleted\n * (deleted flag in the entry flags set). So the total number of items\n * actually inside the listpack (both deleted and not) is count+deleted.\n *\n * The real entries will be encoded with an ID that is just the\n * millisecond and sequence difference compared to the key stored at\n * the radix tree node containing the listpack (delta encoding), and\n * if the fields of the entry are the same as the master entry fields, the\n * entry flags will specify this fact and the entry fields and number\n * of fields will be omitted (see later in the code of this function).\n *\n * The \"0\" entry at the end is the same as the 'lp-count' entry in the\n * regular stream entries (see below), and marks the fact that there are\n * no more entries, when we scan the stream from right to left. */\n\n /* First of all, check if we can append to the current macro node or\n * if we need to switch to the next one. 'lp' will be set to NULL if\n * the current node is full. */\n if (lp != NULL) {\n if (server.stream_node_max_bytes &&\n lp_bytes >= server.stream_node_max_bytes)\n {\n lp = NULL;\n } else if (server.stream_node_max_entries) {\n int64_t count = lpGetInteger(lpFirst(lp));\n if (count >= server.stream_node_max_entries) lp = NULL;\n }\n }\n\n int flags = STREAM_ITEM_FLAG_NONE;\n if (lp == NULL || lp_bytes >= server.stream_node_max_bytes) {\n master_id = id;\n streamEncodeID(rax_key,&id);\n /* Create the listpack having the master entry ID and fields. */\n lp = lpNew();\n lp = lpAppendInteger(lp,1); /* One item, the one we are adding. */\n lp = lpAppendInteger(lp,0); /* Zero deleted so far. */\n lp = lpAppendInteger(lp,numfields);\n for (int64_t i = 0; i < numfields; i++) {\n sds field = argv[i*2]->ptr;\n lp = lpAppend(lp,(unsigned char*)field,sdslen(field));\n }\n lp = lpAppendInteger(lp,0); /* Master entry zero terminator. */\n raxInsert(s->rax,(unsigned char*)&rax_key,sizeof(rax_key),lp,NULL);\n /* The first entry we insert, has obviously the same fields of the\n * master entry. */\n flags |= STREAM_ITEM_FLAG_SAMEFIELDS;\n } else {\n serverAssert(ri.key_len == sizeof(rax_key));\n memcpy(rax_key,ri.key,sizeof(rax_key));\n\n /* Read the master ID from the radix tree key. */\n streamDecodeID(rax_key,&master_id);\n unsigned char *lp_ele = lpFirst(lp);\n\n /* Update count and skip the deleted fields. */\n int64_t count = lpGetInteger(lp_ele);\n lp = lpReplaceInteger(lp,&lp_ele,count+1);\n lp_ele = lpNext(lp,lp_ele); /* seek deleted. */\n lp_ele = lpNext(lp,lp_ele); /* seek master entry num fields. */\n\n /* Check if the entry we are adding, have the same fields\n * as the master entry. */\n int64_t master_fields_count = lpGetInteger(lp_ele);\n lp_ele = lpNext(lp,lp_ele);\n if (numfields == master_fields_count) {\n int64_t i;\n for (i = 0; i < master_fields_count; i++) {\n sds field = argv[i*2]->ptr;\n int64_t e_len;\n unsigned char buf[LP_INTBUF_SIZE];\n unsigned char *e = lpGet(lp_ele,&e_len,buf);\n /* Stop if there is a mismatch. */\n if (sdslen(field) != (size_t)e_len ||\n memcmp(e,field,e_len) != 0) break;\n lp_ele = lpNext(lp,lp_ele);\n }\n /* All fields are the same! We can compress the field names\n * setting a single bit in the flags. */\n if (i == master_fields_count) flags |= STREAM_ITEM_FLAG_SAMEFIELDS;\n }\n }\n\n /* Populate the listpack with the new entry. We use the following\n * encoding:\n *\n * +-----+--------+----------+-------+-------+-/-+-------+-------+--------+\n * |flags|entry-id|num-fields|field-1|value-1|...|field-N|value-N|lp-count|\n * +-----+--------+----------+-------+-------+-/-+-------+-------+--------+\n *\n * However if the SAMEFIELD flag is set, we have just to populate\n * the entry with the values, so it becomes:\n *\n * +-----+--------+-------+-/-+-------+--------+\n * |flags|entry-id|value-1|...|value-N|lp-count|\n * +-----+--------+-------+-/-+-------+--------+\n *\n * The entry-id field is actually two separated fields: the ms\n * and seq difference compared to the master entry.\n *\n * The lp-count field is a number that states the number of listpack pieces\n * that compose the entry, so that it's possible to travel the entry\n * in reverse order: we can just start from the end of the listpack, read\n * the entry, and jump back N times to seek the \"flags\" field to read\n * the stream full entry. */\n lp = lpAppendInteger(lp,flags);\n lp = lpAppendInteger(lp,id.ms - master_id.ms);\n lp = lpAppendInteger(lp,id.seq - master_id.seq);\n if (!(flags & STREAM_ITEM_FLAG_SAMEFIELDS))\n lp = lpAppendInteger(lp,numfields);\n for (int64_t i = 0; i < numfields; i++) {\n sds field = argv[i*2]->ptr, value = argv[i*2+1]->ptr;\n if (!(flags & STREAM_ITEM_FLAG_SAMEFIELDS))\n lp = lpAppend(lp,(unsigned char*)field,sdslen(field));\n lp = lpAppend(lp,(unsigned char*)value,sdslen(value));\n }\n /* Compute and store the lp-count field. */\n int64_t lp_count = numfields;\n lp_count += 3; /* Add the 3 fixed fields flags + ms-diff + seq-diff. */\n if (!(flags & STREAM_ITEM_FLAG_SAMEFIELDS)) {\n /* If the item is not compressed, it also has the fields other than\n * the values, and an additional num-fileds field. */\n lp_count += numfields+1;\n }\n lp = lpAppendInteger(lp,lp_count);\n\n /* Insert back into the tree in order to update the listpack pointer. */\n if (ri.data != lp)\n raxInsert(s->rax,(unsigned char*)&rax_key,sizeof(rax_key),lp,NULL);\n s->length++;\n s->last_id = id;\n if (added_id) *added_id = id;\n return C_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Fix ziplist and listpack overflows and truncations (CVE-2021-32627, CVE-2021-32628)\n\n- fix possible heap corruption in ziplist and listpack resulting by trying to\n allocate more than the maximum size of 4GB.\n- prevent ziplist (hash and zset) from reaching size of above 1GB, will be\n converted to HT encoding, that's not a useful size.\n- prevent listpack (stream) from reaching size of above 1GB.\n- XADD will start a new listpack if the new record may cause the previous\n listpack to grow over 1GB.\n- XADD will respond with an error if a single stream record is over 1GB\n- List type (ziplist in quicklist) was truncating strings that were over 4GB,\n now it'll respond with an error.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int detach_capi_ctr(struct capi_ctr *ctr)\n{\n\tint err = 0;\n\n\tmutex_lock(&capi_controller_lock);\n\n\tctr_down(ctr, CAPI_CTR_DETACHED);\n\n\tif (capi_controller[ctr->cnr - 1] != ctr) {\n\t\terr = -EINVAL;\n\t\tgoto unlock_out;\n\t}\n\tcapi_controller[ctr->cnr - 1] = NULL;\n\tncontrollers--;\n\n\tif (ctr->procent)\n\t\tremove_proc_entry(ctr->procfn, NULL);\n\n\tprintk(KERN_NOTICE \"kcapi: controller [%03d]: %s unregistered\\n\",\n\t ctr->cnr, ctr->name);\n\nunlock_out:\n\tmutex_unlock(&capi_controller_lock);\n\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'isdn: cpai: check ctr->cnr to avoid array index out of bound\n\nThe cmtp_add_connection() would add a cmtp session to a controller\nand run a kernel thread to process cmtp.\n\n\t__module_get(THIS_MODULE);\n\tsession->task = kthread_run(cmtp_session, session, \"kcmtpd_ctr_%d\",\n\t\t\t\t\t\t\t\tsession->num);\n\nDuring this process, the kernel thread would call detach_capi_ctr()\nto detach a register controller. if the controller\nwas not attached yet, detach_capi_ctr() would\ntrigger an array-index-out-bounds bug.\n\n[ 46.866069][ T6479] UBSAN: array-index-out-of-bounds in\ndrivers/isdn/capi/kcapi.c:483:21\n[ 46.867196][ T6479] index -1 is out of range for type 'capi_ctr *[32]'\n[ 46.867982][ T6479] CPU: 1 PID: 6479 Comm: kcmtpd_ctr_0 Not tainted\n5.15.0-rc2+ #8\n[ 46.869002][ T6479] Hardware name: QEMU Standard PC (i440FX + PIIX,\n1996), BIOS 1.14.0-2 04/01/2014\n[ 46.870107][ T6479] Call Trace:\n[ 46.870473][ T6479] dump_stack_lvl+0x57/0x7d\n[ 46.870974][ T6479] ubsan_epilogue+0x5/0x40\n[ 46.871458][ T6479] __ubsan_handle_out_of_bounds.cold+0x43/0x48\n[ 46.872135][ T6479] detach_capi_ctr+0x64/0xc0\n[ 46.872639][ T6479] cmtp_session+0x5c8/0x5d0\n[ 46.873131][ T6479] ? __init_waitqueue_head+0x60/0x60\n[ 46.873712][ T6479] ? cmtp_add_msgpart+0x120/0x120\n[ 46.874256][ T6479] kthread+0x147/0x170\n[ 46.874709][ T6479] ? set_kthread_struct+0x40/0x40\n[ 46.875248][ T6479] ret_from_fork+0x1f/0x30\n[ 46.875773][ T6479]\n\nSigned-off-by: Xiaolong Huang \nAcked-by: Arnd Bergmann \nLink: https://lore.kernel.org/r/20211008065830.305057-1-butterflyhuangxx@gmail.com\nSigned-off-by: Jakub Kicinski '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static struct fpm_child_s *fpm_resources_prepare(struct fpm_worker_pool_s *wp) /* {{{ */\n{\n\tstruct fpm_child_s *c;\n\n\tc = fpm_child_alloc();\n\n\tif (!c) {\n\t\tzlog(ZLOG_ERROR, \"[pool %s] unable to malloc new child\", wp->config->name);\n\t\treturn 0;\n\t}\n\n\tc->wp = wp;\n\tc->fd_stdout = -1; c->fd_stderr = -1;\n\n\tif (0 > fpm_stdio_prepare_pipes(c)) {\n\t\tfpm_child_free(c);\n\t\treturn 0;\n\t}\n\n\tif (0 > fpm_scoreboard_proc_alloc(wp->scoreboard, &c->scoreboard_i)) {\n\t\tfpm_stdio_discard_pipes(c);\n\t\tfpm_child_free(c);\n\t\treturn 0;\n\t}\n\n\treturn c;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix bug #81026 (PHP-FPM oob R/W in root process leading to priv escalation)\n\nThe main change is to store scoreboard procs directly to the variable sized\narray rather than indirectly through the pointer.\n\nSigned-off-by: Stanislav Malyshev '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void fpm_worker_pool_cleanup(int which, void *arg) /* {{{ */\n{\n\tstruct fpm_worker_pool_s *wp, *wp_next;\n\n\tfor (wp = fpm_worker_all_pools; wp; wp = wp_next) {\n\t\twp_next = wp->next;\n\t\tfpm_worker_pool_config_free(wp->config);\n\t\tfpm_children_free(wp->children);\n\t\tif ((which & FPM_CLEANUP_CHILD) == 0 && fpm_globals.parent_pid == getpid()) {\n\t\t\tfpm_scoreboard_free(wp->scoreboard);\n\t\t}\n\t\tfpm_worker_pool_free(wp);\n\t}\n\tfpm_worker_all_pools = NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix bug #81026 (PHP-FPM oob R/W in root process leading to priv escalation)\n\nThe main change is to store scoreboard procs directly to the variable sized\narray rather than indirectly through the pointer.\n\nSigned-off-by: Stanislav Malyshev '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ipf_extract_frags_from_batch(struct ipf *ipf, struct dp_packet_batch *pb,\n ovs_be16 dl_type, uint16_t zone, long long now,\n uint32_t hash_basis)\n{\n const size_t pb_cnt = dp_packet_batch_size(pb);\n int pb_idx; /* Index in a packet batch. */\n struct dp_packet *pkt;\n\n DP_PACKET_BATCH_REFILL_FOR_EACH (pb_idx, pb_cnt, pkt, pb) {\n if (OVS_UNLIKELY((dl_type == htons(ETH_TYPE_IP) &&\n ipf_is_valid_v4_frag(ipf, pkt))\n ||\n (dl_type == htons(ETH_TYPE_IPV6) &&\n ipf_is_valid_v6_frag(ipf, pkt)))) {\n\n ovs_mutex_lock(&ipf->ipf_lock);\n if (!ipf_handle_frag(ipf, pkt, dl_type, zone, now, hash_basis)) {\n dp_packet_batch_refill(pb, pkt, pb_idx);\n }\n ovs_mutex_unlock(&ipf->ipf_lock);\n } else {\n dp_packet_batch_refill(pb, pkt, pb_idx);\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'ipf: release unhandled packets from the batch\n\nSince 640d4db788ed (\"ipf: Fix a use-after-free error, ...\") the ipf\nframework unconditionally allocates a new dp_packet to track\nindividual fragments. This prevents a use-after-free. However, an\nadditional issue was present - even when the packet buffer is cloned,\nif the ip fragment handling code keeps it, the original buffer is\nleaked during the refill loop. Even in the original processing code,\nthe hardcoded dnsteal branches would always leak a packet buffer from\nthe refill loop.\n\nThis can be confirmed with valgrind:\n\n==717566== 16,672 (4,480 direct, 12,192 indirect) bytes in 8 blocks are definitely lost in loss record 390 of 390\n==717566== at 0x484086F: malloc (vg_replace_malloc.c:380)\n==717566== by 0x537BFD: xmalloc__ (util.c:137)\n==717566== by 0x537BFD: xmalloc (util.c:172)\n==717566== by 0x46DDD4: dp_packet_new (dp-packet.c:153)\n==717566== by 0x46DDD4: dp_packet_new_with_headroom (dp-packet.c:163)\n==717566== by 0x550AA6: netdev_linux_batch_rxq_recv_sock.constprop.0 (netdev-linux.c:1262)\n==717566== by 0x5512AF: netdev_linux_rxq_recv (netdev-linux.c:1511)\n==717566== by 0x4AB7E0: netdev_rxq_recv (netdev.c:727)\n==717566== by 0x47F00D: dp_netdev_process_rxq_port (dpif-netdev.c:4699)\n==717566== by 0x47FD13: dpif_netdev_run (dpif-netdev.c:5957)\n==717566== by 0x4331D2: type_run (ofproto-dpif.c:370)\n==717566== by 0x41DFD8: ofproto_type_run (ofproto.c:1768)\n==717566== by 0x40A7FB: bridge_run__ (bridge.c:3245)\n==717566== by 0x411269: bridge_run (bridge.c:3310)\n==717566== by 0x406E6C: main (ovs-vswitchd.c:127)\n\nThe fix is to delete the original packet when it isn't able to be\nreinserted into the packet batch. Subsequent valgrind runs show that\nthe packets are not leaked from the batch any longer.\n\nFixes: 640d4db788ed (\"ipf: Fix a use-after-free error, and remove the 'do_not_steal' flag.\")\nFixes: 4ea96698f667 (\"Userspace datapath: Add fragmentation handling.\")\nReported-by: Wan Junjie \nReported-at: https://github.com/openvswitch/ovs-issues/issues/226\nSigned-off-by: Aaron Conole \nReviewed-by: David Marchand \nTested-by: Wan Junjie \nSigned-off-by: Alin-Gabriel Serdean '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void desc_read_cb(struct gatt_db_attribute *attrib,\n\t\t\t\t\tunsigned int id, uint16_t offset,\n\t\t\t\t\tuint8_t opcode, struct bt_att *att,\n\t\t\t\t\tvoid *user_data)\n{\n\tstruct external_desc *desc = user_data;\n\tstruct btd_device *device;\n\n\tif (desc->attrib != attrib) {\n\t\terror(\"Read callback called with incorrect attribute\");\n\t\tgoto fail;\n\t}\n\n\tdevice = att_get_device(att);\n\tif (!device) {\n\t\terror(\"Unable to find device object\");\n\t\tgoto fail;\n\t}\n\n\tif (send_read(device, attrib, desc->proxy, desc->pending_reads, id,\n\t\t\t\t\toffset, bt_att_get_link_type(att)))\n\t\treturn;\n\nfail:\n\tgatt_db_attribute_read_result(attrib, id, BT_ATT_ERROR_UNLIKELY,\n\t\t\t\t\t\t\t\tNULL, 0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'gatt: Fix not cleaning up when disconnected\n\nThere is a current use after free possible on a gatt server if a client\ndisconnects while a WriteValue call is being processed with dbus.\n\nThis patch includes the addition of a pending disconnect callback to handle\ncleanup better if a disconnect occurs during a write, an acquire write\nor read operation using bt_att_register_disconnect with the cb.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: suggest_trie_walk(\n suginfo_T\t*su,\n langp_T\t*lp,\n char_u\t*fword,\n int\t\tsoundfold)\n{\n char_u\ttword[MAXWLEN];\t // good word collected so far\n trystate_T\tstack[MAXWLEN];\n char_u\tpreword[MAXWLEN * 3]; // word found with proper case;\n\t\t\t\t // concatenation of prefix compound\n\t\t\t\t // words and split word. NUL terminated\n\t\t\t\t // when going deeper but not when coming\n\t\t\t\t // back.\n char_u\tcompflags[MAXWLEN];\t// compound flags, one for each word\n trystate_T\t*sp;\n int\t\tnewscore;\n int\t\tscore;\n char_u\t*byts, *fbyts, *pbyts;\n idx_T\t*idxs, *fidxs, *pidxs;\n int\t\tdepth;\n int\t\tc, c2, c3;\n int\t\tn = 0;\n int\t\tflags;\n garray_T\t*gap;\n idx_T\tarridx;\n int\t\tlen;\n char_u\t*p;\n fromto_T\t*ftp;\n int\t\tfl = 0, tl;\n int\t\trepextra = 0;\t // extra bytes in fword[] from REP item\n slang_T\t*slang = lp->lp_slang;\n int\t\tfword_ends;\n int\t\tgoodword_ends;\n#ifdef DEBUG_TRIEWALK\n // Stores the name of the change made at each level.\n char_u\tchangename[MAXWLEN][80];\n#endif\n int\t\tbreakcheckcount = 1000;\n int\t\tcompound_ok;\n\n // Go through the whole case-fold tree, try changes at each node.\n // \"tword[]\" contains the word collected from nodes in the tree.\n // \"fword[]\" the word we are trying to match with (initially the bad\n // word).\n depth = 0;\n sp = &stack[0];\n CLEAR_POINTER(sp);\n sp->ts_curi = 1;\n\n if (soundfold)\n {\n\t// Going through the soundfold tree.\n\tbyts = fbyts = slang->sl_sbyts;\n\tidxs = fidxs = slang->sl_sidxs;\n\tpbyts = NULL;\n\tpidxs = NULL;\n\tsp->ts_prefixdepth = PFD_NOPREFIX;\n\tsp->ts_state = STATE_START;\n }\n else\n {\n\t// When there are postponed prefixes we need to use these first. At\n\t// the end of the prefix we continue in the case-fold tree.\n\tfbyts = slang->sl_fbyts;\n\tfidxs = slang->sl_fidxs;\n\tpbyts = slang->sl_pbyts;\n\tpidxs = slang->sl_pidxs;\n\tif (pbyts != NULL)\n\t{\n\t byts = pbyts;\n\t idxs = pidxs;\n\t sp->ts_prefixdepth = PFD_PREFIXTREE;\n\t sp->ts_state = STATE_NOPREFIX;\t// try without prefix first\n\t}\n\telse\n\t{\n\t byts = fbyts;\n\t idxs = fidxs;\n\t sp->ts_prefixdepth = PFD_NOPREFIX;\n\t sp->ts_state = STATE_START;\n\t}\n }\n\n // Loop to find all suggestions. At each round we either:\n // - For the current state try one operation, advance \"ts_curi\",\n // increase \"depth\".\n // - When a state is done go to the next, set \"ts_state\".\n // - When all states are tried decrease \"depth\".\n while (depth >= 0 && !got_int)\n {\n\tsp = &stack[depth];\n\tswitch (sp->ts_state)\n\t{\n\tcase STATE_START:\n\tcase STATE_NOPREFIX:\n\t // Start of node: Deal with NUL bytes, which means\n\t // tword[] may end here.\n\t arridx = sp->ts_arridx;\t // current node in the tree\n\t len = byts[arridx];\t\t // bytes in this node\n\t arridx += sp->ts_curi;\t // index of current byte\n\n\t if (sp->ts_prefixdepth == PFD_PREFIXTREE)\n\t {\n\t\t// Skip over the NUL bytes, we use them later.\n\t\tfor (n = 0; n < len && byts[arridx + n] == 0; ++n)\n\t\t ;\n\t\tsp->ts_curi += n;\n\n\t\t// Always past NUL bytes now.\n\t\tn = (int)sp->ts_state;\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_ENDNUL;\n\t\tsp->ts_save_badflags = su->su_badflags;\n\n\t\t// At end of a prefix or at start of prefixtree: check for\n\t\t// following word.\n\t\tif (byts[arridx] == 0 || n == (int)STATE_NOPREFIX)\n\t\t{\n\t\t // Set su->su_badflags to the caps type at this position.\n\t\t // Use the caps type until here for the prefix itself.\n\t\t if (has_mbyte)\n\t\t\tn = nofold_len(fword, sp->ts_fidx, su->su_badptr);\n\t\t else\n\t\t\tn = sp->ts_fidx;\n\t\t flags = badword_captype(su->su_badptr, su->su_badptr + n);\n\t\t su->su_badflags = badword_captype(su->su_badptr + n,\n\t\t\t\t\t su->su_badptr + su->su_badlen);\n#ifdef DEBUG_TRIEWALK\n\t\t sprintf(changename[depth], \"prefix\");\n#endif\n\t\t go_deeper(stack, depth, 0);\n\t\t ++depth;\n\t\t sp = &stack[depth];\n\t\t sp->ts_prefixdepth = depth - 1;\n\t\t byts = fbyts;\n\t\t idxs = fidxs;\n\t\t sp->ts_arridx = 0;\n\n\t\t // Move the prefix to preword[] with the right case\n\t\t // and make find_keepcap_word() works.\n\t\t tword[sp->ts_twordlen] = NUL;\n\t\t make_case_word(tword + sp->ts_splitoff,\n\t\t\t\t\t preword + sp->ts_prewordlen, flags);\n\t\t sp->ts_prewordlen = (char_u)STRLEN(preword);\n\t\t sp->ts_splitoff = sp->ts_twordlen;\n\t\t}\n\t\tbreak;\n\t }\n\n\t if (sp->ts_curi > len || byts[arridx] != 0)\n\t {\n\t\t// Past bytes in node and/or past NUL bytes.\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_ENDNUL;\n\t\tsp->ts_save_badflags = su->su_badflags;\n\t\tbreak;\n\t }\n\n\t // End of word in tree.\n\t ++sp->ts_curi;\t\t// eat one NUL byte\n\n\t flags = (int)idxs[arridx];\n\n\t // Skip words with the NOSUGGEST flag.\n\t if (flags & WF_NOSUGGEST)\n\t\tbreak;\n\n\t fword_ends = (fword[sp->ts_fidx] == NUL\n\t\t\t || (soundfold\n\t\t\t ? VIM_ISWHITE(fword[sp->ts_fidx])\n\t\t\t : !spell_iswordp(fword + sp->ts_fidx, curwin)));\n\t tword[sp->ts_twordlen] = NUL;\n\n\t if (sp->ts_prefixdepth <= PFD_NOTSPECIAL\n\t\t\t\t\t&& (sp->ts_flags & TSF_PREFIXOK) == 0\n\t\t\t\t\t&& pbyts != NULL)\n\t {\n\t\t// There was a prefix before the word. Check that the prefix\n\t\t// can be used with this word.\n\t\t// Count the length of the NULs in the prefix. If there are\n\t\t// none this must be the first try without a prefix.\n\t\tn = stack[sp->ts_prefixdepth].ts_arridx;\n\t\tlen = pbyts[n++];\n\t\tfor (c = 0; c < len && pbyts[n + c] == 0; ++c)\n\t\t ;\n\t\tif (c > 0)\n\t\t{\n\t\t c = valid_word_prefix(c, n, flags,\n\t\t\t\t tword + sp->ts_splitoff, slang, FALSE);\n\t\t if (c == 0)\n\t\t\tbreak;\n\n\t\t // Use the WF_RARE flag for a rare prefix.\n\t\t if (c & WF_RAREPFX)\n\t\t\tflags |= WF_RARE;\n\n\t\t // Tricky: when checking for both prefix and compounding\n\t\t // we run into the prefix flag first.\n\t\t // Remember that it's OK, so that we accept the prefix\n\t\t // when arriving at a compound flag.\n\t\t sp->ts_flags |= TSF_PREFIXOK;\n\t\t}\n\t }\n\n\t // Check NEEDCOMPOUND: can't use word without compounding. Do try\n\t // appending another compound word below.\n\t if (sp->ts_complen == sp->ts_compsplit && fword_ends\n\t\t\t\t\t\t && (flags & WF_NEEDCOMP))\n\t\tgoodword_ends = FALSE;\n\t else\n\t\tgoodword_ends = TRUE;\n\n\t p = NULL;\n\t compound_ok = TRUE;\n\t if (sp->ts_complen > sp->ts_compsplit)\n\t {\n\t\tif (slang->sl_nobreak)\n\t\t{\n\t\t // There was a word before this word. When there was no\n\t\t // change in this word (it was correct) add the first word\n\t\t // as a suggestion. If this word was corrected too, we\n\t\t // need to check if a correct word follows.\n\t\t if (sp->ts_fidx - sp->ts_splitfidx\n\t\t\t\t\t == sp->ts_twordlen - sp->ts_splitoff\n\t\t\t && STRNCMP(fword + sp->ts_splitfidx,\n\t\t\t\t\ttword + sp->ts_splitoff,\n\t\t\t\t\t sp->ts_fidx - sp->ts_splitfidx) == 0)\n\t\t {\n\t\t\tpreword[sp->ts_prewordlen] = NUL;\n\t\t\tnewscore = score_wordcount_adj(slang, sp->ts_score,\n\t\t\t\t\t\t preword + sp->ts_prewordlen,\n\t\t\t\t\t\t sp->ts_prewordlen > 0);\n\t\t\t// Add the suggestion if the score isn't too bad.\n\t\t\tif (newscore <= su->su_maxscore)\n\t\t\t add_suggestion(su, &su->su_ga, preword,\n\t\t\t\t sp->ts_splitfidx - repextra,\n\t\t\t\t newscore, 0, FALSE,\n\t\t\t\t lp->lp_sallang, FALSE);\n\t\t\tbreak;\n\t\t }\n\t\t}\n\t\telse\n\t\t{\n\t\t // There was a compound word before this word. If this\n\t\t // word does not support compounding then give up\n\t\t // (splitting is tried for the word without compound\n\t\t // flag).\n\t\t if (((unsigned)flags >> 24) == 0\n\t\t\t || sp->ts_twordlen - sp->ts_splitoff\n\t\t\t\t\t\t < slang->sl_compminlen)\n\t\t\tbreak;\n\t\t // For multi-byte chars check character length against\n\t\t // COMPOUNDMIN.\n\t\t if (has_mbyte\n\t\t\t && slang->sl_compminlen > 0\n\t\t\t && mb_charlen(tword + sp->ts_splitoff)\n\t\t\t\t\t\t < slang->sl_compminlen)\n\t\t\tbreak;\n\n\t\t compflags[sp->ts_complen] = ((unsigned)flags >> 24);\n\t\t compflags[sp->ts_complen + 1] = NUL;\n\t\t vim_strncpy(preword + sp->ts_prewordlen,\n\t\t\t tword + sp->ts_splitoff,\n\t\t\t sp->ts_twordlen - sp->ts_splitoff);\n\n\t\t // Verify CHECKCOMPOUNDPATTERN rules.\n\t\t if (match_checkcompoundpattern(preword, sp->ts_prewordlen,\n\t\t\t\t\t\t\t &slang->sl_comppat))\n\t\t\tcompound_ok = FALSE;\n\n\t\t if (compound_ok)\n\t\t {\n\t\t\tp = preword;\n\t\t\twhile (*skiptowhite(p) != NUL)\n\t\t\t p = skipwhite(skiptowhite(p));\n\t\t\tif (fword_ends && !can_compound(slang, p,\n\t\t\t\t\t\tcompflags + sp->ts_compsplit))\n\t\t\t // Compound is not allowed. But it may still be\n\t\t\t // possible if we add another (short) word.\n\t\t\t compound_ok = FALSE;\n\t\t }\n\n\t\t // Get pointer to last char of previous word.\n\t\t p = preword + sp->ts_prewordlen;\n\t\t MB_PTR_BACK(preword, p);\n\t\t}\n\t }\n\n\t // Form the word with proper case in preword.\n\t // If there is a word from a previous split, append.\n\t // For the soundfold tree don't change the case, simply append.\n\t if (soundfold)\n\t\tSTRCPY(preword + sp->ts_prewordlen, tword + sp->ts_splitoff);\n\t else if (flags & WF_KEEPCAP)\n\t\t// Must find the word in the keep-case tree.\n\t\tfind_keepcap_word(slang, tword + sp->ts_splitoff,\n\t\t\t\t\t\t preword + sp->ts_prewordlen);\n\t else\n\t {\n\t\t// Include badflags: If the badword is onecap or allcap\n\t\t// use that for the goodword too. But if the badword is\n\t\t// allcap and it's only one char long use onecap.\n\t\tc = su->su_badflags;\n\t\tif ((c & WF_ALLCAP)\n\t\t\t&& su->su_badlen == (*mb_ptr2len)(su->su_badptr))\n\t\t c = WF_ONECAP;\n\t\tc |= flags;\n\n\t\t// When appending a compound word after a word character don't\n\t\t// use Onecap.\n\t\tif (p != NULL && spell_iswordp_nmw(p, curwin))\n\t\t c &= ~WF_ONECAP;\n\t\tmake_case_word(tword + sp->ts_splitoff,\n\t\t\t\t\t preword + sp->ts_prewordlen, c);\n\t }\n\n\t if (!soundfold)\n\t {\n\t\t// Don't use a banned word. It may appear again as a good\n\t\t// word, thus remember it.\n\t\tif (flags & WF_BANNED)\n\t\t{\n\t\t add_banned(su, preword + sp->ts_prewordlen);\n\t\t break;\n\t\t}\n\t\tif ((sp->ts_complen == sp->ts_compsplit\n\t\t\t && WAS_BANNED(su, preword + sp->ts_prewordlen))\n\t\t\t\t\t\t || WAS_BANNED(su, preword))\n\t\t{\n\t\t if (slang->sl_compprog == NULL)\n\t\t\tbreak;\n\t\t // the word so far was banned but we may try compounding\n\t\t goodword_ends = FALSE;\n\t\t}\n\t }\n\n\t newscore = 0;\n\t if (!soundfold)\t// soundfold words don't have flags\n\t {\n\t\tif ((flags & WF_REGION)\n\t\t\t && (((unsigned)flags >> 16) & lp->lp_region) == 0)\n\t\t newscore += SCORE_REGION;\n\t\tif (flags & WF_RARE)\n\t\t newscore += SCORE_RARE;\n\n\t\tif (!spell_valid_case(su->su_badflags,\n\t\t\t\t captype(preword + sp->ts_prewordlen, NULL)))\n\t\t newscore += SCORE_ICASE;\n\t }\n\n\t // TODO: how about splitting in the soundfold tree?\n\t if (fword_ends\n\t\t && goodword_ends\n\t\t && sp->ts_fidx >= sp->ts_fidxtry\n\t\t && compound_ok)\n\t {\n\t\t// The badword also ends: add suggestions.\n#ifdef DEBUG_TRIEWALK\n\t\tif (soundfold && STRCMP(preword, \"smwrd\") == 0)\n\t\t{\n\t\t int\t j;\n\n\t\t // print the stack of changes that brought us here\n\t\t smsg(\"------ %s -------\", fword);\n\t\t for (j = 0; j < depth; ++j)\n\t\t\tsmsg(\"%s\", changename[j]);\n\t\t}\n#endif\n\t\tif (soundfold)\n\t\t{\n\t\t // For soundfolded words we need to find the original\n\t\t // words, the edit distance and then add them.\n\t\t add_sound_suggest(su, preword, sp->ts_score, lp);\n\t\t}\n\t\telse if (sp->ts_fidx > 0)\n\t\t{\n\t\t // Give a penalty when changing non-word char to word\n\t\t // char, e.g., \"thes,\" -> \"these\".\n\t\t p = fword + sp->ts_fidx;\n\t\t MB_PTR_BACK(fword, p);\n\t\t if (!spell_iswordp(p, curwin))\n\t\t {\n\t\t\tp = preword + STRLEN(preword);\n\t\t\tMB_PTR_BACK(preword, p);\n\t\t\tif (spell_iswordp(p, curwin))\n\t\t\t newscore += SCORE_NONWORD;\n\t\t }\n\n\t\t // Give a bonus to words seen before.\n\t\t score = score_wordcount_adj(slang,\n\t\t\t\t\t\tsp->ts_score + newscore,\n\t\t\t\t\t\tpreword + sp->ts_prewordlen,\n\t\t\t\t\t\tsp->ts_prewordlen > 0);\n\n\t\t // Add the suggestion if the score isn't too bad.\n\t\t if (score <= su->su_maxscore)\n\t\t {\n\t\t\tadd_suggestion(su, &su->su_ga, preword,\n\t\t\t\t sp->ts_fidx - repextra,\n\t\t\t\t score, 0, FALSE, lp->lp_sallang, FALSE);\n\n\t\t\tif (su->su_badflags & WF_MIXCAP)\n\t\t\t{\n\t\t\t // We really don't know if the word should be\n\t\t\t // upper or lower case, add both.\n\t\t\t c = captype(preword, NULL);\n\t\t\t if (c == 0 || c == WF_ALLCAP)\n\t\t\t {\n\t\t\t\tmake_case_word(tword + sp->ts_splitoff,\n\t\t\t\t\t preword + sp->ts_prewordlen,\n\t\t\t\t\t\t c == 0 ? WF_ALLCAP : 0);\n\n\t\t\t\tadd_suggestion(su, &su->su_ga, preword,\n\t\t\t\t\tsp->ts_fidx - repextra,\n\t\t\t\t\tscore + SCORE_ICASE, 0, FALSE,\n\t\t\t\t\tlp->lp_sallang, FALSE);\n\t\t\t }\n\t\t\t}\n\t\t }\n\t\t}\n\t }\n\n\t // Try word split and/or compounding.\n\t if ((sp->ts_fidx >= sp->ts_fidxtry || fword_ends)\n\t\t // Don't split halfway a character.\n\t\t && (!has_mbyte || sp->ts_tcharlen == 0))\n\t {\n\t\tint\ttry_compound;\n\t\tint\ttry_split;\n\n\t\t// If past the end of the bad word don't try a split.\n\t\t// Otherwise try changing the next word. E.g., find\n\t\t// suggestions for \"the the\" where the second \"the\" is\n\t\t// different. It's done like a split.\n\t\t// TODO: word split for soundfold words\n\t\ttry_split = (sp->ts_fidx - repextra < su->su_badlen)\n\t\t\t\t\t\t\t\t&& !soundfold;\n\n\t\t// Get here in several situations:\n\t\t// 1. The word in the tree ends:\n\t\t// If the word allows compounding try that. Otherwise try\n\t\t// a split by inserting a space. For both check that a\n\t\t// valid words starts at fword[sp->ts_fidx].\n\t\t// For NOBREAK do like compounding to be able to check if\n\t\t// the next word is valid.\n\t\t// 2. The badword does end, but it was due to a change (e.g.,\n\t\t// a swap). No need to split, but do check that the\n\t\t// following word is valid.\n\t\t// 3. The badword and the word in the tree end. It may still\n\t\t// be possible to compound another (short) word.\n\t\ttry_compound = FALSE;\n\t\tif (!soundfold\n\t\t\t&& !slang->sl_nocompoundsugs\n\t\t\t&& slang->sl_compprog != NULL\n\t\t\t&& ((unsigned)flags >> 24) != 0\n\t\t\t&& sp->ts_twordlen - sp->ts_splitoff\n\t\t\t\t\t\t >= slang->sl_compminlen\n\t\t\t&& (!has_mbyte\n\t\t\t || slang->sl_compminlen == 0\n\t\t\t || mb_charlen(tword + sp->ts_splitoff)\n\t\t\t\t\t\t >= slang->sl_compminlen)\n\t\t\t&& (slang->sl_compsylmax < MAXWLEN\n\t\t\t || sp->ts_complen + 1 - sp->ts_compsplit\n\t\t\t\t\t\t\t < slang->sl_compmax)\n\t\t\t&& (can_be_compound(sp, slang,\n\t\t\t\t\t compflags, ((unsigned)flags >> 24))))\n\n\t\t{\n\t\t try_compound = TRUE;\n\t\t compflags[sp->ts_complen] = ((unsigned)flags >> 24);\n\t\t compflags[sp->ts_complen + 1] = NUL;\n\t\t}\n\n\t\t// For NOBREAK we never try splitting, it won't make any word\n\t\t// valid.\n\t\tif (slang->sl_nobreak && !slang->sl_nocompoundsugs)\n\t\t try_compound = TRUE;\n\n\t\t// If we could add a compound word, and it's also possible to\n\t\t// split at this point, do the split first and set\n\t\t// TSF_DIDSPLIT to avoid doing it again.\n\t\telse if (!fword_ends\n\t\t\t&& try_compound\n\t\t\t&& (sp->ts_flags & TSF_DIDSPLIT) == 0)\n\t\t{\n\t\t try_compound = FALSE;\n\t\t sp->ts_flags |= TSF_DIDSPLIT;\n\t\t --sp->ts_curi;\t // do the same NUL again\n\t\t compflags[sp->ts_complen] = NUL;\n\t\t}\n\t\telse\n\t\t sp->ts_flags &= ~TSF_DIDSPLIT;\n\n\t\tif (try_split || try_compound)\n\t\t{\n\t\t if (!try_compound && (!fword_ends || !goodword_ends))\n\t\t {\n\t\t\t// If we're going to split need to check that the\n\t\t\t// words so far are valid for compounding. If there\n\t\t\t// is only one word it must not have the NEEDCOMPOUND\n\t\t\t// flag.\n\t\t\tif (sp->ts_complen == sp->ts_compsplit\n\t\t\t\t\t\t && (flags & WF_NEEDCOMP))\n\t\t\t break;\n\t\t\tp = preword;\n\t\t\twhile (*skiptowhite(p) != NUL)\n\t\t\t p = skipwhite(skiptowhite(p));\n\t\t\tif (sp->ts_complen > sp->ts_compsplit\n\t\t\t\t&& !can_compound(slang, p,\n\t\t\t\t\t\tcompflags + sp->ts_compsplit))\n\t\t\t break;\n\n\t\t\tif (slang->sl_nosplitsugs)\n\t\t\t newscore += SCORE_SPLIT_NO;\n\t\t\telse\n\t\t\t newscore += SCORE_SPLIT;\n\n\t\t\t// Give a bonus to words seen before.\n\t\t\tnewscore = score_wordcount_adj(slang, newscore,\n\t\t\t\t\t preword + sp->ts_prewordlen, TRUE);\n\t\t }\n\n\t\t if (TRY_DEEPER(su, stack, depth, newscore))\n\t\t {\n\t\t\tgo_deeper(stack, depth, newscore);\n#ifdef DEBUG_TRIEWALK\n\t\t\tif (!try_compound && !fword_ends)\n\t\t\t sprintf(changename[depth], \"%.*s-%s: split\",\n\t\t\t\t sp->ts_twordlen, tword, fword + sp->ts_fidx);\n\t\t\telse\n\t\t\t sprintf(changename[depth], \"%.*s-%s: compound\",\n\t\t\t\t sp->ts_twordlen, tword, fword + sp->ts_fidx);\n#endif\n\t\t\t// Save things to be restored at STATE_SPLITUNDO.\n\t\t\tsp->ts_save_badflags = su->su_badflags;\n\t\t\tPROF_STORE(sp->ts_state)\n\t\t\tsp->ts_state = STATE_SPLITUNDO;\n\n\t\t\t++depth;\n\t\t\tsp = &stack[depth];\n\n\t\t\t// Append a space to preword when splitting.\n\t\t\tif (!try_compound && !fword_ends)\n\t\t\t STRCAT(preword, \" \");\n\t\t\tsp->ts_prewordlen = (char_u)STRLEN(preword);\n\t\t\tsp->ts_splitoff = sp->ts_twordlen;\n\t\t\tsp->ts_splitfidx = sp->ts_fidx;\n\n\t\t\t// If the badword has a non-word character at this\n\t\t\t// position skip it. That means replacing the\n\t\t\t// non-word character with a space. Always skip a\n\t\t\t// character when the word ends. But only when the\n\t\t\t// good word can end.\n\t\t\tif (((!try_compound && !spell_iswordp_nmw(fword\n\t\t\t\t\t\t\t + sp->ts_fidx,\n\t\t\t\t\t\t\t curwin))\n\t\t\t\t || fword_ends)\n\t\t\t\t&& fword[sp->ts_fidx] != NUL\n\t\t\t\t&& goodword_ends)\n\t\t\t{\n\t\t\t int\t l;\n\n\t\t\t l = mb_ptr2len(fword + sp->ts_fidx);\n\t\t\t if (fword_ends)\n\t\t\t {\n\t\t\t\t// Copy the skipped character to preword.\n\t\t\t\tmch_memmove(preword + sp->ts_prewordlen,\n\t\t\t\t\t\t fword + sp->ts_fidx, l);\n\t\t\t\tsp->ts_prewordlen += l;\n\t\t\t\tpreword[sp->ts_prewordlen] = NUL;\n\t\t\t }\n\t\t\t else\n\t\t\t\tsp->ts_score -= SCORE_SPLIT - SCORE_SUBST;\n\t\t\t sp->ts_fidx += l;\n\t\t\t}\n\n\t\t\t// When compounding include compound flag in\n\t\t\t// compflags[] (already set above). When splitting we\n\t\t\t// may start compounding over again.\n\t\t\tif (try_compound)\n\t\t\t ++sp->ts_complen;\n\t\t\telse\n\t\t\t sp->ts_compsplit = sp->ts_complen;\n\t\t\tsp->ts_prefixdepth = PFD_NOPREFIX;\n\n\t\t\t// set su->su_badflags to the caps type at this\n\t\t\t// position\n\t\t\tif (has_mbyte)\n\t\t\t n = nofold_len(fword, sp->ts_fidx, su->su_badptr);\n\t\t\telse\n\t\t\t n = sp->ts_fidx;\n\t\t\tsu->su_badflags = badword_captype(su->su_badptr + n,\n\t\t\t\t\t su->su_badptr + su->su_badlen);\n\n\t\t\t// Restart at top of the tree.\n\t\t\tsp->ts_arridx = 0;\n\n\t\t\t// If there are postponed prefixes, try these too.\n\t\t\tif (pbyts != NULL)\n\t\t\t{\n\t\t\t byts = pbyts;\n\t\t\t idxs = pidxs;\n\t\t\t sp->ts_prefixdepth = PFD_PREFIXTREE;\n\t\t\t PROF_STORE(sp->ts_state)\n\t\t\t sp->ts_state = STATE_NOPREFIX;\n\t\t\t}\n\t\t }\n\t\t}\n\t }\n\t break;\n\n\tcase STATE_SPLITUNDO:\n\t // Undo the changes done for word split or compound word.\n\t su->su_badflags = sp->ts_save_badflags;\n\n\t // Continue looking for NUL bytes.\n\t PROF_STORE(sp->ts_state)\n\t sp->ts_state = STATE_START;\n\n\t // In case we went into the prefix tree.\n\t byts = fbyts;\n\t idxs = fidxs;\n\t break;\n\n\tcase STATE_ENDNUL:\n\t // Past the NUL bytes in the node.\n\t su->su_badflags = sp->ts_save_badflags;\n\t if (fword[sp->ts_fidx] == NUL && sp->ts_tcharlen == 0)\n\t {\n\t\t// The badword ends, can't use STATE_PLAIN.\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_DEL;\n\t\tbreak;\n\t }\n\t PROF_STORE(sp->ts_state)\n\t sp->ts_state = STATE_PLAIN;\n\t // FALLTHROUGH\n\n\tcase STATE_PLAIN:\n\t // Go over all possible bytes at this node, add each to tword[]\n\t // and use child node. \"ts_curi\" is the index.\n\t arridx = sp->ts_arridx;\n\t if (sp->ts_curi > byts[arridx])\n\t {\n\t\t// Done all bytes at this node, do next state. When still at\n\t\t// already changed bytes skip the other tricks.\n\t\tPROF_STORE(sp->ts_state)\n\t\tif (sp->ts_fidx >= sp->ts_fidxtry)\n\t\t sp->ts_state = STATE_DEL;\n\t\telse\n\t\t sp->ts_state = STATE_FINAL;\n\t }\n\t else\n\t {\n\t\tarridx += sp->ts_curi++;\n\t\tc = byts[arridx];\n\n\t\t// Normal byte, go one level deeper. If it's not equal to the\n\t\t// byte in the bad word adjust the score. But don't even try\n\t\t// when the byte was already changed. And don't try when we\n\t\t// just deleted this byte, accepting it is always cheaper than\n\t\t// delete + substitute.\n\t\tif (c == fword[sp->ts_fidx]\n\t\t\t|| (sp->ts_tcharlen > 0 && sp->ts_isdiff != DIFF_NONE))\n\t\t newscore = 0;\n\t\telse\n\t\t newscore = SCORE_SUBST;\n\t\tif ((newscore == 0\n\t\t\t || (sp->ts_fidx >= sp->ts_fidxtry\n\t\t\t\t&& ((sp->ts_flags & TSF_DIDDEL) == 0\n\t\t\t\t || c != fword[sp->ts_delidx])))\n\t\t\t&& TRY_DEEPER(su, stack, depth, newscore))\n\t\t{\n\t\t go_deeper(stack, depth, newscore);\n#ifdef DEBUG_TRIEWALK\n\t\t if (newscore > 0)\n\t\t\tsprintf(changename[depth], \"%.*s-%s: subst %c to %c\",\n\t\t\t\tsp->ts_twordlen, tword, fword + sp->ts_fidx,\n\t\t\t\tfword[sp->ts_fidx], c);\n\t\t else\n\t\t\tsprintf(changename[depth], \"%.*s-%s: accept %c\",\n\t\t\t\tsp->ts_twordlen, tword, fword + sp->ts_fidx,\n\t\t\t\tfword[sp->ts_fidx]);\n#endif\n\t\t ++depth;\n\t\t sp = &stack[depth];\n\t\t ++sp->ts_fidx;\n\t\t tword[sp->ts_twordlen++] = c;\n\t\t sp->ts_arridx = idxs[arridx];\n\t\t if (newscore == SCORE_SUBST)\n\t\t\tsp->ts_isdiff = DIFF_YES;\n\t\t if (has_mbyte)\n\t\t {\n\t\t\t// Multi-byte characters are a bit complicated to\n\t\t\t// handle: They differ when any of the bytes differ\n\t\t\t// and then their length may also differ.\n\t\t\tif (sp->ts_tcharlen == 0)\n\t\t\t{\n\t\t\t // First byte.\n\t\t\t sp->ts_tcharidx = 0;\n\t\t\t sp->ts_tcharlen = MB_BYTE2LEN(c);\n\t\t\t sp->ts_fcharstart = sp->ts_fidx - 1;\n\t\t\t sp->ts_isdiff = (newscore != 0)\n\t\t\t\t\t\t ? DIFF_YES : DIFF_NONE;\n\t\t\t}\n\t\t\telse if (sp->ts_isdiff == DIFF_INSERT)\n\t\t\t // When inserting trail bytes don't advance in the\n\t\t\t // bad word.\n\t\t\t --sp->ts_fidx;\n\t\t\tif (++sp->ts_tcharidx == sp->ts_tcharlen)\n\t\t\t{\n\t\t\t // Last byte of character.\n\t\t\t if (sp->ts_isdiff == DIFF_YES)\n\t\t\t {\n\t\t\t\t// Correct ts_fidx for the byte length of the\n\t\t\t\t// character (we didn't check that before).\n\t\t\t\tsp->ts_fidx = sp->ts_fcharstart\n\t\t\t\t\t + mb_ptr2len(\n\t\t\t\t\t\t fword + sp->ts_fcharstart);\n\t\t\t\t// For changing a composing character adjust\n\t\t\t\t// the score from SCORE_SUBST to\n\t\t\t\t// SCORE_SUBCOMP.\n\t\t\t\tif (enc_utf8\n\t\t\t\t\t&& utf_iscomposing(\n\t\t\t\t\t utf_ptr2char(tword\n\t\t\t\t\t\t+ sp->ts_twordlen\n\t\t\t\t\t\t\t - sp->ts_tcharlen))\n\t\t\t\t\t&& utf_iscomposing(\n\t\t\t\t\t utf_ptr2char(fword\n\t\t\t\t\t\t\t+ sp->ts_fcharstart)))\n\t\t\t\t sp->ts_score -=\n\t\t\t\t\t\t SCORE_SUBST - SCORE_SUBCOMP;\n\n\t\t\t\t// For a similar character adjust score from\n\t\t\t\t// SCORE_SUBST to SCORE_SIMILAR.\n\t\t\t\telse if (!soundfold\n\t\t\t\t\t&& slang->sl_has_map\n\t\t\t\t\t&& similar_chars(slang,\n\t\t\t\t\t mb_ptr2char(tword\n\t\t\t\t\t\t+ sp->ts_twordlen\n\t\t\t\t\t\t\t - sp->ts_tcharlen),\n\t\t\t\t\t mb_ptr2char(fword\n\t\t\t\t\t\t\t+ sp->ts_fcharstart)))\n\t\t\t\t sp->ts_score -=\n\t\t\t\t\t\t SCORE_SUBST - SCORE_SIMILAR;\n\t\t\t }\n\t\t\t else if (sp->ts_isdiff == DIFF_INSERT\n\t\t\t\t\t && sp->ts_twordlen > sp->ts_tcharlen)\n\t\t\t {\n\t\t\t\tp = tword + sp->ts_twordlen - sp->ts_tcharlen;\n\t\t\t\tc = mb_ptr2char(p);\n\t\t\t\tif (enc_utf8 && utf_iscomposing(c))\n\t\t\t\t{\n\t\t\t\t // Inserting a composing char doesn't\n\t\t\t\t // count that much.\n\t\t\t\t sp->ts_score -= SCORE_INS - SCORE_INSCOMP;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t // If the previous character was the same,\n\t\t\t\t // thus doubling a character, give a bonus\n\t\t\t\t // to the score. Also for the soundfold\n\t\t\t\t // tree (might seem illogical but does\n\t\t\t\t // give better scores).\n\t\t\t\t MB_PTR_BACK(tword, p);\n\t\t\t\t if (c == mb_ptr2char(p))\n\t\t\t\t\tsp->ts_score -= SCORE_INS\n\t\t\t\t\t\t\t - SCORE_INSDUP;\n\t\t\t\t}\n\t\t\t }\n\n\t\t\t // Starting a new char, reset the length.\n\t\t\t sp->ts_tcharlen = 0;\n\t\t\t}\n\t\t }\n\t\t else\n\t\t {\n\t\t\t// If we found a similar char adjust the score.\n\t\t\t// We do this after calling go_deeper() because\n\t\t\t// it's slow.\n\t\t\tif (newscore != 0\n\t\t\t\t&& !soundfold\n\t\t\t\t&& slang->sl_has_map\n\t\t\t\t&& similar_chars(slang,\n\t\t\t\t\t\t c, fword[sp->ts_fidx - 1]))\n\t\t\t sp->ts_score -= SCORE_SUBST - SCORE_SIMILAR;\n\t\t }\n\t\t}\n\t }\n\t break;\n\n\tcase STATE_DEL:\n\t // When past the first byte of a multi-byte char don't try\n\t // delete/insert/swap a character.\n\t if (has_mbyte && sp->ts_tcharlen > 0)\n\t {\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_FINAL;\n\t\tbreak;\n\t }\n\t // Try skipping one character in the bad word (delete it).\n\t PROF_STORE(sp->ts_state)\n\t sp->ts_state = STATE_INS_PREP;\n\t sp->ts_curi = 1;\n\t if (soundfold && sp->ts_fidx == 0 && fword[sp->ts_fidx] == '*')\n\t\t// Deleting a vowel at the start of a word counts less, see\n\t\t// soundalike_score().\n\t\tnewscore = 2 * SCORE_DEL / 3;\n\t else\n\t\tnewscore = SCORE_DEL;\n\t if (fword[sp->ts_fidx] != NUL\n\t\t\t\t && TRY_DEEPER(su, stack, depth, newscore))\n\t {\n\t\tgo_deeper(stack, depth, newscore);\n#ifdef DEBUG_TRIEWALK\n\t\tsprintf(changename[depth], \"%.*s-%s: delete %c\",\n\t\t\tsp->ts_twordlen, tword, fword + sp->ts_fidx,\n\t\t\tfword[sp->ts_fidx]);\n#endif\n\t\t++depth;\n\n\t\t// Remember what character we deleted, so that we can avoid\n\t\t// inserting it again.\n\t\tstack[depth].ts_flags |= TSF_DIDDEL;\n\t\tstack[depth].ts_delidx = sp->ts_fidx;\n\n\t\t// Advance over the character in fword[]. Give a bonus to the\n\t\t// score if the same character is following \"nn\" -> \"n\". It's\n\t\t// a bit illogical for soundfold tree but it does give better\n\t\t// results.\n\t\tif (has_mbyte)\n\t\t{\n\t\t c = mb_ptr2char(fword + sp->ts_fidx);\n\t\t stack[depth].ts_fidx += mb_ptr2len(fword + sp->ts_fidx);\n\t\t if (enc_utf8 && utf_iscomposing(c))\n\t\t\tstack[depth].ts_score -= SCORE_DEL - SCORE_DELCOMP;\n\t\t else if (c == mb_ptr2char(fword + stack[depth].ts_fidx))\n\t\t\tstack[depth].ts_score -= SCORE_DEL - SCORE_DELDUP;\n\t\t}\n\t\telse\n\t\t{\n\t\t ++stack[depth].ts_fidx;\n\t\t if (fword[sp->ts_fidx] == fword[sp->ts_fidx + 1])\n\t\t\tstack[depth].ts_score -= SCORE_DEL - SCORE_DELDUP;\n\t\t}\n\t\tbreak;\n\t }\n\t // FALLTHROUGH\n\n\tcase STATE_INS_PREP:\n\t if (sp->ts_flags & TSF_DIDDEL)\n\t {\n\t\t// If we just deleted a byte then inserting won't make sense,\n\t\t// a substitute is always cheaper.\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_SWAP;\n\t\tbreak;\n\t }\n\n\t // skip over NUL bytes\n\t n = sp->ts_arridx;\n\t for (;;)\n\t {\n\t\tif (sp->ts_curi > byts[n])\n\t\t{\n\t\t // Only NUL bytes at this node, go to next state.\n\t\t PROF_STORE(sp->ts_state)\n\t\t sp->ts_state = STATE_SWAP;\n\t\t break;\n\t\t}\n\t\tif (byts[n + sp->ts_curi] != NUL)\n\t\t{\n\t\t // Found a byte to insert.\n\t\t PROF_STORE(sp->ts_state)\n\t\t sp->ts_state = STATE_INS;\n\t\t break;\n\t\t}\n\t\t++sp->ts_curi;\n\t }\n\t break;\n\n\t // FALLTHROUGH\n\n\tcase STATE_INS:\n\t // Insert one byte. Repeat this for each possible byte at this\n\t // node.\n\t n = sp->ts_arridx;\n\t if (sp->ts_curi > byts[n])\n\t {\n\t\t// Done all bytes at this node, go to next state.\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_SWAP;\n\t\tbreak;\n\t }\n\n\t // Do one more byte at this node, but:\n\t // - Skip NUL bytes.\n\t // - Skip the byte if it's equal to the byte in the word,\n\t // accepting that byte is always better.\n\t n += sp->ts_curi++;\n\t c = byts[n];\n\t if (soundfold && sp->ts_twordlen == 0 && c == '*')\n\t\t// Inserting a vowel at the start of a word counts less,\n\t\t// see soundalike_score().\n\t\tnewscore = 2 * SCORE_INS / 3;\n\t else\n\t\tnewscore = SCORE_INS;\n\t if (c != fword[sp->ts_fidx]\n\t\t\t\t && TRY_DEEPER(su, stack, depth, newscore))\n\t {\n\t\tgo_deeper(stack, depth, newscore);\n#ifdef DEBUG_TRIEWALK\n\t\tsprintf(changename[depth], \"%.*s-%s: insert %c\",\n\t\t\tsp->ts_twordlen, tword, fword + sp->ts_fidx,\n\t\t\tc);\n#endif\n\t\t++depth;\n\t\tsp = &stack[depth];\n\t\ttword[sp->ts_twordlen++] = c;\n\t\tsp->ts_arridx = idxs[n];\n\t\tif (has_mbyte)\n\t\t{\n\t\t fl = MB_BYTE2LEN(c);\n\t\t if (fl > 1)\n\t\t {\n\t\t\t// There are following bytes for the same character.\n\t\t\t// We must find all bytes before trying\n\t\t\t// delete/insert/swap/etc.\n\t\t\tsp->ts_tcharlen = fl;\n\t\t\tsp->ts_tcharidx = 1;\n\t\t\tsp->ts_isdiff = DIFF_INSERT;\n\t\t }\n\t\t}\n\t\telse\n\t\t fl = 1;\n\t\tif (fl == 1)\n\t\t{\n\t\t // If the previous character was the same, thus doubling a\n\t\t // character, give a bonus to the score. Also for\n\t\t // soundfold words (illogical but does give a better\n\t\t // score).\n\t\t if (sp->ts_twordlen >= 2\n\t\t\t\t\t && tword[sp->ts_twordlen - 2] == c)\n\t\t\tsp->ts_score -= SCORE_INS - SCORE_INSDUP;\n\t\t}\n\t }\n\t break;\n\n\tcase STATE_SWAP:\n\t // Swap two bytes in the bad word: \"12\" -> \"21\".\n\t // We change \"fword\" here, it's changed back afterwards at\n\t // STATE_UNSWAP.\n\t p = fword + sp->ts_fidx;\n\t c = *p;\n\t if (c == NUL)\n\t {\n\t\t// End of word, can't swap or replace.\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_FINAL;\n\t\tbreak;\n\t }\n\n\t // Don't swap if the first character is not a word character.\n\t // SWAP3 etc. also don't make sense then.\n\t if (!soundfold && !spell_iswordp(p, curwin))\n\t {\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_REP_INI;\n\t\tbreak;\n\t }\n\n\t if (has_mbyte)\n\t {\n\t\tn = MB_CPTR2LEN(p);\n\t\tc = mb_ptr2char(p);\n\t\tif (p[n] == NUL)\n\t\t c2 = NUL;\n\t\telse if (!soundfold && !spell_iswordp(p + n, curwin))\n\t\t c2 = c; // don't swap non-word char\n\t\telse\n\t\t c2 = mb_ptr2char(p + n);\n\t }\n\t else\n\t {\n\t\tif (p[1] == NUL)\n\t\t c2 = NUL;\n\t\telse if (!soundfold && !spell_iswordp(p + 1, curwin))\n\t\t c2 = c; // don't swap non-word char\n\t\telse\n\t\t c2 = p[1];\n\t }\n\n\t // When the second character is NUL we can't swap.\n\t if (c2 == NUL)\n\t {\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_REP_INI;\n\t\tbreak;\n\t }\n\n\t // When characters are identical, swap won't do anything.\n\t // Also get here if the second char is not a word character.\n\t if (c == c2)\n\t {\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_SWAP3;\n\t\tbreak;\n\t }\n\t if (c2 != NUL && TRY_DEEPER(su, stack, depth, SCORE_SWAP))\n\t {\n\t\tgo_deeper(stack, depth, SCORE_SWAP);\n#ifdef DEBUG_TRIEWALK\n\t\tsprintf(changename[depth], \"%.*s-%s: swap %c and %c\",\n\t\t\tsp->ts_twordlen, tword, fword + sp->ts_fidx,\n\t\t\tc, c2);\n#endif\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_UNSWAP;\n\t\t++depth;\n\t\tif (has_mbyte)\n\t\t{\n\t\t fl = mb_char2len(c2);\n\t\t mch_memmove(p, p + n, fl);\n\t\t mb_char2bytes(c, p + fl);\n\t\t stack[depth].ts_fidxtry = sp->ts_fidx + n + fl;\n\t\t}\n\t\telse\n\t\t{\n\t\t p[0] = c2;\n\t\t p[1] = c;\n\t\t stack[depth].ts_fidxtry = sp->ts_fidx + 2;\n\t\t}\n\t }\n\t else\n\t {\n\t\t// If this swap doesn't work then SWAP3 won't either.\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_REP_INI;\n\t }\n\t break;\n\n\tcase STATE_UNSWAP:\n\t // Undo the STATE_SWAP swap: \"21\" -> \"12\".\n\t p = fword + sp->ts_fidx;\n\t if (has_mbyte)\n\t {\n\t\tn = mb_ptr2len(p);\n\t\tc = mb_ptr2char(p + n);\n\t\tmch_memmove(p + mb_ptr2len(p + n), p, n);\n\t\tmb_char2bytes(c, p);\n\t }\n\t else\n\t {\n\t\tc = *p;\n\t\t*p = p[1];\n\t\tp[1] = c;\n\t }\n\t // FALLTHROUGH\n\n\tcase STATE_SWAP3:\n\t // Swap two bytes, skipping one: \"123\" -> \"321\". We change\n\t // \"fword\" here, it's changed back afterwards at STATE_UNSWAP3.\n\t p = fword + sp->ts_fidx;\n\t if (has_mbyte)\n\t {\n\t\tn = MB_CPTR2LEN(p);\n\t\tc = mb_ptr2char(p);\n\t\tfl = MB_CPTR2LEN(p + n);\n\t\tc2 = mb_ptr2char(p + n);\n\t\tif (!soundfold && !spell_iswordp(p + n + fl, curwin))\n\t\t c3 = c;\t// don't swap non-word char\n\t\telse\n\t\t c3 = mb_ptr2char(p + n + fl);\n\t }\n\t else\n\t {\n\t\tc = *p;\n\t\tc2 = p[1];\n\t\tif (!soundfold && !spell_iswordp(p + 2, curwin))\n\t\t c3 = c;\t// don't swap non-word char\n\t\telse\n\t\t c3 = p[2];\n\t }\n\n\t // When characters are identical: \"121\" then SWAP3 result is\n\t // identical, ROT3L result is same as SWAP: \"211\", ROT3L result is\n\t // same as SWAP on next char: \"112\". Thus skip all swapping.\n\t // Also skip when c3 is NUL.\n\t // Also get here when the third character is not a word character.\n\t // Second character may any char: \"a.b\" -> \"b.a\"\n\t if (c == c3 || c3 == NUL)\n\t {\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_REP_INI;\n\t\tbreak;\n\t }\n\t if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3))\n\t {\n\t\tgo_deeper(stack, depth, SCORE_SWAP3);\n#ifdef DEBUG_TRIEWALK\n\t\tsprintf(changename[depth], \"%.*s-%s: swap3 %c and %c\",\n\t\t\tsp->ts_twordlen, tword, fword + sp->ts_fidx,\n\t\t\tc, c3);\n#endif\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_UNSWAP3;\n\t\t++depth;\n\t\tif (has_mbyte)\n\t\t{\n\t\t tl = mb_char2len(c3);\n\t\t mch_memmove(p, p + n + fl, tl);\n\t\t mb_char2bytes(c2, p + tl);\n\t\t mb_char2bytes(c, p + fl + tl);\n\t\t stack[depth].ts_fidxtry = sp->ts_fidx + n + fl + tl;\n\t\t}\n\t\telse\n\t\t{\n\t\t p[0] = p[2];\n\t\t p[2] = c;\n\t\t stack[depth].ts_fidxtry = sp->ts_fidx + 3;\n\t\t}\n\t }\n\t else\n\t {\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_REP_INI;\n\t }\n\t break;\n\n\tcase STATE_UNSWAP3:\n\t // Undo STATE_SWAP3: \"321\" -> \"123\"\n\t p = fword + sp->ts_fidx;\n\t if (has_mbyte)\n\t {\n\t\tn = mb_ptr2len(p);\n\t\tc2 = mb_ptr2char(p + n);\n\t\tfl = mb_ptr2len(p + n);\n\t\tc = mb_ptr2char(p + n + fl);\n\t\ttl = mb_ptr2len(p + n + fl);\n\t\tmch_memmove(p + fl + tl, p, n);\n\t\tmb_char2bytes(c, p);\n\t\tmb_char2bytes(c2, p + tl);\n\t\tp = p + tl;\n\t }\n\t else\n\t {\n\t\tc = *p;\n\t\t*p = p[2];\n\t\tp[2] = c;\n\t\t++p;\n\t }\n\n\t if (!soundfold && !spell_iswordp(p, curwin))\n\t {\n\t\t// Middle char is not a word char, skip the rotate. First and\n\t\t// third char were already checked at swap and swap3.\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_REP_INI;\n\t\tbreak;\n\t }\n\n\t // Rotate three characters left: \"123\" -> \"231\". We change\n\t // \"fword\" here, it's changed back afterwards at STATE_UNROT3L.\n\t if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3))\n\t {\n\t\tgo_deeper(stack, depth, SCORE_SWAP3);\n#ifdef DEBUG_TRIEWALK\n\t\tp = fword + sp->ts_fidx;\n\t\tsprintf(changename[depth], \"%.*s-%s: rotate left %c%c%c\",\n\t\t\tsp->ts_twordlen, tword, fword + sp->ts_fidx,\n\t\t\tp[0], p[1], p[2]);\n#endif\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_UNROT3L;\n\t\t++depth;\n\t\tp = fword + sp->ts_fidx;\n\t\tif (has_mbyte)\n\t\t{\n\t\t n = MB_CPTR2LEN(p);\n\t\t c = mb_ptr2char(p);\n\t\t fl = MB_CPTR2LEN(p + n);\n\t\t fl += MB_CPTR2LEN(p + n + fl);\n\t\t mch_memmove(p, p + n, fl);\n\t\t mb_char2bytes(c, p + fl);\n\t\t stack[depth].ts_fidxtry = sp->ts_fidx + n + fl;\n\t\t}\n\t\telse\n\t\t{\n\t\t c = *p;\n\t\t *p = p[1];\n\t\t p[1] = p[2];\n\t\t p[2] = c;\n\t\t stack[depth].ts_fidxtry = sp->ts_fidx + 3;\n\t\t}\n\t }\n\t else\n\t {\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_REP_INI;\n\t }\n\t break;\n\n\tcase STATE_UNROT3L:\n\t // Undo ROT3L: \"231\" -> \"123\"\n\t p = fword + sp->ts_fidx;\n\t if (has_mbyte)\n\t {\n\t\tn = mb_ptr2len(p);\n\t\tn += mb_ptr2len(p + n);\n\t\tc = mb_ptr2char(p + n);\n\t\ttl = mb_ptr2len(p + n);\n\t\tmch_memmove(p + tl, p, n);\n\t\tmb_char2bytes(c, p);\n\t }\n\t else\n\t {\n\t\tc = p[2];\n\t\tp[2] = p[1];\n\t\tp[1] = *p;\n\t\t*p = c;\n\t }\n\n\t // Rotate three bytes right: \"123\" -> \"312\". We change \"fword\"\n\t // here, it's changed back afterwards at STATE_UNROT3R.\n\t if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3))\n\t {\n\t\tgo_deeper(stack, depth, SCORE_SWAP3);\n#ifdef DEBUG_TRIEWALK\n\t\tp = fword + sp->ts_fidx;\n\t\tsprintf(changename[depth], \"%.*s-%s: rotate right %c%c%c\",\n\t\t\tsp->ts_twordlen, tword, fword + sp->ts_fidx,\n\t\t\tp[0], p[1], p[2]);\n#endif\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_UNROT3R;\n\t\t++depth;\n\t\tp = fword + sp->ts_fidx;\n\t\tif (has_mbyte)\n\t\t{\n\t\t n = MB_CPTR2LEN(p);\n\t\t n += MB_CPTR2LEN(p + n);\n\t\t c = mb_ptr2char(p + n);\n\t\t tl = MB_CPTR2LEN(p + n);\n\t\t mch_memmove(p + tl, p, n);\n\t\t mb_char2bytes(c, p);\n\t\t stack[depth].ts_fidxtry = sp->ts_fidx + n + tl;\n\t\t}\n\t\telse\n\t\t{\n\t\t c = p[2];\n\t\t p[2] = p[1];\n\t\t p[1] = *p;\n\t\t *p = c;\n\t\t stack[depth].ts_fidxtry = sp->ts_fidx + 3;\n\t\t}\n\t }\n\t else\n\t {\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_REP_INI;\n\t }\n\t break;\n\n\tcase STATE_UNROT3R:\n\t // Undo ROT3R: \"312\" -> \"123\"\n\t p = fword + sp->ts_fidx;\n\t if (has_mbyte)\n\t {\n\t\tc = mb_ptr2char(p);\n\t\ttl = mb_ptr2len(p);\n\t\tn = mb_ptr2len(p + tl);\n\t\tn += mb_ptr2len(p + tl + n);\n\t\tmch_memmove(p, p + tl, n);\n\t\tmb_char2bytes(c, p + n);\n\t }\n\t else\n\t {\n\t\tc = *p;\n\t\t*p = p[1];\n\t\tp[1] = p[2];\n\t\tp[2] = c;\n\t }\n\t // FALLTHROUGH\n\n\tcase STATE_REP_INI:\n\t // Check if matching with REP items from the .aff file would work.\n\t // Quickly skip if:\n\t // - there are no REP items and we are not in the soundfold trie\n\t // - the score is going to be too high anyway\n\t // - already applied a REP item or swapped here\n\t if ((lp->lp_replang == NULL && !soundfold)\n\t\t || sp->ts_score + SCORE_REP >= su->su_maxscore\n\t\t || sp->ts_fidx < sp->ts_fidxtry)\n\t {\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_FINAL;\n\t\tbreak;\n\t }\n\n\t // Use the first byte to quickly find the first entry that may\n\t // match. If the index is -1 there is none.\n\t if (soundfold)\n\t\tsp->ts_curi = slang->sl_repsal_first[fword[sp->ts_fidx]];\n\t else\n\t\tsp->ts_curi = lp->lp_replang->sl_rep_first[fword[sp->ts_fidx]];\n\n\t if (sp->ts_curi < 0)\n\t {\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_FINAL;\n\t\tbreak;\n\t }\n\n\t PROF_STORE(sp->ts_state)\n\t sp->ts_state = STATE_REP;\n\t // FALLTHROUGH\n\n\tcase STATE_REP:\n\t // Try matching with REP items from the .aff file. For each match\n\t // replace the characters and check if the resulting word is\n\t // valid.\n\t p = fword + sp->ts_fidx;\n\n\t if (soundfold)\n\t\tgap = &slang->sl_repsal;\n\t else\n\t\tgap = &lp->lp_replang->sl_rep;\n\t while (sp->ts_curi < gap->ga_len)\n\t {\n\t\tftp = (fromto_T *)gap->ga_data + sp->ts_curi++;\n\t\tif (*ftp->ft_from != *p)\n\t\t{\n\t\t // past possible matching entries\n\t\t sp->ts_curi = gap->ga_len;\n\t\t break;\n\t\t}\n\t\tif (STRNCMP(ftp->ft_from, p, STRLEN(ftp->ft_from)) == 0\n\t\t\t&& TRY_DEEPER(su, stack, depth, SCORE_REP))\n\t\t{\n\t\t go_deeper(stack, depth, SCORE_REP);\n#ifdef DEBUG_TRIEWALK\n\t\t sprintf(changename[depth], \"%.*s-%s: replace %s with %s\",\n\t\t\t sp->ts_twordlen, tword, fword + sp->ts_fidx,\n\t\t\t ftp->ft_from, ftp->ft_to);\n#endif\n\t\t // Need to undo this afterwards.\n\t\t PROF_STORE(sp->ts_state)\n\t\t sp->ts_state = STATE_REP_UNDO;\n\n\t\t // Change the \"from\" to the \"to\" string.\n\t\t ++depth;\n\t\t fl = (int)STRLEN(ftp->ft_from);\n\t\t tl = (int)STRLEN(ftp->ft_to);\n\t\t if (fl != tl)\n\t\t {\n\t\t\tSTRMOVE(p + tl, p + fl);\n\t\t\trepextra += tl - fl;\n\t\t }\n\t\t mch_memmove(p, ftp->ft_to, tl);\n\t\t stack[depth].ts_fidxtry = sp->ts_fidx + tl;\n\t\t stack[depth].ts_tcharlen = 0;\n\t\t break;\n\t\t}\n\t }\n\n\t if (sp->ts_curi >= gap->ga_len && sp->ts_state == STATE_REP)\n\t {\n\t\t// No (more) matches.\n\t\tPROF_STORE(sp->ts_state)\n\t\tsp->ts_state = STATE_FINAL;\n\t }\n\n\t break;\n\n\tcase STATE_REP_UNDO:\n\t // Undo a REP replacement and continue with the next one.\n\t if (soundfold)\n\t\tgap = &slang->sl_repsal;\n\t else\n\t\tgap = &lp->lp_replang->sl_rep;\n\t ftp = (fromto_T *)gap->ga_data + sp->ts_curi - 1;\n\t fl = (int)STRLEN(ftp->ft_from);\n\t tl = (int)STRLEN(ftp->ft_to);\n\t p = fword + sp->ts_fidx;\n\t if (fl != tl)\n\t {\n\t\tSTRMOVE(p + fl, p + tl);\n\t\trepextra -= tl - fl;\n\t }\n\t mch_memmove(p, ftp->ft_from, fl);\n\t PROF_STORE(sp->ts_state)\n\t sp->ts_state = STATE_REP;\n\t break;\n\n\tdefault:\n\t // Did all possible states at this level, go up one level.\n\t --depth;\n\n\t if (depth >= 0 && stack[depth].ts_prefixdepth == PFD_PREFIXTREE)\n\t {\n\t\t// Continue in or go back to the prefix tree.\n\t\tbyts = pbyts;\n\t\tidxs = pidxs;\n\t }\n\n\t // Don't check for CTRL-C too often, it takes time.\n\t if (--breakcheckcount == 0)\n\t {\n\t\tui_breakcheck();\n\t\tbreakcheckcount = 1000;\n\t }\n\t}\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-457'], 'message': 'patch 8.2.3582: reading uninitialized memory when giving spell suggestions\n\nProblem: Reading uninitialized memory when giving spell suggestions.\nSolution: Check that preword is not empty.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: DEFINE_TEST(test_write_disk_fixup)\n{\n#if defined(_WIN32) && !defined(__CYGWIN__)\n\tskipping(\"Skipping test on Windows\");\n#else\n\tstruct archive *ad;\n\tstruct archive_entry *ae;\n\tint r;\n\n\tif (!canSymlink()) {\n\t\tskipping(\"Symlinks not supported\");\n\t\treturn;\n\t}\n\n\t/* Write entries to disk. */\n\tassert((ad = archive_write_disk_new()) != NULL);\n\n\t/*\n\t * Create a file\n\t */\n\tassertMakeFile(\"victim\", 0600, \"a\");\n\n\t/*\n\t * Create a directory and a symlink with the same name\n\t */\n\n\t/* Directory: dir */\n assert((ae = archive_entry_new()) != NULL);\n archive_entry_copy_pathname(ae, \"dir\");\n archive_entry_set_mode(ae, AE_IFDIR | 0606);\n\tassertEqualIntA(ad, 0, archive_write_header(ad, ae));\n\tassertEqualIntA(ad, 0, archive_write_finish_entry(ad));\n archive_entry_free(ae);\n\n\t/* Symbolic Link: dir -> foo */\n\tassert((ae = archive_entry_new()) != NULL);\n\tarchive_entry_copy_pathname(ae, \"dir\");\n\tarchive_entry_set_mode(ae, AE_IFLNK | 0777);\n\tarchive_entry_set_size(ae, 0);\n\tarchive_entry_copy_symlink(ae, \"victim\");\n\tassertEqualIntA(ad, 0, r = archive_write_header(ad, ae));\n\tif (r >= ARCHIVE_WARN)\n\t\tassertEqualIntA(ad, 0, archive_write_finish_entry(ad));\n\tarchive_entry_free(ae);\n\n\tassertEqualInt(ARCHIVE_OK, archive_write_free(ad));\n\n\t/* Test the entries on disk. */\n\tassertIsSymlink(\"dir\", \"victim\", 0);\n\tassertFileMode(\"victim\", 0600);\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59'], 'message': 'Fix following symlinks when processing the fixup list\n\nThe previous fix in b41daecb5 was incomplete. Fixup entries are\ngiven the original path without calling cleanup_pathname().\nTo make sure we don't follow a symlink, we must strip trailing\nslashes from the path.\n\nThe fixup entries are always directories. Make sure we try to modify\nonly directories by providing O_DIRECTORY to open() (if supported)\nand if it fails to check directory via lstat().\n\nFixes #1566'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: set_acl(struct archive *a, int fd, const char *name,\n struct archive_acl *abstract_acl,\n int ae_requested_type, const char *tname)\n{\n\tint\t\t acl_type = 0;\n\tint\t\t ae_type, ae_permset, ae_tag, ae_id;\n\tuid_t\t\t ae_uid;\n\tgid_t\t\t ae_gid;\n\tconst char\t*ae_name;\n\tint\t\t entries;\n\tint\t\t i;\n\tint\t\t ret;\n\tacl_t\t\t acl = NULL;\n\tacl_entry_t\t acl_entry;\n\tacl_permset_t\t acl_permset;\n\n\tret = ARCHIVE_OK;\n\tentries = archive_acl_reset(abstract_acl, ae_requested_type);\n\tif (entries == 0)\n\t\treturn (ARCHIVE_OK);\n\n\tswitch (ae_requested_type) {\n\tcase ARCHIVE_ENTRY_ACL_TYPE_ACCESS:\n\t\tacl_type = ACL_TYPE_ACCESS;\n\t\tbreak;\n\tcase ARCHIVE_ENTRY_ACL_TYPE_DEFAULT:\n\t\tacl_type = ACL_TYPE_DEFAULT;\n\t\tbreak;\n\tdefault:\n\t\terrno = ENOENT;\n\t\tarchive_set_error(a, errno, \"Unsupported ACL type\");\n\t\treturn (ARCHIVE_FAILED);\n\t}\n\n\tacl = acl_init(entries);\n\tif (acl == (acl_t)NULL) {\n\t\tarchive_set_error(a, errno,\n\t\t \"Failed to initialize ACL working storage\");\n\t\treturn (ARCHIVE_FAILED);\n\t}\n\n\twhile (archive_acl_next(a, abstract_acl, ae_requested_type, &ae_type,\n\t\t &ae_permset, &ae_tag, &ae_id, &ae_name) == ARCHIVE_OK) {\n\n\t\tif (acl_create_entry(&acl, &acl_entry) != 0) {\n\t\t\tarchive_set_error(a, errno,\n\t\t\t \"Failed to create a new ACL entry\");\n\t\t\tret = ARCHIVE_FAILED;\n\t\t\tgoto exit_free;\n\t\t}\n\n\t\tswitch (ae_tag) {\n\t\tcase ARCHIVE_ENTRY_ACL_USER:\n\t\t\tae_uid = archive_write_disk_uid(a, ae_name, ae_id);\n\t\t\tacl_set_tag_type(acl_entry, ACL_USER);\n\t\t\tacl_set_qualifier(acl_entry, &ae_uid);\n\t\t\tbreak;\n\t\tcase ARCHIVE_ENTRY_ACL_GROUP:\n\t\t\tae_gid = archive_write_disk_gid(a, ae_name, ae_id);\n\t\t\tacl_set_tag_type(acl_entry, ACL_GROUP);\n\t\t\tacl_set_qualifier(acl_entry, &ae_gid);\n\t\t\tbreak;\n\t\tcase ARCHIVE_ENTRY_ACL_USER_OBJ:\n\t\t\tacl_set_tag_type(acl_entry, ACL_USER_OBJ);\n\t\t\tbreak;\n\t\tcase ARCHIVE_ENTRY_ACL_GROUP_OBJ:\n\t\t\tacl_set_tag_type(acl_entry, ACL_GROUP_OBJ);\n\t\t\tbreak;\n\t\tcase ARCHIVE_ENTRY_ACL_MASK:\n\t\t\tacl_set_tag_type(acl_entry, ACL_MASK);\n\t\t\tbreak;\n\t\tcase ARCHIVE_ENTRY_ACL_OTHER:\n\t\t\tacl_set_tag_type(acl_entry, ACL_OTHER);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tarchive_set_error(a, ARCHIVE_ERRNO_MISC,\n\t\t\t \"Unsupported ACL tag\");\n\t\t\tret = ARCHIVE_FAILED;\n\t\t\tgoto exit_free;\n\t\t}\n\n\t\tif (acl_get_permset(acl_entry, &acl_permset) != 0) {\n\t\t\tarchive_set_error(a, errno,\n\t\t\t \"Failed to get ACL permission set\");\n\t\t\tret = ARCHIVE_FAILED;\n\t\t\tgoto exit_free;\n\t\t}\n\t\tif (acl_clear_perms(acl_permset) != 0) {\n\t\t\tarchive_set_error(a, errno,\n\t\t\t \"Failed to clear ACL permissions\");\n\t\t\tret = ARCHIVE_FAILED;\n\t\t\tgoto exit_free;\n\t\t}\n\n\t\tfor (i = 0; i < acl_posix_perm_map_size; ++i) {\n\t\t\tif (ae_permset & acl_posix_perm_map[i].a_perm) {\n\t\t\t\tif (acl_add_perm(acl_permset,\n\t\t\t\t acl_posix_perm_map[i].p_perm) != 0) {\n\t\t\t\t\tarchive_set_error(a, errno,\n\t\t\t\t\t \"Failed to add ACL permission\");\n\t\t\t\t\tret = ARCHIVE_FAILED;\n\t\t\t\t\tgoto exit_free;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif (fd >= 0 && ae_requested_type == ARCHIVE_ENTRY_ACL_TYPE_ACCESS) {\n\t\tif (acl_set_fd(fd, acl) == 0)\n\t\t\tret = ARCHIVE_OK;\n\t\telse {\n\t\t\tif (errno == EOPNOTSUPP) {\n\t\t\t\t/* Filesystem doesn't support ACLs */\n\t\t\t\tret = ARCHIVE_OK;\n\t\t\t} else {\n\t\t\t\tarchive_set_error(a, errno,\n\t\t\t\t \"Failed to set acl on fd: %s\", tname);\n\t\t\t\tret = ARCHIVE_WARN;\n\t\t\t}\n\t\t}\n\t} else if (acl_set_file(name, acl_type, acl) != 0) {\n\t\tif (errno == EOPNOTSUPP) {\n\t\t\t/* Filesystem doesn't support ACLs */\n\t\t\tret = ARCHIVE_OK;\n\t\t} else {\n\t\t\tarchive_set_error(a, errno, \"Failed to set acl: %s\",\n\t\t\t tname);\n\t\t\tret = ARCHIVE_WARN;\n\t\t}\n\t}\nexit_free:\n\tacl_free(acl);\n\treturn (ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'Fix handling of symbolic link ACLs\n\nOn Linux ACLs on symbolic links are not supported.\nWe must avoid calling acl_set_file() on symbolic links as their\ntargets are modified instead.\n\nWhile here, do not try to set default ACLs on non-directories.\n\nFixes #1565'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int is_fuse_usermount(struct libmnt_context *cxt, int *errsv)\n{\n\tstruct libmnt_ns *ns_old;\n\tconst char *type = mnt_fs_get_fstype(cxt->fs);\n\tconst char *optstr;\n\tchar *user_id = NULL;\n\tsize_t sz;\n\tuid_t uid;\n\tchar uidstr[sizeof(stringify_value(ULONG_MAX))];\n\n\t*errsv = 0;\n\n\tif (!type)\n\t\treturn 0;\n\n\tif (strcmp(type, \"fuse\") != 0 &&\n\t strcmp(type, \"fuseblk\") != 0 &&\n\t strncmp(type, \"fuse.\", 5) != 0 &&\n\t strncmp(type, \"fuseblk.\", 8) != 0)\n\t\treturn 0;\n\n\t/* get user_id= from mount table */\n\toptstr = mnt_fs_get_fs_options(cxt->fs);\n\tif (!optstr)\n\t\treturn 0;\n\n\tif (mnt_optstr_get_option(optstr, \"user_id\", &user_id, &sz) != 0)\n\t\treturn 0;\n\n\tif (sz == 0 || user_id == NULL)\n\t\treturn 0;\n\n\t/* get current user */\n\tns_old = mnt_context_switch_origin_ns(cxt);\n\tif (!ns_old) {\n\t\t*errsv = -MNT_ERR_NAMESPACE;\n\t\treturn 0;\n\t}\n\n\tuid = getuid();\n\n\tif (!mnt_context_switch_ns(cxt, ns_old)) {\n\t\t*errsv = -MNT_ERR_NAMESPACE;\n\t\treturn 0;\n\t}\n\n\tsnprintf(uidstr, sizeof(uidstr), \"%lu\", (unsigned long) uid);\n\treturn strncmp(user_id, uidstr, sz) == 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-552', 'CWE-703'], 'message': 'libmount: fix UID check for FUSE umount [CVE-2021-3995]\n\nImproper UID check allows an unprivileged user to unmount FUSE\nfilesystems of users with similar UID.\n\nSigned-off-by: Karel Zak '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: nfa_regmatch(\n nfa_regprog_T\t*prog,\n nfa_state_T\t\t*start,\n regsubs_T\t\t*submatch,\n regsubs_T\t\t*m)\n{\n int\t\tresult = FALSE;\n size_t\tsize = 0;\n int\t\tflag = 0;\n int\t\tgo_to_nextline = FALSE;\n nfa_thread_T *t;\n nfa_list_T\tlist[2];\n int\t\tlistidx;\n nfa_list_T\t*thislist;\n nfa_list_T\t*nextlist;\n int\t\t*listids = NULL;\n int\t\tlistids_len = 0;\n nfa_state_T *add_state;\n int\t\tadd_here;\n int\t\tadd_count;\n int\t\tadd_off = 0;\n int\t\ttoplevel = start->c == NFA_MOPEN;\n regsubs_T\t*r;\n#ifdef NFA_REGEXP_DEBUG_LOG\n FILE\t*debug;\n#endif\n\n // Some patterns may take a long time to match, especially when using\n // recursive_regmatch(). Allow interrupting them with CTRL-C.\n fast_breakcheck();\n if (got_int)\n\treturn FALSE;\n#ifdef FEAT_RELTIME\n if (nfa_did_time_out())\n\treturn FALSE;\n#endif\n\n#ifdef NFA_REGEXP_DEBUG_LOG\n debug = fopen(NFA_REGEXP_DEBUG_LOG, \"a\");\n if (debug == NULL)\n {\n\tsemsg(\"(NFA) COULD NOT OPEN %s!\", NFA_REGEXP_DEBUG_LOG);\n\treturn FALSE;\n }\n#endif\n nfa_match = FALSE;\n\n // Allocate memory for the lists of nodes.\n size = (prog->nstate + 1) * sizeof(nfa_thread_T);\n\n list[0].t = alloc(size);\n list[0].len = prog->nstate + 1;\n list[1].t = alloc(size);\n list[1].len = prog->nstate + 1;\n if (list[0].t == NULL || list[1].t == NULL)\n\tgoto theend;\n\n#ifdef ENABLE_LOG\n log_fd = fopen(NFA_REGEXP_RUN_LOG, \"a\");\n if (log_fd != NULL)\n {\n\tfprintf(log_fd, \"**********************************\\n\");\n\tnfa_set_code(start->c);\n\tfprintf(log_fd, \" RUNNING nfa_regmatch() starting with state %d, code %s\\n\",\n\tabs(start->id), code);\n\tfprintf(log_fd, \"**********************************\\n\");\n }\n else\n {\n\temsg(_(e_log_open_failed));\n\tlog_fd = stderr;\n }\n#endif\n\n thislist = &list[0];\n thislist->n = 0;\n thislist->has_pim = FALSE;\n nextlist = &list[1];\n nextlist->n = 0;\n nextlist->has_pim = FALSE;\n#ifdef ENABLE_LOG\n fprintf(log_fd, \"(---) STARTSTATE first\\n\");\n#endif\n thislist->id = rex.nfa_listid + 1;\n\n // Inline optimized code for addstate(thislist, start, m, 0) if we know\n // it's the first MOPEN.\n if (toplevel)\n {\n\tif (REG_MULTI)\n\t{\n\t m->norm.list.multi[0].start_lnum = rex.lnum;\n\t m->norm.list.multi[0].start_col = (colnr_T)(rex.input - rex.line);\n\t}\n\telse\n\t m->norm.list.line[0].start = rex.input;\n\tm->norm.in_use = 1;\n\tr = addstate(thislist, start->out, m, NULL, 0);\n }\n else\n\tr = addstate(thislist, start, m, NULL, 0);\n if (r == NULL)\n {\n\tnfa_match = NFA_TOO_EXPENSIVE;\n\tgoto theend;\n }\n\n#define\tADD_STATE_IF_MATCH(state)\t\t\t\\\n if (result) {\t\t\t\t\t\\\n\tadd_state = state->out;\t\t\t\t\\\n\tadd_off = clen;\t\t\t\t\t\\\n }\n\n /*\n * Run for each character.\n */\n for (;;)\n {\n\tint\tcurc;\n\tint\tclen;\n\n\tif (has_mbyte)\n\t{\n\t curc = (*mb_ptr2char)(rex.input);\n\t clen = (*mb_ptr2len)(rex.input);\n\t}\n\telse\n\t{\n\t curc = *rex.input;\n\t clen = 1;\n\t}\n\tif (curc == NUL)\n\t{\n\t clen = 0;\n\t go_to_nextline = FALSE;\n\t}\n\n\t// swap lists\n\tthislist = &list[flag];\n\tnextlist = &list[flag ^= 1];\n\tnextlist->n = 0;\t // clear nextlist\n\tnextlist->has_pim = FALSE;\n\t++rex.nfa_listid;\n\tif (prog->re_engine == AUTOMATIC_ENGINE\n\t\t&& (rex.nfa_listid >= NFA_MAX_STATES\n# ifdef FEAT_EVAL\n\t\t || nfa_fail_for_testing\n# endif\n\t\t ))\n\t{\n\t // too many states, retry with old engine\n\t nfa_match = NFA_TOO_EXPENSIVE;\n\t goto theend;\n\t}\n\n\tthislist->id = rex.nfa_listid;\n\tnextlist->id = rex.nfa_listid + 1;\n\n#ifdef ENABLE_LOG\n\tfprintf(log_fd, \"------------------------------------------\\n\");\n\tfprintf(log_fd, \">>> Reginput is \\\"%s\\\"\\n\", rex.input);\n\tfprintf(log_fd, \">>> Advanced one character... Current char is %c (code %d) \\n\", curc, (int)curc);\n\tfprintf(log_fd, \">>> Thislist has %d states available: \", thislist->n);\n\t{\n\t int i;\n\n\t for (i = 0; i < thislist->n; i++)\n\t\tfprintf(log_fd, \"%d \", abs(thislist->t[i].state->id));\n\t}\n\tfprintf(log_fd, \"\\n\");\n#endif\n\n#ifdef NFA_REGEXP_DEBUG_LOG\n\tfprintf(debug, \"\\n-------------------\\n\");\n#endif\n\t/*\n\t * If the state lists are empty we can stop.\n\t */\n\tif (thislist->n == 0)\n\t break;\n\n\t// compute nextlist\n\tfor (listidx = 0; listidx < thislist->n; ++listidx)\n\t{\n\t // If the list gets very long there probably is something wrong.\n\t // At least allow interrupting with CTRL-C.\n\t fast_breakcheck();\n\t if (got_int)\n\t\tbreak;\n#ifdef FEAT_RELTIME\n\t if (nfa_time_limit != NULL && ++nfa_time_count == 20)\n\t {\n\t\tnfa_time_count = 0;\n\t\tif (nfa_did_time_out())\n\t\t break;\n\t }\n#endif\n\t t = &thislist->t[listidx];\n\n#ifdef NFA_REGEXP_DEBUG_LOG\n\t nfa_set_code(t->state->c);\n\t fprintf(debug, \"%s, \", code);\n#endif\n#ifdef ENABLE_LOG\n\t {\n\t\tint col;\n\n\t\tif (t->subs.norm.in_use <= 0)\n\t\t col = -1;\n\t\telse if (REG_MULTI)\n\t\t col = t->subs.norm.list.multi[0].start_col;\n\t\telse\n\t\t col = (int)(t->subs.norm.list.line[0].start - rex.line);\n\t\tnfa_set_code(t->state->c);\n\t\tfprintf(log_fd, \"(%d) char %d %s (start col %d)%s... \\n\",\n\t\t\tabs(t->state->id), (int)t->state->c, code, col,\n\t\t\tpim_info(&t->pim));\n\t }\n#endif\n\n\t /*\n\t * Handle the possible codes of the current state.\n\t * The most important is NFA_MATCH.\n\t */\n\t add_state = NULL;\n\t add_here = FALSE;\n\t add_count = 0;\n\t switch (t->state->c)\n\t {\n\t case NFA_MATCH:\n\t {\n\t\t// If the match is not at the start of the line, ends before a\n\t\t// composing characters and rex.reg_icombine is not set, that\n\t\t// is not really a match.\n\t\tif (enc_utf8 && !rex.reg_icombine\n\t\t\t && rex.input != rex.line && utf_iscomposing(curc))\n\t\t break;\n\n\t\tnfa_match = TRUE;\n\t\tcopy_sub(&submatch->norm, &t->subs.norm);\n#ifdef FEAT_SYN_HL\n\t\tif (rex.nfa_has_zsubexpr)\n\t\t copy_sub(&submatch->synt, &t->subs.synt);\n#endif\n#ifdef ENABLE_LOG\n\t\tlog_subsexpr(&t->subs);\n#endif\n\t\t// Found the left-most longest match, do not look at any other\n\t\t// states at this position. When the list of states is going\n\t\t// to be empty quit without advancing, so that \"rex.input\" is\n\t\t// correct.\n\t\tif (nextlist->n == 0)\n\t\t clen = 0;\n\t\tgoto nextchar;\n\t }\n\n\t case NFA_END_INVISIBLE:\n\t case NFA_END_INVISIBLE_NEG:\n\t case NFA_END_PATTERN:\n\t\t/*\n\t\t * This is only encountered after a NFA_START_INVISIBLE or\n\t\t * NFA_START_INVISIBLE_BEFORE node.\n\t\t * They surround a zero-width group, used with \"\\@=\", \"\\&\",\n\t\t * \"\\@!\", \"\\@<=\" and \"\\@se_u.pos.lnum,\n\t\t\t\t(int)(rex.input - rex.line),\n\t\t\t\tnfa_endp->se_u.pos.col);\n\t\t else\n\t\t\tfprintf(log_fd, \"Current col: %d, endp col: %d\\n\",\n\t\t\t\t(int)(rex.input - rex.line),\n\t\t\t\t(int)(nfa_endp->se_u.ptr - rex.input));\n\t\t}\n#endif\n\t\t// If \"nfa_endp\" is set it's only a match if it ends at\n\t\t// \"nfa_endp\"\n\t\tif (nfa_endp != NULL && (REG_MULTI\n\t\t\t? (rex.lnum != nfa_endp->se_u.pos.lnum\n\t\t\t || (int)(rex.input - rex.line)\n\t\t\t\t\t\t!= nfa_endp->se_u.pos.col)\n\t\t\t: rex.input != nfa_endp->se_u.ptr))\n\t\t break;\n\n\t\t// do not set submatches for \\@!\n\t\tif (t->state->c != NFA_END_INVISIBLE_NEG)\n\t\t{\n\t\t copy_sub(&m->norm, &t->subs.norm);\n#ifdef FEAT_SYN_HL\n\t\t if (rex.nfa_has_zsubexpr)\n\t\t\tcopy_sub(&m->synt, &t->subs.synt);\n#endif\n\t\t}\n#ifdef ENABLE_LOG\n\t\tfprintf(log_fd, \"Match found:\\n\");\n\t\tlog_subsexpr(m);\n#endif\n\t\tnfa_match = TRUE;\n\t\t// See comment above at \"goto nextchar\".\n\t\tif (nextlist->n == 0)\n\t\t clen = 0;\n\t\tgoto nextchar;\n\n\t case NFA_START_INVISIBLE:\n\t case NFA_START_INVISIBLE_FIRST:\n\t case NFA_START_INVISIBLE_NEG:\n\t case NFA_START_INVISIBLE_NEG_FIRST:\n\t case NFA_START_INVISIBLE_BEFORE:\n\t case NFA_START_INVISIBLE_BEFORE_FIRST:\n\t case NFA_START_INVISIBLE_BEFORE_NEG:\n\t case NFA_START_INVISIBLE_BEFORE_NEG_FIRST:\n\t\t{\n#ifdef ENABLE_LOG\n\t\t fprintf(log_fd, \"Failure chance invisible: %d, what follows: %d\\n\",\n\t\t\t failure_chance(t->state->out, 0),\n\t\t\t failure_chance(t->state->out1->out, 0));\n#endif\n\t\t // Do it directly if there already is a PIM or when\n\t\t // nfa_postprocess() detected it will work better.\n\t\t if (t->pim.result != NFA_PIM_UNUSED\n\t\t\t || t->state->c == NFA_START_INVISIBLE_FIRST\n\t\t\t || t->state->c == NFA_START_INVISIBLE_NEG_FIRST\n\t\t\t || t->state->c == NFA_START_INVISIBLE_BEFORE_FIRST\n\t\t\t || t->state->c == NFA_START_INVISIBLE_BEFORE_NEG_FIRST)\n\t\t {\n\t\t\tint in_use = m->norm.in_use;\n\n\t\t\t// Copy submatch info for the recursive call, opposite\n\t\t\t// of what happens on success below.\n\t\t\tcopy_sub_off(&m->norm, &t->subs.norm);\n#ifdef FEAT_SYN_HL\n\t\t\tif (rex.nfa_has_zsubexpr)\n\t\t\t copy_sub_off(&m->synt, &t->subs.synt);\n#endif\n\n\t\t\t/*\n\t\t\t * First try matching the invisible match, then what\n\t\t\t * follows.\n\t\t\t */\n\t\t\tresult = recursive_regmatch(t->state, NULL, prog,\n\t\t\t\t\t submatch, m, &listids, &listids_len);\n\t\t\tif (result == NFA_TOO_EXPENSIVE)\n\t\t\t{\n\t\t\t nfa_match = result;\n\t\t\t goto theend;\n\t\t\t}\n\n\t\t\t// for \\@! and \\@state->c == NFA_START_INVISIBLE_NEG\n\t\t\t || t->state->c == NFA_START_INVISIBLE_NEG_FIRST\n\t\t\t || t->state->c\n\t\t\t\t\t == NFA_START_INVISIBLE_BEFORE_NEG\n\t\t\t || t->state->c\n\t\t\t\t == NFA_START_INVISIBLE_BEFORE_NEG_FIRST))\n\t\t\t{\n\t\t\t // Copy submatch info from the recursive call\n\t\t\t copy_sub_off(&t->subs.norm, &m->norm);\n#ifdef FEAT_SYN_HL\n\t\t\t if (rex.nfa_has_zsubexpr)\n\t\t\t\tcopy_sub_off(&t->subs.synt, &m->synt);\n#endif\n\t\t\t // If the pattern has \\ze and it matched in the\n\t\t\t // sub pattern, use it.\n\t\t\t copy_ze_off(&t->subs.norm, &m->norm);\n\n\t\t\t // t->state->out1 is the corresponding\n\t\t\t // END_INVISIBLE node; Add its out to the current\n\t\t\t // list (zero-width match).\n\t\t\t add_here = TRUE;\n\t\t\t add_state = t->state->out1->out;\n\t\t\t}\n\t\t\tm->norm.in_use = in_use;\n\t\t }\n\t\t else\n\t\t {\n\t\t\tnfa_pim_T pim;\n\n\t\t\t/*\n\t\t\t * First try matching what follows. Only if a match\n\t\t\t * is found verify the invisible match matches. Add a\n\t\t\t * nfa_pim_T to the following states, it contains info\n\t\t\t * about the invisible match.\n\t\t\t */\n\t\t\tpim.state = t->state;\n\t\t\tpim.result = NFA_PIM_TODO;\n\t\t\tpim.subs.norm.in_use = 0;\n#ifdef FEAT_SYN_HL\n\t\t\tpim.subs.synt.in_use = 0;\n#endif\n\t\t\tif (REG_MULTI)\n\t\t\t{\n\t\t\t pim.end.pos.col = (int)(rex.input - rex.line);\n\t\t\t pim.end.pos.lnum = rex.lnum;\n\t\t\t}\n\t\t\telse\n\t\t\t pim.end.ptr = rex.input;\n\n\t\t\t// t->state->out1 is the corresponding END_INVISIBLE\n\t\t\t// node; Add its out to the current list (zero-width\n\t\t\t// match).\n\t\t\tif (addstate_here(thislist, t->state->out1->out,\n\t\t\t\t\t &t->subs, &pim, &listidx) == NULL)\n\t\t\t{\n\t\t\t nfa_match = NFA_TOO_EXPENSIVE;\n\t\t\t goto theend;\n\t\t\t}\n\t\t }\n\t\t}\n\t\tbreak;\n\n\t case NFA_START_PATTERN:\n\t {\n\t\tnfa_state_T *skip = NULL;\n#ifdef ENABLE_LOG\n\t\tint\t skip_lid = 0;\n#endif\n\n\t\t// There is no point in trying to match the pattern if the\n\t\t// output state is not going to be added to the list.\n\t\tif (state_in_list(nextlist, t->state->out1->out, &t->subs))\n\t\t{\n\t\t skip = t->state->out1->out;\n#ifdef ENABLE_LOG\n\t\t skip_lid = nextlist->id;\n#endif\n\t\t}\n\t\telse if (state_in_list(nextlist,\n\t\t\t\t\t t->state->out1->out->out, &t->subs))\n\t\t{\n\t\t skip = t->state->out1->out->out;\n#ifdef ENABLE_LOG\n\t\t skip_lid = nextlist->id;\n#endif\n\t\t}\n\t\telse if (state_in_list(thislist,\n\t\t\t\t\t t->state->out1->out->out, &t->subs))\n\t\t{\n\t\t skip = t->state->out1->out->out;\n#ifdef ENABLE_LOG\n\t\t skip_lid = thislist->id;\n#endif\n\t\t}\n\t\tif (skip != NULL)\n\t\t{\n#ifdef ENABLE_LOG\n\t\t nfa_set_code(skip->c);\n\t\t fprintf(log_fd, \"> Not trying to match pattern, output state %d is already in list %d. char %d: %s\\n\",\n\t\t\t abs(skip->id), skip_lid, skip->c, code);\n#endif\n\t\t break;\n\t\t}\n\t\t// Copy submatch info to the recursive call, opposite of what\n\t\t// happens afterwards.\n\t\tcopy_sub_off(&m->norm, &t->subs.norm);\n#ifdef FEAT_SYN_HL\n\t\tif (rex.nfa_has_zsubexpr)\n\t\t copy_sub_off(&m->synt, &t->subs.synt);\n#endif\n\n\t\t// First try matching the pattern.\n\t\tresult = recursive_regmatch(t->state, NULL, prog,\n\t\t\t\t\t submatch, m, &listids, &listids_len);\n\t\tif (result == NFA_TOO_EXPENSIVE)\n\t\t{\n\t\t nfa_match = result;\n\t\t goto theend;\n\t\t}\n\t\tif (result)\n\t\t{\n\t\t int bytelen;\n\n#ifdef ENABLE_LOG\n\t\t fprintf(log_fd, \"NFA_START_PATTERN matches:\\n\");\n\t\t log_subsexpr(m);\n#endif\n\t\t // Copy submatch info from the recursive call\n\t\t copy_sub_off(&t->subs.norm, &m->norm);\n#ifdef FEAT_SYN_HL\n\t\t if (rex.nfa_has_zsubexpr)\n\t\t\tcopy_sub_off(&t->subs.synt, &m->synt);\n#endif\n\t\t // Now we need to skip over the matched text and then\n\t\t // continue with what follows.\n\t\t if (REG_MULTI)\n\t\t\t// TODO: multi-line match\n\t\t\tbytelen = m->norm.list.multi[0].end_col\n\t\t\t\t\t\t - (int)(rex.input - rex.line);\n\t\t else\n\t\t\tbytelen = (int)(m->norm.list.line[0].end - rex.input);\n\n#ifdef ENABLE_LOG\n\t\t fprintf(log_fd, \"NFA_START_PATTERN length: %d\\n\", bytelen);\n#endif\n\t\t if (bytelen == 0)\n\t\t {\n\t\t\t// empty match, output of corresponding\n\t\t\t// NFA_END_PATTERN/NFA_SKIP to be used at current\n\t\t\t// position\n\t\t\tadd_here = TRUE;\n\t\t\tadd_state = t->state->out1->out->out;\n\t\t }\n\t\t else if (bytelen <= clen)\n\t\t {\n\t\t\t// match current character, output of corresponding\n\t\t\t// NFA_END_PATTERN to be used at next position.\n\t\t\tadd_state = t->state->out1->out->out;\n\t\t\tadd_off = clen;\n\t\t }\n\t\t else\n\t\t {\n\t\t\t// skip over the matched characters, set character\n\t\t\t// count in NFA_SKIP\n\t\t\tadd_state = t->state->out1->out;\n\t\t\tadd_off = bytelen;\n\t\t\tadd_count = bytelen - clen;\n\t\t }\n\t\t}\n\t\tbreak;\n\t }\n\n\t case NFA_BOL:\n\t\tif (rex.input == rex.line)\n\t\t{\n\t\t add_here = TRUE;\n\t\t add_state = t->state->out;\n\t\t}\n\t\tbreak;\n\n\t case NFA_EOL:\n\t\tif (curc == NUL)\n\t\t{\n\t\t add_here = TRUE;\n\t\t add_state = t->state->out;\n\t\t}\n\t\tbreak;\n\n\t case NFA_BOW:\n\t\tresult = TRUE;\n\n\t\tif (curc == NUL)\n\t\t result = FALSE;\n\t\telse if (has_mbyte)\n\t\t{\n\t\t int this_class;\n\n\t\t // Get class of current and previous char (if it exists).\n\t\t this_class = mb_get_class_buf(rex.input, rex.reg_buf);\n\t\t if (this_class <= 1)\n\t\t\tresult = FALSE;\n\t\t else if (reg_prev_class() == this_class)\n\t\t\tresult = FALSE;\n\t\t}\n\t\telse if (!vim_iswordc_buf(curc, rex.reg_buf)\n\t\t\t || (rex.input > rex.line\n\t\t\t\t&& vim_iswordc_buf(rex.input[-1], rex.reg_buf)))\n\t\t result = FALSE;\n\t\tif (result)\n\t\t{\n\t\t add_here = TRUE;\n\t\t add_state = t->state->out;\n\t\t}\n\t\tbreak;\n\n\t case NFA_EOW:\n\t\tresult = TRUE;\n\t\tif (rex.input == rex.line)\n\t\t result = FALSE;\n\t\telse if (has_mbyte)\n\t\t{\n\t\t int this_class, prev_class;\n\n\t\t // Get class of current and previous char (if it exists).\n\t\t this_class = mb_get_class_buf(rex.input, rex.reg_buf);\n\t\t prev_class = reg_prev_class();\n\t\t if (this_class == prev_class\n\t\t\t\t\t|| prev_class == 0 || prev_class == 1)\n\t\t\tresult = FALSE;\n\t\t}\n\t\telse if (!vim_iswordc_buf(rex.input[-1], rex.reg_buf)\n\t\t\t|| (rex.input[0] != NUL\n\t\t\t\t\t&& vim_iswordc_buf(curc, rex.reg_buf)))\n\t\t result = FALSE;\n\t\tif (result)\n\t\t{\n\t\t add_here = TRUE;\n\t\t add_state = t->state->out;\n\t\t}\n\t\tbreak;\n\n\t case NFA_BOF:\n\t\tif (rex.lnum == 0 && rex.input == rex.line\n\t\t\t\t && (!REG_MULTI || rex.reg_firstlnum == 1))\n\t\t{\n\t\t add_here = TRUE;\n\t\t add_state = t->state->out;\n\t\t}\n\t\tbreak;\n\n\t case NFA_EOF:\n\t\tif (rex.lnum == rex.reg_maxline && curc == NUL)\n\t\t{\n\t\t add_here = TRUE;\n\t\t add_state = t->state->out;\n\t\t}\n\t\tbreak;\n\n\t case NFA_COMPOSING:\n\t {\n\t\tint\t mc = curc;\n\t\tint\t len = 0;\n\t\tnfa_state_T *end;\n\t\tnfa_state_T *sta;\n\t\tint\t cchars[MAX_MCO];\n\t\tint\t ccount = 0;\n\t\tint\t j;\n\n\t\tsta = t->state->out;\n\t\tlen = 0;\n\t\tif (utf_iscomposing(sta->c))\n\t\t{\n\t\t // Only match composing character(s), ignore base\n\t\t // character. Used for \".{composing}\" and \"{composing}\"\n\t\t // (no preceding character).\n\t\t len += mb_char2len(mc);\n\t\t}\n\t\tif (rex.reg_icombine && len == 0)\n\t\t{\n\t\t // If \\Z was present, then ignore composing characters.\n\t\t // When ignoring the base character this always matches.\n\t\t if (sta->c != curc)\n\t\t\tresult = FAIL;\n\t\t else\n\t\t\tresult = OK;\n\t\t while (sta->c != NFA_END_COMPOSING)\n\t\t\tsta = sta->out;\n\t\t}\n\n\t\t// Check base character matches first, unless ignored.\n\t\telse if (len > 0 || mc == sta->c)\n\t\t{\n\t\t if (len == 0)\n\t\t {\n\t\t\tlen += mb_char2len(mc);\n\t\t\tsta = sta->out;\n\t\t }\n\n\t\t // We don't care about the order of composing characters.\n\t\t // Get them into cchars[] first.\n\t\t while (len < clen)\n\t\t {\n\t\t\tmc = mb_ptr2char(rex.input + len);\n\t\t\tcchars[ccount++] = mc;\n\t\t\tlen += mb_char2len(mc);\n\t\t\tif (ccount == MAX_MCO)\n\t\t\t break;\n\t\t }\n\n\t\t // Check that each composing char in the pattern matches a\n\t\t // composing char in the text. We do not check if all\n\t\t // composing chars are matched.\n\t\t result = OK;\n\t\t while (sta->c != NFA_END_COMPOSING)\n\t\t {\n\t\t\tfor (j = 0; j < ccount; ++j)\n\t\t\t if (cchars[j] == sta->c)\n\t\t\t\tbreak;\n\t\t\tif (j == ccount)\n\t\t\t{\n\t\t\t result = FAIL;\n\t\t\t break;\n\t\t\t}\n\t\t\tsta = sta->out;\n\t\t }\n\t\t}\n\t\telse\n\t\t result = FAIL;\n\n\t\tend = t->state->out1;\t // NFA_END_COMPOSING\n\t\tADD_STATE_IF_MATCH(end);\n\t\tbreak;\n\t }\n\n\t case NFA_NEWL:\n\t\tif (curc == NUL && !rex.reg_line_lbr && REG_MULTI\n\t\t\t\t\t\t && rex.lnum <= rex.reg_maxline)\n\t\t{\n\t\t go_to_nextline = TRUE;\n\t\t // Pass -1 for the offset, which means taking the position\n\t\t // at the start of the next line.\n\t\t add_state = t->state->out;\n\t\t add_off = -1;\n\t\t}\n\t\telse if (curc == '\\n' && rex.reg_line_lbr)\n\t\t{\n\t\t // match \\n as if it is an ordinary character\n\t\t add_state = t->state->out;\n\t\t add_off = 1;\n\t\t}\n\t\tbreak;\n\n\t case NFA_START_COLL:\n\t case NFA_START_NEG_COLL:\n\t {\n\t\t// What follows is a list of characters, until NFA_END_COLL.\n\t\t// One of them must match or none of them must match.\n\t\tnfa_state_T\t*state;\n\t\tint\t\tresult_if_matched;\n\t\tint\t\tc1, c2;\n\n\t\t// Never match EOL. If it's part of the collection it is added\n\t\t// as a separate state with an OR.\n\t\tif (curc == NUL)\n\t\t break;\n\n\t\tstate = t->state->out;\n\t\tresult_if_matched = (t->state->c == NFA_START_COLL);\n\t\tfor (;;)\n\t\t{\n\t\t if (state->c == NFA_END_COLL)\n\t\t {\n\t\t\tresult = !result_if_matched;\n\t\t\tbreak;\n\t\t }\n\t\t if (state->c == NFA_RANGE_MIN)\n\t\t {\n\t\t\tc1 = state->val;\n\t\t\tstate = state->out; // advance to NFA_RANGE_MAX\n\t\t\tc2 = state->val;\n#ifdef ENABLE_LOG\n\t\t\tfprintf(log_fd, \"NFA_RANGE_MIN curc=%d c1=%d c2=%d\\n\",\n\t\t\t\tcurc, c1, c2);\n#endif\n\t\t\tif (curc >= c1 && curc <= c2)\n\t\t\t{\n\t\t\t result = result_if_matched;\n\t\t\t break;\n\t\t\t}\n\t\t\tif (rex.reg_ic)\n\t\t\t{\n\t\t\t int curc_low = MB_CASEFOLD(curc);\n\t\t\t int done = FALSE;\n\n\t\t\t for ( ; c1 <= c2; ++c1)\n\t\t\t\tif (MB_CASEFOLD(c1) == curc_low)\n\t\t\t\t{\n\t\t\t\t result = result_if_matched;\n\t\t\t\t done = TRUE;\n\t\t\t\t break;\n\t\t\t\t}\n\t\t\t if (done)\n\t\t\t\tbreak;\n\t\t\t}\n\t\t }\n\t\t else if (state->c < 0 ? check_char_class(state->c, curc)\n\t\t\t : (curc == state->c\n\t\t\t\t || (rex.reg_ic && MB_CASEFOLD(curc)\n\t\t\t\t\t\t == MB_CASEFOLD(state->c))))\n\t\t {\n\t\t\tresult = result_if_matched;\n\t\t\tbreak;\n\t\t }\n\t\t state = state->out;\n\t\t}\n\t\tif (result)\n\t\t{\n\t\t // next state is in out of the NFA_END_COLL, out1 of\n\t\t // START points to the END state\n\t\t add_state = t->state->out1->out;\n\t\t add_off = clen;\n\t\t}\n\t\tbreak;\n\t }\n\n\t case NFA_ANY:\n\t\t// Any char except '\\0', (end of input) does not match.\n\t\tif (curc > 0)\n\t\t{\n\t\t add_state = t->state->out;\n\t\t add_off = clen;\n\t\t}\n\t\tbreak;\n\n\t case NFA_ANY_COMPOSING:\n\t\t// On a composing character skip over it. Otherwise do\n\t\t// nothing. Always matches.\n\t\tif (enc_utf8 && utf_iscomposing(curc))\n\t\t{\n\t\t add_off = clen;\n\t\t}\n\t\telse\n\t\t{\n\t\t add_here = TRUE;\n\t\t add_off = 0;\n\t\t}\n\t\tadd_state = t->state->out;\n\t\tbreak;\n\n\t /*\n\t * Character classes like \\a for alpha, \\d for digit etc.\n\t */\n\t case NFA_IDENT:\t// \\i\n\t\tresult = vim_isIDc(curc);\n\t\tADD_STATE_IF_MATCH(t->state);\n\t\tbreak;\n\n\t case NFA_SIDENT:\t// \\I\n\t\tresult = !VIM_ISDIGIT(curc) && vim_isIDc(curc);\n\t\tADD_STATE_IF_MATCH(t->state);\n\t\tbreak;\n\n\t case NFA_KWORD:\t// \\k\n\t\tresult = vim_iswordp_buf(rex.input, rex.reg_buf);\n\t\tADD_STATE_IF_MATCH(t->state);\n\t\tbreak;\n\n\t case NFA_SKWORD:\t// \\K\n\t\tresult = !VIM_ISDIGIT(curc)\n\t\t\t\t && vim_iswordp_buf(rex.input, rex.reg_buf);\n\t\tADD_STATE_IF_MATCH(t->state);\n\t\tbreak;\n\n\t case NFA_FNAME:\t// \\f\n\t\tresult = vim_isfilec(curc);\n\t\tADD_STATE_IF_MATCH(t->state);\n\t\tbreak;\n\n\t case NFA_SFNAME:\t// \\F\n\t\tresult = !VIM_ISDIGIT(curc) && vim_isfilec(curc);\n\t\tADD_STATE_IF_MATCH(t->state);\n\t\tbreak;\n\n\t case NFA_PRINT:\t// \\p\n\t\tresult = vim_isprintc(PTR2CHAR(rex.input));\n\t\tADD_STATE_IF_MATCH(t->state);\n\t\tbreak;\n\n\t case NFA_SPRINT:\t// \\P\n\t\tresult = !VIM_ISDIGIT(curc) && vim_isprintc(PTR2CHAR(rex.input));\n\t\tADD_STATE_IF_MATCH(t->state);\n\t\tbreak;\n\n\t case NFA_WHITE:\t// \\s\n\t\tresult = VIM_ISWHITE(curc);\n\t\tADD_STATE_IF_MATCH(t->state);\n\t\tbreak;\n\n\t case NFA_NWHITE:\t// \\S\n\t\tresult = curc != NUL && !VIM_ISWHITE(curc);\n\t\tADD_STATE_IF_MATCH(t->state);\n\t\tbreak;\n\n\t case NFA_DIGIT:\t// \\d\n\t\tresult = ri_digit(curc);\n\t\tADD_STATE_IF_MATCH(t->state);\n\t\tbreak;\n\n\t case NFA_NDIGIT:\t// \\D\n\t\tresult = curc != NUL && !ri_digit(curc);\n\t\tADD_STATE_IF_MATCH(t->state);\n\t\tbreak;\n\n\t case NFA_HEX:\t// \\x\n\t\tresult = ri_hex(curc);\n\t\tADD_STATE_IF_MATCH(t->state);\n\t\tbreak;\n\n\t case NFA_NHEX:\t// \\X\n\t\tresult = curc != NUL && !ri_hex(curc);\n\t\tADD_STATE_IF_MATCH(t->state);\n\t\tbreak;\n\n\t case NFA_OCTAL:\t// \\o\n\t\tresult = ri_octal(curc);\n\t\tADD_STATE_IF_MATCH(t->state);\n\t\tbreak;\n\n\t case NFA_NOCTAL:\t// \\O\n\t\tresult = curc != NUL && !ri_octal(curc);\n\t\tADD_STATE_IF_MATCH(t->state);\n\t\tbreak;\n\n\t case NFA_WORD:\t// \\w\n\t\tresult = ri_word(curc);\n\t\tADD_STATE_IF_MATCH(t->state);\n\t\tbreak;\n\n\t case NFA_NWORD:\t// \\W\n\t\tresult = curc != NUL && !ri_word(curc);\n\t\tADD_STATE_IF_MATCH(t->state);\n\t\tbreak;\n\n\t case NFA_HEAD:\t// \\h\n\t\tresult = ri_head(curc);\n\t\tADD_STATE_IF_MATCH(t->state);\n\t\tbreak;\n\n\t case NFA_NHEAD:\t// \\H\n\t\tresult = curc != NUL && !ri_head(curc);\n\t\tADD_STATE_IF_MATCH(t->state);\n\t\tbreak;\n\n\t case NFA_ALPHA:\t// \\a\n\t\tresult = ri_alpha(curc);\n\t\tADD_STATE_IF_MATCH(t->state);\n\t\tbreak;\n\n\t case NFA_NALPHA:\t// \\A\n\t\tresult = curc != NUL && !ri_alpha(curc);\n\t\tADD_STATE_IF_MATCH(t->state);\n\t\tbreak;\n\n\t case NFA_LOWER:\t// \\l\n\t\tresult = ri_lower(curc);\n\t\tADD_STATE_IF_MATCH(t->state);\n\t\tbreak;\n\n\t case NFA_NLOWER:\t// \\L\n\t\tresult = curc != NUL && !ri_lower(curc);\n\t\tADD_STATE_IF_MATCH(t->state);\n\t\tbreak;\n\n\t case NFA_UPPER:\t// \\u\n\t\tresult = ri_upper(curc);\n\t\tADD_STATE_IF_MATCH(t->state);\n\t\tbreak;\n\n\t case NFA_NUPPER:\t// \\U\n\t\tresult = curc != NUL && !ri_upper(curc);\n\t\tADD_STATE_IF_MATCH(t->state);\n\t\tbreak;\n\n\t case NFA_LOWER_IC:\t// [a-z]\n\t\tresult = ri_lower(curc) || (rex.reg_ic && ri_upper(curc));\n\t\tADD_STATE_IF_MATCH(t->state);\n\t\tbreak;\n\n\t case NFA_NLOWER_IC:\t// [^a-z]\n\t\tresult = curc != NUL\n\t\t\t&& !(ri_lower(curc) || (rex.reg_ic && ri_upper(curc)));\n\t\tADD_STATE_IF_MATCH(t->state);\n\t\tbreak;\n\n\t case NFA_UPPER_IC:\t// [A-Z]\n\t\tresult = ri_upper(curc) || (rex.reg_ic && ri_lower(curc));\n\t\tADD_STATE_IF_MATCH(t->state);\n\t\tbreak;\n\n\t case NFA_NUPPER_IC:\t// ^[A-Z]\n\t\tresult = curc != NUL\n\t\t\t&& !(ri_upper(curc) || (rex.reg_ic && ri_lower(curc)));\n\t\tADD_STATE_IF_MATCH(t->state);\n\t\tbreak;\n\n\t case NFA_BACKREF1:\n\t case NFA_BACKREF2:\n\t case NFA_BACKREF3:\n\t case NFA_BACKREF4:\n\t case NFA_BACKREF5:\n\t case NFA_BACKREF6:\n\t case NFA_BACKREF7:\n\t case NFA_BACKREF8:\n\t case NFA_BACKREF9:\n#ifdef FEAT_SYN_HL\n\t case NFA_ZREF1:\n\t case NFA_ZREF2:\n\t case NFA_ZREF3:\n\t case NFA_ZREF4:\n\t case NFA_ZREF5:\n\t case NFA_ZREF6:\n\t case NFA_ZREF7:\n\t case NFA_ZREF8:\n\t case NFA_ZREF9:\n#endif\n\t\t// \\1 .. \\9 \\z1 .. \\z9\n\t {\n\t\tint subidx;\n\t\tint bytelen;\n\n\t\tif (t->state->c <= NFA_BACKREF9)\n\t\t{\n\t\t subidx = t->state->c - NFA_BACKREF1 + 1;\n\t\t result = match_backref(&t->subs.norm, subidx, &bytelen);\n\t\t}\n#ifdef FEAT_SYN_HL\n\t\telse\n\t\t{\n\t\t subidx = t->state->c - NFA_ZREF1 + 1;\n\t\t result = match_zref(subidx, &bytelen);\n\t\t}\n#endif\n\n\t\tif (result)\n\t\t{\n\t\t if (bytelen == 0)\n\t\t {\n\t\t\t// empty match always works, output of NFA_SKIP to be\n\t\t\t// used next\n\t\t\tadd_here = TRUE;\n\t\t\tadd_state = t->state->out->out;\n\t\t }\n\t\t else if (bytelen <= clen)\n\t\t {\n\t\t\t// match current character, jump ahead to out of\n\t\t\t// NFA_SKIP\n\t\t\tadd_state = t->state->out->out;\n\t\t\tadd_off = clen;\n\t\t }\n\t\t else\n\t\t {\n\t\t\t// skip over the matched characters, set character\n\t\t\t// count in NFA_SKIP\n\t\t\tadd_state = t->state->out;\n\t\t\tadd_off = bytelen;\n\t\t\tadd_count = bytelen - clen;\n\t\t }\n\t\t}\n\t\tbreak;\n\t }\n\t case NFA_SKIP:\n\t // character of previous matching \\1 .. \\9 or \\@>\n\t if (t->count - clen <= 0)\n\t {\n\t\t // end of match, go to what follows\n\t\t add_state = t->state->out;\n\t\t add_off = clen;\n\t }\n\t else\n\t {\n\t\t // add state again with decremented count\n\t\t add_state = t->state;\n\t\t add_off = 0;\n\t\t add_count = t->count - clen;\n\t }\n\t break;\n\n\t case NFA_LNUM:\n\t case NFA_LNUM_GT:\n\t case NFA_LNUM_LT:\n\t\tresult = (REG_MULTI &&\n\t\t\tnfa_re_num_cmp(t->state->val, t->state->c - NFA_LNUM,\n\t\t\t (long_u)(rex.lnum + rex.reg_firstlnum)));\n\t\tif (result)\n\t\t{\n\t\t add_here = TRUE;\n\t\t add_state = t->state->out;\n\t\t}\n\t\tbreak;\n\n\t case NFA_COL:\n\t case NFA_COL_GT:\n\t case NFA_COL_LT:\n\t\tresult = nfa_re_num_cmp(t->state->val, t->state->c - NFA_COL,\n\t\t\t(long_u)(rex.input - rex.line) + 1);\n\t\tif (result)\n\t\t{\n\t\t add_here = TRUE;\n\t\t add_state = t->state->out;\n\t\t}\n\t\tbreak;\n\n\t case NFA_VCOL:\n\t case NFA_VCOL_GT:\n\t case NFA_VCOL_LT:\n\t\t{\n\t\t int op = t->state->c - NFA_VCOL;\n\t\t colnr_T col = (colnr_T)(rex.input - rex.line);\n\t\t win_T *wp = rex.reg_win == NULL ? curwin : rex.reg_win;\n\n\t\t // Bail out quickly when there can't be a match, avoid the\n\t\t // overhead of win_linetabsize() on long lines.\n\t\t if (op != 1 && col > t->state->val\n\t\t\t * (has_mbyte ? MB_MAXBYTES : 1))\n\t\t\tbreak;\n\t\t result = FALSE;\n\t\t if (op == 1 && col - 1 > t->state->val && col > 100)\n\t\t {\n\t\t\tint ts = wp->w_buffer->b_p_ts;\n\n\t\t\t// Guess that a character won't use more columns than\n\t\t\t// 'tabstop', with a minimum of 4.\n\t\t\tif (ts < 4)\n\t\t\t ts = 4;\n\t\t\tresult = col > t->state->val * ts;\n\t\t }\n\t\t if (!result)\n\t\t\tresult = nfa_re_num_cmp(t->state->val, op,\n\t\t\t\t(long_u)win_linetabsize(wp, rex.line, col) + 1);\n\t\t if (result)\n\t\t {\n\t\t\tadd_here = TRUE;\n\t\t\tadd_state = t->state->out;\n\t\t }\n\t\t}\n\t\tbreak;\n\n\t case NFA_MARK:\n\t case NFA_MARK_GT:\n\t case NFA_MARK_LT:\n\t {\n\t\tpos_T\t*pos = getmark_buf(rex.reg_buf, t->state->val, FALSE);\n\n\t\t// Compare the mark position to the match position, if the mark\n\t\t// exists and mark is set in reg_buf.\n\t\tif (pos != NULL && pos->lnum > 0)\n\t\t{\n\t\t colnr_T pos_col = pos->lnum == rex.lnum + rex.reg_firstlnum\n\t\t\t\t\t\t\t && pos->col == MAXCOL\n\t\t\t\t ? (colnr_T)STRLEN(reg_getline(\n\t\t\t\t\t\tpos->lnum - rex.reg_firstlnum))\n\t\t\t\t : pos->col;\n\n\t\t result = (pos->lnum == rex.lnum + rex.reg_firstlnum\n\t\t\t\t? (pos_col == (colnr_T)(rex.input - rex.line)\n\t\t\t\t ? t->state->c == NFA_MARK\n\t\t\t\t : (pos_col < (colnr_T)(rex.input - rex.line)\n\t\t\t\t\t? t->state->c == NFA_MARK_GT\n\t\t\t\t\t: t->state->c == NFA_MARK_LT))\n\t\t\t\t: (pos->lnum < rex.lnum + rex.reg_firstlnum\n\t\t\t\t ? t->state->c == NFA_MARK_GT\n\t\t\t\t : t->state->c == NFA_MARK_LT));\n\t\t if (result)\n\t\t {\n\t\t\tadd_here = TRUE;\n\t\t\tadd_state = t->state->out;\n\t\t }\n\t\t}\n\t\tbreak;\n\t }\n\n\t case NFA_CURSOR:\n\t\tresult = (rex.reg_win != NULL\n\t\t\t&& (rex.lnum + rex.reg_firstlnum\n\t\t\t\t\t\t == rex.reg_win->w_cursor.lnum)\n\t\t\t&& ((colnr_T)(rex.input - rex.line)\n\t\t\t\t\t\t== rex.reg_win->w_cursor.col));\n\t\tif (result)\n\t\t{\n\t\t add_here = TRUE;\n\t\t add_state = t->state->out;\n\t\t}\n\t\tbreak;\n\n\t case NFA_VISUAL:\n\t\tresult = reg_match_visual();\n\t\tif (result)\n\t\t{\n\t\t add_here = TRUE;\n\t\t add_state = t->state->out;\n\t\t}\n\t\tbreak;\n\n\t case NFA_MOPEN1:\n\t case NFA_MOPEN2:\n\t case NFA_MOPEN3:\n\t case NFA_MOPEN4:\n\t case NFA_MOPEN5:\n\t case NFA_MOPEN6:\n\t case NFA_MOPEN7:\n\t case NFA_MOPEN8:\n\t case NFA_MOPEN9:\n#ifdef FEAT_SYN_HL\n\t case NFA_ZOPEN:\n\t case NFA_ZOPEN1:\n\t case NFA_ZOPEN2:\n\t case NFA_ZOPEN3:\n\t case NFA_ZOPEN4:\n\t case NFA_ZOPEN5:\n\t case NFA_ZOPEN6:\n\t case NFA_ZOPEN7:\n\t case NFA_ZOPEN8:\n\t case NFA_ZOPEN9:\n#endif\n\t case NFA_NOPEN:\n\t case NFA_ZSTART:\n\t\t// These states are only added to be able to bail out when\n\t\t// they are added again, nothing is to be done.\n\t\tbreak;\n\n\t default:\t// regular character\n\t {\n\t\tint c = t->state->c;\n\n#ifdef DEBUG\n\t\tif (c < 0)\n\t\t siemsg(\"INTERNAL: Negative state char: %ld\", c);\n#endif\n\t\tresult = (c == curc);\n\n\t\tif (!result && rex.reg_ic)\n\t\t result = MB_CASEFOLD(c) == MB_CASEFOLD(curc);\n\t\t// If rex.reg_icombine is not set only skip over the character\n\t\t// itself. When it is set skip over composing characters.\n\t\tif (result && enc_utf8 && !rex.reg_icombine)\n\t\t clen = utf_ptr2len(rex.input);\n\t\tADD_STATE_IF_MATCH(t->state);\n\t\tbreak;\n\t }\n\n\t } // switch (t->state->c)\n\n\t if (add_state != NULL)\n\t {\n\t\tnfa_pim_T *pim;\n\t\tnfa_pim_T pim_copy;\n\n\t\tif (t->pim.result == NFA_PIM_UNUSED)\n\t\t pim = NULL;\n\t\telse\n\t\t pim = &t->pim;\n\n\t\t// Handle the postponed invisible match if the match might end\n\t\t// without advancing and before the end of the line.\n\t\tif (pim != NULL && (clen == 0 || match_follows(add_state, 0)))\n\t\t{\n\t\t if (pim->result == NFA_PIM_TODO)\n\t\t {\n#ifdef ENABLE_LOG\n\t\t\tfprintf(log_fd, \"\\n\");\n\t\t\tfprintf(log_fd, \"==================================\\n\");\n\t\t\tfprintf(log_fd, \"Postponed recursive nfa_regmatch()\\n\");\n\t\t\tfprintf(log_fd, \"\\n\");\n#endif\n\t\t\tresult = recursive_regmatch(pim->state, pim,\n\t\t\t\t prog, submatch, m, &listids, &listids_len);\n\t\t\tpim->result = result ? NFA_PIM_MATCH : NFA_PIM_NOMATCH;\n\t\t\t// for \\@! and \\@state->c == NFA_START_INVISIBLE_NEG\n\t\t\t || pim->state->c == NFA_START_INVISIBLE_NEG_FIRST\n\t\t\t || pim->state->c\n\t\t\t\t\t == NFA_START_INVISIBLE_BEFORE_NEG\n\t\t\t || pim->state->c\n\t\t\t\t == NFA_START_INVISIBLE_BEFORE_NEG_FIRST))\n\t\t\t{\n\t\t\t // Copy submatch info from the recursive call\n\t\t\t copy_sub_off(&pim->subs.norm, &m->norm);\n#ifdef FEAT_SYN_HL\n\t\t\t if (rex.nfa_has_zsubexpr)\n\t\t\t\tcopy_sub_off(&pim->subs.synt, &m->synt);\n#endif\n\t\t\t}\n\t\t }\n\t\t else\n\t\t {\n\t\t\tresult = (pim->result == NFA_PIM_MATCH);\n#ifdef ENABLE_LOG\n\t\t\tfprintf(log_fd, \"\\n\");\n\t\t\tfprintf(log_fd, \"Using previous recursive nfa_regmatch() result, result == %d\\n\", pim->result);\n\t\t\tfprintf(log_fd, \"MATCH = %s\\n\", result == TRUE ? \"OK\" : \"FALSE\");\n\t\t\tfprintf(log_fd, \"\\n\");\n#endif\n\t\t }\n\n\t\t // for \\@! and \\@state->c == NFA_START_INVISIBLE_NEG\n\t\t\t || pim->state->c == NFA_START_INVISIBLE_NEG_FIRST\n\t\t\t || pim->state->c\n\t\t\t\t\t == NFA_START_INVISIBLE_BEFORE_NEG\n\t\t\t || pim->state->c\n\t\t\t\t == NFA_START_INVISIBLE_BEFORE_NEG_FIRST))\n\t\t {\n\t\t\t// Copy submatch info from the recursive call\n\t\t\tcopy_sub_off(&t->subs.norm, &pim->subs.norm);\n#ifdef FEAT_SYN_HL\n\t\t\tif (rex.nfa_has_zsubexpr)\n\t\t\t copy_sub_off(&t->subs.synt, &pim->subs.synt);\n#endif\n\t\t }\n\t\t else\n\t\t\t// look-behind match failed, don't add the state\n\t\t\tcontinue;\n\n\t\t // Postponed invisible match was handled, don't add it to\n\t\t // following states.\n\t\t pim = NULL;\n\t\t}\n\n\t\t// If \"pim\" points into l->t it will become invalid when\n\t\t// adding the state causes the list to be reallocated. Make a\n\t\t// local copy to avoid that.\n\t\tif (pim == &t->pim)\n\t\t{\n\t\t copy_pim(&pim_copy, pim);\n\t\t pim = &pim_copy;\n\t\t}\n\n\t\tif (add_here)\n\t\t r = addstate_here(thislist, add_state, &t->subs,\n\t\t\t\t\t\t\t\tpim, &listidx);\n\t\telse\n\t\t{\n\t\t r = addstate(nextlist, add_state, &t->subs, pim, add_off);\n\t\t if (add_count > 0)\n\t\t\tnextlist->t[nextlist->n - 1].count = add_count;\n\t\t}\n\t\tif (r == NULL)\n\t\t{\n\t\t nfa_match = NFA_TOO_EXPENSIVE;\n\t\t goto theend;\n\t\t}\n\t }\n\n\t} // for (thislist = thislist; thislist->state; thislist++)\n\n\t// Look for the start of a match in the current position by adding the\n\t// start state to the list of states.\n\t// The first found match is the leftmost one, thus the order of states\n\t// matters!\n\t// Do not add the start state in recursive calls of nfa_regmatch(),\n\t// because recursive calls should only start in the first position.\n\t// Unless \"nfa_endp\" is not NULL, then we match the end position.\n\t// Also don't start a match past the first line.\n\tif (nfa_match == FALSE\n\t\t&& ((toplevel\n\t\t\t&& rex.lnum == 0\n\t\t\t&& clen != 0\n\t\t\t&& (rex.reg_maxcol == 0\n\t\t\t || (colnr_T)(rex.input - rex.line) < rex.reg_maxcol))\n\t\t || (nfa_endp != NULL\n\t\t\t&& (REG_MULTI\n\t\t\t ? (rex.lnum < nfa_endp->se_u.pos.lnum\n\t\t\t || (rex.lnum == nfa_endp->se_u.pos.lnum\n\t\t\t\t && (int)(rex.input - rex.line)\n\t\t\t\t\t\t < nfa_endp->se_u.pos.col))\n\t\t\t : rex.input < nfa_endp->se_u.ptr))))\n\t{\n#ifdef ENABLE_LOG\n\t fprintf(log_fd, \"(---) STARTSTATE\\n\");\n#endif\n\t // Inline optimized code for addstate() if we know the state is\n\t // the first MOPEN.\n\t if (toplevel)\n\t {\n\t\tint add = TRUE;\n\t\tint c;\n\n\t\tif (prog->regstart != NUL && clen != 0)\n\t\t{\n\t\t if (nextlist->n == 0)\n\t\t {\n\t\t\tcolnr_T col = (colnr_T)(rex.input - rex.line) + clen;\n\n\t\t\t// Nextlist is empty, we can skip ahead to the\n\t\t\t// character that must appear at the start.\n\t\t\tif (skip_to_start(prog->regstart, &col) == FAIL)\n\t\t\t break;\n#ifdef ENABLE_LOG\n\t\t\tfprintf(log_fd, \" Skipping ahead %d bytes to regstart\\n\",\n\t\t\t\tcol - ((colnr_T)(rex.input - rex.line) + clen));\n#endif\n\t\t\trex.input = rex.line + col - clen;\n\t\t }\n\t\t else\n\t\t {\n\t\t\t// Checking if the required start character matches is\n\t\t\t// cheaper than adding a state that won't match.\n\t\t\tc = PTR2CHAR(rex.input + clen);\n\t\t\tif (c != prog->regstart && (!rex.reg_ic\n\t\t\t || MB_CASEFOLD(c) != MB_CASEFOLD(prog->regstart)))\n\t\t\t{\n#ifdef ENABLE_LOG\n\t\t\t fprintf(log_fd, \" Skipping start state, regstart does not match\\n\");\n#endif\n\t\t\t add = FALSE;\n\t\t\t}\n\t\t }\n\t\t}\n\n\t\tif (add)\n\t\t{\n\t\t if (REG_MULTI)\n\t\t\tm->norm.list.multi[0].start_col =\n\t\t\t\t\t (colnr_T)(rex.input - rex.line) + clen;\n\t\t else\n\t\t\tm->norm.list.line[0].start = rex.input + clen;\n\t\t if (addstate(nextlist, start->out, m, NULL, clen) == NULL)\n\t\t {\n\t\t\tnfa_match = NFA_TOO_EXPENSIVE;\n\t\t\tgoto theend;\n\t\t }\n\t\t}\n\t }\n\t else\n\t {\n\t\tif (addstate(nextlist, start, m, NULL, clen) == NULL)\n\t\t{\n\t\t nfa_match = NFA_TOO_EXPENSIVE;\n\t\t goto theend;\n\t\t}\n\t }\n\t}\n\n#ifdef ENABLE_LOG\n\tfprintf(log_fd, \">>> Thislist had %d states available: \", thislist->n);\n\t{\n\t int i;\n\n\t for (i = 0; i < thislist->n; i++)\n\t\tfprintf(log_fd, \"%d \", abs(thislist->t[i].state->id));\n\t}\n\tfprintf(log_fd, \"\\n\");\n#endif\n\nnextchar:\n\t// Advance to the next character, or advance to the next line, or\n\t// finish.\n\tif (clen != 0)\n\t rex.input += clen;\n\telse if (go_to_nextline || (nfa_endp != NULL && REG_MULTI\n\t\t\t\t\t&& rex.lnum < nfa_endp->se_u.pos.lnum))\n\t reg_nextline();\n\telse\n\t break;\n\n\t// Allow interrupting with CTRL-C.\n\tline_breakcheck();\n\tif (got_int)\n\t break;\n#ifdef FEAT_RELTIME\n\t// Check for timeout once in a twenty times to avoid overhead.\n\tif (nfa_time_limit != NULL && ++nfa_time_count == 20)\n\t{\n\t nfa_time_count = 0;\n\t if (nfa_did_time_out())\n\t\tbreak;\n\t}\n#endif\n }\n\n#ifdef ENABLE_LOG\n if (log_fd != stderr)\n\tfclose(log_fd);\n log_fd = NULL;\n#endif\n\ntheend:\n // Free memory\n vim_free(list[0].t);\n vim_free(list[1].t);\n vim_free(listids);\n#undef ADD_STATE_IF_MATCH\n#ifdef NFA_REGEXP_DEBUG_LOG\n fclose(debug);\n#endif\n\n return nfa_match;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'patch 8.2.3612: using freed memory with regexp using a mark\n\nProblem: Using freed memory with regexp using a mark.\nSolution: Get the line again after getting the mark position.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int map_freeze(const union bpf_attr *attr)\n{\n\tint err = 0, ufd = attr->map_fd;\n\tstruct bpf_map *map;\n\tstruct fd f;\n\n\tif (CHECK_ATTR(BPF_MAP_FREEZE))\n\t\treturn -EINVAL;\n\n\tf = fdget(ufd);\n\tmap = __bpf_map_get(f);\n\tif (IS_ERR(map))\n\t\treturn PTR_ERR(map);\n\n\tif (map->map_type == BPF_MAP_TYPE_STRUCT_OPS ||\n\t map_value_has_timer(map)) {\n\t\tfdput(f);\n\t\treturn -ENOTSUPP;\n\t}\n\n\tmutex_lock(&map->freeze_mutex);\n\n\tif (map->writecnt) {\n\t\terr = -EBUSY;\n\t\tgoto err_put;\n\t}\n\tif (READ_ONCE(map->frozen)) {\n\t\terr = -EBUSY;\n\t\tgoto err_put;\n\t}\n\tif (!bpf_capable()) {\n\t\terr = -EPERM;\n\t\tgoto err_put;\n\t}\n\n\tWRITE_ONCE(map->frozen, true);\nerr_put:\n\tmutex_unlock(&map->freeze_mutex);\n\tfdput(f);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-367'], 'message': 'bpf: Fix toctou on read-only map's constant scalar tracking\n\nCommit a23740ec43ba (\"bpf: Track contents of read-only maps as scalars\") is\nchecking whether maps are read-only both from BPF program side and user space\nside, and then, given their content is constant, reading out their data via\nmap->ops->map_direct_value_addr() which is then subsequently used as known\nscalar value for the register, that is, it is marked as __mark_reg_known()\nwith the read value at verification time. Before a23740ec43ba, the register\ncontent was marked as an unknown scalar so the verifier could not make any\nassumptions about the map content.\n\nThe current implementation however is prone to a TOCTOU race, meaning, the\nvalue read as known scalar for the register is not guaranteed to be exactly\nthe same at a later point when the program is executed, and as such, the\nprior made assumptions of the verifier with regards to the program will be\ninvalid which can cause issues such as OOB access, etc.\n\nWhile the BPF_F_RDONLY_PROG map flag is always fixed and required to be\nspecified at map creation time, the map->frozen property is initially set to\nfalse for the map given the map value needs to be populated, e.g. for global\ndata sections. Once complete, the loader \"freezes\" the map from user space\nsuch that no subsequent updates/deletes are possible anymore. For the rest\nof the lifetime of the map, this freeze one-time trigger cannot be undone\nanymore after a successful BPF_MAP_FREEZE cmd return. Meaning, any new BPF_*\ncmd calls which would update/delete map entries will be rejected with -EPERM\nsince map_get_sys_perms() removes the FMODE_CAN_WRITE permission. This also\nmeans that pending update/delete map entries must still complete before this\nguarantee is given. This corner case is not an issue for loaders since they\ncreate and prepare such program private map in successive steps.\n\nHowever, a malicious user is able to trigger this TOCTOU race in two different\nways: i) via userfaultfd, and ii) via batched updates. For i) userfaultfd is\nused to expand the competition interval, so that map_update_elem() can modify\nthe contents of the map after map_freeze() and bpf_prog_load() were executed.\nThis works, because userfaultfd halts the parallel thread which triggered a\nmap_update_elem() at the time where we copy key/value from the user buffer and\nthis already passed the FMODE_CAN_WRITE capability test given at that time the\nmap was not \"frozen\". Then, the main thread performs the map_freeze() and\nbpf_prog_load(), and once that had completed successfully, the other thread\nis woken up to complete the pending map_update_elem() which then changes the\nmap content. For ii) the idea of the batched update is similar, meaning, when\nthere are a large number of updates to be processed, it can increase the\ncompetition interval between the two. It is therefore possible in practice to\nmodify the contents of the map after executing map_freeze() and bpf_prog_load().\n\nOne way to fix both i) and ii) at the same time is to expand the use of the\nmap's map->writecnt. The latter was introduced in fc9702273e2e (\"bpf: Add mmap()\nsupport for BPF_MAP_TYPE_ARRAY\") and further refined in 1f6cb19be2e2 (\"bpf:\nPrevent re-mmap()'ing BPF map as writable for initially r/o mapping\") with\nthe rationale to make a writable mmap()'ing of a map mutually exclusive with\nread-only freezing. The counter indicates writable mmap() mappings and then\nprevents/fails the freeze operation. Its semantics can be expanded beyond\njust mmap() by generally indicating ongoing write phases. This would essentially\nspan any parallel regular and batched flavor of update/delete operation and\nthen also have map_freeze() fail with -EBUSY. For the check_mem_access() in\nthe verifier we expand upon the bpf_map_is_rdonly() check ensuring that all\nlast pending writes have completed via bpf_map_write_active() test. Once the\nmap->frozen is set and bpf_map_write_active() indicates a map->writecnt of 0\nonly then we are really guaranteed to use the map's data as known constants.\nFor map->frozen being set and pending writes in process of still being completed\nwe fall back to marking that register as unknown scalar so we don't end up\nmaking assumptions about it. With this, both TOCTOU reproducers from i) and\nii) are fixed.\n\nNote that the map->writecnt has been converted into a atomic64 in the fix in\norder to avoid a double freeze_mutex mutex_{un,}lock() pair when updating\nmap->writecnt in the various map update/delete BPF_* cmd flavors. Spanning\nthe freeze_mutex over entire map update/delete operations in syscall side\nwould not be possible due to then causing everything to be serialized.\nSimilarly, something like synchronize_rcu() after setting map->frozen to wait\nfor update/deletes to complete is not possible either since it would also\nhave to span the user copy which can sleep. On the libbpf side, this won't\nbreak d66562fba1ce (\"libbpf: Add BPF object skeleton support\") as the\nanonymous mmap()-ed \"map initialization image\" is remapped as a BPF map-backed\nmmap()-ed memory where for .rodata it's non-writable.\n\nFixes: a23740ec43ba (\"bpf: Track contents of read-only maps as scalars\")\nReported-by: w1tcher.bupt@gmail.com\nSigned-off-by: Daniel Borkmann \nAcked-by: Andrii Nakryiko \nSigned-off-by: Alexei Starovoitov '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ex_open(exarg_T *eap)\n{\n regmatch_T\tregmatch;\n char_u\t*p;\n\n#ifdef FEAT_EVAL\n if (not_in_vim9(eap) == FAIL)\n\treturn;\n#endif\n curwin->w_cursor.lnum = eap->line2;\n beginline(BL_SOL | BL_FIX);\n if (*eap->arg == '/')\n {\n\t// \":open /pattern/\": put cursor in column found with pattern\n\t++eap->arg;\n\tp = skip_regexp(eap->arg, '/', magic_isset());\n\t*p = NUL;\n\tregmatch.regprog = vim_regcomp(eap->arg, magic_isset() ? RE_MAGIC : 0);\n\tif (regmatch.regprog != NULL)\n\t{\n\t regmatch.rm_ic = p_ic;\n\t p = ml_get_curline();\n\t if (vim_regexec(®match, p, (colnr_T)0))\n\t\tcurwin->w_cursor.col = (colnr_T)(regmatch.startp[0] - p);\n\t else\n\t\temsg(_(e_nomatch));\n\t vim_regfree(regmatch.regprog);\n\t}\n\t// Move to the NUL, ignore any other arguments.\n\teap->arg += STRLEN(eap->arg);\n }\n check_cursor();\n\n eap->cmdidx = CMD_visual;\n do_exedit(eap, NULL);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'patch 8.2.3741: using freed memory in open command\n\nProblem: Using freed memory in open command.\nSolution: Make a copy of the current line.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int unix_dgram_recvmsg(struct socket *sock, struct msghdr *msg,\n\t\t\t size_t size, int flags)\n{\n\tstruct scm_cookie scm;\n\tstruct sock *sk = sock->sk;\n\tstruct unix_sock *u = unix_sk(sk);\n\tstruct sk_buff *skb, *last;\n\tlong timeo;\n\tint skip;\n\tint err;\n\n\terr = -EOPNOTSUPP;\n\tif (flags&MSG_OOB)\n\t\tgoto out;\n\n\ttimeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);\n\n\tdo {\n\t\tmutex_lock(&u->iolock);\n\n\t\tskip = sk_peek_offset(sk, flags);\n\t\tskb = __skb_try_recv_datagram(sk, &sk->sk_receive_queue, flags,\n\t\t\t\t\t &skip, &err, &last);\n\t\tif (skb) {\n\t\t\tif (!(flags & MSG_PEEK))\n\t\t\t\tscm_stat_del(sk, skb);\n\t\t\tbreak;\n\t\t}\n\n\t\tmutex_unlock(&u->iolock);\n\n\t\tif (err != -EAGAIN)\n\t\t\tbreak;\n\t} while (timeo &&\n\t\t !__skb_wait_for_more_packets(sk, &sk->sk_receive_queue,\n\t\t\t\t\t &err, &timeo, last));\n\n\tif (!skb) { /* implies iolock unlocked */\n\t\tunix_state_lock(sk);\n\t\t/* Signal EOF on disconnected non-blocking SEQPACKET socket. */\n\t\tif (sk->sk_type == SOCK_SEQPACKET && err == -EAGAIN &&\n\t\t (sk->sk_shutdown & RCV_SHUTDOWN))\n\t\t\terr = 0;\n\t\tunix_state_unlock(sk);\n\t\tgoto out;\n\t}\n\n\tif (wq_has_sleeper(&u->peer_wait))\n\t\twake_up_interruptible_sync_poll(&u->peer_wait,\n\t\t\t\t\t\tEPOLLOUT | EPOLLWRNORM |\n\t\t\t\t\t\tEPOLLWRBAND);\n\n\tif (msg->msg_name)\n\t\tunix_copy_addr(msg, skb->sk);\n\n\tif (size > skb->len - skip)\n\t\tsize = skb->len - skip;\n\telse if (size < skb->len - skip)\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\n\terr = skb_copy_datagram_msg(skb, skip, msg, size);\n\tif (err)\n\t\tgoto out_free;\n\n\tif (sock_flag(sk, SOCK_RCVTSTAMP))\n\t\t__sock_recv_timestamp(msg, sk, skb);\n\n\tmemset(&scm, 0, sizeof(scm));\n\n\tscm_set_cred(&scm, UNIXCB(skb).pid, UNIXCB(skb).uid, UNIXCB(skb).gid);\n\tunix_set_secdata(&scm, skb);\n\n\tif (!(flags & MSG_PEEK)) {\n\t\tif (UNIXCB(skb).fp)\n\t\t\tunix_detach_fds(&scm, skb);\n\n\t\tsk_peek_offset_bwd(sk, skb->len);\n\t} else {\n\t\t/* It is questionable: on PEEK we could:\n\t\t - do not return fds - good, but too simple 8)\n\t\t - return fds, and do not return them on read (old strategy,\n\t\t apparently wrong)\n\t\t - clone fds (I chose it for now, it is the most universal\n\t\t solution)\n\n\t\t POSIX 1003.1g does not actually define this clearly\n\t\t at all. POSIX 1003.1g doesn't define a lot of things\n\t\t clearly however!\n\n\t\t*/\n\n\t\tsk_peek_offset_fwd(sk, size);\n\n\t\tif (UNIXCB(skb).fp)\n\t\t\tscm.fp = scm_fp_dup(UNIXCB(skb).fp);\n\t}\n\terr = (flags & MSG_TRUNC) ? skb->len - skip : size;\n\n\tscm_recv(sock, msg, &scm, flags);\n\nout_free:\n\tskb_free_datagram(sk, skb);\n\tmutex_unlock(&u->iolock);\nout:\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'af_unix: fix garbage collect vs MSG_PEEK\n\nunix_gc() assumes that candidate sockets can never gain an external\nreference (i.e. be installed into an fd) while the unix_gc_lock is\nheld. Except for MSG_PEEK this is guaranteed by modifying inflight\ncount under the unix_gc_lock.\n\nMSG_PEEK does not touch any variable protected by unix_gc_lock (file\ncount is not), yet it needs to be serialized with garbage collection.\nDo this by locking/unlocking unix_gc_lock:\n\n 1) increment file count\n\n 2) lock/unlock barrier to make sure incremented file count is visible\n to garbage collection\n\n 3) install file into fd\n\nThis is a lock barrier (unlike smp_mb()) that ensures that garbage\ncollection is run completely before or completely after the barrier.\n\nCc: \nSigned-off-by: Greg Kroah-Hartman \nSigned-off-by: Miklos Szeredi \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static uint32_t get_requirement_by_name(const char *requirement)\n{\n\tint i;\n\n\tfor (i = 0; requirements_flags[i].description; i++)\n\t\tif (!strcmp(requirement, requirements_flags[i].description))\n\t\t\treturn requirements_flags[i].flag;\n\n\treturn CRYPT_REQUIREMENT_UNKNOWN;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-345'], 'message': 'Fix CVE-2021-4122 - LUKS2 reencryption crash recovery attack\n\nFix possible attacks against data confidentiality through LUKS2 online\nreencryption extension crash recovery.\n\nAn attacker can modify on-disk metadata to simulate decryption in\nprogress with crashed (unfinished) reencryption step and persistently\ndecrypt part of the LUKS device.\n\nThis attack requires repeated physical access to the LUKS device but\nno knowledge of user passphrases.\n\nThe decryption step is performed after a valid user activates\nthe device with a correct passphrase and modified metadata.\nThere are no visible warnings for the user that such recovery happened\n(except using the luksDump command). The attack can also be reversed\nafterward (simulating crashed encryption from a plaintext) with\npossible modification of revealed plaintext.\n\nThe problem was caused by reusing a mechanism designed for actual\nreencryption operation without reassessing the security impact for new\nencryption and decryption operations. While the reencryption requires\ncalculating and verifying both key digests, no digest was needed to\ninitiate decryption recovery if the destination is plaintext (no\nencryption key). Also, some metadata (like encryption cipher) is not\nprotected, and an attacker could change it. Note that LUKS2 protects\nvisible metadata only when a random change occurs. It does not protect\nagainst intentional modification but such modification must not cause\na violation of data confidentiality.\n\nThe fix introduces additional digest protection of reencryption\nmetadata. The digest is calculated from known keys and critical\nreencryption metadata. Now an attacker cannot create correct metadata\ndigest without knowledge of a passphrase for used keyslots.\nFor more details, see LUKS2 On-Disk Format Specification version 1.1.0.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: libxlDomainEventHandler(void *data, libxl_event *event)\n{\n libxlDriverPrivate *driver = data;\n libxl_shutdown_reason xl_reason = event->u.domain_shutdown.shutdown_reason;\n virDomainObj *vm = NULL;\n g_autoptr(libxlDriverConfig) cfg = NULL;\n\n VIR_DEBUG(\"Received libxl event '%d' for domid '%d'\", event->type, event->domid);\n\n if (event->type != LIBXL_EVENT_TYPE_DOMAIN_SHUTDOWN &&\n event->type != LIBXL_EVENT_TYPE_DOMAIN_DEATH) {\n VIR_INFO(\"Unhandled event type %d\", event->type);\n goto cleanup;\n }\n\n /*\n * Similar to the xl implementation, ignore SUSPEND. Any actions needed\n * after calling libxl_domain_suspend() are handled by its callers.\n */\n if (xl_reason == LIBXL_SHUTDOWN_REASON_SUSPEND)\n goto cleanup;\n\n vm = virDomainObjListFindByID(driver->domains, event->domid);\n if (!vm) {\n /* Nothing to do if we can't find the virDomainObj */\n goto cleanup;\n }\n\n if (event->type == LIBXL_EVENT_TYPE_DOMAIN_SHUTDOWN) {\n libxlDomainObjPrivate *priv = vm->privateData;\n struct libxlShutdownThreadInfo *shutdown_info = NULL;\n virThread thread;\n g_autofree char *name = NULL;\n\n /*\n * Start a thread to handle shutdown. We don't want to be tying up\n * libxl's event machinery by doing a potentially lengthy shutdown.\n */\n shutdown_info = g_new0(struct libxlShutdownThreadInfo, 1);\n\n shutdown_info->driver = driver;\n shutdown_info->vm = vm;\n shutdown_info->event = (libxl_event *)event;\n name = g_strdup_printf(\"ev-%d\", event->domid);\n /*\n * Cleanup will be handled by the shutdown thread.\n * Ignore the forthcoming death event from libxl\n */\n priv->ignoreDeathEvent = true;\n if (virThreadCreateFull(&thread, false, libxlDomainShutdownThread,\n name, false, shutdown_info) < 0) {\n priv->ignoreDeathEvent = false;\n /*\n * Not much we can do on error here except log it.\n */\n VIR_ERROR(_(\"Failed to create thread to handle domain shutdown\"));\n VIR_FREE(shutdown_info);\n goto cleanup;\n }\n /*\n * virDomainObjEndAPI is called in the shutdown thread, where\n * libxlShutdownThreadInfo and libxl_event are also freed.\n */\n return;\n } else if (event->type == LIBXL_EVENT_TYPE_DOMAIN_DEATH) {\n /*\n * On death the domain is cleaned up from Xen's perspective.\n * Cleanup on the libvirt side can be done synchronously.\n */\n libxlDomainHandleDeath(driver, vm);\n }\n\n cleanup:\n virDomainObjEndAPI(&vm);\n cfg = libxlDriverConfigGet(driver);\n /* Cast away any const */\n libxl_event_free(cfg->ctx, (libxl_event *)event);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-667'], 'message': 'libxl: Disable death events after receiving a shutdown event\n\nThe libxl driver will handle all domain destruction and cleanup\nwhen receiving a domain shutdown event from libxl. Commit fa30ee04a2a\nintroduced the ignoreDeathEvent boolean in the DomainObjPrivate struct\nto ignore subsequent death events from libxl. But libxl already provides\na mechanism to disable death events via libxl_evdisable_domain_death.\n\nThis patch partially reverts commit fa30ee04a2a and instead uses\nlibxl_evdisable_domain_death to disable subsequent death events when\nprocessing a shutdown event.\n\nSigned-off-by: Jim Fehlig \nReviewed-by: Daniel P. Berrang\u00e9 \nReviewed-by: J\u00e1n Tomko '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: libxlLoggerNew(const char *logDir, virLogPriority minLevel)\n{\n xentoollog_logger_libvirt logger;\n g_autofree char *path = NULL;\n\n switch (minLevel) {\n case VIR_LOG_DEBUG:\n logger.minLevel = XTL_DEBUG;\n break;\n case VIR_LOG_INFO:\n logger.minLevel = XTL_INFO;\n break;\n case VIR_LOG_WARN:\n logger.minLevel = XTL_WARN;\n break;\n case VIR_LOG_ERROR:\n logger.minLevel = XTL_ERROR;\n break;\n }\n logger.logDir = logDir;\n\n path = g_strdup_printf(\"%s/libxl-driver.log\", logDir);\n\n if ((logger.defaultLogFile = fopen(path, \"a\")) == NULL)\n return NULL;\n\n logger.files = virHashNew(libxlLoggerFileFree);\n\n return XTL_NEW_LOGGER(libvirt, logger);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-667'], 'message': 'libxl: Protect access to libxlLogger files hash table\n\nThe hash table of log file objects in libxlLogger is not protected against\nconcurrent access. It is possible for one thread to remove an entry while\nanother is updating it. Add a mutex to the libxlLogger object and lock it\nwhen accessing the files hash table.\n\nSigned-off-by: Jim Fehlig \nReviewed-by: Daniel P. Berrang\u00e9 \nReviewed-by: J\u00e1n Tomko '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void addDbAdminAnyDbPrivileges(PrivilegeVector* privileges) {\n Privilege::addPrivilegeToPrivilegeVector(\n privileges, Privilege(ResourcePattern::forClusterResource(), ActionType::listDatabases));\n Privilege::addPrivilegeToPrivilegeVector(\n privileges, Privilege(ResourcePattern::forAnyNormalResource(), dbAdminRoleActions));\n ActionSet profileActions = readRoleActions;\n profileActions.addAction(ActionType::convertToCapped);\n profileActions.addAction(ActionType::createCollection);\n profileActions.addAction(ActionType::dropCollection);\n Privilege::addPrivilegeToPrivilegeVector(\n privileges,\n Privilege(ResourcePattern::forCollectionName(\"system.profile\"), profileActions));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'SERVER-36263 Bypassing operation validation in applyOps should require special privilege'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: compile_def_function(\n\tufunc_T\t\t*ufunc,\n\tint\t\tcheck_return_type,\n\tcompiletype_T compile_type,\n\tcctx_T\t\t*outer_cctx)\n{\n char_u\t*line = NULL;\n char_u\t*line_to_free = NULL;\n char_u\t*p;\n char\t*errormsg = NULL;\t// error message\n cctx_T\tcctx;\n garray_T\t*instr;\n int\t\tdid_emsg_before = did_emsg;\n int\t\tdid_emsg_silent_before = did_emsg_silent;\n int\t\tret = FAIL;\n sctx_T\tsave_current_sctx = current_sctx;\n int\t\tsave_estack_compiling = estack_compiling;\n int\t\tsave_cmod_flags = cmdmod.cmod_flags;\n int\t\tdo_estack_push;\n int\t\tnew_def_function = FALSE;\n#ifdef FEAT_PROFILE\n int\t\tprof_lnum = -1;\n#endif\n int\t\tdebug_lnum = -1;\n\n // When using a function that was compiled before: Free old instructions.\n // The index is reused. Otherwise add a new entry in \"def_functions\".\n if (ufunc->uf_dfunc_idx > 0)\n {\n\tdfunc_T *dfunc = ((dfunc_T *)def_functions.ga_data)\n\t\t\t\t\t\t\t + ufunc->uf_dfunc_idx;\n\tisn_T\t*instr_dest = NULL;\n\n\tswitch (compile_type)\n\t{\n\t case CT_PROFILE:\n#ifdef FEAT_PROFILE\n\t\t\t instr_dest = dfunc->df_instr_prof; break;\n#endif\n\t case CT_NONE: instr_dest = dfunc->df_instr; break;\n\t case CT_DEBUG: instr_dest = dfunc->df_instr_debug; break;\n\t}\n\tif (instr_dest != NULL)\n\t // Was compiled in this mode before: Free old instructions.\n\t delete_def_function_contents(dfunc, FALSE);\n\tga_clear_strings(&dfunc->df_var_names);\n }\n else\n {\n\tif (add_def_function(ufunc) == FAIL)\n\t return FAIL;\n\tnew_def_function = TRUE;\n }\n\n ufunc->uf_def_status = UF_COMPILING;\n\n CLEAR_FIELD(cctx);\n\n cctx.ctx_compile_type = compile_type;\n cctx.ctx_ufunc = ufunc;\n cctx.ctx_lnum = -1;\n cctx.ctx_outer = outer_cctx;\n ga_init2(&cctx.ctx_locals, sizeof(lvar_T), 10);\n ga_init2(&cctx.ctx_type_stack, sizeof(type_T *), 50);\n ga_init2(&cctx.ctx_imports, sizeof(imported_T), 10);\n cctx.ctx_type_list = &ufunc->uf_type_list;\n ga_init2(&cctx.ctx_instr, sizeof(isn_T), 50);\n instr = &cctx.ctx_instr;\n\n // Set the context to the function, it may be compiled when called from\n // another script. Set the script version to the most modern one.\n // The line number will be set in next_line_from_context().\n current_sctx = ufunc->uf_script_ctx;\n current_sctx.sc_version = SCRIPT_VERSION_VIM9;\n\n // Don't use the flag from \":legacy\" here.\n cmdmod.cmod_flags &= ~CMOD_LEGACY;\n\n // Make sure error messages are OK.\n do_estack_push = !estack_top_is_ufunc(ufunc, 1);\n if (do_estack_push)\n\testack_push_ufunc(ufunc, 1);\n estack_compiling = TRUE;\n\n if (ufunc->uf_def_args.ga_len > 0)\n {\n\tint\tcount = ufunc->uf_def_args.ga_len;\n\tint\tfirst_def_arg = ufunc->uf_args.ga_len - count;\n\tint\ti;\n\tchar_u\t*arg;\n\tint\toff = STACK_FRAME_SIZE + (ufunc->uf_va_name != NULL ? 1 : 0);\n\tint\tdid_set_arg_type = FALSE;\n\n\t// Produce instructions for the default values of optional arguments.\n\tSOURCING_LNUM = 0; // line number unknown\n\tfor (i = 0; i < count; ++i)\n\t{\n\t garray_T\t*stack = &cctx.ctx_type_stack;\n\t type_T\t*val_type;\n\t int\t\targ_idx = first_def_arg + i;\n\t where_T\twhere = WHERE_INIT;\n\t int\t\tr;\n\t int\t\tjump_instr_idx = instr->ga_len;\n\t isn_T\t*isn;\n\n\t // Use a JUMP_IF_ARG_SET instruction to skip if the value was given.\n\t if (generate_JUMP_IF_ARG_SET(&cctx, i - count - off) == FAIL)\n\t\tgoto erret;\n\n\t // Make sure later arguments are not found.\n\t ufunc->uf_args_visible = arg_idx;\n\n\t arg = ((char_u **)(ufunc->uf_def_args.ga_data))[i];\n\t r = compile_expr0(&arg, &cctx);\n\n\t if (r == FAIL)\n\t\tgoto erret;\n\n\t // If no type specified use the type of the default value.\n\t // Otherwise check that the default value type matches the\n\t // specified type.\n\t val_type = ((type_T **)stack->ga_data)[stack->ga_len - 1];\n\t where.wt_index = arg_idx + 1;\n\t if (ufunc->uf_arg_types[arg_idx] == &t_unknown)\n\t {\n\t\tdid_set_arg_type = TRUE;\n\t\tufunc->uf_arg_types[arg_idx] = val_type;\n\t }\n\t else if (need_type_where(val_type, ufunc->uf_arg_types[arg_idx],\n\t\t\t\t -1, where, &cctx, FALSE, FALSE) == FAIL)\n\t\tgoto erret;\n\n\t if (generate_STORE(&cctx, ISN_STORE, i - count - off, NULL) == FAIL)\n\t\tgoto erret;\n\n\t // set instruction index in JUMP_IF_ARG_SET to here\n\t isn = ((isn_T *)instr->ga_data) + jump_instr_idx;\n\t isn->isn_arg.jumparg.jump_where = instr->ga_len;\n\t}\n\n\tif (did_set_arg_type)\n\t set_function_type(ufunc);\n }\n ufunc->uf_args_visible = ufunc->uf_args.ga_len;\n\n /*\n * Loop over all the lines of the function and generate instructions.\n */\n for (;;)\n {\n\texarg_T\t ea;\n\tint\t starts_with_colon = FALSE;\n\tchar_u\t *cmd;\n\tcmdmod_T local_cmdmod;\n\n\t// Bail out on the first error to avoid a flood of errors and report\n\t// the right line number when inside try/catch.\n\tif (did_emsg_before != did_emsg)\n\t goto erret;\n\n\tif (line != NULL && *line == '|')\n\t // the line continues after a '|'\n\t ++line;\n\telse if (line != NULL && *skipwhite(line) != NUL\n\t\t&& !(*line == '#' && (line == cctx.ctx_line_start\n\t\t\t\t\t\t || VIM_ISWHITE(line[-1]))))\n\t{\n\t semsg(_(e_trailing_arg), line);\n\t goto erret;\n\t}\n\telse if (line != NULL && vim9_bad_comment(skipwhite(line)))\n\t goto erret;\n\telse\n\t{\n\t line = next_line_from_context(&cctx, FALSE);\n\t if (cctx.ctx_lnum >= ufunc->uf_lines.ga_len)\n\t {\n\t\t// beyond the last line\n#ifdef FEAT_PROFILE\n\t\tif (cctx.ctx_skip != SKIP_YES)\n\t\t may_generate_prof_end(&cctx, prof_lnum);\n#endif\n\t\tbreak;\n\t }\n\t // Make a copy, splitting off nextcmd and removing trailing spaces\n\t // may change it.\n\t if (line != NULL)\n\t {\n\t\tline = vim_strsave(line);\n\t\tvim_free(line_to_free);\n\t\tline_to_free = line;\n\t }\n\t}\n\n\tCLEAR_FIELD(ea);\n\tea.cmdlinep = &line;\n\tea.cmd = skipwhite(line);\n\n\tif (*ea.cmd == '#')\n\t{\n\t // \"#\" starts a comment\n\t line = (char_u *)\"\";\n\t continue;\n\t}\n\n#ifdef FEAT_PROFILE\n\tif (cctx.ctx_compile_type == CT_PROFILE && cctx.ctx_lnum != prof_lnum\n\t\t\t\t\t\t && cctx.ctx_skip != SKIP_YES)\n\t{\n\t may_generate_prof_end(&cctx, prof_lnum);\n\n\t prof_lnum = cctx.ctx_lnum;\n\t generate_instr(&cctx, ISN_PROF_START);\n\t}\n#endif\n\tif (cctx.ctx_compile_type == CT_DEBUG && cctx.ctx_lnum != debug_lnum\n\t\t\t\t\t\t && cctx.ctx_skip != SKIP_YES)\n\t{\n\t debug_lnum = cctx.ctx_lnum;\n\t generate_instr_debug(&cctx);\n\t}\n\tcctx.ctx_prev_lnum = cctx.ctx_lnum + 1;\n\n\t// Some things can be recognized by the first character.\n\tswitch (*ea.cmd)\n\t{\n\t case '}':\n\t\t{\n\t\t // \"}\" ends a block scope\n\t\t scopetype_T stype = cctx.ctx_scope == NULL\n\t\t\t\t\t ? NO_SCOPE : cctx.ctx_scope->se_type;\n\n\t\t if (stype == BLOCK_SCOPE)\n\t\t {\n\t\t\tcompile_endblock(&cctx);\n\t\t\tline = ea.cmd;\n\t\t }\n\t\t else\n\t\t {\n\t\t\temsg(_(e_using_rcurly_outside_if_block_scope));\n\t\t\tgoto erret;\n\t\t }\n\t\t if (line != NULL)\n\t\t\tline = skipwhite(ea.cmd + 1);\n\t\t continue;\n\t\t}\n\n\t case '{':\n\t\t// \"{\" starts a block scope\n\t\t// \"{'a': 1}->func() is something else\n\t\tif (ends_excmd(*skipwhite(ea.cmd + 1)))\n\t\t{\n\t\t line = compile_block(ea.cmd, &cctx);\n\t\t continue;\n\t\t}\n\t\tbreak;\n\t}\n\n\t/*\n\t * COMMAND MODIFIERS\n\t */\n\tcctx.ctx_has_cmdmod = FALSE;\n\tif (parse_command_modifiers(&ea, &errormsg, &local_cmdmod, FALSE)\n\t\t\t\t\t\t\t\t == FAIL)\n\t{\n\t if (errormsg != NULL)\n\t\tgoto erret;\n\t // empty line or comment\n\t line = (char_u *)\"\";\n\t continue;\n\t}\n\tgenerate_cmdmods(&cctx, &local_cmdmod);\n\tundo_cmdmod(&local_cmdmod);\n\n\t// Check if there was a colon after the last command modifier or before\n\t// the current position.\n\tfor (p = ea.cmd; p >= line; --p)\n\t{\n\t if (*p == ':')\n\t\tstarts_with_colon = TRUE;\n\t if (p < ea.cmd && !VIM_ISWHITE(*p))\n\t\tbreak;\n\t}\n\n\t// Skip \":call\" to get to the function name, unless using :legacy\n\tp = ea.cmd;\n\tif (!(local_cmdmod.cmod_flags & CMOD_LEGACY))\n\t{\n\t if (checkforcmd(&ea.cmd, \"call\", 3))\n\t {\n\t\tif (*ea.cmd == '(')\n\t\t // not for \"call()\"\n\t\t ea.cmd = p;\n\t\telse\n\t\t ea.cmd = skipwhite(ea.cmd);\n\t }\n\n\t if (!starts_with_colon)\n\t {\n\t\tint\t assign;\n\n\t\t// Check for assignment after command modifiers.\n\t\tassign = may_compile_assignment(&ea, &line, &cctx);\n\t\tif (assign == OK)\n\t\t goto nextline;\n\t\tif (assign == FAIL)\n\t\t goto erret;\n\t }\n\t}\n\n\t/*\n\t * COMMAND after range\n\t * 'text'->func() should not be confused with 'a mark\n\t * \"++nr\" and \"--nr\" are eval commands\n\t * in \"$ENV->func()\" the \"$\" is not a range\n\t */\n\tcmd = ea.cmd;\n\tif ((*cmd != '$' || starts_with_colon)\n\t\t&& (starts_with_colon || !(*cmd == '\\''\n\t\t || (cmd[0] == cmd[1] && (*cmd == '+' || *cmd == '-')))))\n\t{\n\t ea.cmd = skip_range(ea.cmd, TRUE, NULL);\n\t if (ea.cmd > cmd)\n\t {\n\t\tif (!starts_with_colon\n\t\t\t\t && !(local_cmdmod.cmod_flags & CMOD_LEGACY))\n\t\t{\n\t\t semsg(_(e_colon_required_before_range_str), cmd);\n\t\t goto erret;\n\t\t}\n\t\tea.addr_count = 1;\n\t\tif (ends_excmd2(line, ea.cmd))\n\t\t{\n\t\t // A range without a command: jump to the line.\n\t\t generate_EXEC(&cctx, ISN_EXECRANGE,\n\t\t\t\t\t vim_strnsave(cmd, ea.cmd - cmd));\n\t\t line = ea.cmd;\n\t\t goto nextline;\n\t\t}\n\t }\n\t}\n\tp = find_ex_command(&ea, NULL,\n\t\tstarts_with_colon || (local_cmdmod.cmod_flags & CMOD_LEGACY)\n\t\t\t\t\t\t ? NULL : item_exists, &cctx);\n\n\tif (p == NULL)\n\t{\n\t if (cctx.ctx_skip != SKIP_YES)\n\t\temsg(_(e_ambiguous_use_of_user_defined_command));\n\t goto erret;\n\t}\n\n\t// When using \":legacy cmd\" always use compile_exec().\n\tif (local_cmdmod.cmod_flags & CMOD_LEGACY)\n\t{\n\t char_u *start = ea.cmd;\n\n\t switch (ea.cmdidx)\n\t {\n\t\tcase CMD_if:\n\t\tcase CMD_elseif:\n\t\tcase CMD_else:\n\t\tcase CMD_endif:\n\t\tcase CMD_for:\n\t\tcase CMD_endfor:\n\t\tcase CMD_continue:\n\t\tcase CMD_break:\n\t\tcase CMD_while:\n\t\tcase CMD_endwhile:\n\t\tcase CMD_try:\n\t\tcase CMD_catch:\n\t\tcase CMD_finally:\n\t\tcase CMD_endtry:\n\t\t\tsemsg(_(e_cannot_use_legacy_with_command_str), ea.cmd);\n\t\t\tgoto erret;\n\t\tdefault: break;\n\t }\n\n\t // \":legacy return expr\" needs to be handled differently.\n\t if (checkforcmd(&start, \"return\", 4))\n\t\tea.cmdidx = CMD_return;\n\t else\n\t\tea.cmdidx = CMD_legacy;\n\t}\n\n\tif (p == ea.cmd && ea.cmdidx != CMD_SIZE)\n\t{\n\t if (cctx.ctx_skip == SKIP_YES && ea.cmdidx != CMD_eval)\n\t {\n\t\tline += STRLEN(line);\n\t\tgoto nextline;\n\t }\n\t else if (ea.cmdidx != CMD_eval)\n\t {\n\t\t// CMD_var cannot happen, compile_assignment() above would be\n\t\t// used. Most likely an assignment to a non-existing variable.\n\t\tsemsg(_(e_command_not_recognized_str), ea.cmd);\n\t\tgoto erret;\n\t }\n\t}\n\n\tif (cctx.ctx_had_return\n\t\t&& ea.cmdidx != CMD_elseif\n\t\t&& ea.cmdidx != CMD_else\n\t\t&& ea.cmdidx != CMD_endif\n\t\t&& ea.cmdidx != CMD_endfor\n\t\t&& ea.cmdidx != CMD_endwhile\n\t\t&& ea.cmdidx != CMD_catch\n\t\t&& ea.cmdidx != CMD_finally\n\t\t&& ea.cmdidx != CMD_endtry)\n\t{\n\t emsg(_(e_unreachable_code_after_return));\n\t goto erret;\n\t}\n\n\tp = skipwhite(p);\n\tif (ea.cmdidx != CMD_SIZE\n\t\t\t && ea.cmdidx != CMD_write && ea.cmdidx != CMD_read)\n\t{\n\t if (ea.cmdidx >= 0)\n\t\tea.argt = excmd_get_argt(ea.cmdidx);\n\t if ((ea.argt & EX_BANG) && *p == '!')\n\t {\n\t\tea.forceit = TRUE;\n\t\tp = skipwhite(p + 1);\n\t }\n\t}\n\n\tswitch (ea.cmdidx)\n\t{\n\t case CMD_def:\n\t case CMD_function:\n\t\t ea.arg = p;\n\t\t line = compile_nested_function(&ea, &cctx);\n\t\t break;\n\n\t case CMD_return:\n\t\t line = compile_return(p, check_return_type,\n\t\t\t\t local_cmdmod.cmod_flags & CMOD_LEGACY, &cctx);\n\t\t cctx.ctx_had_return = TRUE;\n\t\t break;\n\n\t case CMD_let:\n\t\t emsg(_(e_cannot_use_let_in_vim9_script));\n\t\t break;\n\t case CMD_var:\n\t case CMD_final:\n\t case CMD_const:\n\t case CMD_increment:\n\t case CMD_decrement:\n\t\t line = compile_assignment(p, &ea, ea.cmdidx, &cctx);\n\t\t if (line == p)\n\t\t\tline = NULL;\n\t\t break;\n\n\t case CMD_unlet:\n\t case CMD_unlockvar:\n\t case CMD_lockvar:\n\t\t line = compile_unletlock(p, &ea, &cctx);\n\t\t break;\n\n\t case CMD_import:\n\t\t emsg(_(e_import_can_only_be_used_in_script));\n\t\t line = NULL;\n\t\t break;\n\n\t case CMD_if:\n\t\t line = compile_if(p, &cctx);\n\t\t break;\n\t case CMD_elseif:\n\t\t line = compile_elseif(p, &cctx);\n\t\t cctx.ctx_had_return = FALSE;\n\t\t break;\n\t case CMD_else:\n\t\t line = compile_else(p, &cctx);\n\t\t cctx.ctx_had_return = FALSE;\n\t\t break;\n\t case CMD_endif:\n\t\t line = compile_endif(p, &cctx);\n\t\t break;\n\n\t case CMD_while:\n\t\t line = compile_while(p, &cctx);\n\t\t break;\n\t case CMD_endwhile:\n\t\t line = compile_endwhile(p, &cctx);\n\t\t cctx.ctx_had_return = FALSE;\n\t\t break;\n\n\t case CMD_for:\n\t\t line = compile_for(p, &cctx);\n\t\t break;\n\t case CMD_endfor:\n\t\t line = compile_endfor(p, &cctx);\n\t\t cctx.ctx_had_return = FALSE;\n\t\t break;\n\t case CMD_continue:\n\t\t line = compile_continue(p, &cctx);\n\t\t break;\n\t case CMD_break:\n\t\t line = compile_break(p, &cctx);\n\t\t break;\n\n\t case CMD_try:\n\t\t line = compile_try(p, &cctx);\n\t\t break;\n\t case CMD_catch:\n\t\t line = compile_catch(p, &cctx);\n\t\t cctx.ctx_had_return = FALSE;\n\t\t break;\n\t case CMD_finally:\n\t\t line = compile_finally(p, &cctx);\n\t\t cctx.ctx_had_return = FALSE;\n\t\t break;\n\t case CMD_endtry:\n\t\t line = compile_endtry(p, &cctx);\n\t\t cctx.ctx_had_return = FALSE;\n\t\t break;\n\t case CMD_throw:\n\t\t line = compile_throw(p, &cctx);\n\t\t break;\n\n\t case CMD_eval:\n\t\t line = compile_eval(p, &cctx);\n\t\t break;\n\n\t case CMD_echo:\n\t case CMD_echon:\n\t case CMD_execute:\n\t case CMD_echomsg:\n\t case CMD_echoerr:\n\t case CMD_echoconsole:\n\t\t line = compile_mult_expr(p, ea.cmdidx, &cctx);\n\t\t break;\n\n\t case CMD_put:\n\t\t ea.cmd = cmd;\n\t\t line = compile_put(p, &ea, &cctx);\n\t\t break;\n\n\t case CMD_substitute:\n\t\t if (check_global_and_subst(ea.cmd, p) == FAIL)\n\t\t\tgoto erret;\n\t\t if (cctx.ctx_skip == SKIP_YES)\n\t\t\tline = (char_u *)\"\";\n\t\t else\n\t\t {\n\t\t\tea.arg = p;\n\t\t\tline = compile_substitute(line, &ea, &cctx);\n\t\t }\n\t\t break;\n\n\t case CMD_redir:\n\t\t ea.arg = p;\n\t\t line = compile_redir(line, &ea, &cctx);\n\t\t break;\n\n\t case CMD_cexpr:\n\t case CMD_lexpr:\n\t case CMD_caddexpr:\n\t case CMD_laddexpr:\n\t case CMD_cgetexpr:\n\t case CMD_lgetexpr:\n#ifdef FEAT_QUICKFIX\n\t\t ea.arg = p;\n\t\t line = compile_cexpr(line, &ea, &cctx);\n#else\n\t\t ex_ni(&ea);\n\t\t line = NULL;\n#endif\n\t\t break;\n\n\t case CMD_append:\n\t case CMD_change:\n\t case CMD_insert:\n\t case CMD_k:\n\t case CMD_t:\n\t case CMD_xit:\n\t\t not_in_vim9(&ea);\n\t\t goto erret;\n\n\t case CMD_SIZE:\n\t\t if (cctx.ctx_skip != SKIP_YES)\n\t\t {\n\t\t\tsemsg(_(e_invalid_command_str), ea.cmd);\n\t\t\tgoto erret;\n\t\t }\n\t\t // We don't check for a next command here.\n\t\t line = (char_u *)\"\";\n\t\t break;\n\n\t case CMD_lua:\n\t case CMD_mzscheme:\n\t case CMD_perl:\n\t case CMD_py3:\n\t case CMD_python3:\n\t case CMD_python:\n\t case CMD_pythonx:\n\t case CMD_ruby:\n\t case CMD_tcl:\n\t\t ea.arg = p;\n\t\t if (vim_strchr(line, '\\n') == NULL)\n\t\t\tline = compile_exec(line, &ea, &cctx);\n\t\t else\n\t\t\t// heredoc lines have been concatenated with NL\n\t\t\t// characters in get_function_body()\n\t\t\tline = compile_script(line, &cctx);\n\t\t break;\n\n\t case CMD_global:\n\t\t if (check_global_and_subst(ea.cmd, p) == FAIL)\n\t\t\tgoto erret;\n\t\t // FALLTHROUGH\n\t default:\n\t\t // Not recognized, execute with do_cmdline_cmd().\n\t\t ea.arg = p;\n\t\t line = compile_exec(line, &ea, &cctx);\n\t\t break;\n\t}\nnextline:\n\tif (line == NULL)\n\t goto erret;\n\tline = skipwhite(line);\n\n\t// Undo any command modifiers.\n\tgenerate_undo_cmdmods(&cctx);\n\n\tif (cctx.ctx_type_stack.ga_len < 0)\n\t{\n\t iemsg(\"Type stack underflow\");\n\t goto erret;\n\t}\n }\n\n if (cctx.ctx_scope != NULL)\n {\n\tif (cctx.ctx_scope->se_type == IF_SCOPE)\n\t emsg(_(e_endif));\n\telse if (cctx.ctx_scope->se_type == WHILE_SCOPE)\n\t emsg(_(e_endwhile));\n\telse if (cctx.ctx_scope->se_type == FOR_SCOPE)\n\t emsg(_(e_endfor));\n\telse\n\t emsg(_(e_missing_rcurly));\n\tgoto erret;\n }\n\n if (!cctx.ctx_had_return)\n {\n\tif (ufunc->uf_ret_type->tt_type == VAR_UNKNOWN)\n\t ufunc->uf_ret_type = &t_void;\n\telse if (ufunc->uf_ret_type->tt_type != VAR_VOID)\n\t{\n\t emsg(_(e_missing_return_statement));\n\t goto erret;\n\t}\n\n\t// Return void if there is no return at the end.\n\tgenerate_instr(&cctx, ISN_RETURN_VOID);\n }\n\n // When compiled with \":silent!\" and there was an error don't consider the\n // function compiled.\n if (emsg_silent == 0 || did_emsg_silent == did_emsg_silent_before)\n {\n\tdfunc_T\t*dfunc = ((dfunc_T *)def_functions.ga_data)\n\t\t\t\t\t\t\t + ufunc->uf_dfunc_idx;\n\tdfunc->df_deleted = FALSE;\n\tdfunc->df_script_seq = current_sctx.sc_seq;\n#ifdef FEAT_PROFILE\n\tif (cctx.ctx_compile_type == CT_PROFILE)\n\t{\n\t dfunc->df_instr_prof = instr->ga_data;\n\t dfunc->df_instr_prof_count = instr->ga_len;\n\t}\n\telse\n#endif\n\tif (cctx.ctx_compile_type == CT_DEBUG)\n\t{\n\t dfunc->df_instr_debug = instr->ga_data;\n\t dfunc->df_instr_debug_count = instr->ga_len;\n\t}\n\telse\n\t{\n\t dfunc->df_instr = instr->ga_data;\n\t dfunc->df_instr_count = instr->ga_len;\n\t}\n\tdfunc->df_varcount = dfunc->df_var_names.ga_len;\n\tdfunc->df_has_closure = cctx.ctx_has_closure;\n\tif (cctx.ctx_outer_used)\n\t ufunc->uf_flags |= FC_CLOSURE;\n\tufunc->uf_def_status = UF_COMPILED;\n }\n\n ret = OK;\n\nerret:\n if (ufunc->uf_def_status == UF_COMPILING)\n {\n\tdfunc_T\t*dfunc = ((dfunc_T *)def_functions.ga_data)\n\t\t\t\t\t\t\t + ufunc->uf_dfunc_idx;\n\n\t// Compiling aborted, free the generated instructions.\n\tclear_instr_ga(instr);\n\tVIM_CLEAR(dfunc->df_name);\n\tga_clear_strings(&dfunc->df_var_names);\n\n\t// If using the last entry in the table and it was added above, we\n\t// might as well remove it.\n\tif (!dfunc->df_deleted && new_def_function\n\t\t\t && ufunc->uf_dfunc_idx == def_functions.ga_len - 1)\n\t{\n\t --def_functions.ga_len;\n\t ufunc->uf_dfunc_idx = 0;\n\t}\n\tufunc->uf_def_status = UF_COMPILE_ERROR;\n\n\twhile (cctx.ctx_scope != NULL)\n\t drop_scope(&cctx);\n\n\tif (errormsg != NULL)\n\t emsg(errormsg);\n\telse if (did_emsg == did_emsg_before)\n\t emsg(_(e_compiling_def_function_failed));\n }\n\n if (cctx.ctx_redir_lhs.lhs_name != NULL)\n {\n\tif (ret == OK)\n\t{\n\t emsg(_(e_missing_redir_end));\n\t ret = FAIL;\n\t}\n\tvim_free(cctx.ctx_redir_lhs.lhs_name);\n\tvim_free(cctx.ctx_redir_lhs.lhs_whole);\n }\n\n current_sctx = save_current_sctx;\n estack_compiling = save_estack_compiling;\n cmdmod.cmod_flags =\tsave_cmod_flags;\n if (do_estack_push)\n\testack_pop();\n\n vim_free(line_to_free);\n free_imported(&cctx);\n free_locals(&cctx);\n ga_clear(&cctx.ctx_type_stack);\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'patch 8.2.3902: Vim9: double free with nested :def function\n\nProblem: Vim9: double free with nested :def function.\nSolution: Pass \"line_to_free\" from compile_def_function() and make sure\n cmdlinep is valid.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int bond_ipsec_add_sa(struct xfrm_state *xs)\n{\n\tstruct net_device *bond_dev = xs->xso.dev;\n\tstruct bonding *bond;\n\tstruct slave *slave;\n\tint err;\n\n\tif (!bond_dev)\n\t\treturn -EINVAL;\n\n\trcu_read_lock();\n\tbond = netdev_priv(bond_dev);\n\tslave = rcu_dereference(bond->curr_active_slave);\n\txs->xso.real_dev = slave->dev;\n\tbond->xs = xs;\n\n\tif (!(slave->dev->xfrmdev_ops\n\t && slave->dev->xfrmdev_ops->xdo_dev_state_add)) {\n\t\tslave_warn(bond_dev, slave->dev, \"Slave does not support ipsec offload\\n\");\n\t\trcu_read_unlock();\n\t\treturn -EINVAL;\n\t}\n\n\terr = slave->dev->xfrmdev_ops->xdo_dev_state_add(xs);\n\trcu_read_unlock();\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-703'], 'message': 'bonding: fix null dereference in bond_ipsec_add_sa()\n\nIf bond doesn't have real device, bond->curr_active_slave is null.\nBut bond_ipsec_add_sa() dereferences bond->curr_active_slave without\nnull checking.\nSo, null-ptr-deref would occur.\n\nTest commands:\n ip link add bond0 type bond\n ip link set bond0 up\n ip x s add proto esp dst 14.1.1.1 src 15.1.1.1 spi \\\n0x07 mode transport reqid 0x07 replay-window 32 aead 'rfc4106(gcm(aes))' \\\n0x44434241343332312423222114131211f4f3f2f1 128 sel src 14.0.0.52/24 \\\ndst 14.0.0.70/24 proto tcp offload dev bond0 dir in\n\nSplat looks like:\nKASAN: null-ptr-deref in range [0x0000000000000000-0x0000000000000007]\nCPU: 4 PID: 680 Comm: ip Not tainted 5.13.0-rc3+ #1168\nRIP: 0010:bond_ipsec_add_sa+0xc4/0x2e0 [bonding]\nCode: 85 21 02 00 00 4d 8b a6 48 0c 00 00 e8 75 58 44 ce 85 c0 0f 85 14\n01 00 00 48 b8 00 00 00 00 00 fc ff df 4c 89 e2 48 c1 ea 03 <80> 3c 02\n00 0f 85 fc 01 00 00 48 8d bb e0 02 00 00 4d 8b 2c 24 48\nRSP: 0018:ffff88810946f508 EFLAGS: 00010246\nRAX: dffffc0000000000 RBX: ffff88810b4e8040 RCX: 0000000000000001\nRDX: 0000000000000000 RSI: ffffffff8fe34280 RDI: ffff888115abe100\nRBP: ffff88810946f528 R08: 0000000000000003 R09: fffffbfff2287e11\nR10: 0000000000000001 R11: ffff888115abe0c8 R12: 0000000000000000\nR13: ffffffffc0aea9a0 R14: ffff88800d7d2000 R15: ffff88810b4e8330\nFS: 00007efc5552e680(0000) GS:ffff888119c00000(0000)\nknlGS:0000000000000000\nCS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033\nCR2: 000055c2530dbf40 CR3: 0000000103056004 CR4: 00000000003706e0\nDR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000\nDR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400\nCall Trace:\n xfrm_dev_state_add+0x2a9/0x770\n ? memcpy+0x38/0x60\n xfrm_add_sa+0x2278/0x3b10 [xfrm_user]\n ? xfrm_get_policy+0xaa0/0xaa0 [xfrm_user]\n ? register_lock_class+0x1750/0x1750\n xfrm_user_rcv_msg+0x331/0x660 [xfrm_user]\n ? rcu_read_lock_sched_held+0x91/0xc0\n ? xfrm_user_state_lookup.constprop.39+0x320/0x320 [xfrm_user]\n ? find_held_lock+0x3a/0x1c0\n ? mutex_lock_io_nested+0x1210/0x1210\n ? sched_clock_cpu+0x18/0x170\n netlink_rcv_skb+0x121/0x350\n ? xfrm_user_state_lookup.constprop.39+0x320/0x320 [xfrm_user]\n ? netlink_ack+0x9d0/0x9d0\n ? netlink_deliver_tap+0x17c/0xa50\n xfrm_netlink_rcv+0x68/0x80 [xfrm_user]\n netlink_unicast+0x41c/0x610\n ? netlink_attachskb+0x710/0x710\n netlink_sendmsg+0x6b9/0xb70\n[ ...]\n\nFixes: 18cb261afd7b (\"bonding: support hardware encryption offload to slaves\")\nSigned-off-by: Taehee Yoo \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: \nstatic void kvm_invalidate_memslot(struct kvm *kvm,\n\t\t\t\t struct kvm_memory_slot *old,\n\t\t\t\t struct kvm_memory_slot *invalid_slot)\n{\n\t/*\n\t * Mark the current slot INVALID. As with all memslot modifications,\n\t * this must be done on an unreachable slot to avoid modifying the\n\t * current slot in the active tree.\n\t */\n\tkvm_copy_memslot(invalid_slot, old);\n\tinvalid_slot->flags |= KVM_MEMSLOT_INVALID;\n\tkvm_replace_memslot(kvm, old, invalid_slot);\n\n\t/*\n\t * Activate the slot that is now marked INVALID, but don't propagate\n\t * the slot to the now inactive slots. The slot is either going to be\n\t * deleted or recreated as a new slot.\n\t */\n\tkvm_swap_active_memslots(kvm, old->as_id);\n\n\t/*\n\t * From this point no new shadow pages pointing to a deleted, or moved,\n\t * memslot will be created. Validation of sp->gfn happens in:\n\t *\t- gfn_to_hva (kvm_read_guest, gfn_to_pfn)\n\t *\t- kvm_is_visible_gfn (mmu_check_root)\n\t */\n\tkvm_arch_flush_shadow_memslot(kvm, old);\n\n\t/* Was released by kvm_swap_active_memslots, reacquire. */\n\tmutex_lock(&kvm->slots_arch_lock);\n\n\t/*\n\t * Copy the arch-specific field of the newly-installed slot back to the\n\t * old slot as the arch data could have changed between releasing\n\t * slots_arch_lock in install_new_memslots() and re-acquiring the lock\n\t * above. Writers are required to retrieve memslots *after* acquiring\n\t * slots_arch_lock, thus the active slot's data is guaranteed to be fresh.\n\t */\n\told->arch = invalid_slot->arch; ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-459'], 'message': 'KVM: SEV: add cache flush to solve SEV cache incoherency issues\n\nFlush the CPU caches when memory is reclaimed from an SEV guest (where\nreclaim also includes it being unmapped from KVM's memslots). Due to lack\nof coherency for SEV encrypted memory, failure to flush results in silent\ndata corruption if userspace is malicious/broken and doesn't ensure SEV\nguest memory is properly pinned and unpinned.\n\nCache coherency is not enforced across the VM boundary in SEV (AMD APM\nvol.2 Section 15.34.7). Confidential cachelines, generated by confidential\nVM guests have to be explicitly flushed on the host side. If a memory page\ncontaining dirty confidential cachelines was released by VM and reallocated\nto another user, the cachelines may corrupt the new user at a later time.\n\nKVM takes a shortcut by assuming all confidential memory remain pinned\nuntil the end of VM lifetime. Therefore, KVM does not flush cache at\nmmu_notifier invalidation events. Because of this incorrect assumption and\nthe lack of cache flushing, malicous userspace can crash the host kernel:\ncreating a malicious VM and continuously allocates/releases unpinned\nconfidential memory pages when the VM is running.\n\nAdd cache flush operations to mmu_notifier operations to ensure that any\nphysical memory leaving the guest VM get flushed. In particular, hook\nmmu_notifier_invalidate_range_start and mmu_notifier_release events and\nflush cache accordingly. The hook after releasing the mmu lock to avoid\ncontention with other vCPUs.\n\nCc: stable@vger.kernel.org\nSuggested-by: Sean Christpherson \nReported-by: Mingwei Zhang \nSigned-off-by: Mingwei Zhang \nMessage-Id: <20220421031407.2516575-4-mizhang@google.com>\nSigned-off-by: Paolo Bonzini '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: get_function_args(\n char_u\t**argp,\n char_u\tendchar,\n garray_T\t*newargs,\n garray_T\t*argtypes,\t// NULL unless using :def\n int\t\ttypes_optional,\t// types optional if \"argtypes\" is not NULL\n evalarg_T\t*evalarg,\t// context or NULL\n int\t\t*varargs,\n garray_T\t*default_args,\n int\t\tskip,\n exarg_T\t*eap,\n char_u\t**line_to_free)\n{\n int\t\tmustend = FALSE;\n char_u\t*arg;\n char_u\t*p;\n int\t\tc;\n int\t\tany_default = FALSE;\n char_u\t*expr;\n char_u\t*whitep = *argp;\n\n if (newargs != NULL)\n\tga_init2(newargs, (int)sizeof(char_u *), 3);\n if (argtypes != NULL)\n\tga_init2(argtypes, (int)sizeof(char_u *), 3);\n if (!skip && default_args != NULL)\n\tga_init2(default_args, (int)sizeof(char_u *), 3);\n\n if (varargs != NULL)\n\t*varargs = FALSE;\n\n /*\n * Isolate the arguments: \"arg1, arg2, ...)\"\n */\n arg = skipwhite(*argp);\n p = arg;\n while (*p != endchar)\n {\n\twhile (eap != NULL && eap->getline != NULL\n\t\t\t && (*p == NUL || (VIM_ISWHITE(*whitep) && *p == '#')))\n\t{\n\t // End of the line, get the next one.\n\t char_u *theline = get_function_line(eap, line_to_free, 0,\n\t\t\t\t\t\t\t GETLINE_CONCAT_CONT);\n\n\t if (theline == NULL)\n\t\tbreak;\n\t whitep = (char_u *)\" \";\n\t p = skipwhite(theline);\n\t}\n\n\tif (mustend && *p != endchar)\n\t{\n\t if (!skip)\n\t\tsemsg(_(e_invalid_argument_str), *argp);\n\t goto err_ret;\n\t}\n\tif (*p == endchar)\n\t break;\n\n\tif (p[0] == '.' && p[1] == '.' && p[2] == '.')\n\t{\n\t if (varargs != NULL)\n\t\t*varargs = TRUE;\n\t p += 3;\n\t mustend = TRUE;\n\n\t if (argtypes != NULL)\n\t {\n\t\t// ...name: list\n\t\tif (!eval_isnamec1(*p))\n\t\t{\n\t\t if (!skip)\n\t\t\temsg(_(e_missing_name_after_dots));\n\t\t goto err_ret;\n\t\t}\n\n\t\targ = p;\n\t\tp = one_function_arg(p, newargs, argtypes, types_optional,\n\t\t\t\t\t\t\t evalarg, TRUE, skip);\n\t\tif (p == arg)\n\t\t break;\n\t\tif (*skipwhite(p) == '=')\n\t\t{\n\t\t emsg(_(e_cannot_use_default_for_variable_arguments));\n\t\t break;\n\t\t}\n\t }\n\t}\n\telse\n\t{\n\t char_u *np;\n\n\t arg = p;\n\t p = one_function_arg(p, newargs, argtypes, types_optional,\n\t\t\t\t\t\t\t evalarg, FALSE, skip);\n\t if (p == arg)\n\t\tbreak;\n\n\t // Recognize \" = expr\" but not \" == expr\". A lambda can have\n\t // \"(a = expr\" but \"(a == expr\" and \"(a =~ expr\" are not a lambda.\n\t np = skipwhite(p);\n\t if (*np == '=' && np[1] != '=' && np[1] != '~'\n\t\t\t\t\t\t && default_args != NULL)\n\t {\n\t\ttypval_T\trettv;\n\n\t\t// find the end of the expression (doesn't evaluate it)\n\t\tany_default = TRUE;\n\t\tp = skipwhite(p) + 1;\n\t\twhitep = p;\n\t\tp = skipwhite(p);\n\t\texpr = p;\n\t\tif (eval1(&p, &rettv, NULL) != FAIL)\n\t\t{\n\t\t if (!skip)\n\t\t {\n\t\t\tif (ga_grow(default_args, 1) == FAIL)\n\t\t\t goto err_ret;\n\n\t\t\t// trim trailing whitespace\n\t\t\twhile (p > expr && VIM_ISWHITE(p[-1]))\n\t\t\t p--;\n\t\t\tc = *p;\n\t\t\t*p = NUL;\n\t\t\texpr = vim_strsave(expr);\n\t\t\tif (expr == NULL)\n\t\t\t{\n\t\t\t *p = c;\n\t\t\t goto err_ret;\n\t\t\t}\n\t\t\t((char_u **)(default_args->ga_data))\n\t\t\t\t\t\t [default_args->ga_len] = expr;\n\t\t\tdefault_args->ga_len++;\n\t\t\t*p = c;\n\t\t }\n\t\t}\n\t\telse\n\t\t mustend = TRUE;\n\t }\n\t else if (any_default)\n\t {\n\t\temsg(_(e_non_default_argument_follows_default_argument));\n\t\tgoto err_ret;\n\t }\n\n\t if (VIM_ISWHITE(*p) && *skipwhite(p) == ',')\n\t {\n\t\t// Be tolerant when skipping\n\t\tif (!skip)\n\t\t{\n\t\t semsg(_(e_no_white_space_allowed_before_str_str), \",\", p);\n\t\t goto err_ret;\n\t\t}\n\t\tp = skipwhite(p);\n\t }\n\t if (*p == ',')\n\t {\n\t\t++p;\n\t\t// Don't give this error when skipping, it makes the \"->\" not\n\t\t// found in \"{k,v -> x}\" and give a confusing error.\n\t\t// Allow missing space after comma in legacy functions.\n\t\tif (!skip && argtypes != NULL\n\t\t\t\t && !IS_WHITE_OR_NUL(*p) && *p != endchar)\n\t\t{\n\t\t semsg(_(e_white_space_required_after_str_str), \",\", p - 1);\n\t\t goto err_ret;\n\t\t}\n\t }\n\t else\n\t\tmustend = TRUE;\n\t}\n\twhitep = p;\n\tp = skipwhite(p);\n }\n\n if (*p != endchar)\n\tgoto err_ret;\n ++p;\t// skip \"endchar\"\n\n *argp = p;\n return OK;\n\nerr_ret:\n if (newargs != NULL)\n\tga_clear_strings(newargs);\n if (!skip && default_args != NULL)\n\tga_clear_strings(default_args);\n return FAIL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'patch 8.2.4040: keeping track of allocated lines is too complicated\n\nProblem: Keeping track of allocated lines in user functions is too\n complicated.\nSolution: Instead of freeing individual lines keep them all until the end.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ga_add_string(garray_T *gap, char_u *p)\n{\n char_u *cp = vim_strsave(p);\n\n if (cp == NULL)\n\treturn FAIL;\n\n if (ga_grow(gap, 1) == FAIL)\n {\n\tvim_free(cp);\n\treturn FAIL;\n }\n ((char_u **)(gap->ga_data))[gap->ga_len++] = cp;\n return OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'patch 8.2.4040: keeping track of allocated lines is too complicated\n\nProblem: Keeping track of allocated lines in user functions is too\n complicated.\nSolution: Instead of freeing individual lines keep them all until the end.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: byte* decode_base64(char* src,size_t ssize, size_t *ret_len)\n{\n byte* outbuf;\n byte* retbuf;\n char* inb;\n int i;\n int l;\n int left;\n int pos;\n unsigned long triple;\n\n /* Exit on empty input */\n if (!ssize||src==NULL) {\n log_msg(LOG_LEVEL_DEBUG, \"decode base64: empty string\");\n return NULL;\n }\n\n\n /* Initialize working pointers */\n inb = src;\n outbuf = (byte *)checked_malloc(sizeof(byte)*B64_BUF);\n\n l = 0;\n triple = 0;\n pos=0;\n left = ssize;\n /*\n * Process entire inbuf.\n */\n while (left != 0)\n {\n left--;\n i = fromb64[(unsigned char)*inb];\n switch(i)\n\t{\n\tcase FAIL:\n\t log_msg(LOG_LEVEL_WARNING, \"decode_base64: illegal character: '%c' in '%s'\", *inb, src);\n\t free(outbuf);\n\t return NULL;\n\t break;\n\tcase SKIP:\n\t break;\n\tdefault:\n\t triple = triple<<6 | (0x3f & i);\n\t l++;\n\t break;\n\t}\n if (l == 4 || left == 0)\n\t{\n\t switch(l)\n\t {\n\t case 2:\n\t triple = triple>>4;\n\t break;\n\t case 3:\n\t triple = triple>>2;\n\t break;\n\t default:\n\t break;\n\t }\n\t for (l -= 2; l >= 0; l--)\n\t {\n\t outbuf[pos]=( 0xff & (triple>>(l*8)));\n\t pos++;\n\t }\n\t triple = 0;\n\t l = 0;\n\t}\n inb++;\n }\n \n retbuf=(byte*)checked_malloc(sizeof(byte)*(pos+1));\n memcpy(retbuf,outbuf,pos);\n retbuf[pos]='\\0';\n \n free(outbuf);\n\n if (ret_len) *ret_len = pos;\n \n return retbuf;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Precalculate buffer size in base64 functions\n\nAide uses a fixed size (16k bytes) for the return buffer in\nencode_base64/decode_base64 functions. This results in a segfault if\naide processes a file with too large extended attribute value or ACL.\n\nFix this issue by precalculating the size of the return buffer depending on\nthe input in the encode_base64/decode_base64 functions.\n\nThis addresses CVE-2021-45417. Thanks to David Bouman for reporting this\nvulnerability and reviewing this patch.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int wrap_nettle_hash_fast(gnutls_digest_algorithm_t algo,\n\t\t\t\t const void *text, size_t text_size,\n\t\t\t\t void *digest)\n{\n\tstruct nettle_hash_ctx ctx;\n\tint ret;\n\n\tret = _ctx_init(algo, &ctx);\n\tif (ret < 0)\n\t\treturn gnutls_assert_val(ret);\n\n\tctx.update(&ctx, text_size, text);\n\tctx.digest(&ctx, ctx.length, digest);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'wrap_nettle_hash_fast: avoid calling _update with zero-length input\n\nAs Nettle's hash update functions internally call memcpy, providing\nzero-length input may cause undefined behavior.\n\nSigned-off-by: Daiki Ueno '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static MagickBooleanType WritePICONImage(const ImageInfo *image_info,\n Image *image,ExceptionInfo *exception)\n{\n#define ColormapExtent 155\n#define GraymapExtent 95\n#define PiconGeometry \"48x48>\"\n\n static unsigned char\n Colormap[]=\n {\n 0x47, 0x49, 0x46, 0x38, 0x37, 0x61, 0x06, 0x00, 0x05, 0x00, 0xf4, 0x05,\n 0x00, 0x00, 0x00, 0x00, 0x2f, 0x4f, 0x4f, 0x70, 0x80, 0x90, 0x7e, 0x7e,\n 0x7e, 0xdc, 0xdc, 0xdc, 0xff, 0xff, 0xff, 0x00, 0x00, 0x80, 0x00, 0x00,\n 0xff, 0x1e, 0x90, 0xff, 0x87, 0xce, 0xeb, 0xe6, 0xe6, 0xfa, 0x00, 0xff,\n 0xff, 0x80, 0x00, 0x80, 0xb2, 0x22, 0x22, 0x2e, 0x8b, 0x57, 0x32, 0xcd,\n 0x32, 0x00, 0xff, 0x00, 0x98, 0xfb, 0x98, 0xff, 0x00, 0xff, 0xff, 0x00,\n 0x00, 0xff, 0x63, 0x47, 0xff, 0xa5, 0x00, 0xff, 0xd7, 0x00, 0xff, 0xff,\n 0x00, 0xee, 0x82, 0xee, 0xa0, 0x52, 0x2d, 0xcd, 0x85, 0x3f, 0xd2, 0xb4,\n 0x8c, 0xf5, 0xde, 0xb3, 0xff, 0xfa, 0xcd, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x21, 0xf9, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00,\n 0x00, 0x00, 0x06, 0x00, 0x05, 0x00, 0x00, 0x05, 0x18, 0x20, 0x10, 0x08,\n 0x03, 0x51, 0x18, 0x07, 0x92, 0x28, 0x0b, 0xd3, 0x38, 0x0f, 0x14, 0x49,\n 0x13, 0x55, 0x59, 0x17, 0x96, 0x69, 0x1b, 0xd7, 0x85, 0x00, 0x3b,\n },\n Graymap[]=\n {\n 0x47, 0x49, 0x46, 0x38, 0x37, 0x61, 0x04, 0x00, 0x04, 0x00, 0xf3, 0x0f,\n 0x00, 0x00, 0x00, 0x00, 0x12, 0x12, 0x12, 0x21, 0x21, 0x21, 0x33, 0x33,\n 0x33, 0x45, 0x45, 0x45, 0x54, 0x54, 0x54, 0x66, 0x66, 0x66, 0x78, 0x78,\n 0x78, 0x87, 0x87, 0x87, 0x99, 0x99, 0x99, 0xab, 0xab, 0xab, 0xba, 0xba,\n 0xba, 0xcc, 0xcc, 0xcc, 0xde, 0xde, 0xde, 0xed, 0xed, 0xed, 0xff, 0xff,\n 0xff, 0x21, 0xf9, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00,\n 0x00, 0x00, 0x04, 0x00, 0x04, 0x00, 0x00, 0x04, 0x0c, 0x10, 0x04, 0x31,\n 0x48, 0x31, 0x07, 0x25, 0xb5, 0x58, 0x73, 0x4f, 0x04, 0x00, 0x3b,\n };\n\n#define MaxCixels 92\n\n static const char\n Cixel[MaxCixels+1] = \" .XoO+@#$%&*=-;:>,<1234567890qwertyuipasdfghjk\"\n \"lzxcvbnmMNBVCZASDFGHJKLPIUYTREWQ!~^/()_`'][{}|\";\n\n char\n buffer[MagickPathExtent],\n basename[MagickPathExtent],\n name[MagickPathExtent],\n symbol[MagickPathExtent];\n\n Image\n *affinity_image,\n *picon;\n\n ImageInfo\n *blob_info;\n\n MagickBooleanType\n status,\n transparent;\n\n PixelInfo\n pixel;\n\n QuantizeInfo\n *quantize_info;\n\n RectangleInfo\n geometry;\n\n const Quantum\n *p;\n\n ssize_t\n i,\n x;\n\n Quantum\n *q;\n\n size_t\n characters_per_pixel,\n colors;\n\n ssize_t\n j,\n k,\n y;\n\n /*\n Open output image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);\n if (status == MagickFalse)\n return(status);\n if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)\n (void) TransformImageColorspace(image,sRGBColorspace,exception);\n SetGeometry(image,&geometry);\n (void) ParseMetaGeometry(PiconGeometry,&geometry.x,&geometry.y,\n &geometry.width,&geometry.height);\n picon=ResizeImage(image,geometry.width,geometry.height,TriangleFilter,\n exception);\n blob_info=CloneImageInfo(image_info);\n *blob_info->magick='\\0';\n (void) AcquireUniqueFilename(blob_info->filename);\n if ((image_info->type != TrueColorType) &&\n (IdentifyImageCoderGray(image,exception) != MagickFalse))\n affinity_image=BlobToImage(blob_info,Graymap,GraymapExtent,exception);\n else\n affinity_image=BlobToImage(blob_info,Colormap,ColormapExtent,exception);\n (void) RelinquishUniqueFileResource(blob_info->filename);\n blob_info=DestroyImageInfo(blob_info);\n if ((picon == (Image *) NULL) || (affinity_image == (Image *) NULL))\n {\n if (affinity_image != (Image *) NULL)\n affinity_image=DestroyImage(affinity_image);\n if (picon != (Image *) NULL)\n picon=DestroyImage(picon);\n return(MagickFalse);\n }\n quantize_info=AcquireQuantizeInfo(image_info);\n status=RemapImage(quantize_info,picon,affinity_image,exception);\n quantize_info=DestroyQuantizeInfo(quantize_info);\n affinity_image=DestroyImage(affinity_image);\n transparent=MagickFalse;\n if (picon->storage_class == PseudoClass)\n {\n (void) CompressImageColormap(picon,exception);\n if (picon->alpha_trait != UndefinedPixelTrait)\n transparent=MagickTrue;\n }\n else\n {\n /*\n Convert DirectClass to PseudoClass picon.\n */\n if (picon->alpha_trait != UndefinedPixelTrait)\n {\n /*\n Map all the transparent pixels.\n */\n for (y=0; y < (ssize_t) picon->rows; y++)\n {\n q=GetAuthenticPixels(picon,0,y,picon->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) picon->columns; x++)\n {\n if (GetPixelAlpha(image,q) == (Quantum) TransparentAlpha)\n transparent=MagickTrue;\n else\n SetPixelAlpha(picon,OpaqueAlpha,q);\n q+=GetPixelChannels(picon);\n }\n if (SyncAuthenticPixels(picon,exception) == MagickFalse)\n break;\n }\n }\n (void) SetImageType(picon,PaletteType,exception);\n }\n colors=picon->colors;\n if (transparent != MagickFalse)\n {\n colors++;\n picon->colormap=(PixelInfo *) ResizeQuantumMemory((void **)\n picon->colormap,(size_t) colors,sizeof(*picon->colormap));\n if (picon->colormap == (PixelInfo *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationError\");\n picon->colormap[colors-1].red=0.0;\n picon->colormap[colors-1].green=0.0;\n picon->colormap[colors-1].blue=0.0;\n picon->colormap[colors-1].alpha=TransparentAlpha;\n for (y=0; y < (ssize_t) picon->rows; y++)\n {\n q=GetAuthenticPixels(picon,0,y,picon->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) picon->columns; x++)\n {\n if (GetPixelAlpha(image,q) == (Quantum) TransparentAlpha)\n SetPixelIndex(picon,(Quantum) picon->colors,q);\n q+=GetPixelChannels(picon);\n }\n if (SyncAuthenticPixels(picon,exception) == MagickFalse)\n break;\n }\n }\n /*\n Compute the character per pixel.\n */\n characters_per_pixel=1;\n for (k=MaxCixels; (ssize_t) colors > k; k*=MaxCixels)\n characters_per_pixel++;\n /*\n XPM header.\n */\n (void) WriteBlobString(image,\"/* XPM */\\n\");\n GetPathComponent(picon->filename,BasePath,basename);\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"static const char *%.1024s[] = {\\n\",basename);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"/* columns rows colors chars-per-pixel */\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"\\\"%.20g %.20g %.20g %.20g\\\",\\n\",(double) picon->columns,(double)\n picon->rows,(double) colors,(double) characters_per_pixel);\n (void) WriteBlobString(image,buffer);\n GetPixelInfo(image,&pixel);\n for (i=0; i < (ssize_t) colors; i++)\n {\n /*\n Define XPM color.\n */\n pixel=picon->colormap[i];\n pixel.colorspace=sRGBColorspace;\n pixel.depth=8;\n pixel.alpha=(double) OpaqueAlpha;\n (void) QueryColorname(image,&pixel,XPMCompliance,name,exception);\n if (transparent != MagickFalse)\n {\n if (i == (ssize_t) (colors-1))\n (void) CopyMagickString(name,\"grey75\",MagickPathExtent);\n }\n /*\n Write XPM color.\n */\n k=i % MaxCixels;\n symbol[0]=Cixel[k];\n for (j=1; j < (ssize_t) characters_per_pixel; j++)\n {\n k=((i-k)/MaxCixels) % MaxCixels;\n symbol[j]=Cixel[k];\n }\n symbol[j]='\\0';\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"\\\"%.1024s c %.1024s\\\",\\n\",symbol,name);\n (void) WriteBlobString(image,buffer);\n }\n /*\n Define XPM pixels.\n */\n (void) WriteBlobString(image,\"/* pixels */\\n\");\n for (y=0; y < (ssize_t) picon->rows; y++)\n {\n p=GetVirtualPixels(picon,0,y,picon->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n (void) WriteBlobString(image,\"\\\"\");\n for (x=0; x < (ssize_t) picon->columns; x++)\n {\n k=((ssize_t) GetPixelIndex(picon,p) % MaxCixels);\n symbol[0]=Cixel[k];\n for (j=1; j < (ssize_t) characters_per_pixel; j++)\n {\n k=(((int) GetPixelIndex(picon,p)-k)/MaxCixels) % MaxCixels;\n symbol[j]=Cixel[k];\n }\n symbol[j]='\\0';\n (void) CopyMagickString(buffer,symbol,MagickPathExtent);\n (void) WriteBlobString(image,buffer);\n p+=GetPixelChannels(picon);\n }\n (void) FormatLocaleString(buffer,MagickPathExtent,\"\\\"%.1024s\\n\",\n y == (ssize_t) (picon->rows-1) ? \"\" : \",\");\n (void) WriteBlobString(image,buffer);\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n picon->rows);\n if (status == MagickFalse)\n break;\n }\n picon=DestroyImage(picon);\n (void) WriteBlobString(image,\"};\\n\");\n (void) CloseBlob(image);\n return(MagickTrue);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/4729'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ex_substitute(exarg_T *eap)\n{\n linenr_T\tlnum;\n long\ti = 0;\n regmmatch_T regmatch;\n static subflags_T subflags = {FALSE, FALSE, FALSE, TRUE, FALSE,\n\t\t\t\t\t\t\t FALSE, FALSE, 0};\n#ifdef FEAT_EVAL\n subflags_T\tsubflags_save;\n#endif\n int\t\tsave_do_all;\t\t// remember user specified 'g' flag\n int\t\tsave_do_ask;\t\t// remember user specified 'c' flag\n char_u\t*pat = NULL, *sub = NULL;\t// init for GCC\n int\t\tdelimiter;\n int\t\tsublen;\n int\t\tgot_quit = FALSE;\n int\t\tgot_match = FALSE;\n int\t\ttemp;\n int\t\twhich_pat;\n char_u\t*cmd;\n int\t\tsave_State;\n linenr_T\tfirst_line = 0;\t\t// first changed line\n linenr_T\tlast_line= 0;\t\t// below last changed line AFTER the\n\t\t\t\t\t// change\n linenr_T\told_line_count = curbuf->b_ml.ml_line_count;\n linenr_T\tline2;\n long\tnmatch;\t\t\t// number of lines in match\n char_u\t*sub_firstline;\t\t// allocated copy of first sub line\n int\t\tendcolumn = FALSE;\t// cursor in last column when done\n pos_T\told_cursor = curwin->w_cursor;\n int\t\tstart_nsubs;\n#ifdef FEAT_EVAL\n int\t\tsave_ma = 0;\n#endif\n\n cmd = eap->arg;\n if (!global_busy)\n {\n\tsub_nsubs = 0;\n\tsub_nlines = 0;\n }\n start_nsubs = sub_nsubs;\n\n if (eap->cmdidx == CMD_tilde)\n\twhich_pat = RE_LAST;\t// use last used regexp\n else\n\twhich_pat = RE_SUBST;\t// use last substitute regexp\n\n\t\t\t\t// new pattern and substitution\n if (eap->cmd[0] == 's' && *cmd != NUL && !VIM_ISWHITE(*cmd)\n\t\t&& vim_strchr((char_u *)\"0123456789cegriIp|\\\"\", *cmd) == NULL)\n {\n\t\t\t\t// don't accept alphanumeric for separator\n\tif (check_regexp_delim(*cmd) == FAIL)\n\t return;\n#ifdef FEAT_EVAL\n\tif (in_vim9script() && check_global_and_subst(eap->cmd, eap->arg)\n\t\t\t\t\t\t\t\t == FAIL)\n\t return;\n#endif\n\n\t/*\n\t * undocumented vi feature:\n\t * \"\\/sub/\" and \"\\?sub?\" use last used search pattern (almost like\n\t * //sub/r). \"\\&sub&\" use last substitute pattern (like //sub/).\n\t */\n\tif (*cmd == '\\\\')\n\t{\n\t ++cmd;\n\t if (vim_strchr((char_u *)\"/?&\", *cmd) == NULL)\n\t {\n\t\temsg(_(e_backslash_should_be_followed_by));\n\t\treturn;\n\t }\n\t if (*cmd != '&')\n\t\twhich_pat = RE_SEARCH;\t // use last '/' pattern\n\t pat = (char_u *)\"\";\t\t // empty search pattern\n\t delimiter = *cmd++;\t\t // remember delimiter character\n\t}\n\telse\t\t// find the end of the regexp\n\t{\n\t which_pat = RE_LAST;\t // use last used regexp\n\t delimiter = *cmd++;\t\t // remember delimiter character\n\t pat = cmd;\t\t\t // remember start of search pat\n\t cmd = skip_regexp_ex(cmd, delimiter, magic_isset(),\n\t\t\t\t\t\t\t&eap->arg, NULL, NULL);\n\t if (cmd[0] == delimiter)\t // end delimiter found\n\t\t*cmd++ = NUL;\t\t // replace it with a NUL\n\t}\n\n\t/*\n\t * Small incompatibility: vi sees '\\n' as end of the command, but in\n\t * Vim we want to use '\\n' to find/substitute a NUL.\n\t */\n\tsub = cmd;\t // remember the start of the substitution\n\tcmd = skip_substitute(cmd, delimiter);\n\n\tif (!eap->skip)\n\t{\n\t // In POSIX vi \":s/pat/%/\" uses the previous subst. string.\n\t if (STRCMP(sub, \"%\") == 0\n\t\t\t\t && vim_strchr(p_cpo, CPO_SUBPERCENT) != NULL)\n\t {\n\t\tif (old_sub == NULL)\t// there is no previous command\n\t\t{\n\t\t emsg(_(e_no_previous_substitute_regular_expression));\n\t\t return;\n\t\t}\n\t\tsub = old_sub;\n\t }\n\t else\n\t {\n\t\tvim_free(old_sub);\n\t\told_sub = vim_strsave(sub);\n\t }\n\t}\n }\n else if (!eap->skip)\t// use previous pattern and substitution\n {\n\tif (old_sub == NULL)\t// there is no previous command\n\t{\n\t emsg(_(e_no_previous_substitute_regular_expression));\n\t return;\n\t}\n\tpat = NULL;\t\t// search_regcomp() will use previous pattern\n\tsub = old_sub;\n\n\t// Vi compatibility quirk: repeating with \":s\" keeps the cursor in the\n\t// last column after using \"$\".\n\tendcolumn = (curwin->w_curswant == MAXCOL);\n }\n\n // Recognize \":%s/\\n//\" and turn it into a join command, which is much\n // more efficient.\n // TODO: find a generic solution to make line-joining operations more\n // efficient, avoid allocating a string that grows in size.\n if (pat != NULL && STRCMP(pat, \"\\\\n\") == 0\n\t && *sub == NUL\n\t && (*cmd == NUL || (cmd[1] == NUL && (*cmd == 'g' || *cmd == 'l'\n\t\t\t\t\t || *cmd == 'p' || *cmd == '#'))))\n {\n\tlinenr_T joined_lines_count;\n\n\tif (eap->skip)\n\t return;\n\tcurwin->w_cursor.lnum = eap->line1;\n\tif (*cmd == 'l')\n\t eap->flags = EXFLAG_LIST;\n\telse if (*cmd == '#')\n\t eap->flags = EXFLAG_NR;\n\telse if (*cmd == 'p')\n\t eap->flags = EXFLAG_PRINT;\n\n\t// The number of lines joined is the number of lines in the range plus\n\t// one. One less when the last line is included.\n\tjoined_lines_count = eap->line2 - eap->line1 + 1;\n\tif (eap->line2 < curbuf->b_ml.ml_line_count)\n\t ++joined_lines_count;\n\tif (joined_lines_count > 1)\n\t{\n\t (void)do_join(joined_lines_count, FALSE, TRUE, FALSE, TRUE);\n\t sub_nsubs = joined_lines_count - 1;\n\t sub_nlines = 1;\n\t (void)do_sub_msg(FALSE);\n\t ex_may_print(eap);\n\t}\n\n\tif ((cmdmod.cmod_flags & CMOD_KEEPPATTERNS) == 0)\n\t save_re_pat(RE_SUBST, pat, magic_isset());\n\t// put pattern in history\n\tadd_to_history(HIST_SEARCH, pat, TRUE, NUL);\n\n\treturn;\n }\n\n /*\n * Find trailing options. When '&' is used, keep old options.\n */\n if (*cmd == '&')\n\t++cmd;\n else\n {\n#ifdef FEAT_EVAL\n\tif (in_vim9script())\n\t{\n\t // ignore 'gdefault' and 'edcompatible'\n\t subflags.do_all = FALSE;\n\t subflags.do_ask = FALSE;\n\t}\n\telse\n#endif\n\tif (!p_ed)\n\t{\n\t if (p_gd)\t\t// default is global on\n\t\tsubflags.do_all = TRUE;\n\t else\n\t\tsubflags.do_all = FALSE;\n\t subflags.do_ask = FALSE;\n\t}\n\tsubflags.do_error = TRUE;\n\tsubflags.do_print = FALSE;\n\tsubflags.do_list = FALSE;\n\tsubflags.do_count = FALSE;\n\tsubflags.do_number = FALSE;\n\tsubflags.do_ic = 0;\n }\n while (*cmd)\n {\n\t/*\n\t * Note that 'g' and 'c' are always inverted, also when p_ed is off.\n\t * 'r' is never inverted.\n\t */\n\tif (*cmd == 'g')\n\t subflags.do_all = !subflags.do_all;\n\telse if (*cmd == 'c')\n\t subflags.do_ask = !subflags.do_ask;\n\telse if (*cmd == 'n')\n\t subflags.do_count = TRUE;\n\telse if (*cmd == 'e')\n\t subflags.do_error = !subflags.do_error;\n\telse if (*cmd == 'r')\t // use last used regexp\n\t which_pat = RE_LAST;\n\telse if (*cmd == 'p')\n\t subflags.do_print = TRUE;\n\telse if (*cmd == '#')\n\t{\n\t subflags.do_print = TRUE;\n\t subflags.do_number = TRUE;\n\t}\n\telse if (*cmd == 'l')\n\t{\n\t subflags.do_print = TRUE;\n\t subflags.do_list = TRUE;\n\t}\n\telse if (*cmd == 'i')\t // ignore case\n\t subflags.do_ic = 'i';\n\telse if (*cmd == 'I')\t // don't ignore case\n\t subflags.do_ic = 'I';\n\telse\n\t break;\n\t++cmd;\n }\n if (subflags.do_count)\n\tsubflags.do_ask = FALSE;\n\n save_do_all = subflags.do_all;\n save_do_ask = subflags.do_ask;\n\n /*\n * check for a trailing count\n */\n cmd = skipwhite(cmd);\n if (VIM_ISDIGIT(*cmd))\n {\n\ti = getdigits(&cmd);\n\tif (i <= 0 && !eap->skip && subflags.do_error)\n\t{\n\t emsg(_(e_positive_count_required));\n\t return;\n\t}\n\teap->line1 = eap->line2;\n\teap->line2 += i - 1;\n\tif (eap->line2 > curbuf->b_ml.ml_line_count)\n\t eap->line2 = curbuf->b_ml.ml_line_count;\n }\n\n /*\n * check for trailing command or garbage\n */\n cmd = skipwhite(cmd);\n if (*cmd && *cmd != '\"')\t // if not end-of-line or comment\n {\n\tset_nextcmd(eap, cmd);\n\tif (eap->nextcmd == NULL)\n\t{\n\t semsg(_(e_trailing_characters_str), cmd);\n\t return;\n\t}\n }\n\n if (eap->skip)\t // not executing commands, only parsing\n\treturn;\n\n if (!subflags.do_count && !curbuf->b_p_ma)\n {\n\t// Substitution is not allowed in non-'modifiable' buffer\n\temsg(_(e_cannot_make_changes_modifiable_is_off));\n\treturn;\n }\n\n if (search_regcomp(pat, RE_SUBST, which_pat, SEARCH_HIS, ®match) == FAIL)\n {\n\tif (subflags.do_error)\n\t emsg(_(e_invalid_command));\n\treturn;\n }\n\n // the 'i' or 'I' flag overrules 'ignorecase' and 'smartcase'\n if (subflags.do_ic == 'i')\n\tregmatch.rmm_ic = TRUE;\n else if (subflags.do_ic == 'I')\n\tregmatch.rmm_ic = FALSE;\n\n sub_firstline = NULL;\n\n /*\n * ~ in the substitute pattern is replaced with the old pattern.\n * We do it here once to avoid it to be replaced over and over again.\n * But don't do it when it starts with \"\\=\", then it's an expression.\n */\n if (!(sub[0] == '\\\\' && sub[1] == '='))\n\tsub = regtilde(sub, magic_isset());\n\n /*\n * Check for a match on each line.\n */\n line2 = eap->line2;\n for (lnum = eap->line1; lnum <= line2 && !(got_quit\n#if defined(FEAT_EVAL)\n\t\t|| aborting()\n#endif\n\t\t); ++lnum)\n {\n\tnmatch = vim_regexec_multi(®match, curwin, curbuf, lnum,\n\t\t\t\t\t\t (colnr_T)0, NULL, NULL);\n\tif (nmatch)\n\t{\n\t colnr_T\tcopycol;\n\t colnr_T\tmatchcol;\n\t colnr_T\tprev_matchcol = MAXCOL;\n\t char_u\t*new_end, *new_start = NULL;\n\t unsigned\tnew_start_len = 0;\n\t char_u\t*p1;\n\t int\t\tdid_sub = FALSE;\n\t int\t\tlastone;\n\t int\t\tlen, copy_len, needed_len;\n\t long\tnmatch_tl = 0;\t// nr of lines matched below lnum\n\t int\t\tdo_again;\t// do it again after joining lines\n\t int\t\tskip_match = FALSE;\n\t linenr_T\tsub_firstlnum;\t// nr of first sub line\n#ifdef FEAT_PROP_POPUP\n\t int\t\tapc_flags = APC_SAVE_FOR_UNDO | APC_SUBSTITUTE;\n\t colnr_T\ttotal_added = 0;\n#endif\n\n\t /*\n\t * The new text is build up step by step, to avoid too much\n\t * copying. There are these pieces:\n\t * sub_firstline\tThe old text, unmodified.\n\t * copycol\t\tColumn in the old text where we started\n\t *\t\t\tlooking for a match; from here old text still\n\t *\t\t\tneeds to be copied to the new text.\n\t * matchcol\t\tColumn number of the old text where to look\n\t *\t\t\tfor the next match. It's just after the\n\t *\t\t\tprevious match or one further.\n\t * prev_matchcol\tColumn just after the previous match (if any).\n\t *\t\t\tMostly equal to matchcol, except for the first\n\t *\t\t\tmatch and after skipping an empty match.\n\t * regmatch.*pos\tWhere the pattern matched in the old text.\n\t * new_start\tThe new text, all that has been produced so\n\t *\t\t\tfar.\n\t * new_end\t\tThe new text, where to append new text.\n\t *\n\t * lnum\t\tThe line number where we found the start of\n\t *\t\t\tthe match. Can be below the line we searched\n\t *\t\t\twhen there is a \\n before a \\zs in the\n\t *\t\t\tpattern.\n\t * sub_firstlnum\tThe line number in the buffer where to look\n\t *\t\t\tfor a match. Can be different from \"lnum\"\n\t *\t\t\twhen the pattern or substitute string contains\n\t *\t\t\tline breaks.\n\t *\n\t * Special situations:\n\t * - When the substitute string contains a line break, the part up\n\t * to the line break is inserted in the text, but the copy of\n\t * the original line is kept. \"sub_firstlnum\" is adjusted for\n\t * the inserted lines.\n\t * - When the matched pattern contains a line break, the old line\n\t * is taken from the line at the end of the pattern. The lines\n\t * in the match are deleted later, \"sub_firstlnum\" is adjusted\n\t * accordingly.\n\t *\n\t * The new text is built up in new_start[]. It has some extra\n\t * room to avoid using alloc()/free() too often. new_start_len is\n\t * the length of the allocated memory at new_start.\n\t *\n\t * Make a copy of the old line, so it won't be taken away when\n\t * updating the screen or handling a multi-line match. The \"old_\"\n\t * pointers point into this copy.\n\t */\n\t sub_firstlnum = lnum;\n\t copycol = 0;\n\t matchcol = 0;\n\n\t // At first match, remember current cursor position.\n\t if (!got_match)\n\t {\n\t\tsetpcmark();\n\t\tgot_match = TRUE;\n\t }\n\n\t /*\n\t * Loop until nothing more to replace in this line.\n\t * 1. Handle match with empty string.\n\t * 2. If do_ask is set, ask for confirmation.\n\t * 3. substitute the string.\n\t * 4. if do_all is set, find next match\n\t * 5. break if there isn't another match in this line\n\t */\n\t for (;;)\n\t {\n\t\t// Advance \"lnum\" to the line where the match starts. The\n\t\t// match does not start in the first line when there is a line\n\t\t// break before \\zs.\n\t\tif (regmatch.startpos[0].lnum > 0)\n\t\t{\n\t\t lnum += regmatch.startpos[0].lnum;\n\t\t sub_firstlnum += regmatch.startpos[0].lnum;\n\t\t nmatch -= regmatch.startpos[0].lnum;\n\t\t VIM_CLEAR(sub_firstline);\n\t\t}\n\n\t\t// Match might be after the last line for \"\\n\\zs\" matching at\n\t\t// the end of the last line.\n\t\tif (lnum > curbuf->b_ml.ml_line_count)\n\t\t break;\n\n\t\tif (sub_firstline == NULL)\n\t\t{\n\t\t sub_firstline = vim_strsave(ml_get(sub_firstlnum));\n\t\t if (sub_firstline == NULL)\n\t\t {\n\t\t\tvim_free(new_start);\n\t\t\tgoto outofmem;\n\t\t }\n\t\t}\n\n\t\t// Save the line number of the last change for the final\n\t\t// cursor position (just like Vi).\n\t\tcurwin->w_cursor.lnum = lnum;\n\t\tdo_again = FALSE;\n\n\t\t/*\n\t\t * 1. Match empty string does not count, except for first\n\t\t * match. This reproduces the strange vi behaviour.\n\t\t * This also catches endless loops.\n\t\t */\n\t\tif (matchcol == prev_matchcol\n\t\t\t&& regmatch.endpos[0].lnum == 0\n\t\t\t&& matchcol == regmatch.endpos[0].col)\n\t\t{\n\t\t if (sub_firstline[matchcol] == NUL)\n\t\t\t// We already were at the end of the line. Don't look\n\t\t\t// for a match in this line again.\n\t\t\tskip_match = TRUE;\n\t\t else\n\t\t {\n\t\t\t // search for a match at next column\n\t\t\tif (has_mbyte)\n\t\t\t matchcol += mb_ptr2len(sub_firstline + matchcol);\n\t\t\telse\n\t\t\t ++matchcol;\n\t\t }\n\t\t goto skip;\n\t\t}\n\n\t\t// Normally we continue searching for a match just after the\n\t\t// previous match.\n\t\tmatchcol = regmatch.endpos[0].col;\n\t\tprev_matchcol = matchcol;\n\n\t\t/*\n\t\t * 2. If do_count is set only increase the counter.\n\t\t * If do_ask is set, ask for confirmation.\n\t\t */\n\t\tif (subflags.do_count)\n\t\t{\n\t\t // For a multi-line match, put matchcol at the NUL at\n\t\t // the end of the line and set nmatch to one, so that\n\t\t // we continue looking for a match on the next line.\n\t\t // Avoids that \":s/\\nB\\@=//gc\" get stuck.\n\t\t if (nmatch > 1)\n\t\t {\n\t\t\tmatchcol = (colnr_T)STRLEN(sub_firstline);\n\t\t\tnmatch = 1;\n\t\t\tskip_match = TRUE;\n\t\t }\n\t\t sub_nsubs++;\n\t\t did_sub = TRUE;\n#ifdef FEAT_EVAL\n\t\t // Skip the substitution, unless an expression is used,\n\t\t // then it is evaluated in the sandbox.\n\t\t if (!(sub[0] == '\\\\' && sub[1] == '='))\n#endif\n\t\t\tgoto skip;\n\t\t}\n\n\t\tif (subflags.do_ask)\n\t\t{\n\t\t int typed = 0;\n\n\t\t // change State to CONFIRM, so that the mouse works\n\t\t // properly\n\t\t save_State = State;\n\t\t State = CONFIRM;\n\t\t setmouse();\t\t// disable mouse in xterm\n\t\t curwin->w_cursor.col = regmatch.startpos[0].col;\n\t\t if (curwin->w_p_crb)\n\t\t\tdo_check_cursorbind();\n\n\t\t // When 'cpoptions' contains \"u\" don't sync undo when\n\t\t // asking for confirmation.\n\t\t if (vim_strchr(p_cpo, CPO_UNDO) != NULL)\n\t\t\t++no_u_sync;\n\n\t\t /*\n\t\t * Loop until 'y', 'n', 'q', CTRL-E or CTRL-Y typed.\n\t\t */\n\t\t while (subflags.do_ask)\n\t\t {\n\t\t\tif (exmode_active)\n\t\t\t{\n\t\t\t char_u\t*resp;\n\t\t\t colnr_T\tsc, ec;\n\n\t\t\t print_line_no_prefix(lnum,\n\t\t\t\t\t subflags.do_number, subflags.do_list);\n\n\t\t\t getvcol(curwin, &curwin->w_cursor, &sc, NULL, NULL);\n\t\t\t curwin->w_cursor.col = regmatch.endpos[0].col - 1;\n\t\t\t if (curwin->w_cursor.col < 0)\n\t\t\t\tcurwin->w_cursor.col = 0;\n\t\t\t getvcol(curwin, &curwin->w_cursor, NULL, NULL, &ec);\n\t\t\t curwin->w_cursor.col = regmatch.startpos[0].col;\n\t\t\t if (subflags.do_number || curwin->w_p_nu)\n\t\t\t {\n\t\t\t\tint numw = number_width(curwin) + 1;\n\t\t\t\tsc += numw;\n\t\t\t\tec += numw;\n\t\t\t }\n\t\t\t msg_start();\n\t\t\t for (i = 0; i < (long)sc; ++i)\n\t\t\t\tmsg_putchar(' ');\n\t\t\t for ( ; i <= (long)ec; ++i)\n\t\t\t\tmsg_putchar('^');\n\n\t\t\t resp = getexmodeline('?', NULL, 0, TRUE);\n\t\t\t if (resp != NULL)\n\t\t\t {\n\t\t\t\ttyped = *resp;\n\t\t\t\tvim_free(resp);\n\t\t\t }\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t char_u *orig_line = NULL;\n\t\t\t int len_change = 0;\n\t\t\t int\t save_p_lz = p_lz;\n#ifdef FEAT_FOLDING\n\t\t\t int save_p_fen = curwin->w_p_fen;\n\n\t\t\t curwin->w_p_fen = FALSE;\n#endif\n\t\t\t // Invert the matched string.\n\t\t\t // Remove the inversion afterwards.\n\t\t\t temp = RedrawingDisabled;\n\t\t\t RedrawingDisabled = 0;\n\n\t\t\t // avoid calling update_screen() in vgetorpeek()\n\t\t\t p_lz = FALSE;\n\n\t\t\t if (new_start != NULL)\n\t\t\t {\n\t\t\t\t// There already was a substitution, we would\n\t\t\t\t// like to show this to the user. We cannot\n\t\t\t\t// really update the line, it would change\n\t\t\t\t// what matches. Temporarily replace the line\n\t\t\t\t// and change it back afterwards.\n\t\t\t\torig_line = vim_strsave(ml_get(lnum));\n\t\t\t\tif (orig_line != NULL)\n\t\t\t\t{\n\t\t\t\t char_u *new_line = concat_str(new_start,\n\t\t\t\t\t\t sub_firstline + copycol);\n\n\t\t\t\t if (new_line == NULL)\n\t\t\t\t\tVIM_CLEAR(orig_line);\n\t\t\t\t else\n\t\t\t\t {\n\t\t\t\t\t// Position the cursor relative to the\n\t\t\t\t\t// end of the line, the previous\n\t\t\t\t\t// substitute may have inserted or\n\t\t\t\t\t// deleted characters before the\n\t\t\t\t\t// cursor.\n\t\t\t\t\tlen_change = (int)STRLEN(new_line)\n\t\t\t\t\t\t - (int)STRLEN(orig_line);\n\t\t\t\t\tcurwin->w_cursor.col += len_change;\n\t\t\t\t\tml_replace(lnum, new_line, FALSE);\n\t\t\t\t }\n\t\t\t\t}\n\t\t\t }\n\n\t\t\t search_match_lines = regmatch.endpos[0].lnum\n\t\t\t\t\t\t - regmatch.startpos[0].lnum;\n\t\t\t search_match_endcol = regmatch.endpos[0].col\n\t\t\t\t\t\t\t\t + len_change;\n\t\t\t highlight_match = TRUE;\n\n\t\t\t update_topline();\n\t\t\t validate_cursor();\n\t\t\t update_screen(SOME_VALID);\n\t\t\t highlight_match = FALSE;\n\t\t\t redraw_later(SOME_VALID);\n\n#ifdef FEAT_FOLDING\n\t\t\t curwin->w_p_fen = save_p_fen;\n#endif\n\t\t\t if (msg_row == Rows - 1)\n\t\t\t\tmsg_didout = FALSE;\t// avoid a scroll-up\n\t\t\t msg_starthere();\n\t\t\t i = msg_scroll;\n\t\t\t msg_scroll = 0;\t\t// truncate msg when\n\t\t\t\t\t\t\t// needed\n\t\t\t msg_no_more = TRUE;\n\t\t\t // write message same highlighting as for\n\t\t\t // wait_return\n\t\t\t smsg_attr(HL_ATTR(HLF_R),\n\t\t\t\t_(\"replace with %s (y/n/a/q/l/^E/^Y)?\"), sub);\n\t\t\t msg_no_more = FALSE;\n\t\t\t msg_scroll = i;\n\t\t\t showruler(TRUE);\n\t\t\t windgoto(msg_row, msg_col);\n\t\t\t RedrawingDisabled = temp;\n\n#ifdef USE_ON_FLY_SCROLL\n\t\t\t dont_scroll = FALSE; // allow scrolling here\n#endif\n\t\t\t ++no_mapping;\t// don't map this key\n\t\t\t ++allow_keys;\t// allow special keys\n\t\t\t typed = plain_vgetc();\n\t\t\t --allow_keys;\n\t\t\t --no_mapping;\n\n\t\t\t // clear the question\n\t\t\t msg_didout = FALSE;\t// don't scroll up\n\t\t\t msg_col = 0;\n\t\t\t gotocmdline(TRUE);\n\t\t\t p_lz = save_p_lz;\n\n\t\t\t // restore the line\n\t\t\t if (orig_line != NULL)\n\t\t\t\tml_replace(lnum, orig_line, FALSE);\n\t\t\t}\n\n\t\t\tneed_wait_return = FALSE; // no hit-return prompt\n\t\t\tif (typed == 'q' || typed == ESC || typed == Ctrl_C\n#ifdef UNIX\n\t\t\t\t|| typed == intr_char\n#endif\n\t\t\t\t)\n\t\t\t{\n\t\t\t got_quit = TRUE;\n\t\t\t break;\n\t\t\t}\n\t\t\tif (typed == 'n')\n\t\t\t break;\n\t\t\tif (typed == 'y')\n\t\t\t break;\n\t\t\tif (typed == 'l')\n\t\t\t{\n\t\t\t // last: replace and then stop\n\t\t\t subflags.do_all = FALSE;\n\t\t\t line2 = lnum;\n\t\t\t break;\n\t\t\t}\n\t\t\tif (typed == 'a')\n\t\t\t{\n\t\t\t subflags.do_ask = FALSE;\n\t\t\t break;\n\t\t\t}\n\t\t\tif (typed == Ctrl_E)\n\t\t\t scrollup_clamp();\n\t\t\telse if (typed == Ctrl_Y)\n\t\t\t scrolldown_clamp();\n\t\t }\n\t\t State = save_State;\n\t\t setmouse();\n\t\t if (vim_strchr(p_cpo, CPO_UNDO) != NULL)\n\t\t\t--no_u_sync;\n\n\t\t if (typed == 'n')\n\t\t {\n\t\t\t// For a multi-line match, put matchcol at the NUL at\n\t\t\t// the end of the line and set nmatch to one, so that\n\t\t\t// we continue looking for a match on the next line.\n\t\t\t// Avoids that \":%s/\\nB\\@=//gc\" and \":%s/\\n/,\\r/gc\"\n\t\t\t// get stuck when pressing 'n'.\n\t\t\tif (nmatch > 1)\n\t\t\t{\n\t\t\t matchcol = (colnr_T)STRLEN(sub_firstline);\n\t\t\t skip_match = TRUE;\n\t\t\t}\n\t\t\tgoto skip;\n\t\t }\n\t\t if (got_quit)\n\t\t\tgoto skip;\n\t\t}\n\n\t\t// Move the cursor to the start of the match, so that we can\n\t\t// use \"\\=col(\".\").\n\t\tcurwin->w_cursor.col = regmatch.startpos[0].col;\n\n\t\t/*\n\t\t * 3. substitute the string.\n\t\t */\n#ifdef FEAT_EVAL\n\t\tsave_ma = curbuf->b_p_ma;\n\t\tif (subflags.do_count)\n\t\t{\n\t\t // prevent accidentally changing the buffer by a function\n\t\t curbuf->b_p_ma = FALSE;\n\t\t sandbox++;\n\t\t}\n\t\t// Save flags for recursion. They can change for e.g.\n\t\t// :s/^/\\=execute(\"s#^##gn\")\n\t\tsubflags_save = subflags;\n#endif\n\t\t// get length of substitution part\n\t\tsublen = vim_regsub_multi(®match,\n\t\t\t\t sub_firstlnum - regmatch.startpos[0].lnum,\n\t\t\t sub, sub_firstline, FALSE, magic_isset(), TRUE);\n#ifdef FEAT_EVAL\n\t\t// If getting the substitute string caused an error, don't do\n\t\t// the replacement.\n\t\t// Don't keep flags set by a recursive call.\n\t\tsubflags = subflags_save;\n\t\tif (aborting() || subflags.do_count)\n\t\t{\n\t\t curbuf->b_p_ma = save_ma;\n\t\t if (sandbox > 0)\n\t\t\tsandbox--;\n\t\t goto skip;\n\t\t}\n#endif\n\n\t\t// When the match included the \"$\" of the last line it may\n\t\t// go beyond the last line of the buffer.\n\t\tif (nmatch > curbuf->b_ml.ml_line_count - sub_firstlnum + 1)\n\t\t{\n\t\t nmatch = curbuf->b_ml.ml_line_count - sub_firstlnum + 1;\n\t\t skip_match = TRUE;\n\t\t}\n\n\t\t// Need room for:\n\t\t// - result so far in new_start (not for first sub in line)\n\t\t// - original text up to match\n\t\t// - length of substituted part\n\t\t// - original text after match\n\t\t// Adjust text properties here, since we have all information\n\t\t// needed.\n\t\tif (nmatch == 1)\n\t\t{\n\t\t p1 = sub_firstline;\n#ifdef FEAT_PROP_POPUP\n\t\t if (curbuf->b_has_textprop)\n\t\t {\n\t\t\tint bytes_added = sublen - 1 - (regmatch.endpos[0].col\n\t\t\t\t\t\t - regmatch.startpos[0].col);\n\n\t\t\t// When text properties are changed, need to save for\n\t\t\t// undo first, unless done already.\n\t\t\tif (adjust_prop_columns(lnum,\n\t\t\t\t\ttotal_added + regmatch.startpos[0].col,\n\t\t\t\t\t\t bytes_added, apc_flags))\n\t\t\t apc_flags &= ~APC_SAVE_FOR_UNDO;\n\t\t\t// Offset for column byte number of the text property\n\t\t\t// in the resulting buffer afterwards.\n\t\t\ttotal_added += bytes_added;\n\t\t }\n#endif\n\t\t}\n\t\telse\n\t\t{\n\t\t p1 = ml_get(sub_firstlnum + nmatch - 1);\n\t\t nmatch_tl += nmatch - 1;\n\t\t}\n\t\tcopy_len = regmatch.startpos[0].col - copycol;\n\t\tneeded_len = copy_len + ((unsigned)STRLEN(p1)\n\t\t\t\t - regmatch.endpos[0].col) + sublen + 1;\n\t\tif (new_start == NULL)\n\t\t{\n\t\t /*\n\t\t * Get some space for a temporary buffer to do the\n\t\t * substitution into (and some extra space to avoid\n\t\t * too many calls to alloc()/free()).\n\t\t */\n\t\t new_start_len = needed_len + 50;\n\t\t if ((new_start = alloc(new_start_len)) == NULL)\n\t\t\tgoto outofmem;\n\t\t *new_start = NUL;\n\t\t new_end = new_start;\n\t\t}\n\t\telse\n\t\t{\n\t\t /*\n\t\t * Check if the temporary buffer is long enough to do the\n\t\t * substitution into. If not, make it larger (with a bit\n\t\t * extra to avoid too many calls to alloc()/free()).\n\t\t */\n\t\t len = (unsigned)STRLEN(new_start);\n\t\t needed_len += len;\n\t\t if (needed_len > (int)new_start_len)\n\t\t {\n\t\t\tnew_start_len = needed_len + 50;\n\t\t\tif ((p1 = alloc(new_start_len)) == NULL)\n\t\t\t{\n\t\t\t vim_free(new_start);\n\t\t\t goto outofmem;\n\t\t\t}\n\t\t\tmch_memmove(p1, new_start, (size_t)(len + 1));\n\t\t\tvim_free(new_start);\n\t\t\tnew_start = p1;\n\t\t }\n\t\t new_end = new_start + len;\n\t\t}\n\n\t\t/*\n\t\t * copy the text up to the part that matched\n\t\t */\n\t\tmch_memmove(new_end, sub_firstline + copycol, (size_t)copy_len);\n\t\tnew_end += copy_len;\n\n\t\t(void)vim_regsub_multi(®match,\n\t\t\t\t sub_firstlnum - regmatch.startpos[0].lnum,\n\t\t\t\t sub, new_end, TRUE, magic_isset(), TRUE);\n\t\tsub_nsubs++;\n\t\tdid_sub = TRUE;\n\n\t\t// Move the cursor to the start of the line, to avoid that it\n\t\t// is beyond the end of the line after the substitution.\n\t\tcurwin->w_cursor.col = 0;\n\n\t\t// For a multi-line match, make a copy of the last matched\n\t\t// line and continue in that one.\n\t\tif (nmatch > 1)\n\t\t{\n\t\t sub_firstlnum += nmatch - 1;\n\t\t vim_free(sub_firstline);\n\t\t sub_firstline = vim_strsave(ml_get(sub_firstlnum));\n\t\t // When going beyond the last line, stop substituting.\n\t\t if (sub_firstlnum <= line2)\n\t\t\tdo_again = TRUE;\n\t\t else\n\t\t\tsubflags.do_all = FALSE;\n\t\t}\n\n\t\t// Remember next character to be copied.\n\t\tcopycol = regmatch.endpos[0].col;\n\n\t\tif (skip_match)\n\t\t{\n\t\t // Already hit end of the buffer, sub_firstlnum is one\n\t\t // less than what it ought to be.\n\t\t vim_free(sub_firstline);\n\t\t sub_firstline = vim_strsave((char_u *)\"\");\n\t\t copycol = 0;\n\t\t}\n\n\t\t/*\n\t\t * Now the trick is to replace CTRL-M chars with a real line\n\t\t * break. This would make it impossible to insert a CTRL-M in\n\t\t * the text. The line break can be avoided by preceding the\n\t\t * CTRL-M with a backslash. To be able to insert a backslash,\n\t\t * they must be doubled in the string and are halved here.\n\t\t * That is Vi compatible.\n\t\t */\n\t\tfor (p1 = new_end; *p1; ++p1)\n\t\t{\n\t\t if (p1[0] == '\\\\' && p1[1] != NUL) // remove backslash\n\t\t {\n\t\t\tSTRMOVE(p1, p1 + 1);\n#ifdef FEAT_PROP_POPUP\n\t\t\tif (curbuf->b_has_textprop)\n\t\t\t{\n\t\t\t // When text properties are changed, need to save\n\t\t\t // for undo first, unless done already.\n\t\t\t if (adjust_prop_columns(lnum,\n\t\t\t\t\t(colnr_T)(p1 - new_start), -1,\n\t\t\t\t\tapc_flags))\n\t\t\t\tapc_flags &= ~APC_SAVE_FOR_UNDO;\n\t\t\t}\n#endif\n\t\t }\n\t\t else if (*p1 == CAR)\n\t\t {\n\t\t\tif (u_inssub(lnum) == OK) // prepare for undo\n\t\t\t{\n\t\t\t colnr_T\tplen = (colnr_T)(p1 - new_start + 1);\n\n\t\t\t *p1 = NUL;\t\t // truncate up to the CR\n\t\t\t ml_append(lnum - 1, new_start, plen, FALSE);\n\t\t\t mark_adjust(lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);\n\t\t\t if (subflags.do_ask)\n\t\t\t\tappended_lines(lnum - 1, 1L);\n\t\t\t else\n\t\t\t {\n\t\t\t\tif (first_line == 0)\n\t\t\t\t first_line = lnum;\n\t\t\t\tlast_line = lnum + 1;\n\t\t\t }\n#ifdef FEAT_PROP_POPUP\n\t\t\t adjust_props_for_split(lnum + 1, lnum, plen, 1);\n#endif\n\t\t\t // all line numbers increase\n\t\t\t ++sub_firstlnum;\n\t\t\t ++lnum;\n\t\t\t ++line2;\n\t\t\t // move the cursor to the new line, like Vi\n\t\t\t ++curwin->w_cursor.lnum;\n\t\t\t // copy the rest\n\t\t\t STRMOVE(new_start, p1 + 1);\n\t\t\t p1 = new_start - 1;\n\t\t\t}\n\t\t }\n\t\t else if (has_mbyte)\n\t\t\tp1 += (*mb_ptr2len)(p1) - 1;\n\t\t}\n\n\t\t/*\n\t\t * 4. If do_all is set, find next match.\n\t\t * Prevent endless loop with patterns that match empty\n\t\t * strings, e.g. :s/$/pat/g or :s/[a-z]* /(&)/g.\n\t\t * But \":s/\\n/#/\" is OK.\n\t\t */\nskip:\n\t\t// We already know that we did the last subst when we are at\n\t\t// the end of the line, except that a pattern like\n\t\t// \"bar\\|\\nfoo\" may match at the NUL. \"lnum\" can be below\n\t\t// \"line2\" when there is a \\zs in the pattern after a line\n\t\t// break.\n\t\tlastone = (skip_match\n\t\t\t|| got_int\n\t\t\t|| got_quit\n\t\t\t|| lnum > line2\n\t\t\t|| !(subflags.do_all || do_again)\n\t\t\t|| (sub_firstline[matchcol] == NUL && nmatch <= 1\n\t\t\t\t\t && !re_multiline(regmatch.regprog)));\n\t\tnmatch = -1;\n\n\t\t/*\n\t\t * Replace the line in the buffer when needed. This is\n\t\t * skipped when there are more matches.\n\t\t * The check for nmatch_tl is needed for when multi-line\n\t\t * matching must replace the lines before trying to do another\n\t\t * match, otherwise \"\\@<=\" won't work.\n\t\t * When the match starts below where we start searching also\n\t\t * need to replace the line first (using \\zs after \\n).\n\t\t */\n\t\tif (lastone\n\t\t\t|| nmatch_tl > 0\n\t\t\t|| (nmatch = vim_regexec_multi(®match, curwin,\n\t\t\t\t\t\t\tcurbuf, sub_firstlnum,\n\t\t\t\t\t\t matchcol, NULL, NULL)) == 0\n\t\t\t|| regmatch.startpos[0].lnum > 0)\n\t\t{\n\t\t if (new_start != NULL)\n\t\t {\n\t\t\t/*\n\t\t\t * Copy the rest of the line, that didn't match.\n\t\t\t * \"matchcol\" has to be adjusted, we use the end of\n\t\t\t * the line as reference, because the substitute may\n\t\t\t * have changed the number of characters. Same for\n\t\t\t * \"prev_matchcol\".\n\t\t\t */\n\t\t\tSTRCAT(new_start, sub_firstline + copycol);\n\t\t\tmatchcol = (colnr_T)STRLEN(sub_firstline) - matchcol;\n\t\t\tprev_matchcol = (colnr_T)STRLEN(sub_firstline)\n\t\t\t\t\t\t\t - prev_matchcol;\n\n\t\t\tif (u_savesub(lnum) != OK)\n\t\t\t break;\n\t\t\tml_replace(lnum, new_start, TRUE);\n\n\t\t\tif (nmatch_tl > 0)\n\t\t\t{\n\t\t\t /*\n\t\t\t * Matched lines have now been substituted and are\n\t\t\t * useless, delete them. The part after the match\n\t\t\t * has been appended to new_start, we don't need\n\t\t\t * it in the buffer.\n\t\t\t */\n\t\t\t ++lnum;\n\t\t\t if (u_savedel(lnum, nmatch_tl) != OK)\n\t\t\t\tbreak;\n\t\t\t for (i = 0; i < nmatch_tl; ++i)\n\t\t\t\tml_delete(lnum);\n\t\t\t mark_adjust(lnum, lnum + nmatch_tl - 1,\n\t\t\t\t\t\t (long)MAXLNUM, -nmatch_tl);\n\t\t\t if (subflags.do_ask)\n\t\t\t\tdeleted_lines(lnum, nmatch_tl);\n\t\t\t --lnum;\n\t\t\t line2 -= nmatch_tl; // nr of lines decreases\n\t\t\t nmatch_tl = 0;\n\t\t\t}\n\n\t\t\t// When asking, undo is saved each time, must also set\n\t\t\t// changed flag each time.\n\t\t\tif (subflags.do_ask)\n\t\t\t changed_bytes(lnum, 0);\n\t\t\telse\n\t\t\t{\n\t\t\t if (first_line == 0)\n\t\t\t\tfirst_line = lnum;\n\t\t\t last_line = lnum + 1;\n\t\t\t}\n\n\t\t\tsub_firstlnum = lnum;\n\t\t\tvim_free(sub_firstline); // free the temp buffer\n\t\t\tsub_firstline = new_start;\n\t\t\tnew_start = NULL;\n\t\t\tmatchcol = (colnr_T)STRLEN(sub_firstline) - matchcol;\n\t\t\tprev_matchcol = (colnr_T)STRLEN(sub_firstline)\n\t\t\t\t\t\t\t - prev_matchcol;\n\t\t\tcopycol = 0;\n\t\t }\n\t\t if (nmatch == -1 && !lastone)\n\t\t\tnmatch = vim_regexec_multi(®match, curwin, curbuf,\n\t\t\t\t\t sub_firstlnum, matchcol, NULL, NULL);\n\n\t\t /*\n\t\t * 5. break if there isn't another match in this line\n\t\t */\n\t\t if (nmatch <= 0)\n\t\t {\n\t\t\t// If the match found didn't start where we were\n\t\t\t// searching, do the next search in the line where we\n\t\t\t// found the match.\n\t\t\tif (nmatch == -1)\n\t\t\t lnum -= regmatch.startpos[0].lnum;\n\t\t\tbreak;\n\t\t }\n\t\t}\n\n\t\tline_breakcheck();\n\t }\n\n\t if (did_sub)\n\t\t++sub_nlines;\n\t vim_free(new_start);\t// for when substitute was cancelled\n\t VIM_CLEAR(sub_firstline);\t// free the copy of the original line\n\t}\n\n\tline_breakcheck();\n }\n\n if (first_line != 0)\n {\n\t// Need to subtract the number of added lines from \"last_line\" to get\n\t// the line number before the change (same as adding the number of\n\t// deleted lines).\n\ti = curbuf->b_ml.ml_line_count - old_line_count;\n\tchanged_lines(first_line, 0, last_line - i, i);\n }\n\noutofmem:\n vim_free(sub_firstline); // may have to free allocated copy of the line\n\n // \":s/pat//n\" doesn't move the cursor\n if (subflags.do_count)\n\tcurwin->w_cursor = old_cursor;\n\n if (sub_nsubs > start_nsubs)\n {\n\tif ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0)\n\t{\n\t // Set the '[ and '] marks.\n\t curbuf->b_op_start.lnum = eap->line1;\n\t curbuf->b_op_end.lnum = line2;\n\t curbuf->b_op_start.col = curbuf->b_op_end.col = 0;\n\t}\n\n\tif (!global_busy)\n\t{\n\t // when interactive leave cursor on the match\n\t if (!subflags.do_ask)\n\t {\n\t\tif (endcolumn)\n\t\t coladvance((colnr_T)MAXCOL);\n\t\telse\n\t\t beginline(BL_WHITE | BL_FIX);\n\t }\n\t if (!do_sub_msg(subflags.do_count) && subflags.do_ask)\n\t\tmsg(\"\");\n\t}\n\telse\n\t global_need_beginline = TRUE;\n\tif (subflags.do_print)\n\t print_line(curwin->w_cursor.lnum,\n\t\t\t\t\t subflags.do_number, subflags.do_list);\n }\n else if (!global_busy)\n {\n\tif (got_int)\t\t// interrupted\n\t emsg(_(e_interrupted));\n\telse if (got_match)\t// did find something but nothing substituted\n\t msg(\"\");\n\telse if (subflags.do_error)\t// nothing found\n\t semsg(_(e_pattern_not_found_str), get_search_pat());\n }\n\n#ifdef FEAT_FOLDING\n if (subflags.do_ask && hasAnyFolding(curwin))\n\t// Cursor position may require updating\n\tchanged_window_setting();\n#endif\n\n vim_regfree(regmatch.regprog);\n\n // Restore the flag values, they can be used for \":&&\".\n subflags.do_all = save_do_all;\n subflags.do_ask = save_do_ask;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'patch 8.2.4253: using freed memory when substitute with function call\n\nProblem: Using freed memory when substitute uses a recursive function call.\nSolution: Make a copy of the substitute text.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: paste_option_changed(void)\n{\n static int\told_p_paste = FALSE;\n static int\tsave_sm = 0;\n static int\tsave_sta = 0;\n#ifdef FEAT_CMDL_INFO\n static int\tsave_ru = 0;\n#endif\n#ifdef FEAT_RIGHTLEFT\n static int\tsave_ri = 0;\n static int\tsave_hkmap = 0;\n#endif\n buf_T\t*buf;\n\n if (p_paste)\n {\n\t/*\n\t * Paste switched from off to on.\n\t * Save the current values, so they can be restored later.\n\t */\n\tif (!old_p_paste)\n\t{\n\t // save options for each buffer\n\t FOR_ALL_BUFFERS(buf)\n\t {\n\t\tbuf->b_p_tw_nopaste = buf->b_p_tw;\n\t\tbuf->b_p_wm_nopaste = buf->b_p_wm;\n\t\tbuf->b_p_sts_nopaste = buf->b_p_sts;\n\t\tbuf->b_p_ai_nopaste = buf->b_p_ai;\n\t\tbuf->b_p_et_nopaste = buf->b_p_et;\n#ifdef FEAT_VARTABS\n\t\tif (buf->b_p_vsts_nopaste)\n\t\t vim_free(buf->b_p_vsts_nopaste);\n\t\tbuf->b_p_vsts_nopaste = buf->b_p_vsts && buf->b_p_vsts != empty_option\n\t\t\t\t ? vim_strsave(buf->b_p_vsts) : NULL;\n#endif\n\t }\n\n\t // save global options\n\t save_sm = p_sm;\n\t save_sta = p_sta;\n#ifdef FEAT_CMDL_INFO\n\t save_ru = p_ru;\n#endif\n#ifdef FEAT_RIGHTLEFT\n\t save_ri = p_ri;\n\t save_hkmap = p_hkmap;\n#endif\n\t // save global values for local buffer options\n\t p_ai_nopaste = p_ai;\n\t p_et_nopaste = p_et;\n\t p_sts_nopaste = p_sts;\n\t p_tw_nopaste = p_tw;\n\t p_wm_nopaste = p_wm;\n#ifdef FEAT_VARTABS\n\t if (p_vsts_nopaste)\n\t\tvim_free(p_vsts_nopaste);\n\t p_vsts_nopaste = p_vsts && p_vsts != empty_option ? vim_strsave(p_vsts) : NULL;\n#endif\n\t}\n\n\t/*\n\t * Always set the option values, also when 'paste' is set when it is\n\t * already on.\n\t */\n\t// set options for each buffer\n\tFOR_ALL_BUFFERS(buf)\n\t{\n\t buf->b_p_tw = 0;\t // textwidth is 0\n\t buf->b_p_wm = 0;\t // wrapmargin is 0\n\t buf->b_p_sts = 0;\t // softtabstop is 0\n\t buf->b_p_ai = 0;\t // no auto-indent\n\t buf->b_p_et = 0;\t // no expandtab\n#ifdef FEAT_VARTABS\n\t if (buf->b_p_vsts)\n\t\tfree_string_option(buf->b_p_vsts);\n\t buf->b_p_vsts = empty_option;\n\t if (buf->b_p_vsts_array)\n\t\tvim_free(buf->b_p_vsts_array);\n\t buf->b_p_vsts_array = 0;\n#endif\n\t}\n\n\t// set global options\n\tp_sm = 0;\t\t // no showmatch\n\tp_sta = 0;\t\t // no smarttab\n#ifdef FEAT_CMDL_INFO\n\tif (p_ru)\n\t status_redraw_all(); // redraw to remove the ruler\n\tp_ru = 0;\t\t // no ruler\n#endif\n#ifdef FEAT_RIGHTLEFT\n\tp_ri = 0;\t\t // no reverse insert\n\tp_hkmap = 0;\t\t // no Hebrew keyboard\n#endif\n\t// set global values for local buffer options\n\tp_tw = 0;\n\tp_wm = 0;\n\tp_sts = 0;\n\tp_ai = 0;\n#ifdef FEAT_VARTABS\n\tif (p_vsts)\n\t free_string_option(p_vsts);\n\tp_vsts = empty_option;\n#endif\n }\n\n /*\n * Paste switched from on to off: Restore saved values.\n */\n else if (old_p_paste)\n {\n\t// restore options for each buffer\n\tFOR_ALL_BUFFERS(buf)\n\t{\n\t buf->b_p_tw = buf->b_p_tw_nopaste;\n\t buf->b_p_wm = buf->b_p_wm_nopaste;\n\t buf->b_p_sts = buf->b_p_sts_nopaste;\n\t buf->b_p_ai = buf->b_p_ai_nopaste;\n\t buf->b_p_et = buf->b_p_et_nopaste;\n#ifdef FEAT_VARTABS\n\t if (buf->b_p_vsts)\n\t\tfree_string_option(buf->b_p_vsts);\n\t buf->b_p_vsts = buf->b_p_vsts_nopaste\n\t\t\t ? vim_strsave(buf->b_p_vsts_nopaste) : empty_option;\n\t if (buf->b_p_vsts_array)\n\t\tvim_free(buf->b_p_vsts_array);\n\t if (buf->b_p_vsts && buf->b_p_vsts != empty_option)\n\t\t(void)tabstop_set(buf->b_p_vsts, &buf->b_p_vsts_array);\n\t else\n\t\tbuf->b_p_vsts_array = 0;\n#endif\n\t}\n\n\t// restore global options\n\tp_sm = save_sm;\n\tp_sta = save_sta;\n#ifdef FEAT_CMDL_INFO\n\tif (p_ru != save_ru)\n\t status_redraw_all(); // redraw to draw the ruler\n\tp_ru = save_ru;\n#endif\n#ifdef FEAT_RIGHTLEFT\n\tp_ri = save_ri;\n\tp_hkmap = save_hkmap;\n#endif\n\t// set global values for local buffer options\n\tp_ai = p_ai_nopaste;\n\tp_et = p_et_nopaste;\n\tp_sts = p_sts_nopaste;\n\tp_tw = p_tw_nopaste;\n\tp_wm = p_wm_nopaste;\n#ifdef FEAT_VARTABS\n\tif (p_vsts)\n\t free_string_option(p_vsts);\n\tp_vsts = p_vsts_nopaste ? vim_strsave(p_vsts_nopaste) : empty_option;\n#endif\n }\n\n old_p_paste = p_paste;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-122', 'CWE-787'], 'message': 'patch 8.2.4245: \":retab 0\" may cause illegal memory access\n\nProblem: \":retab 0\" may cause illegal memory access.\nSolution: Limit the value of 'tabstop' to 10000.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: free_command (void *vp, int *error)\n{\n struct command *command = vp;\n struct buffer *buffer = command->slice.buffer;\n\n if (buffer != NULL) {\n if (--buffer->refs == 0) {\n free (buffer->data);\n free (buffer);\n }\n }\n\n free (command);\n\n return 1; /* auto-retires the command */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-252'], 'message': 'copy: CVE-2022-0485: Fail nbdcopy if NBD read or write fails\n\nnbdcopy has a nasty bug when performing multi-threaded copies using\nasynchronous nbd calls - it was blindly treating the completion of an\nasynchronous command as successful, rather than checking the *error\nparameter. This can result in the silent creation of a corrupted\nimage in two different ways: when a read fails, we blindly wrote\ngarbage to the destination; when a write fails, we did not flag that\nthe destination was not written.\n\nSince nbdcopy already calls exit() on a synchronous read or write\nfailure to a file, doing the same for an asynchronous op to an NBD\nserver is the simplest solution. A nicer solution, but more invasive\nto code and thus not done here, might be to allow up to N retries of\nthe transaction (in case the read or write failure was transient), or\neven having a mode where as much data is copied as possible (portions\nof the copy that failed would be logged on stderr, and nbdcopy would\nstill fail with a non-zero exit status, but this would copy more than\njust stopping at the first error, as can be done with rsync or\nddrescue).\n\nNote that since we rely on auto-retiring and do NOT call\nnbd_aio_command_completed, our completion callbacks must always return\n1 (if they do not exit() first), even when acting on *error, so as not\nleave the command allocated until nbd_close. As such, there is no\nsane way to return an error to a manual caller of the callback, and\ntherefore we can drop dead code that calls perror() and exit() if the\ncallback \"failed\". It is also worth documenting the contract on when\nwe must manually call the callback during the asynch_zero callback, so\nthat we do not leak or double-free the command; thankfully, all the\nexisting code paths were correct.\n\nThe added testsuite script demonstrates several scenarios, some of\nwhich fail without the rest of this patch in place, and others which\nshowcase ways in which sparse images can bypass errors.\n\nOnce backports are complete, a followup patch on the main branch will\nedit docs/libnbd-security.pod with the mailing list announcement of\nthe stable branch commit ids and release versions that incorporate\nthis fix.\n\nReported-by: Nir Soffer \nFixes: bc896eec4d (\"copy: Implement multi-conn, multiple threads, multiple requests in flight.\", v1.5.6)\nFixes: https://bugzilla.redhat.com/2046194\nMessage-Id: <20220203202558.203013-6-eblake@redhat.com>\nAcked-by: Richard W.M. Jones \nAcked-by: Nir Soffer \n[eblake: fix error message per Nir, tweak requires lines in unit test per Rich]\nReviewed-by: Laszlo Ersek '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static ssize_t cgroup_release_agent_write(struct kernfs_open_file *of,\n\t\t\t\t\t char *buf, size_t nbytes, loff_t off)\n{\n\tstruct cgroup *cgrp;\n\n\tBUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);\n\n\tcgrp = cgroup_kn_lock_live(of->kn, false);\n\tif (!cgrp)\n\t\treturn -ENODEV;\n\tspin_lock(&release_agent_path_lock);\n\tstrlcpy(cgrp->root->release_agent_path, strstrip(buf),\n\t\tsizeof(cgrp->root->release_agent_path));\n\tspin_unlock(&release_agent_path_lock);\n\tcgroup_kn_unlock(of->kn);\n\treturn nbytes;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-287', 'CWE-269'], 'message': 'cgroup-v1: Require capabilities to set release_agent\n\nThe cgroup release_agent is called with call_usermodehelper. The function\ncall_usermodehelper starts the release_agent with a full set fo capabilities.\nTherefore require capabilities when setting the release_agaent.\n\nReported-by: Tabitha Sable \nTested-by: Tabitha Sable \nFixes: 81a6a5cdd2c5 (\"Task Control Groups: automatic userspace notification of idle cgroups\")\nCc: stable@vger.kernel.org # v2.6.24+\nSigned-off-by: \"Eric W. Biederman\" \nSigned-off-by: Tejun Heo '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static char *ask_new_field(struct chfn_control *ctl, const char *question,\n\t\t\t char *def_val)\n{\n\tint len;\n\tchar *buf = NULL; /* leave initialized to NULL or getline segfaults */\n#ifndef HAVE_LIBREADLINE\n\tsize_t dummy = 0;\n#endif\n\n\tif (!def_val)\n\t\tdef_val = \"\";\n\twhile (true) {\n\t\tprintf(\"%s [%s]:\", question, def_val);\n\t\t__fpurge(stdin);\n#ifdef HAVE_LIBREADLINE\n\t\trl_bind_key('\\t', rl_insert);\n\t\tif ((buf = readline(\" \")) == NULL)\n#else\n\t\tputchar(' ');\n\t\tfflush(stdout);\n\t\tif (getline(&buf, &dummy, stdin) < 0)\n#endif\n\t\t\terrx(EXIT_FAILURE, _(\"Aborted.\"));\n\t\t/* remove white spaces from string end */\n\t\tltrim_whitespace((unsigned char *) buf);\n\t\tlen = rtrim_whitespace((unsigned char *) buf);\n\t\tif (len == 0) {\n\t\t\tfree(buf);\n\t\t\treturn xstrdup(def_val);\n\t\t}\n\t\tif (!strcasecmp(buf, \"none\")) {\n\t\t\tfree(buf);\n\t\t\tctl->changed = 1;\n\t\t\treturn xstrdup(\"\");\n\t\t}\n\t\tif (check_gecos_string(question, buf) >= 0)\n\t\t\tbreak;\n\t}\n\tctl->changed = 1;\n\treturn buf;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-209'], 'message': 'chsh, chfn: remove readline support [CVE-2022-0563]\n\nThe readline library uses INPUTRC= environment variable to get a path\nto the library config file. When the library cannot parse the\nspecified file, it prints an error message containing data from the\nfile.\n\nUnfortunately, the library does not use secure_getenv() (or a similar\nconcept) to avoid vulnerabilities that could occur if set-user-ID or\nset-group-ID programs.\n\nReported-by: Rory Mackie \nSigned-off-by: Karel Zak '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int yam_siocdevprivate(struct net_device *dev, struct ifreq *ifr, void __user *data, int cmd)\n{\n\tstruct yam_port *yp = netdev_priv(dev);\n\tstruct yamdrv_ioctl_cfg yi;\n\tstruct yamdrv_ioctl_mcs *ym;\n\tint ioctl_cmd;\n\n\tif (copy_from_user(&ioctl_cmd, data, sizeof(int)))\n\t\treturn -EFAULT;\n\n\tif (yp->magic != YAM_MAGIC)\n\t\treturn -EINVAL;\n\n\tif (!capable(CAP_NET_ADMIN))\n\t\treturn -EPERM;\n\n\tif (cmd != SIOCDEVPRIVATE)\n\t\treturn -EINVAL;\n\n\tswitch (ioctl_cmd) {\n\n\tcase SIOCYAMRESERVED:\n\t\treturn -EINVAL;\t\t\t/* unused */\n\n\tcase SIOCYAMSMCS:\n\t\tif (netif_running(dev))\n\t\t\treturn -EINVAL;\t\t/* Cannot change this parameter when up */\n\t\tym = memdup_user(data, sizeof(struct yamdrv_ioctl_mcs));\n\t\tif (IS_ERR(ym))\n\t\t\treturn PTR_ERR(ym);\n\t\tif (ym->cmd != SIOCYAMSMCS)\n\t\t\treturn -EINVAL;\n\t\tif (ym->bitrate > YAM_MAXBITRATE) {\n\t\t\tkfree(ym);\n\t\t\treturn -EINVAL;\n\t\t}\n\t\t/* setting predef as 0 for loading userdefined mcs data */\n\t\tadd_mcs(ym->bits, ym->bitrate, 0);\n\t\tkfree(ym);\n\t\tbreak;\n\n\tcase SIOCYAMSCFG:\n\t\tif (!capable(CAP_SYS_RAWIO))\n\t\t\treturn -EPERM;\n\t\tif (copy_from_user(&yi, data, sizeof(struct yamdrv_ioctl_cfg)))\n\t\t\treturn -EFAULT;\n\n\t\tif (yi.cmd != SIOCYAMSCFG)\n\t\t\treturn -EINVAL;\n\t\tif ((yi.cfg.mask & YAM_IOBASE) && netif_running(dev))\n\t\t\treturn -EINVAL;\t\t/* Cannot change this parameter when up */\n\t\tif ((yi.cfg.mask & YAM_IRQ) && netif_running(dev))\n\t\t\treturn -EINVAL;\t\t/* Cannot change this parameter when up */\n\t\tif ((yi.cfg.mask & YAM_BITRATE) && netif_running(dev))\n\t\t\treturn -EINVAL;\t\t/* Cannot change this parameter when up */\n\t\tif ((yi.cfg.mask & YAM_BAUDRATE) && netif_running(dev))\n\t\t\treturn -EINVAL;\t\t/* Cannot change this parameter when up */\n\n\t\tif (yi.cfg.mask & YAM_IOBASE) {\n\t\t\typ->iobase = yi.cfg.iobase;\n\t\t\tdev->base_addr = yi.cfg.iobase;\n\t\t}\n\t\tif (yi.cfg.mask & YAM_IRQ) {\n\t\t\tif (yi.cfg.irq > 15)\n\t\t\t\treturn -EINVAL;\n\t\t\typ->irq = yi.cfg.irq;\n\t\t\tdev->irq = yi.cfg.irq;\n\t\t}\n\t\tif (yi.cfg.mask & YAM_BITRATE) {\n\t\t\tif (yi.cfg.bitrate > YAM_MAXBITRATE)\n\t\t\t\treturn -EINVAL;\n\t\t\typ->bitrate = yi.cfg.bitrate;\n\t\t}\n\t\tif (yi.cfg.mask & YAM_BAUDRATE) {\n\t\t\tif (yi.cfg.baudrate > YAM_MAXBAUDRATE)\n\t\t\t\treturn -EINVAL;\n\t\t\typ->baudrate = yi.cfg.baudrate;\n\t\t}\n\t\tif (yi.cfg.mask & YAM_MODE) {\n\t\t\tif (yi.cfg.mode > YAM_MAXMODE)\n\t\t\t\treturn -EINVAL;\n\t\t\typ->dupmode = yi.cfg.mode;\n\t\t}\n\t\tif (yi.cfg.mask & YAM_HOLDDLY) {\n\t\t\tif (yi.cfg.holddly > YAM_MAXHOLDDLY)\n\t\t\t\treturn -EINVAL;\n\t\t\typ->holdd = yi.cfg.holddly;\n\t\t}\n\t\tif (yi.cfg.mask & YAM_TXDELAY) {\n\t\t\tif (yi.cfg.txdelay > YAM_MAXTXDELAY)\n\t\t\t\treturn -EINVAL;\n\t\t\typ->txd = yi.cfg.txdelay;\n\t\t}\n\t\tif (yi.cfg.mask & YAM_TXTAIL) {\n\t\t\tif (yi.cfg.txtail > YAM_MAXTXTAIL)\n\t\t\t\treturn -EINVAL;\n\t\t\typ->txtail = yi.cfg.txtail;\n\t\t}\n\t\tif (yi.cfg.mask & YAM_PERSIST) {\n\t\t\tif (yi.cfg.persist > YAM_MAXPERSIST)\n\t\t\t\treturn -EINVAL;\n\t\t\typ->pers = yi.cfg.persist;\n\t\t}\n\t\tif (yi.cfg.mask & YAM_SLOTTIME) {\n\t\t\tif (yi.cfg.slottime > YAM_MAXSLOTTIME)\n\t\t\t\treturn -EINVAL;\n\t\t\typ->slot = yi.cfg.slottime;\n\t\t\typ->slotcnt = yp->slot / 10;\n\t\t}\n\t\tbreak;\n\n\tcase SIOCYAMGCFG:\n\t\tmemset(&yi, 0, sizeof(yi));\n\t\tyi.cfg.mask = 0xffffffff;\n\t\tyi.cfg.iobase = yp->iobase;\n\t\tyi.cfg.irq = yp->irq;\n\t\tyi.cfg.bitrate = yp->bitrate;\n\t\tyi.cfg.baudrate = yp->baudrate;\n\t\tyi.cfg.mode = yp->dupmode;\n\t\tyi.cfg.txdelay = yp->txd;\n\t\tyi.cfg.holddly = yp->holdd;\n\t\tyi.cfg.txtail = yp->txtail;\n\t\tyi.cfg.persist = yp->pers;\n\t\tyi.cfg.slottime = yp->slot;\n\t\tif (copy_to_user(data, &yi, sizeof(struct yamdrv_ioctl_cfg)))\n\t\t\treturn -EFAULT;\n\t\tbreak;\n\n\tdefault:\n\t\treturn -EINVAL;\n\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401'], 'message': 'yam: fix a memory leak in yam_siocdevprivate()\n\nym needs to be free when ym->cmd != SIOCYAMSMCS.\n\nFixes: 0781168e23a2 (\"yam: fix a missing-check bug\")\nSigned-off-by: Hangyu Hua \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: R_API RBinJavaElementValue *r_bin_java_element_value_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {\n\tut32 i = 0;\n\tut64 offset = 0;\n\tRBinJavaElementValue *element_value = R_NEW0 (RBinJavaElementValue);\n\tif (!element_value) {\n\t\treturn NULL;\n\t}\n\tRBinJavaElementValuePair *evps = NULL;\n\telement_value->metas = R_NEW0 (RBinJavaMetaInfo);\n\tif (!element_value->metas) {\n\t\tR_FREE (element_value);\n\t\treturn NULL;\n\t}\n\telement_value->file_offset = buf_offset;\n\telement_value->tag = buffer[offset];\n\telement_value->size += 1;\n\toffset += 1;\n\telement_value->metas->type_info = (void *) r_bin_java_get_ev_meta_from_tag (element_value->tag);\n\tswitch (element_value->tag) {\n\tcase R_BIN_JAVA_EV_TAG_BYTE:\n\tcase R_BIN_JAVA_EV_TAG_CHAR:\n\tcase R_BIN_JAVA_EV_TAG_DOUBLE:\n\tcase R_BIN_JAVA_EV_TAG_FLOAT:\n\tcase R_BIN_JAVA_EV_TAG_INT:\n\tcase R_BIN_JAVA_EV_TAG_LONG:\n\tcase R_BIN_JAVA_EV_TAG_SHORT:\n\tcase R_BIN_JAVA_EV_TAG_BOOLEAN:\n\tcase R_BIN_JAVA_EV_TAG_STRING:\n\t\t// look up value in bin->cp_list\n\t\t// (ut16) read and set const_value.const_value_idx\n\t\telement_value->value.const_value.const_value_idx = R_BIN_JAVA_USHORT (buffer, offset);\n\t\telement_value->size += 2;\n\t\t// look-up, deep copy, and set const_value.const_value_cp_obj\n\t\telement_value->value.const_value.const_value_cp_obj = r_bin_java_clone_cp_idx (R_BIN_JAVA_GLOBAL_BIN, element_value->value.const_value.const_value_idx);\n\t\tbreak;\n\tcase R_BIN_JAVA_EV_TAG_ENUM:\n\t\t// (ut16) read and set enum_const_value.type_name_idx\n\t\telement_value->value.enum_const_value.type_name_idx = R_BIN_JAVA_USHORT (buffer, offset);\n\t\telement_value->size += 2;\n\t\toffset += 2;\n\t\t// (ut16) read and set enum_const_value.const_name_idx\n\t\telement_value->value.enum_const_value.const_name_idx = R_BIN_JAVA_USHORT (buffer, offset);\n\t\telement_value->size += 2;\n\t\toffset += 2;\n\t\t// look up type_name_index in bin->cp_list\n\t\t// look-up, deep copy, and set enum_const_value.const_name_cp_obj\n\t\telement_value->value.enum_const_value.const_name_cp_obj = r_bin_java_clone_cp_idx (R_BIN_JAVA_GLOBAL_BIN, element_value->value.enum_const_value.const_name_idx);\n\t\t// look-up, deep copy, and set enum_const_value.type_name_cp_obj\n\t\telement_value->value.enum_const_value.type_name_cp_obj = r_bin_java_clone_cp_idx (R_BIN_JAVA_GLOBAL_BIN, element_value->value.enum_const_value.type_name_idx);\n\t\tbreak;\n\tcase R_BIN_JAVA_EV_TAG_CLASS:\n\t\t// (ut16) read and set class_value.class_info_idx\n\t\telement_value->value.class_value.class_info_idx = R_BIN_JAVA_USHORT (buffer, offset);\n\t\telement_value->size += 2;\n\t\toffset += 2;\n\t\t// look up type_name_index in bin->cp_list\n\t\t// look-up, deep copy, and set class_value.class_info_cp_obj\n\t\telement_value->value.class_value.class_info_cp_obj = r_bin_java_clone_cp_idx (R_BIN_JAVA_GLOBAL_BIN, element_value->value.class_value.class_info_idx);\n\t\tbreak;\n\tcase R_BIN_JAVA_EV_TAG_ARRAY:\n\t\t// (ut16) read and set array_value.num_values\n\t\telement_value->value.array_value.num_values = R_BIN_JAVA_USHORT (buffer, offset);\n\t\telement_value->size += 2;\n\t\toffset += 2;\n\t\telement_value->value.array_value.values = r_list_new ();\n\t\tfor (i = 0; i < element_value->value.array_value.num_values; i++) {\n\t\t\tif (offset >= sz) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tRBinJavaElementValue *ev_element = r_bin_java_element_value_new (buffer + offset, sz - offset, buf_offset + offset);\n\t\t\tif (ev_element) {\n\t\t\t\telement_value->size += ev_element->size;\n\t\t\t\toffset += ev_element->size;\n\t\t\t\t// read array_value.num_values, and append to array_value.values\n\t\t\t\tr_list_append (element_value->value.array_value.values, (void *) ev_element);\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase R_BIN_JAVA_EV_TAG_ANNOTATION:\n\t\t// annotation new is not used here.\n\t\t// (ut16) read and set annotation_value.type_idx;\n\t\tif (offset + 8 < sz) {\n\t\t\telement_value->value.annotation_value.type_idx = R_BIN_JAVA_USHORT (buffer, offset);\n\t\t\telement_value->size += 2;\n\t\t\toffset += 2;\n\t\t\t// (ut16) read and set annotation_value.num_element_value_pairs;\n\t\t\telement_value->value.annotation_value.num_element_value_pairs = R_BIN_JAVA_USHORT (buffer, offset);\n\t\t\telement_value->size += 2;\n\t\t\toffset += 2;\n\t\t}\n\t\telement_value->value.annotation_value.element_value_pairs = r_list_newf (r_bin_java_element_pair_free);\n\t\t// read annotation_value.num_element_value_pairs, and append to annotation_value.element_value_pairs\n\t\tfor (i = 0; i < element_value->value.annotation_value.num_element_value_pairs; i++) {\n\t\t\tif (offset > sz) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tevps = r_bin_java_element_pair_new (buffer + offset, sz - offset, buf_offset + offset);\n\t\t\tif (evps) {\n\t\t\t\telement_value->size += evps->size;\n\t\t\t\toffset += evps->size;\n\t\t\t}\n\t\t\tif (evps == NULL) {\n\t\t\t\t// TODO: eprintf error when reading element pair\n\t\t\t}\n\t\t\tr_list_append (element_value->value.annotation_value.element_value_pairs, (void *) evps);\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\t// eprintf unable to handle tag\n\t\tbreak;\n\t}\n\treturn element_value;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-788'], 'message': 'Improve boundary checks to fix oobread segfaults ##crash\n\n* Reported by Cen Zhang via huntr.dev\n* Reproducer: bins/fuzzed/javaoob-havoc.class'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: R_API RBinJavaAttrInfo *r_bin_java_enclosing_methods_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {\n\tut64 offset = 6;\n\tRBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);\n\tif (!attr || sz < 10) {\n\t\tfree (attr);\n\t\treturn NULL;\n\t}\n\tattr->type = R_BIN_JAVA_ATTR_TYPE_ENCLOSING_METHOD_ATTR;\n\tattr->info.enclosing_method_attr.class_idx = R_BIN_JAVA_USHORT (buffer, offset);\n\toffset += 2;\n\tattr->info.enclosing_method_attr.method_idx = R_BIN_JAVA_USHORT (buffer, offset);\n\toffset += 2;\n\tattr->info.enclosing_method_attr.class_name = r_bin_java_get_name_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, attr->info.enclosing_method_attr.class_idx);\n\tif (attr->info.enclosing_method_attr.class_name == NULL) {\n\t\teprintf (\"Could not resolve enclosing class name for the enclosed method.\\n\");\n\t}\n\tattr->info.enclosing_method_attr.method_name = r_bin_java_get_name_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, attr->info.enclosing_method_attr.method_idx);\n\tif (attr->info.enclosing_method_attr.class_name == NULL) {\n\t\teprintf (\"Could not resolve method descriptor for the enclosed method.\\n\");\n\t}\n\tattr->info.enclosing_method_attr.method_descriptor = r_bin_java_get_desc_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, attr->info.enclosing_method_attr.method_idx);\n\tif (attr->info.enclosing_method_attr.method_name == NULL) {\n\t\teprintf (\"Could not resolve method name for the enclosed method.\\n\");\n\t}\n\tattr->size = offset;\n\treturn attr;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-788'], 'message': 'Improve boundary checks to fix oobread segfaults ##crash\n\n* Reported by Cen Zhang via huntr.dev\n* Reproducer: bins/fuzzed/javaoob-havoc.class'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: R_API bool r_io_bank_map_add_top(RIO *io, const ut32 bankid, const ut32 mapid) {\n\tRIOBank *bank = r_io_bank_get (io, bankid);\n\tRIOMap *map = r_io_map_get (io, mapid);\n\tr_return_val_if_fail (io && bank && map, false);\n\tRIOMapRef *mapref = _mapref_from_map (map);\n\tif (!mapref) {\n\t\treturn false;\n\t}\n\tRIOSubMap *sm = r_io_submap_new (io, mapref);\n\tif (!sm) {\n\t\tfree (mapref);\n\t\treturn false;\n\t}\n\tRRBNode *entry = _find_entry_submap_node (bank, sm);\n\tif (!entry) {\n\t\t// no intersection with any submap, so just insert\n\t\tif (!r_crbtree_insert (bank->submaps, sm, _find_sm_by_from_vaddr_cb, NULL)) {\n\t\t\tfree (sm);\n\t\t\tfree (mapref);\n\t\t\treturn false;\n\t\t}\n\t\tr_list_append (bank->maprefs, mapref);\n\t\treturn true;\n\t}\n\tbank->last_used = NULL;\n\tRIOSubMap *bd = (RIOSubMap *)entry->data;\n\tif (r_io_submap_to (bd) == r_io_submap_to (sm) &&\n\t\tr_io_submap_from (bd) >= r_io_submap_from (sm)) {\n\t\t// _find_entry_submap_node guarantees, that there is no submap\n\t\t// prior to bd in the range of sm, so instead of deleting and inserting\n\t\t// we can just memcpy\n\t\tmemcpy (bd, sm, sizeof (RIOSubMap));\n\t\tfree (sm);\n\t\tr_list_append (bank->maprefs, mapref);\n\t\treturn true;\n\t}\n\tif (r_io_submap_from (bd) < r_io_submap_from (sm) &&\n\t\tr_io_submap_to (sm) < r_io_submap_to (bd)) {\n\t\t// split bd into 2 maps => bd and bdsm\n\t\tRIOSubMap *bdsm = R_NEWCOPY (RIOSubMap, bd);\n\t\tif (!bdsm) {\n\t\t\tfree (sm);\n\t\t\tfree (mapref);\n\t\t\treturn false;\n\t\t}\n\t\tr_io_submap_set_from (bdsm, r_io_submap_to (sm) + 1);\n\t\tr_io_submap_set_to (bd, r_io_submap_from (sm) - 1);\n\t\t// TODO: insert and check return value, before adjusting sm size\n\t\tif (!r_crbtree_insert (bank->submaps, sm, _find_sm_by_from_vaddr_cb, NULL)) {\n\t\t\tfree (sm);\n\t\t\tfree (bdsm);\n\t\t\tfree (mapref);\n\t\t\treturn false;\n\t\t}\n\t\tif (!r_crbtree_insert (bank->submaps, bdsm, _find_sm_by_from_vaddr_cb, NULL)) {\n\t\t\tr_crbtree_delete (bank->submaps, sm, _find_sm_by_from_vaddr_cb, NULL);\n\t\t\tfree (sm);\n\t\t\tfree (bdsm);\n\t\t\tfree (mapref);\n\t\t\treturn false;\n\t\t}\n\t\tr_list_append (bank->maprefs, mapref);\n\t\treturn true;\n\t}\n\n\t// guaranteed intersection\n\tif (r_io_submap_from (bd) < r_io_submap_from (sm)) {\n\t\tr_io_submap_set_to (bd, r_io_submap_from (sm) - 1);\n\t\tentry = r_rbnode_next (entry);\n\t}\n\twhile (entry && r_io_submap_to (((RIOSubMap *)entry->data)) <= r_io_submap_to (sm)) {\n\t\t//delete all submaps that are completly included in sm\n\t\tRRBNode *next = r_rbnode_next (entry);\n\t\t// this can be optimized, there is no need to do search here\n\t\tbool a = r_crbtree_delete (bank->submaps, entry->data, _find_sm_by_from_vaddr_cb, NULL);\n\t\tif (!a) {\n\t\t\tbreak;\n\t\t}\n\t\tentry = next;\n\t}\n\tif (entry && r_io_submap_from (((RIOSubMap *)entry->data)) <= r_io_submap_to (sm)) {\n\t\tbd = (RIOSubMap *)entry->data;\n\t\tr_io_submap_set_from (bd, r_io_submap_to (sm) + 1);\n\t}\n\tif (!r_crbtree_insert (bank->submaps, sm, _find_sm_by_from_vaddr_cb, NULL)) {\n\t\tfree (sm);\n\t\tfree (mapref);\n\t\treturn false;\n\t}\n\tr_list_append (bank->maprefs, mapref);\n\treturn true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Prefer memleak over usaf in io.bank's rbtree bug ##crash\n\n* That's a workaround, proper fix will come later\n* Reproducer: bins/fuzzed/iobank-crash\n* Reported by Akyne Choi via huntr.dev'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: PREFIX(prologTok)(const ENCODING *enc, const char *ptr, const char *end,\n const char **nextTokPtr) {\n int tok;\n if (ptr >= end)\n return XML_TOK_NONE;\n if (MINBPC(enc) > 1) {\n size_t n = end - ptr;\n if (n & (MINBPC(enc) - 1)) {\n n &= ~(MINBPC(enc) - 1);\n if (n == 0)\n return XML_TOK_PARTIAL;\n end = ptr + n;\n }\n }\n switch (BYTE_TYPE(enc, ptr)) {\n case BT_QUOT:\n return PREFIX(scanLit)(BT_QUOT, enc, ptr + MINBPC(enc), end, nextTokPtr);\n case BT_APOS:\n return PREFIX(scanLit)(BT_APOS, enc, ptr + MINBPC(enc), end, nextTokPtr);\n case BT_LT: {\n ptr += MINBPC(enc);\n REQUIRE_CHAR(enc, ptr, end);\n switch (BYTE_TYPE(enc, ptr)) {\n case BT_EXCL:\n return PREFIX(scanDecl)(enc, ptr + MINBPC(enc), end, nextTokPtr);\n case BT_QUEST:\n return PREFIX(scanPi)(enc, ptr + MINBPC(enc), end, nextTokPtr);\n case BT_NMSTRT:\n case BT_HEX:\n case BT_NONASCII:\n case BT_LEAD2:\n case BT_LEAD3:\n case BT_LEAD4:\n *nextTokPtr = ptr - MINBPC(enc);\n return XML_TOK_INSTANCE_START;\n }\n *nextTokPtr = ptr;\n return XML_TOK_INVALID;\n }\n case BT_CR:\n if (ptr + MINBPC(enc) == end) {\n *nextTokPtr = end;\n /* indicate that this might be part of a CR/LF pair */\n return -XML_TOK_PROLOG_S;\n }\n /* fall through */\n case BT_S:\n case BT_LF:\n for (;;) {\n ptr += MINBPC(enc);\n if (! HAS_CHAR(enc, ptr, end))\n break;\n switch (BYTE_TYPE(enc, ptr)) {\n case BT_S:\n case BT_LF:\n break;\n case BT_CR:\n /* don't split CR/LF pair */\n if (ptr + MINBPC(enc) != end)\n break;\n /* fall through */\n default:\n *nextTokPtr = ptr;\n return XML_TOK_PROLOG_S;\n }\n }\n *nextTokPtr = ptr;\n return XML_TOK_PROLOG_S;\n case BT_PERCNT:\n return PREFIX(scanPercent)(enc, ptr + MINBPC(enc), end, nextTokPtr);\n case BT_COMMA:\n *nextTokPtr = ptr + MINBPC(enc);\n return XML_TOK_COMMA;\n case BT_LSQB:\n *nextTokPtr = ptr + MINBPC(enc);\n return XML_TOK_OPEN_BRACKET;\n case BT_RSQB:\n ptr += MINBPC(enc);\n if (! HAS_CHAR(enc, ptr, end))\n return -XML_TOK_CLOSE_BRACKET;\n if (CHAR_MATCHES(enc, ptr, ASCII_RSQB)) {\n REQUIRE_CHARS(enc, ptr, end, 2);\n if (CHAR_MATCHES(enc, ptr + MINBPC(enc), ASCII_GT)) {\n *nextTokPtr = ptr + 2 * MINBPC(enc);\n return XML_TOK_COND_SECT_CLOSE;\n }\n }\n *nextTokPtr = ptr;\n return XML_TOK_CLOSE_BRACKET;\n case BT_LPAR:\n *nextTokPtr = ptr + MINBPC(enc);\n return XML_TOK_OPEN_PAREN;\n case BT_RPAR:\n ptr += MINBPC(enc);\n if (! HAS_CHAR(enc, ptr, end))\n return -XML_TOK_CLOSE_PAREN;\n switch (BYTE_TYPE(enc, ptr)) {\n case BT_AST:\n *nextTokPtr = ptr + MINBPC(enc);\n return XML_TOK_CLOSE_PAREN_ASTERISK;\n case BT_QUEST:\n *nextTokPtr = ptr + MINBPC(enc);\n return XML_TOK_CLOSE_PAREN_QUESTION;\n case BT_PLUS:\n *nextTokPtr = ptr + MINBPC(enc);\n return XML_TOK_CLOSE_PAREN_PLUS;\n case BT_CR:\n case BT_LF:\n case BT_S:\n case BT_GT:\n case BT_COMMA:\n case BT_VERBAR:\n case BT_RPAR:\n *nextTokPtr = ptr;\n return XML_TOK_CLOSE_PAREN;\n }\n *nextTokPtr = ptr;\n return XML_TOK_INVALID;\n case BT_VERBAR:\n *nextTokPtr = ptr + MINBPC(enc);\n return XML_TOK_OR;\n case BT_GT:\n *nextTokPtr = ptr + MINBPC(enc);\n return XML_TOK_DECL_CLOSE;\n case BT_NUM:\n return PREFIX(scanPoundName)(enc, ptr + MINBPC(enc), end, nextTokPtr);\n# define LEAD_CASE(n) \\\n case BT_LEAD##n: \\\n if (end - ptr < n) \\\n return XML_TOK_PARTIAL_CHAR; \\\n if (IS_NMSTRT_CHAR(enc, ptr, n)) { \\\n ptr += n; \\\n tok = XML_TOK_NAME; \\\n break; \\\n } \\\n if (IS_NAME_CHAR(enc, ptr, n)) { \\\n ptr += n; \\\n tok = XML_TOK_NMTOKEN; \\\n break; \\\n } \\\n *nextTokPtr = ptr; \\\n return XML_TOK_INVALID;\n LEAD_CASE(2)\n LEAD_CASE(3)\n LEAD_CASE(4)\n# undef LEAD_CASE\n case BT_NMSTRT:\n case BT_HEX:\n tok = XML_TOK_NAME;\n ptr += MINBPC(enc);\n break;\n case BT_DIGIT:\n case BT_NAME:\n case BT_MINUS:\n# ifdef XML_NS\n case BT_COLON:\n# endif\n tok = XML_TOK_NMTOKEN;\n ptr += MINBPC(enc);\n break;\n case BT_NONASCII:\n if (IS_NMSTRT_CHAR_MINBPC(enc, ptr)) {\n ptr += MINBPC(enc);\n tok = XML_TOK_NAME;\n break;\n }\n if (IS_NAME_CHAR_MINBPC(enc, ptr)) {\n ptr += MINBPC(enc);\n tok = XML_TOK_NMTOKEN;\n break;\n }\n /* fall through */\n default:\n *nextTokPtr = ptr;\n return XML_TOK_INVALID;\n }\n while (HAS_CHAR(enc, ptr, end)) {\n switch (BYTE_TYPE(enc, ptr)) {\n CHECK_NAME_CASES(enc, ptr, end, nextTokPtr)\n case BT_GT:\n case BT_RPAR:\n case BT_COMMA:\n case BT_VERBAR:\n case BT_LSQB:\n case BT_PERCNT:\n case BT_S:\n case BT_CR:\n case BT_LF:\n *nextTokPtr = ptr;\n return tok;\n# ifdef XML_NS\n case BT_COLON:\n ptr += MINBPC(enc);\n switch (tok) {\n case XML_TOK_NAME:\n REQUIRE_CHAR(enc, ptr, end);\n tok = XML_TOK_PREFIXED_NAME;\n switch (BYTE_TYPE(enc, ptr)) {\n CHECK_NAME_CASES(enc, ptr, end, nextTokPtr)\n default:\n tok = XML_TOK_NMTOKEN;\n break;\n }\n break;\n case XML_TOK_PREFIXED_NAME:\n tok = XML_TOK_NMTOKEN;\n break;\n }\n break;\n# endif\n case BT_PLUS:\n if (tok == XML_TOK_NMTOKEN) {\n *nextTokPtr = ptr;\n return XML_TOK_INVALID;\n }\n *nextTokPtr = ptr + MINBPC(enc);\n return XML_TOK_NAME_PLUS;\n case BT_AST:\n if (tok == XML_TOK_NMTOKEN) {\n *nextTokPtr = ptr;\n return XML_TOK_INVALID;\n }\n *nextTokPtr = ptr + MINBPC(enc);\n return XML_TOK_NAME_ASTERISK;\n case BT_QUEST:\n if (tok == XML_TOK_NMTOKEN) {\n *nextTokPtr = ptr;\n return XML_TOK_INVALID;\n }\n *nextTokPtr = ptr + MINBPC(enc);\n return XML_TOK_NAME_QUESTION;\n default:\n *nextTokPtr = ptr;\n return XML_TOK_INVALID;\n }\n }\n return -tok;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-116'], 'message': 'lib: Add missing validation of encoding (CVE-2022-25235)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: win_new_tabpage(int after)\n{\n tabpage_T\t*tp = curtab;\n tabpage_T\t*prev_tp = curtab;\n tabpage_T\t*newtp;\n int\t\tn;\n\n newtp = alloc_tabpage();\n if (newtp == NULL)\n\treturn FAIL;\n\n // Remember the current windows in this Tab page.\n if (leave_tabpage(curbuf, TRUE) == FAIL)\n {\n\tvim_free(newtp);\n\treturn FAIL;\n }\n curtab = newtp;\n\n newtp->tp_localdir = (tp->tp_localdir == NULL)\n\t\t\t\t ? NULL : vim_strsave(tp->tp_localdir);\n // Create a new empty window.\n if (win_alloc_firstwin(tp->tp_curwin) == OK)\n {\n\t// Make the new Tab page the new topframe.\n\tif (after == 1)\n\t{\n\t // New tab page becomes the first one.\n\t newtp->tp_next = first_tabpage;\n\t first_tabpage = newtp;\n\t}\n\telse\n\t{\n\t if (after > 0)\n\t {\n\t\t// Put new tab page before tab page \"after\".\n\t\tn = 2;\n\t\tfor (tp = first_tabpage; tp->tp_next != NULL\n\t\t\t\t\t && n < after; tp = tp->tp_next)\n\t\t ++n;\n\t }\n\t newtp->tp_next = tp->tp_next;\n\t tp->tp_next = newtp;\n\t}\n\tnewtp->tp_firstwin = newtp->tp_lastwin = newtp->tp_curwin = curwin;\n\n\twin_init_size();\n\tfirstwin->w_winrow = tabline_height();\n\twin_comp_scroll(curwin);\n\n\tnewtp->tp_topframe = topframe;\n\tlast_status(FALSE);\n\n\tlastused_tabpage = prev_tp;\n\n#if defined(FEAT_GUI)\n\t// When 'guioptions' includes 'L' or 'R' may have to remove or add\n\t// scrollbars. Have to update them anyway.\n\tgui_may_update_scrollbars();\n#endif\n#ifdef FEAT_JOB_CHANNEL\n\tentering_window(curwin);\n#endif\n\n\tredraw_all_later(NOT_VALID);\n\tapply_autocmds(EVENT_WINNEW, NULL, NULL, FALSE, curbuf);\n\tapply_autocmds(EVENT_WINENTER, NULL, NULL, FALSE, curbuf);\n\tapply_autocmds(EVENT_TABNEW, NULL, NULL, FALSE, curbuf);\n\tapply_autocmds(EVENT_TABENTER, NULL, NULL, FALSE, curbuf);\n\treturn OK;\n }\n\n // Failed, get back the previous Tab page\n enter_tabpage(curtab, curbuf, TRUE, TRUE);\n return FAIL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'patch 8.2.4428: crash when switching tabpage while in the cmdline window\n\nProblem: Crash when switching tabpage while in the cmdline window.\nSolution: Disallow switching tabpage when in the cmdline window.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: xmlValidCtxtNormalizeAttributeValue(xmlValidCtxtPtr ctxt, xmlDocPtr doc,\n\t xmlNodePtr elem, const xmlChar *name, const xmlChar *value) {\n xmlChar *ret, *dst;\n const xmlChar *src;\n xmlAttributePtr attrDecl = NULL;\n int extsubset = 0;\n\n if (doc == NULL) return(NULL);\n if (elem == NULL) return(NULL);\n if (name == NULL) return(NULL);\n if (value == NULL) return(NULL);\n\n if ((elem->ns != NULL) && (elem->ns->prefix != NULL)) {\n\txmlChar fn[50];\n\txmlChar *fullname;\n\n\tfullname = xmlBuildQName(elem->name, elem->ns->prefix, fn, 50);\n\tif (fullname == NULL)\n\t return(NULL);\n\tattrDecl = xmlGetDtdAttrDesc(doc->intSubset, fullname, name);\n\tif ((attrDecl == NULL) && (doc->extSubset != NULL)) {\n\t attrDecl = xmlGetDtdAttrDesc(doc->extSubset, fullname, name);\n\t if (attrDecl != NULL)\n\t\textsubset = 1;\n\t}\n\tif ((fullname != fn) && (fullname != elem->name))\n\t xmlFree(fullname);\n }\n if ((attrDecl == NULL) && (doc->intSubset != NULL))\n\tattrDecl = xmlGetDtdAttrDesc(doc->intSubset, elem->name, name);\n if ((attrDecl == NULL) && (doc->extSubset != NULL)) {\n\tattrDecl = xmlGetDtdAttrDesc(doc->extSubset, elem->name, name);\n\tif (attrDecl != NULL)\n\t extsubset = 1;\n }\n\n if (attrDecl == NULL)\n\treturn(NULL);\n if (attrDecl->atype == XML_ATTRIBUTE_CDATA)\n\treturn(NULL);\n\n ret = xmlStrdup(value);\n if (ret == NULL)\n\treturn(NULL);\n src = value;\n dst = ret;\n while (*src == 0x20) src++;\n while (*src != 0) {\n\tif (*src == 0x20) {\n\t while (*src == 0x20) src++;\n\t if (*src != 0)\n\t\t*dst++ = 0x20;\n\t} else {\n\t *dst++ = *src++;\n\t}\n }\n *dst = 0;\n if ((doc->standalone) && (extsubset == 1) && (!xmlStrEqual(value, ret))) {\n\txmlErrValidNode(ctxt, elem, XML_DTD_NOT_STANDALONE,\n\"standalone: %s on %s value had to be normalized based on external subset declaration\\n\",\n\t name, elem->name, NULL);\n\tctxt->valid = 0;\n }\n return(ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': '[CVE-2022-23308] Use-after-free of ID and IDREF attributes\n\nIf a document is parsed with XML_PARSE_DTDVALID and without\nXML_PARSE_NOENT, the value of ID attributes has to be normalized after\npotentially expanding entities in xmlRemoveID. Otherwise, later calls\nto xmlGetID can return a pointer to previously freed memory.\n\nID attributes which are empty or contain only whitespace after\nentity expansion are affected in a similar way. This is fixed by\nnot storing such attributes in the ID table.\n\nThe test to detect streaming mode when validating against a DTD was\nbroken. In connection with the defects above, this could result in a\nuse-after-free when using the xmlReader interface with validation.\nFix detection of streaming mode to avoid similar issues. (This changes\nthe expected result of a test case. But as far as I can tell, using the\nXML reader with XIncludes referencing the root document never worked\nproperly, anyway.)\n\nAll of these issues can result in denial of service. Using xmlReader\nwith validation could result in disclosure of memory via the error\nchannel, typically stderr. The security impact of xmlGetID returning\na pointer to freed memory depends on the application. The typical use\ncase of calling xmlGetID on an unmodified document is not affected.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static bool r_bin_mdmp_init_directory_entry(struct r_bin_mdmp_obj *obj, struct minidump_directory *entry) {\n\tr_strf_buffer (128);\n\tstruct minidump_handle_operation_list handle_operation_list;\n\tstruct minidump_memory_list memory_list;\n\tstruct minidump_memory64_list memory64_list;\n\tstruct minidump_memory_info_list memory_info_list;\n\tstruct minidump_module_list module_list;\n\tstruct minidump_thread_list thread_list;\n\tstruct minidump_thread_ex_list thread_ex_list;\n\tstruct minidump_thread_info_list thread_info_list;\n\tstruct minidump_token_info_list token_info_list;\n\tstruct minidump_unloaded_module_list unloaded_module_list;\n\tut64 offset;\n\tint i, r;\n\n\t/* We could confirm data sizes but a malcious MDMP will always get around\n\t** this! But we can ensure that the data is not outside of the file */\n\tif ((ut64)entry->location.rva + entry->location.data_size > r_buf_size (obj->b)) {\n\t\teprintf (\"[ERROR] Size Mismatch - Stream data is larger than file size!\\n\");\n\t\treturn false;\n\t}\n\n\tswitch (entry->stream_type) {\n\tcase THREAD_LIST_STREAM:\n\t\tr = r_buf_read_at (obj->b, entry->location.rva, (ut8 *)&thread_list, sizeof (thread_list));\n\t\tif (r != sizeof (thread_list)) {\n\t\t\tbreak;\n\t\t}\n\n\t\tsdb_set (obj->kv, \"mdmp_thread.format\", \"ddddq?? \"\n\t\t\t\"ThreadId SuspendCount PriorityClass Priority \"\n\t\t\t\"Teb (mdmp_memory_descriptor)Stack \"\n\t\t\t\"(mdmp_location_descriptor)ThreadContext\", 0);\n\t\tsdb_num_set (obj->kv, \"mdmp_thread_list.offset\",\n\t\t\tentry->location.rva, 0);\n\t\tsdb_set (obj->kv, \"mdmp_thread_list.format\",\n\t\t\tr_strf (\"d[%d]? \"\n\t\t\t\t\"NumberOfThreads (mdmp_thread)Threads\",\n\t\t\t\tthread_list.number_of_threads),\n\t\t\t0);\n\n\t\t/* TODO: Not yet fully parsed or utilised */\n\t\tbreak;\n\tcase MODULE_LIST_STREAM:\n\t\tmodule_list.number_of_modules = r_buf_read_le32_at (obj->b, entry->location.rva);\n\n\t\tsdb_set (obj->kv, \"mdmp_module.format\", \"qddtd???qq \"\n\t\t\t\"BaseOfImage SizeOfImage CheckSum \"\n\t\t\t\"TimeDateStamp ModuleNameRVA \"\n\t\t\t\"(mdmp_vs_fixedfileinfo)VersionInfo \"\n\t\t\t\"(mdmp_location_descriptor)CvRecord \"\n\t\t\t\"(mdmp_location_descriptor)MiscRecord \"\n\t\t\t\"Reserved0 Reserved1\", 0);\n\t\tsdb_num_set (obj->kv, \"mdmp_module_list.offset\",\n\t\t\tentry->location.rva, 0);\n\t\tsdb_set (obj->kv, \"mdmp_module_list.format\",\n\t\t\tr_strf (\"d[%d]? \"\n\t\t\t\t\"NumberOfModule (mdmp_module)Modules\",\n\t\t\t\tmodule_list.number_of_modules),\n\t\t\t0);\n\n\t\toffset = entry->location.rva + sizeof (module_list);\n\t\tfor (i = 0; i < module_list.number_of_modules; i++) {\n\t\t\tstruct minidump_module *module = R_NEW (struct minidump_module);\n\t\t\tif (!module) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tread_module (obj->b, offset, module);\n\t\t\tr_list_append (obj->streams.modules, module);\n\t\t\toffset += sizeof (*module);\n\t\t}\n\t\tbreak;\n\tcase MEMORY_LIST_STREAM:\n\t\tr = r_buf_read_at (obj->b, entry->location.rva, (ut8 *)&memory_list, sizeof (memory_list));\n\t\tif (r != sizeof (memory_list)) {\n\t\t\tbreak;\n\t\t}\n\n\t\tsdb_num_set (obj->kv, \"mdmp_memory_list.offset\",\n\t\t\tentry->location.rva, 0);\n\t\tsdb_set (obj->kv, \"mdmp_memory_list.format\",\n\t\t\tr_strf (\"d[%d]? \"\n\t\t\t\t\"NumberOfMemoryRanges \"\n\t\t\t\t\"(mdmp_memory_descriptor)MemoryRanges \",\n\t\t\t\tmemory_list.number_of_memory_ranges),\n\t\t\t0);\n\n\t\toffset = entry->location.rva + sizeof (memory_list);\n\t\tfor (i = 0; i < memory_list.number_of_memory_ranges; i++) {\n\t\t\tstruct minidump_memory_descriptor *desc = R_NEW (struct minidump_memory_descriptor);\n\t\t\tif (!desc) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tr = r_buf_read_at (obj->b, offset, (ut8 *)desc, sizeof (*desc));\n\t\t\tif (r != sizeof (*desc)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tr_list_append (obj->streams.memories, desc);\n\t\t\toffset += sizeof (*desc);\n\t\t}\n\t\tbreak;\n\tcase EXCEPTION_STREAM:\n\t\t/* TODO: Not yet fully parsed or utilised */\n\t\tobj->streams.exception = R_NEW (struct minidump_exception_stream);\n\t\tif (!obj->streams.exception) {\n\t\t\tbreak;\n\t\t}\n\n\t\tr = r_buf_read_at (obj->b, entry->location.rva, (ut8 *)obj->streams.exception, sizeof (*obj->streams.exception));\n\t\tif (r != sizeof (*obj->streams.exception)) {\n\t\t\tbreak;\n\t\t}\n\n\t\tsdb_set (obj->kv, \"mdmp_exception.format\", \"[4]E[4]Eqqdd[15]q \"\n\t\t\t\t\t\t\t \"(mdmp_exception_code)ExceptionCode \"\n\t\t\t\t\t\t\t \"(mdmp_exception_flags)ExceptionFlags \"\n\t\t\t\t\t\t\t \"ExceptionRecord ExceptionAddress \"\n\t\t\t\t\t\t\t \"NumberParameters __UnusedAlignment \"\n\t\t\t\t\t\t\t \"ExceptionInformation\",\n\t\t\t0);\n\t\tsdb_num_set (obj->kv, \"mdmp_exception_stream.offset\",\n\t\t\tentry->location.rva, 0);\n\t\tsdb_set (obj->kv, \"mdmp_exception_stream.format\", \"dd?? \"\n\t\t\t\t\t\t\t\t \"ThreadId __Alignment \"\n\t\t\t\t\t\t\t\t \"(mdmp_exception)ExceptionRecord \"\n\t\t\t\t\t\t\t\t \"(mdmp_location_descriptor)ThreadContext\",\n\t\t\t0);\n\n\t\tbreak;\n\tcase SYSTEM_INFO_STREAM:\n\t\tobj->streams.system_info = R_NEW (struct minidump_system_info);\n\t\tif (!obj->streams.system_info) {\n\t\t\tbreak;\n\t\t}\n\t\tr = r_buf_read_at (obj->b, entry->location.rva, (ut8 *)obj->streams.system_info, sizeof (*obj->streams.system_info));\n\t\tif (r != sizeof (*obj->streams.system_info)) {\n\t\t\tbreak;\n\t\t}\n\n\t\tsdb_num_set (obj->kv, \"mdmp_system_info.offset\",\n\t\t\tentry->location.rva, 0);\n\t\t/* TODO: We need E as a byte! */\n\t\tsdb_set (obj->kv, \"mdmp_system_info.format\", \"[2]EwwbBddd[4]Ed[2]Ew[2]q \"\n\t\t\t\"(mdmp_processor_architecture)ProcessorArchitecture \"\n\t\t\t\"ProcessorLevel ProcessorRevision NumberOfProcessors \"\n\t\t\t\"(mdmp_product_type)ProductType \"\n\t\t\t\"MajorVersion MinorVersion BuildNumber (mdmp_platform_id)PlatformId \"\n\t\t\t\"CsdVersionRva (mdmp_suite_mask)SuiteMask Reserved2 ProcessorFeatures\", 0);\n\n\t\tbreak;\n\tcase THREAD_EX_LIST_STREAM:\n\t\t/* TODO: Not yet fully parsed or utilised */\n\t\tr = r_buf_read_at (obj->b, entry->location.rva, (ut8 *)&thread_ex_list, sizeof (thread_ex_list));\n\t\tif (r != sizeof (thread_ex_list)) {\n\t\t\tbreak;\n\t\t}\n\n\t\tsdb_set (obj->kv, \"mdmp_thread_ex.format\", \"ddddq??? \"\n\t\t\t\"ThreadId SuspendCount PriorityClass Priority \"\n\t\t\t\"Teb (mdmp_memory_descriptor)Stack \"\n\t\t\t\"(mdmp_location_descriptor)ThreadContext \"\n\t\t\t\"(mdmp_memory_descriptor)BackingStore\", 0);\n\t\tsdb_num_set (obj->kv, \"mdmp_thread_ex_list.offset\",\n\t\t\tentry->location.rva, 0);\n\t\tsdb_set (obj->kv, \"mdmp_thread_ex_list.format\",\n\t\t\tr_strf (\"d[%d]? NumberOfThreads \"\n\t\t\t\t\"(mdmp_thread_ex)Threads\",\n\t\t\t\tthread_ex_list.number_of_threads),\n\t\t\t0);\n\n\t\toffset = entry->location.rva + sizeof (thread_ex_list);\n\t\tfor (i = 0; i < thread_ex_list.number_of_threads; i++) {\n\t\t\tstruct minidump_thread_ex *thread = R_NEW (struct minidump_thread_ex);\n\t\t\tif (!thread) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tr = r_buf_read_at (obj->b, offset, (ut8 *)thread, sizeof (*thread));\n\t\t\tif (r != sizeof (*thread)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tr_list_append (obj->streams.ex_threads, thread);\n\t\t\toffset += sizeof (*thread);\n\t\t}\n\t\tbreak;\n\tcase MEMORY_64_LIST_STREAM:\n\t\tread_memory64_list (obj->b, entry->location.rva, &memory64_list);\n\n\t\tsdb_num_set (obj->kv, \"mdmp_memory64_list.offset\",\n\t\t\tentry->location.rva, 0);\n\t\tsdb_set (obj->kv, \"mdmp_memory64_list.format\",\n\t\t\tr_strf (\"qq[%\"PFMT64d\"]? NumberOfMemoryRanges \"\n\t\t\t\t\"BaseRva \"\n\t\t\t\t\"(mdmp_memory_descriptor64)MemoryRanges\",\n\t\t\t\tmemory64_list.number_of_memory_ranges),\n\t\t\t0);\n\n\t\tobj->streams.memories64.base_rva = memory64_list.base_rva;\n\t\toffset = entry->location.rva + sizeof (memory64_list);\n\t\tfor (i = 0; i < memory64_list.number_of_memory_ranges; i++) {\n\t\t\tstruct minidump_memory_descriptor64 *desc = R_NEW (struct minidump_memory_descriptor64);\n\t\t\tif (!desc) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tread_desc (obj->b, offset, desc);\n\t\t\tr_list_append (obj->streams.memories64.memories, desc);\n\t\t\toffset += sizeof (*desc);\n\t\t}\n\t\tbreak;\n\tcase COMMENT_STREAM_A:\n\t\t/* TODO: Not yet fully parsed or utilised */\n\t\tobj->streams.comments_a = R_NEWS (ut8, COMMENTS_SIZE);\n\t\tif (!obj->streams.comments_a) {\n\t\t\tbreak;\n\t\t}\n\t\tr = r_buf_read_at (obj->b, entry->location.rva, obj->streams.comments_a, COMMENTS_SIZE);\n\t\tif (r != COMMENTS_SIZE) {\n\t\t\tbreak;\n\t\t}\n\n\t\tsdb_num_set (obj->kv, \"mdmp_comment_stream_a.offset\",\n\t\t\tentry->location.rva, 0);\n\t\tsdb_set (obj->kv, \"mdmp_comment_stream_a.format\",\n\t\t\t\"s CommentA\", 0);\n\n\t\tbreak;\n\tcase COMMENT_STREAM_W:\n\t\t/* TODO: Not yet fully parsed or utilised */\n\t\tobj->streams.comments_w = R_NEWS (ut8, COMMENTS_SIZE);\n\t\tif (!obj->streams.comments_w) {\n\t\t\tbreak;\n\t\t}\n\t\tr = r_buf_read_at (obj->b, entry->location.rva, obj->streams.comments_w, COMMENTS_SIZE);\n\t\tif (r != COMMENTS_SIZE) {\n\t\t\tbreak;\n\t\t}\n\n\t\tsdb_num_set (obj->kv, \"mdmp_comment_stream_w.offset\",\n\t\t\tentry->location.rva, 0);\n\t\tsdb_set (obj->kv, \"mdmp_comment_stream_w.format\",\n\t\t\t\t\"s CommentW\", 0);\n\n\t\tbreak;\n\tcase HANDLE_DATA_STREAM:\n\t\t/* TODO: Not yet fully parsed or utilised */\n\t\tobj->streams.handle_data = R_NEW (struct minidump_handle_data_stream);\n\t\tif (!obj->streams.handle_data) {\n\t\t\tbreak;\n\t\t}\n\t\tr = r_buf_read_at (obj->b, entry->location.rva, (ut8 *)obj->streams.handle_data, sizeof (*obj->streams.handle_data));\n\t\tif (r != sizeof (*obj->streams.handle_data)) {\n\t\t\tbreak;\n\t\t}\n\n\t\tsdb_num_set (obj->kv, \"mdmp_handle_data_stream.offset\",\n\t\t\t\tentry->location.rva, 0);\n\t\tsdb_set (obj->kv, \"mdmp_handle_data_stream.format\", \"dddd \"\n\t\t\t\t\"SizeOfHeader SizeOfDescriptor \"\n\t\t\t\t\"NumberOfDescriptors Reserved\", 0);\n\t\tbreak;\n\tcase FUNCTION_TABLE_STREAM:\n\t\t/* TODO: Not yet fully parsed or utilised */\n\t\tobj->streams.function_table = R_NEW (struct minidump_function_table_stream);\n\t\tif (!obj->streams.function_table) {\n\t\t\tbreak;\n\t\t}\n\t\tr = r_buf_read_at (obj->b, entry->location.rva, (ut8 *)obj->streams.function_table, sizeof (*obj->streams.function_table));\n\t\tif (r != sizeof (*obj->streams.function_table)) {\n\t\t\tbreak;\n\t\t}\n\n\t\tsdb_num_set (obj->kv, \"mdmp_function_table_stream.offset\",\n\t\t\tentry->location.rva, 0);\n\t\tsdb_set (obj->kv, \"mdmp_function_table_stream.format\", \"dddddd \"\n\t\t\t\"SizeOfHeader SizeOfDescriptor SizeOfNativeDescriptor \"\n\t\t\t\"SizeOfFunctionEntry NumberOfDescriptors SizeOfAlignPad\",\n\t\t\t0);\n\t\tbreak;\n\tcase UNLOADED_MODULE_LIST_STREAM:\n\t\t/* TODO: Not yet fully parsed or utilised */\n\t\tr = r_buf_read_at (obj->b, entry->location.rva, (ut8 *)&unloaded_module_list, sizeof (unloaded_module_list));\n\t\tif (r != sizeof (unloaded_module_list)) {\n\t\t\tbreak;\n\t\t}\n\n\t\tsdb_set (obj->kv, \"mdmp_unloaded_module.format\", \"qddtd \"\n\t\t\t\"BaseOfImage SizeOfImage CheckSum TimeDateStamp \"\n\t\t\t\"ModuleNameRva\", 0);\n\t\tsdb_num_set (obj->kv, \"mdmp_unloaded_module_list.offset\",\n\t\t\tentry->location.rva, 0);\n\t\tsdb_set (obj->kv, \"mdmp_unloaded_module_list.format\", \"ddd \"\n\t\t\t\"SizeOfHeader SizeOfEntry NumberOfEntries\", 0);\n\n\t\toffset = entry->location.rva + sizeof (unloaded_module_list);\n\t\tfor (i = 0; i < unloaded_module_list.number_of_entries; i++) {\n\t\t\tstruct minidump_unloaded_module *module = R_NEW (struct minidump_unloaded_module);\n\t\t\tif (!module) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tr = r_buf_read_at (obj->b, offset, (ut8 *)module, sizeof (*module));\n\t\t\tif (r != sizeof (*module)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tr_list_append (obj->streams.unloaded_modules, module);\n\t\t\toffset += sizeof (*module);\n\t\t}\n\t\tbreak;\n\tcase MISC_INFO_STREAM:\n\t\t/* TODO: Not yet fully parsed or utilised */\n\t\tobj->streams.misc_info.misc_info_1 = R_NEW (struct minidump_misc_info);\n\t\tif (!obj->streams.misc_info.misc_info_1) {\n\t\t\tbreak;\n\t\t}\n\t\tr = r_buf_read_at (obj->b, entry->location.rva, (ut8 *)obj->streams.misc_info.misc_info_1, sizeof (*obj->streams.misc_info.misc_info_1));\n\t\tif (r != sizeof (*obj->streams.misc_info.misc_info_1)) {\n\t\t\tbreak;\n\t\t}\n\n\t\t/* TODO: Handle different sizes */\n\t\tsdb_num_set (obj->kv, \"mdmp_misc_info.offset\",\n\t\t\tentry->location.rva, 0);\n\t\tsdb_set (obj->kv, \"mdmp_misc_info.format\", \"d[4]Bdtttddddd \"\n\t\t\t\"SizeOfInfo (mdmp_misc1_flags)Flags1 ProcessId \"\n\t\t\t\"ProcessCreateTime ProcessUserTime ProcessKernelTime \"\n\t\t\t\"ProcessorMaxMhz ProcessorCurrentMhz \"\n\t\t\t\"ProcessorMhzLimit ProcessorMaxIdleState \"\n\t\t\t\"ProcessorCurrentIdleState\", 0);\n\n\t\tbreak;\n\tcase MEMORY_INFO_LIST_STREAM:\n\t\tr = r_buf_read_at (obj->b, entry->location.rva, (ut8 *)&memory_info_list, sizeof (memory_info_list));\n\t\tif (r != sizeof (memory_info_list)) {\n\t\t\tbreak;\n\t\t}\n\n\t\tsdb_set (obj->kv, \"mdmp_memory_info.format\",\n\t\t\t\"qq[4]Edq[4]E[4]E[4]Ed BaseAddress AllocationBase \"\n\t\t\t\"(mdmp_page_protect)AllocationProtect __Alignment1 RegionSize \"\n\t\t\t\"(mdmp_mem_state)State (mdmp_page_protect)Protect \"\n\t\t\t\"(mdmp_mem_type)Type __Alignment2\", 0);\n\t\tsdb_num_set (obj->kv, \"mdmp_memory_info_list.offset\",\n\t\t\tentry->location.rva, 0);\n\t\tsdb_set (obj->kv, \"mdmp_memory_info_list.format\",\n\t\t\tr_strf (\"ddq[%\"PFMT64d\"]? SizeOfHeader SizeOfEntry \"\n\t\t\t\t\"NumberOfEntries (mdmp_memory_info)MemoryInfo\",\n\t\t\t\tmemory_info_list.number_of_entries),\n\t\t\t0);\n\n\t\toffset = entry->location.rva + sizeof (memory_info_list);\n\t\tfor (i = 0; i < memory_info_list.number_of_entries; i++) {\n\t\t\tstruct minidump_memory_info *info = R_NEW (struct minidump_memory_info);\n\t\t\tif (!info) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tr = r_buf_read_at (obj->b, offset, (ut8 *)info, sizeof (*info));\n\t\t\tif (r != sizeof (*info)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tr_list_append (obj->streams.memory_infos, info);\n\t\t\toffset += sizeof (*info);\n\t\t}\n\t\tbreak;\n\tcase THREAD_INFO_LIST_STREAM:\n\t\t/* TODO: Not yet fully parsed or utilised */\n\t\tr = r_buf_read_at (obj->b, entry->location.rva, (ut8 *)&thread_info_list, sizeof (thread_info_list));\n\t\tif (r != sizeof (thread_info_list)) {\n\t\t\tbreak;\n\t\t}\n\n\t\tsdb_set (obj->kv, \"mdmp_thread_info.format\", \"ddddttttqq \"\n\t\t\t\"ThreadId DumpFlags DumpError ExitStatus CreateTime \"\n\t\t\t\"ExitTime KernelTime UserTime StartAddress Affinity\",\n\t\t\t0);\n\t\tsdb_num_set (obj->kv, \"mdmp_thread_info_list.offset\",\n\t\t\t\tentry->location.rva, 0);\n\t\tsdb_set (obj->kv, \"mdmp_thread_info_list.format\", \"ddd \"\n\t\t\t\"SizeOfHeader SizeOfEntry NumberOfEntries\", 0);\n\n\t\toffset = entry->location.rva + sizeof (thread_info_list);\n\t\tfor (i = 0; i < thread_info_list.number_of_entries; i++) {\n\t\t\tstruct minidump_thread_info *info = R_NEW (struct minidump_thread_info);\n\t\t\tif (!info) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tr = r_buf_read_at (obj->b, offset, (ut8 *)info, sizeof (*info));\n\t\t\tif (r != sizeof (*info)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tr_list_append (obj->streams.thread_infos, info);\n\t\t\toffset += sizeof (*info);\n\t\t}\n\t\tbreak;\n\tcase HANDLE_OPERATION_LIST_STREAM:\n\t\t/* TODO: Not yet fully parsed or utilised */\n\t\tr = r_buf_read_at (obj->b, entry->location.rva, (ut8 *)&handle_operation_list, sizeof (handle_operation_list));\n\t\tif (r != sizeof (handle_operation_list)) {\n\t\t\tbreak;\n\t\t}\n\n\t\tsdb_num_set (obj->kv, \"mdmp_handle_operation_list.offset\",\n\t\t\tentry->location.rva, 0);\n\t\tsdb_set (obj->kv, \"mdmp_handle_operation_list.format\", \"dddd \"\n\t\t\t\"SizeOfHeader SizeOfEntry NumberOfEntries Reserved\", 0);\n\n\t\toffset = entry->location.rva + sizeof (handle_operation_list);\n\t\tfor (i = 0; i < handle_operation_list.number_of_entries; i++) {\n\t\t\tstruct avrf_handle_operation *op = R_NEW (struct avrf_handle_operation);\n\t\t\tif (!op) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tr = r_buf_read_at (obj->b, offset, (ut8 *)op, sizeof (*op));\n\t\t\tif (r != sizeof (*op)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tr_list_append (obj->streams.operations, op);\n\t\t\toffset += sizeof (*op);\n\t\t}\n\n\t\tbreak;\n\tcase TOKEN_STREAM:\n\t\t/* TODO: Not fully parsed or utilised */\n\t\tr = r_buf_read_at (obj->b, entry->location.rva, (ut8 *)&token_info_list, sizeof (token_info_list));\n\t\tif (r != sizeof (token_info_list)) {\n\t\t\tbreak;\n\t\t}\n\n\t\tsdb_set (obj->kv, \"mdmp_token_info.format\", \"ddq \"\n\t\t\t\"TokenSize TokenId TokenHandle\", 0);\n\n\t\tsdb_num_set (obj->kv, \"mdmp_token_info_list.offset\",\n\t\t\tentry->location.rva, 0);\n\t\tsdb_set (obj->kv, \"mdmp_token_info_list.format\", \"dddd \"\n\t\t\t\"TokenListSize TokenListEntries ListHeaderSize ElementHeaderSize\", 0);\n\n\t\toffset = entry->location.rva + sizeof (token_info_list);\n\t\tfor (i = 0; i < token_info_list.number_of_entries; i++) {\n\t\t\tstruct minidump_token_info *info = R_NEW (struct minidump_token_info);\n\t\t\tif (!info) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tr = r_buf_read_at (obj->b, offset, (ut8 *)info, sizeof (*info));\n\t\t\tif (r != sizeof (*info)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tr_list_append (obj->streams.token_infos, info);\n\t\t\toffset += sizeof (*info);\n\t\t}\n\t\tbreak;\n\n\tcase LAST_RESERVED_STREAM:\n\t\t/* TODO: Not yet fully parsed or utilised */\n\t\tbreak;\n\tcase UNUSED_STREAM:\n\tcase RESERVED_STREAM_0:\n\tcase RESERVED_STREAM_1:\n\t\t/* Silently ignore reserved streams */\n\t\tbreak;\n\tdefault:\n\t\teprintf (\"[WARN] Invalid or unsupported enumeration encountered %d\\n\", entry->stream_type);\n\t\tbreak;\n\t}\n\treturn true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Fix DoS in the minidump parser ##crash\n\n* Reported by lazymio via huntr.dev\n* Reproducer: mdmp-dos'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static bool load_buffer(RBinFile *bf, void **bin_obj, RBuffer *buf, ut64 loadaddr, Sdb *sdb) {\n\tQnxObj *qo = R_NEW0 (QnxObj);\n\tif (!qo) {\n\t\treturn false;\n\t}\n\tlmf_record lrec;\n\tlmf_resource lres;\n\tlmf_data ldata;\n\tut64 offset = QNX_RECORD_SIZE;\n\tRList *sections = NULL;\n\tRList *fixups = NULL;\n\n\tif (!qo) {\n\t\tgoto beach;\n\t}\n\tif (!(sections = r_list_newf ((RListFree)r_bin_section_free)) || !(fixups = r_list_new ())) {\n\t\tgoto beach;\n\t}\n\tqo->kv = sdb_new0 ();\n\tif (!qo->kv) {\n\t\tgoto beach;\n\t}\n\t// Read the first record\n\tif (r_buf_fread_at (bf->buf, 0, (ut8 *)&lrec, \"ccss\", 1) < QNX_RECORD_SIZE) {\n\t\tgoto beach;\n\t}\n\t// Load the header\n\tlmf_header_load (&qo->lmfh, bf->buf, qo->kv);\n\toffset += lrec.data_nbytes;\n\n\tfor (;;) {\n\t\tif (r_buf_fread_at (bf->buf, offset, (ut8 *)&lrec, \"ccss\", 1) < QNX_RECORD_SIZE) {\n\t\t\tgoto beach;\n\t\t}\n\t\toffset += sizeof (lmf_record);\n\n\t\tif (lrec.rec_type == LMF_IMAGE_END_REC) {\n\t\t\tbreak;\n\t\t} else if (lrec.rec_type == LMF_RESOURCE_REC) {\n\t\t\tRBinSection *ptr = R_NEW0 (RBinSection);\n\t\t\tif (!ptr) {\n\t\t\t\tgoto beach;\n\t\t\t}\n\t\t\tif (r_buf_fread_at (bf->buf, offset, (ut8 *)&lres, \"ssss\", 1) < sizeof (lmf_resource)) {\n\t\t\t\tgoto beach;\n\t\t\t}\n\t\t\tptr->name = strdup (\"LMF_RESOURCE\");\n\t\t\tptr->paddr = offset;\n\t\t\tptr->vsize = lrec.data_nbytes - sizeof (lmf_resource);\n\t\t\tptr->size = ptr->vsize;\n\t\t\tptr->add = true;\n\t\t \tr_list_append (sections, ptr);\n\t\t} else if (lrec.rec_type == LMF_LOAD_REC) {\n\t\t\tRBinSection *ptr = R_NEW0 (RBinSection);\n\t\t\tif (r_buf_fread_at (bf->buf, offset, (ut8 *)&ldata, \"si\", 1) < sizeof (lmf_data)) {\n\t\t\t\tgoto beach;\n\t\t\t}\n\t\t\tif (!ptr) {\n\t\t\t\tgoto beach;\n\t\t\t}\n\t\t\tptr->name = strdup (\"LMF_LOAD\");\n\t\t\tptr->paddr = offset;\n\t\t\tptr->vaddr = ldata.offset;\n\t\t\tptr->vsize = lrec.data_nbytes - sizeof (lmf_data);\n\t\t\tptr->size = ptr->vsize;\n\t\t\tptr->add = true;\n\t\t \tr_list_append (sections, ptr);\n\t\t} else if (lrec.rec_type == LMF_FIXUP_REC) {\n\t\t\tRBinReloc *ptr = R_NEW0 (RBinReloc);\n\t\t\tif (!ptr || r_buf_fread_at (bf->buf, offset, (ut8 *)&ldata, \"si\", 1) < sizeof (lmf_data)) {\n\t\t\t\tgoto beach;\n\t\t\t}\n\t\t\tptr->vaddr = ptr->paddr = ldata.offset;\n\t\t\tptr->type = 'f'; // \"LMF_FIXUP\";\n\t\t\tr_list_append (fixups, ptr);\n\t\t} else if (lrec.rec_type == LMF_8087_FIXUP_REC) {\n\t\t\tRBinReloc *ptr = R_NEW0 (RBinReloc);\n\t\t\tif (!ptr || r_buf_fread_at (bf->buf, offset, (ut8 *)&ldata, \"si\", 1) < sizeof (lmf_data)) {\n\t\t\t\tgoto beach;\n\t\t\t}\n\t\t\tptr->vaddr = ptr->paddr = ldata.offset;\n\t\t\tptr->type = 'F'; // \"LMF_8087_FIXUP\";\n\t\t\tr_list_append (fixups, ptr);\n\t\t} else if (lrec.rec_type == LMF_RW_END_REC) {\n\t\t\tr_buf_fread_at (bf->buf, offset, (ut8 *)&qo->rwend, \"si\", 1);\n\t\t}\n\t\toffset += lrec.data_nbytes;\n\t}\n\tsdb_ns_set (sdb, \"info\", qo->kv);\n\tqo->sections = sections;\n\tqo->fixups = fixups;\n\t*bin_obj = qo;\n\treturn true;\nbeach:\n\tfree (qo);\n\tr_list_free (fixups);\n\tr_list_free (sections);\n\treturn false;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Fix DoS in PE/QNX/DYLDCACHE/PSX parsers ##crash\n\n* Reported by lazymio\n* Reproducer: AAA4AAAAAB4='" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void isis_notif_authentication_failure(const struct isis_circuit *circuit,\n\t\t\t\t const char *raw_pdu, size_t raw_pdu_len)\n{\n\tconst char *xpath = \"/frr-isisd:authentication-failure\";\n\tstruct list *arguments = yang_data_list_new();\n\tchar xpath_arg[XPATH_MAXLEN];\n\tstruct yang_data *data;\n\tstruct isis_area *area = circuit->area;\n\n\tnotif_prep_instance_hdr(xpath, area, \"default\", arguments);\n\tnotif_prepr_iface_hdr(xpath, circuit, arguments);\n\tsnprintf(xpath_arg, sizeof(xpath_arg), \"%s/raw-pdu\", xpath);\n\tdata = yang_data_new(xpath_arg, raw_pdu);\n\tlistnode_add(arguments, data);\n\n\thook_call(isis_hook_authentication_failure, circuit, raw_pdu,\n\t\t raw_pdu_len);\n\n\tnb_notification_send(xpath, arguments);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'isisd: fix #10505 using base64 encoding\n\nUsing base64 instead of the raw string to encode\nthe binary data.\n\nSigned-off-by: whichbug '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static size_t push_pipe(struct iov_iter *i, size_t size,\n\t\t\tint *iter_headp, size_t *offp)\n{\n\tstruct pipe_inode_info *pipe = i->pipe;\n\tunsigned int p_tail = pipe->tail;\n\tunsigned int p_mask = pipe->ring_size - 1;\n\tunsigned int iter_head;\n\tsize_t off;\n\tssize_t left;\n\n\tif (unlikely(size > i->count))\n\t\tsize = i->count;\n\tif (unlikely(!size))\n\t\treturn 0;\n\n\tleft = size;\n\tdata_start(i, &iter_head, &off);\n\t*iter_headp = iter_head;\n\t*offp = off;\n\tif (off) {\n\t\tleft -= PAGE_SIZE - off;\n\t\tif (left <= 0) {\n\t\t\tpipe->bufs[iter_head & p_mask].len += size;\n\t\t\treturn size;\n\t\t}\n\t\tpipe->bufs[iter_head & p_mask].len = PAGE_SIZE;\n\t\titer_head++;\n\t}\n\twhile (!pipe_full(iter_head, p_tail, pipe->max_usage)) {\n\t\tstruct pipe_buffer *buf = &pipe->bufs[iter_head & p_mask];\n\t\tstruct page *page = alloc_page(GFP_USER);\n\t\tif (!page)\n\t\t\tbreak;\n\n\t\tbuf->ops = &default_pipe_buf_ops;\n\t\tbuf->page = page;\n\t\tbuf->offset = 0;\n\t\tbuf->len = min_t(ssize_t, left, PAGE_SIZE);\n\t\tleft -= buf->len;\n\t\titer_head++;\n\t\tpipe->head = iter_head;\n\n\t\tif (left == 0)\n\t\t\treturn size;\n\t}\n\treturn size - left;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-665', 'CWE-284'], 'message': 'lib/iov_iter: initialize \"flags\" in new pipe_buffer\n\nThe functions copy_page_to_iter_pipe() and push_pipe() can both\nallocate a new pipe_buffer, but the \"flags\" member initializer is\nmissing.\n\nFixes: 241699cd72a8 (\"new iov_iter flavour: pipe-backed\")\nTo: Alexander Viro \nTo: linux-fsdevel@vger.kernel.org\nTo: linux-kernel@vger.kernel.org\nCc: stable@vger.kernel.org\nSigned-off-by: Max Kellermann \nSigned-off-by: Al Viro '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: spell_suggest(int count)\n{\n char_u\t*line;\n pos_T\tprev_cursor = curwin->w_cursor;\n char_u\twcopy[MAXWLEN + 2];\n char_u\t*p;\n int\t\ti;\n int\t\tc;\n suginfo_T\tsug;\n suggest_T\t*stp;\n int\t\tmouse_used;\n int\t\tneed_cap;\n int\t\tlimit;\n int\t\tselected = count;\n int\t\tbadlen = 0;\n int\t\tmsg_scroll_save = msg_scroll;\n int\t\two_spell_save = curwin->w_p_spell;\n\n if (!curwin->w_p_spell)\n {\n\tdid_set_spelllang(curwin);\n\tcurwin->w_p_spell = TRUE;\n }\n\n if (*curwin->w_s->b_p_spl == NUL)\n {\n\temsg(_(e_spell_checking_is_not_possible));\n\treturn;\n }\n\n if (VIsual_active)\n {\n\t// Use the Visually selected text as the bad word. But reject\n\t// a multi-line selection.\n\tif (curwin->w_cursor.lnum != VIsual.lnum)\n\t{\n\t vim_beep(BO_SPELL);\n\t return;\n\t}\n\tbadlen = (int)curwin->w_cursor.col - (int)VIsual.col;\n\tif (badlen < 0)\n\t badlen = -badlen;\n\telse\n\t curwin->w_cursor.col = VIsual.col;\n\t++badlen;\n\tend_visual_mode();\n }\n // Find the start of the badly spelled word.\n else if (spell_move_to(curwin, FORWARD, TRUE, TRUE, NULL) == 0\n\t || curwin->w_cursor.col > prev_cursor.col)\n {\n\t// No bad word or it starts after the cursor: use the word under the\n\t// cursor.\n\tcurwin->w_cursor = prev_cursor;\n\tline = ml_get_curline();\n\tp = line + curwin->w_cursor.col;\n\t// Backup to before start of word.\n\twhile (p > line && spell_iswordp_nmw(p, curwin))\n\t MB_PTR_BACK(line, p);\n\t// Forward to start of word.\n\twhile (*p != NUL && !spell_iswordp_nmw(p, curwin))\n\t MB_PTR_ADV(p);\n\n\tif (!spell_iswordp_nmw(p, curwin))\t\t// No word found.\n\t{\n\t beep_flush();\n\t return;\n\t}\n\tcurwin->w_cursor.col = (colnr_T)(p - line);\n }\n\n // Get the word and its length.\n\n // Figure out if the word should be capitalised.\n need_cap = check_need_cap(curwin->w_cursor.lnum, curwin->w_cursor.col);\n\n // Make a copy of current line since autocommands may free the line.\n line = vim_strsave(ml_get_curline());\n if (line == NULL)\n\tgoto skip;\n\n // Get the list of suggestions. Limit to 'lines' - 2 or the number in\n // 'spellsuggest', whatever is smaller.\n if (sps_limit > (int)Rows - 2)\n\tlimit = (int)Rows - 2;\n else\n\tlimit = sps_limit;\n spell_find_suggest(line + curwin->w_cursor.col, badlen, &sug, limit,\n\t\t\t\t\t\t\tTRUE, need_cap, TRUE);\n\n if (sug.su_ga.ga_len == 0)\n\tmsg(_(\"Sorry, no suggestions\"));\n else if (count > 0)\n {\n\tif (count > sug.su_ga.ga_len)\n\t smsg(_(\"Sorry, only %ld suggestions\"), (long)sug.su_ga.ga_len);\n }\n else\n {\n#ifdef FEAT_RIGHTLEFT\n\t// When 'rightleft' is set the list is drawn right-left.\n\tcmdmsg_rl = curwin->w_p_rl;\n\tif (cmdmsg_rl)\n\t msg_col = Columns - 1;\n#endif\n\n\t// List the suggestions.\n\tmsg_start();\n\tmsg_row = Rows - 1;\t// for when 'cmdheight' > 1\n\tlines_left = Rows;\t// avoid more prompt\n\tvim_snprintf((char *)IObuff, IOSIZE, _(\"Change \\\"%.*s\\\" to:\"),\n\t\t\t\t\t\tsug.su_badlen, sug.su_badptr);\n#ifdef FEAT_RIGHTLEFT\n\tif (cmdmsg_rl && STRNCMP(IObuff, \"Change\", 6) == 0)\n\t{\n\t // And now the rabbit from the high hat: Avoid showing the\n\t // untranslated message rightleft.\n\t vim_snprintf((char *)IObuff, IOSIZE, \":ot \\\"%.*s\\\" egnahC\",\n\t\t\t\t\t\tsug.su_badlen, sug.su_badptr);\n\t}\n#endif\n\tmsg_puts((char *)IObuff);\n\tmsg_clr_eos();\n\tmsg_putchar('\\n');\n\n\tmsg_scroll = TRUE;\n\tfor (i = 0; i < sug.su_ga.ga_len; ++i)\n\t{\n\t stp = &SUG(sug.su_ga, i);\n\n\t // The suggested word may replace only part of the bad word, add\n\t // the not replaced part.\n\t vim_strncpy(wcopy, stp->st_word, MAXWLEN);\n\t if (sug.su_badlen > stp->st_orglen)\n\t\tvim_strncpy(wcopy + stp->st_wordlen,\n\t\t\t\t\t sug.su_badptr + stp->st_orglen,\n\t\t\t\t\t sug.su_badlen - stp->st_orglen);\n\t vim_snprintf((char *)IObuff, IOSIZE, \"%2d\", i + 1);\n#ifdef FEAT_RIGHTLEFT\n\t if (cmdmsg_rl)\n\t\trl_mirror(IObuff);\n#endif\n\t msg_puts((char *)IObuff);\n\n\t vim_snprintf((char *)IObuff, IOSIZE, \" \\\"%s\\\"\", wcopy);\n\t msg_puts((char *)IObuff);\n\n\t // The word may replace more than \"su_badlen\".\n\t if (sug.su_badlen < stp->st_orglen)\n\t {\n\t\tvim_snprintf((char *)IObuff, IOSIZE, _(\" < \\\"%.*s\\\"\"),\n\t\t\t\t\t stp->st_orglen, sug.su_badptr);\n\t\tmsg_puts((char *)IObuff);\n\t }\n\n\t if (p_verbose > 0)\n\t {\n\t\t// Add the score.\n\t\tif (sps_flags & (SPS_DOUBLE | SPS_BEST))\n\t\t vim_snprintf((char *)IObuff, IOSIZE, \" (%s%d - %d)\",\n\t\t\tstp->st_salscore ? \"s \" : \"\",\n\t\t\tstp->st_score, stp->st_altscore);\n\t\telse\n\t\t vim_snprintf((char *)IObuff, IOSIZE, \" (%d)\",\n\t\t\t stp->st_score);\n#ifdef FEAT_RIGHTLEFT\n\t\tif (cmdmsg_rl)\n\t\t // Mirror the numbers, but keep the leading space.\n\t\t rl_mirror(IObuff + 1);\n#endif\n\t\tmsg_advance(30);\n\t\tmsg_puts((char *)IObuff);\n\t }\n\t msg_putchar('\\n');\n\t}\n\n#ifdef FEAT_RIGHTLEFT\n\tcmdmsg_rl = FALSE;\n\tmsg_col = 0;\n#endif\n\t// Ask for choice.\n\tselected = prompt_for_number(&mouse_used);\n\tif (mouse_used)\n\t selected -= lines_left;\n\tlines_left = Rows;\t\t// avoid more prompt\n\t// don't delay for 'smd' in normal_cmd()\n\tmsg_scroll = msg_scroll_save;\n }\n\n if (selected > 0 && selected <= sug.su_ga.ga_len && u_save_cursor() == OK)\n {\n\t// Save the from and to text for :spellrepall.\n\tVIM_CLEAR(repl_from);\n\tVIM_CLEAR(repl_to);\n\n\tstp = &SUG(sug.su_ga, selected - 1);\n\tif (sug.su_badlen > stp->st_orglen)\n\t{\n\t // Replacing less than \"su_badlen\", append the remainder to\n\t // repl_to.\n\t repl_from = vim_strnsave(sug.su_badptr, sug.su_badlen);\n\t vim_snprintf((char *)IObuff, IOSIZE, \"%s%.*s\", stp->st_word,\n\t\t sug.su_badlen - stp->st_orglen,\n\t\t\t\t\t sug.su_badptr + stp->st_orglen);\n\t repl_to = vim_strsave(IObuff);\n\t}\n\telse\n\t{\n\t // Replacing su_badlen or more, use the whole word.\n\t repl_from = vim_strnsave(sug.su_badptr, stp->st_orglen);\n\t repl_to = vim_strsave(stp->st_word);\n\t}\n\n\t// Replace the word.\n\tp = alloc(STRLEN(line) - stp->st_orglen + stp->st_wordlen + 1);\n\tif (p != NULL)\n\t{\n\t c = (int)(sug.su_badptr - line);\n\t mch_memmove(p, line, c);\n\t STRCPY(p + c, stp->st_word);\n\t STRCAT(p, sug.su_badptr + stp->st_orglen);\n\n\t // For redo we use a change-word command.\n\t ResetRedobuff();\n\t AppendToRedobuff((char_u *)\"ciw\");\n\t AppendToRedobuffLit(p + c,\n\t\t\t stp->st_wordlen + sug.su_badlen - stp->st_orglen);\n\t AppendCharToRedobuff(ESC);\n\n\t // \"p\" may be freed here\n\t ml_replace(curwin->w_cursor.lnum, p, FALSE);\n\t curwin->w_cursor.col = c;\n\n\t changed_bytes(curwin->w_cursor.lnum, c);\n\t}\n }\n else\n\tcurwin->w_cursor = prev_cursor;\n\n spell_find_cleanup(&sug);\nskip:\n vim_free(line);\n curwin->w_p_spell = wo_spell_save;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-122', 'CWE-787'], 'message': 'patch 8.2.4563: \"z=\" in Visual mode may go beyond the end of the line\n\nProblem: \"z=\" in Visual mode may go beyond the end of the line.\nSolution: Adjust \"badlen\".'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int main(int argc, char **argv) {\n\tswaylock_log_init(LOG_ERROR);\n\tinitialize_pw_backend(argc, argv);\n\tsrand(time(NULL));\n\n\tenum line_mode line_mode = LM_LINE;\n\tstate.failed_attempts = 0;\n\tstate.args = (struct swaylock_args){\n\t\t.mode = BACKGROUND_MODE_FILL,\n\t\t.font = strdup(\"sans-serif\"),\n\t\t.font_size = 0,\n\t\t.radius = 50,\n\t\t.thickness = 10,\n\t\t.indicator_x_position = 0,\n\t\t.indicator_y_position = 0,\n\t\t.override_indicator_x_position = false,\n\t\t.override_indicator_y_position = false,\n\t\t.ignore_empty = false,\n\t\t.show_indicator = true,\n\t\t.show_caps_lock_indicator = false,\n\t\t.show_caps_lock_text = true,\n\t\t.show_keyboard_layout = false,\n\t\t.hide_keyboard_layout = false,\n\t\t.show_failed_attempts = false,\n\t\t.indicator_idle_visible = false\n\t};\n\twl_list_init(&state.images);\n\tset_default_colors(&state.args.colors);\n\n\tchar *config_path = NULL;\n\tint result = parse_options(argc, argv, NULL, NULL, &config_path);\n\tif (result != 0) {\n\t\tfree(config_path);\n\t\treturn result;\n\t}\n\tif (!config_path) {\n\t\tconfig_path = get_config_path();\n\t}\n\n\tif (config_path) {\n\t\tswaylock_log(LOG_DEBUG, \"Found config at %s\", config_path);\n\t\tint config_status = load_config(config_path, &state, &line_mode);\n\t\tfree(config_path);\n\t\tif (config_status != 0) {\n\t\t\tfree(state.args.font);\n\t\t\treturn config_status;\n\t\t}\n\t}\n\n\tif (argc > 1) {\n\t\tswaylock_log(LOG_DEBUG, \"Parsing CLI Args\");\n\t\tint result = parse_options(argc, argv, &state, &line_mode, NULL);\n\t\tif (result != 0) {\n\t\t\tfree(state.args.font);\n\t\t\treturn result;\n\t\t}\n\t}\n\n\tif (line_mode == LM_INSIDE) {\n\t\tstate.args.colors.line = state.args.colors.inside;\n\t} else if (line_mode == LM_RING) {\n\t\tstate.args.colors.line = state.args.colors.ring;\n\t}\n\n#ifdef __linux__\n\t// Most non-linux platforms require root to mlock()\n\tif (mlock(state.password.buffer, sizeof(state.password.buffer)) != 0) {\n\t\tswaylock_log(LOG_ERROR, \"Unable to mlock() password memory.\");\n\t\treturn EXIT_FAILURE;\n\t}\n#endif\n\n\twl_list_init(&state.surfaces);\n\tstate.xkb.context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);\n\tstate.display = wl_display_connect(NULL);\n\tif (!state.display) {\n\t\tfree(state.args.font);\n\t\tswaylock_log(LOG_ERROR, \"Unable to connect to the compositor. \"\n\t\t\t\t\"If your compositor is running, check or set the \"\n\t\t\t\t\"WAYLAND_DISPLAY environment variable.\");\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tstruct wl_registry *registry = wl_display_get_registry(state.display);\n\twl_registry_add_listener(registry, ®istry_listener, &state);\n\twl_display_roundtrip(state.display);\n\tassert(state.compositor && state.layer_shell && state.shm);\n\tif (!state.input_inhibit_manager) {\n\t\tfree(state.args.font);\n\t\tswaylock_log(LOG_ERROR, \"Compositor does not support the input \"\n\t\t\t\t\"inhibitor protocol, refusing to run insecurely\");\n\t\treturn 1;\n\t}\n\n\tzwlr_input_inhibit_manager_v1_get_inhibitor(state.input_inhibit_manager);\n\tif (wl_display_roundtrip(state.display) == -1) {\n\t\tfree(state.args.font);\n\t\tswaylock_log(LOG_ERROR, \"Exiting - failed to inhibit input:\"\n\t\t\t\t\" is another lockscreen already running?\");\n\t\treturn 2;\n\t}\n\n\tif (state.zxdg_output_manager) {\n\t\tstruct swaylock_surface *surface;\n\t\twl_list_for_each(surface, &state.surfaces, link) {\n\t\t\tsurface->xdg_output = zxdg_output_manager_v1_get_xdg_output(\n\t\t\t\t\t\tstate.zxdg_output_manager, surface->output);\n\t\t\tzxdg_output_v1_add_listener(\n\t\t\t\t\tsurface->xdg_output, &_xdg_output_listener, surface);\n\t\t}\n\t\twl_display_roundtrip(state.display);\n\t} else {\n\t\tswaylock_log(LOG_INFO, \"Compositor does not support zxdg output \"\n\t\t\t\t\"manager, images assigned to named outputs will not work\");\n\t}\n\n\tstruct swaylock_surface *surface;\n\twl_list_for_each(surface, &state.surfaces, link) {\n\t\tcreate_layer_surface(surface);\n\t}\n\n\tif (state.args.daemonize) {\n\t\twl_display_roundtrip(state.display);\n\t\tdaemonize();\n\t}\n\n\tstate.eventloop = loop_create();\n\tloop_add_fd(state.eventloop, wl_display_get_fd(state.display), POLLIN,\n\t\t\tdisplay_in, NULL);\n\n\tloop_add_fd(state.eventloop, get_comm_reply_fd(), POLLIN, comm_in, NULL);\n\n\tstate.run_display = true;\n\twhile (state.run_display) {\n\t\terrno = 0;\n\t\tif (wl_display_flush(state.display) == -1 && errno != EAGAIN) {\n\t\t\tbreak;\n\t\t}\n\t\tloop_poll(state.eventloop);\n\t}\n\n\tfree(state.args.font);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'Add support for ext-session-lock-v1\n\nThis is a new protocol to lock the session [1]. It should be more\nreliable than layer-shell + input-inhibitor.\n\n[1]: https://gitlab.freedesktop.org/wayland/wayland-protocols/-/merge_requests/131'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ZEXPORT deflatePrime (strm, bits, value)\n z_streamp strm;\n int bits;\n int value;\n{\n deflate_state *s;\n int put;\n\n if (deflateStateCheck(strm)) return Z_STREAM_ERROR;\n s = strm->state;\n if ((Bytef *)(s->d_buf) < s->pending_out + ((Buf_size + 7) >> 3))\n return Z_BUF_ERROR;\n do {\n put = Buf_size - s->bi_valid;\n if (put > bits)\n put = bits;\n s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid);\n s->bi_valid += put;\n _tr_flush_bits(s);\n value >>= put;\n bits -= put;\n } while (bits);\n return Z_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284', 'CWE-787'], 'message': 'Fix a bug that can crash deflate on some input when using Z_FIXED.\n\nThis bug was reported by Danilo Ramos of Eideticom, Inc. It has\nlain in wait 13 years before being found! The bug was introduced\nin zlib 1.2.2.2, with the addition of the Z_FIXED option. That\noption forces the use of fixed Huffman codes. For rare inputs with\na large number of distant matches, the pending buffer into which\nthe compressed data is written can overwrite the distance symbol\ntable which it overlays. That results in corrupted output due to\ninvalid distances, and can result in out-of-bound accesses,\ncrashing the application.\n\nThe fix here combines the distance buffer and literal/length\nbuffers into a single symbol buffer. Now three bytes of pending\nbuffer space are opened up for each literal or length/distance\npair consumed, instead of the previous two bytes. This assures\nthat the pending buffer cannot overwrite the symbol table, since\nthe maximum fixed code compressed length/distance is 31 bits, and\nsince there are four bytes of pending space for every three bytes\nof symbol space.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void MACH0_(iterate_chained_fixups)(struct MACH0_(obj_t) *bin, ut64 limit_start, ut64 limit_end, ut32 event_mask, RFixupCallback callback, void * context) {\n\tint i = 0;\n\tfor (; i < bin->nsegs; i++) {\n\t\tif (!bin->chained_starts[i]) {\n\t\t\tcontinue;\n\t\t}\n\t\tint page_size = bin->chained_starts[i]->page_size;\n\t\tif (page_size < 1) {\n\t\t\tpage_size = 4096;\n\t\t}\n\t\tut64 start = bin->segs[i].fileoff;\n\t\tut64 end = start + bin->segs[i].filesize;\n\t\tif (end >= limit_start && start <= limit_end) {\n\t\t\tut64 page_idx = (R_MAX (start, limit_start) - start) / page_size;\n\t\t\tut64 page_end_idx = (R_MIN (limit_end, end) - start) / page_size;\n\t\t\tfor (; page_idx <= page_end_idx; page_idx++) {\n\t\t\t\tif (page_idx >= bin->chained_starts[i]->page_count) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tut16 page_start = bin->chained_starts[i]->page_start[page_idx];\n\t\t\t\tif (page_start == DYLD_CHAINED_PTR_START_NONE) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tut64 cursor = start + page_idx * page_size + page_start;\n\t\t\t\twhile (cursor < limit_end && cursor < end) {\n\t\t\t\t\tut8 tmp[8];\n\t\t\t\t\tbool previous_rebasing = bin->rebasing_buffer;\n\t\t\t\t\tbin->rebasing_buffer = true;\n\t\t\t\t\tif (r_buf_read_at (bin->b, cursor, tmp, 8) != 8) {\n\t\t\t\t\t\tbin->rebasing_buffer = previous_rebasing;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tbin->rebasing_buffer = previous_rebasing;\n\t\t\t\t\tut64 raw_ptr = r_read_le64 (tmp);\n\t\t\t\t\tut64 ptr_value = raw_ptr;\n\t\t\t\t\tut64 delta, stride, addend;\n\t\t\t\t\tut16 pointer_format = bin->chained_starts[i]->pointer_format;\n\t\t\t\t\tRFixupEvent event = R_FIXUP_EVENT_NONE;\n\t\t\t\t\tut8 key = 0, addr_div = 0;\n\t\t\t\t\tut16 diversity = 0;\n\t\t\t\t\tut32 ordinal = UT32_MAX;\n\t\t\t\t\tif (pointer_format == DYLD_CHAINED_PTR_ARM64E) {\n\t\t\t\t\t\tstride = 8;\n\t\t\t\t\t\tbool is_auth = IS_PTR_AUTH (raw_ptr);\n\t\t\t\t\t\tbool is_bind = IS_PTR_BIND (raw_ptr);\n\t\t\t\t\t\tif (is_auth && is_bind) {\n\t\t\t\t\t\t\tstruct dyld_chained_ptr_arm64e_auth_bind *p =\n\t\t\t\t\t\t\t\t\t(struct dyld_chained_ptr_arm64e_auth_bind *) &raw_ptr;\n\t\t\t\t\t\t\tevent = R_FIXUP_EVENT_BIND_AUTH;\n\t\t\t\t\t\t\tdelta = p->next;\n\t\t\t\t\t\t\tordinal = p->ordinal;\n\t\t\t\t\t\t\tkey = p->key;\n\t\t\t\t\t\t\taddr_div = p->addrDiv;\n\t\t\t\t\t\t\tdiversity = p->diversity;\n\t\t\t\t\t\t} else if (!is_auth && is_bind) {\n\t\t\t\t\t\t\tstruct dyld_chained_ptr_arm64e_bind *p =\n\t\t\t\t\t\t\t\t\t(struct dyld_chained_ptr_arm64e_bind *) &raw_ptr;\n\t\t\t\t\t\t\tevent = R_FIXUP_EVENT_BIND;\n\t\t\t\t\t\t\tdelta = p->next;\n\t\t\t\t\t\t\tordinal = p->ordinal;\n\t\t\t\t\t\t\taddend = p->addend;\n\t\t\t\t\t\t} else if (is_auth && !is_bind) {\n\t\t\t\t\t\t\tstruct dyld_chained_ptr_arm64e_auth_rebase *p =\n\t\t\t\t\t\t\t\t\t(struct dyld_chained_ptr_arm64e_auth_rebase *) &raw_ptr;\n\t\t\t\t\t\t\tevent = R_FIXUP_EVENT_REBASE_AUTH;\n\t\t\t\t\t\t\tdelta = p->next;\n\t\t\t\t\t\t\tptr_value = p->target + bin->baddr;\n\t\t\t\t\t\t\tkey = p->key;\n\t\t\t\t\t\t\taddr_div = p->addrDiv;\n\t\t\t\t\t\t\tdiversity = p->diversity;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tstruct dyld_chained_ptr_arm64e_rebase *p =\n\t\t\t\t\t\t\t\t\t(struct dyld_chained_ptr_arm64e_rebase *) &raw_ptr;\n\t\t\t\t\t\t\tevent = R_FIXUP_EVENT_REBASE;\n\t\t\t\t\t\t\tdelta = p->next;\n\t\t\t\t\t\t\tptr_value = ((ut64)p->high8 << 56) | p->target;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (pointer_format == DYLD_CHAINED_PTR_ARM64E_USERLAND24) {\n\t\t\t\t\t\tstride = 8;\n\t\t\t\t\t\tstruct dyld_chained_ptr_arm64e_bind24 *bind =\n\t\t\t\t\t\t\t\t(struct dyld_chained_ptr_arm64e_bind24 *) &raw_ptr;\n\t\t\t\t\t\tif (bind->bind) {\n\t\t\t\t\t\t\tdelta = bind->next;\n\t\t\t\t\t\t\tif (bind->auth) {\n\t\t\t\t\t\t\t\tstruct dyld_chained_ptr_arm64e_auth_bind24 *p =\n\t\t\t\t\t\t\t\t\t\t(struct dyld_chained_ptr_arm64e_auth_bind24 *) &raw_ptr;\n\t\t\t\t\t\t\t\tevent = R_FIXUP_EVENT_BIND_AUTH;\n\t\t\t\t\t\t\t\tordinal = p->ordinal;\n\t\t\t\t\t\t\t\tkey = p->key;\n\t\t\t\t\t\t\t\taddr_div = p->addrDiv;\n\t\t\t\t\t\t\t\tdiversity = p->diversity;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tevent = R_FIXUP_EVENT_BIND;\n\t\t\t\t\t\t\t\tordinal = bind->ordinal;\n\t\t\t\t\t\t\t\taddend = bind->addend;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif (bind->auth) {\n\t\t\t\t\t\t\t\tstruct dyld_chained_ptr_arm64e_auth_rebase *p =\n\t\t\t\t\t\t\t\t\t\t(struct dyld_chained_ptr_arm64e_auth_rebase *) &raw_ptr;\n\t\t\t\t\t\t\t\tevent = R_FIXUP_EVENT_REBASE_AUTH;\n\t\t\t\t\t\t\t\tdelta = p->next;\n\t\t\t\t\t\t\t\tptr_value = p->target + bin->baddr;\n\t\t\t\t\t\t\t\tkey = p->key;\n\t\t\t\t\t\t\t\taddr_div = p->addrDiv;\n\t\t\t\t\t\t\t\tdiversity = p->diversity;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tstruct dyld_chained_ptr_arm64e_rebase *p =\n\t\t\t\t\t\t\t\t\t(struct dyld_chained_ptr_arm64e_rebase *) &raw_ptr;\n\t\t\t\t\t\t\t\tevent = R_FIXUP_EVENT_REBASE;\n\t\t\t\t\t\t\t\tdelta = p->next;\n\t\t\t\t\t\t\t\tptr_value = bin->baddr + (((ut64)p->high8 << 56) | p->target);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (pointer_format == DYLD_CHAINED_PTR_64_OFFSET) {\n\t\t\t\t\t\tstride = 4;\n\t\t\t\t\t\tstruct dyld_chained_ptr_64_bind *bind =\n\t\t\t\t\t\t\t\t(struct dyld_chained_ptr_64_bind *) &raw_ptr;\n\t\t\t\t\t\tif (bind->bind) {\n\t\t\t\t\t\t\tevent = R_FIXUP_EVENT_BIND;\n\t\t\t\t\t\t\tdelta = bind->next;\n\t\t\t\t\t\t\tordinal = bind->ordinal;\n\t\t\t\t\t\t\taddend = bind->addend;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tstruct dyld_chained_ptr_64_rebase *p =\n\t\t\t\t\t\t\t\t(struct dyld_chained_ptr_64_rebase *) &raw_ptr;\n\t\t\t\t\t\t\tevent = R_FIXUP_EVENT_REBASE;\n\t\t\t\t\t\t\tdelta = p->next;\n\t\t\t\t\t\t\tptr_value = bin->baddr + (((ut64)p->high8 << 56) | p->target);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\teprintf (\"Unsupported chained pointer format %d\\n\", pointer_format);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (cursor >= limit_start && cursor <= limit_end - 8 && (event & event_mask) != 0) {\n\t\t\t\t\t\tbool carry_on;\n\t\t\t\t\t\tswitch (event) {\n\t\t\t\t\t\t\tcase R_FIXUP_EVENT_BIND: {\n\t\t\t\t\t\t\t\tRFixupBindEventDetails event_details;\n\n\t\t\t\t\t\t\t\tevent_details.type = event;\n\t\t\t\t\t\t\t\tevent_details.bin = bin;\n\t\t\t\t\t\t\t\tevent_details.offset = cursor;\n\t\t\t\t\t\t\t\tevent_details.raw_ptr = raw_ptr;\n\t\t\t\t\t\t\t\tevent_details.ordinal = ordinal;\n\t\t\t\t\t\t\t\tevent_details.addend = addend;\n\n\t\t\t\t\t\t\t\tcarry_on = callback (context, (RFixupEventDetails *) &event_details);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcase R_FIXUP_EVENT_BIND_AUTH: {\n\t\t\t\t\t\t\t\tRFixupBindAuthEventDetails event_details;\n\n\t\t\t\t\t\t\t\tevent_details.type = event;\n\t\t\t\t\t\t\t\tevent_details.bin = bin;\n\t\t\t\t\t\t\t\tevent_details.offset = cursor;\n\t\t\t\t\t\t\t\tevent_details.raw_ptr = raw_ptr;\n\t\t\t\t\t\t\t\tevent_details.ordinal = ordinal;\n\t\t\t\t\t\t\t\tevent_details.key = key;\n\t\t\t\t\t\t\t\tevent_details.addr_div = addr_div;\n\t\t\t\t\t\t\t\tevent_details.diversity = diversity;\n\n\t\t\t\t\t\t\t\tcarry_on = callback (context, (RFixupEventDetails *) &event_details);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcase R_FIXUP_EVENT_REBASE: {\n\t\t\t\t\t\t\t\tRFixupRebaseEventDetails event_details;\n\n\t\t\t\t\t\t\t\tevent_details.type = event;\n\t\t\t\t\t\t\t\tevent_details.bin = bin;\n\t\t\t\t\t\t\t\tevent_details.offset = cursor;\n\t\t\t\t\t\t\t\tevent_details.raw_ptr = raw_ptr;\n\t\t\t\t\t\t\t\tevent_details.ptr_value = ptr_value;\n\n\t\t\t\t\t\t\t\tcarry_on = callback (context, (RFixupEventDetails *) &event_details);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcase R_FIXUP_EVENT_REBASE_AUTH: {\n\t\t\t\t\t\t\t\tRFixupRebaseAuthEventDetails event_details;\n\n\t\t\t\t\t\t\t\tevent_details.type = event;\n\t\t\t\t\t\t\t\tevent_details.bin = bin;\n\t\t\t\t\t\t\t\tevent_details.offset = cursor;\n\t\t\t\t\t\t\t\tevent_details.raw_ptr = raw_ptr;\n\t\t\t\t\t\t\t\tevent_details.ptr_value = ptr_value;\n\t\t\t\t\t\t\t\tevent_details.key = key;\n\t\t\t\t\t\t\t\tevent_details.addr_div = addr_div;\n\t\t\t\t\t\t\t\tevent_details.diversity = diversity;\n\n\t\t\t\t\t\t\t\tcarry_on = callback (context, (RFixupEventDetails *) &event_details);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\teprintf (\"Unexpected event while iterating chained fixups\\n\");\n\t\t\t\t\t\t\t\tcarry_on = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!carry_on) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcursor += delta * stride;\n\t\t\t\t\tif (!delta) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'Fix heap OOB read in macho.iterate_chained_fixups ##crash\n\n* Reported by peacock-doris via huntr.dev\r\n* Reproducer 'tests_65305'\r\n\r\nmrmacete:\r\n* Return early if segs_count is 0\r\n* Initialize segs_count also for reconstructed fixups\r\n\r\nCo-authored-by: pancake \r\nCo-authored-by: Francesco Tamagni '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int FNAME(cmpxchg_gpte)(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,\n\t\t\t pt_element_t __user *ptep_user, unsigned index,\n\t\t\t pt_element_t orig_pte, pt_element_t new_pte)\n{\n\tint npages;\n\tpt_element_t ret;\n\tpt_element_t *table;\n\tstruct page *page;\n\n\tnpages = get_user_pages_fast((unsigned long)ptep_user, 1, FOLL_WRITE, &page);\n\tif (likely(npages == 1)) {\n\t\ttable = kmap_atomic(page);\n\t\tret = CMPXCHG(&table[index], orig_pte, new_pte);\n\t\tkunmap_atomic(table);\n\n\t\tkvm_release_page_dirty(page);\n\t} else {\n\t\tstruct vm_area_struct *vma;\n\t\tunsigned long vaddr = (unsigned long)ptep_user & PAGE_MASK;\n\t\tunsigned long pfn;\n\t\tunsigned long paddr;\n\n\t\tmmap_read_lock(current->mm);\n\t\tvma = find_vma_intersection(current->mm, vaddr, vaddr + PAGE_SIZE);\n\t\tif (!vma || !(vma->vm_flags & VM_PFNMAP)) {\n\t\t\tmmap_read_unlock(current->mm);\n\t\t\treturn -EFAULT;\n\t\t}\n\t\tpfn = ((vaddr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;\n\t\tpaddr = pfn << PAGE_SHIFT;\n\t\ttable = memremap(paddr, PAGE_SIZE, MEMREMAP_WB);\n\t\tif (!table) {\n\t\t\tmmap_read_unlock(current->mm);\n\t\t\treturn -EFAULT;\n\t\t}\n\t\tret = CMPXCHG(&table[index], orig_pte, new_pte);\n\t\tmemunmap(table);\n\t\tmmap_read_unlock(current->mm);\n\t}\n\n\treturn (ret != orig_pte);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'KVM: x86/mmu: do compare-and-exchange of gPTE via the user address\n\nFNAME(cmpxchg_gpte) is an inefficient mess. It is at least decent if it\ncan go through get_user_pages_fast(), but if it cannot then it tries to\nuse memremap(); that is not just terribly slow, it is also wrong because\nit assumes that the VM_PFNMAP VMA is contiguous.\n\nThe right way to do it would be to do the same thing as\nhva_to_pfn_remapped() does since commit add6a0cd1c5b (\"KVM: MMU: try to\nfix up page faults before giving up\", 2016-07-05), using follow_pte()\nand fixup_user_fault() to determine the correct address to use for\nmemremap(). To do this, one could for example extract hva_to_pfn()\nfor use outside virt/kvm/kvm_main.c. But really there is no reason to\ndo that either, because there is already a perfectly valid address to\ndo the cmpxchg() on, only it is a userspace address. That means doing\nuser_access_begin()/user_access_end() and writing the code in assembly\nto handle exceptions correctly. Worse, the guest PTE can be 8-byte\neven on i686 so there is the extra complication of using cmpxchg8b to\naccount for. But at least it is an efficient mess.\n\n(Thanks to Linus for suggesting improvement on the inline assembly).\n\nReported-by: Qiuhao Li \nReported-by: Gaoning Pan \nReported-by: Yongkang Jia \nReported-by: syzbot+6cde2282daa792c49ab8@syzkaller.appspotmail.com\nDebugged-by: Tadeusz Struk \nTested-by: Maxim Levitsky \nCc: stable@vger.kernel.org\nFixes: bd53cb35a3e9 (\"X86/KVM: Handle PFNs outside of kernel reach when touching GPTEs\")\nSigned-off-by: Paolo Bonzini '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void ax25_kill_by_device(struct net_device *dev)\n{\n\tax25_dev *ax25_dev;\n\tax25_cb *s;\n\tstruct sock *sk;\n\n\tif ((ax25_dev = ax25_dev_ax25dev(dev)) == NULL)\n\t\treturn;\n\n\tspin_lock_bh(&ax25_list_lock);\nagain:\n\tax25_for_each(s, &ax25_list) {\n\t\tif (s->ax25_dev == ax25_dev) {\n\t\t\tsk = s->sk;\n\t\t\tif (!sk) {\n\t\t\t\tspin_unlock_bh(&ax25_list_lock);\n\t\t\t\ts->ax25_dev = NULL;\n\t\t\t\tax25_disconnect(s, ENETUNREACH);\n\t\t\t\tspin_lock_bh(&ax25_list_lock);\n\t\t\t\tgoto again;\n\t\t\t}\n\t\t\tsock_hold(sk);\n\t\t\tspin_unlock_bh(&ax25_list_lock);\n\t\t\tlock_sock(sk);\n\t\t\ts->ax25_dev = NULL;\n\t\t\tif (sk->sk_socket) {\n\t\t\t\tdev_put_track(ax25_dev->dev, &ax25_dev->dev_tracker);\n\t\t\t\tax25_dev_put(ax25_dev);\n\t\t\t}\n\t\t\tax25_disconnect(s, ENETUNREACH);\n\t\t\trelease_sock(sk);\n\t\t\tspin_lock_bh(&ax25_list_lock);\n\t\t\tsock_put(sk);\n\t\t\t/* The entry could have been deleted from the\n\t\t\t * list meanwhile and thus the next pointer is\n\t\t\t * no longer valid. Play it safe and restart\n\t\t\t * the scan. Forward progress is ensured\n\t\t\t * because we set s->ax25_dev to NULL and we\n\t\t\t * are never passed a NULL 'dev' argument.\n\t\t\t */\n\t\t\tgoto again;\n\t\t}\n\t}\n\tspin_unlock_bh(&ax25_list_lock);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'ax25: Fix NULL pointer dereferences in ax25 timers\n\nThe previous commit 7ec02f5ac8a5 (\"ax25: fix NPD bug in ax25_disconnect\")\nmove ax25_disconnect into lock_sock() in order to prevent NPD bugs. But\nthere are race conditions that may lead to null pointer dereferences in\nax25_heartbeat_expiry(), ax25_t1timer_expiry(), ax25_t2timer_expiry(),\nax25_t3timer_expiry() and ax25_idletimer_expiry(), when we use\nax25_kill_by_device() to detach the ax25 device.\n\nOne of the race conditions that cause null pointer dereferences can be\nshown as below:\n\n (Thread 1) | (Thread 2)\nax25_connect() |\n ax25_std_establish_data_link() |\n ax25_start_t1timer() |\n mod_timer(&ax25->t1timer,..) |\n | ax25_kill_by_device()\n (wait a time) | ...\n | s->ax25_dev = NULL; //(1)\n ax25_t1timer_expiry() |\n ax25->ax25_dev->values[..] //(2)| ...\n ... |\n\nWe set null to ax25_cb->ax25_dev in position (1) and dereference\nthe null pointer in position (2).\n\nThe corresponding fail log is shown below:\n===============================================================\nBUG: kernel NULL pointer dereference, address: 0000000000000050\nCPU: 1 PID: 0 Comm: swapper/1 Not tainted 5.17.0-rc6-00794-g45690b7d0\nRIP: 0010:ax25_t1timer_expiry+0x12/0x40\n...\nCall Trace:\n call_timer_fn+0x21/0x120\n __run_timers.part.0+0x1ca/0x250\n run_timer_softirq+0x2c/0x60\n __do_softirq+0xef/0x2f3\n irq_exit_rcu+0xb6/0x100\n sysvec_apic_timer_interrupt+0xa2/0xd0\n...\n\nThis patch moves ax25_disconnect() before s->ax25_dev = NULL\nand uses del_timer_sync() to delete timers in ax25_disconnect().\nIf ax25_disconnect() is called by ax25_kill_by_device() or\nax25->ax25_dev is NULL, the reason in ax25_disconnect() will be\nequal to ENETUNREACH, it will wait all timers to stop before we\nset null to s->ax25_dev in ax25_kill_by_device().\n\nFixes: 7ec02f5ac8a5 (\"ax25: fix NPD bug in ax25_disconnect\")\nSigned-off-by: Duoming Zhou \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int __must_check ax25_rt_add(struct ax25_routes_struct *route)\n{\n\tax25_route *ax25_rt;\n\tax25_dev *ax25_dev;\n\tint i;\n\n\tif ((ax25_dev = ax25_addr_ax25dev(&route->port_addr)) == NULL)\n\t\treturn -EINVAL;\n\tif (route->digi_count > AX25_MAX_DIGIS)\n\t\treturn -EINVAL;\n\n\twrite_lock_bh(&ax25_route_lock);\n\n\tax25_rt = ax25_route_list;\n\twhile (ax25_rt != NULL) {\n\t\tif (ax25cmp(&ax25_rt->callsign, &route->dest_addr) == 0 &&\n\t\t\t ax25_rt->dev == ax25_dev->dev) {\n\t\t\tkfree(ax25_rt->digipeat);\n\t\t\tax25_rt->digipeat = NULL;\n\t\t\tif (route->digi_count != 0) {\n\t\t\t\tif ((ax25_rt->digipeat = kmalloc(sizeof(ax25_digi), GFP_ATOMIC)) == NULL) {\n\t\t\t\t\twrite_unlock_bh(&ax25_route_lock);\n\t\t\t\t\treturn -ENOMEM;\n\t\t\t\t}\n\t\t\t\tax25_rt->digipeat->lastrepeat = -1;\n\t\t\t\tax25_rt->digipeat->ndigi = route->digi_count;\n\t\t\t\tfor (i = 0; i < route->digi_count; i++) {\n\t\t\t\t\tax25_rt->digipeat->repeated[i] = 0;\n\t\t\t\t\tax25_rt->digipeat->calls[i] = route->digi_addr[i];\n\t\t\t\t}\n\t\t\t}\n\t\t\twrite_unlock_bh(&ax25_route_lock);\n\t\t\treturn 0;\n\t\t}\n\t\tax25_rt = ax25_rt->next;\n\t}\n\n\tif ((ax25_rt = kmalloc(sizeof(ax25_route), GFP_ATOMIC)) == NULL) {\n\t\twrite_unlock_bh(&ax25_route_lock);\n\t\treturn -ENOMEM;\n\t}\n\n\trefcount_set(&ax25_rt->refcount, 1);\n\tax25_rt->callsign = route->dest_addr;\n\tax25_rt->dev = ax25_dev->dev;\n\tax25_rt->digipeat = NULL;\n\tax25_rt->ip_mode = ' ';\n\tif (route->digi_count != 0) {\n\t\tif ((ax25_rt->digipeat = kmalloc(sizeof(ax25_digi), GFP_ATOMIC)) == NULL) {\n\t\t\twrite_unlock_bh(&ax25_route_lock);\n\t\t\tkfree(ax25_rt);\n\t\t\treturn -ENOMEM;\n\t\t}\n\t\tax25_rt->digipeat->lastrepeat = -1;\n\t\tax25_rt->digipeat->ndigi = route->digi_count;\n\t\tfor (i = 0; i < route->digi_count; i++) {\n\t\t\tax25_rt->digipeat->repeated[i] = 0;\n\t\t\tax25_rt->digipeat->calls[i] = route->digi_addr[i];\n\t\t}\n\t}\n\tax25_rt->next = ax25_route_list;\n\tax25_route_list = ax25_rt;\n\twrite_unlock_bh(&ax25_route_lock);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'ax25: add refcount in ax25_dev to avoid UAF bugs\n\nIf we dereference ax25_dev after we call kfree(ax25_dev) in\nax25_dev_device_down(), it will lead to concurrency UAF bugs.\nThere are eight syscall functions suffer from UAF bugs, include\nax25_bind(), ax25_release(), ax25_connect(), ax25_ioctl(),\nax25_getname(), ax25_sendmsg(), ax25_getsockopt() and\nax25_info_show().\n\nOne of the concurrency UAF can be shown as below:\n\n (USE) | (FREE)\n | ax25_device_event\n | ax25_dev_device_down\nax25_bind | ...\n ... | kfree(ax25_dev)\n ax25_fillin_cb() | ...\n ax25_fillin_cb_from_dev() |\n ... |\n\nThe root cause of UAF bugs is that kfree(ax25_dev) in\nax25_dev_device_down() is not protected by any locks.\nWhen ax25_dev, which there are still pointers point to,\nis released, the concurrency UAF bug will happen.\n\nThis patch introduces refcount into ax25_dev in order to\nguarantee that there are no pointers point to it when ax25_dev\nis released.\n\nSigned-off-by: Duoming Zhou \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int ax25_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct full_sockaddr_ax25 *addr = (struct full_sockaddr_ax25 *)uaddr;\n\tax25_dev *ax25_dev = NULL;\n\tax25_uid_assoc *user;\n\tax25_address call;\n\tax25_cb *ax25;\n\tint err = 0;\n\n\tif (addr_len != sizeof(struct sockaddr_ax25) &&\n\t addr_len != sizeof(struct full_sockaddr_ax25))\n\t\t/* support for old structure may go away some time\n\t\t * ax25_bind(): uses old (6 digipeater) socket structure.\n\t\t */\n\t\tif ((addr_len < sizeof(struct sockaddr_ax25) + sizeof(ax25_address) * 6) ||\n\t\t (addr_len > sizeof(struct full_sockaddr_ax25)))\n\t\t\treturn -EINVAL;\n\n\tif (addr->fsa_ax25.sax25_family != AF_AX25)\n\t\treturn -EINVAL;\n\n\tuser = ax25_findbyuid(current_euid());\n\tif (user) {\n\t\tcall = user->call;\n\t\tax25_uid_put(user);\n\t} else {\n\t\tif (ax25_uid_policy && !capable(CAP_NET_ADMIN))\n\t\t\treturn -EACCES;\n\n\t\tcall = addr->fsa_ax25.sax25_call;\n\t}\n\n\tlock_sock(sk);\n\n\tax25 = sk_to_ax25(sk);\n\tif (!sock_flag(sk, SOCK_ZAPPED)) {\n\t\terr = -EINVAL;\n\t\tgoto out;\n\t}\n\n\tax25->source_addr = call;\n\n\t/*\n\t * User already set interface with SO_BINDTODEVICE\n\t */\n\tif (ax25->ax25_dev != NULL)\n\t\tgoto done;\n\n\tif (addr_len > sizeof(struct sockaddr_ax25) && addr->fsa_ax25.sax25_ndigis == 1) {\n\t\tif (ax25cmp(&addr->fsa_digipeater[0], &null_ax25_address) != 0 &&\n\t\t (ax25_dev = ax25_addr_ax25dev(&addr->fsa_digipeater[0])) == NULL) {\n\t\t\terr = -EADDRNOTAVAIL;\n\t\t\tgoto out;\n\t\t}\n\t} else {\n\t\tif ((ax25_dev = ax25_addr_ax25dev(&addr->fsa_ax25.sax25_call)) == NULL) {\n\t\t\terr = -EADDRNOTAVAIL;\n\t\t\tgoto out;\n\t\t}\n\t}\n\n\tif (ax25_dev != NULL)\n\t\tax25_fillin_cb(ax25, ax25_dev);\n\ndone:\n\tax25_cb_add(ax25);\n\tsock_reset_flag(sk, SOCK_ZAPPED);\n\nout:\n\trelease_sock(sk);\n\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'ax25: fix UAF bugs of net_device caused by rebinding operation\n\nThe ax25_kill_by_device() will set s->ax25_dev = NULL and\ncall ax25_disconnect() to change states of ax25_cb and\nsock, if we call ax25_bind() before ax25_kill_by_device().\n\nHowever, if we call ax25_bind() again between the window of\nax25_kill_by_device() and ax25_dev_device_down(), the values\nand states changed by ax25_kill_by_device() will be reassigned.\n\nFinally, ax25_dev_device_down() will deallocate net_device.\nIf we dereference net_device in syscall functions such as\nax25_release(), ax25_sendmsg(), ax25_getsockopt(), ax25_getname()\nand ax25_info_show(), a UAF bug will occur.\n\nOne of the possible race conditions is shown below:\n\n (USE) | (FREE)\nax25_bind() |\n | ax25_kill_by_device()\nax25_bind() |\nax25_connect() | ...\n | ax25_dev_device_down()\n | ...\n | dev_put_track(dev, ...) //FREE\nax25_release() | ...\n ax25_send_control() |\n alloc_skb() //USE |\n\nthe corresponding fail log is shown below:\n===============================================================\nBUG: KASAN: use-after-free in ax25_send_control+0x43/0x210\n...\nCall Trace:\n ...\n ax25_send_control+0x43/0x210\n ax25_release+0x2db/0x3b0\n __sock_release+0x6d/0x120\n sock_close+0xf/0x20\n __fput+0x11f/0x420\n ...\nAllocated by task 1283:\n ...\n __kasan_kmalloc+0x81/0xa0\n alloc_netdev_mqs+0x5a/0x680\n mkiss_open+0x6c/0x380\n tty_ldisc_open+0x55/0x90\n ...\nFreed by task 1969:\n ...\n kfree+0xa3/0x2c0\n device_release+0x54/0xe0\n kobject_put+0xa5/0x120\n tty_ldisc_kill+0x3e/0x80\n ...\n\nIn order to fix these UAF bugs caused by rebinding operation,\nthis patch adds dev_hold_track() into ax25_bind() and\ncorresponding dev_put_track() into ax25_kill_by_device().\n\nSigned-off-by: Duoming Zhou \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static netdev_tx_t usb_8dev_start_xmit(struct sk_buff *skb,\n\t\t\t\t struct net_device *netdev)\n{\n\tstruct usb_8dev_priv *priv = netdev_priv(netdev);\n\tstruct net_device_stats *stats = &netdev->stats;\n\tstruct can_frame *cf = (struct can_frame *) skb->data;\n\tstruct usb_8dev_tx_msg *msg;\n\tstruct urb *urb;\n\tstruct usb_8dev_tx_urb_context *context = NULL;\n\tu8 *buf;\n\tint i, err;\n\tsize_t size = sizeof(struct usb_8dev_tx_msg);\n\n\tif (can_dropped_invalid_skb(netdev, skb))\n\t\treturn NETDEV_TX_OK;\n\n\t/* create a URB, and a buffer for it, and copy the data to the URB */\n\turb = usb_alloc_urb(0, GFP_ATOMIC);\n\tif (!urb)\n\t\tgoto nomem;\n\n\tbuf = usb_alloc_coherent(priv->udev, size, GFP_ATOMIC,\n\t\t\t\t &urb->transfer_dma);\n\tif (!buf) {\n\t\tnetdev_err(netdev, \"No memory left for USB buffer\\n\");\n\t\tgoto nomembuf;\n\t}\n\n\tmemset(buf, 0, size);\n\n\tmsg = (struct usb_8dev_tx_msg *)buf;\n\tmsg->begin = USB_8DEV_DATA_START;\n\tmsg->flags = 0x00;\n\n\tif (cf->can_id & CAN_RTR_FLAG)\n\t\tmsg->flags |= USB_8DEV_RTR;\n\n\tif (cf->can_id & CAN_EFF_FLAG)\n\t\tmsg->flags |= USB_8DEV_EXTID;\n\n\tmsg->id = cpu_to_be32(cf->can_id & CAN_ERR_MASK);\n\tmsg->dlc = can_get_cc_dlc(cf, priv->can.ctrlmode);\n\tmemcpy(msg->data, cf->data, cf->len);\n\tmsg->end = USB_8DEV_DATA_END;\n\n\tfor (i = 0; i < MAX_TX_URBS; i++) {\n\t\tif (priv->tx_contexts[i].echo_index == MAX_TX_URBS) {\n\t\t\tcontext = &priv->tx_contexts[i];\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t/* May never happen! When this happens we'd more URBs in flight as\n\t * allowed (MAX_TX_URBS).\n\t */\n\tif (!context)\n\t\tgoto nofreecontext;\n\n\tcontext->priv = priv;\n\tcontext->echo_index = i;\n\n\tusb_fill_bulk_urb(urb, priv->udev,\n\t\t\t usb_sndbulkpipe(priv->udev, USB_8DEV_ENDP_DATA_TX),\n\t\t\t buf, size, usb_8dev_write_bulk_callback, context);\n\turb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;\n\tusb_anchor_urb(urb, &priv->tx_submitted);\n\n\tcan_put_echo_skb(skb, netdev, context->echo_index, 0);\n\n\tatomic_inc(&priv->active_tx_urbs);\n\n\terr = usb_submit_urb(urb, GFP_ATOMIC);\n\tif (unlikely(err))\n\t\tgoto failed;\n\telse if (atomic_read(&priv->active_tx_urbs) >= MAX_TX_URBS)\n\t\t/* Slow down tx path */\n\t\tnetif_stop_queue(netdev);\n\n\t/* Release our reference to this URB, the USB core will eventually free\n\t * it entirely.\n\t */\n\tusb_free_urb(urb);\n\n\treturn NETDEV_TX_OK;\n\nnofreecontext:\n\tusb_free_coherent(priv->udev, size, buf, urb->transfer_dma);\n\tusb_free_urb(urb);\n\n\tnetdev_warn(netdev, \"couldn't find free context\");\n\n\treturn NETDEV_TX_BUSY;\n\nfailed:\n\tcan_free_echo_skb(netdev, context->echo_index, NULL);\n\n\tusb_unanchor_urb(urb);\n\tusb_free_coherent(priv->udev, size, buf, urb->transfer_dma);\n\n\tatomic_dec(&priv->active_tx_urbs);\n\n\tif (err == -ENODEV)\n\t\tnetif_device_detach(netdev);\n\telse\n\t\tnetdev_warn(netdev, \"failed tx_urb %d\\n\", err);\n\nnomembuf:\n\tusb_free_urb(urb);\n\nnomem:\n\tdev_kfree_skb(skb);\n\tstats->tx_dropped++;\n\n\treturn NETDEV_TX_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'can: usb_8dev: usb_8dev_start_xmit(): fix double dev_kfree_skb() in error path\n\nThere is no need to call dev_kfree_skb() when usb_submit_urb() fails\nbecause can_put_echo_skb() deletes original skb and\ncan_free_echo_skb() deletes the cloned skb.\n\nFixes: 0024d8ad1639 (\"can: usb_8dev: Add support for USB2CAN interface from 8 devices\")\nLink: https://lore.kernel.org/all/20220311080614.45229-1-hbh25y@gmail.com\nCc: stable@vger.kernel.org\nSigned-off-by: Hangyu Hua \nSigned-off-by: Marc Kleine-Budde '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: RList *r_bin_ne_get_entrypoints(r_bin_ne_obj_t *bin) {\n\tRList *entries = r_list_newf (free);\n\tif (!entries) {\n\t\treturn NULL;\n\t}\n\tRBinAddr *entry;\n\tRList *segments = r_bin_ne_get_segments (bin);\n\tif (!segments) {\n\t\tr_list_free (entries);\n\t\treturn NULL;\n\t}\n\tif (bin->ne_header->csEntryPoint) {\n\t\tentry = R_NEW0 (RBinAddr);\n\t\tif (!entry) {\n\t\t\tr_list_free (entries);\n\t\t\treturn NULL;\n\t\t}\n\t\tentry->bits = 16;\n\t\tRBinSection *s = r_list_get_n (segments, bin->ne_header->csEntryPoint - 1);\n\t\tentry->paddr = bin->ne_header->ipEntryPoint + (s? s->paddr: 0);\n\t\tr_list_append (entries, entry);\n\t}\n\tint off = 0;\n\twhile (off < bin->ne_header->EntryTableLength) {\n\t\tut8 bundle_length = *(ut8 *)(bin->entry_table + off);\n\t\tif (!bundle_length) {\n\t\t\tbreak;\n\t\t}\n\t\toff++;\n\t\tut8 bundle_type = *(ut8 *)(bin->entry_table + off);\n\t\toff++;\n\t\tint i;\n\t\tfor (i = 0; i < bundle_length; i++) {\n\t\t\tentry = R_NEW0 (RBinAddr);\n\t\t\tif (!entry) {\n\t\t\t\tr_list_free (entries);\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\toff++;\n\t\t\tif (!bundle_type) { // Skip\n\t\t\t\toff--;\n\t\t\t\tfree (entry);\n\t\t\t\tbreak;\n\t\t\t} else if (bundle_type == 0xFF) { // Moveable\n\t\t\t\toff += 2;\n\t\t\t\tut8 segnum = *(bin->entry_table + off);\n\t\t\t\toff++;\n\t\t\t\tut16 segoff = *(ut16 *)(bin->entry_table + off);\n\t\t\t\tentry->paddr = (ut64)bin->segment_entries[segnum - 1].offset * bin->alignment + segoff;\n\t\t\t} else { // Fixed\n\t\t\t\tentry->paddr = (ut64)bin->segment_entries[bundle_type - 1].offset * bin->alignment + *(ut16 *)(bin->entry_table + off);\n\t\t\t}\n\t\t\toff += 2;\n\t\t\tr_list_append (entries, entry);\n\t\t}\n\t}\n\tr_list_free (segments);\n\tbin->entries = entries;\n\treturn entries;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-805', 'CWE-787'], 'message': 'Fix another oobread segfault in the NE bin parser ##crash\n\n* Reported by @han0nly via huntr.dev\n* Reproducers: sample1 sample2 sample3\n* BountyID: 47422cdf-aad2-4405-a6a1-6f63a3a93200'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: evdev_device_get_sysname(struct evdev_device *device)\n{\n\treturn udev_device_get_sysname(device->udev_device);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-134'], 'message': 'evdev: strip the device name of format directives\n\nThis fixes a format string vulnerabilty.\n\nevdev_log_message() composes a format string consisting of a fixed\nprefix (including the rendered device name) and the passed-in format\nbuffer. This format string is then passed with the arguments to the\nactual log handler, which usually and eventually ends up being printf.\n\nIf the device name contains a printf-style format directive, these ended\nup in the format string and thus get interpreted correctly, e.g. for a\ndevice \"Foo%sBar\" the log message vs printf invocation ends up being:\n evdev_log_message(device, \"some message %s\", \"some argument\");\n printf(\"event9 - Foo%sBar: some message %s\", \"some argument\");\n\nThis can enable an attacker to execute malicious code with the\nprivileges of the process using libinput.\n\nTo exploit this, an attacker needs to be able to create a kernel device\nwith a malicious name, e.g. through /dev/uinput or a Bluetooth device.\n\nTo fix this, convert any potential format directives in the device name\nby duplicating percentages.\n\nPre-rendering the device to avoid the issue altogether would be nicer\nbut the current log level hooks do not easily allow for this. The device\nname is the only user-controlled part of the format string.\n\nA second potential issue is the sysname of the device which is also\nsanitized.\n\nThis issue was found by Albin Eldst\u00e5l-Ahrens and Benjamin Svensson from\nAssured AB, and independently by Lukas Lamster.\n\nFixes #752\n\nSigned-off-by: Peter Hutterer '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void get_cmdln_options(int argc, char *argv[]) {\n\tint o;\n#if CONFIG_FILE && HAVE_GETPWUID\n static struct passwd *pwd_entry;\n char *str;\n#endif\n#ifdef LONG_OPTIONS\n int option_index = 0;\n static struct option long_options[] = {\n {\"timeout\", 1, 0, 't'},\n#ifdef PROC_NET_DEV\n {\"procfile\",1,0,'f'},\n#endif\n#ifdef PROC_DISKSTATS\n\t\t\t{\"diskstatsfile\",1,0,1000},\n\t\t\t{\"partitionsfile\",1,0,1001},\n#endif\t\t \n#if NETSTAT && ALLOW_NETSTATPATH\n {\"netstat\",1,0,'n'},\n#endif\n#if IOSERVICE_IN\n\t\t {\"longdisknames\",0,0,1002},\n#endif\n {\"input\",1,0,'i'},\n {\"dynamic\",1,0,'d'},\n {\"help\", 0, 0, 'h'},\n {\"version\",0,0,'V'},\n {\"allif\",1,0,'a'},\n {\"unit\",1,0,'u'},\n\t\t {\"ansiout\",0,0,'N'},\n#if EXTENDED_STATS \n {\"type\",1,0,'T'},\n {\"avglength\",1,0,'A'},\n#endif \n {\"interfaces\",1,0,'I'},\n {\"sumhidden\",1,0,'S'},\n {\"output\",1,0,'o'},\n#ifdef CSV\n {\"csvchar\",1,0,'C'},\n {\"csvfile\",1,0,'F'},\n#endif\n {\"count\",1,0,'c'},\n {\"daemon\",1,0,'D'},\n#ifdef HTML\n {\"htmlrefresh\",1,0,'R'},\n {\"htmlheader\",1,0,'H'},\n#endif\n {0,0,0,0}\n };\n#endif\n#ifdef CONFIG_FILE\n /* loop till first non option argument */\n opterr=0;\n while (1) {\n#ifdef LONG_OPTIONS\n o=getopt_long (argc,argv,SHORT_OPTIONS,long_options, &option_index);\n#else\n o=getopt (argc,argv,SHORT_OPTIONS);\n#endif\n if (o==-1) break;\n }\n opterr=1;\n if (optind < argc) {\n read_config(argv[optind]);\n } else {\n read_config(\"/etc/bwm-ng.conf\");\n#ifdef HAVE_GETPWUID \n pwd_entry=getpwuid(getuid());\n if (pwd_entry!=NULL) {\n str=(char*)malloc(strlen(pwd_entry->pw_dir)+14);\n snprintf(str,strlen(pwd_entry->pw_dir)+14,\"%s/.bwm-ng.conf\",pwd_entry->pw_dir);\n read_config(str);\n free(str);\n }\n#endif \n }\n /* reset getopt again */\n optind=1;\n#endif\n /* get command line arguments, kinda ugly, wanna rewrite it? */\n while (1) {\n#ifdef LONG_OPTIONS\n\t\to=getopt_long (argc,argv,SHORT_OPTIONS,long_options, &option_index);\n#else\n\t\to=getopt (argc,argv,SHORT_OPTIONS);\n#endif\t\t\n if (o==-1) break;\n switch (o) {\n case '?': printf(\"unknown option: %s\\n\",argv[optind-1]);\n exit(EXIT_FAILURE);\n break;\n /* ugly workaround to handle optional arguments for all platforms */ \n case ':': if (!strcmp(argv[optind-1],\"-a\") || !strcasecmp(argv[optind-1],\"--allif\")) \n show_all_if=1;\n else if (!strcmp(argv[optind-1],\"-d\") || !strcasecmp(argv[optind-1],\"--dynamic\"))\n dynamic=1;\n else if (!strcmp(argv[optind-1],\"-D\") || !strcasecmp(argv[optind-1],\"--daemon\"))\n daemonize=1;\n#ifdef HTML \n else if (!strcmp(argv[optind-1],\"-H\") || !strcasecmp(argv[optind-1],\"--htmlheader\"))\n html_header=1;\n#endif \n else if (!strcmp(argv[optind-1],\"-S\") || !strcasecmp(argv[optind-1],\"--sumhidden\"))\n sumhidden=1; \n else {\n printf(\"%s requires an argument!\\n\",argv[optind-1]);\n exit(EXIT_FAILURE);\n }\n break;\n#ifdef PROC_DISKSTATS\n\t\t\tcase 1000:\n\t\t\t\tif (strlen(optarg)0) { html_refresh=atol(optarg); }\n\t\t\t\tbreak;\n\t\t\tcase 'H':\n\t\t\t\tif (optarg) html_header=atoi(optarg);\n\t\t\t\tbreak;\n#endif\n\t\t\tcase 'c':\n\t\t\t\tif (optarg) output_count=atol(optarg);\n\t\t\t\tbreak;\n#if CSV || HTML\n case 'F':\n if (optarg) { \n if (out_file) fclose(out_file);\n out_file=fopen(optarg,\"a\"); \n if (!out_file) deinit(1, \"failed to open outfile\\n\");\n if (out_file_path) free(out_file_path);\n out_file_path=(char *)strdup(optarg);\n }\n break;\n#endif\n#ifdef CSV\n\t\t\tcase 'C':\n\t\t\t\tif (optarg) csv_char=optarg[0];\n\t\t\t\tbreak;\n#endif\n case 'h':\n cmdln_printhelp();\n break;\n#ifdef PROC_NET_DEV\n\t\t\tcase 'f':\n if (optarg && (strlen(optarg)0) { delay=atol(optarg); }\n break;\n#if EXTENDED_STATS \n case 'T':\n output_type=str2output_type(optarg);\n break;\n case 'A':\n if (optarg) avg_length=atoi(optarg)*1000;\n break;\n#endif \n case 'd':\n if (optarg) dynamic=atoi(optarg);\n break;\n case 'u':\n output_unit=str2output_unit(optarg);\n break;\n#if NETSTAT && ALLOW_NETSTATPATH\n case 'n':\n if (optarg && (strlen(optarg)=avg_length) deinit(1, \"avglength needs to be a least twice the value of timeout\\n\");\n#endif \n\t if ((output_unit==ERRORS_OUT && !net_input_method(input_method)) || \n\t\t\t (output_unit==PACKETS_OUT && input_method==LIBSTATDISK_IN)) \n\t\toutput_unit=BYTES_OUT;\n return;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fix https://github.com/vgropp/bwm-ng/issues/26'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: pcl_status_read(byte * data, uint max_data, pcl_state_t * pcs)\n{\n uint count = min(max_data,\n pcs->status.write_pos - pcs->status.read_pos);\n\n if (count)\n memcpy(data, pcs->status.buffer + pcs->status.read_pos, count);\n pcs->status.read_pos += count;\n if (pcs->status.read_pos == pcs->status.write_pos) {\n gs_free_object(pcs->memory, pcs->status.buffer, \"status buffer\");\n pcs->status.write_pos = pcs->status.read_pos = 0;\n }\n return count;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Bug 705156(1): Avoid double free of PCL error buffer'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static RList *symbols(RBinFile *bf) {\n\tRList *res = r_list_newf ((RListFree)r_bin_symbol_free);\n\tr_return_val_if_fail (res && bf->o && bf->o->bin_obj, res);\n\tRCoreSymCacheElement *element = bf->o->bin_obj;\n\tsize_t i;\n\tHtUU *hash = ht_uu_new0 ();\n\tif (!hash) {\n\t\treturn res;\n\t}\n\tbool found = false;\n\tfor (i = 0; i < element->hdr->n_lined_symbols; i++) {\n\t\tRCoreSymCacheElementSymbol *sym = (RCoreSymCacheElementSymbol *)&element->lined_symbols[i];\n\t\tif (!sym) {\n\t\t\tbreak;\n\t\t}\n\t\tht_uu_find (hash, sym->paddr, &found);\n\t\tif (found) {\n\t\t\tcontinue;\n\t\t}\n\t\tRBinSymbol *s = bin_symbol_from_symbol (element, sym);\n\t\tif (s) {\n\t\t\tr_list_append (res, s);\n\t\t\tht_uu_insert (hash, sym->paddr, 1);\n\t\t}\n\t}\n\tif (element->symbols) {\n\t\tfor (i = 0; i < element->hdr->n_symbols; i++) {\n\t\t\tRCoreSymCacheElementSymbol *sym = &element->symbols[i];\n\t\t\tht_uu_find (hash, sym->paddr, &found);\n\t\t\tif (found) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tRBinSymbol *s = bin_symbol_from_symbol (element, sym);\n\t\t\tif (s) {\n\t\t\t\tr_list_append (res, s);\n\t\t\t}\n\t\t}\n\t}\n\tht_uu_free (hash);\n\treturn res;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix oobread and null deref in symbols file parser ##crash\n\n* Reported by @cnitlrt\n* BountyID: af6c3e9e-b7df-4d80-b48f-77fdd17b4038/\n* Reproducer: symoob'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: \t__must_hold(&req->ctx->completion_lock)\n{\n\tbool posted = false;\n\n\tif (req->flags & REQ_F_ARM_LTIMEOUT) {\n\t\tstruct io_kiocb *link = req->link;\n\n\t\treq->flags &= ~REQ_F_ARM_LTIMEOUT;\n\t\tif (link && link->opcode == IORING_OP_LINK_TIMEOUT) {\n\t\t\tio_remove_next_linked(req);\n\t\t\t/* leave REQ_F_CQE_SKIP to io_fill_cqe_req */\n\t\t\tio_fill_cqe_req(link, -ECANCELED, 0);\n\t\t\tio_put_req_deferred(link);\n\t\t\tposted = true;\n\t\t}\n\t} else if (req->flags & REQ_F_LINK_TIMEOUT) {\n\t\tstruct io_ring_ctx *ctx = req->ctx;\n\n\t\tspin_lock_irq(&ctx->timeout_lock);\n\t\tposted = io_kill_linked_timeout(req);\n\t\tspin_unlock_irq(&ctx->timeout_lock);\n\t}\n\tif (unlikely((req->flags & REQ_F_FAIL) &&\n\t\t !(req->flags & REQ_F_HARDLINK))) {\n\t\tposted |= (req->link != NULL);\n\t\tio_fail_links(req);\n\t}\n\treturn posted;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'io_uring: fix race between timeout flush and removal\n\nio_flush_timeouts() assumes the timeout isn't in progress of triggering\nor being removed/canceled, so it unconditionally removes it from the\ntimeout list and attempts to cancel it.\n\nLeave it on the list and let the normal timeout cancelation take care\nof it.\n\nCc: stable@vger.kernel.org # 5.5+\nSigned-off-by: Jens Axboe '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: MOBI_RET mobi_reconstruct_infl(char *outstring, const MOBIIndx *infl, const MOBIIndexEntry *orth_entry) {\n const char *label = orth_entry->label;\n uint32_t *infl_groups = NULL;\n size_t infl_count = mobi_get_indxentry_tagarray(&infl_groups, orth_entry, INDX_TAGARR_ORTH_INFL);\n \n if (infl_count == 0 || !infl_groups) {\n return MOBI_SUCCESS;\n } \n const char *start_tag = \"\";\n const char *end_tag = \"\";\n const char *iform_tag = \"\";\n char name_attr[INDX_INFLBUF_SIZEMAX + 1];\n char infl_tag[INDX_INFLBUF_SIZEMAX + 1];\n strcpy(outstring, start_tag);\n size_t initlen = strlen(start_tag) + strlen(end_tag);\n size_t outlen = initlen;\n size_t label_length = strlen(label);\n if (label_length > INDX_INFLBUF_SIZEMAX) {\n debug_print(\"Entry label too long (%s)\\n\", label);\n return MOBI_DATA_CORRUPT;\n }\n if (infl->cncx_record == NULL) {\n debug_print(\"%s\\n\", \"Missing cncx record\");\n return MOBI_DATA_CORRUPT;\n }\n for (size_t i = 0; i < infl_count; i++) {\n size_t offset = infl_groups[i];\n if (offset >= infl->entries_count) {\n debug_print(\"%s\\n\", \"Invalid entry offset\");\n return MOBI_DATA_CORRUPT;\n }\n uint32_t *groups;\n size_t group_cnt = mobi_get_indxentry_tagarray(&groups, &infl->entries[offset], INDX_TAGARR_INFL_GROUPS);\n uint32_t *parts;\n size_t part_cnt = mobi_get_indxentry_tagarray(&parts, &infl->entries[offset], INDX_TAGARR_INFL_PARTS_V2);\n if (group_cnt != part_cnt) {\n return MOBI_DATA_CORRUPT;\n }\n for (size_t j = 0; j < part_cnt; j++) {\n name_attr[0] = '\\0';\n char *group_name = mobi_get_cncx_string(infl->cncx_record, groups[j]);\n if (group_name == NULL) {\n debug_print(\"%s\\n\", \"Memory allocation failed\");\n return MOBI_MALLOC_FAILED;\n }\n if (strlen(group_name)) {\n snprintf(name_attr, INDX_INFLBUF_SIZEMAX, \" name=\\\"%s\\\"\", group_name);\n }\n free(group_name);\n \n unsigned char decoded[INDX_INFLBUF_SIZEMAX + 1];\n memset(decoded, 0, INDX_INFLBUF_SIZEMAX + 1);\n unsigned char *rule = (unsigned char *) infl->entries[parts[j]].label;\n memcpy(decoded, label, label_length);\n int decoded_length = (int) label_length;\n MOBI_RET ret = mobi_decode_infl(decoded, &decoded_length, rule);\n if (ret != MOBI_SUCCESS) {\n return ret;\n }\n if (decoded_length == 0) {\n continue;\n }\n int n = snprintf(infl_tag, INDX_INFLBUF_SIZEMAX, iform_tag, name_attr, decoded);\n if (n > INDX_INFLBUF_SIZEMAX) {\n debug_print(\"Skipping truncated tag: %s\\n\", infl_tag);\n continue;\n }\n outlen += strlen(infl_tag);\n if (outlen > INDX_INFLTAG_SIZEMAX) {\n debug_print(\"Inflections text in %s too long (%zu)\\n\", label, outlen);\n return MOBI_ERROR;\n }\n strcat(outstring, infl_tag);\n }\n }\n if (outlen == initlen) {\n outstring[0] = '\\0';\n } else {\n strcat(outstring, end_tag);\n }\n return MOBI_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-125'], 'message': 'Fix array boundary check when parsing inflections which could result in buffer over-read with corrupt input'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: \nstatic SDL_Surface* Create_Surface_Shaded(int width, int height, SDL_Color fg, SDL_Color bg, Uint32 *color)\n{\n const int alignment = Get_Alignement() - 1;\n SDL_Surface *textbuf;\n Sint64 size;\n Uint8 bg_alpha = bg.a;\n\n /* Create a surface with memory:\n * - pitch is rounded to alignment\n * - adress is aligned\n */\n void *pixels, *ptr;\n /* Worse case at the end of line pulling 'alignment' extra blank pixels */\n Sint64 pitch = width + alignment;\n pitch += alignment;\n pitch &= ~alignment;\n size = height * pitch + sizeof (void *) + alignment;\n if (size < 0 || size > SDL_MAX_SINT32) {\n /* Overflow... */\n return NULL;\n }\n\n ptr = SDL_malloc((size_t)size);\n if (ptr == NULL) {\n return NULL;\n }\n\n /* address is aligned */\n pixels = (void *)(((uintptr_t)ptr + sizeof(void *) + alignment) & ~alignment);\n ((void **)pixels)[-1] = ptr;\n\n textbuf = SDL_CreateRGBSurfaceWithFormatFrom(pixels, width, height, 0, pitch, SDL_PIXELFORMAT_INDEX8);\n if (textbuf == NULL) {\n SDL_free(ptr);\n return NULL;\n }\n\n /* Let SDL handle the memory allocation */\n textbuf->flags &= ~SDL_PREALLOC;\n textbuf->flags |= SDL_SIMD_ALIGNED;\n\n /* Initialize with background to 0 */\n SDL_memset(pixels, 0, height * pitch);\n\n /* Underline/Strikethrough color style */\n *color = NUM_GRAYS - 1;\n\n /* Support alpha blending */\n if (fg.a != SDL_ALPHA_OPAQUE || bg.a != SDL_ALPHA_OPAQUE) {\n SDL_SetSurfaceBlendMode(textbuf, SDL_BLENDMODE_BLEND);\n\n /* Would disturb alpha palette */\n if (bg.a == SDL_ALPHA_OPAQUE) {\n bg.a = 0;\n }\n }\n\n /* Fill the palette with NUM_GRAYS levels of shading from bg to fg */\n {\n SDL_Palette *palette = textbuf->format->palette;\n int rdiff = fg.r - bg.r;\n int gdiff = fg.g - bg.g;\n int bdiff = fg.b - bg.b;\n int adiff = fg.a - bg.a;\n int sign_r = (rdiff >= 0) ? 1 : 255;\n int sign_g = (gdiff >= 0) ? 1 : 255;\n int sign_b = (bdiff >= 0) ? 1 : 255;\n int sign_a = (adiff >= 0) ? 1 : 255;\n int i;\n\n for (i = 0; i < NUM_GRAYS; ++i) {\n /* Compute color[i] = (i * color_diff / 255) */\n int tmp_r = i * rdiff;\n int tmp_g = i * gdiff;\n int tmp_b = i * bdiff;\n int tmp_a = i * adiff;\n palette->colors[i].r = (Uint8)(bg.r + DIVIDE_BY_255_SIGNED(tmp_r, sign_r));\n palette->colors[i].g = (Uint8)(bg.g + DIVIDE_BY_255_SIGNED(tmp_g, sign_g));\n palette->colors[i].b = (Uint8)(bg.b + DIVIDE_BY_255_SIGNED(tmp_b, sign_b));\n palette->colors[i].a = (Uint8)(bg.a + DIVIDE_BY_255_SIGNED(tmp_a, sign_a));\n }\n\n /* Make sure background has the correct alpha value */\n palette->colors[0].a = bg_alpha;\n }\n\n return textbuf; ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190', 'CWE-787'], 'message': 'More integer overflow (see bug #187)\nMake sure that 'width + alignment' doesn't overflow, otherwise\nit could create a SDL_Surface of 'width' but with wrong 'pitch''" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: xmlBufCreateSize(size_t size) {\n xmlBufPtr ret;\n\n ret = (xmlBufPtr) xmlMalloc(sizeof(xmlBuf));\n if (ret == NULL) {\n\txmlBufMemoryError(NULL, \"creating buffer\");\n return(NULL);\n }\n ret->use = 0;\n ret->error = 0;\n ret->buffer = NULL;\n ret->alloc = xmlBufferAllocScheme;\n ret->size = (size ? size+2 : 0); /* +1 for ending null */\n UPDATE_COMPAT(ret);\n if (ret->size){\n ret->content = (xmlChar *) xmlMallocAtomic(ret->size * sizeof(xmlChar));\n if (ret->content == NULL) {\n\t xmlBufMemoryError(ret, \"creating buffer\");\n xmlFree(ret);\n return(NULL);\n }\n ret->content[0] = 0;\n } else\n\tret->content = NULL;\n ret->contentIO = NULL;\n return(ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': '[CVE-2022-29824] Fix integer overflows in xmlBuf and xmlBuffer\n\nIn several places, the code handling string buffers didn't check for\ninteger overflow or used wrong types for buffer sizes. This could\nresult in out-of-bounds writes or other memory errors when working on\nlarge, multi-gigabyte buffers.\n\nThanks to Felix Wilhelm for the report.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadCINImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n#define MonoColorType 1\n#define RGBColorType 3\n\n char\n property[MagickPathExtent];\n\n CINInfo\n cin;\n\n Image\n *image;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n offset;\n\n QuantumInfo\n *quantum_info;\n\n QuantumType\n quantum_type;\n\n ssize_t\n i;\n\n Quantum\n *q;\n\n size_t\n length;\n\n ssize_t\n count,\n y;\n\n unsigned char\n magick[4],\n *pixels;\n\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n File information.\n */\n offset=0;\n count=ReadBlob(image,4,magick);\n offset+=count;\n if ((count != 4) ||\n ((LocaleNCompare((char *) magick,\"\\200\\052\\137\\327\",4) != 0)))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n memset(&cin,0,sizeof(cin));\n image->endian=(magick[0] == 0x80) && (magick[1] == 0x2a) &&\n (magick[2] == 0x5f) && (magick[3] == 0xd7) ? MSBEndian : LSBEndian;\n cin.file.image_offset=ReadBlobLong(image);\n offset+=4;\n cin.file.generic_length=ReadBlobLong(image);\n offset+=4;\n cin.file.industry_length=ReadBlobLong(image);\n offset+=4;\n cin.file.user_length=ReadBlobLong(image);\n offset+=4;\n cin.file.file_size=ReadBlobLong(image);\n offset+=4;\n offset+=ReadBlob(image,sizeof(cin.file.version),(unsigned char *)\n cin.file.version);\n (void) CopyMagickString(property,cin.file.version,sizeof(cin.file.version));\n (void) SetImageProperty(image,\"dpx:file.version\",property,exception);\n offset+=ReadBlob(image,sizeof(cin.file.filename),(unsigned char *)\n cin.file.filename);\n (void) CopyMagickString(property,cin.file.filename,sizeof(cin.file.filename));\n (void) SetImageProperty(image,\"dpx:file.filename\",property,exception);\n offset+=ReadBlob(image,sizeof(cin.file.create_date),(unsigned char *)\n cin.file.create_date);\n (void) CopyMagickString(property,cin.file.create_date,\n sizeof(cin.file.create_date));\n (void) SetImageProperty(image,\"dpx:file.create_date\",property,exception);\n offset+=ReadBlob(image,sizeof(cin.file.create_time),(unsigned char *)\n cin.file.create_time);\n (void) CopyMagickString(property,cin.file.create_time,\n sizeof(cin.file.create_time));\n (void) SetImageProperty(image,\"dpx:file.create_time\",property,exception);\n offset+=ReadBlob(image,sizeof(cin.file.reserve),(unsigned char *)\n cin.file.reserve);\n /*\n Image information.\n */\n cin.image.orientation=(unsigned char) ReadBlobByte(image);\n offset++;\n if (cin.image.orientation != (unsigned char) (~0))\n (void) FormatImageProperty(image,\"dpx:image.orientation\",\"%d\",\n cin.image.orientation);\n switch (cin.image.orientation)\n {\n default:\n case 0: image->orientation=TopLeftOrientation; break;\n case 1: image->orientation=TopRightOrientation; break;\n case 2: image->orientation=BottomLeftOrientation; break;\n case 3: image->orientation=BottomRightOrientation; break;\n case 4: image->orientation=LeftTopOrientation; break;\n case 5: image->orientation=RightTopOrientation; break;\n case 6: image->orientation=LeftBottomOrientation; break;\n case 7: image->orientation=RightBottomOrientation; break;\n }\n cin.image.number_channels=(unsigned char) ReadBlobByte(image);\n offset++;\n offset+=ReadBlob(image,sizeof(cin.image.reserve1),(unsigned char *)\n cin.image.reserve1);\n for (i=0; i < 8; i++)\n {\n cin.image.channel[i].designator[0]=(unsigned char) ReadBlobByte(image);\n offset++;\n cin.image.channel[i].designator[1]=(unsigned char) ReadBlobByte(image);\n offset++;\n cin.image.channel[i].bits_per_pixel=(unsigned char) ReadBlobByte(image);\n offset++;\n cin.image.channel[i].reserve=(unsigned char) ReadBlobByte(image);\n offset++;\n cin.image.channel[i].pixels_per_line=ReadBlobLong(image);\n offset+=4;\n cin.image.channel[i].lines_per_image=ReadBlobLong(image);\n offset+=4;\n cin.image.channel[i].min_data=ReadBlobFloat(image);\n offset+=4;\n cin.image.channel[i].min_quantity=ReadBlobFloat(image);\n offset+=4;\n cin.image.channel[i].max_data=ReadBlobFloat(image);\n offset+=4;\n cin.image.channel[i].max_quantity=ReadBlobFloat(image);\n offset+=4;\n }\n cin.image.white_point[0]=ReadBlobFloat(image);\n offset+=4;\n if (IsFloatDefined(cin.image.white_point[0]) != MagickFalse)\n image->chromaticity.white_point.x=cin.image.white_point[0];\n cin.image.white_point[1]=ReadBlobFloat(image);\n offset+=4;\n if (IsFloatDefined(cin.image.white_point[1]) != MagickFalse)\n image->chromaticity.white_point.y=cin.image.white_point[1];\n cin.image.red_primary_chromaticity[0]=ReadBlobFloat(image);\n offset+=4;\n if (IsFloatDefined(cin.image.red_primary_chromaticity[0]) != MagickFalse)\n image->chromaticity.red_primary.x=cin.image.red_primary_chromaticity[0];\n cin.image.red_primary_chromaticity[1]=ReadBlobFloat(image);\n offset+=4;\n if (IsFloatDefined(cin.image.red_primary_chromaticity[1]) != MagickFalse)\n image->chromaticity.red_primary.y=cin.image.red_primary_chromaticity[1];\n cin.image.green_primary_chromaticity[0]=ReadBlobFloat(image);\n offset+=4;\n if (IsFloatDefined(cin.image.green_primary_chromaticity[0]) != MagickFalse)\n image->chromaticity.red_primary.x=cin.image.green_primary_chromaticity[0];\n cin.image.green_primary_chromaticity[1]=ReadBlobFloat(image);\n offset+=4;\n if (IsFloatDefined(cin.image.green_primary_chromaticity[1]) != MagickFalse)\n image->chromaticity.green_primary.y=cin.image.green_primary_chromaticity[1];\n cin.image.blue_primary_chromaticity[0]=ReadBlobFloat(image);\n offset+=4;\n if (IsFloatDefined(cin.image.blue_primary_chromaticity[0]) != MagickFalse)\n image->chromaticity.blue_primary.x=cin.image.blue_primary_chromaticity[0];\n cin.image.blue_primary_chromaticity[1]=ReadBlobFloat(image);\n offset+=4;\n if (IsFloatDefined(cin.image.blue_primary_chromaticity[1]) != MagickFalse)\n image->chromaticity.blue_primary.y=cin.image.blue_primary_chromaticity[1];\n offset+=ReadBlob(image,sizeof(cin.image.label),(unsigned char *)\n cin.image.label);\n (void) CopyMagickString(property,cin.image.label,sizeof(cin.image.label));\n (void) SetImageProperty(image,\"dpx:image.label\",property,exception);\n offset+=ReadBlob(image,sizeof(cin.image.reserve),(unsigned char *)\n cin.image.reserve);\n /*\n Image data format information.\n */\n cin.data_format.interleave=(unsigned char) ReadBlobByte(image);\n offset++;\n cin.data_format.packing=(unsigned char) ReadBlobByte(image);\n offset++;\n cin.data_format.sign=(unsigned char) ReadBlobByte(image);\n offset++;\n cin.data_format.sense=(unsigned char) ReadBlobByte(image);\n offset++;\n cin.data_format.line_pad=ReadBlobLong(image);\n offset+=4;\n cin.data_format.channel_pad=ReadBlobLong(image);\n offset+=4;\n offset+=ReadBlob(image,sizeof(cin.data_format.reserve),(unsigned char *)\n cin.data_format.reserve);\n /*\n Image origination information.\n */\n cin.origination.x_offset=ReadBlobSignedLong(image);\n offset+=4;\n if ((size_t) cin.origination.x_offset != ~0UL)\n (void) FormatImageProperty(image,\"dpx:origination.x_offset\",\"%.20g\",\n (double) cin.origination.x_offset);\n cin.origination.y_offset=(ssize_t) ReadBlobLong(image);\n offset+=4;\n if ((size_t) cin.origination.y_offset != ~0UL)\n (void) FormatImageProperty(image,\"dpx:origination.y_offset\",\"%.20g\",\n (double) cin.origination.y_offset);\n offset+=ReadBlob(image,sizeof(cin.origination.filename),(unsigned char *)\n cin.origination.filename);\n (void) CopyMagickString(property,cin.origination.filename,\n sizeof(cin.origination.filename));\n (void) SetImageProperty(image,\"dpx:origination.filename\",property,exception);\n offset+=ReadBlob(image,sizeof(cin.origination.create_date),(unsigned char *)\n cin.origination.create_date);\n (void) CopyMagickString(property,cin.origination.create_date,\n sizeof(cin.origination.create_date));\n (void) SetImageProperty(image,\"dpx:origination.create_date\",property,\n exception);\n offset+=ReadBlob(image,sizeof(cin.origination.create_time),(unsigned char *)\n cin.origination.create_time);\n (void) CopyMagickString(property,cin.origination.create_time,\n sizeof(cin.origination.create_time));\n (void) SetImageProperty(image,\"dpx:origination.create_time\",property,\n exception);\n offset+=ReadBlob(image,sizeof(cin.origination.device),(unsigned char *)\n cin.origination.device);\n (void) CopyMagickString(property,cin.origination.device,\n sizeof(cin.origination.device));\n (void) SetImageProperty(image,\"dpx:origination.device\",property,exception);\n offset+=ReadBlob(image,sizeof(cin.origination.model),(unsigned char *)\n cin.origination.model);\n (void) CopyMagickString(property,cin.origination.model,\n sizeof(cin.origination.model));\n (void) SetImageProperty(image,\"dpx:origination.model\",property,exception);\n (void) memset(cin.origination.serial,0, \n sizeof(cin.origination.serial));\n offset+=ReadBlob(image,sizeof(cin.origination.serial),(unsigned char *)\n cin.origination.serial);\n (void) CopyMagickString(property,cin.origination.serial,\n sizeof(cin.origination.serial));\n (void) SetImageProperty(image,\"dpx:origination.serial\",property,exception);\n cin.origination.x_pitch=ReadBlobFloat(image);\n offset+=4;\n cin.origination.y_pitch=ReadBlobFloat(image);\n offset+=4;\n cin.origination.gamma=ReadBlobFloat(image);\n offset+=4;\n if (IsFloatDefined(cin.origination.gamma) != MagickFalse)\n image->gamma=cin.origination.gamma;\n offset+=ReadBlob(image,sizeof(cin.origination.reserve),(unsigned char *)\n cin.origination.reserve);\n if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0))\n {\n int\n c;\n\n /*\n Image film information.\n */\n cin.film.id=ReadBlobByte(image);\n offset++;\n c=cin.film.id;\n if (c != ~0)\n (void) FormatImageProperty(image,\"dpx:film.id\",\"%d\",cin.film.id);\n cin.film.type=ReadBlobByte(image);\n offset++;\n c=cin.film.type;\n if (c != ~0)\n (void) FormatImageProperty(image,\"dpx:film.type\",\"%d\",cin.film.type);\n cin.film.offset=ReadBlobByte(image);\n offset++;\n c=cin.film.offset;\n if (c != ~0)\n (void) FormatImageProperty(image,\"dpx:film.offset\",\"%d\",\n cin.film.offset);\n cin.film.reserve1=ReadBlobByte(image);\n offset++;\n cin.film.prefix=ReadBlobLong(image);\n offset+=4;\n if (cin.film.prefix != ~0UL)\n (void) FormatImageProperty(image,\"dpx:film.prefix\",\"%.20g\",(double)\n cin.film.prefix);\n cin.film.count=ReadBlobLong(image);\n offset+=4;\n offset+=ReadBlob(image,sizeof(cin.film.format),(unsigned char *)\n cin.film.format);\n (void) CopyMagickString(property,cin.film.format,sizeof(cin.film.format));\n (void) SetImageProperty(image,\"dpx:film.format\",property,exception);\n cin.film.frame_position=ReadBlobLong(image);\n offset+=4;\n if (cin.film.frame_position != ~0UL)\n (void) FormatImageProperty(image,\"dpx:film.frame_position\",\"%.20g\",\n (double) cin.film.frame_position);\n cin.film.frame_rate=ReadBlobFloat(image);\n offset+=4;\n if (IsFloatDefined(cin.film.frame_rate) != MagickFalse)\n (void) FormatImageProperty(image,\"dpx:film.frame_rate\",\"%g\",\n cin.film.frame_rate);\n offset+=ReadBlob(image,sizeof(cin.film.frame_id),(unsigned char *)\n cin.film.frame_id);\n (void) CopyMagickString(property,cin.film.frame_id,\n sizeof(cin.film.frame_id));\n (void) SetImageProperty(image,\"dpx:film.frame_id\",property,exception);\n offset+=ReadBlob(image,sizeof(cin.film.slate_info),(unsigned char *)\n cin.film.slate_info);\n (void) CopyMagickString(property,cin.film.slate_info,\n sizeof(cin.film.slate_info));\n (void) SetImageProperty(image,\"dpx:film.slate_info\",property,exception);\n offset+=ReadBlob(image,sizeof(cin.film.reserve),(unsigned char *)\n cin.film.reserve);\n }\n if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0))\n {\n StringInfo\n *profile;\n\n /*\n User defined data.\n */\n if (cin.file.user_length > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n profile=BlobToStringInfo((const unsigned char *) NULL,\n cin.file.user_length);\n if (profile == (StringInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n offset+=ReadBlob(image,GetStringInfoLength(profile),\n GetStringInfoDatum(profile));\n (void) SetImageProfile(image,\"dpx:user.data\",profile,exception);\n profile=DestroyStringInfo(profile);\n }\n image->depth=cin.image.channel[0].bits_per_pixel;\n image->columns=cin.image.channel[0].pixels_per_line;\n image->rows=cin.image.channel[0].lines_per_image;\n if (image_info->ping != MagickFalse)\n {\n (void) CloseBlob(image);\n return(image);\n }\n if (((MagickSizeType) image->columns*image->rows/8) > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n for ( ; offset < (MagickOffsetType) cin.file.image_offset; offset++)\n {\n int\n c;\n\n c=ReadBlobByte(image);\n if (c == EOF)\n break;\n }\n if (offset < (MagickOffsetType) cin.file.image_offset)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n (void) SetImageBackgroundColor(image,exception);\n /*\n Convert CIN raster image to pixel packets.\n */\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n SetQuantumQuantum(quantum_info,32);\n SetQuantumPack(quantum_info,MagickFalse);\n quantum_type=RGBQuantum;\n length=GetBytesPerRow(image->columns,3,image->depth,MagickTrue);\n if (cin.image.number_channels == 1)\n {\n quantum_type=GrayQuantum;\n length=GetBytesPerRow(image->columns,1,image->depth,MagickTrue);\n }\n status=SetQuantumPad(image,quantum_info,0);\n pixels=GetQuantumPixels(quantum_info);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n const void\n *stream;\n\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n stream=ReadBlobStream(image,length,pixels,&count);\n if ((size_t) count != length)\n break;\n (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n quantum_type,(unsigned char *) stream,exception);\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n SetQuantumImageType(image,quantum_type);\n quantum_info=DestroyQuantumInfo(quantum_info);\n if (EOFBlob(image) != MagickFalse)\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n SetImageColorspace(image,LogColorspace,exception);\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/4988'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int kgdb_cpu_enter(struct kgdb_state *ks, struct pt_regs *regs,\n\t\tint exception_state)\n{\n\tunsigned long flags;\n\tint sstep_tries = 100;\n\tint error;\n\tint cpu;\n\tint trace_on = 0;\n\tint online_cpus = num_online_cpus();\n\tu64 time_left;\n\n\tkgdb_info[ks->cpu].enter_kgdb++;\n\tkgdb_info[ks->cpu].exception_state |= exception_state;\n\n\tif (exception_state == DCPU_WANT_MASTER)\n\t\tatomic_inc(&masters_in_kgdb);\n\telse\n\t\tatomic_inc(&slaves_in_kgdb);\n\n\tif (arch_kgdb_ops.disable_hw_break)\n\t\tarch_kgdb_ops.disable_hw_break(regs);\n\nacquirelock:\n\trcu_read_lock();\n\t/*\n\t * Interrupts will be restored by the 'trap return' code, except when\n\t * single stepping.\n\t */\n\tlocal_irq_save(flags);\n\n\tcpu = ks->cpu;\n\tkgdb_info[cpu].debuggerinfo = regs;\n\tkgdb_info[cpu].task = current;\n\tkgdb_info[cpu].ret_state = 0;\n\tkgdb_info[cpu].irq_depth = hardirq_count() >> HARDIRQ_SHIFT;\n\n\t/* Make sure the above info reaches the primary CPU */\n\tsmp_mb();\n\n\tif (exception_level == 1) {\n\t\tif (raw_spin_trylock(&dbg_master_lock))\n\t\t\tatomic_xchg(&kgdb_active, cpu);\n\t\tgoto cpu_master_loop;\n\t}\n\n\t/*\n\t * CPU will loop if it is a slave or request to become a kgdb\n\t * master cpu and acquire the kgdb_active lock:\n\t */\n\twhile (1) {\ncpu_loop:\n\t\tif (kgdb_info[cpu].exception_state & DCPU_NEXT_MASTER) {\n\t\t\tkgdb_info[cpu].exception_state &= ~DCPU_NEXT_MASTER;\n\t\t\tgoto cpu_master_loop;\n\t\t} else if (kgdb_info[cpu].exception_state & DCPU_WANT_MASTER) {\n\t\t\tif (raw_spin_trylock(&dbg_master_lock)) {\n\t\t\t\tatomic_xchg(&kgdb_active, cpu);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} else if (kgdb_info[cpu].exception_state & DCPU_WANT_BT) {\n\t\t\tdump_stack();\n\t\t\tkgdb_info[cpu].exception_state &= ~DCPU_WANT_BT;\n\t\t} else if (kgdb_info[cpu].exception_state & DCPU_IS_SLAVE) {\n\t\t\tif (!raw_spin_is_locked(&dbg_slave_lock))\n\t\t\t\tgoto return_normal;\n\t\t} else {\nreturn_normal:\n\t\t\t/* Return to normal operation by executing any\n\t\t\t * hw breakpoint fixup.\n\t\t\t */\n\t\t\tif (arch_kgdb_ops.correct_hw_break)\n\t\t\t\tarch_kgdb_ops.correct_hw_break();\n\t\t\tif (trace_on)\n\t\t\t\ttracing_on();\n\t\t\tkgdb_info[cpu].debuggerinfo = NULL;\n\t\t\tkgdb_info[cpu].task = NULL;\n\t\t\tkgdb_info[cpu].exception_state &=\n\t\t\t\t~(DCPU_WANT_MASTER | DCPU_IS_SLAVE);\n\t\t\tkgdb_info[cpu].enter_kgdb--;\n\t\t\tsmp_mb__before_atomic();\n\t\t\tatomic_dec(&slaves_in_kgdb);\n\t\t\tdbg_touch_watchdogs();\n\t\t\tlocal_irq_restore(flags);\n\t\t\trcu_read_unlock();\n\t\t\treturn 0;\n\t\t}\n\t\tcpu_relax();\n\t}\n\n\t/*\n\t * For single stepping, try to only enter on the processor\n\t * that was single stepping. To guard against a deadlock, the\n\t * kernel will only try for the value of sstep_tries before\n\t * giving up and continuing on.\n\t */\n\tif (atomic_read(&kgdb_cpu_doing_single_step) != -1 &&\n\t (kgdb_info[cpu].task &&\n\t kgdb_info[cpu].task->pid != kgdb_sstep_pid) && --sstep_tries) {\n\t\tatomic_set(&kgdb_active, -1);\n\t\traw_spin_unlock(&dbg_master_lock);\n\t\tdbg_touch_watchdogs();\n\t\tlocal_irq_restore(flags);\n\t\trcu_read_unlock();\n\n\t\tgoto acquirelock;\n\t}\n\n\tif (!kgdb_io_ready(1)) {\n\t\tkgdb_info[cpu].ret_state = 1;\n\t\tgoto kgdb_restore; /* No I/O connection, resume the system */\n\t}\n\n\t/*\n\t * Don't enter if we have hit a removed breakpoint.\n\t */\n\tif (kgdb_skipexception(ks->ex_vector, ks->linux_regs))\n\t\tgoto kgdb_restore;\n\n\tatomic_inc(&ignore_console_lock_warning);\n\n\t/* Call the I/O driver's pre_exception routine */\n\tif (dbg_io_ops->pre_exception)\n\t\tdbg_io_ops->pre_exception();\n\n\t/*\n\t * Get the passive CPU lock which will hold all the non-primary\n\t * CPU in a spin state while the debugger is active\n\t */\n\tif (!kgdb_single_step)\n\t\traw_spin_lock(&dbg_slave_lock);\n\n#ifdef CONFIG_SMP\n\t/* If send_ready set, slaves are already waiting */\n\tif (ks->send_ready)\n\t\tatomic_set(ks->send_ready, 1);\n\n\t/* Signal the other CPUs to enter kgdb_wait() */\n\telse if ((!kgdb_single_step) && kgdb_do_roundup)\n\t\tkgdb_roundup_cpus();\n#endif\n\n\t/*\n\t * Wait for the other CPUs to be notified and be waiting for us:\n\t */\n\ttime_left = MSEC_PER_SEC;\n\twhile (kgdb_do_roundup && --time_left &&\n\t (atomic_read(&masters_in_kgdb) + atomic_read(&slaves_in_kgdb)) !=\n\t\t online_cpus)\n\t\tudelay(1000);\n\tif (!time_left)\n\t\tpr_crit(\"Timed out waiting for secondary CPUs.\\n\");\n\n\t/*\n\t * At this point the primary processor is completely\n\t * in the debugger and all secondary CPUs are quiescent\n\t */\n\tdbg_deactivate_sw_breakpoints();\n\tkgdb_single_step = 0;\n\tkgdb_contthread = current;\n\texception_level = 0;\n\ttrace_on = tracing_is_on();\n\tif (trace_on)\n\t\ttracing_off();\n\n\twhile (1) {\ncpu_master_loop:\n\t\tif (dbg_kdb_mode) {\n\t\t\tkgdb_connected = 1;\n\t\t\terror = kdb_stub(ks);\n\t\t\tif (error == -1)\n\t\t\t\tcontinue;\n\t\t\tkgdb_connected = 0;\n\t\t} else {\n\t\t\terror = gdb_serial_stub(ks);\n\t\t}\n\n\t\tif (error == DBG_PASS_EVENT) {\n\t\t\tdbg_kdb_mode = !dbg_kdb_mode;\n\t\t} else if (error == DBG_SWITCH_CPU_EVENT) {\n\t\t\tkgdb_info[dbg_switch_cpu].exception_state |=\n\t\t\t\tDCPU_NEXT_MASTER;\n\t\t\tgoto cpu_loop;\n\t\t} else {\n\t\t\tkgdb_info[cpu].ret_state = error;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tdbg_activate_sw_breakpoints();\n\n\t/* Call the I/O driver's post_exception routine */\n\tif (dbg_io_ops->post_exception)\n\t\tdbg_io_ops->post_exception();\n\n\tatomic_dec(&ignore_console_lock_warning);\n\n\tif (!kgdb_single_step) {\n\t\traw_spin_unlock(&dbg_slave_lock);\n\t\t/* Wait till all the CPUs have quit from the debugger. */\n\t\twhile (kgdb_do_roundup && atomic_read(&slaves_in_kgdb))\n\t\t\tcpu_relax();\n\t}\n\nkgdb_restore:\n\tif (atomic_read(&kgdb_cpu_doing_single_step) != -1) {\n\t\tint sstep_cpu = atomic_read(&kgdb_cpu_doing_single_step);\n\t\tif (kgdb_info[sstep_cpu].task)\n\t\t\tkgdb_sstep_pid = kgdb_info[sstep_cpu].task->pid;\n\t\telse\n\t\t\tkgdb_sstep_pid = 0;\n\t}\n\tif (arch_kgdb_ops.correct_hw_break)\n\t\tarch_kgdb_ops.correct_hw_break();\n\tif (trace_on)\n\t\ttracing_on();\n\n\tkgdb_info[cpu].debuggerinfo = NULL;\n\tkgdb_info[cpu].task = NULL;\n\tkgdb_info[cpu].exception_state &=\n\t\t~(DCPU_WANT_MASTER | DCPU_IS_SLAVE);\n\tkgdb_info[cpu].enter_kgdb--;\n\tsmp_mb__before_atomic();\n\tatomic_dec(&masters_in_kgdb);\n\t/* Free kgdb_active */\n\tatomic_set(&kgdb_active, -1);\n\traw_spin_unlock(&dbg_master_lock);\n\tdbg_touch_watchdogs();\n\tlocal_irq_restore(flags);\n\trcu_read_unlock();\n\n\treturn kgdb_info[cpu].ret_state;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'lockdown: also lock down previous kgdb use\n\nKGDB and KDB allow read and write access to kernel memory, and thus\nshould be restricted during lockdown. An attacker with access to a\nserial port (for example, via a hypervisor console, which some cloud\nvendors provide over the network) could trigger the debugger so it is\nimportant that the debugger respect the lockdown mode when/if it is\ntriggered.\n\nFix this by integrating lockdown into kdb's existing permissions\nmechanism. Unfortunately kgdb does not have any permissions mechanism\n(although it certainly could be added later) so, for now, kgdb is simply\nand brutally disabled by immediately exiting the gdb stub without taking\nany action.\n\nFor lockdowns established early in the boot (e.g. the normal case) then\nthis should be fine but on systems where kgdb has set breakpoints before\nthe lockdown is enacted than \"bad things\" will happen.\n\nCVE: CVE-2022-21499\nCo-developed-by: Stephen Brennan \nSigned-off-by: Stephen Brennan \nReviewed-by: Douglas Anderson \nSigned-off-by: Daniel Thompson \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int nfc_disable_se(struct nfc_dev *dev, u32 se_idx)\n{\n\tstruct nfc_se *se;\n\tint rc;\n\n\tpr_debug(\"%s se index %d\\n\", dev_name(&dev->dev), se_idx);\n\n\tdevice_lock(&dev->dev);\n\n\tif (!device_is_registered(&dev->dev)) {\n\t\trc = -ENODEV;\n\t\tgoto error;\n\t}\n\n\tif (!dev->dev_up) {\n\t\trc = -ENODEV;\n\t\tgoto error;\n\t}\n\n\tif (!dev->ops->enable_se || !dev->ops->disable_se) {\n\t\trc = -EOPNOTSUPP;\n\t\tgoto error;\n\t}\n\n\tse = nfc_find_se(dev, se_idx);\n\tif (!se) {\n\t\trc = -EINVAL;\n\t\tgoto error;\n\t}\n\n\tif (se->state == NFC_SE_DISABLED) {\n\t\trc = -EALREADY;\n\t\tgoto error;\n\t}\n\n\trc = dev->ops->disable_se(dev, se_idx);\n\tif (rc >= 0)\n\t\tse->state = NFC_SE_DISABLED;\n\nerror:\n\tdevice_unlock(&dev->dev);\n\treturn rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'nfc: replace improper check device_is_registered() in netlink related functions\n\nThe device_is_registered() in nfc core is used to check whether\nnfc device is registered in netlink related functions such as\nnfc_fw_download(), nfc_dev_up() and so on. Although device_is_registered()\nis protected by device_lock, there is still a race condition between\ndevice_del() and device_is_registered(). The root cause is that\nkobject_del() in device_del() is not protected by device_lock.\n\n (cleanup task) | (netlink task)\n |\nnfc_unregister_device | nfc_fw_download\n device_del | device_lock\n ... | if (!device_is_registered)//(1)\n kobject_del//(2) | ...\n ... | device_unlock\n\nThe device_is_registered() returns the value of state_in_sysfs and\nthe state_in_sysfs is set to zero in kobject_del(). If we pass check in\nposition (1), then set zero in position (2). As a result, the check\nin position (1) is useless.\n\nThis patch uses bool variable instead of device_is_registered() to judge\nwhether the nfc device is registered, which is well synchronized.\n\nFixes: 3e256b8f8dfa (\"NFC: add nfc subsystem core\")\nSigned-off-by: Duoming Zhou \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static bool init_ehdr(ELFOBJ *bin) {\n\tut8 e_ident[EI_NIDENT];\n\tut8 ehdr[sizeof (Elf_(Ehdr))] = {0};\n\tint i, len;\n\tif (r_buf_read_at (bin->b, 0, e_ident, EI_NIDENT) == -1) {\n\t\tR_LOG_ERROR (\"read (magic)\");\n\t\treturn false;\n\t}\n\tsdb_set (bin->kv, \"elf_type.cparse\", \"enum elf_type { ET_NONE=0, ET_REL=1,\"\n\t\t\t\" ET_EXEC=2, ET_DYN=3, ET_CORE=4, ET_LOOS=0xfe00, ET_HIOS=0xfeff,\"\n\t\t\t\" ET_LOPROC=0xff00, ET_HIPROC=0xffff };\", 0);\n\tsdb_set (bin->kv, \"elf_machine.cparse\", \"enum elf_machine {EM_NONE=0, EM_M32=1,\"\n\t\t\t\" EM_SPARC=2, EM_386=3, EM_68K=4, EM_88K=5, EM_IAMCU=6, EM_860=7, EM_MIPS=8,\"\n\t\t\t\" EM_S370=9, EM_MIPS_RS3_LE=10, EM_RS6000=11, EM_PARISC=15, EM_nCUBE=16,\"\n\t\t\t\" EM_VPP500=17, EM_SPARC32PLUS=18, EM_960=19, EM_PPC=20, EM_PPC64=21, EM_S390=22,\"\n\t\t\t\" EM_SPU=23, EM_V800=36, EM_FR20=37, EM_RH32=38, EM_RCE=39, EM_ARM=40,\"\n\t\t\t\" EM_ALPHA=41, EM_SH=42, EM_SPARCV9=43, EM_TRICORE=44, EM_ARC=45, EM_H8_300=46,\"\n\t\t\t\" EM_H8_300H=47, EM_H8S=48, EM_H8_500=49, EM_IA_64=50, EM_MIPS_X=51,\"\n\t\t\t\" EM_COLDFIRE=52, EM_68HC12=53, EM_MMA=54, EM_PCP=55, EM_NCPU=56, EM_NDR1=57,\"\n\t\t\t\" EM_STARCORE=58, EM_ME16=59, EM_ST100=60, EM_TINYJ=61, EM_X86_64=62, EM_PDSP=63,\"\n\t\t\t\" EM_PDP10=64, EM_PDP11=65, EM_FX66=66, EM_ST9PLUS=67, EM_ST7=68, EM_68HC16=69,\"\n\t\t\t\" EM_68HC11=70, EM_68HC08=71, EM_68HC05=72, EM_SVX=73, EM_ST19=74, EM_VAX=75,\"\n\t\t\t\" EM_CRIS=76, EM_JAVELIN=77, EM_FIREPATH=78, EM_ZSP=79, EM_MMIX=80, EM_HUANY=81,\"\n\t\t\t\" EM_PRISM=82, EM_AVR=83, EM_FR30=84, EM_D10V=85, EM_D30V=86, EM_V850=87,\"\n\t\t\t\" EM_M32R=88, EM_MN10300=89, EM_MN10200=90, EM_PJ=91, EM_OPENRISC=92,\"\n\t\t\t\" EM_ARC_COMPACT=93, EM_XTENSA=94, EM_VIDEOCORE=95, EM_TMM_GPP=96, EM_NS32K=97,\"\n\t\t\t\" EM_TPC=98, EM_SNP1K=99, EM_ST200=100, EM_IP2K=101, EM_MAX=102, EM_CR=103,\"\n\t\t\t\" EM_F2MC16=104, EM_MSP430=105, EM_BLACKFIN=106, EM_SE_C33=107, EM_SEP=108,\"\n\t\t\t\" EM_ARCA=109, EM_UNICORE=110, EM_EXCESS=111, EM_DXP=112, EM_ALTERA_NIOS2=113,\"\n\t\t\t\" EM_CRX=114, EM_XGATE=115, EM_C166=116, EM_M16C=117, EM_DSPIC30F=118, EM_CE=119,\"\n\t\t\t\" EM_M32C=120, EM_TSK3000=131, EM_RS08=132, EM_SHARC=133, EM_ECOG2=134,\"\n\t\t\t\" EM_SCORE7=135, EM_DSP24=136, EM_VIDEOCORE3=137, EM_LATTICEMICO32=138,\"\n\t\t\t\" EM_SE_C17=139, EM_TI_C6000=140, EM_TI_C2000=141, EM_TI_C5500=142,\"\n\t\t\t\" EM_TI_ARP32=143, EM_TI_PRU=144,\"\n\t\t\t\" EM_MMDSP_PLUS=160, EM_CYPRESS_M8C=161, EM_R32C=162, EM_TRIMEDIA=163,\"\n\t\t\t\" EM_QDSP6=164, EM_8051=165, EM_STXP7X=166, EM_NDS32=167,\"\n\t\t\t\" EM_ECOG1X=168, EM_MAXQ30=169, EM_XIMO16=170, EM_MANIK=171, EM_CRAYNV2=172,\"\n\t\t\t\" EM_RX=173, EM_METAG=174, EM_MCST_ELBRUS=175, EM_ECOG16=176, EM_CR16=177,\"\n\t\t\t\" EM_ETPU=178, EM_SLE9X=179, EM_L10M=180, EM_K10M=181, EM_AARCH64=183,\"\n\t\t\t\" EM_AVR32=185, EM_STM8=186, EM_TILE64=187, EM_TILEPRO=188, EM_CUDA=190,\"\n\t\t\t\" EM_TILEGX=191, EM_CLOUDSHIELD=192, EM_COREA_1ST=193, EM_COREA_2ND=194,\"\n\t\t\t\" EM_ARC_COMPACT2=195, EM_OPEN8=196, EM_RL78=197, EM_VIDEOCORE5=198,\"\n\t\t\t\" EM_78KOR=199, EM_56800EX=200, EM_BA1=201, EM_BA2=202, EM_XCORE=203,\"\n\t\t\t\" EM_MCHP_PIC=204, EM_INTEL205=205, EM_INTEL206=206, EM_INTEL207=207,\"\n\t\t\t\" EM_INTEL208=208, EM_INTEL209=209, EM_KM32=210, EM_KMX32=211, EM_KMX16=212,\"\n\t\t\t\" EM_KMX8=213, EM_KVARC=214, EM_CDP=215, EM_COGE=216, EM_COOL=217, EM_NORC=218,\"\n\t\t\t\" EM_CSR_KALIMBA=219, EM_AMDGPU=224, EM_RISCV=243, EM_LANAI=244, EM_BPF=247,\"\n\t\t\t\" EM_CSKY=252, EM_KVX=256, EM_LOONGARCH=258}\", 0);\n\tsdb_set (bin->kv, \"elf_class.cparse\", \"enum elf_class {ELFCLASSNONE=0, ELFCLASS32=1, ELFCLASS64=2};\", 0);\n\tsdb_set (bin->kv, \"elf_data.cparse\", \"enum elf_data {ELFDATANONE=0, ELFDATA2LSB=1, ELFDATA2MSB=2};\", 0);\n\tsdb_set (bin->kv, \"elf_hdr_version.cparse\", \"enum elf_hdr_version {EV_NONE=0, EV_CURRENT=1};\", 0);\n\tsdb_set (bin->kv, \"elf_obj_version.cparse\", \"enum elf_obj_version {EV_NONE=0, EV_CURRENT=1};\", 0);\n\tsdb_num_set (bin->kv, \"elf_header.offset\", 0, 0);\n\tsdb_num_set (bin->kv, \"elf_header.size\", sizeof (Elf_(Ehdr)), 0);\n\tsdb_set (bin->kv, \"elf_ident.format\", \"[4]z[1]E[1]E[1]E.::\"\n\t\t\t\" magic (elf_class)class (elf_data)data (elf_hdr_version)version\", 0);\n#if R_BIN_ELF64\n\tsdb_set (bin->kv, \"elf_header.format\", \"?[2]E[2]E[4]EqqqxN2N2N2N2N2N2\"\n\t\t\t\" (elf_ident)ident (elf_type)type (elf_machine)machine (elf_obj_version)version\"\n\t\t\t\" entry phoff shoff flags ehsize phentsize phnum shentsize shnum shstrndx\", 0);\n#else\n\tsdb_set (bin->kv, \"elf_header.format\", \"?[2]E[2]E[4]ExxxxN2N2N2N2N2N2\"\n\t\t\t\" (elf_ident)ident (elf_type)type (elf_machine)machine (elf_obj_version)version\"\n\t\t\t\" entry phoff shoff flags ehsize phentsize phnum shentsize shnum shstrndx\", 0);\n#endif\n\tbin->endian = (e_ident[EI_DATA] == ELFDATA2MSB)? 1: 0;\n\tmemset (&bin->ehdr, 0, sizeof (Elf_(Ehdr)));\n\tlen = r_buf_read_at (bin->b, 0, ehdr, sizeof (ehdr));\n\tif (len < 32) { // tinyelf != sizeof (Elf_(Ehdr))) {\n\t\tR_LOG_ERROR (\"read (ehdr)\");\n\t\treturn false;\n\t}\n\t// XXX no need to check twice\n\tmemcpy (&bin->ehdr.e_ident, ehdr, 16);\n\tif (!__is_valid_ident (bin)) {\n\t\treturn false;\n\t}\n\ti = 16;\n\t// TODO: use r_read or r_buf_read_ apis instead\n\tbin->ehdr.e_type = READ16 (ehdr, i);\n\tbin->ehdr.e_machine = READ16 (ehdr, i);\n\tbin->ehdr.e_version = READ32 (ehdr, i);\n#if R_BIN_ELF64\n\tbin->ehdr.e_entry = READ64 (ehdr, i);\n\tbin->ehdr.e_phoff = READ64 (ehdr, i);\n\tbin->ehdr.e_shoff = READ64 (ehdr, i);\n#else\n\tbin->ehdr.e_entry = READ32 (ehdr, i);\n\tbin->ehdr.e_phoff = READ32 (ehdr, i);\n\tbin->ehdr.e_shoff = READ32 (ehdr, i);\n#endif\n\tbin->ehdr.e_flags = READ32 (ehdr, i);\n\tbin->ehdr.e_ehsize = READ16 (ehdr, i);\n\tbin->ehdr.e_phentsize = READ16 (ehdr, i);\n\tbin->ehdr.e_phnum = READ16 (ehdr, i);\n\tbin->ehdr.e_shentsize = READ16 (ehdr, i);\n\tbin->ehdr.e_shnum = READ16 (ehdr, i);\n\tbin->ehdr.e_shstrndx = READ16 (ehdr, i);\n\treturn true;\n\t// [Outdated] Usage example:\n\t// > td `k bin/cur/info/elf_type.cparse`; td `k bin/cur/info/elf_machine.cparse`\n\t// > pf `k bin/cur/info/elf_header.format` @ `k bin/cur/info/elf_header.offset`\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix 4 byte oobread in msp430 disassembler ##crash\n\n* Only crashes with asan builds\n* Add missing =SN register\n* Reported by cnitlrt via huntrdev\n* BountyID: 1c22055b-b015-47a8-a57b-4982978751d0'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: xcf_load_old_paths (XcfInfo *info,\n GimpImage *image)\n{\n guint32 num_paths;\n guint32 last_selected_row;\n GimpVectors *active_vectors;\n\n xcf_read_int32 (info, &last_selected_row, 1);\n xcf_read_int32 (info, &num_paths, 1);\n\n while (num_paths-- > 0)\n xcf_load_old_path (info, image);\n\n active_vectors =\n GIMP_VECTORS (gimp_container_get_child_by_index (gimp_image_get_vectors (image),\n last_selected_row));\n\n if (active_vectors)\n gimp_image_set_active_vectors (image, active_vectors);\n\n return TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'app: fix #8120 GIMP 2.10.30 crashed when allocate large memory\n\nGIMP could crash if the information regarding old path properties read\nfrom XCF was incorrect. It did not check if xcf_old_path succeeded and\nkept trying to load more paths even if the last one failed to load.\n\nInstead we now stop loading paths as soon as that function fails.\nIn case we have a failure here we also try to skip to the next property\nbased on the size of the path property, in hopes that the only problem\nwas this property.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static bool vtable_is_addr_vtable_start_msvc(RVTableContext *context, ut64 curAddress) {\n\tRAnalRef *xref;\n\tRListIter *xrefIter;\n\n\tif (!curAddress || curAddress == UT64_MAX) {\n\t\treturn false;\n\t}\n\tif (curAddress && !vtable_is_value_in_text_section (context, curAddress, NULL)) {\n\t\treturn false;\n\t}\n\t// total xref's to curAddress\n\tRList *xrefs = r_anal_xrefs_get (context->anal, curAddress);\n\tif (r_list_empty (xrefs)) {\n\t\tr_list_free (xrefs);\n\t\treturn false;\n\t}\n\tr_list_foreach (xrefs, xrefIter, xref) {\n\t\t// section in which currenct xref lies\n\t\tif (vtable_addr_in_text_section (context, xref->addr)) {\n\t\t\tut8 buf[VTABLE_BUFF_SIZE];\n\t\t\tcontext->anal->iob.read_at (context->anal->iob.io, xref->addr, buf, sizeof(buf));\n\n\t\t\tRAnalOp analop = {0};\n\t\t\tr_anal_op (context->anal, &analop, xref->addr, buf, sizeof(buf), R_ANAL_OP_MASK_BASIC);\n\n\t\t\tif (analop.type == R_ANAL_OP_TYPE_MOV\n\t\t\t\t|| analop.type == R_ANAL_OP_TYPE_LEA) {\n\t\t\t\tr_list_free (xrefs);\n\t\t\t\tr_anal_op_fini (&analop);\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tr_anal_op_fini (&analop);\n\t\t}\n\t}\n\tr_list_free (xrefs);\n\treturn false;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284', 'CWE-824'], 'message': 'Fix crash in vtable analysis on UB ##crash\n\n* Reported by @greatergoodest via huntrdev\n* BountyID 0730a95e-c485-4ff2-9a5d-bb3abfda0b17\n* Reproducer: minified_crash'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: normal_cmd(\n oparg_T\t*oap,\n int\t\ttoplevel UNUSED)\t// TRUE when called from main()\n{\n cmdarg_T\tca;\t\t\t// command arguments\n int\t\tc;\n int\t\tctrl_w = FALSE;\t\t// got CTRL-W command\n int\t\told_col = curwin->w_curswant;\n int\t\tneed_flushbuf = FALSE;\t// need to call out_flush()\n pos_T\told_pos;\t\t// cursor position before command\n int\t\tmapped_len;\n static int\told_mapped_len = 0;\n int\t\tidx;\n int\t\tset_prevcount = FALSE;\n int\t\tsave_did_cursorhold = did_cursorhold;\n\n CLEAR_FIELD(ca);\t// also resets ca.retval\n ca.oap = oap;\n\n // Use a count remembered from before entering an operator. After typing\n // \"3d\" we return from normal_cmd() and come back here, the \"3\" is\n // remembered in \"opcount\".\n ca.opcount = opcount;\n\n // If there is an operator pending, then the command we take this time\n // will terminate it. Finish_op tells us to finish the operation before\n // returning this time (unless the operation was cancelled).\n#ifdef CURSOR_SHAPE\n c = finish_op;\n#endif\n finish_op = (oap->op_type != OP_NOP);\n#ifdef CURSOR_SHAPE\n if (finish_op != c)\n {\n\tui_cursor_shape();\t\t// may show different cursor shape\n# ifdef FEAT_MOUSESHAPE\n\tupdate_mouseshape(-1);\n# endif\n }\n#endif\n may_trigger_modechanged();\n\n // When not finishing an operator and no register name typed, reset the\n // count.\n if (!finish_op && !oap->regname)\n {\n\tca.opcount = 0;\n#ifdef FEAT_EVAL\n\tset_prevcount = TRUE;\n#endif\n }\n\n // Restore counts from before receiving K_CURSORHOLD. This means after\n // typing \"3\", handling K_CURSORHOLD and then typing \"2\" we get \"32\", not\n // \"3 * 2\".\n if (oap->prev_opcount > 0 || oap->prev_count0 > 0)\n {\n\tca.opcount = oap->prev_opcount;\n\tca.count0 = oap->prev_count0;\n\toap->prev_opcount = 0;\n\toap->prev_count0 = 0;\n }\n\n mapped_len = typebuf_maplen();\n\n State = MODE_NORMAL_BUSY;\n#ifdef USE_ON_FLY_SCROLL\n dont_scroll = FALSE;\t// allow scrolling here\n#endif\n\n#ifdef FEAT_EVAL\n // Set v:count here, when called from main() and not a stuffed\n // command, so that v:count can be used in an expression mapping\n // when there is no count. Do set it for redo.\n if (toplevel && readbuf1_empty())\n\tset_vcount_ca(&ca, &set_prevcount);\n#endif\n\n /*\n * Get the command character from the user.\n */\n c = safe_vgetc();\n LANGMAP_ADJUST(c, get_real_state() != MODE_SELECT);\n\n // If a mapping was started in Visual or Select mode, remember the length\n // of the mapping. This is used below to not return to Insert mode for as\n // long as the mapping is being executed.\n if (restart_edit == 0)\n\told_mapped_len = 0;\n else if (old_mapped_len\n\t\t|| (VIsual_active && mapped_len == 0 && typebuf_maplen() > 0))\n\told_mapped_len = typebuf_maplen();\n\n if (c == NUL)\n\tc = K_ZERO;\n\n // In Select mode, typed text replaces the selection.\n if (VIsual_active\n\t && VIsual_select\n\t && (vim_isprintc(c) || c == NL || c == CAR || c == K_KENTER))\n {\n\tint len;\n\n\t// Fake a \"c\"hange command. When \"restart_edit\" is set (e.g., because\n\t// 'insertmode' is set) fake a \"d\"elete command, Insert mode will\n\t// restart automatically.\n\t// Insert the typed character in the typeahead buffer, so that it can\n\t// be mapped in Insert mode. Required for \":lmap\" to work.\n\tlen = ins_char_typebuf(vgetc_char, vgetc_mod_mask);\n\n\t// When recording and gotchars() was called the character will be\n\t// recorded again, remove the previous recording.\n\tif (KeyTyped)\n\t ungetchars(len);\n\n\tif (restart_edit != 0)\n\t c = 'd';\n\telse\n\t c = 'c';\n\tmsg_nowait = TRUE;\t// don't delay going to insert mode\n\told_mapped_len = 0;\t// do go to Insert mode\n }\n\n // If the window was made so small that nothing shows, make it at least one\n // line and one column when typing a command.\n if (KeyTyped && !KeyStuffed)\n\twin_ensure_size();\n\n#ifdef FEAT_CMDL_INFO\n need_flushbuf = add_to_showcmd(c);\n#endif\n\n // Get the command count\n c = normal_cmd_get_count(&ca, c, toplevel, set_prevcount, &ctrl_w,\n\t\t\t\t\t\t\t&need_flushbuf);\n\n // Find the command character in the table of commands.\n // For CTRL-W we already got nchar when looking for a count.\n if (ctrl_w)\n {\n\tca.nchar = c;\n\tca.cmdchar = Ctrl_W;\n }\n else\n\tca.cmdchar = c;\n idx = find_command(ca.cmdchar);\n if (idx < 0)\n {\n\t// Not a known command: beep.\n\tclearopbeep(oap);\n\tgoto normal_end;\n }\n\n if (text_locked() && (nv_cmds[idx].cmd_flags & NV_NCW))\n {\n\t// This command is not allowed while editing a cmdline: beep.\n\tclearopbeep(oap);\n\ttext_locked_msg();\n\tgoto normal_end;\n }\n if ((nv_cmds[idx].cmd_flags & NV_NCW) && curbuf_locked())\n\tgoto normal_end;\n\n // In Visual/Select mode, a few keys are handled in a special way.\n if (VIsual_active)\n {\n\t// when 'keymodel' contains \"stopsel\" may stop Select/Visual mode\n\tif (km_stopsel\n\t\t&& (nv_cmds[idx].cmd_flags & NV_STS)\n\t\t&& !(mod_mask & MOD_MASK_SHIFT))\n\t{\n\t end_visual_mode();\n\t redraw_curbuf_later(INVERTED);\n\t}\n\n\t// Keys that work different when 'keymodel' contains \"startsel\"\n\tif (km_startsel)\n\t{\n\t if (nv_cmds[idx].cmd_flags & NV_SS)\n\t {\n\t\tunshift_special(&ca);\n\t\tidx = find_command(ca.cmdchar);\n\t\tif (idx < 0)\n\t\t{\n\t\t // Just in case\n\t\t clearopbeep(oap);\n\t\t goto normal_end;\n\t\t}\n\t }\n\t else if ((nv_cmds[idx].cmd_flags & NV_SSS)\n\t\t\t\t\t && (mod_mask & MOD_MASK_SHIFT))\n\t\tmod_mask &= ~MOD_MASK_SHIFT;\n\t}\n }\n\n#ifdef FEAT_RIGHTLEFT\n if (curwin->w_p_rl && KeyTyped && !KeyStuffed\n\t\t\t\t\t && (nv_cmds[idx].cmd_flags & NV_RL))\n {\n\t// Invert horizontal movements and operations. Only when typed by the\n\t// user directly, not when the result of a mapping or \"x\" translated\n\t// to \"dl\".\n\tswitch (ca.cmdchar)\n\t{\n\t case 'l':\t ca.cmdchar = 'h'; break;\n\t case K_RIGHT: ca.cmdchar = K_LEFT; break;\n\t case K_S_RIGHT: ca.cmdchar = K_S_LEFT; break;\n\t case K_C_RIGHT: ca.cmdchar = K_C_LEFT; break;\n\t case 'h':\t ca.cmdchar = 'l'; break;\n\t case K_LEFT: ca.cmdchar = K_RIGHT; break;\n\t case K_S_LEFT: ca.cmdchar = K_S_RIGHT; break;\n\t case K_C_LEFT: ca.cmdchar = K_C_RIGHT; break;\n\t case '>':\t ca.cmdchar = '<'; break;\n\t case '<':\t ca.cmdchar = '>'; break;\n\t}\n\tidx = find_command(ca.cmdchar);\n }\n#endif\n\n // Get additional characters if we need them.\n if (normal_cmd_needs_more_chars(&ca, nv_cmds[idx].cmd_flags))\n\tidx = normal_cmd_get_more_chars(idx, &ca, &need_flushbuf);\n\n#ifdef FEAT_CMDL_INFO\n // Flush the showcmd characters onto the screen so we can see them while\n // the command is being executed. Only do this when the shown command was\n // actually displayed, otherwise this will slow down a lot when executing\n // mappings.\n if (need_flushbuf)\n\tout_flush();\n#endif\n if (ca.cmdchar != K_IGNORE)\n {\n\tif (ex_normal_busy)\n\t did_cursorhold = save_did_cursorhold;\n\telse\n\t did_cursorhold = FALSE;\n }\n\n State = MODE_NORMAL;\n\n if (ca.nchar == ESC)\n {\n\tclearop(oap);\n\tif (restart_edit == 0 && goto_im())\n\t restart_edit = 'a';\n\tgoto normal_end;\n }\n\n if (ca.cmdchar != K_IGNORE)\n {\n\tmsg_didout = FALSE; // don't scroll screen up for normal command\n\tmsg_col = 0;\n }\n\n old_pos = curwin->w_cursor;\t\t// remember where cursor was\n\n // When 'keymodel' contains \"startsel\" some keys start Select/Visual\n // mode.\n if (!VIsual_active && km_startsel)\n {\n\tif (nv_cmds[idx].cmd_flags & NV_SS)\n\t{\n\t start_selection();\n\t unshift_special(&ca);\n\t idx = find_command(ca.cmdchar);\n\t}\n\telse if ((nv_cmds[idx].cmd_flags & NV_SSS)\n\t\t\t\t\t && (mod_mask & MOD_MASK_SHIFT))\n\t{\n\t start_selection();\n\t mod_mask &= ~MOD_MASK_SHIFT;\n\t}\n }\n\n // Execute the command!\n // Call the command function found in the commands table.\n ca.arg = nv_cmds[idx].cmd_arg;\n (nv_cmds[idx].cmd_func)(&ca);\n\n // If we didn't start or finish an operator, reset oap->regname, unless we\n // need it later.\n if (!finish_op\n\t && !oap->op_type\n\t && (idx < 0 || !(nv_cmds[idx].cmd_flags & NV_KEEPREG)))\n {\n\tclearop(oap);\n#ifdef FEAT_EVAL\n\treset_reg_var();\n#endif\n }\n\n // Get the length of mapped chars again after typing a count, second\n // character or \"z333\".\n if (old_mapped_len > 0)\n\told_mapped_len = typebuf_maplen();\n\n // If an operation is pending, handle it. But not for K_IGNORE or\n // K_MOUSEMOVE.\n if (ca.cmdchar != K_IGNORE && ca.cmdchar != K_MOUSEMOVE)\n\tdo_pending_operator(&ca, old_col, FALSE);\n\n // Wait for a moment when a message is displayed that will be overwritten\n // by the mode message.\n if (normal_cmd_need_to_wait_for_msg(&ca, &old_pos))\n\tnormal_cmd_wait_for_msg();\n\n // Finish up after executing a Normal mode command.\nnormal_end:\n\n msg_nowait = FALSE;\n\n#ifdef FEAT_EVAL\n if (finish_op)\n\treset_reg_var();\n#endif\n\n // Reset finish_op, in case it was set\n#ifdef CURSOR_SHAPE\n c = finish_op;\n#endif\n finish_op = FALSE;\n may_trigger_modechanged();\n#ifdef CURSOR_SHAPE\n // Redraw the cursor with another shape, if we were in Operator-pending\n // mode or did a replace command.\n if (c || ca.cmdchar == 'r')\n {\n\tui_cursor_shape();\t\t// may show different cursor shape\n# ifdef FEAT_MOUSESHAPE\n\tupdate_mouseshape(-1);\n# endif\n }\n#endif\n\n#ifdef FEAT_CMDL_INFO\n if (oap->op_type == OP_NOP && oap->regname == 0\n\t && ca.cmdchar != K_CURSORHOLD)\n\tclear_showcmd();\n#endif\n\n checkpcmark();\t\t// check if we moved since setting pcmark\n vim_free(ca.searchbuf);\n\n if (has_mbyte)\n\tmb_adjust_cursor();\n\n if (curwin->w_p_scb && toplevel)\n {\n\tvalidate_cursor();\t// may need to update w_leftcol\n\tdo_check_scrollbind(TRUE);\n }\n\n if (curwin->w_p_crb && toplevel)\n {\n\tvalidate_cursor();\t// may need to update w_leftcol\n\tdo_check_cursorbind();\n }\n\n#ifdef FEAT_TERMINAL\n // don't go to Insert mode if a terminal has a running job\n if (term_job_running(curbuf->b_term))\n\trestart_edit = 0;\n#endif\n\n // May restart edit(), if we got here with CTRL-O in Insert mode (but not\n // if still inside a mapping that started in Visual mode).\n // May switch from Visual to Select mode after CTRL-O command.\n if ( oap->op_type == OP_NOP\n\t && ((restart_edit != 0 && !VIsual_active && old_mapped_len == 0)\n\t\t|| restart_VIsual_select == 1)\n\t && !(ca.retval & CA_COMMAND_BUSY)\n\t && stuff_empty()\n\t && oap->regname == 0)\n {\n\tif (restart_VIsual_select == 1)\n\t{\n\t VIsual_select = TRUE;\n\t may_trigger_modechanged();\n\t showmode();\n\t restart_VIsual_select = 0;\n\t VIsual_select_reg = 0;\n\t}\n\tif (restart_edit != 0 && !VIsual_active && old_mapped_len == 0)\n\t (void)edit(restart_edit, FALSE, 1L);\n }\n\n if (restart_VIsual_select == 2)\n\trestart_VIsual_select = 1;\n\n // Save count before an operator for next time.\n opcount = ca.opcount;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'patch 8.2.5023: substitute overwrites allocated buffer\n\nProblem: Substitute overwrites allocated buffer.\nSolution: Disallow undo when in a substitute command.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: \t__must_hold(&req->ctx->timeout_lock)\n{\n\tstruct io_timeout_data *io = req->async_data;\n\n\tif (hrtimer_try_to_cancel(&io->timer) != -1) {\n\t\tif (status)\n\t\t\treq_set_fail(req);\n\t\tatomic_set(&req->ctx->cq_timeouts,\n\t\t\tatomic_read(&req->ctx->cq_timeouts) + 1);\n\t\tlist_del_init(&req->timeout.list);\n\t\tio_req_tw_post_queue(req, status, 0);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'io_uring: reinstate the inflight tracking\n\nAfter some debugging, it was realized that we really do still need the\nold inflight tracking for any file type that has io_uring_fops assigned.\nIf we don't, then trivial circular references will mean that we never get\nthe ctx cleaned up and hence it'll leak.\n\nJust bring back the inflight tracking, which then also means we can\neliminate the conditional dropping of the file when task_work is queued.\n\nFixes: d5361233e9ab (\"io_uring: drop the old style inflight file tracking\")\nSigned-off-by: Jens Axboe '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void sandboxfs(int op, pid_t pid, const char *path1, const char *path2) {\n\tEUID_ASSERT();\n\tassert(path1);\n\n\t// in case the pid is that of a firejail process, use the pid of the first child process\n\tpid = switch_to_child(pid);\n\n\t// exit if no permission to join the sandbox\n\tcheck_join_permission(pid);\n\n\t// expand paths\n\tchar *fname1 = expand_path(path1);\n\tchar *fname2 = NULL;\n\tif (path2 != NULL) {\n\t\tfname2 = expand_path(path2);\n\t}\n\tif (arg_debug) {\n\t\tprintf(\"file1 %s\\n\", fname1);\n\t\tprintf(\"file2 %s\\n\", fname2 ? fname2 : \"(null)\");\n\t}\n\n\t// get file from sandbox and store it in the current directory\n\t// implemented using --cat\n\tif (op == SANDBOX_FS_GET) {\n\t\tchar *dest_fname = strrchr(fname1, '/');\n\t\tif (!dest_fname || *(++dest_fname) == '\\0') {\n\t\t\tfprintf(stderr, \"Error: invalid file name %s\\n\", fname1);\n\t\t\texit(1);\n\t\t}\n\t\t// create destination file if necessary\n\t\tEUID_ASSERT();\n\t\tint fd = open(dest_fname, O_WRONLY|O_CREAT|O_CLOEXEC, S_IRUSR | S_IWUSR);\n\t\tif (fd == -1) {\n\t\t\tfprintf(stderr, \"Error: cannot open %s for writing\\n\", dest_fname);\n\t\t\texit(1);\n\t\t}\n\t\tstruct stat s;\n\t\tif (fstat(fd, &s) == -1)\n\t\t\terrExit(\"fstat\");\n\t\tif (!S_ISREG(s.st_mode)) {\n\t\t\tfprintf(stderr, \"Error: %s is no regular file\\n\", dest_fname);\n\t\t\texit(1);\n\t\t}\n\t\tif (ftruncate(fd, 0) == -1)\n\t\t\terrExit(\"ftruncate\");\n\t\t// go quiet - messages on stdout will corrupt the file\n\t\targ_debug = 0;\n\t\targ_quiet = 1;\n\t\t// redirection\n\t\tif (dup2(fd, STDOUT_FILENO) == -1)\n\t\t\terrExit(\"dup2\");\n\t\tclose(fd);\n\t\top = SANDBOX_FS_CAT;\n\t}\n\n\t// sandbox root directory\n\tchar *rootdir;\n\tif (asprintf(&rootdir, \"/proc/%d/root\", pid) == -1)\n\t\terrExit(\"asprintf\");\n\n\tif (op == SANDBOX_FS_LS || op == SANDBOX_FS_CAT) {\n\t\tEUID_ROOT();\n\t\t// chroot\n\t\tif (chroot(rootdir) < 0)\n\t\t\terrExit(\"chroot\");\n\t\tif (chdir(\"/\") < 0)\n\t\t\terrExit(\"chdir\");\n\n\t\t// drop privileges\n\t\tdrop_privs(0);\n\n\t\tif (op == SANDBOX_FS_LS)\n\t\t\tls(fname1);\n\t\telse\n\t\t\tcat(fname1);\n\n\t\t__gcov_flush();\n\t}\n\t// get file from host and store it in the sandbox\n\telse if (op == SANDBOX_FS_PUT && path2) {\n\t\tchar *src_fname =fname1;\n\t\tchar *dest_fname = fname2;\n\n\t\tEUID_ROOT();\n\t\tif (arg_debug)\n\t\t\tprintf(\"copy %s to %s\\n\", src_fname, dest_fname);\n\n\t\t// create a user-owned temporary file in /run/firejail directory\n\t\tchar tmp_fname[] = \"/run/firejail/tmpget-XXXXXX\";\n\t\tint fd = mkstemp(tmp_fname);\n\t\tif (fd == -1) {\n\t\t\tfprintf(stderr, \"Error: cannot create temporary file %s\\n\", tmp_fname);\n\t\t\texit(1);\n\t\t}\n\t\tSET_PERMS_FD(fd, getuid(), getgid(), 0600);\n\t\tclose(fd);\n\n\t\t// copy the source file into the temporary file - we need to chroot\n\t\tpid_t child = fork();\n\t\tif (child < 0)\n\t\t\terrExit(\"fork\");\n\t\tif (child == 0) {\n\t\t\t// drop privileges\n\t\t\tdrop_privs(0);\n\n\t\t\t// copy the file\n\t\t\tif (copy_file(src_fname, tmp_fname, getuid(), getgid(), 0600)) // already a regular user\n\t\t\t\t_exit(1);\n\n\t\t\t__gcov_flush();\n\n\t\t\t_exit(0);\n\t\t}\n\n\t\t// wait for the child to finish\n\t\tint status = 0;\n\t\twaitpid(child, &status, 0);\n\t\tif (WIFEXITED(status) && WEXITSTATUS(status) == 0);\n\t\telse {\n\t\t\tunlink(tmp_fname);\n\t\t\texit(1);\n\t\t}\n\n\t\t// copy the temporary file into the destination file\n\t\tchild = fork();\n\t\tif (child < 0)\n\t\t\terrExit(\"fork\");\n\t\tif (child == 0) {\n\t\t\t// chroot\n\t\t\tif (chroot(rootdir) < 0)\n\t\t\t\terrExit(\"chroot\");\n\t\t\tif (chdir(\"/\") < 0)\n\t\t\t\terrExit(\"chdir\");\n\n\t\t\t// drop privileges\n\t\t\tdrop_privs(0);\n\n\t\t\t// copy the file\n\t\t\tif (copy_file(tmp_fname, dest_fname, getuid(), getgid(), 0600)) // already a regular user\n\t\t\t\t_exit(1);\n\n\t\t\t__gcov_flush();\n\n\t\t\t_exit(0);\n\t\t}\n\n\t\t// wait for the child to finish\n\t\tstatus = 0;\n\t\twaitpid(child, &status, 0);\n\t\tif (WIFEXITED(status) && WEXITSTATUS(status) == 0);\n\t\telse {\n\t\t\tunlink(tmp_fname);\n\t\t\texit(1);\n\t\t}\n\n\t\t// remove the temporary file\n\t\tunlink(tmp_fname);\n\t\tEUID_USER();\n\t}\n\n\tif (fname2)\n\t\tfree(fname2);\n\tfree(fname1);\n\tfree(rootdir);\n\n\texit(0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-269', 'CWE-94'], 'message': 'fixing CVE-2022-31214'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void delete_run_files(pid_t pid) {\n\tdelete_bandwidth_run_file(pid);\n\tdelete_network_run_file(pid);\n\tdelete_name_run_file(pid);\n\tdelete_x11_run_file(pid);\n\tdelete_profile_run_file(pid);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-269', 'CWE-94'], 'message': 'fixing CVE-2022-31214'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static uint64_t extract_caps(int pid) {\n\tEUID_ASSERT();\n\n\tchar *file;\n\tif (asprintf(&file, \"/proc/%d/status\", pid) == -1)\n\t\terrExit(\"asprintf\");\n\n\tEUID_ROOT();\t// grsecurity\n\tFILE *fp = fopen(file, \"re\");\n\tEUID_USER();\t// grsecurity\n\tif (!fp)\n\t\tgoto errexit;\n\n\tchar buf[MAXBUF];\n\twhile (fgets(buf, MAXBUF, fp)) {\n\t\tif (strncmp(buf, \"CapBnd:\\t\", 8) == 0) {\n\t\t\tchar *ptr = buf + 8;\n\t\t\tunsigned long long val;\n\t\t\tsscanf(ptr, \"%llx\", &val);\n\t\t\tfree(file);\n\t\t\tfclose(fp);\n\t\t\treturn val;\n\t\t}\n\t}\n\tfclose(fp);\n\nerrexit:\n\tfree(file);\n\tfprintf(stderr, \"Error: cannot read caps configuration\\n\");\n\texit(1);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-269', 'CWE-94'], 'message': 'fixing CVE-2022-31214'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void extract_cpu(pid_t pid) {\n\tchar *fname;\n\tif (asprintf(&fname, \"/proc/%d/root%s\", pid, RUN_CPU_CFG) == -1)\n\t\terrExit(\"asprintf\");\n\n\tstruct stat s;\n\tif (stat(fname, &s) == -1) {\n\t\tfree(fname);\n\t\treturn;\n\t}\n\n\t// there is a CPU_CFG file, load it!\n\tload_cpu(fname);\n\tfree(fname);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-269', 'CWE-94'], 'message': 'fixing CVE-2022-31214'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void build_dirs(char *src, char *dst, size_t src_prefix_len, size_t dst_prefix_len) {\n\tchar *p = src + src_prefix_len + 1;\n\tchar *q = dst + dst_prefix_len + 1;\n\tchar *r = dst + dst_prefix_len;\n\tstruct stat s;\n\tbool last = false;\n\t*r = '\\0';\n\tfor (; !last; p++, q++) {\n\t\tif (*p == '\\0') {\n\t\t\tlast = true;\n\t\t}\n\t\tif (*p == '\\0' || (*p == '/' && *(p - 1) != '/')) {\n\t\t\t// We found a new component of our src path.\n\t\t\t// Null-terminate it temporarily here so that we can work\n\t\t\t// with it.\n\t\t\t*p = '\\0';\n\t\t\tif (stat(src, &s) == 0 && S_ISDIR(s.st_mode)) {\n\t\t\t\t// Null-terminate the dst path and undo its previous\n\t\t\t\t// termination.\n\t\t\t\t*q = '\\0';\n\t\t\t\t*r = '/';\n\t\t\t\tr = q;\n\t\t\t\tmkdir_attr(dst, s.st_mode, 0, 0);\n\t\t\t}\n\t\t\tif (!last) {\n\t\t\t\t// If we're not at the final terminating null, restore\n\t\t\t\t// the slash so that we can continue our traversal.\n\t\t\t\t*p = '/';\n\t\t\t}\n\t\t}\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-269', 'CWE-94'], 'message': 'CVE-2022-31214: fixing the fix, one more time\n\nthe previous commit \"CVE-2022-31214: fixing the fix\"\nmade private-etc=fonts,fonts and similar commands\nfail with an error\n\nfix that regression by tolerating already existing\ndirectories'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: dwarf_global_formref_b(Dwarf_Attribute attr,\n Dwarf_Off * ret_offset,\n Dwarf_Bool * offset_is_info,\n Dwarf_Error * error)\n{\n Dwarf_Debug dbg = 0;\n Dwarf_Unsigned offset = 0;\n Dwarf_CU_Context cu_context = 0;\n Dwarf_Half context_version = 0;\n Dwarf_Byte_Ptr section_end = 0;\n Dwarf_Bool is_info = TRUE;\n\n int res = get_attr_dbg(&dbg,&cu_context,attr,error);\n if (res != DW_DLV_OK) {\n return res;\n }\n section_end =\n _dwarf_calculate_info_section_end_ptr(cu_context);\n context_version = cu_context->cc_version_stamp;\n is_info = cu_context->cc_is_info;\n switch (attr->ar_attribute_form) {\n\n case DW_FORM_ref1:\n offset = *(Dwarf_Small *) attr->ar_debug_ptr;\n goto fixoffset;\n\n case DW_FORM_ref2:\n READ_UNALIGNED_CK(dbg, offset, Dwarf_Unsigned,\n attr->ar_debug_ptr, DWARF_HALF_SIZE,\n error,section_end);\n goto fixoffset;\n\n case DW_FORM_ref4:\n READ_UNALIGNED_CK(dbg, offset, Dwarf_Unsigned,\n attr->ar_debug_ptr, DWARF_32BIT_SIZE,\n error,section_end);\n goto fixoffset;\n\n case DW_FORM_ref8:\n READ_UNALIGNED_CK(dbg, offset, Dwarf_Unsigned,\n attr->ar_debug_ptr, DWARF_64BIT_SIZE,\n error,section_end);\n goto fixoffset;\n\n case DW_FORM_ref_udata:\n {\n Dwarf_Byte_Ptr ptr = attr->ar_debug_ptr;\n Dwarf_Unsigned localoffset = 0;\n\n DECODE_LEB128_UWORD_CK(ptr,localoffset,\n dbg,error,section_end);\n offset = localoffset;\n\n fixoffset: /* we have a local offset, make it global */\n\n /* check legality of offset */\n if (offset >= cu_context->cc_length +\n cu_context->cc_length_size +\n cu_context->cc_extension_size) {\n _dwarf_error(dbg, error, DW_DLE_ATTR_FORM_OFFSET_BAD);\n return DW_DLV_ERROR;\n }\n\n /* globalize the offset */\n offset += cu_context->cc_debug_offset;\n }\n break;\n\n /* The DWARF2 document did not make clear that\n DW_FORM_data4( and 8) were references with\n global offsets to some section.\n That was first clearly documented in DWARF3.\n In DWARF4 these two forms are no longer references. */\n case DW_FORM_data4:\n if (context_version >= DW_CU_VERSION4) {\n _dwarf_error(dbg, error, DW_DLE_NOT_REF_FORM);\n return DW_DLV_ERROR;\n }\n READ_UNALIGNED_CK(dbg, offset, Dwarf_Unsigned,\n attr->ar_debug_ptr, DWARF_32BIT_SIZE,\n error, section_end);\n /* The offset is global. */\n break;\n case DW_FORM_data8:\n if (context_version >= DW_CU_VERSION4) {\n _dwarf_error(dbg, error, DW_DLE_NOT_REF_FORM);\n return DW_DLV_ERROR;\n }\n READ_UNALIGNED_CK(dbg, offset, Dwarf_Unsigned,\n attr->ar_debug_ptr, DWARF_64BIT_SIZE,\n error,section_end);\n /* The offset is global. */\n break;\n case DW_FORM_ref_addr:\n {\n /* In Dwarf V2 DW_FORM_ref_addr was defined\n as address-size even though it is a .debug_info\n offset. Fixed in Dwarf V3 to be offset-size.\n */\n unsigned length_size = 0;\n if (context_version == 2) {\n length_size = cu_context->cc_address_size;\n } else {\n length_size = cu_context->cc_length_size;\n }\n if (length_size == 4) {\n READ_UNALIGNED_CK(dbg, offset, Dwarf_Unsigned,\n attr->ar_debug_ptr, DWARF_32BIT_SIZE,\n error,section_end);\n } else if (length_size == 8) {\n READ_UNALIGNED_CK(dbg, offset, Dwarf_Unsigned,\n attr->ar_debug_ptr, DWARF_64BIT_SIZE,\n error,section_end);\n } else {\n _dwarf_error(dbg, error,\n DW_DLE_FORM_SEC_OFFSET_LENGTH_BAD);\n return DW_DLV_ERROR;\n }\n }\n break;\n /* Index into .debug_rnglists/.debug_loclists section.\n Return the index itself. */\n case DW_FORM_loclistx:\n case DW_FORM_rnglistx: {\n unsigned length_size = cu_context->cc_length_size;\n READ_UNALIGNED_CK(dbg, offset, Dwarf_Unsigned,\n attr->ar_debug_ptr, length_size,\n error,section_end);\n }\n break;\n case DW_FORM_sec_offset:\n case DW_FORM_GNU_ref_alt: /* 2013 GNU extension */\n case DW_FORM_GNU_strp_alt: /* 2013 GNU extension */\n case DW_FORM_strp_sup: /* DWARF5, sup string section */\n case DW_FORM_line_strp: /* DWARF5, .debug_line_str section */\n {\n /* DW_FORM_sec_offset first exists in DWARF4.*/\n /* It is up to the caller to know what the offset\n of DW_FORM_sec_offset, DW_FORM_strp_sup\n or DW_FORM_GNU_strp_alt etc refer to,\n the offset is not going to refer to .debug_info! */\n unsigned length_size = cu_context->cc_length_size;\n if (length_size == 4) {\n READ_UNALIGNED_CK(dbg, offset, Dwarf_Unsigned,\n attr->ar_debug_ptr, DWARF_32BIT_SIZE,\n error,section_end);\n } else if (length_size == 8) {\n READ_UNALIGNED_CK(dbg, offset, Dwarf_Unsigned,\n attr->ar_debug_ptr, DWARF_64BIT_SIZE,\n error,section_end);\n } else {\n _dwarf_error(dbg, error,\n DW_DLE_FORM_SEC_OFFSET_LENGTH_BAD);\n return DW_DLV_ERROR;\n }\n }\n break;\n case DW_FORM_ref_sig8: {\n /* This, in DWARF4, is how\n .debug_info refers to .debug_types. */\n Dwarf_Sig8 sig8;\n Dwarf_Bool t_is_info = TRUE;\n Dwarf_Unsigned t_offset = 0;\n\n memcpy(&sig8,attr->ar_debug_ptr,sizeof(Dwarf_Sig8));\n res = find_sig8_target_as_global_offset(attr,\n &sig8,&t_is_info,&t_offset,error);\n if (res == DW_DLV_ERROR) {\n _dwarf_error_string(dbg, error,\n DW_DLE_REF_SIG8_NOT_HANDLED,\n \"DW_DLE_REF_SIG8_NOT_HANDLED: \"\n \" problem finding target\");\n return DW_DLV_ERROR;\n }\n if (res == DW_DLV_NO_ENTRY) {\n return res;\n }\n is_info = t_is_info;\n offset = t_offset;\n break;\n }\n default: {\n dwarfstring m;\n int formcode = attr->ar_attribute_form;\n int fcres = 0;\n const char *name = 0;\n\n dwarfstring_constructor(&m);\n dwarfstring_append_printf_u(&m,\n \"DW_DLE_BAD_REF_FORM: The form code is 0x%x \",\n formcode);\n fcres = dwarf_get_FORM_name (formcode,&name);\n if (fcres != DW_DLV_OK) {\n name=\"\";\n }\n dwarfstring_append_printf_s(&m,\n \" %s.\",(char *)name);\n _dwarf_error_string(dbg, error, DW_DLE_BAD_REF_FORM,\n dwarfstring_string(&m));\n dwarfstring_destructor(&m);\n return DW_DLV_ERROR;\n }\n }\n\n *offset_is_info = is_info;\n *ret_offset = offset;\n return DW_DLV_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-125'], 'message': 'Fixes old bug(which could result in Denial of Service)\ndue to a missing check before reading the 8 bytes of a DW_FORM_ref_sig8.\nDW202206-001\n\tmodified: src/lib/libdwarf/dwarf_form.c'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static struct rpmsg_device *rpmsg_virtio_add_ctrl_dev(struct virtio_device *vdev)\n{\n\tstruct virtproc_info *vrp = vdev->priv;\n\tstruct virtio_rpmsg_channel *vch;\n\tstruct rpmsg_device *rpdev_ctrl;\n\tint err = 0;\n\n\tvch = kzalloc(sizeof(*vch), GFP_KERNEL);\n\tif (!vch)\n\t\treturn ERR_PTR(-ENOMEM);\n\n\t/* Link the channel to the vrp */\n\tvch->vrp = vrp;\n\n\t/* Assign public information to the rpmsg_device */\n\trpdev_ctrl = &vch->rpdev;\n\trpdev_ctrl->ops = &virtio_rpmsg_ops;\n\n\trpdev_ctrl->dev.parent = &vrp->vdev->dev;\n\trpdev_ctrl->dev.release = virtio_rpmsg_release_device;\n\trpdev_ctrl->little_endian = virtio_is_little_endian(vrp->vdev);\n\n\terr = rpmsg_ctrldev_register_device(rpdev_ctrl);\n\tif (err) {\n\t\tkfree(vch);\n\t\treturn ERR_PTR(err);\n\t}\n\n\treturn rpdev_ctrl;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415'], 'message': 'rpmsg: virtio: Fix possible double free in rpmsg_virtio_add_ctrl_dev()\n\nvch will be free in virtio_rpmsg_release_device() when\nrpmsg_ctrldev_register_device() fails. There is no need to call\nkfree() again.\n\nFixes: c486682ae1e2 (\"rpmsg: virtio: Register the rpmsg_char device\")\nSigned-off-by: Hangyu Hua \nTested-by: Arnaud Pouliquen \nLink: https://lore.kernel.org/r/20220426060536.15594-3-hbh25y@gmail.com\nSigned-off-by: Mathieu Poirier '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: store_word(\n spellinfo_T\t*spin,\n char_u\t*word,\n int\t\tflags,\t\t// extra flags, WF_BANNED\n int\t\tregion,\t\t// supported region(s)\n char_u\t*pfxlist,\t// list of prefix IDs or NULL\n int\t\tneed_affix)\t// only store word with affix ID\n{\n int\t\tlen = (int)STRLEN(word);\n int\t\tct = captype(word, word + len);\n char_u\tfoldword[MAXWLEN];\n int\t\tres = OK;\n char_u\t*p;\n\n // Avoid adding illegal bytes to the word tree.\n if (enc_utf8 && !utf_valid_string(word, NULL))\n\treturn FAIL;\n\n (void)spell_casefold(curwin, word, len, foldword, MAXWLEN);\n for (p = pfxlist; res == OK; ++p)\n {\n\tif (!need_affix || (p != NULL && *p != NUL))\n\t res = tree_add_word(spin, foldword, spin->si_foldroot, ct | flags,\n\t\t\t\t\t\t region, p == NULL ? 0 : *p);\n\tif (p == NULL || *p == NUL)\n\t break;\n }\n ++spin->si_foldwcount;\n\n if (res == OK && (ct == WF_KEEPCAP || (flags & WF_KEEPCAP)))\n {\n\tfor (p = pfxlist; res == OK; ++p)\n\t{\n\t if (!need_affix || (p != NULL && *p != NUL))\n\t\tres = tree_add_word(spin, word, spin->si_keeproot, flags,\n\t\t\t\t\t\t region, p == NULL ? 0 : *p);\n\t if (p == NULL || *p == NUL)\n\t\tbreak;\n\t}\n\t++spin->si_keepwcount;\n }\n return res;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'patch 9.0.0021: invalid memory access when adding word to spell word list\n\nProblem: Invalid memory access when adding word with a control character to\n the internal spell word list.\nSolution: Disallow adding a word with control characters or a trailing\n slash.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void rose_start_idletimer(struct sock *sk)\n{\n\tstruct rose_sock *rose = rose_sk(sk);\n\n\tdel_timer(&rose->idletimer);\n\n\tif (rose->idle > 0) {\n\t\trose->idletimer.function = rose_idletimer_expiry;\n\t\trose->idletimer.expires = jiffies + rose->idle;\n\n\t\tadd_timer(&rose->idletimer);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'net: rose: fix UAF bugs caused by timer handler\n\nThere are UAF bugs in rose_heartbeat_expiry(), rose_timer_expiry()\nand rose_idletimer_expiry(). The root cause is that del_timer()\ncould not stop the timer handler that is running and the refcount\nof sock is not managed properly.\n\nOne of the UAF bugs is shown below:\n\n (thread 1) | (thread 2)\n | rose_bind\n | rose_connect\n | rose_start_heartbeat\nrose_release | (wait a time)\n case ROSE_STATE_0 |\n rose_destroy_socket | rose_heartbeat_expiry\n rose_stop_heartbeat |\n sock_put(sk) | ...\n sock_put(sk) // FREE |\n | bh_lock_sock(sk) // USE\n\nThe sock is deallocated by sock_put() in rose_release() and\nthen used by bh_lock_sock() in rose_heartbeat_expiry().\n\nAlthough rose_destroy_socket() calls rose_stop_heartbeat(),\nit could not stop the timer that is running.\n\nThe KASAN report triggered by POC is shown below:\n\nBUG: KASAN: use-after-free in _raw_spin_lock+0x5a/0x110\nWrite of size 4 at addr ffff88800ae59098 by task swapper/3/0\n...\nCall Trace:\n \n dump_stack_lvl+0xbf/0xee\n print_address_description+0x7b/0x440\n print_report+0x101/0x230\n ? irq_work_single+0xbb/0x140\n ? _raw_spin_lock+0x5a/0x110\n kasan_report+0xed/0x120\n ? _raw_spin_lock+0x5a/0x110\n kasan_check_range+0x2bd/0x2e0\n _raw_spin_lock+0x5a/0x110\n rose_heartbeat_expiry+0x39/0x370\n ? rose_start_heartbeat+0xb0/0xb0\n call_timer_fn+0x2d/0x1c0\n ? rose_start_heartbeat+0xb0/0xb0\n expire_timers+0x1f3/0x320\n __run_timers+0x3ff/0x4d0\n run_timer_softirq+0x41/0x80\n __do_softirq+0x233/0x544\n irq_exit_rcu+0x41/0xa0\n sysvec_apic_timer_interrupt+0x8c/0xb0\n \n \n asm_sysvec_apic_timer_interrupt+0x1b/0x20\nRIP: 0010:default_idle+0xb/0x10\nRSP: 0018:ffffc9000012fea0 EFLAGS: 00000202\nRAX: 000000000000bcae RBX: ffff888006660f00 RCX: 000000000000bcae\nRDX: 0000000000000001 RSI: ffffffff843a11c0 RDI: ffffffff843a1180\nRBP: dffffc0000000000 R08: dffffc0000000000 R09: ffffed100da36d46\nR10: dfffe9100da36d47 R11: ffffffff83cf0950 R12: 0000000000000000\nR13: 1ffff11000ccc1e0 R14: ffffffff8542af28 R15: dffffc0000000000\n...\nAllocated by task 146:\n __kasan_kmalloc+0xc4/0xf0\n sk_prot_alloc+0xdd/0x1a0\n sk_alloc+0x2d/0x4e0\n rose_create+0x7b/0x330\n __sock_create+0x2dd/0x640\n __sys_socket+0xc7/0x270\n __x64_sys_socket+0x71/0x80\n do_syscall_64+0x43/0x90\n entry_SYSCALL_64_after_hwframe+0x46/0xb0\n\nFreed by task 152:\n kasan_set_track+0x4c/0x70\n kasan_set_free_info+0x1f/0x40\n ____kasan_slab_free+0x124/0x190\n kfree+0xd3/0x270\n __sk_destruct+0x314/0x460\n rose_release+0x2fa/0x3b0\n sock_close+0xcb/0x230\n __fput+0x2d9/0x650\n task_work_run+0xd6/0x160\n exit_to_user_mode_loop+0xc7/0xd0\n exit_to_user_mode_prepare+0x4e/0x80\n syscall_exit_to_user_mode+0x20/0x40\n do_syscall_64+0x4f/0x90\n entry_SYSCALL_64_after_hwframe+0x46/0xb0\n\nThis patch adds refcount of sock when we use functions\nsuch as rose_start_heartbeat() and so on to start timer,\nand decreases the refcount of sock when timer is finished\nor deleted by functions such as rose_stop_heartbeat()\nand so on. As a result, the UAF bugs could be mitigated.\n\nFixes: 1da177e4c3f4 (\"Linux-2.6.12-rc2\")\nSigned-off-by: Duoming Zhou \nTested-by: Duoming Zhou \nLink: https://lore.kernel.org/r/20220629002640.5693-1-duoming@zju.edu.cn\nSigned-off-by: Paolo Abeni '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static ssize_t smtcfb_read(struct fb_info *info, char __user *buf,\n\t\t\t size_t count, loff_t *ppos)\n{\n\tunsigned long p = *ppos;\n\n\tu32 *buffer, *dst;\n\tu32 __iomem *src;\n\tint c, i, cnt = 0, err = 0;\n\tunsigned long total_size;\n\n\tif (!info || !info->screen_base)\n\t\treturn -ENODEV;\n\n\tif (info->state != FBINFO_STATE_RUNNING)\n\t\treturn -EPERM;\n\n\ttotal_size = info->screen_size;\n\n\tif (total_size == 0)\n\t\ttotal_size = info->fix.smem_len;\n\n\tif (p >= total_size)\n\t\treturn 0;\n\n\tif (count >= total_size)\n\t\tcount = total_size;\n\n\tif (count + p > total_size)\n\t\tcount = total_size - p;\n\n\tbuffer = kmalloc((count > PAGE_SIZE) ? PAGE_SIZE : count, GFP_KERNEL);\n\tif (!buffer)\n\t\treturn -ENOMEM;\n\n\tsrc = (u32 __iomem *)(info->screen_base + p);\n\n\tif (info->fbops->fb_sync)\n\t\tinfo->fbops->fb_sync(info);\n\n\twhile (count) {\n\t\tc = (count > PAGE_SIZE) ? PAGE_SIZE : count;\n\t\tdst = buffer;\n\t\tfor (i = c >> 2; i--;) {\n\t\t\t*dst = fb_readl(src++);\n\t\t\t*dst = big_swap(*dst);\n\t\t\tdst++;\n\t\t}\n\t\tif (c & 3) {\n\t\t\tu8 *dst8 = (u8 *)dst;\n\t\t\tu8 __iomem *src8 = (u8 __iomem *)src;\n\n\t\t\tfor (i = c & 3; i--;) {\n\t\t\t\tif (i & 1) {\n\t\t\t\t\t*dst8++ = fb_readb(++src8);\n\t\t\t\t} else {\n\t\t\t\t\t*dst8++ = fb_readb(--src8);\n\t\t\t\t\tsrc8 += 2;\n\t\t\t\t}\n\t\t\t}\n\t\t\tsrc = (u32 __iomem *)src8;\n\t\t}\n\n\t\tif (copy_to_user(buf, buffer, c)) {\n\t\t\terr = -EFAULT;\n\t\t\tbreak;\n\t\t}\n\t\t*ppos += c;\n\t\tbuf += c;\n\t\tcnt += c;\n\t\tcount -= c;\n\t}\n\n\tkfree(buffer);\n\n\treturn (err) ? err : cnt;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'video: fbdev: sm712fb: Fix crash in smtcfb_read()\n\nZheyu Ma reported this crash in the sm712fb driver when reading\nthree bytes from the framebuffer:\n\n BUG: unable to handle page fault for address: ffffc90001ffffff\n RIP: 0010:smtcfb_read+0x230/0x3e0\n Call Trace:\n vfs_read+0x198/0xa00\n ? do_sys_openat2+0x27d/0x350\n ? __fget_light+0x54/0x340\n ksys_read+0xce/0x190\n do_syscall_64+0x43/0x90\n\nFix it by removing the open-coded endianess fixup-code and\nby moving the pointer post decrement out the fb_readl() function.\n\nReported-by: Zheyu Ma \nSigned-off-by: Helge Deller \nTested-by: Zheyu Ma \nCc: stable@vger.kernel.org'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: SetDeviceIndicators(char *wire,\n DeviceIntPtr dev,\n unsigned changed,\n int num,\n int *status_rtrn,\n ClientPtr client,\n xkbExtensionDeviceNotify * ev,\n xkbSetDeviceInfoReq * stuff)\n{\n xkbDeviceLedsWireDesc *ledWire;\n int i;\n XkbEventCauseRec cause;\n unsigned namec, mapc, statec;\n xkbExtensionDeviceNotify ed;\n XkbChangesRec changes;\n DeviceIntPtr kbd;\n\n memset((char *) &ed, 0, sizeof(xkbExtensionDeviceNotify));\n memset((char *) &changes, 0, sizeof(XkbChangesRec));\n XkbSetCauseXkbReq(&cause, X_kbSetDeviceInfo, client);\n ledWire = (xkbDeviceLedsWireDesc *) wire;\n for (i = 0; i < num; i++) {\n register int n;\n register unsigned bit;\n CARD32 *atomWire;\n xkbIndicatorMapWireDesc *mapWire;\n XkbSrvLedInfoPtr sli;\n\n if (!_XkbCheckRequestBounds(client, stuff, ledWire, ledWire + 1)) {\n *status_rtrn = BadLength;\n return (char *) ledWire;\n }\n\n namec = mapc = statec = 0;\n sli = XkbFindSrvLedInfo(dev, ledWire->ledClass, ledWire->ledID,\n XkbXI_IndicatorMapsMask);\n if (!sli) {\n /* SHOULD NEVER HAPPEN!! */\n return (char *) ledWire;\n }\n\n atomWire = (CARD32 *) &ledWire[1];\n if (changed & XkbXI_IndicatorNamesMask) {\n namec = sli->namesPresent | ledWire->namesPresent;\n memset((char *) sli->names, 0, XkbNumIndicators * sizeof(Atom));\n }\n if (ledWire->namesPresent) {\n sli->namesPresent = ledWire->namesPresent;\n memset((char *) sli->names, 0, XkbNumIndicators * sizeof(Atom));\n for (n = 0, bit = 1; n < XkbNumIndicators; n++, bit <<= 1) {\n if (ledWire->namesPresent & bit) {\n if (!_XkbCheckRequestBounds(client, stuff, atomWire, atomWire + 1)) {\n *status_rtrn = BadLength;\n return (char *) atomWire;\n }\n sli->names[n] = (Atom) *atomWire;\n if (sli->names[n] == None)\n ledWire->namesPresent &= ~bit;\n atomWire++;\n }\n }\n }\n mapWire = (xkbIndicatorMapWireDesc *) atomWire;\n if (changed & XkbXI_IndicatorMapsMask) {\n mapc = sli->mapsPresent | ledWire->mapsPresent;\n sli->mapsPresent = ledWire->mapsPresent;\n memset((char *) sli->maps, 0,\n XkbNumIndicators * sizeof(XkbIndicatorMapRec));\n }\n if (ledWire->mapsPresent) {\n for (n = 0, bit = 1; n < XkbNumIndicators; n++, bit <<= 1) {\n if (ledWire->mapsPresent & bit) {\n if (!_XkbCheckRequestBounds(client, stuff, mapWire, mapWire + 1)) {\n *status_rtrn = BadLength;\n return (char *) mapWire;\n }\n sli->maps[n].flags = mapWire->flags;\n sli->maps[n].which_groups = mapWire->whichGroups;\n sli->maps[n].groups = mapWire->groups;\n sli->maps[n].which_mods = mapWire->whichMods;\n sli->maps[n].mods.mask = mapWire->mods;\n sli->maps[n].mods.real_mods = mapWire->realMods;\n sli->maps[n].mods.vmods = mapWire->virtualMods;\n sli->maps[n].ctrls = mapWire->ctrls;\n mapWire++;\n }\n }\n }\n if (changed & XkbXI_IndicatorStateMask) {\n statec = sli->effectiveState ^ ledWire->state;\n sli->explicitState &= ~statec;\n sli->explicitState |= (ledWire->state & statec);\n }\n if (namec)\n XkbApplyLedNameChanges(dev, sli, namec, &ed, &changes, &cause);\n if (mapc)\n XkbApplyLedMapChanges(dev, sli, mapc, &ed, &changes, &cause);\n if (statec)\n XkbApplyLedStateChanges(dev, sli, statec, &ed, &changes, &cause);\n\n kbd = dev;\n if ((sli->flags & XkbSLI_HasOwnState) == 0)\n kbd = inputInfo.keyboard;\n\n XkbFlushLedEvents(dev, kbd, sli, &ed, &changes, &cause);\n ledWire = (xkbDeviceLedsWireDesc *) mapWire;\n }\n return (char *) ledWire;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-94', 'CWE-787'], 'message': 'xkb: swap XkbSetDeviceInfo and XkbSetDeviceInfoCheck\n\nXKB often uses a FooCheck and Foo function pair, the former is supposed\nto check all values in the request and error out on BadLength,\nBadValue, etc. The latter is then called once we're confident the values\nare good (they may still fail on an individual device, but that's a\ndifferent topic).\n\nIn the case of XkbSetDeviceInfo, those functions were incorrectly\nnamed, with XkbSetDeviceInfo ending up as the checker function and\nXkbSetDeviceInfoCheck as the setter function. As a result, the setter\nfunction was called before the checker function, accessing request\ndata and modifying device state before we ensured that the data is\nvalid.\n\nIn particular, the setter function relied on values being already\nbyte-swapped. This in turn could lead to potential OOB memory access.\n\nFix this by correctly naming the functions and moving the length checks\nover to the checker function. These were added in 87c64fc5b0 to the\nwrong function, probably due to the incorrect naming.\n\nFixes ZDI-CAN 16070, CVE-2022-2320.\n\nThis vulnerability was discovered by:\nJan-Niklas Sohn working with Trend Micro Zero Day Initiative\n\nIntroduced in c06e27b2f6fd9f7b9f827623a48876a225264132\n\nSigned-off-by: Peter Hutterer '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: at_bitmap input_bmp_reader(gchar * filename, at_input_opts_type * opts, at_msg_func msg_func, gpointer msg_data, gpointer user_data)\n{\n FILE *fd;\n unsigned char buffer[64];\n int ColormapSize, rowbytes, Maps;\n gboolean Grey = FALSE;\n unsigned char ColorMap[256][3];\n at_bitmap image = at_bitmap_init(0, 0, 0, 1);\n unsigned char *image_storage;\n at_exception_type exp = at_exception_new(msg_func, msg_data);\n char magick[2];\n Bitmap_Channel masks[4];\n\n fd = fopen(filename, \"rb\");\n\n if (!fd) {\n LOG(\"Can't open \\\"%s\\\"\\n\", filename);\n at_exception_fatal(&exp, \"bmp: cannot open input file\");\n goto cleanup;\n }\n\n /* It is a File. Now is it a Bitmap? Read the shortest possible header. */\n\n if (!ReadOK(fd, magick, 2) ||\n\t !(!strncmp(magick, \"BA\", 2) ||\n\t\t !strncmp(magick, \"BM\", 2) ||\n\t\t !strncmp(magick, \"IC\", 2) ||\n\t\t !strncmp(magick, \"PT\", 2) ||\n\t\t !strncmp(magick, \"CI\", 2) ||\n\t\t !strncmp(magick, \"CP\", 2)))\n {\n\t LOG(\"%s is not a valid BMP file\", filename);\n\t at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t goto cleanup;\n }\n\n while (!strncmp(magick, \"BA\", 2))\n {\n\t if (!ReadOK(fd, buffer, 12))\n\t {\n\t\t LOG(\"%s is not a valid BMP file\", filename);\n\t\t at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t\t goto cleanup;\n\t }\n\n\t if (!ReadOK(fd, magick, 2))\n\t {\n\t\t LOG(\"%s is not a valid BMP file\", filename);\n\t\t at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t\t goto cleanup;\n\t }\n }\n\n if (!ReadOK(fd, buffer, 12))////\n {\n\t LOG(\"%s is not a valid BMP file\", filename);\n\t at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t goto cleanup;\n }\n\n /* bring them to the right byteorder. Not too nice, but it should work */\n\n Bitmap_File_Head.bfSize = ToL(&buffer[0x00]);\n Bitmap_File_Head.zzHotX = ToS(&buffer[0x04]);\n Bitmap_File_Head.zzHotY = ToS(&buffer[0x06]);\n Bitmap_File_Head.bfOffs = ToL(&buffer[0x08]);\n\n if (!ReadOK(fd, buffer, 4))\n {\n\t LOG(\"%s is not a valid BMP file\", filename);\n\t at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t goto cleanup;\n }\n\n Bitmap_File_Head.biSize = ToL(&buffer[0x00]);\n\n /* What kind of bitmap is it? */\n\n if (Bitmap_File_Head.biSize == 12) { /* OS/2 1.x ? */\n if (!ReadOK(fd, buffer, 8)) {\n LOG(\"Error reading BMP file header\\n\");\n at_exception_fatal(&exp, \"Error reading BMP file header\");\n goto cleanup;\n }\n\n Bitmap_Head.biWidth = ToS(&buffer[0x00]); /* 12 */\n Bitmap_Head.biHeight = ToS(&buffer[0x02]); /* 14 */\n Bitmap_Head.biPlanes = ToS(&buffer[0x04]); /* 16 */\n Bitmap_Head.biBitCnt = ToS(&buffer[0x06]); /* 18 */\n Bitmap_Head.biCompr = 0;\n Bitmap_Head.biSizeIm = 0;\n Bitmap_Head.biXPels = Bitmap_Head.biYPels = 0;\n Bitmap_Head.biClrUsed = 0;\n Bitmap_Head.biClrImp = 0;\n Bitmap_Head.masks[0] = 0;\n Bitmap_Head.masks[1] = 0;\n Bitmap_Head.masks[2] = 0;\n Bitmap_Head.masks[3] = 0;\n\n memset(masks, 0, sizeof(masks));\n Maps = 3;\n\n } else if (Bitmap_File_Head.biSize == 40) { /* Windows 3.x */\n if (!ReadOK(fd, buffer, 36))\n {\n LOG (\"Error reading BMP file header\\n\");\n at_exception_fatal(&exp, \"Error reading BMP file header\");\n goto cleanup;\n }\n \n\n Bitmap_Head.biWidth = ToL(&buffer[0x00]); /* 12 */\n Bitmap_Head.biHeight = ToL(&buffer[0x04]); /* 16 */\n Bitmap_Head.biPlanes = ToS(&buffer[0x08]); /* 1A */\n Bitmap_Head.biBitCnt = ToS(&buffer[0x0A]); /* 1C */\n Bitmap_Head.biCompr = ToL(&buffer[0x0C]); /* 1E */\n Bitmap_Head.biSizeIm = ToL(&buffer[0x10]); /* 22 */\n Bitmap_Head.biXPels = ToL(&buffer[0x14]); /* 26 */\n Bitmap_Head.biYPels = ToL(&buffer[0x18]); /* 2A */\n Bitmap_Head.biClrUsed = ToL(&buffer[0x1C]); /* 2E */\n Bitmap_Head.biClrImp = ToL(&buffer[0x20]); /* 32 */\n Bitmap_Head.masks[0] = 0;\n Bitmap_Head.masks[1] = 0;\n Bitmap_Head.masks[2] = 0;\n Bitmap_Head.masks[3] = 0;\n\n Maps = 4;\n memset(masks, 0, sizeof(masks));\n\n if (Bitmap_Head.biCompr == BI_BITFIELDS)\n {\n\tif (!ReadOK(fd, buffer, 3 * sizeof(unsigned long)))\n\t {\n\t LOG(\"Error reading BMP file header\\n\");\n\t at_exception_fatal(&exp, \"Error reading BMP file header\");\n\t goto cleanup;\n\t }\n\n\tBitmap_Head.masks[0] = ToL(&buffer[0x00]);\n\tBitmap_Head.masks[1] = ToL(&buffer[0x04]);\n\tBitmap_Head.masks[2] = ToL(&buffer[0x08]);\n\n\tReadChannelMasks(&Bitmap_Head.masks[0], masks, 3);\n }\n else if (Bitmap_Head.biCompr == BI_RGB)\n {\n\tsetMasksDefault(Bitmap_Head.biBitCnt, masks);\n }\n else if ((Bitmap_Head.biCompr != BI_RLE4) &&\n\t (Bitmap_Head.biCompr != BI_RLE8))\n {\n\t/* BI_ALPHABITFIELDS, etc. */\n\tLOG(\"Unsupported compression in BMP file\\n\");\n\tat_exception_fatal(&exp, \"Unsupported compression in BMP file\");\n\tgoto cleanup;\n }\n }\n else if (Bitmap_File_Head.biSize >= 56 &&\n\t Bitmap_File_Head.biSize <= 64)\n {\n /* enhanced Windows format with bit masks */\n\n if (!ReadOK (fd, buffer, Bitmap_File_Head.biSize - 4))\n {\n\n LOG(\"Error reading BMP file header\\n\");\n at_exception_fatal(&exp, \"Error reading BMP file header\");\n goto cleanup;\n }\n\n Bitmap_Head.biWidth = ToL(&buffer[0x00]); /* 12 */\n Bitmap_Head.biHeight = ToL(&buffer[0x04]); /* 16 */\n Bitmap_Head.biPlanes = ToS(&buffer[0x08]); /* 1A */\n Bitmap_Head.biBitCnt = ToS(&buffer[0x0A]); /* 1C */\n Bitmap_Head.biCompr = ToL(&buffer[0x0C]); /* 1E */\n Bitmap_Head.biSizeIm = ToL(&buffer[0x10]); /* 22 */\n Bitmap_Head.biXPels = ToL(&buffer[0x14]); /* 26 */\n Bitmap_Head.biYPels = ToL(&buffer[0x18]); /* 2A */\n Bitmap_Head.biClrUsed = ToL(&buffer[0x1C]); /* 2E */\n Bitmap_Head.biClrImp = ToL(&buffer[0x20]); /* 32 */\n Bitmap_Head.masks[0] = ToL(&buffer[0x24]); /* 36 */\n Bitmap_Head.masks[1] = ToL(&buffer[0x28]); /* 3A */\n Bitmap_Head.masks[2] = ToL(&buffer[0x2C]); /* 3E */\n Bitmap_Head.masks[3] = ToL(&buffer[0x30]); /* 42 */\n\n Maps = 4;\n ReadChannelMasks(&Bitmap_Head.masks[0], masks, 4);\n }\n else if (Bitmap_File_Head.biSize == 108 ||\n Bitmap_File_Head.biSize == 124)\n {\n /* BMP Version 4 or 5 */\n\n if (!ReadOK(fd, buffer, Bitmap_File_Head.biSize - 4))\n {\n\t LOG(\"Error reading BMP file header\\n\");\n\t at_exception_fatal(&exp, \"Error reading BMP file header\");\n\t goto cleanup;\n }\n\n Bitmap_Head.biWidth = ToL(&buffer[0x00]);\n Bitmap_Head.biHeight = ToL(&buffer[0x04]);\n Bitmap_Head.biPlanes = ToS(&buffer[0x08]);\n Bitmap_Head.biBitCnt = ToS(&buffer[0x0A]);\n Bitmap_Head.biCompr = ToL(&buffer[0x0C]);\n Bitmap_Head.biSizeIm = ToL(&buffer[0x10]);\n Bitmap_Head.biXPels = ToL(&buffer[0x14]);\n Bitmap_Head.biYPels = ToL(&buffer[0x18]);\n Bitmap_Head.biClrUsed = ToL(&buffer[0x1C]);\n Bitmap_Head.biClrImp = ToL(&buffer[0x20]);\n Bitmap_Head.masks[0] = ToL(&buffer[0x24]);\n Bitmap_Head.masks[1] = ToL(&buffer[0x28]);\n Bitmap_Head.masks[2] = ToL(&buffer[0x2C]);\n Bitmap_Head.masks[3] = ToL(&buffer[0x30]);\n\n Maps = 4;\n\n if (Bitmap_Head.biCompr == BI_BITFIELDS)\n {\n\t ReadChannelMasks(&Bitmap_Head.masks[0], masks, 4);\n }\n else if (Bitmap_Head.biCompr == BI_RGB)\n {\n\t setMasksDefault(Bitmap_Head.biBitCnt, masks);\n }\n } else {\n LOG(\"Error reading BMP file header\\n\");\n at_exception_fatal(&exp, \"Error reading BMP file header\");\n goto cleanup;\n }\n\n /* Valid options 1, 4, 8, 16, 24, 32 */\n /* 16 is awful, we should probably shoot whoever invented it */\n\n switch (Bitmap_Head.biBitCnt)\n {\n case 1:\n case 2:\n case 4:\n case 8:\n case 16:\n case 24:\n case 32:\n\t break;\n default:\n\t LOG(\"%s is not a valid BMP file\", filename);\n\t at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t goto cleanup;\n }\n\n /* There should be some colors used! */\n\n ColormapSize = (Bitmap_File_Head.bfOffs - Bitmap_File_Head.biSize - 14) / Maps;\n\n if ((Bitmap_Head.biClrUsed == 0) &&\n (Bitmap_Head.biBitCnt <= 8))\n {\n\t ColormapSize = Bitmap_Head.biClrUsed = 1 << Bitmap_Head.biBitCnt;\n }\n\n if (ColormapSize > 256)\n ColormapSize = 256;\n\n /* Sanity checks */\n\n if (Bitmap_Head.biHeight == 0 ||\n\t Bitmap_Head.biWidth == 0)\n {\n\t LOG(\"%s is not a valid BMP file\", filename);\n\t at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t goto cleanup;\n }\n\n /* biHeight may be negative, but -2147483648 is dangerous because:\n\t -2147483648 == -(-2147483648) */\n if (Bitmap_Head.biWidth < 0 ||\n\t Bitmap_Head.biHeight == -2147483648)\n {\n\t LOG(\"%s is not a valid BMP file\", filename);\n\t at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t goto cleanup;\n }\n\n if (Bitmap_Head.biPlanes != 1)\n {\n\t LOG(\"%s is not a valid BMP file\", filename);\n\t at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t goto cleanup;\n }\n\n if (Bitmap_Head.biClrUsed > 256 &&\n\t Bitmap_Head.biBitCnt <= 8)\n {\n\t LOG(\"%s is not a valid BMP file\", filename);\n\t at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t goto cleanup;\n }\n\n /* protect against integer overflows caused by malicious BMPs */\n /* use divisions in comparisons to avoid type overflows */\n\n if (((unsigned long)Bitmap_Head.biWidth) > (unsigned int)0x7fffffff / Bitmap_Head.biBitCnt ||\n\t ((unsigned long)Bitmap_Head.biWidth) > ((unsigned int)0x7fffffff /abs(Bitmap_Head.biHeight)) / 4)\n {\n\t LOG(\"%s is not a valid BMP file\", filename);\n\t at_exception_fatal(&exp, \"bmp: invalid input file\");\n\t goto cleanup;\n }\n\n /* Windows and OS/2 declare filler so that rows are a multiple of\n * word length (32 bits == 4 bytes)\n */\n \n unsigned long overflowTest = Bitmap_Head.biWidth * Bitmap_Head.biBitCnt;\n if (overflowTest / Bitmap_Head.biWidth != Bitmap_Head.biBitCnt) {\n LOG(\"Error reading BMP file header. Width is too large\\n\");\n at_exception_fatal(&exp, \"Error reading BMP file header. Width is too large\");\n goto cleanup;\n }\n\n rowbytes = ((Bitmap_Head.biWidth * Bitmap_Head.biBitCnt - 1) / 32) * 4 + 4;\n\n#ifdef DEBUG\n printf(\"\\nSize: %u, Colors: %u, Bits: %u, Width: %u, Height: %u, Comp: %u, Zeile: %u\\n\", Bitmap_File_Head.bfSize, Bitmap_Head.biClrUsed, Bitmap_Head.biBitCnt, Bitmap_Head.biWidth, Bitmap_Head.biHeight, Bitmap_Head.biCompr, rowbytes);\n#endif\n\n\n if (Bitmap_Head.biBitCnt <= 8)\n {\n#ifdef DEBUG\n printf(\"Colormap read\\n\");\n#endif\n\t /* Get the Colormap */\n\t if (!ReadColorMap(fd, ColorMap, ColormapSize, Maps, &Grey, &exp))\n\t\t goto cleanup;\n }\n\n fseek(fd, Bitmap_File_Head.bfOffs, SEEK_SET);\n\n /* Get the Image and return the ID or -1 on error */\n image_storage = ReadImage(fd, \n\tBitmap_Head.biWidth, Bitmap_Head.biHeight,\n\tColorMap,\n Bitmap_Head.biClrUsed,\n\tBitmap_Head.biBitCnt, Bitmap_Head.biCompr, rowbytes,\n Grey,\n\tmasks,\n\t&exp);\n\n image = at_bitmap_init(image_storage, (unsigned short)Bitmap_Head.biWidth, (unsigned short)Bitmap_Head.biHeight, Grey ? 1 : 3);\ncleanup:\n fclose(fd);\n return (image);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'input-bmp: Increase header buffer in some cases\n\nSigned-off-by: Peter Lemenkov '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int dns_stream_complete(DnsStream *s, int error) {\n assert(s);\n\n#if ENABLE_DNS_OVER_TLS\n if (s->encrypted) {\n int r;\n\n r = dnstls_stream_shutdown(s, error);\n if (r != -EAGAIN)\n dns_stream_stop(s);\n } else\n#endif\n dns_stream_stop(s);\n\n if (s->complete)\n s->complete(s, error);\n else /* the default action if no completion function is set is to close the stream */\n dns_stream_unref(s);\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-703'], 'message': 'resolved: pin stream while calling callbacks for it\n\nThese callbacks might unref the stream, but we still have to access it,\nlet's hence ref it explicitly.\n\nMaybe fixes: #10725'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int vc_allocate(unsigned int currcons)\t/* return 0 on success */\n{\n\tstruct vt_notifier_param param;\n\tstruct vc_data *vc;\n\n\tWARN_CONSOLE_UNLOCKED();\n\n\tif (currcons >= MAX_NR_CONSOLES)\n\t\treturn -ENXIO;\n\n\tif (vc_cons[currcons].d)\n\t\treturn 0;\n\n\t/* due to the granularity of kmalloc, we waste some memory here */\n\t/* the alloc is done in two steps, to optimize the common situation\n\t of a 25x80 console (structsize=216, screenbuf_size=4000) */\n\t/* although the numbers above are not valid since long ago, the\n\t point is still up-to-date and the comment still has its value\n\t even if only as a historical artifact. --mj, July 1998 */\n\tparam.vc = vc = kzalloc(sizeof(struct vc_data), GFP_KERNEL);\n\tif (!vc)\n\t\treturn -ENOMEM;\n\n\tvc_cons[currcons].d = vc;\n\ttty_port_init(&vc->port);\n\tINIT_WORK(&vc_cons[currcons].SAK_work, vc_SAK);\n\n\tvisual_init(vc, currcons, 1);\n\n\tif (!*vc->vc_uni_pagedir_loc)\n\t\tcon_set_default_unimap(vc);\n\n\tvc->vc_screenbuf = kzalloc(vc->vc_screenbuf_size, GFP_KERNEL);\n\tif (!vc->vc_screenbuf)\n\t\tgoto err_free;\n\n\t/* If no drivers have overridden us and the user didn't pass a\n\t boot option, default to displaying the cursor */\n\tif (global_cursor_default == -1)\n\t\tglobal_cursor_default = 1;\n\n\tvc_init(vc, vc->vc_rows, vc->vc_cols, 1);\n\tvcs_make_sysfs(currcons);\n\tatomic_notifier_call_chain(&vt_notifier_list, VT_ALLOCATE, ¶m);\n\n\treturn 0;\nerr_free:\n\tvisual_deinit(vc);\n\tkfree(vc);\n\tvc_cons[currcons].d = NULL;\n\treturn -ENOMEM;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-362'], 'message': 'vt: vt_ioctl: fix VT_DISALLOCATE freeing in-use virtual console\n\nThe VT_DISALLOCATE ioctl can free a virtual console while tty_release()\nis still running, causing a use-after-free in con_shutdown(). This\noccurs because VT_DISALLOCATE considers a virtual console's\n'struct vc_data' to be unused as soon as the corresponding tty's\nrefcount hits 0. But actually it may be still being closed.\n\nFix this by making vc_data be reference-counted via the embedded\n'struct tty_port'. A newly allocated virtual console has refcount 1.\nOpening it for the first time increments the refcount to 2. Closing it\nfor the last time decrements the refcount (in tty_operations::cleanup()\nso that it happens late enough), as does VT_DISALLOCATE.\n\nReproducer:\n\t#include \n\t#include \n\t#include \n\t#include \n\n\tint main()\n\t{\n\t\tif (fork()) {\n\t\t\tfor (;;)\n\t\t\t\tclose(open(\"/dev/tty5\", O_RDWR));\n\t\t} else {\n\t\t\tint fd = open(\"/dev/tty10\", O_RDWR);\n\n\t\t\tfor (;;)\n\t\t\t\tioctl(fd, VT_DISALLOCATE, 5);\n\t\t}\n\t}\n\nKASAN report:\n\tBUG: KASAN: use-after-free in con_shutdown+0x76/0x80 drivers/tty/vt/vt.c:3278\n\tWrite of size 8 at addr ffff88806a4ec108 by task syz_vt/129\n\n\tCPU: 0 PID: 129 Comm: syz_vt Not tainted 5.6.0-rc2 #11\n\tHardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS ?-20191223_100556-anatol 04/01/2014\n\tCall Trace:\n\t [...]\n\t con_shutdown+0x76/0x80 drivers/tty/vt/vt.c:3278\n\t release_tty+0xa8/0x410 drivers/tty/tty_io.c:1514\n\t tty_release_struct+0x34/0x50 drivers/tty/tty_io.c:1629\n\t tty_release+0x984/0xed0 drivers/tty/tty_io.c:1789\n\t [...]\n\n\tAllocated by task 129:\n\t [...]\n\t kzalloc include/linux/slab.h:669 [inline]\n\t vc_allocate drivers/tty/vt/vt.c:1085 [inline]\n\t vc_allocate+0x1ac/0x680 drivers/tty/vt/vt.c:1066\n\t con_install+0x4d/0x3f0 drivers/tty/vt/vt.c:3229\n\t tty_driver_install_tty drivers/tty/tty_io.c:1228 [inline]\n\t tty_init_dev+0x94/0x350 drivers/tty/tty_io.c:1341\n\t tty_open_by_driver drivers/tty/tty_io.c:1987 [inline]\n\t tty_open+0x3ca/0xb30 drivers/tty/tty_io.c:2035\n\t [...]\n\n\tFreed by task 130:\n\t [...]\n\t kfree+0xbf/0x1e0 mm/slab.c:3757\n\t vt_disallocate drivers/tty/vt/vt_ioctl.c:300 [inline]\n\t vt_ioctl+0x16dc/0x1e30 drivers/tty/vt/vt_ioctl.c:818\n\t tty_ioctl+0x9db/0x11b0 drivers/tty/tty_io.c:2660\n\t [...]\n\nFixes: 4001d7b7fc27 (\"vt: push down the tty lock so we can see what is left to tackle\")\nCc: # v3.4+\nReported-by: syzbot+522643ab5729b0421998@syzkaller.appspotmail.com\nAcked-by: Jiri Slaby \nSigned-off-by: Eric Biggers \nLink: https://lore.kernel.org/r/20200322034305.210082-2-ebiggers@kernel.org\nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: mesh_state_create(struct module_env* env, struct query_info* qinfo,\n\tstruct respip_client_info* cinfo, uint16_t qflags, int prime,\n\tint valrec)\n{\n\tstruct regional* region = alloc_reg_obtain(env->alloc);\n\tstruct mesh_state* mstate;\n\tint i;\n\tif(!region)\n\t\treturn NULL;\n\tmstate = (struct mesh_state*)regional_alloc(region, \n\t\tsizeof(struct mesh_state));\n\tif(!mstate) {\n\t\talloc_reg_release(env->alloc, region);\n\t\treturn NULL;\n\t}\n\tmemset(mstate, 0, sizeof(*mstate));\n\tmstate->node = *RBTREE_NULL;\n\tmstate->run_node = *RBTREE_NULL;\n\tmstate->node.key = mstate;\n\tmstate->run_node.key = mstate;\n\tmstate->reply_list = NULL;\n\tmstate->list_select = mesh_no_list;\n\tmstate->replies_sent = 0;\n\trbtree_init(&mstate->super_set, &mesh_state_ref_compare);\n\trbtree_init(&mstate->sub_set, &mesh_state_ref_compare);\n\tmstate->num_activated = 0;\n\tmstate->unique = NULL;\n\t/* init module qstate */\n\tmstate->s.qinfo.qtype = qinfo->qtype;\n\tmstate->s.qinfo.qclass = qinfo->qclass;\n\tmstate->s.qinfo.local_alias = NULL;\n\tmstate->s.qinfo.qname_len = qinfo->qname_len;\n\tmstate->s.qinfo.qname = regional_alloc_init(region, qinfo->qname,\n\t\tqinfo->qname_len);\n\tif(!mstate->s.qinfo.qname) {\n\t\talloc_reg_release(env->alloc, region);\n\t\treturn NULL;\n\t}\n\tif(cinfo) {\n\t\tmstate->s.client_info = regional_alloc_init(region, cinfo,\n\t\t\tsizeof(*cinfo));\n\t\tif(!mstate->s.client_info) {\n\t\t\talloc_reg_release(env->alloc, region);\n\t\t\treturn NULL;\n\t\t}\n\t}\n\t/* remove all weird bits from qflags */\n\tmstate->s.query_flags = (qflags & (BIT_RD|BIT_CD));\n\tmstate->s.is_priming = prime;\n\tmstate->s.is_valrec = valrec;\n\tmstate->s.reply = NULL;\n\tmstate->s.region = region;\n\tmstate->s.curmod = 0;\n\tmstate->s.return_msg = 0;\n\tmstate->s.return_rcode = LDNS_RCODE_NOERROR;\n\tmstate->s.env = env;\n\tmstate->s.mesh_info = mstate;\n\tmstate->s.prefetch_leeway = 0;\n\tmstate->s.serve_expired_data = NULL;\n\tmstate->s.no_cache_lookup = 0;\n\tmstate->s.no_cache_store = 0;\n\tmstate->s.need_refetch = 0;\n\tmstate->s.was_ratelimited = 0;\n\n\t/* init modules */\n\tfor(i=0; imesh->mods.num; i++) {\n\t\tmstate->s.minfo[i] = NULL;\n\t\tmstate->s.ext_state[i] = module_state_initial;\n\t}\n\t/* init edns option lists */\n\tmstate->s.edns_opts_front_in = NULL;\n\tmstate->s.edns_opts_back_out = NULL;\n\tmstate->s.edns_opts_back_in = NULL;\n\tmstate->s.edns_opts_front_out = NULL;\n\n\treturn mstate;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-613', 'CWE-703'], 'message': '- Fix the novel ghost domain issues CVE-2022-30698 and CVE-2022-30699.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: iter_dns_store(struct module_env* env, struct query_info* msgqinf,\n\tstruct reply_info* msgrep, int is_referral, time_t leeway, int pside,\n\tstruct regional* region, uint16_t flags)\n{\n\tif(!dns_cache_store(env, msgqinf, msgrep, is_referral, leeway,\n\t\tpside, region, flags))\n\t\tlog_err(\"out of memory: cannot store data in cache\");\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-613', 'CWE-703'], 'message': '- Fix the novel ghost domain issues CVE-2022-30698 and CVE-2022-30699.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int storeQueryInCache(struct module_qstate* qstate, struct query_info* qinfo,\n\tstruct reply_info* msgrep, int is_referral)\n{\n\tif (!msgrep)\n\t\treturn 0;\n\n\t/* authoritative answer can't be stored in cache */\n\tif (msgrep->authoritative) {\n\t\tPyErr_SetString(PyExc_ValueError,\n\t\t\t\"Authoritative answer can't be stored\");\n\t\treturn 0;\n\t}\n\n\treturn dns_cache_store(qstate->env, qinfo, msgrep, is_referral,\n\t\tqstate->prefetch_leeway, 0, NULL, qstate->query_flags);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-613', 'CWE-703'], 'message': '- Fix the novel ghost domain issues CVE-2022-30698 and CVE-2022-30699.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: LoadPage::LoadPage():\n\tjsdelay(200),\n\twindowStatus(\"\"),\n\tzoomFactor(1.0),\n\trepeatCustomHeaders(false),\n\tblockLocalFileAccess(false),\n\tstopSlowScripts(true),\n\tdebugJavascript(false),\n\tloadErrorHandling(abort),\n\tmediaLoadErrorHandling(ignore),\n\tcacheDir(\"\"),\n\tproxyHostNameLookup(false) {}; ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-22'], 'message': 'BREAKING CHANGE: block local filesystem access by default\n\nfixes #4536'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: init_evalarg(evalarg_T *evalarg)\n{\n CLEAR_POINTER(evalarg);\n ga_init2(&evalarg->eval_tofree_ga, sizeof(char_u *), 20);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'patch 9.0.0225: using freed memory with multiple line breaks in expression\n\nProblem: Using freed memory with multiple line breaks in expression.\nSolution: Free eval_tofree later.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int psi_fop_release(struct inode *inode, struct file *file)\n{\n\tstruct seq_file *seq = file->private_data;\n\n\tpsi_trigger_replace(&seq->private, NULL);\n\treturn single_release(inode, file);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'psi: Fix uaf issue when psi trigger is destroyed while being polled\n\nWith write operation on psi files replacing old trigger with a new one,\nthe lifetime of its waitqueue is totally arbitrary. Overwriting an\nexisting trigger causes its waitqueue to be freed and pending poll()\nwill stumble on trigger->event_wait which was destroyed.\nFix this by disallowing to redefine an existing psi trigger. If a write\noperation is used on a file descriptor with an already existing psi\ntrigger, the operation will fail with EBUSY error.\nAlso bypass a check for psi_disabled in the psi_trigger_destroy as the\nflag can be flipped after the trigger is created, leading to a memory\nleak.\n\nFixes: 0e94682b73bf (\"psi: introduce psi monitor\")\nReported-by: syzbot+cdb5dd11c97cc532efad@syzkaller.appspotmail.com\nSuggested-by: Linus Torvalds \nAnalyzed-by: Eric Biggers \nSigned-off-by: Suren Baghdasaryan \nSigned-off-by: Peter Zijlstra (Intel) \nReviewed-by: Eric Biggers \nAcked-by: Johannes Weiner \nCc: stable@vger.kernel.org\nLink: https://lore.kernel.org/r/20220111232309.1786347-1-surenb@google.com'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static ssize_t prevent_suspend_time_ms_show(struct device *dev,\n\t\t\t\t\t struct device_attribute *attr,\n\t\t\t\t\t char *buf)\n{\n\tstruct wakeup_source *ws = dev_get_drvdata(dev);\n\tktime_t prevent_sleep_time = ws->prevent_sleep_time;\n\n\tif (ws->active && ws->autosleep_enabled) {\n\t\tprevent_sleep_time = ktime_add(prevent_sleep_time,\n\t\t\tktime_sub(ktime_get(), ws->start_prevent_time));\n\t}\n\treturn sprintf(buf, \"%lld\\n\", ktime_to_ms(prevent_sleep_time));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'drivers core: Use sysfs_emit and sysfs_emit_at for show(device *...) functions\n\nConvert the various sprintf fmaily calls in sysfs device show functions\nto sysfs_emit and sysfs_emit_at for PAGE_SIZE buffer safety.\n\nDone with:\n\n$ spatch -sp-file sysfs_emit_dev.cocci --in-place --max-width=80 .\n\nAnd cocci script:\n\n$ cat sysfs_emit_dev.cocci\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tsprintf(buf,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tsnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tscnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nexpression chr;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tstrcpy(buf, chr);\n+\tsysfs_emit(buf, chr);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tsprintf(buf,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tsnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tscnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n-\tlen += scnprintf(buf + len, PAGE_SIZE - len,\n+\tlen += sysfs_emit_at(buf, len,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nexpression chr;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t...\n-\tstrcpy(buf, chr);\n-\treturn strlen(buf);\n+\treturn sysfs_emit(buf, chr);\n}\n\nSigned-off-by: Joe Perches \nLink: https://lore.kernel.org/r/3d033c33056d88bbe34d4ddb62afd05ee166ab9a.1600285923.git.joe@perches.com\nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static ssize_t write_policy_show(struct device *dev,\n\t\t\t\t struct device_attribute *attr, char *buf)\n{\n\tstruct cacheinfo *this_leaf = dev_get_drvdata(dev);\n\tunsigned int ci_attr = this_leaf->attributes;\n\tint n = 0;\n\n\tif (ci_attr & CACHE_WRITE_THROUGH)\n\t\tn = sprintf(buf, \"WriteThrough\\n\");\n\telse if (ci_attr & CACHE_WRITE_BACK)\n\t\tn = sprintf(buf, \"WriteBack\\n\");\n\treturn n;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'drivers core: Use sysfs_emit and sysfs_emit_at for show(device *...) functions\n\nConvert the various sprintf fmaily calls in sysfs device show functions\nto sysfs_emit and sysfs_emit_at for PAGE_SIZE buffer safety.\n\nDone with:\n\n$ spatch -sp-file sysfs_emit_dev.cocci --in-place --max-width=80 .\n\nAnd cocci script:\n\n$ cat sysfs_emit_dev.cocci\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tsprintf(buf,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tsnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tscnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nexpression chr;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tstrcpy(buf, chr);\n+\tsysfs_emit(buf, chr);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tsprintf(buf,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tsnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tscnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n-\tlen += scnprintf(buf + len, PAGE_SIZE - len,\n+\tlen += sysfs_emit_at(buf, len,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nexpression chr;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t...\n-\tstrcpy(buf, chr);\n-\treturn strlen(buf);\n+\treturn sysfs_emit(buf, chr);\n}\n\nSigned-off-by: Joe Perches \nLink: https://lore.kernel.org/r/3d033c33056d88bbe34d4ddb62afd05ee166ab9a.1600285923.git.joe@perches.com\nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static ssize_t total_time_ms_show(struct device *dev,\n\t\t\t\t struct device_attribute *attr, char *buf)\n{\n\tstruct wakeup_source *ws = dev_get_drvdata(dev);\n\tktime_t active_time;\n\tktime_t total_time = ws->total_time;\n\n\tif (ws->active) {\n\t\tactive_time = ktime_sub(ktime_get(), ws->last_time);\n\t\ttotal_time = ktime_add(total_time, active_time);\n\t}\n\treturn sprintf(buf, \"%lld\\n\", ktime_to_ms(total_time));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'drivers core: Use sysfs_emit and sysfs_emit_at for show(device *...) functions\n\nConvert the various sprintf fmaily calls in sysfs device show functions\nto sysfs_emit and sysfs_emit_at for PAGE_SIZE buffer safety.\n\nDone with:\n\n$ spatch -sp-file sysfs_emit_dev.cocci --in-place --max-width=80 .\n\nAnd cocci script:\n\n$ cat sysfs_emit_dev.cocci\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tsprintf(buf,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tsnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tscnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nexpression chr;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tstrcpy(buf, chr);\n+\tsysfs_emit(buf, chr);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tsprintf(buf,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tsnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tscnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n-\tlen += scnprintf(buf + len, PAGE_SIZE - len,\n+\tlen += sysfs_emit_at(buf, len,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nexpression chr;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t...\n-\tstrcpy(buf, chr);\n-\treturn strlen(buf);\n+\treturn sysfs_emit(buf, chr);\n}\n\nSigned-off-by: Joe Perches \nLink: https://lore.kernel.org/r/3d033c33056d88bbe34d4ddb62afd05ee166ab9a.1600285923.git.joe@perches.com\nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ssize_t __weak cpu_show_l1tf(struct device *dev,\n\t\t\t struct device_attribute *attr, char *buf)\n{\n\treturn sprintf(buf, \"Not affected\\n\");\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'drivers core: Use sysfs_emit and sysfs_emit_at for show(device *...) functions\n\nConvert the various sprintf fmaily calls in sysfs device show functions\nto sysfs_emit and sysfs_emit_at for PAGE_SIZE buffer safety.\n\nDone with:\n\n$ spatch -sp-file sysfs_emit_dev.cocci --in-place --max-width=80 .\n\nAnd cocci script:\n\n$ cat sysfs_emit_dev.cocci\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tsprintf(buf,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tsnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tscnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nexpression chr;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tstrcpy(buf, chr);\n+\tsysfs_emit(buf, chr);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tsprintf(buf,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tsnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tscnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n-\tlen += scnprintf(buf + len, PAGE_SIZE - len,\n+\tlen += sysfs_emit_at(buf, len,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nexpression chr;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t...\n-\tstrcpy(buf, chr);\n-\treturn strlen(buf);\n+\treturn sysfs_emit(buf, chr);\n}\n\nSigned-off-by: Joe Perches \nLink: https://lore.kernel.org/r/3d033c33056d88bbe34d4ddb62afd05ee166ab9a.1600285923.git.joe@perches.com\nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static ssize_t autosuspend_delay_ms_show(struct device *dev,\n\t\tstruct device_attribute *attr, char *buf)\n{\n\tif (!dev->power.use_autosuspend)\n\t\treturn -EIO;\n\treturn sprintf(buf, \"%d\\n\", dev->power.autosuspend_delay);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'drivers core: Use sysfs_emit and sysfs_emit_at for show(device *...) functions\n\nConvert the various sprintf fmaily calls in sysfs device show functions\nto sysfs_emit and sysfs_emit_at for PAGE_SIZE buffer safety.\n\nDone with:\n\n$ spatch -sp-file sysfs_emit_dev.cocci --in-place --max-width=80 .\n\nAnd cocci script:\n\n$ cat sysfs_emit_dev.cocci\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tsprintf(buf,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tsnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tscnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nexpression chr;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tstrcpy(buf, chr);\n+\tsysfs_emit(buf, chr);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tsprintf(buf,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tsnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tscnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n-\tlen += scnprintf(buf + len, PAGE_SIZE - len,\n+\tlen += sysfs_emit_at(buf, len,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nexpression chr;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t...\n-\tstrcpy(buf, chr);\n-\treturn strlen(buf);\n+\treturn sysfs_emit(buf, chr);\n}\n\nSigned-off-by: Joe Perches \nLink: https://lore.kernel.org/r/3d033c33056d88bbe34d4ddb62afd05ee166ab9a.1600285923.git.joe@perches.com\nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static ssize_t runtime_enabled_show(struct device *dev,\n\t\t\t\t struct device_attribute *attr, char *buf)\n{\n\tif (dev->power.disable_depth && (dev->power.runtime_auto == false))\n\t\treturn sprintf(buf, \"disabled & forbidden\\n\");\n\tif (dev->power.disable_depth)\n\t\treturn sprintf(buf, \"disabled\\n\");\n\tif (dev->power.runtime_auto == false)\n\t\treturn sprintf(buf, \"forbidden\\n\");\n\treturn sprintf(buf, \"enabled\\n\");\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'drivers core: Use sysfs_emit and sysfs_emit_at for show(device *...) functions\n\nConvert the various sprintf fmaily calls in sysfs device show functions\nto sysfs_emit and sysfs_emit_at for PAGE_SIZE buffer safety.\n\nDone with:\n\n$ spatch -sp-file sysfs_emit_dev.cocci --in-place --max-width=80 .\n\nAnd cocci script:\n\n$ cat sysfs_emit_dev.cocci\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tsprintf(buf,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tsnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tscnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nexpression chr;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\treturn\n-\tstrcpy(buf, chr);\n+\tsysfs_emit(buf, chr);\n\t...>\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tsprintf(buf,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tsnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n\tlen =\n-\tscnprintf(buf, PAGE_SIZE,\n+\tsysfs_emit(buf,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nidentifier len;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t<...\n-\tlen += scnprintf(buf + len, PAGE_SIZE - len,\n+\tlen += sysfs_emit_at(buf, len,\n\t...);\n\t...>\n\treturn len;\n}\n\n@@\nidentifier d_show;\nidentifier dev, attr, buf;\nexpression chr;\n@@\n\nssize_t d_show(struct device *dev, struct device_attribute *attr, char *buf)\n{\n\t...\n-\tstrcpy(buf, chr);\n-\treturn strlen(buf);\n+\treturn sysfs_emit(buf, chr);\n}\n\nSigned-off-by: Joe Perches \nLink: https://lore.kernel.org/r/3d033c33056d88bbe34d4ddb62afd05ee166ab9a.1600285923.git.joe@perches.com\nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void new_huffman_tree(x3f_hufftree_t *HTP, int bits)\n{\n int leaves = 1 << bits;\n\n HTP->free_node_index = 0;\n HTP->nodes = (x3f_huffnode_t *)calloc(1, HUF_TREE_MAX_NODES(leaves) *\n sizeof(x3f_huffnode_t));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'X3F: check huffman tree size'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void LibRaw::parseSonySRF(unsigned len)\n{\n\n if ((len > 0xfffff) || (len == 0))\n return;\n\n INT64 save = ftell(ifp);\n INT64 offset =\n 0x0310c0 - save; /* for non-DNG this value normally is 0x8ddc */\n if (len < offset || offset < 0)\n return;\n INT64 decrypt_len = offset >> 2; /* master key offset value is the next\n un-encrypted metadata field after SRF0 */\n\n unsigned i, nWB;\n unsigned MasterKey, SRF2Key, RawDataKey;\n INT64 srf_offset, tag_offset, tag_data, tag_dataoffset;\n int tag_dataunitlen;\n uchar *srf_buf;\n short entries;\n unsigned tag_id, tag_type, tag_datalen;\n\n srf_buf = (uchar *)malloc(len);\n fread(srf_buf, len, 1, ifp);\n\n offset += srf_buf[offset] << 2;\n\n#define CHECKBUFFER_SGET4(offset) \\\n do \\\n { \\\n if ((((offset) + 4) > len) || ((offset) < 0)) \\\n goto restore_after_parseSonySRF; \\\n } while (0)\n\n#define CHECKBUFFER_SGET2(offset) \\\n do \\\n { \\\n if ( ((offset + 2) > len) || ((offset) < 0)) \\\n goto restore_after_parseSonySRF; \\\n } while (0)\n\n CHECKBUFFER_SGET4(offset);\n\n /* master key is stored in big endian */\n MasterKey = ((unsigned)srf_buf[offset] << 24) |\n ((unsigned)srf_buf[offset + 1] << 16) |\n ((unsigned)srf_buf[offset + 2] << 8) |\n (unsigned)srf_buf[offset + 3];\n\n /* skip SRF0 */\n srf_offset = 0;\n CHECKBUFFER_SGET2(srf_offset);\n entries = sget2(srf_buf + srf_offset);\n if (entries > 1000)\n goto restore_after_parseSonySRF;\n offset = srf_offset + 2;\n CHECKBUFFER_SGET4(offset);\n CHECKBUFFER_SGET4(offset + 12 * entries);\n srf_offset = sget4(srf_buf + offset + 12 * entries) -\n save; /* SRF0 ends with SRF1 abs. position */\n\n /* get SRF1, it has fixed 40 bytes length and contains keys to decode metadata\n * and raw data */\n if (srf_offset < 0 || decrypt_len < srf_offset / 4)\n goto restore_after_parseSonySRF;\n sony_decrypt((unsigned *)(srf_buf + srf_offset), decrypt_len - srf_offset / 4,\n 1, MasterKey);\n CHECKBUFFER_SGET2(srf_offset);\n entries = sget2(srf_buf + srf_offset);\n if (entries > 1000)\n goto restore_after_parseSonySRF;\n offset = srf_offset + 2;\n tag_offset = offset;\n\n while (entries--) {\n if (tiff_sget (save, srf_buf, len,\n &tag_offset, &tag_id, &tag_type, &tag_dataoffset,\n &tag_datalen, &tag_dataunitlen) == 0) {\n if (tag_id == 0x0000) {\n SRF2Key = sget4(srf_buf + tag_dataoffset);\n } else if (tag_id == 0x0001) {\n RawDataKey = sget4(srf_buf + tag_dataoffset);\n }\n } else goto restore_after_parseSonySRF;\n }\n offset = tag_offset;\n\n /* get SRF2 */\n CHECKBUFFER_SGET4(offset);\n srf_offset =\n sget4(srf_buf + offset) - save; /* SRFn ends with SRFn+1 position */\n if (srf_offset < 0 || decrypt_len < srf_offset / 4)\n goto restore_after_parseSonySRF;\n sony_decrypt((unsigned *)(srf_buf + srf_offset), decrypt_len - srf_offset / 4,\n 1, SRF2Key);\n CHECKBUFFER_SGET2(srf_offset);\n entries = sget2(srf_buf + srf_offset);\n if (entries > 1000)\n goto restore_after_parseSonySRF;\n offset = srf_offset + 2;\n tag_offset = offset;\n\n while (entries--) {\n if (tiff_sget (save, srf_buf, len,\n &tag_offset, &tag_id, &tag_type, &tag_dataoffset,\n &tag_datalen, &tag_dataunitlen) == 0) {\n if ((tag_id >= 0x00c0) && (tag_id <= 0x00ce)) {\n i = (tag_id - 0x00c0) % 3;\n nWB = (tag_id - 0x00c0) / 3;\n icWBC[Sony_SRF_wb_list[nWB]][i] = sget4(srf_buf + tag_dataoffset);\n if (i == 1) {\n icWBC[Sony_SRF_wb_list[nWB]][3] =\n icWBC[Sony_SRF_wb_list[nWB]][i];\n }\n } else if ((tag_id >= 0x00d0) && (tag_id <= 0x00d2)) {\n i = (tag_id - 0x00d0) % 3;\n cam_mul[i] = sget4(srf_buf + tag_dataoffset);\n if (i == 1) {\n cam_mul[3] = cam_mul[i];\n }\n } else switch (tag_id) {\n /*\n 0x0002 SRF6Offset\n 0x0003 SRFDataOffset (?)\n 0x0004 RawDataOffset\n 0x0005 RawDataLength\n */\n case 0x0043:\n ilm.MaxAp4MaxFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n break;\n case 0x0044:\n ilm.MaxAp4MinFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n break;\n case 0x0045:\n ilm.MinFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n break;\n case 0x0046:\n ilm.MaxFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n break;\n }\n } else goto restore_after_parseSonySRF;\n }\n offset = tag_offset;\n\nrestore_after_parseSonySRF:\n free(srf_buf);\n fseek(ifp, save, SEEK_SET);\n#undef CHECKBUFFER_SGET4\n#undef CHECKBUFFER_SGET2\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'additional checks in parseSonySRF\n\nparseSonySR2: buffer size check'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: h2v1_merged_upsample_565_internal(j_decompress_ptr cinfo, JSAMPIMAGE input_buf,\n JDIMENSION in_row_group_ctr,\n JSAMPARRAY output_buf)\n{\n my_upsample_ptr upsample = (my_upsample_ptr)cinfo->upsample;\n register int y, cred, cgreen, cblue;\n int cb, cr;\n register JSAMPROW outptr;\n JSAMPROW inptr0, inptr1, inptr2;\n JDIMENSION col;\n /* copy these pointers into registers if possible */\n register JSAMPLE *range_limit = cinfo->sample_range_limit;\n int *Crrtab = upsample->Cr_r_tab;\n int *Cbbtab = upsample->Cb_b_tab;\n JLONG *Crgtab = upsample->Cr_g_tab;\n JLONG *Cbgtab = upsample->Cb_g_tab;\n unsigned int r, g, b;\n JLONG rgb;\n SHIFT_TEMPS\n\n inptr0 = input_buf[0][in_row_group_ctr];\n inptr1 = input_buf[1][in_row_group_ctr];\n inptr2 = input_buf[2][in_row_group_ctr];\n outptr = output_buf[0];\n\n /* Loop for each pair of output pixels */\n for (col = cinfo->output_width >> 1; col > 0; col--) {\n /* Do the chroma part of the calculation */\n cb = GETJSAMPLE(*inptr1++);\n cr = GETJSAMPLE(*inptr2++);\n cred = Crrtab[cr];\n cgreen = (int)RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);\n cblue = Cbbtab[cb];\n\n /* Fetch 2 Y values and emit 2 pixels */\n y = GETJSAMPLE(*inptr0++);\n r = range_limit[y + cred];\n g = range_limit[y + cgreen];\n b = range_limit[y + cblue];\n rgb = PACK_SHORT_565(r, g, b);\n\n y = GETJSAMPLE(*inptr0++);\n r = range_limit[y + cred];\n g = range_limit[y + cgreen];\n b = range_limit[y + cblue];\n rgb = PACK_TWO_PIXELS(rgb, PACK_SHORT_565(r, g, b));\n\n WRITE_TWO_PIXELS(outptr, rgb);\n outptr += 4;\n }\n\n /* If image width is odd, do the last output column separately */\n if (cinfo->output_width & 1) {\n cb = GETJSAMPLE(*inptr1);\n cr = GETJSAMPLE(*inptr2);\n cred = Crrtab[cr];\n cgreen = (int)RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);\n cblue = Cbbtab[cb];\n y = GETJSAMPLE(*inptr0);\n r = range_limit[y + cred];\n g = range_limit[y + cgreen];\n b = range_limit[y + cblue];\n rgb = PACK_SHORT_565(r, g, b);\n *(INT16 *)outptr = (INT16)rgb;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fix jpeg_skip_scanlines() segfault w/merged upsamp\n\nThe additional segfault mentioned in #244 was due to the fact that\nthe merged upsamplers use a different private structure than the\nnon-merged upsamplers. jpeg_skip_scanlines() was assuming the latter, so\nwhen merged upsampling was enabled, jpeg_skip_scanlines() clobbered one\nof the IDCT method pointers in the merged upsampler's private structure.\n\nFor reasons unknown, the test image in #441 did not encounter this\nsegfault (too small?), but it encountered an issue similar to the one\nfixed in 5bc43c7821df982f65aa1c738f67fbf7cba8bd69, whereby it was\nnecessary to set up a dummy postprocessing function in\nread_and_discard_scanlines() when merged upsampling was enabled.\nFailing to do so caused either a segfault in merged_2v_upsample() (due\nto a NULL pointer being passed to jcopy_sample_rows()) or an error\n(\"Corrupt JPEG data: premature end of data segment\"), depending on the\nnumber of scanlines skipped and whether the first scanline skipped was\nan odd- or even-numbered row.\n\nFixes #441\nFixes #244 (for real this time)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: qf_jump_open_window(\n\tqf_info_T\t*qi,\n\tqfline_T\t*qf_ptr,\n\tint\t\tnewwin,\n\tint\t\t*opened_window)\n{\n qf_list_T\t*qfl = qf_get_curlist(qi);\n int\t\told_changedtick = qfl->qf_changedtick;\n int\t\told_qf_curlist = qi->qf_curlist;\n qfltype_T\tqfl_type = qfl->qfl_type;\n\n // For \":helpgrep\" find a help window or open one.\n if (qf_ptr->qf_type == 1 && (!bt_help(curwin->w_buffer)\n\t\t\t\t\t\t || cmdmod.cmod_tab != 0))\n\tif (jump_to_help_window(qi, newwin, opened_window) == FAIL)\n\t return FAIL;\n if (old_qf_curlist != qi->qf_curlist\n\t || old_changedtick != qfl->qf_changedtick\n\t || !is_qf_entry_present(qfl, qf_ptr))\n {\n\tif (qfl_type == QFLT_QUICKFIX)\n\t emsg(_(e_current_quickfix_list_was_changed));\n\telse\n\t emsg(_(e_current_location_list_was_changed));\n\treturn FAIL;\n }\n\n // If currently in the quickfix window, find another window to show the\n // file in.\n if (bt_quickfix(curbuf) && !*opened_window)\n {\n\t// If there is no file specified, we don't know where to go.\n\t// But do advance, otherwise \":cn\" gets stuck.\n\tif (qf_ptr->qf_fnum == 0)\n\t return NOTDONE;\n\n\tif (qf_jump_to_usable_window(qf_ptr->qf_fnum, newwin,\n\t\t\t\t\t\topened_window) == FAIL)\n\t return FAIL;\n }\n if (old_qf_curlist != qi->qf_curlist\n\t || old_changedtick != qfl->qf_changedtick\n\t || !is_qf_entry_present(qfl, qf_ptr))\n {\n\tif (qfl_type == QFLT_QUICKFIX)\n\t emsg(_(e_current_quickfix_list_was_changed));\n\telse\n\t emsg(_(e_current_location_list_was_changed));\n\treturn FAIL;\n }\n\n return OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'patch 9.0.0286: using freed memory when location list changed in autocmd\n\nProblem: Using freed memory when location list changed in autocmd.\nSolution: Return QF_ABORT and handle it. (Yegappan Lakshmanan,\n closes #10993)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int vcpu_run(struct kvm_vcpu *vcpu)\n{\n\tint r;\n\n\tvcpu->arch.l1tf_flush_l1d = true;\n\n\tfor (;;) {\n\t\tif (kvm_vcpu_running(vcpu)) {\n\t\t\tr = vcpu_enter_guest(vcpu);\n\t\t} else {\n\t\t\tr = vcpu_block(vcpu);\n\t\t}\n\n\t\tif (r <= 0)\n\t\t\tbreak;\n\n\t\tkvm_clear_request(KVM_REQ_UNBLOCK, vcpu);\n\t\tif (kvm_xen_has_pending_events(vcpu))\n\t\t\tkvm_xen_inject_pending_events(vcpu);\n\n\t\tif (kvm_cpu_has_pending_timer(vcpu))\n\t\t\tkvm_inject_pending_timer_irqs(vcpu);\n\n\t\tif (dm_request_for_irq_injection(vcpu) &&\n\t\t\tkvm_vcpu_ready_for_interrupt_injection(vcpu)) {\n\t\t\tr = 0;\n\t\t\tvcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;\n\t\t\t++vcpu->stat.request_irq_exits;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (__xfer_to_guest_mode_work_pending()) {\n\t\t\tkvm_vcpu_srcu_read_unlock(vcpu);\n\t\t\tr = xfer_to_guest_mode_handle_work(vcpu);\n\t\t\tkvm_vcpu_srcu_read_lock(vcpu);\n\t\t\tif (r)\n\t\t\t\treturn r;\n\t\t}\n\t}\n\n\treturn r;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'KVM: x86: do not report a vCPU as preempted outside instruction boundaries\n\nIf a vCPU is outside guest mode and is scheduled out, it might be in the\nprocess of making a memory access. A problem occurs if another vCPU uses\nthe PV TLB flush feature during the period when the vCPU is scheduled\nout, and a virtual address has already been translated but has not yet\nbeen accessed, because this is equivalent to using a stale TLB entry.\n\nTo avoid this, only report a vCPU as preempted if sure that the guest\nis at an instruction boundary. A rescheduling request will be delivered\nto the host physical CPU as an external interrupt, so for simplicity\nconsider any vmexit *not* instruction boundary except for external\ninterrupts.\n\nIt would in principle be okay to report the vCPU as preempted also\nif it is sleeping in kvm_vcpu_block(): a TLB flush IPI will incur the\nvmentry/vmexit overhead unnecessarily, and optimistic spinning is\nalso unlikely to succeed. However, leave it for later because right\nnow kvm_vcpu_check_block() is doing memory accesses. Even\nthough the TLB flush issue only applies to virtual memory address,\nit's very much preferrable to be conservative.\n\nReported-by: Jann Horn \nSigned-off-by: Paolo Bonzini '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static bool reconstruct_chained_fixup(struct MACH0_(obj_t) * bin) {\n\tif (!bin->dyld_info) {\n\t\treturn false;\n\t}\n\tif (!bin->nsegs) {\n\t\treturn false;\n\t}\n\tbin->nchained_starts = bin->nsegs;\n\tbin->chained_starts = RZ_NEWS0(struct rz_dyld_chained_starts_in_segment *, bin->nchained_starts);\n\tif (!bin->chained_starts) {\n\t\treturn false;\n\t}\n\tsize_t wordsize = get_word_size(bin);\n\tut8 *p = NULL;\n\tsize_t j, count, skip, bind_size;\n\tint seg_idx = 0;\n\tut64 seg_off = 0;\n\tbind_size = bin->dyld_info->bind_size;\n\tif (!bind_size || bind_size < 1) {\n\t\treturn false;\n\t}\n\tif (bin->dyld_info->bind_off > bin->size) {\n\t\treturn false;\n\t}\n\tif (bin->dyld_info->bind_off + bind_size > bin->size) {\n\t\treturn false;\n\t}\n\tut8 *opcodes = calloc(1, bind_size + 1);\n\tif (!opcodes) {\n\t\treturn false;\n\t}\n\tif (rz_buf_read_at(bin->b, bin->dyld_info->bind_off, opcodes, bind_size) != bind_size) {\n\t\tbprintf(\"Error: read (dyld_info bind) at 0x%08\" PFMT64x \"\\n\", (ut64)(size_t)bin->dyld_info->bind_off);\n\t\tRZ_FREE(opcodes);\n\t\treturn false;\n\t}\n\tstruct rz_dyld_chained_starts_in_segment *cur_seg = NULL;\n\tsize_t cur_seg_idx = 0;\n\tut8 *end;\n\tbool done = false;\n\tfor (p = opcodes, end = opcodes + bind_size; !done && p < end;) {\n\t\tut8 imm = *p & BIND_IMMEDIATE_MASK, op = *p & BIND_OPCODE_MASK;\n\t\tp++;\n\t\tswitch (op) {\n\t\tcase BIND_OPCODE_DONE:\n\t\t\tdone = true;\n\t\t\tbreak;\n\t\tcase BIND_OPCODE_THREADED: {\n\t\t\tswitch (imm) {\n\t\t\tcase BIND_SUBOPCODE_THREADED_SET_BIND_ORDINAL_TABLE_SIZE_ULEB: {\n\t\t\t\tread_uleb128(&p, end);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase BIND_SUBOPCODE_THREADED_APPLY: {\n\t\t\t\tconst size_t ps = 0x1000;\n\t\t\t\tif (!cur_seg || cur_seg_idx != seg_idx) {\n\t\t\t\t\tcur_seg_idx = seg_idx;\n\t\t\t\t\tcur_seg = bin->chained_starts[seg_idx];\n\t\t\t\t\tif (!cur_seg) {\n\t\t\t\t\t\tcur_seg = RZ_NEW0(struct rz_dyld_chained_starts_in_segment);\n\t\t\t\t\t\tif (!cur_seg) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbin->chained_starts[seg_idx] = cur_seg;\n\t\t\t\t\t\tcur_seg->pointer_format = DYLD_CHAINED_PTR_ARM64E;\n\t\t\t\t\t\tcur_seg->page_size = ps;\n\t\t\t\t\t\tcur_seg->page_count = ((bin->segs[seg_idx].vmsize + (ps - 1)) & ~(ps - 1)) / ps;\n\t\t\t\t\t\tif (cur_seg->page_count > 0) {\n\t\t\t\t\t\t\tcur_seg->page_start = malloc(sizeof(ut16) * cur_seg->page_count);\n\t\t\t\t\t\t\tif (!cur_seg->page_start) {\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tmemset(cur_seg->page_start, 0xff, sizeof(ut16) * cur_seg->page_count);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (cur_seg) {\n\t\t\t\t\tut32 page_index = (ut32)(seg_off / ps);\n\t\t\t\t\tsize_t maxsize = cur_seg->page_count * sizeof(ut16);\n\t\t\t\t\tif (page_index < maxsize) {\n\t\t\t\t\t\tcur_seg->page_start[page_index] = seg_off & 0xfff;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tbprintf(\"Error: Unexpected BIND_OPCODE_THREADED sub-opcode: 0x%x\\n\", imm);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:\n\t\tcase BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:\n\t\tcase BIND_OPCODE_SET_TYPE_IMM:\n\t\t\tbreak;\n\t\tcase BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:\n\t\t\tread_uleb128(&p, end);\n\t\t\tbreak;\n\t\tcase BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:\n\t\t\twhile (*p++ && p < end) {\n\t\t\t\t/* empty loop */\n\t\t\t}\n\t\t\tbreak;\n\t\tcase BIND_OPCODE_SET_ADDEND_SLEB:\n\t\t\trz_sleb128((const ut8 **)&p, end);\n\t\t\tbreak;\n\t\tcase BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:\n\t\t\tseg_idx = imm;\n\t\t\tif (seg_idx >= bin->nsegs) {\n\t\t\t\tbprintf(\"Error: BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB\"\n\t\t\t\t\t\" has unexistent segment %d\\n\",\n\t\t\t\t\tseg_idx);\n\t\t\t\tRZ_FREE(opcodes);\n\t\t\t\treturn false;\n\t\t\t} else {\n\t\t\t\tseg_off = read_uleb128(&p, end);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase BIND_OPCODE_ADD_ADDR_ULEB:\n\t\t\tseg_off += read_uleb128(&p, end);\n\t\t\tbreak;\n\t\tcase BIND_OPCODE_DO_BIND:\n\t\t\tbreak;\n\t\tcase BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:\n\t\t\tseg_off += read_uleb128(&p, end) + wordsize;\n\t\t\tbreak;\n\t\tcase BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:\n\t\t\tseg_off += (ut64)imm * (ut64)wordsize + wordsize;\n\t\t\tbreak;\n\t\tcase BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:\n\t\t\tcount = read_uleb128(&p, end);\n\t\t\tskip = read_uleb128(&p, end);\n\t\t\tfor (j = 0; j < count; j++) {\n\t\t\t\tseg_off += skip + wordsize;\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbprintf(\"Error: unknown bind opcode 0x%02x in dyld_info\\n\", *p);\n\t\t\tRZ_FREE(opcodes);\n\t\t\treturn false;\n\t\t}\n\t}\n\tRZ_FREE(opcodes);\n\n\treturn true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'fix #2956 - oob write in mach0.c'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: f_assert_fails(typval_T *argvars, typval_T *rettv)\n{\n char_u\t*cmd;\n garray_T\tga;\n int\t\tsave_trylevel = trylevel;\n int\t\tcalled_emsg_before = called_emsg;\n char\t*wrong_arg_msg = NULL;\n char_u\t*tofree = NULL;\n\n if (check_for_string_or_number_arg(argvars, 0) == FAIL\n\t || check_for_opt_string_or_list_arg(argvars, 1) == FAIL\n\t || (argvars[1].v_type != VAR_UNKNOWN\n\t\t&& (argvars[2].v_type != VAR_UNKNOWN\n\t\t && (check_for_opt_number_arg(argvars, 3) == FAIL\n\t\t\t|| (argvars[3].v_type != VAR_UNKNOWN\n\t\t\t && check_for_opt_string_arg(argvars, 4) == FAIL)))))\n\treturn;\n\n cmd = tv_get_string_chk(&argvars[0]);\n\n // trylevel must be zero for a \":throw\" command to be considered failed\n trylevel = 0;\n suppress_errthrow = TRUE;\n in_assert_fails = TRUE;\n\n do_cmdline_cmd(cmd);\n if (called_emsg == called_emsg_before)\n {\n\tprepare_assert_error(&ga);\n\tga_concat(&ga, (char_u *)\"command did not fail: \");\n\tassert_append_cmd_or_arg(&ga, argvars, cmd);\n\tassert_error(&ga);\n\tga_clear(&ga);\n\trettv->vval.v_number = 1;\n }\n else if (argvars[1].v_type != VAR_UNKNOWN)\n {\n\tchar_u\tbuf[NUMBUFLEN];\n\tchar_u\t*expected;\n\tchar_u\t*expected_str = NULL;\n\tint\terror_found = FALSE;\n\tint\terror_found_index = 1;\n\tchar_u\t*actual = emsg_assert_fails_msg == NULL ? (char_u *)\"[unknown]\"\n\t\t\t\t\t\t : emsg_assert_fails_msg;\n\n\tif (argvars[1].v_type == VAR_STRING)\n\t{\n\t expected = tv_get_string_buf_chk(&argvars[1], buf);\n\t error_found = expected == NULL\n\t\t\t || strstr((char *)actual, (char *)expected) == NULL;\n\t}\n\telse if (argvars[1].v_type == VAR_LIST)\n\t{\n\t list_T\t*list = argvars[1].vval.v_list;\n\t typval_T\t*tv;\n\n\t if (list == NULL || list->lv_len < 1 || list->lv_len > 2)\n\t {\n\t\twrong_arg_msg = e_assert_fails_second_arg;\n\t\tgoto theend;\n\t }\n\t CHECK_LIST_MATERIALIZE(list);\n\t tv = &list->lv_first->li_tv;\n\t expected = tv_get_string_buf_chk(tv, buf);\n\t if (!pattern_match(expected, actual, FALSE))\n\t {\n\t\terror_found = TRUE;\n\t\texpected_str = expected;\n\t }\n\t else if (list->lv_len == 2)\n\t {\n\t\t// make a copy, an error in pattern_match() may free it\n\t\ttofree = actual = vim_strsave(get_vim_var_str(VV_ERRMSG));\n\t\tif (actual != NULL)\n\t\t{\n\t\t tv = &list->lv_u.mat.lv_last->li_tv;\n\t\t expected = tv_get_string_buf_chk(tv, buf);\n\t\t if (!pattern_match(expected, actual, FALSE))\n\t\t {\n\t\t\terror_found = TRUE;\n\t\t\texpected_str = expected;\n\t\t }\n\t\t}\n\t }\n\t}\n\telse\n\t{\n\t wrong_arg_msg = e_assert_fails_second_arg;\n\t goto theend;\n\t}\n\n\tif (!error_found && argvars[2].v_type != VAR_UNKNOWN\n\t\t&& argvars[3].v_type != VAR_UNKNOWN)\n\t{\n\t if (argvars[3].v_type != VAR_NUMBER)\n\t {\n\t\twrong_arg_msg = e_assert_fails_fourth_argument;\n\t\tgoto theend;\n\t }\n\t else if (argvars[3].vval.v_number >= 0\n\t\t\t && argvars[3].vval.v_number != emsg_assert_fails_lnum)\n\t {\n\t\terror_found = TRUE;\n\t\terror_found_index = 3;\n\t }\n\t if (!error_found && argvars[4].v_type != VAR_UNKNOWN)\n\t {\n\t\tif (argvars[4].v_type != VAR_STRING)\n\t\t{\n\t\t wrong_arg_msg = e_assert_fails_fifth_argument;\n\t\t goto theend;\n\t\t}\n\t\telse if (argvars[4].vval.v_string != NULL\n\t\t && !pattern_match(argvars[4].vval.v_string,\n\t\t\t\t\t emsg_assert_fails_context, FALSE))\n\t\t{\n\t\t error_found = TRUE;\n\t\t error_found_index = 4;\n\t\t}\n\t }\n\t}\n\n\tif (error_found)\n\t{\n\t typval_T actual_tv;\n\n\t prepare_assert_error(&ga);\n\t if (error_found_index == 3)\n\t {\n\t\tactual_tv.v_type = VAR_NUMBER;\n\t\tactual_tv.vval.v_number = emsg_assert_fails_lnum;\n\t }\n\t else if (error_found_index == 4)\n\t {\n\t\tactual_tv.v_type = VAR_STRING;\n\t\tactual_tv.vval.v_string = emsg_assert_fails_context;\n\t }\n\t else\n\t {\n\t\tactual_tv.v_type = VAR_STRING;\n\t\tactual_tv.vval.v_string = actual;\n\t }\n\t fill_assert_error(&ga, &argvars[2], expected_str,\n\t\t\t&argvars[error_found_index], &actual_tv, ASSERT_OTHER);\n\t ga_concat(&ga, (char_u *)\": \");\n\t assert_append_cmd_or_arg(&ga, argvars, cmd);\n\t assert_error(&ga);\n\t ga_clear(&ga);\n\t rettv->vval.v_number = 1;\n\t}\n }\n\ntheend:\n trylevel = save_trylevel;\n suppress_errthrow = FALSE;\n in_assert_fails = FALSE;\n did_emsg = FALSE;\n got_int = FALSE;\n msg_col = 0;\n need_wait_return = FALSE;\n emsg_on_display = FALSE;\n msg_scrolled = 0;\n lines_left = Rows;\n VIM_CLEAR(emsg_assert_fails_msg);\n vim_free(tofree);\n set_vim_var_string(VV_ERRMSG, NULL, 0);\n if (wrong_arg_msg != NULL)\n\temsg(_(wrong_arg_msg));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'patch 9.0.0404: crash when passing invalid arguments to assert_fails()\n\nProblem: Crash when passing invalid arguments to assert_fails().\nSolution: Check for NULL string.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bgp_capability_receive (struct peer *peer, bgp_size_t size)\n{\n u_char *pnt;\n int ret;\n\n /* Fetch pointer. */\n pnt = stream_pnt (peer->ibuf);\n\n if (BGP_DEBUG (normal, NORMAL))\n zlog_debug (\"%s rcv CAPABILITY\", peer->host);\n\n /* If peer does not have the capability, send notification. */\n if (! CHECK_FLAG (peer->cap, PEER_CAP_DYNAMIC_ADV))\n {\n plog_err (peer->log, \"%s [Error] BGP dynamic capability is not enabled\",\n\t\tpeer->host);\n bgp_notify_send (peer,\n\t\t BGP_NOTIFY_HEADER_ERR,\n\t\t BGP_NOTIFY_HEADER_BAD_MESTYPE);\n return;\n }\n\n /* Status must be Established. */\n if (peer->status != Established)\n {\n plog_err (peer->log,\n\t\t\"%s [Error] Dynamic capability packet received under status %s\", peer->host, LOOKUP (bgp_status_msg, peer->status));\n bgp_notify_send (peer, BGP_NOTIFY_FSM_ERR, 0);\n return;\n }\n\n /* Parse packet. */\n ret = bgp_capability_msg_parse (peer, pnt, size);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': '[bgpd] cleanup, compact and consolidate capability parsing code\n\n2007-07-26 Paul Jakma \n\n\t* (general) Clean up and compact capability parsing slightly.\n\t Consolidate validation of length and logging of generic TLV, and\n\t memcpy of capability data, thus removing such from cap specifc\n\t code (not always present or correct).\n\t* bgp_open.h: Add structures for the generic capability TLV header\n\t and for the data formats of the various specific capabilities we\n\t support. Hence remove the badly named, or else misdefined, struct\n\t capability.\n\t* bgp_open.c: (bgp_capability_vty_out) Use struct capability_mp_data.\n\t Do the length checks *before* memcpy()'ing based on that length\n\t (stored capability - should have been validated anyway on input,\n\t but..).\n\t (bgp_afi_safi_valid_indices) new function to validate (afi,safi)\n\t which is about to be used as index into arrays, consolidates\n\t several instances of same, at least one of which appeared to be\n\t incomplete..\n\t (bgp_capability_mp) Much condensed.\n\t (bgp_capability_orf_entry) New, process one ORF entry\n\t (bgp_capability_orf) Condensed. Fixed to process all ORF entries.\n\t (bgp_capability_restart) Condensed, and fixed to use a\n\t cap-specific type, rather than abusing capability_mp.\n\t (struct message capcode_str) added to aid generic logging.\n\t (size_t cap_minsizes[]) added to aid generic validation of\n\t capability length field.\n\t (bgp_capability_parse) Generic logging and validation of TLV\n\t consolidated here. Code compacted as much as possible.\n\t* bgp_packet.c: (bgp_open_receive) Capability parsers now use\n\t streams, so no more need here to manually fudge the input stream\n\t getp.\n\t (bgp_capability_msg_parse) use struct capability_mp_data. Validate\n\t lengths /before/ memcpy. Use bgp_afi_safi_valid_indices.\n\t (bgp_capability_receive) Exported for use by test harness.\n\t* bgp_vty.c: (bgp_show_summary) fix conversion warning\n\t (bgp_show_peer) ditto\n\t* bgp_debug.h: Fix storage 'extern' after type 'const'.\n * lib/log.c: (mes_lookup) warning about code not being in\n same-number array slot should be debug, not warning. E.g. BGP\n has several discontigious number spaces, allocating from\n different parts of a space is not uncommon (e.g. IANA\n assigned versus vendor-assigned code points in some number\n space).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: process_next_cpt_value(\n\tins_compl_next_state_T *st,\n\tint\t\t*compl_type_arg,\n\tpos_T\t\t*start_match_pos)\n{\n int\t compl_type = -1;\n int\t status = INS_COMPL_CPT_OK;\n\n st->found_all = FALSE;\n\n while (*st->e_cpt == ',' || *st->e_cpt == ' ')\n\tst->e_cpt++;\n\n if (*st->e_cpt == '.' && !curbuf->b_scanned)\n {\n\tst->ins_buf = curbuf;\n\tst->first_match_pos = *start_match_pos;\n\t// Move the cursor back one character so that ^N can match the\n\t// word immediately after the cursor.\n\tif (ctrl_x_mode_normal() && dec(&st->first_match_pos) < 0)\n\t{\n\t // Move the cursor to after the last character in the\n\t // buffer, so that word at start of buffer is found\n\t // correctly.\n\t st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;\n\t st->first_match_pos.col =\n\t\t(colnr_T)STRLEN(ml_get(st->first_match_pos.lnum));\n\t}\n\tst->last_match_pos = st->first_match_pos;\n\tcompl_type = 0;\n\n\t// Remember the first match so that the loop stops when we\n\t// wrap and come back there a second time.\n\tst->set_match_pos = TRUE;\n }\n else if (vim_strchr((char_u *)\"buwU\", *st->e_cpt) != NULL\n\t && (st->ins_buf = ins_compl_next_buf(st->ins_buf, *st->e_cpt)) != curbuf)\n {\n\t// Scan a buffer, but not the current one.\n\tif (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer\n\t{\n\t compl_started = TRUE;\n\t st->first_match_pos.col = st->last_match_pos.col = 0;\n\t st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;\n\t st->last_match_pos.lnum = 0;\n\t compl_type = 0;\n\t}\n\telse\t// unloaded buffer, scan like dictionary\n\t{\n\t st->found_all = TRUE;\n\t if (st->ins_buf->b_fname == NULL)\n\t {\n\t\tstatus = INS_COMPL_CPT_CONT;\n\t\tgoto done;\n\t }\n\t compl_type = CTRL_X_DICTIONARY;\n\t st->dict = st->ins_buf->b_fname;\n\t st->dict_f = DICT_EXACT;\n\t}\n\tmsg_hist_off = TRUE;\t// reset in msg_trunc_attr()\n\tvim_snprintf((char *)IObuff, IOSIZE, _(\"Scanning: %s\"),\n\t\tst->ins_buf->b_fname == NULL\n\t\t ? buf_spname(st->ins_buf)\n\t\t : st->ins_buf->b_sfname == NULL\n\t\t\t? st->ins_buf->b_fname\n\t\t\t: st->ins_buf->b_sfname);\n\t(void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));\n }\n else if (*st->e_cpt == NUL)\n\tstatus = INS_COMPL_CPT_END;\n else\n {\n\tif (ctrl_x_mode_line_or_eval())\n\t compl_type = -1;\n\telse if (*st->e_cpt == 'k' || *st->e_cpt == 's')\n\t{\n\t if (*st->e_cpt == 'k')\n\t\tcompl_type = CTRL_X_DICTIONARY;\n\t else\n\t\tcompl_type = CTRL_X_THESAURUS;\n\t if (*++st->e_cpt != ',' && *st->e_cpt != NUL)\n\t {\n\t\tst->dict = st->e_cpt;\n\t\tst->dict_f = DICT_FIRST;\n\t }\n\t}\n#ifdef FEAT_FIND_ID\n\telse if (*st->e_cpt == 'i')\n\t compl_type = CTRL_X_PATH_PATTERNS;\n\telse if (*st->e_cpt == 'd')\n\t compl_type = CTRL_X_PATH_DEFINES;\n#endif\n\telse if (*st->e_cpt == ']' || *st->e_cpt == 't')\n\t{\n\t msg_hist_off = TRUE;\t// reset in msg_trunc_attr()\n\t compl_type = CTRL_X_TAGS;\n\t vim_snprintf((char *)IObuff, IOSIZE, _(\"Scanning tags.\"));\n\t (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));\n\t}\n\telse\n\t compl_type = -1;\n\n\t// in any case e_cpt is advanced to the next entry\n\t(void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, \",\");\n\n\tst->found_all = TRUE;\n\tif (compl_type == -1)\n\t status = INS_COMPL_CPT_CONT;\n }\n\ndone:\n *compl_type_arg = compl_type;\n return status;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'patch 9.0.0579: using freed memory when 'tagfunc' wipes out buffer\n\nProblem: Using freed memory when 'tagfunc' wipes out buffer that holds\n 'complete'.\nSolution: Make a copy of the option. Make sure cursor position is valid.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int fprintf_mtab_fs(FILE *f, struct libmnt_fs *fs)\n{\n\tchar *o;\n\tchar *m1, *m2, *m3, *m4;\n\tint rc;\n\n\tassert(fs);\n\tassert(f);\n\n\to = mnt_fs_strdup_options(fs);\n\tif (!o)\n\t\treturn -ENOMEM;\n\n\tm1 = mangle(mnt_fs_get_source(fs));\n\tm2 = mangle(mnt_fs_get_target(fs));\n\tm3 = mangle(mnt_fs_get_fstype(fs));\n\tm4 = mangle(o);\n\n\tif (m1 && m2 && m3 && m4)\n\t\trc = !fprintf(f, \"%s %s %s %s %d %d\\n\",\n\t\t\t\tm1, m2, m3, m4,\n\t\t\t\tmnt_fs_get_freq(fs),\n\t\t\t\tmnt_fs_get_passno(fs));\n\telse\n\t\trc = -ENOMEM;\n\n\tfree(o);\n\tfree(m1);\n\tfree(m2);\n\tfree(m3);\n\tfree(m4);\n\n\treturn rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'libmount: more robust mtab and utab update (CVE-2011-1676, CVE-2011-1677)\n\nhttp://thread.gmane.org/gmane.comp.security.oss.general/4374\n\nChanges:\n\n - always use temporary file\n\n - use fflush() for the temporary file\n\n - check fprintf() return value\n\nSigned-off-by: Karel Zak '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: doit (struct query *z, int state)\n{\n char key[257];\n char misc[20], header[12];\n char *buf = 0, *cached = 0;\n const char *whichserver = 0;\n\n unsigned int rcode = 0;\n unsigned int posanswers = 0;\n unsigned int len = 0, cachedlen = 0;\n\n uint16 numanswers = 0;\n uint16 numauthority = 0;\n unsigned int posauthority = 0;\n\n uint16 numglue = 0;\n unsigned int posglue = 0;\n unsigned int pos = 0, pos2 = 0;\n\n uint16 datalen = 0;\n char *control = 0, *d = 0;\n\n const char *dtype = 0;\n unsigned int dlen = 0;\n\n int flagout = 0, flagcname = 0;\n int flagreferral = 0, flagsoa = 0;\n\n int i = 0, j = 0, k = 0, p = 0, q = 0;\n uint32 ttl = 0, soattl = 0, cnamettl = 0;\n\n errno = error_io;\n if (state == 1)\n goto HAVEPACKET;\n if (state == -1)\n {\n if (debug_level > 1)\n log_servfail (z->name[z->level]);\n goto SERVFAIL;\n }\n\n\nNEWNAME:\n if (++z->loop == 100)\n goto DIE;\n d = z->name[z->level];\n dtype = z->level ? DNS_T_A : z->type;\n dlen = dns_domain_length (d);\n\n if (globalip (d, misc))\n {\n if (z->level)\n {\n for (k = 0; k < 64; k += 4)\n {\n if (byte_equal (z->servers[z->level - 1] + k, 4, \"\\0\\0\\0\\0\"))\n {\n byte_copy (z->servers[z->level - 1] + k, 4, misc);\n break;\n }\n }\n goto LOWERLEVEL;\n }\n if (!rqa (z))\n goto DIE;\n if (typematch (DNS_T_A, dtype))\n {\n if (!response_rstart (d, DNS_T_A, 655360))\n goto DIE;\n if (!response_addbytes (misc, 4))\n goto DIE;\n response_rfinish (RESPONSE_ANSWER);\n }\n cleanup (z);\n\n return 1;\n }\n\n if (dns_domain_equal (d, \"\\0011\\0010\\0010\\003127\\7in-addr\\4arpa\\0\"))\n {\n if (z->level)\n goto LOWERLEVEL;\n if (!rqa (z))\n goto DIE;\n if (typematch (DNS_T_PTR, dtype))\n {\n if (!response_rstart (d, DNS_T_PTR, 655360))\n goto DIE;\n if (!response_addname (\"\\011localhost\\0\"))\n goto DIE;\n\n response_rfinish (RESPONSE_ANSWER);\n }\n cleanup (z);\n if (debug_level > 2)\n log_stats ();\n\n return 1;\n }\n\n if (dlen <= 255)\n {\n byte_copy (key, 2, DNS_T_ANY);\n byte_copy (key + 2, dlen, d);\n case_lowerb (key + 2, dlen);\n cached = cache_get (key, dlen + 2, &cachedlen, &ttl);\n if (cached)\n {\n if (debug_level > 2)\n log_cachednxdomain (d);\n goto NXDOMAIN;\n }\n\n byte_copy (key, 2, DNS_T_CNAME);\n cached = cache_get (key, dlen + 2, &cachedlen, &ttl);\n if (cached)\n {\n if (typematch (DNS_T_CNAME, dtype))\n {\n if (debug_level > 2)\n log_cachedanswer (d, DNS_T_CNAME);\n\n if (!rqa (z))\n goto DIE;\n if (!response_cname (z->name[0], cached, ttl))\n goto DIE;\n cleanup (z);\n\n return 1;\n }\n if (debug_level > 2)\n log_cachedcname (d, cached);\n\n if (!dns_domain_copy (&cname, cached))\n goto DIE;\n\n goto CNAME;\n }\n\n if (typematch (DNS_T_NS, dtype))\n {\n byte_copy (key, 2, DNS_T_NS);\n cached = cache_get (key, dlen + 2, &cachedlen, &ttl);\n if (cached && (cachedlen || byte_diff (dtype, 2, DNS_T_ANY)))\n {\n if (debug_level > 2)\n log_cachedanswer (d, DNS_T_NS);\n if (!rqa (z))\n goto DIE;\n\n pos = 0;\n while ((pos=dns_packet_getname (cached, cachedlen, pos, &t2)))\n {\n if (!response_rstart (d, DNS_T_NS, ttl))\n goto DIE;\n if (!response_addname (t2))\n goto DIE;\n\n response_rfinish (RESPONSE_ANSWER);\n }\n cleanup (z);\n\n return 1;\n }\n }\n\n if (typematch (DNS_T_PTR, dtype))\n {\n byte_copy (key, 2, DNS_T_PTR);\n cached = cache_get (key, dlen + 2, &cachedlen, &ttl);\n if (cached && (cachedlen || byte_diff(dtype, 2, DNS_T_ANY)))\n {\n if (debug_level > 2)\n log_cachedanswer (d, DNS_T_PTR);\n if (!rqa (z))\n goto DIE;\n\n pos = 0;\n while ((pos=dns_packet_getname (cached, cachedlen, pos, &t2)))\n {\n if (!response_rstart (d, DNS_T_PTR, ttl))\n goto DIE;\n if (!response_addname (t2))\n goto DIE;\n\n response_rfinish (RESPONSE_ANSWER);\n }\n cleanup(z);\n\n return 1;\n }\n }\n\n if (typematch (DNS_T_MX, dtype))\n {\n byte_copy (key, 2, DNS_T_MX);\n cached = cache_get (key, dlen + 2, &cachedlen, &ttl);\n if (cached && (cachedlen || byte_diff (dtype, 2, DNS_T_ANY)))\n {\n if (debug_level > 2)\n log_cachedanswer (d, DNS_T_MX);\n if (!rqa (z))\n goto DIE;\n\n pos = 0;\n while ((pos=dns_packet_copy (cached, cachedlen, pos, misc, 2)))\n {\n pos = dns_packet_getname (cached, cachedlen, pos, &t2);\n if (!pos)\n break;\n if (!response_rstart (d, DNS_T_MX, ttl))\n goto DIE;\n if (!response_addbytes (misc, 2))\n goto DIE;\n if (!response_addname (t2))\n goto DIE;\n\n response_rfinish (RESPONSE_ANSWER);\n }\n cleanup (z);\n\n return 1;\n }\n }\n\n if (typematch (DNS_T_A, dtype))\n {\n byte_copy (key,2,DNS_T_A);\n cached = cache_get (key, dlen + 2, &cachedlen, &ttl);\n if (cached && (cachedlen || byte_diff (dtype, 2, DNS_T_ANY)))\n {\n if (z->level)\n {\n if (debug_level > 2)\n log_cachedanswer (d, DNS_T_A);\n while (cachedlen >= 4)\n {\n for (k = 0; k < 64; k += 4)\n {\n if (byte_equal (z->servers[z->level - 1] + k,\n 4, \"\\0\\0\\0\\0\"))\n {\n byte_copy (z->servers[z->level - 1] + k,\n 4, cached);\n break;\n }\n }\n cached += 4;\n cachedlen -= 4;\n }\n goto LOWERLEVEL;\n }\n\n if (debug_level > 2)\n log_cachedanswer (d, DNS_T_A);\n if (!rqa (z))\n goto DIE;\n while (cachedlen >= 4)\n {\n if (!response_rstart (d, DNS_T_A, ttl))\n goto DIE;\n if (!response_addbytes (cached, 4))\n goto DIE;\n response_rfinish (RESPONSE_ANSWER);\n cached += 4;\n cachedlen -= 4;\n }\n cleanup (z);\n\n return 1;\n }\n }\n\n if (!typematch (DNS_T_ANY, dtype)\n && !typematch (DNS_T_AXFR, dtype)\n && !typematch (DNS_T_CNAME, dtype)\n && !typematch (DNS_T_NS, dtype)\n && !typematch (DNS_T_PTR, dtype)\n && !typematch (DNS_T_A, dtype)\n && !typematch (DNS_T_MX, dtype))\n {\n byte_copy (key, 2, dtype);\n cached = cache_get (key, dlen + 2, &cachedlen, &ttl);\n if (cached && (cachedlen || byte_diff (dtype, 2, DNS_T_ANY)))\n {\n if (debug_level > 2)\n log_cachedanswer (d, dtype);\n if (!rqa (z))\n goto DIE;\n while (cachedlen >= 2)\n {\n uint16_unpack_big (cached, &datalen);\n cached += 2;\n cachedlen -= 2;\n if (datalen > cachedlen)\n goto DIE;\n if (!response_rstart (d, dtype, ttl))\n goto DIE;\n if (!response_addbytes (cached, datalen))\n goto DIE;\n response_rfinish (RESPONSE_ANSWER);\n cached += datalen;\n cachedlen -= datalen;\n }\n cleanup (z);\n\n return 1;\n }\n }\n }\n\n for (;;)\n {\n if (roots (z->servers[z->level], d))\n {\n for (j = 0; j < QUERY_MAXNS; ++j)\n dns_domain_free (&z->ns[z->level][j]);\n z->control[z->level] = d;\n break;\n }\n\n if (!flagforwardonly && (z->level < 2))\n {\n if (dlen < 255)\n {\n byte_copy (key,2,DNS_T_NS);\n byte_copy (key + 2,dlen,d);\n case_lowerb (key + 2,dlen);\n cached = cache_get (key, dlen + 2, &cachedlen, &ttl);\n if (cached && cachedlen)\n {\n z->control[z->level] = d;\n byte_zero (z->servers[z->level],64);\n for (j = 0; j < QUERY_MAXNS; ++j)\n dns_domain_free (&z->ns[z->level][j]);\n\n j = pos = 0;\n pos = dns_packet_getname (cached, cachedlen, pos, &t1);\n while (pos)\n {\n if (debug_level > 2)\n log_cachedns (d, t1);\n if (j < QUERY_MAXNS)\n if (!dns_domain_copy (&z->ns[z->level][j++], t1))\n goto DIE;\n\n pos = dns_packet_getname (cached, cachedlen, pos, &t1);\n }\n break;\n }\n }\n }\n\n if (!*d)\n goto DIE;\n j = 1 + (unsigned int) (unsigned char) *d;\n dlen -= j;\n d += j;\n }\n\n\nHAVENS:\n for (j = 0; j < QUERY_MAXNS; ++j)\n {\n if (z->ns[z->level][j])\n {\n if (z->level + 1 < QUERY_MAXLEVEL)\n {\n int dc = dns_domain_copy (&z->name[z->level + 1],\n z->ns[z->level][j]);\n if (!dc)\n goto DIE;\n\n dns_domain_free (&z->ns[z->level][j]);\n ++z->level;\n goto NEWNAME;\n }\n dns_domain_free (&z->ns[z->level][j]);\n }\n }\n\n for (j = 0; j < 64; j += 4)\n if (byte_diff (z->servers[z->level] + j, 4, \"\\0\\0\\0\\0\"))\n break;\n if (j == 64)\n goto SERVFAIL;\n\n dns_sortip (z->servers[z->level], 64);\n if (z->level)\n {\n if (debug_level > 2)\n log_tx (z->name[z->level], DNS_T_A,\n z->control[z->level], z->servers[z->level],z->level);\n\n if (dns_transmit_start (&z->dt, z->servers[z->level], flagforwardonly,\n z->name[z->level], DNS_T_A,z->localip) == -1)\n goto DIE;\n }\n else\n {\n if (debug_level > 2)\n log_tx (z->name[0], z->type, z->control[0], z->servers[0], 0);\n\n if (dns_transmit_start (&z->dt, z->servers[0], flagforwardonly,\n z->name[0], z->type, z->localip) == -1)\n goto DIE;\n }\n return 0;\n\n\nLOWERLEVEL:\n dns_domain_free (&z->name[z->level]);\n for (j = 0; j < QUERY_MAXNS; ++j)\n dns_domain_free (&z->ns[z->level][j]);\n --z->level;\n goto HAVENS;\n\n\nHAVEPACKET:\n if (++z->loop == 100)\n goto DIE;\n buf = z->dt.packet;\n len = z->dt.packetlen;\n\n whichserver = z->dt.servers + 4 * z->dt.curserver;\n control = z->control[z->level];\n d = z->name[z->level];\n dtype = z->level ? DNS_T_A : z->type;\n\n if (!(pos = dns_packet_copy (buf, len, 0, header, 12)))\n goto DIE;\n if (!(pos = dns_packet_skipname (buf, len, pos)))\n goto DIE;\n pos += 4;\n posanswers = pos;\n\n uint16_unpack_big (header + 6, &numanswers);\n uint16_unpack_big (header + 8, &numauthority);\n uint16_unpack_big (header + 10, &numglue);\n\n rcode = header[3] & 15;\n if (rcode && (rcode != 3))\n goto DIE; /* impossible; see irrelevant() */\n\n flagsoa = soattl = cnamettl = 0;\n flagout = flagcname = flagreferral = 0;\n for (j = 0; j < numanswers; ++j)\n {\n pos = dns_packet_getname (buf, len, pos, &t1);\n if (!pos)\n goto DIE;\n pos = dns_packet_copy (buf, len, pos, header, 10);\n if (!pos)\n goto DIE;\n\n if (dns_domain_equal (t1, d))\n {\n if (byte_equal (header + 2, 2, DNS_C_IN))\n {\n /* should always be true */\n if (typematch (header, dtype))\n flagout = 1;\n else if (typematch (header, DNS_T_CNAME))\n {\n if (!dns_packet_getname (buf, len, pos, &cname))\n goto DIE;\n flagcname = 1;\n cnamettl = ttlget (header + 4);\n }\n }\n }\n uint16_unpack_big (header + 8, &datalen);\n pos += datalen;\n }\n posauthority = pos;\n\n for (j = 0; j < numauthority; ++j)\n {\n pos = dns_packet_getname (buf, len, pos, &t1);\n if (!pos)\n goto DIE;\n pos = dns_packet_copy (buf, len, pos, header, 10);\n if (!pos)\n goto DIE;\n\n if (typematch (header, DNS_T_SOA))\n {\n flagsoa = 1;\n soattl = ttlget (header + 4);\n if (soattl > 3600)\n soattl = 3600;\n }\n else if (typematch (header, DNS_T_NS))\n {\n flagreferral = 1;\n if (!dns_domain_copy (&referral, t1))\n goto DIE;\n }\n\n uint16_unpack_big (header + 8, &datalen);\n pos += datalen;\n }\n posglue = pos;\n\n if (!flagcname && !rcode && !flagout && flagreferral && !flagsoa)\n {\n if (dns_domain_equal (referral, control)\n || !dns_domain_suffix (referral, control))\n {\n if (debug_level > 2)\n log_lame (whichserver, control, referral);\n byte_zero (whichserver, 4);\n\n goto HAVENS;\n }\n }\n\n if (records)\n {\n alloc_free (records);\n records = 0;\n }\n\n k = numanswers + numauthority + numglue;\n records = (unsigned int *) alloc (k * sizeof (unsigned int));\n if (!records)\n goto DIE;\n\n pos = posanswers;\n for (j = 0; j < k; ++j)\n {\n records[j] = pos;\n pos = dns_packet_getname (buf, len, pos, &t1);\n if (!pos)\n goto DIE;\n pos = dns_packet_copy (buf, len, pos, header, 10);\n if (!pos)\n goto DIE;\n uint16_unpack_big (header + 8, &datalen);\n pos += datalen;\n }\n\n i = j = k;\n while (j > 1)\n {\n if (i > 1)\n {\n --i;\n pos = records[i - 1];\n }\n else\n {\n pos = records[j - 1];\n records[j - 1] = records[i - 1];\n --j;\n }\n\n q = i;\n while ((p = q * 2) < j)\n {\n if (!smaller (buf, len, records[p], records[p - 1]))\n ++p;\n records[q - 1] = records[p - 1];\n q = p;\n }\n if (p == j)\n {\n records[q - 1] = records[p - 1];\n q = p;\n }\n while ((q > i) && smaller (buf, len, records[(p = q/2) - 1], pos))\n {\n records[q - 1] = records[p - 1];\n q = p;\n }\n records[q - 1] = pos;\n }\n\n i = 0;\n while (i < k)\n {\n char type[2];\n\n if (!(pos = dns_packet_getname (buf, len, records[i], &t1)))\n goto DIE;\n if (!(pos = dns_packet_copy (buf, len, pos, header, 10)))\n goto DIE;\n ttl = ttlget (header + 4);\n\n byte_copy (type, 2, header);\n if (byte_diff (header + 2, 2, DNS_C_IN))\n {\n ++i;\n continue;\n }\n\n for (j = i + 1; j < k; ++j)\n {\n pos = dns_packet_getname (buf, len, records[j], &t2);\n if (!pos)\n goto DIE;\n pos = dns_packet_copy (buf, len, pos, header, 10);\n if (!pos)\n goto DIE;\n if (!dns_domain_equal (t1, t2))\n break;\n if (byte_diff (header, 2, type))\n break;\n if (byte_diff (header + 2, 2, DNS_C_IN))\n break;\n }\n\n if (!dns_domain_suffix (t1, control))\n {\n i = j;\n continue;\n }\n if (!roots_same (t1, control))\n {\n i = j;\n continue;\n }\n if (byte_equal (type, 2, DNS_T_ANY))\n ;\n else if (byte_equal(type, 2, DNS_T_AXFR))\n ;\n else if (byte_equal (type, 2, DNS_T_SOA))\n {\n while (i < j)\n {\n pos = dns_packet_skipname (buf, len, records[i]);\n if (!pos)\n goto DIE;\n pos = dns_packet_getname (buf, len, pos + 10, &t2);\n if (!pos)\n goto DIE;\n pos = dns_packet_getname (buf, len, pos, &t3);\n if (!pos)\n goto DIE;\n pos = dns_packet_copy (buf, len, pos, misc, 20);\n if (!pos)\n goto DIE;\n if (records[i] < posauthority && debug_level > 2)\n log_rrsoa (whichserver, t1, t2, t3, misc, ttl);\n ++i;\n }\n }\n else if (byte_equal (type, 2, DNS_T_CNAME))\n {\n pos = dns_packet_skipname (buf, len, records[j - 1]);\n if (!pos)\n goto DIE;\n pos = dns_packet_getname (buf, len, pos + 10, &t2);\n if (!pos)\n goto DIE;\n\n if (debug_level > 2)\n log_rrcname (whichserver, t1, t2, ttl);\n\n cachegeneric (DNS_T_CNAME, t1, t2, dns_domain_length (t2), ttl);\n }\n else if (byte_equal (type, 2, DNS_T_PTR))\n {\n save_start ();\n while (i < j)\n {\n pos = dns_packet_skipname (buf, len, records[i]);\n if (!pos)\n goto DIE;\n pos = dns_packet_getname (buf, len, pos + 10, &t2);\n if (!pos)\n goto DIE;\n if (debug_level > 2)\n log_rrptr (whichserver, t1, t2, ttl);\n\n save_data (t2, dns_domain_length (t2));\n ++i;\n }\n save_finish (DNS_T_PTR, t1, ttl);\n }\n else if (byte_equal (type, 2, DNS_T_NS))\n {\n save_start ();\n while (i < j)\n {\n pos = dns_packet_skipname (buf, len, records[i]);\n if (!pos)\n goto DIE;\n pos = dns_packet_getname (buf, len, pos + 10, &t2);\n if (!pos)\n goto DIE;\n if (debug_level > 2)\n log_rrns (whichserver, t1, t2, ttl);\n save_data (t2, dns_domain_length (t2));\n ++i;\n }\n save_finish (DNS_T_NS, t1, ttl);\n }\n else if (byte_equal (type, 2, DNS_T_MX))\n {\n save_start ();\n while (i < j)\n {\n pos = dns_packet_skipname (buf, len, records[i]);\n if (!pos)\n goto DIE;\n pos = dns_packet_copy (buf, len, pos + 10, misc, 2);\n if (!pos)\n goto DIE;\n pos = dns_packet_getname (buf, len, pos, &t2);\n if (!pos)\n goto DIE;\n if (debug_level > 2)\n log_rrmx (whichserver, t1, t2, misc, ttl);\n save_data (misc, 2);\n save_data (t2, dns_domain_length (t2));\n ++i;\n }\n save_finish (DNS_T_MX, t1, ttl);\n }\n else if (byte_equal (type, 2, DNS_T_A))\n {\n save_start ();\n while (i < j)\n {\n pos = dns_packet_skipname (buf, len, records[i]);\n if (!pos)\n goto DIE;\n pos = dns_packet_copy (buf, len, pos, header, 10);\n if (!pos)\n goto DIE;\n if (byte_equal (header + 8, 2, \"\\0\\4\"))\n {\n pos = dns_packet_copy (buf, len, pos, header, 4);\n if (!pos)\n goto DIE;\n save_data (header, 4);\n\n if (debug_level > 2)\n log_rr (whichserver, t1, DNS_T_A, header, 4, ttl);\n }\n ++i;\n }\n save_finish (DNS_T_A, t1, ttl);\n }\n else\n {\n save_start ();\n while (i < j)\n {\n pos = dns_packet_skipname (buf, len, records[i]);\n if (!pos)\n goto DIE;\n pos = dns_packet_copy (buf, len, pos, header, 10);\n if (!pos)\n goto DIE;\n uint16_unpack_big (header + 8, &datalen);\n if (datalen > len - pos)\n goto DIE;\n save_data (header + 8, 2);\n save_data (buf + pos, datalen);\n\n if (debug_level > 2)\n log_rr (whichserver, t1, type, buf + pos, datalen, ttl);\n\n ++i;\n }\n save_finish (type, t1, ttl);\n }\n i = j;\n }\n alloc_free (records);\n records = 0;\n\n if (flagcname)\n {\n ttl = cnamettl;\nCNAME:\n if (!z->level)\n {\n if (z->alias[QUERY_MAXALIAS - 1])\n goto DIE;\n\n for (j = QUERY_MAXALIAS - 1; j > 0; --j)\n z->alias[j] = z->alias[j - 1];\n for (j = QUERY_MAXALIAS - 1; j > 0; --j)\n z->aliasttl[j] = z->aliasttl[j - 1];\n\n z->alias[0] = z->name[0];\n z->aliasttl[0] = ttl;\n z->name[0] = 0;\n }\n if (!dns_domain_copy (&z->name[z->level], cname))\n goto DIE;\n\n goto NEWNAME;\n }\n\n if (rcode == 3)\n {\n if (debug_level > 2)\n log_nxdomain (whichserver, d, soattl);\n cachegeneric (DNS_T_ANY, d, \"\", 0, soattl);\n\nNXDOMAIN:\n if (z->level)\n goto LOWERLEVEL;\n if (!rqa (z))\n goto DIE;\n\n response_nxdomain ();\n cleanup (z);\n\n return 1;\n }\n\n if (!flagout && flagsoa)\n if (byte_diff (DNS_T_ANY, 2, dtype))\n if (byte_diff (DNS_T_AXFR, 2, dtype))\n if (byte_diff (DNS_T_CNAME, 2, dtype))\n {\n save_start ();\n save_finish (dtype, d, soattl);\n if (debug_level > 2)\n log_nodata (whichserver, d, dtype, soattl);\n }\n\n if (debug_level > 2)\n log_stats ();\n\n if (flagout || flagsoa || !flagreferral)\n {\n if (z->level)\n {\n pos = posanswers;\n for (j = 0; j < numanswers; ++j)\n {\n pos = dns_packet_getname (buf, len, pos, &t1);\n if (!pos)\n goto DIE;\n pos = dns_packet_copy (buf, len, pos, header, 10);\n if (!pos)\n goto DIE;\n uint16_unpack_big (header + 8, &datalen);\n if (dns_domain_equal (t1, d))\n if (typematch (header, DNS_T_A))\n if (byte_equal (header + 2, 2, DNS_C_IN))\n /* should always be true */\n if (datalen == 4)\n for (k = 0; k < 64; k += 4)\n {\n if (byte_equal (z->servers[z->level - 1]\n + k, 4, \"\\0\\0\\0\\0\"))\n {\n if (!dns_packet_copy (buf, len, pos,\n z->servers[z->level - 1] + k, 4))\n goto DIE;\n break;\n }\n }\n pos += datalen;\n }\n goto LOWERLEVEL;\n }\n\n if (!rqa (z))\n goto DIE;\n\n pos = posanswers;\n for (j = 0; j < numanswers; ++j)\n {\n pos = dns_packet_getname (buf, len, pos, &t1);\n if (!pos)\n goto DIE;\n pos = dns_packet_copy (buf, len, pos, header, 10);\n if (!pos)\n goto DIE;\n ttl = ttlget (header + 4);\n uint16_unpack_big (header + 8, &datalen);\n if (dns_domain_equal (t1, d))\n {\n if (byte_equal (header + 2, 2, DNS_C_IN))\n { /* should always be true */\n if (typematch (header, dtype))\n {\n if (!response_rstart (t1, header, ttl))\n goto DIE;\n\n if (typematch (header, DNS_T_NS)\n || typematch (header, DNS_T_CNAME)\n || typematch (header, DNS_T_PTR))\n {\n if (!dns_packet_getname (buf, len, pos, &t2))\n goto DIE;\n if (!response_addname (t2))\n goto DIE;\n }\n else if (typematch (header, DNS_T_MX))\n {\n pos2 = dns_packet_copy (buf, len, pos, misc, 2);\n if (!pos2)\n goto DIE;\n if (!response_addbytes (misc, 2))\n goto DIE;\n if (!dns_packet_getname (buf, len, pos2, &t2))\n goto DIE;\n if (!response_addname (t2))\n goto DIE;\n }\n else if (typematch (header, DNS_T_SOA))\n {\n pos2 = dns_packet_getname (buf, len, pos, &t2);\n if (!pos2)\n goto DIE;\n if (!response_addname (t2))\n goto DIE;\n pos2 = dns_packet_getname (buf, len, pos2, &t3);\n if (!pos2)\n goto DIE;\n if (!response_addname (t3))\n goto DIE;\n pos2 = dns_packet_copy (buf, len, pos2, misc, 20);\n if (!pos2)\n goto DIE;\n if (!response_addbytes (misc, 20))\n goto DIE;\n }\n else\n {\n if (pos + datalen > len)\n goto DIE;\n if (!response_addbytes (buf + pos, datalen))\n goto DIE;\n }\n response_rfinish(RESPONSE_ANSWER);\n }\n }\n }\n pos += datalen;\n }\n cleanup (z);\n\n return 1;\n }\n\n if (!dns_domain_suffix (d, referral))\n goto DIE;\n control = d + dns_domain_suffixpos (d, referral);\n z->control[z->level] = control;\n byte_zero (z->servers[z->level], 64);\n for (j = 0; j < QUERY_MAXNS; ++j)\n dns_domain_free (&z->ns[z->level][j]);\n k = 0;\n\n pos = posauthority;\n for (j = 0; j < numauthority; ++j)\n {\n pos = dns_packet_getname (buf, len, pos, &t1);\n if (!pos)\n goto DIE;\n pos = dns_packet_copy (buf, len, pos, header, 10);\n if (!pos)\n goto DIE;\n\n uint16_unpack_big (header + 8, &datalen);\n if (dns_domain_equal (referral, t1)) /* should always be true */\n if (typematch (header, DNS_T_NS)) /* should always be true */\n /* should always be true */\n if (byte_equal (header + 2, 2, DNS_C_IN))\n if (k < QUERY_MAXNS)\n if (!dns_packet_getname (buf, len, pos,\n &z->ns[z->level][k++]))\n goto DIE;\n pos += datalen;\n }\n\n goto HAVENS;\n\n\nSERVFAIL:\n if (z->level)\n goto LOWERLEVEL;\n if (!rqa (z))\n goto DIE;\n response_servfail ();\n cleanup (z);\n\n return 1;\n\n\nDIE:\n cleanup (z);\n if (records)\n {\n alloc_free (records);\n records = 0;\n }\n\n return -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'Make Start of Authority(SOA) responses cache-able.\n\nThis patch fixes dnscache to cache SOA responses sent to clients.\nThis fixes one of the cache poisoning vulnerability reported by\nMr Mark Johnson -> https://bugzilla.redhat.com/show_bug.cgi?id=838965.\n\nNonetheless the original patch for this issue was created by\nMr Jeff king -> http://www.your.org/dnscache/\n\nSincere thanks to Mr Mark for reporting this issue and Mr Jeff for\ncreating the patch and releasing it under public domain.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: dns_transmit_get (struct dns_transmit *d, const iopause_fd *x,\n const struct taia *when)\n{\n char udpbuf[4097];\n int r = 0, fd = 0;\n unsigned char ch = 0;\n\n fd = d->s1 - 1;\n errno = error_io;\n\n if (!x->revents)\n {\n if (taia_less (when, &d->deadline))\n return 0;\n errno = error_timeout;\n if (d->tcpstate == 0)\n return nextudp (d);\n\n return nexttcp (d);\n }\n\n if (d->tcpstate == 0)\n {\n /*\n * have attempted to send UDP query to each server udploop times\n * have sent query to curserver on UDP socket s\n */\n r = recv (fd, udpbuf, sizeof (udpbuf), 0);\n if (r <= 0)\n {\n if (errno == error_connrefused && d->udploop == 2)\n return 0;\n\n return nextudp (d);\n }\n if (r + 1 > sizeof (udpbuf))\n return 0;\n\n if (irrelevant (d, udpbuf, r))\n return 0;\n if (serverwantstcp (udpbuf, r))\n return firsttcp (d);\n if (serverfailed (udpbuf, r))\n {\n if (d->udploop == 2)\n return 0;\n\n return nextudp (d);\n }\n socketfree (d);\n\n d->packetlen = r;\n d->packet = alloc (d->packetlen);\n if (!d->packet)\n {\n dns_transmit_free (d);\n return -1;\n }\n byte_copy (d->packet, d->packetlen, udpbuf);\n\n queryfree (d);\n return 1;\n }\n\n if (d->tcpstate == 1)\n {\n /*\n * have sent connection attempt to curserver on TCP socket s\n * pos not defined\n */\n if (!socket_connected (fd))\n return nexttcp (d);\n\n d->pos = 0;\n d->tcpstate = 2;\n\n return 0;\n }\n\n if (d->tcpstate == 2)\n {\n /* \n * have connection to curserver on TCP socket s have sent pos bytes\n * of query\n */\n r = write (fd, d->query + d->pos, d->querylen - d->pos);\n if (r <= 0)\n return nexttcp (d);\n\n d->pos += r;\n if (d->pos == d->querylen)\n {\n struct taia now;\n\n taia_now (&now);\n taia_uint (&d->deadline, 10);\n taia_add (&d->deadline, &d->deadline, &now);\n d->tcpstate = 3;\n }\n\n return 0;\n }\n\n if (d->tcpstate == 3)\n {\n /*\n * have sent entire query to curserver on TCP socket s\n * pos not defined\n */\n r = read (fd, &ch, 1);\n if (r <= 0)\n return nexttcp (d);\n \n d->packetlen = ch;\n d->tcpstate = 4;\n\n return 0;\n }\n\n if (d->tcpstate == 4)\n {\n /*\n * have sent entire query to curserver on TCP socket s\n * pos not defined\n * have received one byte of packet length into packetlen\n */\n r = read (fd, &ch, 1);\n if (r <= 0)\n return nexttcp (d);\n\n d->pos = 0;\n d->tcpstate = 5;\n d->packetlen <<= 8;\n d->packetlen += ch;\n d->packet = alloc (d->packetlen);\n if (!d->packet)\n {\n dns_transmit_free (d);\n return -1;\n }\n\n return 0;\n }\n\n if (d->tcpstate == 5)\n {\n /*\n * have sent entire query to curserver on TCP socket s have received\n * entire packet length into packetlen packet is allocated have\n * received pos bytes of packet\n */\n r = read (fd, d->packet + d->pos, d->packetlen - d->pos);\n if (r <= 0)\n return nexttcp (d);\n\n d->pos += r;\n if (d->pos < d->packetlen)\n return 0;\n\n socketfree (d);\n if (irrelevant (d, d->packet, d->packetlen))\n return nexttcp(d);\n if (serverwantstcp (d->packet, d->packetlen))\n return nexttcp(d);\n if (serverfailed (d->packet, d->packetlen))\n return nexttcp(d);\n\n queryfree(d);\n return 1;\n }\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'Merge identical outgoing requests - patch 2.\n\nThis patch fixes dnscache to combine *same* client queries into one\nsingle outgoing request, thus securing the server from possible cache\npoisoning attacks. The merges operation takes place in the\ndns_transmit layer, rather than between query and dns_transmit layers,\nas done in the previous patch.\n\nThis fixes one of the cache poisoning vulnerability reported by\nMr Mark Johnson -> https://bugzilla.redhat.com/show_bug.cgi?id=838965.\n\nNonetheless the original patch for this issue was created by\nMr Jeff king -> http://marc.info/?l=djbdns&m=123859517723684&w=3#2\n\nSincere thanks to Mr Mark for reporting this issue and Mr Jeff for\ncreating the patch and releasing it under GPLv2.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: OFCondition WlmActivityManager::StartProvidingService()\n// Date : December 10, 2001\n// Author : Thomas Wilkens\n// Task : Starts providing the implemented service for calling SCUs.\n// After having created an instance of this class, this function\n// shall be called from main.\n// Parameters : none.\n// Return Value : Return value that is supposed to be returned from main().\n{\n OFCondition cond = EC_Normal;\n T_ASC_Network *net = NULL;\n\n // Make sure data dictionary is loaded.\n if( !dcmDataDict.isDictionaryLoaded() )\n {\n DCMWLM_WARN(\"no data dictionary loaded, check environment variable: \" << DCM_DICT_ENVIRONMENT_VARIABLE);\n }\n\n#ifndef DISABLE_PORT_PERMISSION_CHECK\n#ifdef HAVE_GETEUID\n // If port is privileged we must be as well.\n if( opt_port < 1024 && geteuid() != 0 )\n return( WLM_EC_InsufficientPortPrivileges );\n#endif\n#endif\n\n#ifdef _WIN32\n /* if this process was started by CreateProcess, opt_forkedChild is set */\n if (opt_forkedChild)\n {\n /* tell dcmnet DUL about child process status, too */\n DUL_markProcessAsForkedChild();\n\n char buf[256];\n DWORD bytesRead = 0;\n HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE);\n\n // read socket handle number from stdin, i.e. the anonymous pipe\n // to which our parent process has written the handle number.\n if (ReadFile(hStdIn, buf, sizeof(buf), &bytesRead, NULL))\n {\n // make sure buffer is zero terminated\n buf[bytesRead] = '\\0';\n dcmExternalSocketHandle.set(atoi(buf));\n }\n else\n {\n DCMWLM_ERROR(\"cannot read socket handle: \" << GetLastError());\n exit(0);\n }\n }\n else\n {\n // parent process\n if (!opt_singleProcess)\n DUL_requestForkOnTransportConnectionReceipt(cmd_argc, cmd_argv);\n }\n#endif\n\n // Initialize network, i.e. create an instance of T_ASC_Network*.\n cond = ASC_initializeNetwork( NET_ACCEPTOR, OFstatic_cast(int, opt_port), opt_acse_timeout, &net );\n if( cond.bad() ) return( WLM_EC_InitializationOfNetworkConnectionFailed );\n\n#if defined(HAVE_SETUID) && defined(HAVE_GETUID)\n // Return to normal uid so that we can't do too much damage in case\n // things go very wrong. Only works if the program is setuid root,\n // and run by another user. Running as root user may be\n // potentially disasterous if this program screws up badly.\n setuid( getuid() );\n#endif\n\n // If we get to this point, the entire initialization process has been completed\n // successfully. Now, we want to start handling all incoming requests. Since\n // this activity is supposed to represent a server process, we do not want to\n // terminate this activity. Hence, create an endless while-loop.\n while( cond.good() )\n {\n // Wait for an association and handle the requests of\n // the calling applications correspondingly.\n cond = WaitForAssociation( net );\n\n // Clean up any child processes if the execution is not limited to a single process.\n // (On windows platform, childs are not handled via the process table,\n // so there's no need to clean up children)\n#ifdef HAVE_FORK\n if( !opt_singleProcess )\n CleanChildren();\n#elif defined(_WIN32)\n // if running in multi-process mode, always terminate child after one association\n // for unix, this is done in WaitForAssociation() with exit()\n if (DUL_processIsForkedChild()) break;\n#endif\n }\n // Drop the network, i.e. free memory of T_ASC_Network* structure. This call\n // is the counterpart of ASC_initializeNetwork(...) which was called above.\n cond = ASC_dropNetwork( &net );\n if( cond.bad() ) return( WLM_EC_TerminationOfNetworkConnectionFailed );\n\n // return ok\n return( EC_Normal );\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'Make sure to handle setuid() return code properly.\n\nIn some tools the return value of setuid() is not checked. In the worst\ncase this could lead to privilege escalation since the process does not\ngive up its root privileges and continue as root.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ossl_cipher_initialize(VALUE self, VALUE str)\n{\n EVP_CIPHER_CTX *ctx;\n const EVP_CIPHER *cipher;\n char *name;\n unsigned char key[EVP_MAX_KEY_LENGTH];\n\n name = StringValuePtr(str);\n GetCipherInit(self, ctx);\n if (ctx) {\n\tossl_raise(rb_eRuntimeError, \"Cipher already inititalized!\");\n }\n AllocCipher(self, ctx);\n EVP_CIPHER_CTX_init(ctx);\n if (!(cipher = EVP_get_cipherbyname(name))) {\n\tossl_raise(rb_eRuntimeError, \"unsupported cipher algorithm (%s)\", name);\n }\n /*\n * The EVP which has EVP_CIPH_RAND_KEY flag (such as DES3) allows\n * uninitialized key, but other EVPs (such as AES) does not allow it.\n * Calling EVP_CipherUpdate() without initializing key causes SEGV so we\n * set the data filled with \"\\0\" as the key by default.\n */\n memset(key, 0, EVP_MAX_KEY_LENGTH);\n if (EVP_CipherInit_ex(ctx, cipher, NULL, key, NULL, -1) != 1)\n\tossl_raise(eCipherError, NULL);\n\n return self;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-326'], 'message': '* ext/openssl/ossl_cipher.c: remove the encryption key initialization\n from Cipher#initialize. This is effectively a revert of r32723\n (\"Avoid possible SEGV from AES encryption/decryption\", 2011-07-28).\n the patch is derived from https://github.com/ruby/openssl/commit/8108e0a6db133f3375608303fdd2083eb5115062,\n written by Kazuki Yamaguchi.\n [Backport #8221]\n\n\ngit-svn-id: svn+ssh://ci.ruby-lang.org/ruby/branches/ruby_2_3@59267 b2dd03c8-39d4-4d8f-98ff-823fe69b080e'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int local_mkdir(FsContext *fs_ctx, V9fsPath *dir_path,\n const char *name, FsCred *credp)\n{\n int err = -1;\n int dirfd;\n\n dirfd = local_opendir_nofollow(fs_ctx, dir_path->data);\n if (dirfd == -1) {\n return -1;\n }\n\n if (fs_ctx->export_flags & V9FS_SM_MAPPED ||\n fs_ctx->export_flags & V9FS_SM_MAPPED_FILE) {\n err = mkdirat(dirfd, name, SM_LOCAL_DIR_MODE_BITS);\n if (err == -1) {\n goto out;\n }\n credp->fc_mode = credp->fc_mode | S_IFDIR;\n\n if (fs_ctx->export_flags & V9FS_SM_MAPPED) {\n err = local_set_xattrat(dirfd, name, credp);\n } else {\n err = local_set_mapped_file_attrat(dirfd, name, credp);\n }\n if (err == -1) {\n goto err_end;\n }\n } else if (fs_ctx->export_flags & V9FS_SM_PASSTHROUGH ||\n fs_ctx->export_flags & V9FS_SM_NONE) {\n err = mkdirat(dirfd, name, credp->fc_mode);\n if (err == -1) {\n goto out;\n }\n err = local_set_cred_passthrough(fs_ctx, dirfd, name, credp);\n if (err == -1) {\n goto err_end;\n }\n }\n goto out;\n\nerr_end:\n unlinkat_preserve_errno(dirfd, name, AT_REMOVEDIR);\nout:\n close_preserve_errno(dirfd);\n return err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-732'], 'message': '9pfs: local: forbid client access to metadata (CVE-2017-7493)\n\nWhen using the mapped-file security mode, we shouldn't let the client mess\nwith the metadata. The current code already tries to hide the metadata dir\nfrom the client by skipping it in local_readdir(). But the client can still\naccess or modify it through several other operations. This can be used to\nescalate privileges in the guest.\n\nAffected backend operations are:\n- local_mknod()\n- local_mkdir()\n- local_open2()\n- local_symlink()\n- local_link()\n- local_unlinkat()\n- local_renameat()\n- local_rename()\n- local_name_to_path()\n\nOther operations are safe because they are only passed a fid path, which\nis computed internally in local_name_to_path().\n\nThis patch converts all the functions listed above to fail and return\nEINVAL when being passed the name of the metadata dir. This may look\nlike a poor choice for errno, but there's no such thing as an illegal\npath name on Linux and I could not think of anything better.\n\nThis fixes CVE-2017-7493.\n\nReported-by: Leo Gaspard \nSigned-off-by: Greg Kurz \nReviewed-by: Eric Blake '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void qemu_input_event_send_key(QemuConsole *src, KeyValue *key, bool down)\n{\n InputEvent *evt;\n evt = qemu_input_event_new_key(key, down);\n if (QTAILQ_EMPTY(&kbd_queue)) {\n qemu_input_event_send(src, evt);\n qemu_input_event_sync();\n qapi_free_InputEvent(evt);\n } else {\n qemu_input_queue_event(&kbd_queue, src, evt);\n qemu_input_queue_sync(&kbd_queue);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-772'], 'message': 'input: limit kbd queue depth\n\nApply a limit to the number of items we accept into the keyboard queue.\n\nImpact: Without this limit vnc clients can exhaust host memory by\nsending keyboard events faster than qemu feeds them to the guest.\n\nFixes: CVE-2017-8379\nCc: P J P \nCc: Huawei PSIRT \nReported-by: jiangxin1@huawei.com\nSigned-off-by: Gerd Hoffmann \nMessage-id: 20170428084237.23960-1-kraxel@redhat.com'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int32_t ClockMath::floorDivide(int32_t numerator, int32_t denominator) {\n return (numerator >= 0) ?\n numerator / denominator : ((numerator + 1) / denominator) - 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'ICU-12504 in ICU4C Persian cal, use int64_t math for one operation to avoid overflow; add tests in C and J\n\nX-SVN-Rev: 40654'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: main (int argc, char *argv[])\n{\n struct nbd_handle *nbd;\n /* We will connect to a custom nbdkit sh plugin which always fails\n * on reads (with a precise spelling required for older nbdkit), and\n * which delays responding to writes until a witness file no longer\n * exists.\n */\n const char *cmd[] = { \"nbdkit\", \"-s\", \"-v\", \"--exit-with-parent\", \"sh\",\n script, NULL };\n uint32_t strict;\n\n progname = argv[0];\n\n if (atexit (cleanup) != 0) {\n perror (\"atexit\");\n exit (EXIT_FAILURE);\n }\n if ((script_fd = mkstemp (script)) == -1) {\n perror (\"mkstemp\");\n exit (EXIT_FAILURE);\n }\n if ((witness_fd = mkstemp (witness)) == -1) {\n perror (\"mkstemp\");\n exit (EXIT_FAILURE);\n }\n\n if (dprintf (script_fd, \"case $1 in\\n\"\n \" get_size) echo 128m || exit 1 ;;\\n\"\n \" thread_model) echo serialize_all_requests; exit 0 ;;\\n\"\n \" # XXX require 512-alignment, with new enough nbdkit\\n\"\n \" pread) printf 'ENOMEM ' >&2; exit 1 ;;\\n\"\n \" can_write) exit 0 ;;\\n\"\n \" pwrite)\\n\"\n \" while test -e %s; do sleep 1; done\\n\"\n \" exit 0;;\\n\"\n \" *) exit 2 ;;\\n\"\n \"esac\\n\", witness) < 0) {\n perror (\"dprintf\");\n exit (EXIT_FAILURE);\n }\n if (fchmod (script_fd, 0700) == -1) {\n perror (\"fchmod\");\n exit (EXIT_FAILURE);\n }\n if (close (script_fd) == -1) { /* Unlinked later during atexit */\n perror (\"close\");\n exit (EXIT_FAILURE);\n }\n script_fd = -2;\n\n nbd = nbd_create ();\n if (nbd == NULL) {\n fprintf (stderr, \"%s\\n\", nbd_get_error ());\n exit (EXIT_FAILURE);\n }\n\n /* Attempt to set an enum to garbage. */\n if (nbd_set_tls (nbd, LIBNBD_TLS_REQUIRE + 1) != -1) {\n fprintf (stderr, \"%s: test failed: \"\n \"nbd_set_tls did not reject invalid enum\\n\",\n argv[0]);\n exit (EXIT_FAILURE);\n }\n if (nbd_get_tls (nbd) != LIBNBD_TLS_DISABLE) {\n fprintf (stderr, \"%s: test failed: \"\n \"nbd_get_tls not left at default value\\n\",\n argv[0]);\n exit (EXIT_FAILURE);\n }\n\n /* Attempt to set a bitmask with an unknown bit. */\n if (nbd_set_handshake_flags (nbd, LIBNBD_HANDSHAKE_FLAG_MASK + 1) != -1) {\n fprintf (stderr, \"%s: test failed: \"\n \"nbd_set_handshake_flags did not reject invalid bitmask\\n\",\n argv[0]);\n exit (EXIT_FAILURE);\n }\n if (nbd_get_handshake_flags (nbd) != LIBNBD_HANDSHAKE_FLAG_MASK) {\n fprintf (stderr, \"%s: test failed: \"\n \"nbd_get_handshake_flags not left at default value\\n\",\n argv[0]);\n exit (EXIT_FAILURE);\n }\n\n\n /* Issue a connected command when not connected. */\n buf[0] = '1';\n if (nbd_pread (nbd, buf, 512, 0, 0) != -1) {\n fprintf (stderr, \"%s: test failed: \"\n \"nbd_pread did not fail on non-connected handle\\n\",\n argv[0]);\n exit (EXIT_FAILURE);\n }\n check (ENOTCONN, \"nbd_pread: \");\n if (buf[0] != '\\0') {\n fprintf (stderr, \"%s: test failed: \"\n \"nbd_pread did not sanitize buffer on error\\n\",\n argv[0]);\n exit (EXIT_FAILURE);\n }\n\n /* Request a name that is too long. */\n memset (buf, 'a', 4999);\n buf[4999] = '\\0';\n if (nbd_set_export_name (nbd, buf) != -1) {\n fprintf (stderr, \"%s: test failed: \"\n \"nbd_set_export_name did not reject large name\\n\",\n argv[0]);\n exit (EXIT_FAILURE);\n }\n check (ENAMETOOLONG, \"nbd_set_export_name: \");\n\n /* Poll while there is no fd. */\n if (nbd_aio_get_fd (nbd) != -1) {\n fprintf (stderr, \"%s: test failed: \"\n \"nbd_aio_get_fd did not fail prior to connection\\n\",\n argv[0]);\n }\n check (EINVAL, \"nbd_aio_get_fd: \");\n if (nbd_poll (nbd, 1000) != -1) {\n fprintf (stderr, \"%s: test failed: \"\n \"nbd_poll did not fail prior to connection\\n\",\n argv[0]);\n }\n check (EINVAL, \"nbd_poll: \");\n\n /* Connect to a working server, then try to connect again. */\n if (nbd_connect_command (nbd, (char **) cmd) == -1) {\n fprintf (stderr, \"%s: %s\\n\", argv[0], nbd_get_error ());\n exit (EXIT_FAILURE);\n }\n if (nbd_connect_command (nbd, (char **) cmd) != -1) {\n fprintf (stderr, \"%s: test failed: \"\n \"nbd_connect_command did not reject repeat attempt\\n\",\n argv[0]);\n exit (EXIT_FAILURE);\n }\n check (EINVAL, \"nbd_connect_command: \");\n\n /* nbd_opt_abort can only be called during negotiation. */\n if (nbd_opt_abort (nbd) != -1) {\n fprintf (stderr, \"%s: test failed: \"\n \"nbd_opt_abort did not reject attempt in wrong state\\n\",\n argv[0]);\n exit (EXIT_FAILURE);\n }\n check (EINVAL, \"nbd_opt_abort: \");\n\n /* Try to notify that writes are ready when we aren't blocked on POLLOUT */\n if (nbd_aio_notify_write (nbd) != -1) {\n fprintf (stderr, \"%s: test failed: \"\n \"nbd_aio_notify_write in wrong state did not fail\\n\",\n argv[0]);\n exit (EXIT_FAILURE);\n }\n check (EINVAL, \"nbd_aio_notify_write: \");\n\n /* Check for status of a bogus cookie */\n if (nbd_aio_command_completed (nbd, 0) != -1) {\n fprintf (stderr, \"%s: test failed: \"\n \"nbd_aio_command_completed on bogus cookie did not fail\\n\",\n argv[0]);\n exit (EXIT_FAILURE);\n }\n check (EINVAL, \"nbd_aio_command_completed: \");\n\n /* Read from an invalid offset, client-side */\n strict = nbd_get_strict_mode (nbd) | LIBNBD_STRICT_BOUNDS;\n if (nbd_set_strict_mode (nbd, strict) == -1) {\n fprintf (stderr, \"%s\\n\", nbd_get_error ());\n exit (EXIT_FAILURE);\n }\n if (nbd_aio_pread (nbd, buf, 512, -1, NBD_NULL_COMPLETION, 0) != -1) {\n fprintf (stderr, \"%s: test failed: \"\n \"nbd_aio_pread did not fail with bogus offset\\n\",\n argv[0]);\n exit (EXIT_FAILURE);\n }\n check (EINVAL, \"nbd_aio_pread: \");\n\n /* We guarantee callbacks will be freed even on all error paths. */\n if (nbd_aio_pread_structured (nbd, buf, 512, -1,\n (nbd_chunk_callback) { .free = check_chunk, },\n (nbd_completion_callback) {\n .free = check_completion, },\n 0) != -1) {\n fprintf (stderr, \"%s: test failed: \"\n \"nbd_aio_pread_structured did not fail with bogus offset\\n\",\n argv[0]);\n exit (EXIT_FAILURE);\n }\n check (EINVAL, \"nbd_aio_pread_structured: \");\n if (!chunk_clean || !completion_clean) {\n fprintf (stderr, \"%s: test failed: \"\n \"callbacks not freed on nbd_aio_pread_structured failure\\n\",\n argv[0]);\n exit (EXIT_FAILURE);\n }\n\n /* Read from an invalid offset, server-side */\n strict &= ~LIBNBD_STRICT_BOUNDS;\n if (nbd_set_strict_mode (nbd, strict) == -1) {\n fprintf (stderr, \"%s\\n\", nbd_get_error ());\n exit (EXIT_FAILURE);\n }\n check_server_fail (nbd,\n nbd_aio_pread (nbd, buf, 512, -1, NBD_NULL_COMPLETION, 0),\n \"nbd_aio_pread with bogus offset\", EINVAL);\n\n /* Use in-range unknown command flags, client-side */\n strict = nbd_get_strict_mode (nbd) | LIBNBD_STRICT_FLAGS;\n if (nbd_set_strict_mode (nbd, strict) == -1) {\n fprintf (stderr, \"%s\\n\", nbd_get_error ());\n exit (EXIT_FAILURE);\n }\n if (nbd_aio_pread (nbd, buf, 512, 0, NBD_NULL_COMPLETION,\n LIBNBD_CMD_FLAG_MASK + 1) != -1) {\n fprintf (stderr, \"%s: test failed: \"\n \"nbd_aio_pread did not fail with bogus flags\\n\",\n argv[0]);\n exit (EXIT_FAILURE);\n }\n check (EINVAL, \"nbd_aio_pread: \");\n /* Use in-range unknown command flags, server-side */\n strict &= ~LIBNBD_STRICT_FLAGS;\n if (nbd_set_strict_mode (nbd, strict) == -1) {\n fprintf (stderr, \"%s\\n\", nbd_get_error ());\n exit (EXIT_FAILURE);\n }\n check_server_fail (nbd, nbd_aio_pread (nbd, buf, 512, 0, NBD_NULL_COMPLETION,\n LIBNBD_CMD_FLAG_MASK + 1),\n \"nbd_aio_pread with bogus flag\", EINVAL);\n /* Use out-of-range unknown command flags, client-side */\n if (nbd_aio_pread (nbd, buf, 512, 0, NBD_NULL_COMPLETION, 0x10000) != -1) {\n fprintf (stderr, \"%s: test failed: \"\n \"nbd_aio_pread did not fail with bogus flags\\n\",\n argv[0]);\n exit (EXIT_FAILURE);\n }\n check (EINVAL, \"nbd_aio_pread: \");\n\n /* Check that oversized requests are rejected */\n if (nbd_pread (nbd, buf, MAXSIZE, 0, 0) != -1) {\n fprintf (stderr, \"%s: test failed: \"\n \"nbd_pread did not fail with oversize request\\n\",\n argv[0]);\n exit (EXIT_FAILURE);\n }\n check (ERANGE, \"nbd_pread: \");\n if (nbd_aio_pwrite (nbd, buf, MAXSIZE, 0,\n NBD_NULL_COMPLETION, 0) != -1) {\n fprintf (stderr, \"%s: test failed: \"\n \"nbd_aio_pwrite did not fail with oversize request\\n\",\n argv[0]);\n exit (EXIT_FAILURE);\n }\n check (ERANGE, \"nbd_aio_pwrite: \");\n\n /* Use unadvertised command, client-side */\n strict = nbd_get_strict_mode (nbd) | LIBNBD_STRICT_COMMANDS;\n if (nbd_set_strict_mode (nbd, strict) == -1) {\n fprintf (stderr, \"%s\\n\", nbd_get_error ());\n exit (EXIT_FAILURE);\n }\n if (nbd_aio_trim (nbd, 512, 0, NBD_NULL_COMPLETION, 0) != -1) {\n fprintf (stderr, \"%s: test failed: \"\n \"unpermitted nbd_aio_trim did not fail\\n\",\n argv[0]);\n exit (EXIT_FAILURE);\n }\n check (EINVAL, \"nbd_aio_trim: \");\n /* Use unadvertised command, server-side */\n strict &= ~LIBNBD_STRICT_COMMANDS;\n if (nbd_set_strict_mode (nbd, strict) == -1) {\n fprintf (stderr, \"%s\\n\", nbd_get_error ());\n exit (EXIT_FAILURE);\n }\n check_server_fail (nbd, nbd_aio_trim (nbd, 512, 0, NBD_NULL_COMPLETION, 0),\n \"unadvertised nbd_aio_trim\", EINVAL);\n\n /* Send a read that the nbdkit sh plugin will fail. */\n if (nbd_pread (nbd, buf, 512, 0, 0) != -1) {\n fprintf (stderr, \"%s: test failed: \"\n \"nbd_pread did not report server failure\\n\",\n argv[0]);\n exit (EXIT_FAILURE);\n }\n check (ENOMEM, \"nbd_pread: \");\n\n /* Send a zero-sized read, client-side */\n strict = nbd_get_strict_mode (nbd) | LIBNBD_STRICT_ZERO_SIZE;\n if (nbd_set_strict_mode (nbd, strict) == -1) {\n fprintf (stderr, \"%s\\n\", nbd_get_error ());\n exit (EXIT_FAILURE);\n }\n if (nbd_aio_pread (nbd, buf, 0, 0, NBD_NULL_COMPLETION, 0) != -1) {\n fprintf (stderr, \"%s: test failed: \"\n \"zero-size nbd_aio_pread did not fail\\n\",\n argv[0]);\n exit (EXIT_FAILURE);\n }\n check (EINVAL, \"nbd_aio_pread: \");\n /* Send a zero-sized read, server-side */\n strict &= ~LIBNBD_STRICT_ZERO_SIZE;\n if (nbd_set_strict_mode (nbd, strict) == -1) {\n fprintf (stderr, \"%s\\n\", nbd_get_error ());\n exit (EXIT_FAILURE);\n }\n check_server_fail (nbd,\n nbd_aio_pread (nbd, buf, 0, 0, NBD_NULL_COMPLETION, 0),\n \"zero-size nbd_aio_pread\", EINVAL);\n\n /* XXX nbdkit does not yet have a way to test STRICT_ALIGN */\n if (nbd_get_block_size (nbd, LIBNBD_SIZE_MINIMUM) > 1) {\n /* Send an unaligned read, client-side */\n strict = nbd_get_strict_mode (nbd) | LIBNBD_STRICT_ALIGN;\n if (nbd_set_strict_mode (nbd, strict) == -1) {\n fprintf (stderr, \"%s\\n\", nbd_get_error ());\n exit (EXIT_FAILURE);\n }\n if (nbd_aio_pread (nbd, buf, 1, 1, NBD_NULL_COMPLETION, 0) != -1) {\n fprintf (stderr, \"%s: test failed: \"\n \"unaligned nbd_aio_pread did not fail\\n\",\n argv[0]);\n exit (EXIT_FAILURE);\n }\n check (EINVAL, \"nbd_aio_pread: \");\n /* Send an unaligned read, server-side */\n strict &= ~LIBNBD_STRICT_ALIGN;\n if (nbd_set_strict_mode (nbd, strict) == -1) {\n fprintf (stderr, \"%s\\n\", nbd_get_error ());\n exit (EXIT_FAILURE);\n }\n check_server_fail (nbd,\n nbd_aio_pread (nbd, buf, 1, 1, NBD_NULL_COMPLETION, 0),\n \"unaligned nbd_aio_pread\", EINVAL);\n }\n else\n fprintf (stderr, \"skipping alignment tests, nbdkit too old\\n\");\n\n /* Queue up two write commands so large that we block on POLLIN (the\n * first might not block when under load, such as valgrind, but the\n * second definitely will, since the nbdkit sh plugin reads only one\n * command at a time and stalls on the first), then queue multiple\n * disconnects.\n */\n if (nbd_aio_pwrite (nbd, buf, 2 * 1024 * 1024, 0,\n NBD_NULL_COMPLETION, 0) == -1) {\n fprintf (stderr, \"%s: %s\\n\", argv[0], nbd_get_error ());\n exit (EXIT_FAILURE);\n }\n if (nbd_aio_pwrite (nbd, buf, 2 * 1024 * 1024, 0,\n NBD_NULL_COMPLETION, 0) == -1) {\n fprintf (stderr, \"%s: %s\\n\", argv[0], nbd_get_error ());\n exit (EXIT_FAILURE);\n }\n if ((nbd_aio_get_direction (nbd) & LIBNBD_AIO_DIRECTION_WRITE) == 0) {\n fprintf (stderr, \"%s: test failed: \"\n \"expect to be blocked on write\\n\",\n argv[0]);\n exit (EXIT_FAILURE);\n }\n if (nbd_aio_disconnect (nbd, 0) == -1) {\n fprintf (stderr, \"%s: %s\\n\", argv[0], nbd_get_error ());\n exit (EXIT_FAILURE);\n }\n if (nbd_aio_disconnect (nbd, 0) != -1) {\n fprintf (stderr, \"%s: test failed: \"\n \"no diagnosis that nbd_aio_disconnect prevents new commands\\n\",\n argv[0]);\n exit (EXIT_FAILURE);\n }\n check (EINVAL, \"nbd_aio_disconnect: \");\n\n /* Unblock the nbdkit sh plugin */\n if (close (witness_fd) == -1) {\n perror (\"close\");\n exit (EXIT_FAILURE);\n }\n witness_fd = -1;\n if (unlink (witness) == -1) {\n perror (\"unlink\");\n exit (EXIT_FAILURE);\n }\n\n /* Flush the queue (whether this one fails is a race with how fast\n * the server shuts down, so don't enforce status), then try to send\n * another command while CLOSED/DEAD\n */\n if (nbd_shutdown (nbd, 0) == -1) {\n fprintf (stderr, \"%s: ignoring %s\\n\", argv[0], nbd_get_error ());\n }\n else\n fprintf (stderr, \"%s: shutdown completed successfully\\n\", argv[0]);\n if (nbd_pread (nbd, buf, 512, 0, 0) != -1) {\n fprintf (stderr, \"%s: test failed: \"\n \"nbd_pread did not fail on non-connected handle\\n\",\n argv[0]);\n exit (EXIT_FAILURE);\n }\n check (EINVAL, \"nbd_pread: \");\n\n nbd_close (nbd);\n exit (EXIT_SUCCESS);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-252'], 'message': 'api: Add new API nbd_set_pread_initialize()\n\nThe recent patch series for CVE-2022-0485 demonstrated that when\napplications using libnbd are not careful about error checking, the\ndifference on whether a data leak is at least sanitized (all zeroes,\npartial reads, or data leftover from a prior read) vs. a dangerous\ninformation leak (uninitialized data from the heap) was partly under\nlibnbd's control. The previous two patches changed libnbd to always\nsanitize, as a security hardening technique that prevents heap leaks\nno matter how buggy the client app is. But a blind memset() also adds\nan execution delay, even if it doesn't show up as the hot spot in our\nprofiling when compared to the time spent with network traffic.\n\nAt any rate, if client apps choose to pre-initialize their buffers, or\notherwise audit their code to take on their own risk about not\ndereferencing a buffer on failure paths, then the time spent by libnbd\ndoing memset() is wasted; so it is worth adding a knob to let a user\nopt in to faster execution at the expense of giving up our memset()\nhardening on their behalf.\n\nIn addition to adding two new APIs, this patch also causes changes to\nthe four existing APIs nbd_{aio_,}pread{,_structured}, with those\ngenerated lib/api.c changes looking like:\n\n| --- lib/api.c.bak\t2022-02-10 08:17:09.973381979 -0600\n| +++ lib/api.c\t2022-02-10 08:22:27.503428024 -0600\n| @@ -2871,7 +2914,8 @@ nbd_pread (struct nbd_handle *h, void *b\n| debug (h, \"enter: buf= count=%zu offset=%\" PRIu64 \" flags=0x%x\", count, offset, flags);\n| }\n|\n| - memset (buf, 0, count);\n| + if (h->pread_initialize)\n| + memset (buf, 0, count);\n| if (unlikely (!pread_in_permitted_state (h))) {\n| ret = -1;\n| goto out;\n\nMessage-Id: <20220209220726.1902761-4-eblake@redhat.com>\nAcked-by: Laszlo Ersek \n[eblake: enhance commit message to show generated file diff, mention CVE\nin doc text]\nReviewed-by: Richard W.M. Jones \n\n(cherry picked from commit e0953cb71250947bb97b25e34ff1ea34bd504bf3)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void dwgCompressor::copyCompBytes21(duint8 *cbuf, duint8 *dbuf, duint32 l, duint32 si, duint32 di){\n duint32 length =l;\n duint32 dix = di;\n duint32 six = si;\n\n while (length > 31){\n //in doc: 16-31, 0-15\n for (duint32 i = six+24; i \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-191'], 'message': 'fixed heap buffer overflow vulnerability CVE-2021-21899\n\nas reported in TALOS-2021-1350 / CVE-2021-21899,\ndwgCompressor::decompress21() could be abused with a malformed DWG file\nto force heap buffer overflow and possibly lead to malicious code\nexecution.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: virtual~DRW_TableEntry() {\n for (std::vector::iterator it=extData.begin(); it!=extData.end(); ++it)\n delete *it;\n\n extData.clear();\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-191'], 'message': 'fixed heap use after free vulnerability CVE-2021-21900\n\nas reported in TALOS-2021-1351 / CVE-2021-21900,\nDRW_TableEntry::parseCode had the potential to trigger an use after free exception with a malformed DXF file.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ctcompare(const char *a,\t\t/* I - First string */\n const char *b)\t\t/* I - Second string */\n{\n int\tresult = 0;\t\t\t/* Result */\n\n\n while (*a && *b)\n {\n result |= *a ^ *b;\n a ++;\n b ++;\n }\n\n return (result);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284'], 'message': 'CVE-2022-26691: An incorrect comparison in local admin authentication'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static MagickBooleanType WritePDFImage(const ImageInfo *image_info,Image *image,\n ExceptionInfo *exception)\n{\n#define CFormat \"/Filter [ /%s ]\\n\"\n#define ObjectsPerImage 14\n\nDisableMSCWarning(4310)\n static const char\n XMPProfile[]=\n {\n \"\\n\"\n \"\\n\"\n \" \\n\"\n \" \\n\"\n \" %s\\n\"\n \" %s\\n\"\n \" %s\\n\"\n \" %s\\n\"\n \" \\n\"\n \" \\n\"\n \" application/pdf\\n\"\n \" \\n\"\n \" \\n\"\n \" %s\\n\"\n \" \\n\"\n \" \\n\"\n \" \\n\"\n \" \\n\"\n \" uuid:6ec119d7-7982-4f56-808d-dfe64f5b35cf\\n\"\n \" uuid:a79b99b4-6235-447f-9f6c-ec18ef7555cb\\n\"\n \" \\n\"\n \" \\n\"\n \" %s\\n\"\n \" \\n\"\n \" \\n\"\n \" 3\\n\"\n \" B\\n\"\n \" \\n\"\n \" \\n\"\n \"\\n\"\n \"\\n\"\n },\n XMPProfileMagick[4]= { (char) 0xef, (char) 0xbb, (char) 0xbf, (char) 0x00 };\nRestoreMSCWarning\n\n char\n basename[MagickPathExtent],\n buffer[MagickPathExtent],\n *escape,\n date[MagickPathExtent],\n **labels,\n page_geometry[MagickPathExtent],\n *url;\n\n CompressionType\n compression;\n\n const char\n *device,\n *option,\n *value;\n\n const StringInfo\n *profile;\n\n double\n pointsize;\n\n GeometryInfo\n geometry_info;\n\n Image\n *next,\n *tile_image;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n offset,\n scene,\n *xref;\n\n MagickSizeType\n number_pixels;\n\n MagickStatusType\n flags;\n\n PointInfo\n delta,\n resolution,\n scale;\n\n RectangleInfo\n geometry,\n media_info,\n page_info;\n\n register const Quantum\n *p;\n\n register unsigned char\n *q;\n\n register ssize_t\n i,\n x;\n\n size_t\n channels,\n info_id,\n length,\n object,\n pages_id,\n root_id,\n text_size,\n version;\n\n ssize_t\n count,\n page_count,\n y;\n\n struct tm\n local_time;\n\n time_t\n seconds;\n\n unsigned char\n *pixels;\n\n wchar_t\n *utf16;\n\n /*\n Open output image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);\n if (status == MagickFalse)\n return(status);\n /*\n Allocate X ref memory.\n */\n xref=(MagickOffsetType *) AcquireQuantumMemory(2048UL,sizeof(*xref));\n if (xref == (MagickOffsetType *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) ResetMagickMemory(xref,0,2048UL*sizeof(*xref));\n /*\n Write Info object.\n */\n object=0;\n version=3;\n if (image_info->compression == JPEG2000Compression)\n version=(size_t) MagickMax(version,5);\n for (next=image; next != (Image *) NULL; next=GetNextImageInList(next))\n if (next->alpha_trait != UndefinedPixelTrait)\n version=(size_t) MagickMax(version,4);\n if (LocaleCompare(image_info->magick,\"PDFA\") == 0)\n version=(size_t) MagickMax(version,6);\n profile=GetImageProfile(image,\"icc\");\n if (profile != (StringInfo *) NULL)\n version=(size_t) MagickMax(version,7);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%%PDF-1.%.20g \\n\",(double)\n version);\n (void) WriteBlobString(image,buffer);\n if (LocaleCompare(image_info->magick,\"PDFA\") == 0)\n {\n (void) WriteBlobByte(image,'%');\n (void) WriteBlobByte(image,0xe2);\n (void) WriteBlobByte(image,0xe3);\n (void) WriteBlobByte(image,0xcf);\n (void) WriteBlobByte(image,0xd3);\n (void) WriteBlobByte(image,'\\n');\n }\n /*\n Write Catalog object.\n */\n xref[object++]=TellBlob(image);\n root_id=object;\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n if (LocaleCompare(image_info->magick,\"PDFA\") != 0)\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Pages %.20g 0 R\\n\",\n (double) object+1);\n else\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Metadata %.20g 0 R\\n\",\n (double) object+1);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Pages %.20g 0 R\\n\",\n (double) object+2);\n }\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"/Type /Catalog\");\n option=GetImageOption(image_info,\"pdf:page-direction\");\n if ((option != (const char *) NULL) &&\n (LocaleCompare(option,\"right-to-left\") != MagickFalse))\n (void) WriteBlobString(image,\"/ViewerPreferences<>\\n\");\n (void) WriteBlobString(image,\"\\n\");\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n GetPathComponent(image->filename,BasePath,basename);\n if (LocaleCompare(image_info->magick,\"PDFA\") == 0)\n {\n char\n create_date[MagickPathExtent],\n modify_date[MagickPathExtent],\n timestamp[MagickPathExtent],\n *url,\n xmp_profile[MagickPathExtent];\n\n /*\n Write XMP object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n (void) WriteBlobString(image,\"/Subtype /XML\\n\");\n *modify_date='\\0';\n value=GetImageProperty(image,\"date:modify\",exception);\n if (value != (const char *) NULL)\n (void) CopyMagickString(modify_date,value,MagickPathExtent);\n *create_date='\\0';\n value=GetImageProperty(image,\"date:create\",exception);\n if (value != (const char *) NULL)\n (void) CopyMagickString(create_date,value,MagickPathExtent);\n (void) FormatMagickTime(time((time_t *) NULL),MagickPathExtent,timestamp);\n url=GetMagickHomeURL();\n escape=EscapeParenthesis(basename);\n i=FormatLocaleString(xmp_profile,MagickPathExtent,XMPProfile,\n XMPProfileMagick,modify_date,create_date,timestamp,url,escape,url);\n escape=DestroyString(escape);\n url=DestroyString(url);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g\\n\",\n (double) i);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"/Type /Metadata\\n\");\n (void) WriteBlobString(image,\">>\\nstream\\n\");\n (void) WriteBlobString(image,xmp_profile);\n (void) WriteBlobString(image,\"\\nendstream\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n }\n /*\n Write Pages object.\n */\n xref[object++]=TellBlob(image);\n pages_id=object;\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n (void) WriteBlobString(image,\"/Type /Pages\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Kids [ %.20g 0 R \",\n (double) object+1);\n (void) WriteBlobString(image,buffer);\n count=(ssize_t) (pages_id+ObjectsPerImage+1);\n page_count=1;\n if (image_info->adjoin != MagickFalse)\n {\n Image\n *kid_image;\n\n /*\n Predict page object id's.\n */\n kid_image=image;\n for ( ; GetNextImageInList(kid_image) != (Image *) NULL; count+=ObjectsPerImage)\n {\n page_count++;\n profile=GetImageProfile(kid_image,\"icc\");\n if (profile != (StringInfo *) NULL)\n count+=2;\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 R \",(double)\n count);\n (void) WriteBlobString(image,buffer);\n kid_image=GetNextImageInList(kid_image);\n }\n xref=(MagickOffsetType *) ResizeQuantumMemory(xref,(size_t) count+2048UL,\n sizeof(*xref));\n if (xref == (MagickOffsetType *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n (void) WriteBlobString(image,\"]\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Count %.20g\\n\",(double)\n page_count);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n scene=0;\n do\n {\n MagickBooleanType\n has_icc_profile;\n\n profile=GetImageProfile(image,\"icc\");\n has_icc_profile=(profile != (StringInfo *) NULL) ? MagickTrue : MagickFalse;\n compression=image->compression;\n if (image_info->compression != UndefinedCompression)\n compression=image_info->compression;\n switch (compression)\n {\n case FaxCompression:\n case Group4Compression:\n {\n if ((SetImageMonochrome(image,exception) == MagickFalse) ||\n (image->alpha_trait != UndefinedPixelTrait))\n compression=RLECompression;\n break;\n }\n#if !defined(MAGICKCORE_JPEG_DELEGATE)\n case JPEGCompression:\n {\n compression=RLECompression;\n (void) ThrowMagickException(exception,GetMagickModule(),\n MissingDelegateError,\"DelegateLibrarySupportNotBuiltIn\",\"`%s' (JPEG)\",\n image->filename);\n break;\n }\n#endif\n#if !defined(MAGICKCORE_LIBOPENJP2_DELEGATE)\n case JPEG2000Compression:\n {\n compression=RLECompression;\n (void) ThrowMagickException(exception,GetMagickModule(),\n MissingDelegateError,\"DelegateLibrarySupportNotBuiltIn\",\"`%s' (JP2)\",\n image->filename);\n break;\n }\n#endif\n#if !defined(MAGICKCORE_ZLIB_DELEGATE)\n case ZipCompression:\n {\n compression=RLECompression;\n (void) ThrowMagickException(exception,GetMagickModule(),\n MissingDelegateError,\"DelegateLibrarySupportNotBuiltIn\",\"`%s' (ZLIB)\",\n image->filename);\n break;\n }\n#endif\n case LZWCompression:\n {\n if (LocaleCompare(image_info->magick,\"PDFA\") == 0)\n compression=RLECompression; /* LZW compression is forbidden */\n break;\n }\n case NoCompression:\n {\n if (LocaleCompare(image_info->magick,\"PDFA\") == 0)\n compression=RLECompression; /* ASCII 85 compression is forbidden */\n break;\n }\n default:\n break;\n }\n if (compression == JPEG2000Compression)\n (void) TransformImageColorspace(image,sRGBColorspace,exception);\n /*\n Scale relative to dots-per-inch.\n */\n delta.x=DefaultResolution;\n delta.y=DefaultResolution;\n resolution.x=image->resolution.x;\n resolution.y=image->resolution.y;\n if ((resolution.x == 0.0) || (resolution.y == 0.0))\n {\n flags=ParseGeometry(PSDensityGeometry,&geometry_info);\n resolution.x=geometry_info.rho;\n resolution.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n resolution.y=resolution.x;\n }\n if (image_info->density != (char *) NULL)\n {\n flags=ParseGeometry(image_info->density,&geometry_info);\n resolution.x=geometry_info.rho;\n resolution.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n resolution.y=resolution.x;\n }\n if (image->units == PixelsPerCentimeterResolution)\n {\n resolution.x=(double) ((size_t) (100.0*2.54*resolution.x+0.5)/100.0);\n resolution.y=(double) ((size_t) (100.0*2.54*resolution.y+0.5)/100.0);\n }\n SetGeometry(image,&geometry);\n (void) FormatLocaleString(page_geometry,MagickPathExtent,\"%.20gx%.20g\",\n (double) image->columns,(double) image->rows);\n if (image_info->page != (char *) NULL)\n (void) CopyMagickString(page_geometry,image_info->page,MagickPathExtent);\n else\n if ((image->page.width != 0) && (image->page.height != 0))\n (void) FormatLocaleString(page_geometry,MagickPathExtent,\n \"%.20gx%.20g%+.20g%+.20g\",(double) image->page.width,(double)\n image->page.height,(double) image->page.x,(double) image->page.y);\n else\n if ((image->gravity != UndefinedGravity) &&\n (LocaleCompare(image_info->magick,\"PDF\") == 0))\n (void) CopyMagickString(page_geometry,PSPageGeometry,\n MagickPathExtent);\n (void) ConcatenateMagickString(page_geometry,\">\",MagickPathExtent);\n (void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y,\n &geometry.width,&geometry.height);\n scale.x=(double) (geometry.width*delta.x)/resolution.x;\n geometry.width=(size_t) floor(scale.x+0.5);\n scale.y=(double) (geometry.height*delta.y)/resolution.y;\n geometry.height=(size_t) floor(scale.y+0.5);\n (void) ParseAbsoluteGeometry(page_geometry,&media_info);\n (void) ParseGravityGeometry(image,page_geometry,&page_info,exception);\n if (image->gravity != UndefinedGravity)\n {\n geometry.x=(-page_info.x);\n geometry.y=(ssize_t) (media_info.height+page_info.y-image->rows);\n }\n pointsize=12.0;\n if (image_info->pointsize != 0.0)\n pointsize=image_info->pointsize;\n text_size=0;\n value=GetImageProperty(image,\"label\",exception);\n if (value != (const char *) NULL)\n text_size=(size_t) (MultilineCensus(value)*pointsize+12);\n (void) text_size;\n /*\n Write Page object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n (void) WriteBlobString(image,\"/Type /Page\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Parent %.20g 0 R\\n\",\n (double) pages_id);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"/Resources <<\\n\");\n labels=(char **) NULL;\n value=GetImageProperty(image,\"label\",exception);\n if (value != (const char *) NULL)\n labels=StringToList(value);\n if (labels != (char **) NULL)\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"/Font << /F%.20g %.20g 0 R >>\\n\",(double) image->scene,(double)\n object+4);\n (void) WriteBlobString(image,buffer);\n }\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"/XObject << /Im%.20g %.20g 0 R >>\\n\",(double) image->scene,(double)\n object+5);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/ProcSet %.20g 0 R >>\\n\",\n (double) object+3);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"/MediaBox [0 0 %g %g]\\n\",72.0*media_info.width/resolution.x,\n 72.0*media_info.height/resolution.y);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"/CropBox [0 0 %g %g]\\n\",72.0*media_info.width/resolution.x,\n 72.0*media_info.height/resolution.y);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Contents %.20g 0 R\\n\",\n (double) object+1);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Thumb %.20g 0 R\\n\",\n (double) object+(has_icc_profile != MagickFalse ? 10 : 8));\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Contents object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g 0 R\\n\",\n (double) object+1);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"stream\\n\");\n offset=TellBlob(image);\n (void) WriteBlobString(image,\"q\\n\");\n if (labels != (char **) NULL)\n for (i=0; labels[i] != (char *) NULL; i++)\n {\n (void) WriteBlobString(image,\"BT\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/F%.20g %g Tf\\n\",\n (double) image->scene,pointsize);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g %.20g Td\\n\",\n (double) geometry.x,(double) (geometry.y+geometry.height+i*pointsize+\n 12));\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"(%s) Tj\\n\",\n labels[i]);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"ET\\n\");\n labels[i]=DestroyString(labels[i]);\n }\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"%g 0 0 %g %.20g %.20g cm\\n\",scale.x,scale.y,(double) geometry.x,\n (double) geometry.y);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Im%.20g Do\\n\",(double)\n image->scene);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"Q\\n\");\n offset=TellBlob(image)-offset;\n (void) WriteBlobString(image,\"\\nendstream\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Length object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double)\n offset);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Procset object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n if ((image->storage_class == DirectClass) || (image->colors > 256))\n (void) CopyMagickString(buffer,\"[ /PDF /Text /ImageC\",MagickPathExtent);\n else\n if ((compression == FaxCompression) || (compression == Group4Compression))\n (void) CopyMagickString(buffer,\"[ /PDF /Text /ImageB\",MagickPathExtent);\n else\n (void) CopyMagickString(buffer,\"[ /PDF /Text /ImageI\",MagickPathExtent);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\" ]\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Font object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n if (labels != (char **) NULL)\n {\n (void) WriteBlobString(image,\"/Type /Font\\n\");\n (void) WriteBlobString(image,\"/Subtype /Type1\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Name /F%.20g\\n\",\n (double) image->scene);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"/BaseFont /Helvetica\\n\");\n (void) WriteBlobString(image,\"/Encoding /MacRomanEncoding\\n\");\n labels=(char **) RelinquishMagickMemory(labels);\n }\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write XObject object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n (void) WriteBlobString(image,\"/Type /XObject\\n\");\n (void) WriteBlobString(image,\"/Subtype /Image\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Name /Im%.20g\\n\",\n (double) image->scene);\n (void) WriteBlobString(image,buffer);\n switch (compression)\n {\n case NoCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"ASCII85Decode\");\n break;\n }\n case JPEGCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"DCTDecode\");\n if (image->colorspace != CMYKColorspace)\n break;\n (void) WriteBlobString(image,buffer);\n (void) CopyMagickString(buffer,\"/Decode [1 0 1 0 1 0 1 0]\\n\",\n MagickPathExtent);\n break;\n }\n case JPEG2000Compression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"JPXDecode\");\n if (image->colorspace != CMYKColorspace)\n break;\n (void) WriteBlobString(image,buffer);\n (void) CopyMagickString(buffer,\"/Decode [1 0 1 0 1 0 1 0]\\n\",\n MagickPathExtent);\n break;\n }\n case LZWCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"LZWDecode\");\n break;\n }\n case ZipCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"FlateDecode\");\n break;\n }\n case FaxCompression:\n case Group4Compression:\n {\n (void) CopyMagickString(buffer,\"/Filter [ /CCITTFaxDecode ]\\n\",\n MagickPathExtent);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/DecodeParms [ << \"\n \"/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\\n\",CCITTParam,\n (double) image->columns,(double) image->rows);\n break;\n }\n default:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"RunLengthDecode\");\n break;\n }\n }\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Width %.20g\\n\",(double)\n image->columns);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Height %.20g\\n\",(double)\n image->rows);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/ColorSpace %.20g 0 R\\n\",\n (double) object+2);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/BitsPerComponent %d\\n\",\n (compression == FaxCompression) || (compression == Group4Compression) ?\n 1 : 8);\n (void) WriteBlobString(image,buffer);\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/SMask %.20g 0 R\\n\",\n (double) object+(has_icc_profile != MagickFalse ? 9 : 7));\n (void) WriteBlobString(image,buffer);\n }\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g 0 R\\n\",\n (double) object+1);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"stream\\n\");\n offset=TellBlob(image);\n number_pixels=(MagickSizeType) image->columns*image->rows;\n if ((4*number_pixels) != (MagickSizeType) ((size_t) (4*number_pixels)))\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n if ((compression == FaxCompression) || (compression == Group4Compression) ||\n ((image_info->type != TrueColorType) &&\n (SetImageGray(image,exception) != MagickFalse)))\n {\n switch (compression)\n {\n case FaxCompression:\n case Group4Compression:\n {\n if (LocaleCompare(CCITTParam,\"0\") == 0)\n {\n (void) HuffmanEncodeImage(image_info,image,image,exception);\n break;\n }\n (void) Huffman2DEncodeImage(image_info,image,image,exception);\n break;\n }\n case JPEGCompression:\n {\n status=InjectImageBlob(image_info,image,image,\"jpeg\",exception);\n if (status == MagickFalse)\n {\n (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case JPEG2000Compression:\n {\n status=InjectImageBlob(image_info,image,image,\"jp2\",exception);\n if (status == MagickFalse)\n {\n (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case RLECompression:\n default:\n {\n MemoryInfo\n *pixel_info;\n\n /*\n Allocate pixel array.\n */\n length=(size_t) number_pixels;\n pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n /*\n Dump Runlength encoded pixels.\n */\n q=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n *q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma(image,p)));\n p+=GetPixelChannels(image);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)\n y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if (compression == ZipCompression)\n status=ZLIBEncodeImage(image,length,pixels,exception);\n else\n#endif\n if (compression == LZWCompression)\n status=LZWEncodeImage(image,length,pixels,exception);\n else\n status=PackbitsEncodeImage(image,length,pixels,exception);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (status == MagickFalse)\n {\n (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case NoCompression:\n {\n /*\n Dump uncompressed PseudoColor packets.\n */\n Ascii85Initialize(image);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(\n GetPixelLuma(image,p))));\n p+=GetPixelChannels(image);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)\n y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n Ascii85Flush(image);\n break;\n }\n }\n }\n else\n if ((image->storage_class == DirectClass) || (image->colors > 256) ||\n (compression == JPEGCompression) ||\n (compression == JPEG2000Compression))\n switch (compression)\n {\n case JPEGCompression:\n {\n status=InjectImageBlob(image_info,image,image,\"jpeg\",exception);\n if (status == MagickFalse)\n {\n (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case JPEG2000Compression:\n {\n status=InjectImageBlob(image_info,image,image,\"jp2\",exception);\n if (status == MagickFalse)\n {\n (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case RLECompression:\n default:\n {\n MemoryInfo\n *pixel_info;\n\n /*\n Allocate pixel array.\n */\n length=(size_t) number_pixels;\n length*=image->colorspace == CMYKColorspace ? 4UL : 3UL;\n pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n /*\n Dump runoffset encoded pixels.\n */\n q=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n *q++=ScaleQuantumToChar(GetPixelRed(image,p));\n *q++=ScaleQuantumToChar(GetPixelGreen(image,p));\n *q++=ScaleQuantumToChar(GetPixelBlue(image,p));\n if (image->colorspace == CMYKColorspace)\n *q++=ScaleQuantumToChar(GetPixelBlack(image,p));\n p+=GetPixelChannels(image);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)\n y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if (compression == ZipCompression)\n status=ZLIBEncodeImage(image,length,pixels,exception);\n else\n#endif\n if (compression == LZWCompression)\n status=LZWEncodeImage(image,length,pixels,exception);\n else\n status=PackbitsEncodeImage(image,length,pixels,exception);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (status == MagickFalse)\n {\n (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case NoCompression:\n {\n /*\n Dump uncompressed DirectColor packets.\n */\n Ascii85Initialize(image);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n Ascii85Encode(image,ScaleQuantumToChar(GetPixelRed(image,p)));\n Ascii85Encode(image,ScaleQuantumToChar(GetPixelGreen(image,p)));\n Ascii85Encode(image,ScaleQuantumToChar(GetPixelBlue(image,p)));\n if (image->colorspace == CMYKColorspace)\n Ascii85Encode(image,ScaleQuantumToChar(\n GetPixelBlack(image,p)));\n p+=GetPixelChannels(image);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)\n y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n Ascii85Flush(image);\n break;\n }\n }\n else\n {\n /*\n Dump number of colors and colormap.\n */\n switch (compression)\n {\n case RLECompression:\n default:\n {\n MemoryInfo\n *pixel_info;\n\n /*\n Allocate pixel array.\n */\n length=(size_t) number_pixels;\n pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowWriterException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n /*\n Dump Runlength encoded pixels.\n */\n q=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n *q++=(unsigned char) GetPixelIndex(image,p);\n p+=GetPixelChannels(image);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,\n (MagickOffsetType) y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if (compression == ZipCompression)\n status=ZLIBEncodeImage(image,length,pixels,exception);\n else\n#endif\n if (compression == LZWCompression)\n status=LZWEncodeImage(image,length,pixels,exception);\n else\n status=PackbitsEncodeImage(image,length,pixels,exception);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (status == MagickFalse)\n {\n (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case NoCompression:\n {\n /*\n Dump uncompressed PseudoColor packets.\n */\n Ascii85Initialize(image);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n Ascii85Encode(image,(unsigned char) GetPixelIndex(image,p));\n p+=GetPixelChannels(image);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,\n (MagickOffsetType) y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n Ascii85Flush(image);\n break;\n }\n }\n }\n offset=TellBlob(image)-offset;\n (void) WriteBlobString(image,\"\\nendstream\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Length object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double)\n offset);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Colorspace object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n device=\"DeviceRGB\";\n channels=0;\n if (image->colorspace == CMYKColorspace)\n {\n device=\"DeviceCMYK\";\n channels=4;\n }\n else\n if ((compression == FaxCompression) ||\n (compression == Group4Compression) ||\n ((image_info->type != TrueColorType) &&\n (SetImageGray(image,exception) != MagickFalse)))\n {\n device=\"DeviceGray\";\n channels=1;\n }\n else\n if ((image->storage_class == DirectClass) ||\n (image->colors > 256) || (compression == JPEGCompression) ||\n (compression == JPEG2000Compression))\n {\n device=\"DeviceRGB\";\n channels=3;\n }\n profile=GetImageProfile(image,\"icc\");\n if ((profile == (StringInfo *) NULL) || (channels == 0))\n {\n if (channels != 0)\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/%s\\n\",device);\n else\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"[ /Indexed /%s %.20g %.20g 0 R ]\\n\",device,(double) image->colors-\n 1,(double) object+3);\n (void) WriteBlobString(image,buffer);\n }\n else\n {\n const unsigned char\n *p;\n\n /*\n Write ICC profile. \n */\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"[/ICCBased %.20g 0 R]\\n\",(double) object+1);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"endobj\\n\");\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",\n (double) object);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"<<\\n/N %.20g\\n\"\n \"/Filter /ASCII85Decode\\n/Length %.20g 0 R\\n/Alternate /%s\\n>>\\n\"\n \"stream\\n\",(double) channels,(double) object+1,device);\n (void) WriteBlobString(image,buffer);\n offset=TellBlob(image);\n Ascii85Initialize(image);\n p=GetStringInfoDatum(profile);\n for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++)\n Ascii85Encode(image,(unsigned char) *p++);\n Ascii85Flush(image);\n offset=TellBlob(image)-offset;\n (void) WriteBlobString(image,\"endstream\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Length object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",\n (double) object);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double)\n offset);\n (void) WriteBlobString(image,buffer);\n }\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Thumb object.\n */\n SetGeometry(image,&geometry);\n (void) ParseMetaGeometry(\"106x106+0+0>\",&geometry.x,&geometry.y,\n &geometry.width,&geometry.height);\n tile_image=ThumbnailImage(image,geometry.width,geometry.height,exception);\n if (tile_image == (Image *) NULL)\n return(MagickFalse);\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n switch (compression)\n {\n case NoCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"ASCII85Decode\");\n break;\n }\n case JPEGCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"DCTDecode\");\n if (image->colorspace != CMYKColorspace)\n break;\n (void) WriteBlobString(image,buffer);\n (void) CopyMagickString(buffer,\"/Decode [1 0 1 0 1 0 1 0]\\n\",\n MagickPathExtent);\n break;\n }\n case JPEG2000Compression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"JPXDecode\");\n if (image->colorspace != CMYKColorspace)\n break;\n (void) WriteBlobString(image,buffer);\n (void) CopyMagickString(buffer,\"/Decode [1 0 1 0 1 0 1 0]\\n\",\n MagickPathExtent);\n break;\n }\n case LZWCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"LZWDecode\");\n break;\n }\n case ZipCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"FlateDecode\");\n break;\n }\n case FaxCompression:\n case Group4Compression:\n {\n (void) CopyMagickString(buffer,\"/Filter [ /CCITTFaxDecode ]\\n\",\n MagickPathExtent);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/DecodeParms [ << \"\n \"/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\\n\",CCITTParam,\n (double) tile_image->columns,(double) tile_image->rows);\n break;\n }\n default:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"RunLengthDecode\");\n break;\n }\n }\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Width %.20g\\n\",(double)\n tile_image->columns);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Height %.20g\\n\",(double)\n tile_image->rows);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/ColorSpace %.20g 0 R\\n\",\n (double) object-(has_icc_profile != MagickFalse ? 3 : 1));\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/BitsPerComponent %d\\n\",\n (compression == FaxCompression) || (compression == Group4Compression) ?\n 1 : 8);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g 0 R\\n\",\n (double) object+1);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"stream\\n\");\n offset=TellBlob(image);\n number_pixels=(MagickSizeType) tile_image->columns*tile_image->rows;\n if ((compression == FaxCompression) ||\n (compression == Group4Compression) ||\n ((image_info->type != TrueColorType) &&\n (SetImageGray(tile_image,exception) != MagickFalse)))\n {\n switch (compression)\n {\n case FaxCompression:\n case Group4Compression:\n {\n if (LocaleCompare(CCITTParam,\"0\") == 0)\n {\n (void) HuffmanEncodeImage(image_info,image,tile_image,\n exception);\n break;\n }\n (void) Huffman2DEncodeImage(image_info,image,tile_image,exception);\n break;\n }\n case JPEGCompression:\n {\n status=InjectImageBlob(image_info,image,tile_image,\"jpeg\",\n exception);\n if (status == MagickFalse)\n {\n (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case JPEG2000Compression:\n {\n status=InjectImageBlob(image_info,image,tile_image,\"jp2\",exception);\n if (status == MagickFalse)\n {\n (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case RLECompression:\n default:\n {\n MemoryInfo\n *pixel_info;\n\n /*\n Allocate pixel array.\n */\n length=(size_t) number_pixels;\n pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n {\n tile_image=DestroyImage(tile_image);\n ThrowWriterException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n /*\n Dump runlength encoded pixels.\n */\n q=pixels;\n for (y=0; y < (ssize_t) tile_image->rows; y++)\n {\n p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,\n exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) tile_image->columns; x++)\n {\n *q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma(\n tile_image,p)));\n p+=GetPixelChannels(tile_image);\n }\n }\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if (compression == ZipCompression)\n status=ZLIBEncodeImage(image,length,pixels,exception);\n else\n#endif\n if (compression == LZWCompression)\n status=LZWEncodeImage(image,length,pixels,exception);\n else\n status=PackbitsEncodeImage(image,length,pixels,exception);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (status == MagickFalse)\n {\n (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case NoCompression:\n {\n /*\n Dump uncompressed PseudoColor packets.\n */\n Ascii85Initialize(image);\n for (y=0; y < (ssize_t) tile_image->rows; y++)\n {\n p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,\n exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) tile_image->columns; x++)\n {\n Ascii85Encode(tile_image,ScaleQuantumToChar(ClampToQuantum(\n GetPixelLuma(tile_image,p))));\n p+=GetPixelChannels(tile_image);\n }\n }\n Ascii85Flush(image);\n break;\n }\n }\n }\n else\n if ((tile_image->storage_class == DirectClass) ||\n (tile_image->colors > 256) || (compression == JPEGCompression) ||\n (compression == JPEG2000Compression))\n switch (compression)\n {\n case JPEGCompression:\n {\n status=InjectImageBlob(image_info,image,tile_image,\"jpeg\",\n exception);\n if (status == MagickFalse)\n {\n (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case JPEG2000Compression:\n {\n status=InjectImageBlob(image_info,image,tile_image,\"jp2\",exception);\n if (status == MagickFalse)\n {\n (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case RLECompression:\n default:\n {\n MemoryInfo\n *pixel_info;\n\n /*\n Allocate pixel array.\n */\n length=(size_t) number_pixels;\n length*=tile_image->colorspace == CMYKColorspace ? 4UL : 3UL;\n pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n {\n tile_image=DestroyImage(tile_image);\n ThrowWriterException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n /*\n Dump runlength encoded pixels.\n */\n q=pixels;\n for (y=0; y < (ssize_t) tile_image->rows; y++)\n {\n p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,\n exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) tile_image->columns; x++)\n {\n *q++=ScaleQuantumToChar(GetPixelRed(tile_image,p));\n *q++=ScaleQuantumToChar(GetPixelGreen(tile_image,p));\n *q++=ScaleQuantumToChar(GetPixelBlue(tile_image,p));\n if (tile_image->colorspace == CMYKColorspace)\n *q++=ScaleQuantumToChar(GetPixelBlack(tile_image,p));\n p+=GetPixelChannels(tile_image);\n }\n }\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if (compression == ZipCompression)\n status=ZLIBEncodeImage(image,length,pixels,exception);\n else\n#endif\n if (compression == LZWCompression)\n status=LZWEncodeImage(image,length,pixels,exception);\n else\n status=PackbitsEncodeImage(image,length,pixels,exception);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (status == MagickFalse)\n {\n (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case NoCompression:\n {\n /*\n Dump uncompressed DirectColor packets.\n */\n Ascii85Initialize(image);\n for (y=0; y < (ssize_t) tile_image->rows; y++)\n {\n p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,\n exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) tile_image->columns; x++)\n {\n Ascii85Encode(image,ScaleQuantumToChar(\n GetPixelRed(tile_image,p)));\n Ascii85Encode(image,ScaleQuantumToChar(\n GetPixelGreen(tile_image,p)));\n Ascii85Encode(image,ScaleQuantumToChar(\n GetPixelBlue(tile_image,p)));\n if (image->colorspace == CMYKColorspace)\n Ascii85Encode(image,ScaleQuantumToChar(\n GetPixelBlack(tile_image,p)));\n p+=GetPixelChannels(tile_image);\n }\n }\n Ascii85Flush(image);\n break;\n }\n }\n else\n {\n /*\n Dump number of colors and colormap.\n */\n switch (compression)\n {\n case RLECompression:\n default:\n {\n MemoryInfo\n *pixel_info;\n\n /*\n Allocate pixel array.\n */\n length=(size_t) number_pixels;\n pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n {\n tile_image=DestroyImage(tile_image);\n ThrowWriterException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n /*\n Dump runlength encoded pixels.\n */\n q=pixels;\n for (y=0; y < (ssize_t) tile_image->rows; y++)\n {\n p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,\n exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) tile_image->columns; x++)\n {\n *q++=(unsigned char) GetPixelIndex(tile_image,p);\n p+=GetPixelChannels(tile_image);\n }\n }\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if (compression == ZipCompression)\n status=ZLIBEncodeImage(image,length,pixels,exception);\n else\n#endif\n if (compression == LZWCompression)\n status=LZWEncodeImage(image,length,pixels,exception);\n else\n status=PackbitsEncodeImage(image,length,pixels,exception);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (status == MagickFalse)\n {\n (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case NoCompression:\n {\n /*\n Dump uncompressed PseudoColor packets.\n */\n Ascii85Initialize(image);\n for (y=0; y < (ssize_t) tile_image->rows; y++)\n {\n p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,\n exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) tile_image->columns; x++)\n {\n Ascii85Encode(image,(unsigned char)\n GetPixelIndex(tile_image,p));\n p+=GetPixelChannels(image);\n }\n }\n Ascii85Flush(image);\n break;\n }\n }\n }\n tile_image=DestroyImage(tile_image);\n offset=TellBlob(image)-offset;\n (void) WriteBlobString(image,\"\\nendstream\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Length object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double)\n offset);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"endobj\\n\");\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n if ((image->storage_class == DirectClass) || (image->colors > 256) ||\n (compression == FaxCompression) || (compression == Group4Compression))\n (void) WriteBlobString(image,\">>\\n\");\n else\n {\n /*\n Write Colormap object.\n */\n if (compression == NoCompression)\n (void) WriteBlobString(image,\"/Filter [ /ASCII85Decode ]\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g 0 R\\n\",\n (double) object+1);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"stream\\n\");\n offset=TellBlob(image);\n if (compression == NoCompression)\n Ascii85Initialize(image);\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n if (compression == NoCompression)\n {\n Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(\n image->colormap[i].red)));\n Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(\n image->colormap[i].green)));\n Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(\n image->colormap[i].blue)));\n continue;\n }\n (void) WriteBlobByte(image,ScaleQuantumToChar(\n ClampToQuantum(image->colormap[i].red)));\n (void) WriteBlobByte(image,ScaleQuantumToChar(\n ClampToQuantum(image->colormap[i].green)));\n (void) WriteBlobByte(image,ScaleQuantumToChar(\n ClampToQuantum(image->colormap[i].blue)));\n }\n if (compression == NoCompression)\n Ascii85Flush(image);\n offset=TellBlob(image)-offset;\n (void) WriteBlobString(image,\"\\nendstream\\n\");\n }\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Length object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double)\n offset);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write softmask object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n if (image->alpha_trait == UndefinedPixelTrait)\n (void) WriteBlobString(image,\">>\\n\");\n else\n {\n (void) WriteBlobString(image,\"/Type /XObject\\n\");\n (void) WriteBlobString(image,\"/Subtype /Image\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Name /Ma%.20g\\n\",\n (double) image->scene);\n (void) WriteBlobString(image,buffer);\n switch (compression)\n {\n case NoCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"ASCII85Decode\");\n break;\n }\n case LZWCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"LZWDecode\");\n break;\n }\n case ZipCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"FlateDecode\");\n break;\n }\n default:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"RunLengthDecode\");\n break;\n }\n }\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Width %.20g\\n\",\n (double) image->columns);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Height %.20g\\n\",\n (double) image->rows);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"/ColorSpace /DeviceGray\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"/BitsPerComponent %d\\n\",(compression == FaxCompression) ||\n (compression == Group4Compression) ? 1 : 8);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g 0 R\\n\",\n (double) object+1);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"stream\\n\");\n offset=TellBlob(image);\n number_pixels=(MagickSizeType) image->columns*image->rows;\n switch (compression)\n {\n case RLECompression:\n default:\n {\n MemoryInfo\n *pixel_info;\n\n /*\n Allocate pixel array.\n */\n length=(size_t) number_pixels;\n pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n {\n image=DestroyImage(image);\n ThrowWriterException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n /*\n Dump Runlength encoded pixels.\n */\n q=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n *q++=ScaleQuantumToChar(GetPixelAlpha(image,p));\n p+=GetPixelChannels(image);\n }\n }\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if (compression == ZipCompression)\n status=ZLIBEncodeImage(image,length,pixels,exception);\n else\n#endif\n if (compression == LZWCompression)\n status=LZWEncodeImage(image,length,pixels,exception);\n else\n status=PackbitsEncodeImage(image,length,pixels,exception);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (status == MagickFalse)\n {\n (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case NoCompression:\n {\n /*\n Dump uncompressed PseudoColor packets.\n */\n Ascii85Initialize(image);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n Ascii85Encode(image,ScaleQuantumToChar(GetPixelAlpha(image,p)));\n p+=GetPixelChannels(image);\n }\n }\n Ascii85Flush(image);\n break;\n }\n }\n offset=TellBlob(image)-offset;\n (void) WriteBlobString(image,\"\\nendstream\\n\");\n }\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Length object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double)\n offset);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"endobj\\n\");\n if (GetNextImageInList(image) == (Image *) NULL)\n break;\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,SaveImagesTag,scene++,\n GetImageListLength(image));\n if (status == MagickFalse)\n break;\n } while (image_info->adjoin != MagickFalse);\n /*\n Write Metadata object.\n */\n xref[object++]=TellBlob(image);\n info_id=object;\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n utf16=ConvertUTF8ToUTF16((unsigned char *) basename,&length);\n if (utf16 != (wchar_t *) NULL)\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Title (\\xfe\\xff\");\n (void) WriteBlobString(image,buffer);\n for (i=0; i < (ssize_t) length; i++)\n (void) WriteBlobMSBShort(image,(unsigned short) utf16[i]);\n (void) FormatLocaleString(buffer,MagickPathExtent,\")\\n\");\n (void) WriteBlobString(image,buffer);\n utf16=(wchar_t *) RelinquishMagickMemory(utf16);\n }\n seconds=time((time_t *) NULL);\n#if defined(MAGICKCORE_HAVE_LOCALTIME_R)\n (void) localtime_r(&seconds,&local_time);\n#else\n (void) memcpy(&local_time,localtime(&seconds),sizeof(local_time));\n#endif\n (void) FormatLocaleString(date,MagickPathExtent,\"D:%04d%02d%02d%02d%02d%02d\",\n local_time.tm_year+1900,local_time.tm_mon+1,local_time.tm_mday,\n local_time.tm_hour,local_time.tm_min,local_time.tm_sec);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/CreationDate (%s)\\n\",\n date);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/ModDate (%s)\\n\",date);\n (void) WriteBlobString(image,buffer);\n url=GetMagickHomeURL();\n escape=EscapeParenthesis(url);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Producer (%s)\\n\",escape);\n escape=DestroyString(escape);\n url=DestroyString(url);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Xref object.\n */\n offset=TellBlob(image)-xref[0]+\n (LocaleCompare(image_info->magick,\"PDFA\") == 0 ? 6 : 0)+10;\n (void) WriteBlobString(image,\"xref\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"0 %.20g\\n\",(double)\n object+1);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"0000000000 65535 f \\n\");\n for (i=0; i < (ssize_t) object; i++)\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%010lu 00000 n \\n\",\n (unsigned long) xref[i]);\n (void) WriteBlobString(image,buffer);\n }\n (void) WriteBlobString(image,\"trailer\\n\");\n (void) WriteBlobString(image,\"<<\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Size %.20g\\n\",(double)\n object+1);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Info %.20g 0 R\\n\",(double)\n info_id);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Root %.20g 0 R\\n\",(double)\n root_id);\n (void) WriteBlobString(image,buffer);\n (void) SignatureImage(image,exception);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/ID [<%s> <%s>]\\n\",\n GetImageProperty(image,\"signature\",exception),\n GetImageProperty(image,\"signature\",exception));\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"startxref\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"%%EOF\\n\");\n xref=(MagickOffsetType *) RelinquishMagickMemory(xref);\n (void) CloseBlob(image);\n return(MagickTrue);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-772', 'CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/576'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void rose_write_internal(struct sock *sk, int frametype)\n{\n\tstruct rose_sock *rose = rose_sk(sk);\n\tstruct sk_buff *skb;\n\tunsigned char *dptr;\n\tunsigned char lci1, lci2;\n\tchar buffer[100];\n\tint len, faclen = 0;\n\n\tlen = AX25_BPQ_HEADER_LEN + AX25_MAX_HEADER_LEN + ROSE_MIN_LEN + 1;\n\n\tswitch (frametype) {\n\tcase ROSE_CALL_REQUEST:\n\t\tlen += 1 + ROSE_ADDR_LEN + ROSE_ADDR_LEN;\n\t\tfaclen = rose_create_facilities(buffer, rose);\n\t\tlen += faclen;\n\t\tbreak;\n\tcase ROSE_CALL_ACCEPTED:\n\tcase ROSE_CLEAR_REQUEST:\n\tcase ROSE_RESET_REQUEST:\n\t\tlen += 2;\n\t\tbreak;\n\t}\n\n\tif ((skb = alloc_skb(len, GFP_ATOMIC)) == NULL)\n\t\treturn;\n\n\t/*\n\t *\tSpace for AX.25 header and PID.\n\t */\n\tskb_reserve(skb, AX25_BPQ_HEADER_LEN + AX25_MAX_HEADER_LEN + 1);\n\n\tdptr = skb_put(skb, skb_tailroom(skb));\n\n\tlci1 = (rose->lci >> 8) & 0x0F;\n\tlci2 = (rose->lci >> 0) & 0xFF;\n\n\tswitch (frametype) {\n\tcase ROSE_CALL_REQUEST:\n\t\t*dptr++ = ROSE_GFI | lci1;\n\t\t*dptr++ = lci2;\n\t\t*dptr++ = frametype;\n\t\t*dptr++ = 0xAA;\n\t\tmemcpy(dptr, &rose->dest_addr, ROSE_ADDR_LEN);\n\t\tdptr += ROSE_ADDR_LEN;\n\t\tmemcpy(dptr, &rose->source_addr, ROSE_ADDR_LEN);\n\t\tdptr += ROSE_ADDR_LEN;\n\t\tmemcpy(dptr, buffer, faclen);\n\t\tdptr += faclen;\n\t\tbreak;\n\n\tcase ROSE_CALL_ACCEPTED:\n\t\t*dptr++ = ROSE_GFI | lci1;\n\t\t*dptr++ = lci2;\n\t\t*dptr++ = frametype;\n\t\t*dptr++ = 0x00;\t\t/* Address length */\n\t\t*dptr++ = 0;\t\t/* Facilities length */\n\t\tbreak;\n\n\tcase ROSE_CLEAR_REQUEST:\n\t\t*dptr++ = ROSE_GFI | lci1;\n\t\t*dptr++ = lci2;\n\t\t*dptr++ = frametype;\n\t\t*dptr++ = rose->cause;\n\t\t*dptr++ = rose->diagnostic;\n\t\tbreak;\n\n\tcase ROSE_RESET_REQUEST:\n\t\t*dptr++ = ROSE_GFI | lci1;\n\t\t*dptr++ = lci2;\n\t\t*dptr++ = frametype;\n\t\t*dptr++ = ROSE_DTE_ORIGINATED;\n\t\t*dptr++ = 0;\n\t\tbreak;\n\n\tcase ROSE_RR:\n\tcase ROSE_RNR:\n\t\t*dptr++ = ROSE_GFI | lci1;\n\t\t*dptr++ = lci2;\n\t\t*dptr = frametype;\n\t\t*dptr++ |= (rose->vr << 5) & 0xE0;\n\t\tbreak;\n\n\tcase ROSE_CLEAR_CONFIRMATION:\n\tcase ROSE_RESET_CONFIRMATION:\n\t\t*dptr++ = ROSE_GFI | lci1;\n\t\t*dptr++ = lci2;\n\t\t*dptr++ = frametype;\n\t\tbreak;\n\n\tdefault:\n\t\tprintk(KERN_ERR \"ROSE: rose_write_internal - invalid frametype %02X\\n\", frametype);\n\t\tkfree_skb(skb);\n\t\treturn;\n\t}\n\n\trose_transmit_link(skb, rose->neighbour);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'rose: Add length checks to CALL_REQUEST parsing\n\nDefine some constant offsets for CALL_REQUEST based on the description\nat and the\ndefinition of ROSE as using 10-digit (5-byte) addresses. Use them\nconsistently. Validate all implicit and explicit facilities lengths.\nValidate the address length byte rather than either trusting or\nassuming its value.\n\nSigned-off-by: Ben Hutchings \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: mrb_f_send(mrb_state *mrb, mrb_value self)\n{\n mrb_sym name;\n mrb_value block, *regs;\n mrb_method_t m;\n struct RClass *c;\n mrb_callinfo *ci = mrb->c->ci;\n int n = ci->n;\n\n if (ci->cci > CINFO_NONE) {\n funcall:;\n const mrb_value *argv;\n mrb_int argc;\n mrb_get_args(mrb, \"n*&\", &name, &argv, &argc, &block);\n return mrb_funcall_with_block(mrb, self, name, argc, argv, block);\n }\n\n regs = mrb->c->ci->stack+1;\n\n if (n == 0) {\n mrb_argnum_error(mrb, 0, 1, -1);\n }\n else if (n == 15) {\n name = mrb_obj_to_sym(mrb, RARRAY_PTR(regs[0])[0]);\n }\n else {\n name = mrb_obj_to_sym(mrb, regs[0]);\n }\n\n c = mrb_class(mrb, self);\n m = mrb_method_search_vm(mrb, &c, name);\n if (MRB_METHOD_UNDEF_P(m)) { /* call method_mising */\n goto funcall;\n }\n\n ci->mid = name;\n ci->u.target_class = c;\n /* remove first symbol from arguments */\n if (n == 15) { /* variable length arguments */\n regs[0] = mrb_ary_subseq(mrb, regs[0], 1, RARRAY_LEN(regs[0]) - 1);\n }\n else { /* n > 0 */\n for (int i=0; ink > 0) {\n regs[n+1] = regs[n+2]; /* copy block */\n }\n ci->n--;\n }\n\n if (MRB_METHOD_CFUNC_P(m)) {\n if (MRB_METHOD_NOARG_P(m)) {\n check_method_noarg(mrb, ci);\n }\n\n if (MRB_METHOD_PROC_P(m)) {\n mrb_vm_ci_proc_set(ci, MRB_METHOD_PROC(m));\n }\n return MRB_METHOD_CFUNC(m)(mrb, self);\n }\n return exec_irep(mrb, self, MRB_METHOD_PROC(m));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-122', 'CWE-787'], 'message': 'vm.c: packed arguments length may be zero for `send` method.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static ssize_t fuse_fill_write_pages(struct fuse_req *req,\n\t\t\t struct address_space *mapping,\n\t\t\t struct iov_iter *ii, loff_t pos)\n{\n\tstruct fuse_conn *fc = get_fuse_conn(mapping->host);\n\tunsigned offset = pos & (PAGE_CACHE_SIZE - 1);\n\tsize_t count = 0;\n\tint err;\n\n\treq->in.argpages = 1;\n\treq->page_descs[0].offset = offset;\n\n\tdo {\n\t\tsize_t tmp;\n\t\tstruct page *page;\n\t\tpgoff_t index = pos >> PAGE_CACHE_SHIFT;\n\t\tsize_t bytes = min_t(size_t, PAGE_CACHE_SIZE - offset,\n\t\t\t\t iov_iter_count(ii));\n\n\t\tbytes = min_t(size_t, bytes, fc->max_write - count);\n\n again:\n\t\terr = -EFAULT;\n\t\tif (iov_iter_fault_in_readable(ii, bytes))\n\t\t\tbreak;\n\n\t\terr = -ENOMEM;\n\t\tpage = grab_cache_page_write_begin(mapping, index, 0);\n\t\tif (!page)\n\t\t\tbreak;\n\n\t\tif (mapping_writably_mapped(mapping))\n\t\t\tflush_dcache_page(page);\n\n\t\ttmp = iov_iter_copy_from_user_atomic(page, ii, offset, bytes);\n\t\tflush_dcache_page(page);\n\n\t\tif (!tmp) {\n\t\t\tunlock_page(page);\n\t\t\tpage_cache_release(page);\n\t\t\tbytes = min(bytes, iov_iter_single_seg_count(ii));\n\t\t\tgoto again;\n\t\t}\n\n\t\terr = 0;\n\t\treq->pages[req->num_pages] = page;\n\t\treq->page_descs[req->num_pages].length = tmp;\n\t\treq->num_pages++;\n\n\t\tiov_iter_advance(ii, tmp);\n\t\tcount += tmp;\n\t\tpos += tmp;\n\t\toffset += tmp;\n\t\tif (offset == PAGE_CACHE_SIZE)\n\t\t\toffset = 0;\n\n\t\tif (!fc->big_writes)\n\t\t\tbreak;\n\t} while (iov_iter_count(ii) && count < fc->max_write &&\n\t\t req->num_pages < req->max_pages && offset == 0);\n\n\treturn count > 0 ? count : err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-835'], 'message': 'fuse: break infinite loop in fuse_fill_write_pages()\n\nI got a report about unkillable task eating CPU. Further\ninvestigation shows, that the problem is in the fuse_fill_write_pages()\nfunction. If iov's first segment has zero length, we get an infinite\nloop, because we never reach iov_iter_advance() call.\n\nFix this by calling iov_iter_advance() before repeating an attempt to\ncopy data from userspace.\n\nA similar problem is described in 124d3b7041f (\"fix writev regression:\npan hanging unkillable and un-straceable\"). If zero-length segmend\nis followed by segment with invalid address,\niov_iter_fault_in_readable() checks only first segment (zero-length),\niov_iter_copy_from_user_atomic() skips it, fails at second and\nreturns zero -> goto again without skipping zero-length segment.\n\nPatch calls iov_iter_advance() before goto again: we'll skip zero-length\nsegment at second iteraction and iov_iter_fault_in_readable() will detect\ninvalid address.\n\nSpecial thanks to Konstantin Khlebnikov, who helped a lot with the commit\ndescription.\n\nCc: Andrew Morton \nCc: Maxim Patlasov \nCc: Konstantin Khlebnikov \nSigned-off-by: Roman Gushchin \nSigned-off-by: Miklos Szeredi \nFixes: ea9b9907b82a (\"fuse: implement perform_write\")\nCc: '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: char *path_name(const struct name_path *path, const char *name)\n{\n\tconst struct name_path *p;\n\tchar *n, *m;\n\tint nlen = strlen(name);\n\tint len = nlen + 1;\n\n\tfor (p = path; p; p = p->up) {\n\t\tif (p->elem_len)\n\t\t\tlen += p->elem_len + 1;\n\t}\n\tn = xmalloc(len);\n\tm = n + len - (nlen + 1);\n\tstrcpy(m, name);\n\tfor (p = path; p; p = p->up) {\n\t\tif (p->elem_len) {\n\t\t\tm -= p->elem_len + 1;\n\t\t\tmemcpy(m, p->elem, p->elem_len);\n\t\t\tm[p->elem_len] = '/';\n\t\t}\n\t}\n\treturn n;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'prefer memcpy to strcpy\n\nWhen we already know the length of a string (e.g., because\nwe just malloc'd to fit it), it's nicer to use memcpy than\nstrcpy, as it makes it more obvious that we are not going to\noverflow the buffer (because the size we pass matches the\nsize in the allocation).\n\nThis also eliminates calls to strcpy, which make auditing\nthe code base harder.\n\nSigned-off-by: Jeff King \nSigned-off-by: Junio C Hamano '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: get_uncompressed_data(struct archive_read *a, const void **buff, size_t size,\n size_t minimum)\n{\n\tstruct _7zip *zip = (struct _7zip *)a->format->data;\n\tssize_t bytes_avail;\n\n\tif (zip->codec == _7Z_COPY && zip->codec2 == (unsigned long)-1) {\n\t\t/* Copy mode. */\n\n\t\t/*\n\t\t * Note: '1' here is a performance optimization.\n\t\t * Recall that the decompression layer returns a count of\n\t\t * available bytes; asking for more than that forces the\n\t\t * decompressor to combine reads by copying data.\n\t\t */\n\t\t*buff = __archive_read_ahead(a, 1, &bytes_avail);\n\t\tif (bytes_avail <= 0) {\n\t\t\tarchive_set_error(&a->archive,\n\t\t\t ARCHIVE_ERRNO_FILE_FORMAT,\n\t\t\t \"Truncated 7-Zip file data\");\n\t\t\treturn (ARCHIVE_FATAL);\n\t\t}\n\t\tif ((size_t)bytes_avail >\n\t\t zip->uncompressed_buffer_bytes_remaining)\n\t\t\tbytes_avail = (ssize_t)\n\t\t\t zip->uncompressed_buffer_bytes_remaining;\n\t\tif ((size_t)bytes_avail > size)\n\t\t\tbytes_avail = (ssize_t)size;\n\n\t\tzip->pack_stream_bytes_unconsumed = bytes_avail;\n\t} else if (zip->uncompressed_buffer_pointer == NULL) {\n\t\t/* Decompression has failed. */\n\t\tarchive_set_error(&(a->archive),\n\t\t ARCHIVE_ERRNO_MISC, \"Damaged 7-Zip archive\");\n\t\treturn (ARCHIVE_FATAL);\n\t} else {\n\t\t/* Packed mode. */\n\t\tif (minimum > zip->uncompressed_buffer_bytes_remaining) {\n\t\t\t/*\n\t\t\t * If remaining uncompressed data size is less than\n\t\t\t * the minimum size, fill the buffer up to the\n\t\t\t * minimum size.\n\t\t\t */\n\t\t\tif (extract_pack_stream(a, minimum) < 0)\n\t\t\t\treturn (ARCHIVE_FATAL);\n\t\t}\n\t\tif (size > zip->uncompressed_buffer_bytes_remaining)\n\t\t\tbytes_avail = (ssize_t)\n\t\t\t zip->uncompressed_buffer_bytes_remaining;\n\t\telse\n\t\t\tbytes_avail = (ssize_t)size;\n\t\t*buff = zip->uncompressed_buffer_pointer;\n\t\tzip->uncompressed_buffer_pointer += bytes_avail;\n\t}\n\tzip->uncompressed_buffer_bytes_remaining -= bytes_avail;\n\treturn (bytes_avail);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': '7zip: fix crash when parsing certain archives\n\nFuzzing with CRCs disabled revealed that a call to get_uncompressed_data()\nwould sometimes fail to return at least 'minimum' bytes. This can cause\nthe crc32() invocation in header_bytes to read off into invalid memory.\n\nA specially crafted archive can use this to cause a crash.\n\nAn ASAN trace is below, but ASAN is not required - an uninstrumented\nbinary will also crash.\n\n==7719==ERROR: AddressSanitizer: SEGV on unknown address 0x631000040000 (pc 0x7fbdb3b3ec1d bp 0x7ffe77a51310 sp 0x7ffe77a51150 T0)\n==7719==The signal is caused by a READ memory access.\n #0 0x7fbdb3b3ec1c in crc32_z (/lib/x86_64-linux-gnu/libz.so.1+0x2c1c)\n #1 0x84f5eb in header_bytes (/tmp/libarchive/bsdtar+0x84f5eb)\n #2 0x856156 in read_Header (/tmp/libarchive/bsdtar+0x856156)\n #3 0x84e134 in slurp_central_directory (/tmp/libarchive/bsdtar+0x84e134)\n #4 0x849690 in archive_read_format_7zip_read_header (/tmp/libarchive/bsdtar+0x849690)\n #5 0x5713b7 in _archive_read_next_header2 (/tmp/libarchive/bsdtar+0x5713b7)\n #6 0x570e63 in _archive_read_next_header (/tmp/libarchive/bsdtar+0x570e63)\n #7 0x6f08bd in archive_read_next_header (/tmp/libarchive/bsdtar+0x6f08bd)\n #8 0x52373f in read_archive (/tmp/libarchive/bsdtar+0x52373f)\n #9 0x5257be in tar_mode_x (/tmp/libarchive/bsdtar+0x5257be)\n #10 0x51daeb in main (/tmp/libarchive/bsdtar+0x51daeb)\n #11 0x7fbdb27cab96 in __libc_start_main /build/glibc-OTsEL5/glibc-2.27/csu/../csu/libc-start.c:310\n #12 0x41dd09 in _start (/tmp/libarchive/bsdtar+0x41dd09)\n\nThis was primarly done with afl and FairFuzz. Some early corpus entries\nmay have been generated by qsym.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void Compute(OpKernelContext* ctx) override {\n const Tensor& sorted_inputs_t = ctx->input(0);\n const Tensor& values_t = ctx->input(1);\n\n // must have same batch dim_size for both\n OP_REQUIRES(ctx, sorted_inputs_t.dim_size(0) == values_t.dim_size(0),\n Status(error::INVALID_ARGUMENT,\n \"Leading dim_size of both tensors must match.\"));\n\n // this is required because we do indexing in int32 on the GPU\n OP_REQUIRES(ctx, values_t.NumElements() < std::numeric_limits::max(),\n Status(error::INVALID_ARGUMENT,\n \"values tensor size must less than INT_MAX\"));\n\n Tensor* output_t;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, values_t.shape(), &output_t));\n\n if (output_t->dtype() == DT_INT32) {\n OP_REQUIRES(ctx,\n FastBoundsCheck(sorted_inputs_t.dim_size(1),\n std::numeric_limits::max()),\n errors::InvalidArgument(\"trailing dim_size must less than \"\n \"INT_MAX for int32 output type, was \",\n sorted_inputs_t.dim_size(1)));\n }\n\n auto output = output_t->template flat();\n const auto sorted_inputs = sorted_inputs_t.template flat();\n const auto values = values_t.template flat();\n OP_REQUIRES_OK(\n ctx, functor::UpperBoundFunctor::Compute(\n ctx, sorted_inputs, values, sorted_inputs_t.dim_size(0),\n sorted_inputs_t.dim_size(1), values_t.dim_size(1), &output));\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-369'], 'message': 'Prevent CHECK-fail/heap OOB in UpperBound and LowerBound\n\nPiperOrigin-RevId: 387738073\nChange-Id: Iee74de95ddad18440d052a75a5a1cb67544f490a'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: Status PyArrayDescr_to_TF_DataType(PyArray_Descr* descr,\n TF_DataType* out_tf_datatype) {\n PyObject* key;\n PyObject* value;\n Py_ssize_t pos = 0;\n if (PyDict_Next(descr->fields, &pos, &key, &value)) {\n // In Python 3, the keys of numpy custom struct types are unicode, unlike\n // Python 2, where the keys are bytes.\n const char* key_string =\n PyBytes_Check(key) ? PyBytes_AsString(key)\n : PyBytes_AsString(PyUnicode_AsASCIIString(key));\n if (!key_string) {\n return errors::Internal(\"Corrupt numpy type descriptor\");\n }\n tensorflow::string key = key_string;\n // The typenames here should match the field names in the custom struct\n // types constructed in test_util.py.\n // TODO(mrry,keveman): Investigate Numpy type registration to replace this\n // hard-coding of names.\n if (key == \"quint8\") {\n *out_tf_datatype = TF_QUINT8;\n } else if (key == \"qint8\") {\n *out_tf_datatype = TF_QINT8;\n } else if (key == \"qint16\") {\n *out_tf_datatype = TF_QINT16;\n } else if (key == \"quint16\") {\n *out_tf_datatype = TF_QUINT16;\n } else if (key == \"qint32\") {\n *out_tf_datatype = TF_QINT32;\n } else if (key == \"resource\") {\n *out_tf_datatype = TF_RESOURCE;\n } else {\n return errors::Internal(\"Unsupported numpy data type\");\n }\n return Status::OK();\n }\n return errors::Internal(\"Unsupported numpy data type\");\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-843'], 'message': 'Fix `tf.raw_ops.ResourceCountUpTo` null pointer dereference.\n\nPiperOrigin-RevId: 368294347\nChange-Id: I2c16fbfc9b4966c402c3d8e311f0d665a9c852d8'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: _dl_dst_count (const char *name, int is_path)\n{\n size_t cnt = 0;\n\n do\n {\n size_t len = 1;\n\n /* $ORIGIN is not expanded for SUID/GUID programs. */\n if ((((!__libc_enable_secure\n\t && strncmp (&name[1], \"ORIGIN\", 6) == 0 && (len = 7) != 0)\n\t || (strncmp (&name[1], \"PLATFORM\", 8) == 0 && (len = 9) != 0))\n\t && (name[len] == '\\0' || name[len] == '/'\n\t || (is_path && name[len] == ':')))\n\t || (name[1] == '{'\n\t && ((!__libc_enable_secure\n\t\t && strncmp (&name[2], \"ORIGIN}\", 7) == 0 && (len = 9) != 0)\n\t\t || (strncmp (&name[2], \"PLATFORM}\", 9) == 0\n\t\t && (len = 11) != 0))))\n\t++cnt;\n\n name = strchr (name + len, '$');\n }\n while (name != NULL);\n\n return cnt;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190', 'CWE-252'], 'message': 'Update.\n\n1999-11-09 Ulrich Drepper \n\n\t* elf/dl-load.c (_dl_dst_count): Allow $ORIGIN to point to\n\tdirectory with the reference since this is as secure as using the\n\tobject with the dependency.\n\t(_dl_dst_substitute): Likewise.\n\n\t* elf/dl-load.c (_dl_dst_count): Change strings in first two\n\tstrncmp calls to allow reuse.\n\t(_dl_dst_substitute): Likewise.\n\n1999-11-01 Arnold D. Robbins \n\n\t* posix/regex.c (init_syntax_once): move below definition of\n\tISALNUM etc., then use ISALNUM to init the table, so that\n\tthe word ops will work if i18n'ed.\n\t(SYNTAX): And subscript with 0xFF for 8bit character sets.\n\n1999-11-09 Andreas Jaeger \n\n\t* sysdeps/unix/getlogin_r.c (getlogin_r): Sync with getlogin\n\timplementation for ttyname_r call; fix inverted condition; return\n\tut_user. Closes PR libc/1438.\n\n1999-11-09 Ulrich Drepper \n\n\t* timezone/checktab.awk: Update from tzcode1999h.\n\t* timezone/africa: Update from tzdata1999i.\n\t* timezone/asia: Likewise.\n\t* timezone/australasia: Likewise.\n\t* timezone/backward: Likewise.\n\t* timezone/europe: Likewise.\n\t* timezone/northamerica: Likewise.\n\t* timezone/southamerica: Likewise.\n\t* timezone/iso3166.tab: Likewise.\n\t* timezone/zone.tab: Likewise.\n\n\t* sysdeps/unix/sysv/linux/bits/resource.h: Define values also as\n\tmacros. Patch by brg@csua.berkeley.edu [PR libc/1439].\n\n1999-11-09 Andreas Jaeger \n\n\t* posix/Makefile (tests): Added tst-getlogin.\n\n\t* posix/tst-getlogin.c: New file, contains simple tests for\n\tgetlogin and getlogin_r.\n\n1999-11-09 Andreas Schwab \n\n\t* misc/syslog.c: For LOG_PERROR only append a newline if\n\tnecessary.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: PJ_DEF(pj_status_t) pjmedia_rtcp_fb_build_nack(\n\t\t\t\t\tpjmedia_rtcp_session *session,\n\t\t\t\t\tvoid *buf,\n\t\t\t\t\tpj_size_t *length,\n\t\t\t\t\tunsigned nack_cnt,\n\t\t\t\t\tconst pjmedia_rtcp_fb_nack nack[])\n{\n pjmedia_rtcp_common *hdr;\n pj_uint8_t *p;\n unsigned len, i;\n\n PJ_ASSERT_RETURN(session && buf && length && nack_cnt && nack, PJ_EINVAL);\n\n len = (3 + nack_cnt) * 4;\n if (len > *length)\n\treturn PJ_ETOOSMALL;\n\n /* Build RTCP-FB NACK header */\n hdr = (pjmedia_rtcp_common*)buf;\n pj_memcpy(hdr, &session->rtcp_rr_pkt.common, sizeof(*hdr));\n hdr->pt = RTCP_RTPFB;\n hdr->count = 1; /* FMT = 1 */\n hdr->length = pj_htons((pj_uint16_t)(len/4 - 1));\n\n /* Build RTCP-FB NACK FCI */\n p = (pj_uint8_t*)hdr + sizeof(*hdr);\n for (i = 0; i < nack_cnt; ++i) {\n\tpj_uint16_t val;\n\tval = pj_htons((pj_uint16_t)nack[i].pid);\n\tpj_memcpy(p, &val, 2);\n\tval = pj_htons(nack[i].blp);\n\tpj_memcpy(p+2, &val, 2);\n\tp += 4;\n }\n\n /* Finally */\n *length = len;\n\n return PJ_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-787'], 'message': 'Merge pull request from GHSA-vhxv-phmx-g52q\n\n* Prevent OOB read/write when parsing RTCP FB RPSI\n\n* Add log information\n\n* Modification based on comments.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: double GetGPMFSampleRate(size_t handle, uint32_t fourcc, uint32_t flags)\n{\n\tmp4object *mp4 = (mp4object *)handle;\n\tif (mp4 == NULL) return 0.0;\n\n\tGPMF_stream metadata_stream, *ms = &metadata_stream;\n\tuint32_t teststart = 0;\n\tuint32_t testend = mp4->indexcount;\n\tdouble rate = 0.0;\n\n\tif (mp4->indexcount < 1)\n\t\treturn 0.0;\n\n\tif (mp4->indexcount > 3) // samples after first and before last are statistically the best, avoiding camera start up or shutdown anomollies. \n\t{\n\t\tteststart++;\n\t\ttestend--;\n\t}\n\n\tuint32_t *payload = GetPayload(handle, NULL, teststart); // second payload\n\tuint32_t payloadsize = GetPayloadSize(handle, teststart);\n\tint32_t ret = GPMF_Init(ms, payload, payloadsize);\n\n\tif (ret != GPMF_OK)\n\t\tgoto cleanup;\n\n\t{\n\t\tuint32_t startsamples = 0;\n\t\tuint32_t endsamples = 0;\n\t\tuint32_t missing_samples = 0;\n\n\t\twhile (ret == GPMF_OK && GPMF_OK != GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS))\n\t\t{\n\t\t\tmissing_samples = 1;\n\t\t\tteststart++;\n\t\t\tpayload = GetPayload(handle, payload, teststart); // second last payload\n\t\t\tpayloadsize = GetPayloadSize(handle, teststart);\n\t\t\tret = GPMF_Init(ms, payload, payloadsize);\n\t\t}\n\n\t\tif (missing_samples)\n\t\t{\n\t\t\tteststart++; //samples after sensor start are statistically the best\n\t\t\tpayload = GetPayload(handle, payload, teststart);\n\t\t\tpayloadsize = GetPayloadSize(handle, teststart);\n\t\t\tret = GPMF_Init(ms, payload, payloadsize);\n\t\t}\n\n\t\tif (ret == GPMF_OK)\n\t\t{\n\t\t\tuint32_t samples = GPMF_Repeat(ms);\n\t\t\tGPMF_stream find_stream;\n\t\t\tGPMF_CopyState(ms, &find_stream);\n\n\t\t\tif (!(flags & GPMF_SAMPLE_RATE_PRECISE) && GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TOTAL_SAMPLES, GPMF_CURRENT_LEVEL))\n\t\t\t{\n\t\t\t\tstartsamples = BYTESWAP32(*(uint32_t *)GPMF_RawData(&find_stream)) - samples;\n\n\t\t\t\tpayload = GetPayload(handle, payload, testend); // second last payload\n\t\t\t\tpayloadsize = GetPayloadSize(handle, testend);\n\t\t\t\tret = GPMF_Init(ms, payload, payloadsize);\n\t\t\t\tif (ret != GPMF_OK)\n\t\t\t\t\tgoto cleanup;\n\n\t\t\t\tif (GPMF_OK == GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS))\n\t\t\t\t{\n\t\t\t\t\tGPMF_CopyState(ms, &find_stream);\n\t\t\t\t\tif (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TOTAL_SAMPLES, GPMF_CURRENT_LEVEL))\n\t\t\t\t\t{\n\t\t\t\t\t\tendsamples = BYTESWAP32(*(uint32_t *)GPMF_RawData(&find_stream));\n\t\t\t\t\t\trate = (double)(endsamples - startsamples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount);\n\t\t\t\t\t\tgoto cleanup;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\trate = (double)(samples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount);\n\t\t\t}\n\t\t\telse // for increased precision, for older GPMF streams sometimes missing the total sample count \n\t\t\t{\n\t\t\t\tuint32_t payloadpos = 0, payloadcount = 0;\n\t\t\t\tdouble slope, top = 0.0, bot = 0.0, meanX = 0, meanY = 0;\n\t\t\t\tuint32_t *repeatarray = malloc(mp4->indexcount * 4 + 4);\n\t\t\t\tmemset(repeatarray, 0, mp4->indexcount * 4 + 4);\n\n\t\t\t\tsamples = 0;\n\n\t\t\t\tfor (payloadpos = teststart; payloadpos < testend; payloadcount++, payloadpos++)\n\t\t\t\t{\n\t\t\t\t\tpayload = GetPayload(handle, payload, payloadpos); // second last payload\n\t\t\t\t\tpayloadsize = GetPayloadSize(handle, payloadpos);\n\t\t\t\t\tret = GPMF_Init(ms, payload, payloadsize);\n\n\t\t\t\t\tif (ret != GPMF_OK)\n\t\t\t\t\t\tgoto cleanup;\n\n\t\t\t\t\tif (GPMF_OK == GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS))\n\t\t\t\t\t{\n\t\t\t\t\t\tGPMF_stream find_stream2;\n\t\t\t\t\t\tGPMF_CopyState(ms, &find_stream2);\n\n\t\t\t\t\t\tif (GPMF_OK == GPMF_FindNext(&find_stream2, fourcc, GPMF_CURRENT_LEVEL)) // Count the instances, not the repeats\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (repeatarray)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tfloat in, out;\n\n\t\t\t\t\t\t\t\tdo\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tsamples++;\n\t\t\t\t\t\t\t\t} while (GPMF_OK == GPMF_FindNext(ms, fourcc, GPMF_CURRENT_LEVEL));\n\n\t\t\t\t\t\t\t\trepeatarray[payloadpos] = samples;\n\t\t\t\t\t\t\t\tmeanY += (double)samples;\n\n\t\t\t\t\t\t\t\tGetPayloadTime(handle, payloadpos, &in, &out);\n\t\t\t\t\t\t\t\tmeanX += out;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tuint32_t repeat = GPMF_Repeat(ms);\n\t\t\t\t\t\t\tsamples += repeat;\n\n\t\t\t\t\t\t\tif (repeatarray)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tfloat in, out;\n\n\t\t\t\t\t\t\t\trepeatarray[payloadpos] = samples;\n\t\t\t\t\t\t\t\tmeanY += (double)samples;\n\n\t\t\t\t\t\t\t\tGetPayloadTime(handle, payloadpos, &in, &out);\n\t\t\t\t\t\t\t\tmeanX += out;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Compute the line of best fit for a jitter removed sample rate. \n\t\t\t\t// This does assume an unchanging clock, even though the IMU data can thermally impacted causing small clock changes. \n\t\t\t\t// TODO: Next enhancement would be a low order polynominal fit the compensate for any thermal clock drift.\n\t\t\t\tif (repeatarray)\n\t\t\t\t{\n\t\t\t\t\tmeanY /= (double)payloadcount;\n\t\t\t\t\tmeanX /= (double)payloadcount;\n\n\t\t\t\t\tfor (payloadpos = teststart; payloadpos < testend; payloadpos++)\n\t\t\t\t\t{\n\t\t\t\t\t\tfloat in, out;\n\t\t\t\t\t\tGetPayloadTime(handle, payloadpos, &in, &out);\n\n\t\t\t\t\t\ttop += ((double)out - meanX)*((double)repeatarray[payloadpos] - meanY);\n\t\t\t\t\t\tbot += ((double)out - meanX)*((double)out - meanX);\n\t\t\t\t\t}\n\n\t\t\t\t\tslope = top / bot;\n\n#if 0\n\t\t\t\t\t// This sample code might be useful for compare data latency between channels.\n\t\t\t\t\t{\n\t\t\t\t\t\tdouble intercept;\n\t\t\t\t\t\tintercept = meanY - slope*meanX;\n\t\t\t\t\t\tprintf(\"%c%c%c%c start offset = %f (%.3fms)\\n\", PRINTF_4CC(fourcc), intercept, 1000.0 * intercept / slope);\n\t\t\t\t\t}\n#endif\n\t\t\t\t\trate = slope;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\trate = (double)(samples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount);\n\t\t\t\t}\n\n\t\t\t\tfree(repeatarray);\n\n\t\t\t\tgoto cleanup;\n\t\t\t}\n\t\t}\n\t}\n\ncleanup:\n\tif (payload) \n\t{\n\t\tFreePayload(payload);\n\t\tpayload = NULL;\n\t}\n\n\treturn rate;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-369', 'CWE-787'], 'message': 'fixed many security issues with the too crude mp4 reader'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ext4_data_block_valid(struct ext4_sb_info *sbi, ext4_fsblk_t start_blk,\n\t\t\t unsigned int count)\n{\n\tstruct ext4_system_blocks *system_blks;\n\tint ret;\n\n\t/*\n\t * Lock the system zone to prevent it being released concurrently\n\t * when doing a remount which inverse current \"[no]block_validity\"\n\t * mount option.\n\t */\n\trcu_read_lock();\n\tsystem_blks = rcu_dereference(sbi->system_blks);\n\tret = ext4_data_block_valid_rcu(sbi, system_blks, start_blk,\n\t\t\t\t\tcount);\n\trcu_read_unlock();\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'ext4: check journal inode extents more carefully\n\nCurrently, system zones just track ranges of block, that are \"important\"\nfs metadata (bitmaps, group descriptors, journal blocks, etc.). This\nhowever complicates how extent tree (or indirect blocks) can be checked\nfor inodes that actually track such metadata - currently the journal\ninode but arguably we should be treating quota files or resize inode\nsimilarly. We cannot run __ext4_ext_check() on such metadata inodes when\nloading their extents as that would immediately trigger the validity\nchecks and so we just hack around that and special-case the journal\ninode. This however leads to a situation that a journal inode which has\nextent tree of depth at least one can have invalid extent tree that gets\nunnoticed until ext4_cache_extents() crashes.\n\nTo overcome this limitation, track inode number each system zone belongs\nto (0 is used for zones not belonging to any inode). We can then verify\ninode number matches the expected one when verifying extent tree and\nthus avoid the false errors. With this there's no need to to\nspecial-case journal inode during extent tree checking anymore so remove\nit.\n\nFixes: 0a944e8a6c66 (\"ext4: don't perform block validity checks on the journal inode\")\nReported-by: Wolfgang Frisch \nReviewed-by: Lukas Czerner \nSigned-off-by: Jan Kara \nLink: https://lore.kernel.org/r/20200728130437.7804-4-jack@suse.cz\nSigned-off-by: Theodore Ts'o '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline int can_merge(struct ext4_system_zone *entry1,\n\t\t struct ext4_system_zone *entry2)\n{\n\tif ((entry1->start_blk + entry1->count) == entry2->start_blk)\n\t\treturn 1;\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'ext4: check journal inode extents more carefully\n\nCurrently, system zones just track ranges of block, that are \"important\"\nfs metadata (bitmaps, group descriptors, journal blocks, etc.). This\nhowever complicates how extent tree (or indirect blocks) can be checked\nfor inodes that actually track such metadata - currently the journal\ninode but arguably we should be treating quota files or resize inode\nsimilarly. We cannot run __ext4_ext_check() on such metadata inodes when\nloading their extents as that would immediately trigger the validity\nchecks and so we just hack around that and special-case the journal\ninode. This however leads to a situation that a journal inode which has\nextent tree of depth at least one can have invalid extent tree that gets\nunnoticed until ext4_cache_extents() crashes.\n\nTo overcome this limitation, track inode number each system zone belongs\nto (0 is used for zones not belonging to any inode). We can then verify\ninode number matches the expected one when verifying extent tree and\nthus avoid the false errors. With this there's no need to to\nspecial-case journal inode during extent tree checking anymore so remove\nit.\n\nFixes: 0a944e8a6c66 (\"ext4: don't perform block validity checks on the journal inode\")\nReported-by: Wolfgang Frisch \nReviewed-by: Lukas Czerner \nSigned-off-by: Jan Kara \nLink: https://lore.kernel.org/r/20200728130437.7804-4-jack@suse.cz\nSigned-off-by: Theodore Ts'o '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt,\n mbedtls_x509_crt *trust_ca,\n mbedtls_x509_crl *ca_crl,\n const mbedtls_x509_crt_profile *profile,\n const char *cn, uint32_t *flags,\n int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),\n void *p_vrfy )\n{\n size_t cn_len;\n int ret;\n int pathlen = 0, selfsigned = 0;\n mbedtls_x509_crt *parent;\n mbedtls_x509_name *name;\n mbedtls_x509_sequence *cur = NULL;\n mbedtls_pk_type_t pk_type;\n\n if( profile == NULL )\n return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );\n\n *flags = 0;\n\n if( cn != NULL )\n {\n name = &crt->subject;\n cn_len = strlen( cn );\n\n if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME )\n {\n cur = &crt->subject_alt_names;\n\n while( cur != NULL )\n {\n if( cur->buf.len == cn_len &&\n x509_memcasecmp( cn, cur->buf.p, cn_len ) == 0 )\n break;\n\n if( cur->buf.len > 2 &&\n memcmp( cur->buf.p, \"*.\", 2 ) == 0 &&\n x509_check_wildcard( cn, &cur->buf ) == 0 )\n {\n break;\n }\n\n cur = cur->next;\n }\n\n if( cur == NULL )\n *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;\n }\n else\n {\n while( name != NULL )\n {\n if( MBEDTLS_OID_CMP( MBEDTLS_OID_AT_CN, &name->oid ) == 0 )\n {\n if( name->val.len == cn_len &&\n x509_memcasecmp( name->val.p, cn, cn_len ) == 0 )\n break;\n\n if( name->val.len > 2 &&\n memcmp( name->val.p, \"*.\", 2 ) == 0 &&\n x509_check_wildcard( cn, &name->val ) == 0 )\n break;\n }\n\n name = name->next;\n }\n\n if( name == NULL )\n *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;\n }\n }\n\n /* Check the type and size of the key */\n pk_type = mbedtls_pk_get_type( &crt->pk );\n\n if( x509_profile_check_pk_alg( profile, pk_type ) != 0 )\n *flags |= MBEDTLS_X509_BADCERT_BAD_PK;\n\n if( x509_profile_check_key( profile, pk_type, &crt->pk ) != 0 )\n *flags |= MBEDTLS_X509_BADCERT_BAD_KEY;\n\n /* Look for a parent in trusted CAs */\n for( parent = trust_ca; parent != NULL; parent = parent->next )\n {\n if( x509_crt_check_parent( crt, parent, 0, pathlen == 0 ) == 0 )\n break;\n }\n\n if( parent != NULL )\n {\n ret = x509_crt_verify_top( crt, parent, ca_crl, profile,\n pathlen, selfsigned, flags, f_vrfy, p_vrfy );\n if( ret != 0 )\n return( ret );\n }\n else\n {\n /* Look for a parent upwards the chain */\n for( parent = crt->next; parent != NULL; parent = parent->next )\n if( x509_crt_check_parent( crt, parent, 0, pathlen == 0 ) == 0 )\n break;\n\n /* Are we part of the chain or at the top? */\n if( parent != NULL )\n {\n ret = x509_crt_verify_child( crt, parent, trust_ca, ca_crl, profile,\n pathlen, selfsigned, flags, f_vrfy, p_vrfy );\n if( ret != 0 )\n return( ret );\n }\n else\n {\n ret = x509_crt_verify_top( crt, trust_ca, ca_crl, profile,\n pathlen, selfsigned, flags, f_vrfy, p_vrfy );\n if( ret != 0 )\n return( ret );\n }\n }\n\n if( *flags != 0 )\n return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED );\n\n return( 0 );\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'Improve behaviour on fatal errors\n\nIf we didn't walk the whole chain, then there may be any kind of errors in the\npart of the chain we didn't check, so setting all flags looks like the safe\nthing to do.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int packet_recvmsg(struct kiocb *iocb, struct socket *sock,\n\t\t\t struct msghdr *msg, size_t len, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct sk_buff *skb;\n\tint copied, err;\n\tstruct sockaddr_ll *sll;\n\tint vnet_hdr_len = 0;\n\n\terr = -EINVAL;\n\tif (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT|MSG_ERRQUEUE))\n\t\tgoto out;\n\n#if 0\n\t/* What error should we return now? EUNATTACH? */\n\tif (pkt_sk(sk)->ifindex < 0)\n\t\treturn -ENODEV;\n#endif\n\n\tif (flags & MSG_ERRQUEUE) {\n\t\terr = sock_recv_errqueue(sk, msg, len,\n\t\t\t\t\t SOL_PACKET, PACKET_TX_TIMESTAMP);\n\t\tgoto out;\n\t}\n\n\t/*\n\t *\tCall the generic datagram receiver. This handles all sorts\n\t *\tof horrible races and re-entrancy so we can forget about it\n\t *\tin the protocol layers.\n\t *\n\t *\tNow it will return ENETDOWN, if device have just gone down,\n\t *\tbut then it will block.\n\t */\n\n\tskb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err);\n\n\t/*\n\t *\tAn error occurred so return it. Because skb_recv_datagram()\n\t *\thandles the blocking we don't see and worry about blocking\n\t *\tretries.\n\t */\n\n\tif (skb == NULL)\n\t\tgoto out;\n\n\tif (pkt_sk(sk)->has_vnet_hdr) {\n\t\tstruct virtio_net_hdr vnet_hdr = { 0 };\n\n\t\terr = -EINVAL;\n\t\tvnet_hdr_len = sizeof(vnet_hdr);\n\t\tif (len < vnet_hdr_len)\n\t\t\tgoto out_free;\n\n\t\tlen -= vnet_hdr_len;\n\n\t\tif (skb_is_gso(skb)) {\n\t\t\tstruct skb_shared_info *sinfo = skb_shinfo(skb);\n\n\t\t\t/* This is a hint as to how much should be linear. */\n\t\t\tvnet_hdr.hdr_len = skb_headlen(skb);\n\t\t\tvnet_hdr.gso_size = sinfo->gso_size;\n\t\t\tif (sinfo->gso_type & SKB_GSO_TCPV4)\n\t\t\t\tvnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV4;\n\t\t\telse if (sinfo->gso_type & SKB_GSO_TCPV6)\n\t\t\t\tvnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV6;\n\t\t\telse if (sinfo->gso_type & SKB_GSO_UDP)\n\t\t\t\tvnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_UDP;\n\t\t\telse if (sinfo->gso_type & SKB_GSO_FCOE)\n\t\t\t\tgoto out_free;\n\t\t\telse\n\t\t\t\tBUG();\n\t\t\tif (sinfo->gso_type & SKB_GSO_TCP_ECN)\n\t\t\t\tvnet_hdr.gso_type |= VIRTIO_NET_HDR_GSO_ECN;\n\t\t} else\n\t\t\tvnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_NONE;\n\n\t\tif (skb->ip_summed == CHECKSUM_PARTIAL) {\n\t\t\tvnet_hdr.flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;\n\t\t\tvnet_hdr.csum_start = skb_checksum_start_offset(skb);\n\t\t\tvnet_hdr.csum_offset = skb->csum_offset;\n\t\t} else if (skb->ip_summed == CHECKSUM_UNNECESSARY) {\n\t\t\tvnet_hdr.flags = VIRTIO_NET_HDR_F_DATA_VALID;\n\t\t} /* else everything is zero */\n\n\t\terr = memcpy_toiovec(msg->msg_iov, (void *)&vnet_hdr,\n\t\t\t\t vnet_hdr_len);\n\t\tif (err < 0)\n\t\t\tgoto out_free;\n\t}\n\n\t/*\n\t *\tIf the address length field is there to be filled in, we fill\n\t *\tit in now.\n\t */\n\n\tsll = &PACKET_SKB_CB(skb)->sa.ll;\n\tif (sock->type == SOCK_PACKET)\n\t\tmsg->msg_namelen = sizeof(struct sockaddr_pkt);\n\telse\n\t\tmsg->msg_namelen = sll->sll_halen + offsetof(struct sockaddr_ll, sll_addr);\n\n\t/*\n\t *\tYou lose any data beyond the buffer you gave. If it worries a\n\t *\tuser program they can ask the device for its MTU anyway.\n\t */\n\n\tcopied = skb->len;\n\tif (copied > len) {\n\t\tcopied = len;\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t}\n\n\terr = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);\n\tif (err)\n\t\tgoto out_free;\n\n\tsock_recv_ts_and_drops(msg, sk, skb);\n\n\tif (msg->msg_name)\n\t\tmemcpy(msg->msg_name, &PACKET_SKB_CB(skb)->sa,\n\t\t msg->msg_namelen);\n\n\tif (pkt_sk(sk)->auxdata) {\n\t\tstruct tpacket_auxdata aux;\n\n\t\taux.tp_status = TP_STATUS_USER;\n\t\tif (skb->ip_summed == CHECKSUM_PARTIAL)\n\t\t\taux.tp_status |= TP_STATUS_CSUMNOTREADY;\n\t\taux.tp_len = PACKET_SKB_CB(skb)->origlen;\n\t\taux.tp_snaplen = skb->len;\n\t\taux.tp_mac = 0;\n\t\taux.tp_net = skb_network_offset(skb);\n\t\tif (vlan_tx_tag_present(skb)) {\n\t\t\taux.tp_vlan_tci = vlan_tx_tag_get(skb);\n\t\t\taux.tp_status |= TP_STATUS_VLAN_VALID;\n\t\t} else {\n\t\t\taux.tp_vlan_tci = 0;\n\t\t}\n\t\taux.tp_padding = 0;\n\t\tput_cmsg(msg, SOL_PACKET, PACKET_AUXDATA, sizeof(aux), &aux);\n\t}\n\n\t/*\n\t *\tFree or return the buffer as appropriate. Again this\n\t *\thides all the races and re-entrancy issues from us.\n\t */\n\terr = vnet_hdr_len + ((flags&MSG_TRUNC) ? skb->len : copied);\n\nout_free:\n\tskb_free_datagram(sk, skb);\nout:\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-269'], 'message': 'net: rework recvmsg handler msg_name and msg_namelen logic\n\nThis patch now always passes msg->msg_namelen as 0. recvmsg handlers must\nset msg_namelen to the proper size <= sizeof(struct sockaddr_storage)\nto return msg_name to the user.\n\nThis prevents numerous uninitialized memory leaks we had in the\nrecvmsg handlers and makes it harder for new code to accidentally leak\nuninitialized memory.\n\nOptimize for the case recvfrom is called with NULL as address. We don't\nneed to copy the address at all, so set it to NULL before invoking the\nrecvmsg handler. We can do so, because all the recvmsg handlers must\ncope with the case a plain read() is called on them. read() also sets\nmsg_name to NULL.\n\nAlso document these changes in include/linux/net.h as suggested by David\nMiller.\n\nChanges since RFC:\n\nSet msg->msg_name = NULL if user specified a NULL in msg_name but had a\nnon-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't\naffect sendto as it would bail out earlier while trying to copy-in the\naddress. It also more naturally reflects the logic by the callers of\nverify_iovec.\n\nWith this change in place I could remove \"\nif (!uaddr || msg_sys->msg_namelen == 0)\n\tmsg->msg_name = NULL\n\".\n\nThis change does not alter the user visible error logic as we ignore\nmsg_namelen as long as msg_name is NULL.\n\nAlso remove two unnecessary curly brackets in ___sys_recvmsg and change\ncomments to netdev style.\n\nCc: David Miller \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int irda_recvmsg_dgram(struct kiocb *iocb, struct socket *sock,\n\t\t\t struct msghdr *msg, size_t size, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct irda_sock *self = irda_sk(sk);\n\tstruct sk_buff *skb;\n\tsize_t copied;\n\tint err;\n\n\tIRDA_DEBUG(4, \"%s()\\n\", __func__);\n\n\tmsg->msg_namelen = 0;\n\n\tskb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,\n\t\t\t\tflags & MSG_DONTWAIT, &err);\n\tif (!skb)\n\t\treturn err;\n\n\tskb_reset_transport_header(skb);\n\tcopied = skb->len;\n\n\tif (copied > size) {\n\t\tIRDA_DEBUG(2, \"%s(), Received truncated frame (%zd < %zd)!\\n\",\n\t\t\t __func__, copied, size);\n\t\tcopied = size;\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t}\n\tskb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);\n\n\tskb_free_datagram(sk, skb);\n\n\t/*\n\t * Check if we have previously stopped IrTTP and we know\n\t * have more free space in our rx_queue. If so tell IrTTP\n\t * to start delivering frames again before our rx_queue gets\n\t * empty\n\t */\n\tif (self->rx_flow == FLOW_STOP) {\n\t\tif ((atomic_read(&sk->sk_rmem_alloc) << 2) <= sk->sk_rcvbuf) {\n\t\t\tIRDA_DEBUG(2, \"%s(), Starting IrTTP\\n\", __func__);\n\t\t\tself->rx_flow = FLOW_START;\n\t\t\tirttp_flow_request(self->tsap, FLOW_START);\n\t\t}\n\t}\n\n\treturn copied;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-269'], 'message': 'net: rework recvmsg handler msg_name and msg_namelen logic\n\nThis patch now always passes msg->msg_namelen as 0. recvmsg handlers must\nset msg_namelen to the proper size <= sizeof(struct sockaddr_storage)\nto return msg_name to the user.\n\nThis prevents numerous uninitialized memory leaks we had in the\nrecvmsg handlers and makes it harder for new code to accidentally leak\nuninitialized memory.\n\nOptimize for the case recvfrom is called with NULL as address. We don't\nneed to copy the address at all, so set it to NULL before invoking the\nrecvmsg handler. We can do so, because all the recvmsg handlers must\ncope with the case a plain read() is called on them. read() also sets\nmsg_name to NULL.\n\nAlso document these changes in include/linux/net.h as suggested by David\nMiller.\n\nChanges since RFC:\n\nSet msg->msg_name = NULL if user specified a NULL in msg_name but had a\nnon-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't\naffect sendto as it would bail out earlier while trying to copy-in the\naddress. It also more naturally reflects the logic by the callers of\nverify_iovec.\n\nWith this change in place I could remove \"\nif (!uaddr || msg_sys->msg_namelen == 0)\n\tmsg->msg_name = NULL\n\".\n\nThis change does not alter the user visible error logic as we ignore\nmsg_namelen as long as msg_name is NULL.\n\nAlso remove two unnecessary curly brackets in ___sys_recvmsg and change\ncomments to netdev style.\n\nCc: David Miller \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int irda_recvmsg_stream(struct kiocb *iocb, struct socket *sock,\n\t\t\t struct msghdr *msg, size_t size, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct irda_sock *self = irda_sk(sk);\n\tint noblock = flags & MSG_DONTWAIT;\n\tsize_t copied = 0;\n\tint target, err;\n\tlong timeo;\n\n\tIRDA_DEBUG(3, \"%s()\\n\", __func__);\n\n\tif ((err = sock_error(sk)) < 0)\n\t\treturn err;\n\n\tif (sock->flags & __SO_ACCEPTCON)\n\t\treturn -EINVAL;\n\n\terr =-EOPNOTSUPP;\n\tif (flags & MSG_OOB)\n\t\treturn -EOPNOTSUPP;\n\n\terr = 0;\n\ttarget = sock_rcvlowat(sk, flags & MSG_WAITALL, size);\n\ttimeo = sock_rcvtimeo(sk, noblock);\n\n\tmsg->msg_namelen = 0;\n\n\tdo {\n\t\tint chunk;\n\t\tstruct sk_buff *skb = skb_dequeue(&sk->sk_receive_queue);\n\n\t\tif (skb == NULL) {\n\t\t\tDEFINE_WAIT(wait);\n\t\t\terr = 0;\n\n\t\t\tif (copied >= target)\n\t\t\t\tbreak;\n\n\t\t\tprepare_to_wait_exclusive(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);\n\n\t\t\t/*\n\t\t\t *\tPOSIX 1003.1g mandates this order.\n\t\t\t */\n\t\t\terr = sock_error(sk);\n\t\t\tif (err)\n\t\t\t\t;\n\t\t\telse if (sk->sk_shutdown & RCV_SHUTDOWN)\n\t\t\t\t;\n\t\t\telse if (noblock)\n\t\t\t\terr = -EAGAIN;\n\t\t\telse if (signal_pending(current))\n\t\t\t\terr = sock_intr_errno(timeo);\n\t\t\telse if (sk->sk_state != TCP_ESTABLISHED)\n\t\t\t\terr = -ENOTCONN;\n\t\t\telse if (skb_peek(&sk->sk_receive_queue) == NULL)\n\t\t\t\t/* Wait process until data arrives */\n\t\t\t\tschedule();\n\n\t\t\tfinish_wait(sk_sleep(sk), &wait);\n\n\t\t\tif (err)\n\t\t\t\treturn err;\n\t\t\tif (sk->sk_shutdown & RCV_SHUTDOWN)\n\t\t\t\tbreak;\n\n\t\t\tcontinue;\n\t\t}\n\n\t\tchunk = min_t(unsigned int, skb->len, size);\n\t\tif (memcpy_toiovec(msg->msg_iov, skb->data, chunk)) {\n\t\t\tskb_queue_head(&sk->sk_receive_queue, skb);\n\t\t\tif (copied == 0)\n\t\t\t\tcopied = -EFAULT;\n\t\t\tbreak;\n\t\t}\n\t\tcopied += chunk;\n\t\tsize -= chunk;\n\n\t\t/* Mark read part of skb as used */\n\t\tif (!(flags & MSG_PEEK)) {\n\t\t\tskb_pull(skb, chunk);\n\n\t\t\t/* put the skb back if we didn't use it up.. */\n\t\t\tif (skb->len) {\n\t\t\t\tIRDA_DEBUG(1, \"%s(), back on q!\\n\",\n\t\t\t\t\t __func__);\n\t\t\t\tskb_queue_head(&sk->sk_receive_queue, skb);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tkfree_skb(skb);\n\t\t} else {\n\t\t\tIRDA_DEBUG(0, \"%s() questionable!?\\n\", __func__);\n\n\t\t\t/* put message back and return */\n\t\t\tskb_queue_head(&sk->sk_receive_queue, skb);\n\t\t\tbreak;\n\t\t}\n\t} while (size);\n\n\t/*\n\t * Check if we have previously stopped IrTTP and we know\n\t * have more free space in our rx_queue. If so tell IrTTP\n\t * to start delivering frames again before our rx_queue gets\n\t * empty\n\t */\n\tif (self->rx_flow == FLOW_STOP) {\n\t\tif ((atomic_read(&sk->sk_rmem_alloc) << 2) <= sk->sk_rcvbuf) {\n\t\t\tIRDA_DEBUG(2, \"%s(), Starting IrTTP\\n\", __func__);\n\t\t\tself->rx_flow = FLOW_START;\n\t\t\tirttp_flow_request(self->tsap, FLOW_START);\n\t\t}\n\t}\n\n\treturn copied;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-269'], 'message': 'net: rework recvmsg handler msg_name and msg_namelen logic\n\nThis patch now always passes msg->msg_namelen as 0. recvmsg handlers must\nset msg_namelen to the proper size <= sizeof(struct sockaddr_storage)\nto return msg_name to the user.\n\nThis prevents numerous uninitialized memory leaks we had in the\nrecvmsg handlers and makes it harder for new code to accidentally leak\nuninitialized memory.\n\nOptimize for the case recvfrom is called with NULL as address. We don't\nneed to copy the address at all, so set it to NULL before invoking the\nrecvmsg handler. We can do so, because all the recvmsg handlers must\ncope with the case a plain read() is called on them. read() also sets\nmsg_name to NULL.\n\nAlso document these changes in include/linux/net.h as suggested by David\nMiller.\n\nChanges since RFC:\n\nSet msg->msg_name = NULL if user specified a NULL in msg_name but had a\nnon-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't\naffect sendto as it would bail out earlier while trying to copy-in the\naddress. It also more naturally reflects the logic by the callers of\nverify_iovec.\n\nWith this change in place I could remove \"\nif (!uaddr || msg_sys->msg_namelen == 0)\n\tmsg->msg_name = NULL\n\".\n\nThis change does not alter the user visible error logic as we ignore\nmsg_namelen as long as msg_name is NULL.\n\nAlso remove two unnecessary curly brackets in ___sys_recvmsg and change\ncomments to netdev style.\n\nCc: David Miller \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int pppol2tp_recvmsg(struct kiocb *iocb, struct socket *sock,\n\t\t\t struct msghdr *msg, size_t len,\n\t\t\t int flags)\n{\n\tint err;\n\tstruct sk_buff *skb;\n\tstruct sock *sk = sock->sk;\n\n\terr = -EIO;\n\tif (sk->sk_state & PPPOX_BOUND)\n\t\tgoto end;\n\n\tmsg->msg_namelen = 0;\n\n\terr = 0;\n\tskb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,\n\t\t\t\tflags & MSG_DONTWAIT, &err);\n\tif (!skb)\n\t\tgoto end;\n\n\tif (len > skb->len)\n\t\tlen = skb->len;\n\telse if (len < skb->len)\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\n\terr = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, len);\n\tif (likely(err == 0))\n\t\terr = len;\n\n\tkfree_skb(skb);\nend:\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-269'], 'message': 'net: rework recvmsg handler msg_name and msg_namelen logic\n\nThis patch now always passes msg->msg_namelen as 0. recvmsg handlers must\nset msg_namelen to the proper size <= sizeof(struct sockaddr_storage)\nto return msg_name to the user.\n\nThis prevents numerous uninitialized memory leaks we had in the\nrecvmsg handlers and makes it harder for new code to accidentally leak\nuninitialized memory.\n\nOptimize for the case recvfrom is called with NULL as address. We don't\nneed to copy the address at all, so set it to NULL before invoking the\nrecvmsg handler. We can do so, because all the recvmsg handlers must\ncope with the case a plain read() is called on them. read() also sets\nmsg_name to NULL.\n\nAlso document these changes in include/linux/net.h as suggested by David\nMiller.\n\nChanges since RFC:\n\nSet msg->msg_name = NULL if user specified a NULL in msg_name but had a\nnon-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't\naffect sendto as it would bail out earlier while trying to copy-in the\naddress. It also more naturally reflects the logic by the callers of\nverify_iovec.\n\nWith this change in place I could remove \"\nif (!uaddr || msg_sys->msg_namelen == 0)\n\tmsg->msg_name = NULL\n\".\n\nThis change does not alter the user visible error logic as we ignore\nmsg_namelen as long as msg_name is NULL.\n\nAlso remove two unnecessary curly brackets in ___sys_recvmsg and change\ncomments to netdev style.\n\nCc: David Miller \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void Compute(OpKernelContext* context) override {\n const Tensor& splits = context->input(0);\n const Tensor& values = context->input(1);\n const Tensor& weights = context->input(2);\n bool use_weights = weights.NumElements() > 0;\n bool is_1d = false;\n\n const auto splits_values = splits.flat();\n const auto values_values = values.flat();\n const auto weight_values = weights.flat();\n int num_batches = splits.NumElements() - 1;\n int num_values = values.NumElements();\n\n auto per_batch_counts = BatchedMap(num_batches);\n T max_value = 0;\n int batch_idx = 0;\n\n for (int idx = 0; idx < num_values; ++idx) {\n while (idx >= splits_values(batch_idx)) {\n batch_idx++;\n }\n const auto& value = values_values(idx);\n if (value >= 0 && (maxlength_ <= 0 || value < maxlength_)) {\n if (binary_output_) {\n per_batch_counts[batch_idx - 1][value] = 1;\n } else if (use_weights) {\n per_batch_counts[batch_idx - 1][value] += weight_values(idx);\n } else {\n per_batch_counts[batch_idx - 1][value]++;\n }\n if (value > max_value) {\n max_value = value;\n }\n }\n }\n\n int num_output_values = GetOutputSize(max_value, maxlength_, minlength_);\n OP_REQUIRES_OK(context, OutputSparse(per_batch_counts, num_output_values,\n is_1d, context));\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-122', 'CWE-787'], 'message': 'Fix multiple vulnerabilities in `tf.raw_ops.*CountSparseOutput`.\n\nAlso add tests for these API points, both for the happy paths and for the vulnerable ones.\n\nPiperOrigin-RevId: 332563222\nChange-Id: Ib3b52116a83a134c2e742a7c66e5e956db8fba05'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static s32 gf_media_vvc_read_pps_bs_internal(GF_BitStream *bs, VVCState *vvc)\n{\n\tu32 i;\n\ts32 pps_id;\n\tVVC_PPS *pps;\n\n\t//NAL header already read\n\tpps_id = gf_bs_read_int_log(bs, 6, \"pps_id\");\n\n\tif ((pps_id < 0) || (pps_id >= 64)) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[VVC] wrong PPS ID %d in PPS\\n\", pps_id));\n\t\treturn -1;\n\t}\n\tpps = &vvc->pps[pps_id];\n\n\tif (!pps->state) {\n\t\tpps->id = pps_id;\n\t\tpps->state = 1;\n\t}\n\tpps->sps_id = gf_bs_read_int_log(bs, 4, \"sps_id\");\n\tif (pps->sps_id >= 16) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[VVC] wrong SPS ID %d in PPS\\n\", pps->sps_id));\n\t\tpps->sps_id=0;\n\t\treturn -1;\n\t}\n\tvvc->sps_active_idx = pps->sps_id; /*set active sps*/\n\tpps->mixed_nal_types = gf_bs_read_int_log(bs, 1, \"mixed_nal_types\");\n\tpps->width = gf_bs_read_ue_log(bs, \"width\");\n\tpps->height = gf_bs_read_ue_log(bs, \"height\");\n\tpps->conf_window = gf_bs_read_int_log(bs, 1, \"conformance_window_flag\");\n\tif (pps->conf_window) {\n\t\tpps->cw_left = gf_bs_read_ue_log(bs, \"conf_win_left_offset\");\n\t\tpps->cw_right = gf_bs_read_ue_log(bs, \"conf_win_right_offset\");\n\t\tpps->cw_top = gf_bs_read_ue_log(bs, \"conf_win_top_offset\");\n\t\tpps->cw_bottom = gf_bs_read_ue_log(bs, \"conf_win_bottom_offset\");\n\t}\n\t//scaling window\n\tif (gf_bs_read_int_log(bs, 1, \"scaling_window_explicit_signalling_flag\")) {\n\t\tgf_bs_read_se_log(bs, \"scaling_win_left_offset\");\n\t\tgf_bs_read_se_log(bs, \"scaling_win_right_offset\");\n\t\tgf_bs_read_se_log(bs, \"scaling_win_top_offset\");\n\t\tgf_bs_read_se_log(bs, \"scaling_win_bottom_offset\");\n\t}\n\tpps->output_flag_present_flag = gf_bs_read_int_log(bs, 1, \"output_flag_present_flag\");\n\tpps->no_pic_partition_flag = gf_bs_read_int_log(bs, 1, \"no_pic_partition_flag\");\n\tpps->subpic_id_mapping_present_flag = gf_bs_read_int_log(bs, 1, \"subpic_id_mapping_present_flag\");\n\tif (pps->subpic_id_mapping_present_flag) {\n\t\tu32 pps_subpic_id_len, pps_num_subpics=0;\n\t\tif (!pps->no_pic_partition_flag) {\n\t\t\tpps_num_subpics = 1+gf_bs_read_ue_log(bs, \"pps_num_subpics_minus1\");\n\t\t}\n\t\tpps_subpic_id_len = 1 + gf_bs_read_ue(bs);\n\t\tfor (i=0; ino_pic_partition_flag) {\n\t\tgf_bs_read_int_log(bs, 2, \"pps_log2_ctu_size_minus5\");\n\t\tu32 num_exp_tile_columns = 1 + gf_bs_read_ue_log(bs, \"num_exp_tile_columns_minus1\");\n\t\tu32 num_exp_tile_rows = 1 + gf_bs_read_ue_log(bs, \"num_exp_tile_rows_minus1\");\n\t\tfor (i=0; i \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190', 'CWE-787'], 'message': 'add safety in avc/hevc/vvc sps/pps/vps ID check - cf #1720 #1721 #1722'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: lsquic_qeh_settings (struct qpack_enc_hdl *qeh, unsigned max_table_size,\n unsigned dyn_table_size, unsigned max_risked_streams, int server)\n{\n enum lsqpack_enc_opts enc_opts;\n\n assert(qeh->qeh_flags & QEH_INITIALIZED);\n\n if (qeh->qeh_flags & QEH_HAVE_SETTINGS)\n {\n LSQ_WARN(\"settings already set\");\n return -1;\n }\n\n enc_opts = LSQPACK_ENC_OPT_STAGE_2\n | (server ? LSQPACK_ENC_OPT_SERVER : 0);\n qeh->qeh_tsu_sz = sizeof(qeh->qeh_tsu_buf);\n if (0 != lsqpack_enc_init(&qeh->qeh_encoder, (void *) qeh->qeh_conn,\n max_table_size, dyn_table_size, max_risked_streams, enc_opts,\n qeh->qeh_tsu_buf, &qeh->qeh_tsu_sz))\n {\n LSQ_INFO(\"could not initialize QPACK encoder\");\n return -1;\n }\n LSQ_DEBUG(\"%zu-byte post-init TSU\", qeh->qeh_tsu_sz);\n qeh->qeh_flags |= QEH_HAVE_SETTINGS;\n qeh->qeh_max_prefix_size =\n lsqpack_enc_header_block_prefix_size(&qeh->qeh_encoder);\n LSQ_DEBUG(\"have settings: max table size=%u; dyn table size=%u; max risked \"\n \"streams=%u\", max_table_size, dyn_table_size, max_risked_streams);\n if (qeh->qeh_enc_sm_out)\n qeh_begin_out(qeh);\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-269'], 'message': 'Release 3.1.0'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: write(Protocol_* iprot, const StructInfo& structInfo, const void* object) {\n DCHECK(object);\n size_t written = iprot->writeStructBegin(structInfo.name);\n if (UNLIKELY(structInfo.unionExt != nullptr)) {\n const FieldInfo* end = structInfo.fieldInfos + structInfo.numFields;\n const auto& unionId =\n activeUnionMemberId(object, structInfo.unionExt->unionTypeOffset);\n const FieldInfo* found = std::lower_bound(\n structInfo.fieldInfos,\n end,\n unionId,\n [](const FieldInfo& lhs, FieldID rhs) { return lhs.id < rhs; });\n if (found < end && found->id == unionId) {\n const OptionalThriftValue value = getValue(*found->typeInfo, object);\n if (value.hasValue()) {\n written += writeField(iprot, *found, value.value());\n } else if (found->typeInfo->type == protocol::TType::T_STRUCT) {\n written += iprot->writeFieldBegin(\n found->name, found->typeInfo->type, found->id);\n written += iprot->writeStructBegin(found->name);\n written += iprot->writeStructEnd();\n written += iprot->writeFieldStop();\n written += iprot->writeFieldEnd();\n }\n }\n } else {\n for (std::int16_t index = 0; index < structInfo.numFields; index++) {\n const auto& fieldInfo = structInfo.fieldInfos[index];\n if (fieldInfo.isUnqualified || fieldInfo.issetOffset == 0 ||\n fieldIsSet(object, fieldInfo.issetOffset)) {\n const OptionalThriftValue value =\n getValue(*fieldInfo.typeInfo, getMember(fieldInfo, object));\n if (value.hasValue()) {\n written += writeField(iprot, fieldInfo, value.value());\n }\n }\n }\n }\n\n written += iprot->writeFieldStop();\n written += iprot->writeStructEnd();\n return written;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-763'], 'message': 'Fix handling of invalid union data in table-based serializer\n\nSummary:\nFix handling of invalid union data in the table-based serializer. Previously if the input contained duplicate union data, previous active member of the union was overwritten without calling the destructor of the old object, potentially causing a memory leak. In addition to that, if the second piece of data was incomplete the wrong destructor would be called during stack unwinding causing a segfault, data corruption or other undesirable effects.\n\nFix the issue by clearing the union if there is an active member.\n\nAlso fix the type of the data member that holds the active field id (it's `int`, not `FieldID`).\n\nReviewed By: yfeldblum\n\nDifferential Revision: D26440248\n\nfbshipit-source-id: fae9ab96566cf07e14dabe9663b2beb680a01bb4'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: long arch_ptrace(struct task_struct *child, long request,\n\t\t unsigned long addr, unsigned long data)\n{\n\tint ret;\n\tunsigned long __user *datap = (unsigned long __user *) data;\n\n\tswitch (request) {\n\t\tcase PTRACE_PEEKUSR:\n\t\t\tret = ptrace_read_user(child, addr, datap);\n\t\t\tbreak;\n\n\t\tcase PTRACE_POKEUSR:\n\t\t\tret = ptrace_write_user(child, addr, data);\n\t\t\tbreak;\n\n\t\tcase PTRACE_GETREGS:\n\t\t\tret = copy_regset_to_user(child,\n\t\t\t\t\t\t &user_arm_view, REGSET_GPR,\n\t\t\t\t\t\t 0, sizeof(struct pt_regs),\n\t\t\t\t\t\t datap);\n\t\t\tbreak;\n\n\t\tcase PTRACE_SETREGS:\n\t\t\tret = copy_regset_from_user(child,\n\t\t\t\t\t\t &user_arm_view, REGSET_GPR,\n\t\t\t\t\t\t 0, sizeof(struct pt_regs),\n\t\t\t\t\t\t datap);\n\t\t\tbreak;\n\n\t\tcase PTRACE_GETFPREGS:\n\t\t\tret = copy_regset_to_user(child,\n\t\t\t\t\t\t &user_arm_view, REGSET_FPR,\n\t\t\t\t\t\t 0, sizeof(union fp_state),\n\t\t\t\t\t\t datap);\n\t\t\tbreak;\n\n\t\tcase PTRACE_SETFPREGS:\n\t\t\tret = copy_regset_from_user(child,\n\t\t\t\t\t\t &user_arm_view, REGSET_FPR,\n\t\t\t\t\t\t 0, sizeof(union fp_state),\n\t\t\t\t\t\t datap);\n\t\t\tbreak;\n\n#ifdef CONFIG_IWMMXT\n\t\tcase PTRACE_GETWMMXREGS:\n\t\t\tret = ptrace_getwmmxregs(child, datap);\n\t\t\tbreak;\n\n\t\tcase PTRACE_SETWMMXREGS:\n\t\t\tret = ptrace_setwmmxregs(child, datap);\n\t\t\tbreak;\n#endif\n\n\t\tcase PTRACE_GET_THREAD_AREA:\n\t\t\tret = put_user(task_thread_info(child)->tp_value,\n\t\t\t\t datap);\n\t\t\tbreak;\n\n\t\tcase PTRACE_SET_SYSCALL:\n\t\t\ttask_thread_info(child)->syscall = data;\n\t\t\tret = 0;\n\t\t\tbreak;\n\n#ifdef CONFIG_CRUNCH\n\t\tcase PTRACE_GETCRUNCHREGS:\n\t\t\tret = ptrace_getcrunchregs(child, datap);\n\t\t\tbreak;\n\n\t\tcase PTRACE_SETCRUNCHREGS:\n\t\t\tret = ptrace_setcrunchregs(child, datap);\n\t\t\tbreak;\n#endif\n\n#ifdef CONFIG_VFP\n\t\tcase PTRACE_GETVFPREGS:\n\t\t\tret = copy_regset_to_user(child,\n\t\t\t\t\t\t &user_arm_view, REGSET_VFP,\n\t\t\t\t\t\t 0, ARM_VFPREGS_SIZE,\n\t\t\t\t\t\t datap);\n\t\t\tbreak;\n\n\t\tcase PTRACE_SETVFPREGS:\n\t\t\tret = copy_regset_from_user(child,\n\t\t\t\t\t\t &user_arm_view, REGSET_VFP,\n\t\t\t\t\t\t 0, ARM_VFPREGS_SIZE,\n\t\t\t\t\t\t datap);\n\t\t\tbreak;\n#endif\n\n#ifdef CONFIG_HAVE_HW_BREAKPOINT\n\t\tcase PTRACE_GETHBPREGS:\n\t\t\tif (ptrace_get_breakpoints(child) < 0)\n\t\t\t\treturn -ESRCH;\n\n\t\t\tret = ptrace_gethbpregs(child, addr,\n\t\t\t\t\t\t(unsigned long __user *)data);\n\t\t\tptrace_put_breakpoints(child);\n\t\t\tbreak;\n\t\tcase PTRACE_SETHBPREGS:\n\t\t\tif (ptrace_get_breakpoints(child) < 0)\n\t\t\t\treturn -ESRCH;\n\n\t\t\tret = ptrace_sethbpregs(child, addr,\n\t\t\t\t\t\t(unsigned long __user *)data);\n\t\t\tptrace_put_breakpoints(child);\n\t\t\tbreak;\n#endif\n\n\t\tdefault:\n\t\t\tret = ptrace_request(child, request, addr, data);\n\t\t\tbreak;\n\t}\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'ARM: 7735/2: Preserve the user r/w register TPIDRURW on context switch and fork\n\nSince commit 6a1c53124aa1 the user writeable TLS register was zeroed to\nprevent it from being used as a covert channel between two tasks.\n\nThere are more and more applications coming to Windows RT,\nWine could support them, but mostly they expect to have\nthe thread environment block (TEB) in TPIDRURW.\n\nThis patch preserves that register per thread instead of clearing it.\nUnlike the TPIDRURO, which is already switched, the TPIDRURW\ncan be updated from userspace so needs careful treatment in the case that we\nmodify TPIDRURW and call fork(). To avoid this we must always read\nTPIDRURW in copy_thread.\n\nSigned-off-by: Andr\u00e9 Hentschel \nSigned-off-by: Will Deacon \nSigned-off-by: Jonathan Austin \nSigned-off-by: Russell King '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: UTF16Ref getUTF16Ref(llvh::SmallVectorImpl &allocator) const {\n return getUTF16Ref(allocator, false);\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-703'], 'message': 'Fix a bug in transient object property assignment and getUTF16Ref\n\nSummary:\nThe returned `UTF16Ref` from `StringView::getUTF16Ref` can be invalidated by\nappending more contents to the same allocator.\nThis case was encountered in `transientObjectPutErrorMessage`, resulting in\nusing free'd memory.\n\nReviewed By: tmikov\n\nDifferential Revision: D23034855\n\nfbshipit-source-id: 4c25a5369934bf3bdfc5582385503f4b87de3792'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void handle_rx(struct vhost_net *net)\n{\n\tstruct vhost_net_virtqueue *nvq = &net->vqs[VHOST_NET_VQ_RX];\n\tstruct vhost_virtqueue *vq = &nvq->vq;\n\tunsigned uninitialized_var(in), log;\n\tstruct vhost_log *vq_log;\n\tstruct msghdr msg = {\n\t\t.msg_name = NULL,\n\t\t.msg_namelen = 0,\n\t\t.msg_control = NULL, /* FIXME: get and handle RX aux data. */\n\t\t.msg_controllen = 0,\n\t\t.msg_iov = vq->iov,\n\t\t.msg_flags = MSG_DONTWAIT,\n\t};\n\tstruct virtio_net_hdr_mrg_rxbuf hdr = {\n\t\t.hdr.flags = 0,\n\t\t.hdr.gso_type = VIRTIO_NET_HDR_GSO_NONE\n\t};\n\tsize_t total_len = 0;\n\tint err, mergeable;\n\ts16 headcount;\n\tsize_t vhost_hlen, sock_hlen;\n\tsize_t vhost_len, sock_len;\n\tstruct socket *sock;\n\n\tmutex_lock(&vq->mutex);\n\tsock = vq->private_data;\n\tif (!sock)\n\t\tgoto out;\n\tvhost_disable_notify(&net->dev, vq);\n\n\tvhost_hlen = nvq->vhost_hlen;\n\tsock_hlen = nvq->sock_hlen;\n\n\tvq_log = unlikely(vhost_has_feature(&net->dev, VHOST_F_LOG_ALL)) ?\n\t\tvq->log : NULL;\n\tmergeable = vhost_has_feature(&net->dev, VIRTIO_NET_F_MRG_RXBUF);\n\n\twhile ((sock_len = peek_head_len(sock->sk))) {\n\t\tsock_len += sock_hlen;\n\t\tvhost_len = sock_len + vhost_hlen;\n\t\theadcount = get_rx_bufs(vq, vq->heads, vhost_len,\n\t\t\t\t\t&in, vq_log, &log,\n\t\t\t\t\tlikely(mergeable) ? UIO_MAXIOV : 1);\n\t\t/* On error, stop handling until the next kick. */\n\t\tif (unlikely(headcount < 0))\n\t\t\tbreak;\n\t\t/* OK, now we need to know about added descriptors. */\n\t\tif (!headcount) {\n\t\t\tif (unlikely(vhost_enable_notify(&net->dev, vq))) {\n\t\t\t\t/* They have slipped one in as we were\n\t\t\t\t * doing that: check again. */\n\t\t\t\tvhost_disable_notify(&net->dev, vq);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t/* Nothing new? Wait for eventfd to tell us\n\t\t\t * they refilled. */\n\t\t\tbreak;\n\t\t}\n\t\t/* We don't need to be notified again. */\n\t\tif (unlikely((vhost_hlen)))\n\t\t\t/* Skip header. TODO: support TSO. */\n\t\t\tmove_iovec_hdr(vq->iov, nvq->hdr, vhost_hlen, in);\n\t\telse\n\t\t\t/* Copy the header for use in VIRTIO_NET_F_MRG_RXBUF:\n\t\t\t * needed because recvmsg can modify msg_iov. */\n\t\t\tcopy_iovec_hdr(vq->iov, nvq->hdr, sock_hlen, in);\n\t\tmsg.msg_iovlen = in;\n\t\terr = sock->ops->recvmsg(NULL, sock, &msg,\n\t\t\t\t\t sock_len, MSG_DONTWAIT | MSG_TRUNC);\n\t\t/* Userspace might have consumed the packet meanwhile:\n\t\t * it's not supposed to do this usually, but might be hard\n\t\t * to prevent. Discard data we got (if any) and keep going. */\n\t\tif (unlikely(err != sock_len)) {\n\t\t\tpr_debug(\"Discarded rx packet: \"\n\t\t\t\t \" len %d, expected %zd\\n\", err, sock_len);\n\t\t\tvhost_discard_vq_desc(vq, headcount);\n\t\t\tcontinue;\n\t\t}\n\t\tif (unlikely(vhost_hlen) &&\n\t\t memcpy_toiovecend(nvq->hdr, (unsigned char *)&hdr, 0,\n\t\t\t\t vhost_hlen)) {\n\t\t\tvq_err(vq, \"Unable to write vnet_hdr at addr %p\\n\",\n\t\t\t vq->iov->iov_base);\n\t\t\tbreak;\n\t\t}\n\t\t/* TODO: Should check and handle checksum. */\n\t\tif (likely(mergeable) &&\n\t\t memcpy_toiovecend(nvq->hdr, (unsigned char *)&headcount,\n\t\t\t\t offsetof(typeof(hdr), num_buffers),\n\t\t\t\t sizeof hdr.num_buffers)) {\n\t\t\tvq_err(vq, \"Failed num_buffers write\");\n\t\t\tvhost_discard_vq_desc(vq, headcount);\n\t\t\tbreak;\n\t\t}\n\t\tvhost_add_used_and_signal_n(&net->dev, vq, vq->heads,\n\t\t\t\t\t headcount);\n\t\tif (unlikely(vq_log))\n\t\t\tvhost_log_write(vq, vq_log, log, vhost_len);\n\t\ttotal_len += vhost_len;\n\t\tif (unlikely(total_len >= VHOST_NET_WEIGHT)) {\n\t\t\tvhost_poll_queue(&vq->poll);\n\t\t\tbreak;\n\t\t}\n\t}\nout:\n\tmutex_unlock(&vq->mutex);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-787'], 'message': 'vhost: fix total length when packets are too short\n\nWhen mergeable buffers are disabled, and the\nincoming packet is too large for the rx buffer,\nget_rx_bufs returns success.\n\nThis was intentional in order for make recvmsg\ntruncate the packet and then handle_rx would\ndetect err != sock_len and drop it.\n\nUnfortunately we pass the original sock_len to\nrecvmsg - which means we use parts of iov not fully\nvalidated.\n\nFix this up by detecting this overrun and doing packet drop\nimmediately.\n\nCVE-2014-0077\n\nSigned-off-by: Michael S. Tsirkin \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int decode_frame(AVCodecContext *avctx, void *data,\n int *got_frame, AVPacket *avpkt)\n{\n EXRContext *s = avctx->priv_data;\n ThreadFrame frame = { .f = data };\n AVFrame *picture = data;\n uint8_t *ptr;\n\n int i, y, ret, ymax;\n int planes;\n int out_line_size;\n int nb_blocks; /* nb scanline or nb tile */\n uint64_t start_offset_table;\n uint64_t start_next_scanline;\n PutByteContext offset_table_writer;\n\n bytestream2_init(&s->gb, avpkt->data, avpkt->size);\n\n if ((ret = decode_header(s, picture)) < 0)\n return ret;\n\n switch (s->pixel_type) {\n case EXR_FLOAT:\n case EXR_HALF:\n if (s->channel_offsets[3] >= 0) {\n if (!s->is_luma) {\n avctx->pix_fmt = AV_PIX_FMT_GBRAPF32;\n } else {\n /* todo: change this when a floating point pixel format with luma with alpha is implemented */\n avctx->pix_fmt = AV_PIX_FMT_GBRAPF32;\n }\n } else {\n if (!s->is_luma) {\n avctx->pix_fmt = AV_PIX_FMT_GBRPF32;\n } else {\n avctx->pix_fmt = AV_PIX_FMT_GRAYF32;\n }\n }\n break;\n case EXR_UINT:\n if (s->channel_offsets[3] >= 0) {\n if (!s->is_luma) {\n avctx->pix_fmt = AV_PIX_FMT_RGBA64;\n } else {\n avctx->pix_fmt = AV_PIX_FMT_YA16;\n }\n } else {\n if (!s->is_luma) {\n avctx->pix_fmt = AV_PIX_FMT_RGB48;\n } else {\n avctx->pix_fmt = AV_PIX_FMT_GRAY16;\n }\n }\n break;\n default:\n av_log(avctx, AV_LOG_ERROR, \"Missing channel list.\\n\");\n return AVERROR_INVALIDDATA;\n }\n\n if (s->apply_trc_type != AVCOL_TRC_UNSPECIFIED)\n avctx->color_trc = s->apply_trc_type;\n\n switch (s->compression) {\n case EXR_RAW:\n case EXR_RLE:\n case EXR_ZIP1:\n s->scan_lines_per_block = 1;\n break;\n case EXR_PXR24:\n case EXR_ZIP16:\n s->scan_lines_per_block = 16;\n break;\n case EXR_PIZ:\n case EXR_B44:\n case EXR_B44A:\n s->scan_lines_per_block = 32;\n break;\n default:\n avpriv_report_missing_feature(avctx, \"Compression %d\", s->compression);\n return AVERROR_PATCHWELCOME;\n }\n\n /* Verify the xmin, xmax, ymin and ymax before setting the actual image size.\n * It's possible for the data window can larger or outside the display window */\n if (s->xmin > s->xmax || s->ymin > s->ymax ||\n s->ydelta == 0xFFFFFFFF || s->xdelta == 0xFFFFFFFF) {\n av_log(avctx, AV_LOG_ERROR, \"Wrong or missing size information.\\n\");\n return AVERROR_INVALIDDATA;\n }\n\n if ((ret = ff_set_dimensions(avctx, s->w, s->h)) < 0)\n return ret;\n\n s->desc = av_pix_fmt_desc_get(avctx->pix_fmt);\n if (!s->desc)\n return AVERROR_INVALIDDATA;\n\n if (s->desc->flags & AV_PIX_FMT_FLAG_FLOAT) {\n planes = s->desc->nb_components;\n out_line_size = avctx->width * 4;\n } else {\n planes = 1;\n out_line_size = avctx->width * 2 * s->desc->nb_components;\n }\n\n if (s->is_tile) {\n nb_blocks = ((s->xdelta + s->tile_attr.xSize - 1) / s->tile_attr.xSize) *\n ((s->ydelta + s->tile_attr.ySize - 1) / s->tile_attr.ySize);\n } else { /* scanline */\n nb_blocks = (s->ydelta + s->scan_lines_per_block - 1) /\n s->scan_lines_per_block;\n }\n\n if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)\n return ret;\n\n if (bytestream2_get_bytes_left(&s->gb)/8 < nb_blocks)\n return AVERROR_INVALIDDATA;\n\n // check offset table and recreate it if need\n if (!s->is_tile && bytestream2_peek_le64(&s->gb) == 0) {\n av_log(s->avctx, AV_LOG_DEBUG, \"recreating invalid scanline offset table\\n\");\n\n start_offset_table = bytestream2_tell(&s->gb);\n start_next_scanline = start_offset_table + nb_blocks * 8;\n bytestream2_init_writer(&offset_table_writer, &avpkt->data[start_offset_table], nb_blocks * 8);\n\n for (y = 0; y < nb_blocks; y++) {\n /* write offset of prev scanline in offset table */\n bytestream2_put_le64(&offset_table_writer, start_next_scanline);\n\n /* get len of next scanline */\n bytestream2_seek(&s->gb, start_next_scanline + 4, SEEK_SET);/* skip line number */\n start_next_scanline += (bytestream2_get_le32(&s->gb) + 8);\n }\n bytestream2_seek(&s->gb, start_offset_table, SEEK_SET);\n }\n\n // save pointer we are going to use in decode_block\n s->buf = avpkt->data;\n s->buf_size = avpkt->size;\n\n // Zero out the start if ymin is not 0\n for (i = 0; i < planes; i++) {\n ptr = picture->data[i];\n for (y = 0; y < FFMIN(s->ymin, s->h); y++) {\n memset(ptr, 0, out_line_size);\n ptr += picture->linesize[i];\n }\n }\n\n s->picture = picture;\n\n avctx->execute2(avctx, decode_block, s->thread_data, NULL, nb_blocks);\n\n ymax = FFMAX(0, s->ymax + 1);\n // Zero out the end if ymax+1 is not h\n for (i = 0; i < planes; i++) {\n ptr = picture->data[i] + (ymax * picture->linesize[i]);\n for (y = ymax; y < avctx->height; y++) {\n memset(ptr, 0, out_line_size);\n ptr += picture->linesize[i];\n }\n }\n\n picture->pict_type = AV_PICTURE_TYPE_I;\n *got_frame = 1;\n\n return avpkt->size;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'avcodec/exr: skip bottom clearing loop when its outside the image\n\nFixes: signed integer overflow: 1633771809 * 32960 cannot be represented in type 'int'\nFixes: 26532/clusterfuzz-testcase-minimized-ffmpeg_AV_CODEC_ID_EXR_fuzzer-5613925708857344\n\nFound-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg\nSigned-off-by: Michael Niedermayer '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void igmp_heard_query(struct in_device *in_dev, struct sk_buff *skb,\n\tint len)\n{\n\tstruct igmphdr \t\t*ih = igmp_hdr(skb);\n\tstruct igmpv3_query *ih3 = igmpv3_query_hdr(skb);\n\tstruct ip_mc_list\t*im;\n\t__be32\t\t\tgroup = ih->group;\n\tint\t\t\tmax_delay;\n\tint\t\t\tmark = 0;\n\n\n\tif (len == 8) {\n\t\tif (ih->code == 0) {\n\t\t\t/* Alas, old v1 router presents here. */\n\n\t\t\tmax_delay = IGMP_Query_Response_Interval;\n\t\t\tin_dev->mr_v1_seen = jiffies +\n\t\t\t\tIGMP_V1_Router_Present_Timeout;\n\t\t\tgroup = 0;\n\t\t} else {\n\t\t\t/* v2 router present */\n\t\t\tmax_delay = ih->code*(HZ/IGMP_TIMER_SCALE);\n\t\t\tin_dev->mr_v2_seen = jiffies +\n\t\t\t\tIGMP_V2_Router_Present_Timeout;\n\t\t}\n\t\t/* cancel the interface change timer */\n\t\tin_dev->mr_ifc_count = 0;\n\t\tif (del_timer(&in_dev->mr_ifc_timer))\n\t\t\t__in_dev_put(in_dev);\n\t\t/* clear deleted report items */\n\t\tigmpv3_clear_delrec(in_dev);\n\t} else if (len < 12) {\n\t\treturn;\t/* ignore bogus packet; freed by caller */\n\t} else if (IGMP_V1_SEEN(in_dev)) {\n\t\t/* This is a v3 query with v1 queriers present */\n\t\tmax_delay = IGMP_Query_Response_Interval;\n\t\tgroup = 0;\n\t} else if (IGMP_V2_SEEN(in_dev)) {\n\t\t/* this is a v3 query with v2 queriers present;\n\t\t * Interpretation of the max_delay code is problematic here.\n\t\t * A real v2 host would use ih_code directly, while v3 has a\n\t\t * different encoding. We use the v3 encoding as more likely\n\t\t * to be intended in a v3 query.\n\t\t */\n\t\tmax_delay = IGMPV3_MRC(ih3->code)*(HZ/IGMP_TIMER_SCALE);\n\t} else { /* v3 */\n\t\tif (!pskb_may_pull(skb, sizeof(struct igmpv3_query)))\n\t\t\treturn;\n\n\t\tih3 = igmpv3_query_hdr(skb);\n\t\tif (ih3->nsrcs) {\n\t\t\tif (!pskb_may_pull(skb, sizeof(struct igmpv3_query)\n\t\t\t\t\t + ntohs(ih3->nsrcs)*sizeof(__be32)))\n\t\t\t\treturn;\n\t\t\tih3 = igmpv3_query_hdr(skb);\n\t\t}\n\n\t\tmax_delay = IGMPV3_MRC(ih3->code)*(HZ/IGMP_TIMER_SCALE);\n\t\tif (!max_delay)\n\t\t\tmax_delay = 1;\t/* can't mod w/ 0 */\n\t\tin_dev->mr_maxdelay = max_delay;\n\t\tif (ih3->qrv)\n\t\t\tin_dev->mr_qrv = ih3->qrv;\n\t\tif (!group) { /* general query */\n\t\t\tif (ih3->nsrcs)\n\t\t\t\treturn;\t/* no sources allowed */\n\t\t\tigmp_gq_start_timer(in_dev);\n\t\t\treturn;\n\t\t}\n\t\t/* mark sources to include, if group & source-specific */\n\t\tmark = ih3->nsrcs != 0;\n\t}\n\n\t/*\n\t * - Start the timers in all of our membership records\n\t * that the query applies to for the interface on\n\t * which the query arrived excl. those that belong\n\t * to a \"local\" group (224.0.0.X)\n\t * - For timers already running check if they need to\n\t * be reset.\n\t * - Use the igmp->igmp_code field as the maximum\n\t * delay possible\n\t */\n\trcu_read_lock();\n\tfor_each_pmc_rcu(in_dev, im) {\n\t\tint changed;\n\n\t\tif (group && group != im->multiaddr)\n\t\t\tcontinue;\n\t\tif (im->multiaddr == IGMP_ALL_HOSTS)\n\t\t\tcontinue;\n\t\tspin_lock_bh(&im->lock);\n\t\tif (im->tm_running)\n\t\t\tim->gsquery = im->gsquery && mark;\n\t\telse\n\t\t\tim->gsquery = mark;\n\t\tchanged = !im->gsquery ||\n\t\t\tigmp_marksources(im, ntohs(ih3->nsrcs), ih3->srcs);\n\t\tspin_unlock_bh(&im->lock);\n\t\tif (changed)\n\t\t\tigmp_mod_timer(im, max_delay);\n\t}\n\trcu_read_unlock();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-703', 'CWE-369'], 'message': 'igmp: Avoid zero delay when receiving odd mixture of IGMP queries\n\nCommit 5b7c84066733c5dfb0e4016d939757b38de189e4 ('ipv4: correct IGMP\nbehavior on v3 query during v2-compatibility mode') added yet another\ncase for query parsing, which can result in max_delay = 0. Substitute\na value of 1, as in the usual v3 case.\n\nReported-by: Simon McVittie \nReferences: http://bugs.debian.org/654876\nSigned-off-by: Ben Hutchings \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void CalculateOutputIndexRowSplit(\n const RowPartitionTensor& row_split,\n const vector& parent_output_index,\n INDEX_TYPE output_index_multiplier, INDEX_TYPE output_size,\n vector* result) {\n INDEX_TYPE row_split_size = row_split.size();\n if (row_split_size > 0) {\n result->reserve(row_split(row_split_size - 1));\n }\n for (INDEX_TYPE i = 0; i < row_split_size - 1; ++i) {\n INDEX_TYPE row_length = row_split(i + 1) - row_split(i);\n INDEX_TYPE real_length = std::min(output_size, row_length);\n INDEX_TYPE parent_output_index_current = parent_output_index[i];\n\n if (parent_output_index_current == -1) {\n real_length = 0;\n }\n for (INDEX_TYPE j = 0; j < real_length; ++j) {\n result->push_back(parent_output_index_current);\n parent_output_index_current += output_index_multiplier;\n }\n for (INDEX_TYPE j = 0; j < row_length - real_length; ++j) {\n result->push_back(-1);\n }\n }\n if (row_split_size > 0) {\n DCHECK_EQ(result->size(), row_split(row_split_size - 1));\n }\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-131', 'CWE-787'], 'message': 'Fix `tf.raw_ops.RaggedTensorToTensor` failing CHECK.\n\nPiperOrigin-RevId: 368706628\nChange-Id: I5c9ea4833f38835ee183ca50d63251dc89c9f3bc'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TEST_CASE(\"enter/leave handlers test\", \"[general]\")\n{\n parser parser(R\"(\n START <- LTOKEN '=' RTOKEN\n LTOKEN <- TOKEN\n RTOKEN <- TOKEN\n TOKEN <- [A-Za-z]+\n )\");\n\n parser[\"LTOKEN\"].enter = [&](const char*, size_t, any& dt) {\n auto& require_upper_case = *any_cast(dt);\n require_upper_case = false;\n };\n parser[\"LTOKEN\"].leave = [&](const char*, size_t, size_t, any&, any& dt) {\n auto& require_upper_case = *any_cast(dt);\n require_upper_case = true;\n };\n\n auto message = \"should be upper case string...\";\n\n parser[\"TOKEN\"] = [&](const SemanticValues& sv, any& dt) {\n auto& require_upper_case = *any_cast(dt);\n if (require_upper_case) {\n const auto& s = sv.str();\n if (!std::all_of(s.begin(), s.end(), ::isupper)) {\n throw parse_error(message);\n }\n }\n };\n\n bool require_upper_case = false;\n any dt = &require_upper_case;\n REQUIRE(parser.parse(\"hello=world\", dt) == false);\n REQUIRE(parser.parse(\"HELLO=world\", dt) == false);\n REQUIRE(parser.parse(\"hello=WORLD\", dt) == true);\n REQUIRE(parser.parse(\"HELLO=WORLD\", dt) == true);\n\n parser.log = [&](size_t ln, size_t col, const std::string& msg) {\n REQUIRE(ln == 1);\n REQUIRE(col == 7);\n REQUIRE(msg == message);\n };\n parser.parse(\"hello=world\", dt);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix #122'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TEST_CASE(\"String capture test3\", \"[general]\")\n{\n parser pg(R\"(\n ROOT <- _ TOKEN*\n TOKEN <- '[' < (!']' .)+ > ']' _\n _ <- [ \\t\\r\\n]*\n )\");\n\n\n std::vector tags;\n\n pg[\"TOKEN\"] = [&](const SemanticValues& sv) {\n tags.push_back(sv.token());\n };\n\n auto ret = pg.parse(\" [tag1] [tag:2] [tag-3] \");\n\n REQUIRE(ret == true);\n REQUIRE(tags.size() == 3);\n REQUIRE(tags[0] == \"tag1\");\n REQUIRE(tags[1] == \"tag:2\");\n REQUIRE(tags[2] == \"tag-3\");\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix #122'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void cmd_parse_status(struct ImapData *idata, char *s)\n{\n char *value = NULL;\n struct Buffy *inc = NULL;\n struct ImapMbox mx;\n struct ImapStatus *status = NULL;\n unsigned int olduv, oldun;\n unsigned int litlen;\n short new = 0;\n short new_msg_count = 0;\n\n char *mailbox = imap_next_word(s);\n\n /* We need a real tokenizer. */\n if (imap_get_literal_count(mailbox, &litlen) == 0)\n {\n if (imap_cmd_step(idata) != IMAP_CMD_CONTINUE)\n {\n idata->status = IMAP_FATAL;\n return;\n }\n mailbox = idata->buf;\n s = mailbox + litlen;\n *s = '\\0';\n s++;\n SKIPWS(s);\n }\n else\n {\n s = imap_next_word(mailbox);\n *(s - 1) = '\\0';\n imap_unmunge_mbox_name(idata, mailbox);\n }\n\n status = imap_mboxcache_get(idata, mailbox, 1);\n olduv = status->uidvalidity;\n oldun = status->uidnext;\n\n if (*s++ != '(')\n {\n mutt_debug(1, \"Error parsing STATUS\\n\");\n return;\n }\n while (*s && *s != ')')\n {\n value = imap_next_word(s);\n\n errno = 0;\n const unsigned long ulcount = strtoul(value, &value, 10);\n if (((errno == ERANGE) && (ulcount == ULONG_MAX)) || ((unsigned int) ulcount != ulcount))\n {\n mutt_debug(1, \"Error parsing STATUS number\\n\");\n return;\n }\n const unsigned int count = (unsigned int) ulcount;\n\n if (mutt_str_strncmp(\"MESSAGES\", s, 8) == 0)\n {\n status->messages = count;\n new_msg_count = 1;\n }\n else if (mutt_str_strncmp(\"RECENT\", s, 6) == 0)\n status->recent = count;\n else if (mutt_str_strncmp(\"UIDNEXT\", s, 7) == 0)\n status->uidnext = count;\n else if (mutt_str_strncmp(\"UIDVALIDITY\", s, 11) == 0)\n status->uidvalidity = count;\n else if (mutt_str_strncmp(\"UNSEEN\", s, 6) == 0)\n status->unseen = count;\n\n s = value;\n if (*s && *s != ')')\n s = imap_next_word(s);\n }\n mutt_debug(3, \"%s (UIDVALIDITY: %u, UIDNEXT: %u) %d messages, %d recent, %d unseen\\n\",\n status->name, status->uidvalidity, status->uidnext,\n status->messages, status->recent, status->unseen);\n\n /* caller is prepared to handle the result herself */\n if (idata->cmddata && idata->cmdtype == IMAP_CT_STATUS)\n {\n memcpy(idata->cmddata, status, sizeof(struct ImapStatus));\n return;\n }\n\n mutt_debug(3, \"Running default STATUS handler\\n\");\n\n /* should perhaps move this code back to imap_buffy_check */\n for (inc = Incoming; inc; inc = inc->next)\n {\n if (inc->magic != MUTT_IMAP)\n continue;\n\n if (imap_parse_path(inc->path, &mx) < 0)\n {\n mutt_debug(1, \"Error parsing mailbox %s, skipping\\n\", inc->path);\n continue;\n }\n\n if (imap_account_match(&idata->conn->account, &mx.account))\n {\n if (mx.mbox)\n {\n value = mutt_str_strdup(mx.mbox);\n imap_fix_path(idata, mx.mbox, value, mutt_str_strlen(value) + 1);\n FREE(&mx.mbox);\n }\n else\n value = mutt_str_strdup(\"INBOX\");\n\n if (value && (imap_mxcmp(mailbox, value) == 0))\n {\n mutt_debug(3, \"Found %s in buffy list (OV: %u ON: %u U: %d)\\n\", mailbox,\n olduv, oldun, status->unseen);\n\n if (MailCheckRecent)\n {\n if (olduv && olduv == status->uidvalidity)\n {\n if (oldun < status->uidnext)\n new = (status->unseen > 0);\n }\n else if (!olduv && !oldun)\n {\n /* first check per session, use recent. might need a flag for this. */\n new = (status->recent > 0);\n }\n else\n new = (status->unseen > 0);\n }\n else\n new = (status->unseen > 0);\n\n#ifdef USE_SIDEBAR\n if ((inc->new != new) || (inc->msg_count != status->messages) ||\n (inc->msg_unread != status->unseen))\n {\n mutt_menu_set_current_redraw(REDRAW_SIDEBAR);\n }\n#endif\n inc->new = new;\n if (new_msg_count)\n inc->msg_count = status->messages;\n inc->msg_unread = status->unseen;\n\n if (inc->new)\n {\n /* force back to keep detecting new mail until the mailbox is\n opened */\n status->uidnext = oldun;\n }\n\n FREE(&value);\n return;\n }\n\n FREE(&value);\n }\n\n FREE(&mx.mbox);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Ensure litlen isn't larger than our mailbox'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void Compute(OpKernelContext* c) override {\n PartialTensorShape element_shape;\n OP_REQUIRES_OK(c, TensorShapeFromTensor(c->input(0), &element_shape));\n int32 num_elements = c->input(1).scalar()();\n TensorList output;\n output.element_shape = element_shape;\n output.element_dtype = element_dtype_;\n output.tensors().resize(num_elements, Tensor(DT_INVALID));\n Tensor* result;\n AllocatorAttributes attr;\n attr.set_on_host(true);\n OP_REQUIRES_OK(c, c->allocate_output(0, TensorShape{}, &result, attr));\n result->scalar()() = std::move(output);\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617', 'CWE-369'], 'message': 'Validate num_elements input in tf.raw_ops.TensorListReserve\n\nPiperOrigin-RevId: 383954564\nChange-Id: I454bd78eff85bc4f16ddb7e608596971cca47f8f'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: gerbv_gdk_draw_prim22(GdkPixmap *pixmap, GdkGC *gc, double *p, \n\t\t double scale, gint x, gint y)\n{\n const int exposure_idx = 0;\n const int width_idx = 1;\n const int height_idx = 2;\n const int x_lower_left_idx = 3;\n const int y_lower_left_idx = 4;\n const int rotation_idx = 5;\n const int nuf_points = 4;\n GdkPoint points[nuf_points];\n GdkGC *local_gc = gdk_gc_new(pixmap);\n GdkColor color;\n int i;\n\n points[0].x = (int)round(p[x_lower_left_idx] * scale);\n points[0].y = (int)round(p[y_lower_left_idx] * scale);\n\n points[1].x = (int)round((p[x_lower_left_idx] + p[width_idx])\n\t\t\t * scale);\n points[1].y = (int)round(p[y_lower_left_idx] * scale);\n\n points[2].x = (int)round((p[x_lower_left_idx] + p[width_idx])\n\t\t\t * scale);\n points[2].y = (int)round((p[y_lower_left_idx] + p[height_idx])\n\t\t\t * scale);\n\n points[3].x = (int)round(p[x_lower_left_idx] * scale);\n points[3].y = (int)round((p[y_lower_left_idx] + p[height_idx])\n\t\t\t * scale);\n\n for (i = 0; i < nuf_points; i++) {\n\tpoints[i] = rotate_point(points[i], -p[rotation_idx]);\n\tpoints[i].x = x + points[i].x;\n\tpoints[i].y = y - points[i].y;\n }\n\n gdk_gc_copy(local_gc, gc);\n\n /* Exposure */\n if (p[exposure_idx] == 0.0) {\n\tcolor.pixel = 0;\n\tgdk_gc_set_foreground(local_gc, &color);\n }\n\n gdk_draw_polygon(pixmap, local_gc, 1, points, nuf_points);\n\n gdk_gc_unref(local_gc);\n\n return;\n} /* gerbv_gdk_draw_prim22 */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'Avoid direct access on array of unknown size\n\nBe requiring a `gerbv_simplified_amacro_t` the `dgk_draw_amacro_funcs` can be sure of the length of the parameter array.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int wolfSSH_SFTP_RecvOpenDir(WOLFSSH* ssh, int reqId, byte* data, word32 maxSz)\n#ifndef USE_WINDOWS_API\n{\n WDIR ctx;\n word32 sz;\n char* dir;\n word32 idx = 0;\n int ret = WS_SUCCESS;\n\n word32 outSz = sizeof(word32)*2 + WOLFSSH_SFTP_HEADER + UINT32_SZ;\n byte* out = NULL;\n word32 id[2];\n byte idFlat[sizeof(word32) * 2];\n\n if (ssh == NULL) {\n return WS_BAD_ARGUMENT;\n }\n\n WLOG(WS_LOG_SFTP, \"Receiving WOLFSSH_FTP_OPENDIR\");\n\n if (sizeof(WFD) > WOLFSSH_MAX_HANDLE) {\n WLOG(WS_LOG_SFTP, \"Handle size is too large\");\n return WS_FATAL_ERROR;\n }\n\n /* get directory name */\n ato32(data + idx, &sz); idx += UINT32_SZ;\n if (sz + idx > maxSz) {\n return WS_BUFFER_E;\n }\n\n /* plus one to make sure is null terminated */\n dir = (char*)WMALLOC(sz + 1, ssh->ctx->heap, DYNTYPE_BUFFER);\n if (dir == NULL) {\n return WS_MEMORY_E;\n }\n WMEMCPY(dir, data + idx, sz);\n dir[sz] = '\\0';\n\n /* get directory handle */\n if (wolfSSH_CleanPath(ssh, dir) < 0) {\n WFREE(dir, ssh->ctx->heap, DYNTYPE_BUFFER);\n return WS_FATAL_ERROR;\n }\n\n if (WOPENDIR(ssh->fs, ssh->ctx->heap, &ctx, dir) != 0) {\n WLOG(WS_LOG_SFTP, \"Error with opening directory\");\n WFREE(dir, ssh->ctx->heap, DYNTYPE_BUFFER);\n if (wolfSSH_SFTP_CreateStatus(ssh, WOLFSSH_FTP_NOFILE, reqId,\n \"Unable To Open Directory\", \"English\", NULL, &outSz)\n != WS_SIZE_ONLY) {\n return WS_FATAL_ERROR;\n }\n ret = WS_BAD_FILE_E;\n }\n\n (void)reqId;\n\n /* add to directory list @TODO locking for thread safety */\n if (ret == WS_SUCCESS) {\n DIR_HANDLE* cur = (DIR_HANDLE*)WMALLOC(sizeof(DIR_HANDLE),\n ssh->ctx->heap, DYNTYPE_SFTP);\n if (cur == NULL) {\n WFREE(dir, ssh->ctx->heap, DYNTYPE_BUFFER);\n WCLOSEDIR(&ctx);\n return WS_MEMORY_E;\n }\n#ifdef WOLFSSL_NUCLEUS\n WMEMCPY(&cur->dir, &ctx, sizeof(WDIR));\n#else\n cur->dir = ctx;\n#endif\n cur->id[0] = id[0] = idCount[0];\n cur->id[1] = id[1] = idCount[1];\n c32toa(id[0], idFlat);\n c32toa(id[1], idFlat + UINT32_SZ);\n AddAssign64(idCount, 1);\n cur->isEof = 0;\n cur->next = dirList;\n dirList = cur;\n dirList->dirName = dir; /* take over ownership of buffer */\n }\n\n out = (byte*)WMALLOC(outSz, ssh->ctx->heap, DYNTYPE_BUFFER);\n if (out == NULL) {\n return WS_MEMORY_E;\n }\n\n if (ret == WS_SUCCESS) {\n SFTP_CreatePacket(ssh, WOLFSSH_FTP_HANDLE, out, outSz,\n idFlat, sizeof(idFlat));\n }\n else {\n if (wolfSSH_SFTP_CreateStatus(ssh, WOLFSSH_FTP_NOFILE, reqId,\n \"Unable To Open Directory\", \"English\", out, &outSz)\n != WS_SUCCESS) {\n WFREE(out, ssh->ctx->heap, DYNTYPE_BUFFER);\n return WS_FATAL_ERROR;\n }\n }\n\n /* set send out buffer, \"out\" is taken by ssh */\n wolfSSH_SFTP_RecvSetSend(ssh, out, outSz);\n\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'ASAN SFTP Fixes\nWhen decoding SFTP messages, fix the size checks so they don't wrap. (ZD12766)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void LineBitmapRequester::ReconstructRegion(const RectAngle &orgregion,const struct RectangleRequest *rr)\n{\n class ColorTrafo *ctrafo = ColorTrafoOf(false,!rr->rr_bColorTrafo);\n UBYTE i;\n\n if (m_bSubsampling && rr->rr_bUpsampling) { \n for(i = rr->rr_usFirstComponent;i <= rr->rr_usLastComponent;i++) {\n class Component *comp = m_pFrame->ComponentOf(i);\n UBYTE subx = comp->SubXOf();\n UBYTE suby = comp->SubYOf();\n class UpsamplerBase *up; // upsampler\n LONG bx,by;\n RectAngle blocks;\n //\n // Compute the region of blocks\n assert(subx > 0 && suby > 0);\n if ((up = m_ppUpsampler[i])) {\n LONG bwidth = ((m_ulPixelWidth + subx - 1) / subx + 7) >> 3;\n LONG bheight = ((m_ulPixelHeight + suby - 1) / suby + 7) >> 3;\n LONG rx = (subx > 1)?(1):(0);\n LONG ry = (suby > 1)?(1):(0);\n // The +/-1 include additional lines required for subsampling expansion\n blocks.ra_MinX = ((orgregion.ra_MinX / subx - rx) >> 3);\n blocks.ra_MaxX = ((orgregion.ra_MaxX / subx + rx) >> 3);\n blocks.ra_MinY = ((orgregion.ra_MinY / suby - ry) >> 3);\n blocks.ra_MaxY = ((orgregion.ra_MaxY / suby + ry) >> 3);\n // Clip.\n if (blocks.ra_MinX < 0) blocks.ra_MinX = 0;\n if (blocks.ra_MaxX >= bwidth) blocks.ra_MaxX = bwidth - 1;\n if (blocks.ra_MinY < 0) blocks.ra_MinY = 0;\n if (blocks.ra_MaxY >= bheight) blocks.ra_MaxY = bheight - 1;\n up->SetBufferedRegion(blocks); // also removes the rectangle of blocks already buffered.\n //\n for(by = blocks.ra_MinY;by <= blocks.ra_MaxY;by++) {\n for(bx = blocks.ra_MinX;bx <= blocks.ra_MaxX;bx++) {\n LONG dst[64];\n if (*m_pppImage[i]) {\n FetchRegion(bx,*m_pppImage[i],dst);\n } else {\n memset(dst,0,sizeof(dst));\n }\n up->DefineRegion(bx,by,dst);\n }\n Next8Lines(i);\n }\n }\n }\n // Now push blocks into the color transformer from the upsampler.\n {\n RectAngle r;\n ULONG minx = orgregion.ra_MinX >> 3;\n ULONG maxx = orgregion.ra_MaxX >> 3;\n ULONG miny = orgregion.ra_MinY >> 3;\n ULONG maxy = orgregion.ra_MaxY >> 3;\n ULONG x,y;\n \n if (maxy > m_ulMaxMCU)\n maxy = m_ulMaxMCU;\n\n for(y = miny,r.ra_MinY = orgregion.ra_MinY;y <= maxy;y++,r.ra_MinY = r.ra_MaxY + 1) {\n r.ra_MaxY = (r.ra_MinY & -8) + 7;\n if (r.ra_MaxY > orgregion.ra_MaxY)\n r.ra_MaxY = orgregion.ra_MaxY;\n \n for(x = minx,r.ra_MinX = orgregion.ra_MinX;x <= maxx;x++,r.ra_MinX = r.ra_MaxX + 1) {\n r.ra_MaxX = (r.ra_MinX & -8) + 7;\n if (r.ra_MaxX > orgregion.ra_MaxX)\n r.ra_MaxX = orgregion.ra_MaxX;\n \n for(i = 0;i < m_ucCount;i++) {\n if (i >= rr->rr_usFirstComponent && i <= rr->rr_usLastComponent) {\n ExtractBitmap(m_ppTempIBM[i],r,i);\n if (m_ppUpsampler[i]) {\n // Upsampled case, take from the upsampler, transform\n // into the color buffer.\n m_ppUpsampler[i]->UpsampleRegion(r,m_ppCTemp[i]);\n } else if (*m_pppImage[i]) {\n FetchRegion(x,*m_pppImage[i],m_ppCTemp[i]);\n } else {\n memset(m_ppCTemp[0],0,sizeof(LONG) * 64);\n }\n } else {\n // Not requested, zero the buffer.\n memset(m_ppCTemp[i],0,sizeof(LONG) * 64);\n }\n }\n ctrafo->YCbCr2RGB(r,m_ppTempIBM,m_ppCTemp,NULL);\n }\n //\n // Advance the quantized rows for the non-subsampled components,\n // upsampled components have been advanced above.\n for(i = rr->rr_usFirstComponent;i <= rr->rr_usLastComponent;i++) {\n if (m_ppUpsampler[i] == NULL)\n Next8Lines(i);\n }\n }\n }\n } else { // direct case, no upsampling required, residual coding possible.\n RectAngle r;\n RectAngle region = orgregion;\n SubsampledRegion(region,rr);\n ULONG minx = region.ra_MinX >> 3;\n ULONG maxx = region.ra_MaxX >> 3;\n ULONG miny = region.ra_MinY >> 3;\n ULONG maxy = region.ra_MaxY >> 3;\n ULONG x,y;\n \n if (maxy > m_ulMaxMCU)\n maxy = m_ulMaxMCU;\n\n for(y = miny,r.ra_MinY = region.ra_MinY;y <= maxy;y++,r.ra_MinY = r.ra_MaxY + 1) {\n r.ra_MaxY = (r.ra_MinY & -8) + 7;\n if (r.ra_MaxY > region.ra_MaxY)\n r.ra_MaxY = region.ra_MaxY;\n \n for(x = minx,r.ra_MinX = region.ra_MinX;x <= maxx;x++,r.ra_MinX = r.ra_MaxX + 1) {\n r.ra_MaxX = (r.ra_MinX & -8) + 7;\n if (r.ra_MaxX > region.ra_MaxX)\n r.ra_MaxX = region.ra_MaxX;\n\n for(i = 0;i < m_ucCount;i++) { \n LONG *dst = m_ppCTemp[i];\n if (i >= rr->rr_usFirstComponent && i <= rr->rr_usLastComponent) {\n ExtractBitmap(m_ppTempIBM[i],r,i);\n FetchRegion(x,*m_pppImage[i],dst);\n } else {\n memset(dst,0,sizeof(LONG) * 64);\n }\n }\n //\n // Perform the color transformation now.\n ctrafo->YCbCr2RGB(r,m_ppTempIBM,m_ppCTemp,NULL);\n } // of loop over x\n //\n // Advance the rows.\n for(i = rr->rr_usFirstComponent;i <= rr->rr_usLastComponent;i++) {\n Next8Lines(i);\n }\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed a NULL-pointer access in the line-based reconstruction process\nin case no valid scan was found and no data is present.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int igmp6_event_query(struct sk_buff *skb)\n{\n\tstruct inet6_dev *idev = __in6_dev_get(skb->dev);\n\n\tif (!idev)\n\t\treturn -EINVAL;\n\n\tif (idev->dead) {\n\t\tkfree_skb(skb);\n\t\treturn -ENODEV;\n\t}\n\n\tspin_lock_bh(&idev->mc_query_lock);\n\tif (skb_queue_len(&idev->mc_query_queue) < MLD_MAX_SKBS) {\n\t\t__skb_queue_tail(&idev->mc_query_queue, skb);\n\t\tif (!mod_delayed_work(mld_wq, &idev->mc_query_work, 0))\n\t\t\tin6_dev_hold(idev);\n\t}\n\tspin_unlock_bh(&idev->mc_query_lock);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'ipv6: fix skb drops in igmp6_event_query() and igmp6_event_report()\n\nWhile investigating on why a synchronize_net() has been added recently\nin ipv6_mc_down(), I found that igmp6_event_query() and igmp6_event_report()\nmight drop skbs in some cases.\n\nDiscussion about removing synchronize_net() from ipv6_mc_down()\nwill happen in a different thread.\n\nFixes: f185de28d9ae (\"mld: add new workqueues for process mld events\")\nSigned-off-by: Eric Dumazet \nCc: Taehee Yoo \nCc: Cong Wang \nCc: David Ahern \nLink: https://lore.kernel.org/r/20220303173728.937869-1-eric.dumazet@gmail.com\nSigned-off-by: Jakub Kicinski '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: Status Conv3DShape(shape_inference::InferenceContext* c) {\n ShapeHandle input_shape;\n TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 5, &input_shape));\n ShapeHandle filter_shape;\n TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 5, &filter_shape));\n\n string data_format;\n Status s = c->GetAttr(\"data_format\", &data_format);\n\n std::vector dilations;\n TF_RETURN_IF_ERROR(c->GetAttr(\"dilations\", &dilations));\n\n if (dilations.size() != 5) {\n return errors::InvalidArgument(\n \"Conv3D requires the dilation attribute to contain 5 values, but got: \",\n dilations.size());\n }\n\n std::vector strides;\n TF_RETURN_IF_ERROR(c->GetAttr(\"strides\", &strides));\n if (strides.size() != 5) {\n return errors::InvalidArgument(\n \"Conv3D requires the stride attribute to contain 5 values, but got: \",\n strides.size());\n }\n\n int32_t stride_planes, stride_rows, stride_cols;\n int32_t dilation_planes, dilation_rows, dilation_cols;\n if (s.ok() && data_format == \"NCDHW\") {\n // Convert input_shape to NDHWC.\n auto dim = [&](char dimension) {\n return c->Dim(input_shape, GetTensorDimIndex<3>(FORMAT_NCHW, dimension));\n };\n input_shape =\n c->MakeShape({{dim('N'), dim('0'), dim('1'), dim('2'), dim('C')}});\n stride_planes = strides[2];\n stride_rows = strides[3];\n stride_cols = strides[4];\n dilation_planes = dilations[2];\n dilation_cols = dilations[3];\n dilation_rows = dilations[4];\n } else {\n stride_planes = strides[1];\n stride_rows = strides[2];\n stride_cols = strides[3];\n dilation_planes = dilations[1];\n dilation_cols = dilations[2];\n dilation_rows = dilations[3];\n }\n\n DimensionHandle batch_size_dim = c->Dim(input_shape, 0);\n DimensionHandle in_planes_dim = c->Dim(input_shape, 1);\n DimensionHandle in_rows_dim = c->Dim(input_shape, 2);\n DimensionHandle in_cols_dim = c->Dim(input_shape, 3);\n DimensionHandle input_depth_dim = c->Dim(input_shape, 4);\n\n DimensionHandle filter_planes_dim = c->Dim(filter_shape, 0);\n DimensionHandle filter_rows_dim = c->Dim(filter_shape, 1);\n DimensionHandle filter_cols_dim = c->Dim(filter_shape, 2);\n DimensionHandle filter_input_depth_dim = c->Dim(filter_shape, 3);\n DimensionHandle output_depth_dim = c->Dim(filter_shape, 4);\n\n // Check that the input tensor and the filter tensor agree on the channel\n // count.\n if (c->ValueKnown(input_depth_dim) && c->ValueKnown(filter_input_depth_dim)) {\n int64_t input_depth_value = c->Value(input_depth_dim),\n filter_input_depth_value = c->Value(filter_input_depth_dim);\n if (input_depth_value % filter_input_depth_value != 0)\n return errors::InvalidArgument(\n \"Depth of input (\", input_depth_value,\n \") is not a multiple of input depth of filter (\",\n filter_input_depth_value, \")\");\n if (input_depth_value != filter_input_depth_value) {\n int64_t num_groups = input_depth_value / filter_input_depth_value;\n if (c->ValueKnown(output_depth_dim)) {\n int64_t output_depth_value = c->Value(output_depth_dim);\n if (output_depth_value % num_groups != 0)\n return errors::InvalidArgument(\n \"Depth of output (\", output_depth_value,\n \") is not a multiple of the number of groups (\", num_groups, \")\");\n }\n }\n }\n\n Padding padding;\n TF_RETURN_IF_ERROR(c->GetAttr(\"padding\", &padding));\n DimensionHandle output_planes, output_rows, output_cols;\n\n TF_RETURN_IF_ERROR(GetWindowedOutputSizeFromDimsV2(\n c, in_planes_dim, filter_planes_dim, dilation_planes, stride_planes,\n padding, -1, -1, &output_planes));\n TF_RETURN_IF_ERROR(GetWindowedOutputSizeFromDimsV2(\n c, in_rows_dim, filter_rows_dim, dilation_rows, stride_rows, padding, -1,\n -1, &output_rows));\n TF_RETURN_IF_ERROR(GetWindowedOutputSizeFromDimsV2(\n c, in_cols_dim, filter_cols_dim, dilation_cols, stride_cols, padding, -1,\n -1, &output_cols));\n\n ShapeHandle output_shape;\n if (data_format == \"NCDHW\") {\n output_shape = c->MakeShape({batch_size_dim, output_depth_dim,\n output_planes, output_rows, output_cols});\n } else {\n output_shape = c->MakeShape({batch_size_dim, output_planes, output_rows,\n output_cols, output_depth_dim});\n }\n c->set_output(0, output_shape);\n return Status::OK();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-369'], 'message': 'Prevent division by 0 in common shape functions.\n\nPiperOrigin-RevId: 387712197\nChange-Id: Id25c7460e35b68aeeeac23b9a88e455b443ee149'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void show_object_with_name(FILE *out, struct object *obj,\n\t\t\t struct strbuf *path, const char *component)\n{\n\tchar *name = path_name(path, component);\n\tchar *p;\n\n\tfprintf(out, \"%s \", oid_to_hex(&obj->oid));\n\tfor (p = name; *p && *p != '\\n'; p++)\n\t\tfputc(*p, out);\n\tfputc('\\n', out);\n\n\tfree(name);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'list-objects: pass full pathname to callbacks\n\nWhen we find a blob at \"a/b/c\", we currently pass this to\nour show_object_fn callbacks as two components: \"a/b/\" and\n\"c\". Callbacks which want the full value then call\npath_name(), which concatenates the two. But this is an\ninefficient interface; the path is a strbuf, and we could\nsimply append \"c\" to it temporarily, then roll back the\nlength, without creating a new copy.\n\nSo we could improve this by teaching the callsites of\npath_name() this trick (and there are only 3). But we can\nalso notice that no callback actually cares about the\nbroken-down representation, and simply pass each callback\nthe full path \"a/b/c\" as a string. The callback code becomes\neven simpler, then, as we do not have to worry about freeing\nan allocated buffer, nor rolling back our modification to\nthe strbuf.\n\nThis is theoretically less efficient, as some callbacks\nwould not bother to format the final path component. But in\npractice this is not measurable. Since we use the same\nstrbuf over and over, our work to grow it is amortized, and\nwe really only pay to memcpy a few bytes.\n\nSigned-off-by: Jeff King \nSigned-off-by: Junio C Hamano '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void process_tree(struct rev_info *revs,\n\t\t\t struct tree *tree,\n\t\t\t show_object_fn show,\n\t\t\t struct strbuf *base,\n\t\t\t const char *name,\n\t\t\t void *cb_data)\n{\n\tstruct object *obj = &tree->object;\n\tstruct tree_desc desc;\n\tstruct name_entry entry;\n\tenum interesting match = revs->diffopt.pathspec.nr == 0 ?\n\t\tall_entries_interesting: entry_not_interesting;\n\tint baselen = base->len;\n\n\tif (!revs->tree_objects)\n\t\treturn;\n\tif (!obj)\n\t\tdie(\"bad tree object\");\n\tif (obj->flags & (UNINTERESTING | SEEN))\n\t\treturn;\n\tif (parse_tree_gently(tree, revs->ignore_missing_links) < 0) {\n\t\tif (revs->ignore_missing_links)\n\t\t\treturn;\n\t\tdie(\"bad tree object %s\", oid_to_hex(&obj->oid));\n\t}\n\n\tobj->flags |= SEEN;\n\tshow(obj, base, name, cb_data);\n\n\tstrbuf_addstr(base, name);\n\tif (base->len)\n\t\tstrbuf_addch(base, '/');\n\n\tinit_tree_desc(&desc, tree->buffer, tree->size);\n\n\twhile (tree_entry(&desc, &entry)) {\n\t\tif (match != all_entries_interesting) {\n\t\t\tmatch = tree_entry_interesting(&entry, base, 0,\n\t\t\t\t\t\t &revs->diffopt.pathspec);\n\t\t\tif (match == all_entries_not_interesting)\n\t\t\t\tbreak;\n\t\t\tif (match == entry_not_interesting)\n\t\t\t\tcontinue;\n\t\t}\n\n\t\tif (S_ISDIR(entry.mode))\n\t\t\tprocess_tree(revs,\n\t\t\t\t lookup_tree(entry.sha1),\n\t\t\t\t show, base, entry.path,\n\t\t\t\t cb_data);\n\t\telse if (S_ISGITLINK(entry.mode))\n\t\t\tprocess_gitlink(revs, entry.sha1,\n\t\t\t\t\tshow, base, entry.path,\n\t\t\t\t\tcb_data);\n\t\telse\n\t\t\tprocess_blob(revs,\n\t\t\t\t lookup_blob(entry.sha1),\n\t\t\t\t show, base, entry.path,\n\t\t\t\t cb_data);\n\t}\n\tstrbuf_setlen(base, baselen);\n\tfree_tree_buffer(tree);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'list-objects: pass full pathname to callbacks\n\nWhen we find a blob at \"a/b/c\", we currently pass this to\nour show_object_fn callbacks as two components: \"a/b/\" and\n\"c\". Callbacks which want the full value then call\npath_name(), which concatenates the two. But this is an\ninefficient interface; the path is a strbuf, and we could\nsimply append \"c\" to it temporarily, then roll back the\nlength, without creating a new copy.\n\nSo we could improve this by teaching the callsites of\npath_name() this trick (and there are only 3). But we can\nalso notice that no callback actually cares about the\nbroken-down representation, and simply pass each callback\nthe full path \"a/b/c\" as a string. The callback code becomes\neven simpler, then, as we do not have to worry about freeing\nan allocated buffer, nor rolling back our modification to\nthe strbuf.\n\nThis is theoretically less efficient, as some callbacks\nwould not bother to format the final path component. But in\npractice this is not measurable. Since we use the same\nstrbuf over and over, our work to grow it is amortized, and\nwe really only pay to memcpy a few bytes.\n\nSigned-off-by: Jeff King \nSigned-off-by: Junio C Hamano '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static long vfio_pci_ioctl(void *device_data,\n\t\t\t unsigned int cmd, unsigned long arg)\n{\n\tstruct vfio_pci_device *vdev = device_data;\n\tunsigned long minsz;\n\n\tif (cmd == VFIO_DEVICE_GET_INFO) {\n\t\tstruct vfio_device_info info;\n\n\t\tminsz = offsetofend(struct vfio_device_info, num_irqs);\n\n\t\tif (copy_from_user(&info, (void __user *)arg, minsz))\n\t\t\treturn -EFAULT;\n\n\t\tif (info.argsz < minsz)\n\t\t\treturn -EINVAL;\n\n\t\tinfo.flags = VFIO_DEVICE_FLAGS_PCI;\n\n\t\tif (vdev->reset_works)\n\t\t\tinfo.flags |= VFIO_DEVICE_FLAGS_RESET;\n\n\t\tinfo.num_regions = VFIO_PCI_NUM_REGIONS + vdev->num_regions;\n\t\tinfo.num_irqs = VFIO_PCI_NUM_IRQS;\n\n\t\treturn copy_to_user((void __user *)arg, &info, minsz) ?\n\t\t\t-EFAULT : 0;\n\n\t} else if (cmd == VFIO_DEVICE_GET_REGION_INFO) {\n\t\tstruct pci_dev *pdev = vdev->pdev;\n\t\tstruct vfio_region_info info;\n\t\tstruct vfio_info_cap caps = { .buf = NULL, .size = 0 };\n\t\tint i, ret;\n\n\t\tminsz = offsetofend(struct vfio_region_info, offset);\n\n\t\tif (copy_from_user(&info, (void __user *)arg, minsz))\n\t\t\treturn -EFAULT;\n\n\t\tif (info.argsz < minsz)\n\t\t\treturn -EINVAL;\n\n\t\tswitch (info.index) {\n\t\tcase VFIO_PCI_CONFIG_REGION_INDEX:\n\t\t\tinfo.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);\n\t\t\tinfo.size = pdev->cfg_size;\n\t\t\tinfo.flags = VFIO_REGION_INFO_FLAG_READ |\n\t\t\t\t VFIO_REGION_INFO_FLAG_WRITE;\n\t\t\tbreak;\n\t\tcase VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX:\n\t\t\tinfo.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);\n\t\t\tinfo.size = pci_resource_len(pdev, info.index);\n\t\t\tif (!info.size) {\n\t\t\t\tinfo.flags = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tinfo.flags = VFIO_REGION_INFO_FLAG_READ |\n\t\t\t\t VFIO_REGION_INFO_FLAG_WRITE;\n\t\t\tif (vdev->bar_mmap_supported[info.index]) {\n\t\t\t\tinfo.flags |= VFIO_REGION_INFO_FLAG_MMAP;\n\t\t\t\tif (info.index == vdev->msix_bar) {\n\t\t\t\t\tret = msix_sparse_mmap_cap(vdev, &caps);\n\t\t\t\t\tif (ret)\n\t\t\t\t\t\treturn ret;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbreak;\n\t\tcase VFIO_PCI_ROM_REGION_INDEX:\n\t\t{\n\t\t\tvoid __iomem *io;\n\t\t\tsize_t size;\n\n\t\t\tinfo.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);\n\t\t\tinfo.flags = 0;\n\n\t\t\t/* Report the BAR size, not the ROM size */\n\t\t\tinfo.size = pci_resource_len(pdev, info.index);\n\t\t\tif (!info.size) {\n\t\t\t\t/* Shadow ROMs appear as PCI option ROMs */\n\t\t\t\tif (pdev->resource[PCI_ROM_RESOURCE].flags &\n\t\t\t\t\t\t\tIORESOURCE_ROM_SHADOW)\n\t\t\t\t\tinfo.size = 0x20000;\n\t\t\t\telse\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t/* Is it really there? */\n\t\t\tio = pci_map_rom(pdev, &size);\n\t\t\tif (!io || !size) {\n\t\t\t\tinfo.size = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tpci_unmap_rom(pdev, io);\n\n\t\t\tinfo.flags = VFIO_REGION_INFO_FLAG_READ;\n\t\t\tbreak;\n\t\t}\n\t\tcase VFIO_PCI_VGA_REGION_INDEX:\n\t\t\tif (!vdev->has_vga)\n\t\t\t\treturn -EINVAL;\n\n\t\t\tinfo.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);\n\t\t\tinfo.size = 0xc0000;\n\t\t\tinfo.flags = VFIO_REGION_INFO_FLAG_READ |\n\t\t\t\t VFIO_REGION_INFO_FLAG_WRITE;\n\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (info.index >=\n\t\t\t VFIO_PCI_NUM_REGIONS + vdev->num_regions)\n\t\t\t\treturn -EINVAL;\n\n\t\t\ti = info.index - VFIO_PCI_NUM_REGIONS;\n\n\t\t\tinfo.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);\n\t\t\tinfo.size = vdev->region[i].size;\n\t\t\tinfo.flags = vdev->region[i].flags;\n\n\t\t\tret = region_type_cap(vdev, &caps,\n\t\t\t\t\t vdev->region[i].type,\n\t\t\t\t\t vdev->region[i].subtype);\n\t\t\tif (ret)\n\t\t\t\treturn ret;\n\t\t}\n\n\t\tif (caps.size) {\n\t\t\tinfo.flags |= VFIO_REGION_INFO_FLAG_CAPS;\n\t\t\tif (info.argsz < sizeof(info) + caps.size) {\n\t\t\t\tinfo.argsz = sizeof(info) + caps.size;\n\t\t\t\tinfo.cap_offset = 0;\n\t\t\t} else {\n\t\t\t\tvfio_info_cap_shift(&caps, sizeof(info));\n\t\t\t\tif (copy_to_user((void __user *)arg +\n\t\t\t\t\t\t sizeof(info), caps.buf,\n\t\t\t\t\t\t caps.size)) {\n\t\t\t\t\tkfree(caps.buf);\n\t\t\t\t\treturn -EFAULT;\n\t\t\t\t}\n\t\t\t\tinfo.cap_offset = sizeof(info);\n\t\t\t}\n\n\t\t\tkfree(caps.buf);\n\t\t}\n\n\t\treturn copy_to_user((void __user *)arg, &info, minsz) ?\n\t\t\t-EFAULT : 0;\n\n\t} else if (cmd == VFIO_DEVICE_GET_IRQ_INFO) {\n\t\tstruct vfio_irq_info info;\n\n\t\tminsz = offsetofend(struct vfio_irq_info, count);\n\n\t\tif (copy_from_user(&info, (void __user *)arg, minsz))\n\t\t\treturn -EFAULT;\n\n\t\tif (info.argsz < minsz || info.index >= VFIO_PCI_NUM_IRQS)\n\t\t\treturn -EINVAL;\n\n\t\tswitch (info.index) {\n\t\tcase VFIO_PCI_INTX_IRQ_INDEX ... VFIO_PCI_MSIX_IRQ_INDEX:\n\t\tcase VFIO_PCI_REQ_IRQ_INDEX:\n\t\t\tbreak;\n\t\tcase VFIO_PCI_ERR_IRQ_INDEX:\n\t\t\tif (pci_is_pcie(vdev->pdev))\n\t\t\t\tbreak;\n\t\t/* pass thru to return error */\n\t\tdefault:\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t\tinfo.flags = VFIO_IRQ_INFO_EVENTFD;\n\n\t\tinfo.count = vfio_pci_get_irq_count(vdev, info.index);\n\n\t\tif (info.index == VFIO_PCI_INTX_IRQ_INDEX)\n\t\t\tinfo.flags |= (VFIO_IRQ_INFO_MASKABLE |\n\t\t\t\t VFIO_IRQ_INFO_AUTOMASKED);\n\t\telse\n\t\t\tinfo.flags |= VFIO_IRQ_INFO_NORESIZE;\n\n\t\treturn copy_to_user((void __user *)arg, &info, minsz) ?\n\t\t\t-EFAULT : 0;\n\n\t} else if (cmd == VFIO_DEVICE_SET_IRQS) {\n\t\tstruct vfio_irq_set hdr;\n\t\tu8 *data = NULL;\n\t\tint ret = 0;\n\n\t\tminsz = offsetofend(struct vfio_irq_set, count);\n\n\t\tif (copy_from_user(&hdr, (void __user *)arg, minsz))\n\t\t\treturn -EFAULT;\n\n\t\tif (hdr.argsz < minsz || hdr.index >= VFIO_PCI_NUM_IRQS ||\n\t\t hdr.flags & ~(VFIO_IRQ_SET_DATA_TYPE_MASK |\n\t\t\t\t VFIO_IRQ_SET_ACTION_TYPE_MASK))\n\t\t\treturn -EINVAL;\n\n\t\tif (!(hdr.flags & VFIO_IRQ_SET_DATA_NONE)) {\n\t\t\tsize_t size;\n\t\t\tint max = vfio_pci_get_irq_count(vdev, hdr.index);\n\n\t\t\tif (hdr.flags & VFIO_IRQ_SET_DATA_BOOL)\n\t\t\t\tsize = sizeof(uint8_t);\n\t\t\telse if (hdr.flags & VFIO_IRQ_SET_DATA_EVENTFD)\n\t\t\t\tsize = sizeof(int32_t);\n\t\t\telse\n\t\t\t\treturn -EINVAL;\n\n\t\t\tif (hdr.argsz - minsz < hdr.count * size ||\n\t\t\t hdr.start >= max || hdr.start + hdr.count > max)\n\t\t\t\treturn -EINVAL;\n\n\t\t\tdata = memdup_user((void __user *)(arg + minsz),\n\t\t\t\t\t hdr.count * size);\n\t\t\tif (IS_ERR(data))\n\t\t\t\treturn PTR_ERR(data);\n\t\t}\n\n\t\tmutex_lock(&vdev->igate);\n\n\t\tret = vfio_pci_set_irqs_ioctl(vdev, hdr.flags, hdr.index,\n\t\t\t\t\t hdr.start, hdr.count, data);\n\n\t\tmutex_unlock(&vdev->igate);\n\t\tkfree(data);\n\n\t\treturn ret;\n\n\t} else if (cmd == VFIO_DEVICE_RESET) {\n\t\treturn vdev->reset_works ?\n\t\t\tpci_try_reset_function(vdev->pdev) : -EINVAL;\n\n\t} else if (cmd == VFIO_DEVICE_GET_PCI_HOT_RESET_INFO) {\n\t\tstruct vfio_pci_hot_reset_info hdr;\n\t\tstruct vfio_pci_fill_info fill = { 0 };\n\t\tstruct vfio_pci_dependent_device *devices = NULL;\n\t\tbool slot = false;\n\t\tint ret = 0;\n\n\t\tminsz = offsetofend(struct vfio_pci_hot_reset_info, count);\n\n\t\tif (copy_from_user(&hdr, (void __user *)arg, minsz))\n\t\t\treturn -EFAULT;\n\n\t\tif (hdr.argsz < minsz)\n\t\t\treturn -EINVAL;\n\n\t\thdr.flags = 0;\n\n\t\t/* Can we do a slot or bus reset or neither? */\n\t\tif (!pci_probe_reset_slot(vdev->pdev->slot))\n\t\t\tslot = true;\n\t\telse if (pci_probe_reset_bus(vdev->pdev->bus))\n\t\t\treturn -ENODEV;\n\n\t\t/* How many devices are affected? */\n\t\tret = vfio_pci_for_each_slot_or_bus(vdev->pdev,\n\t\t\t\t\t\t vfio_pci_count_devs,\n\t\t\t\t\t\t &fill.max, slot);\n\t\tif (ret)\n\t\t\treturn ret;\n\n\t\tWARN_ON(!fill.max); /* Should always be at least one */\n\n\t\t/*\n\t\t * If there's enough space, fill it now, otherwise return\n\t\t * -ENOSPC and the number of devices affected.\n\t\t */\n\t\tif (hdr.argsz < sizeof(hdr) + (fill.max * sizeof(*devices))) {\n\t\t\tret = -ENOSPC;\n\t\t\thdr.count = fill.max;\n\t\t\tgoto reset_info_exit;\n\t\t}\n\n\t\tdevices = kcalloc(fill.max, sizeof(*devices), GFP_KERNEL);\n\t\tif (!devices)\n\t\t\treturn -ENOMEM;\n\n\t\tfill.devices = devices;\n\n\t\tret = vfio_pci_for_each_slot_or_bus(vdev->pdev,\n\t\t\t\t\t\t vfio_pci_fill_devs,\n\t\t\t\t\t\t &fill, slot);\n\n\t\t/*\n\t\t * If a device was removed between counting and filling,\n\t\t * we may come up short of fill.max. If a device was\n\t\t * added, we'll have a return of -EAGAIN above.\n\t\t */\n\t\tif (!ret)\n\t\t\thdr.count = fill.cur;\n\nreset_info_exit:\n\t\tif (copy_to_user((void __user *)arg, &hdr, minsz))\n\t\t\tret = -EFAULT;\n\n\t\tif (!ret) {\n\t\t\tif (copy_to_user((void __user *)(arg + minsz), devices,\n\t\t\t\t\t hdr.count * sizeof(*devices)))\n\t\t\t\tret = -EFAULT;\n\t\t}\n\n\t\tkfree(devices);\n\t\treturn ret;\n\n\t} else if (cmd == VFIO_DEVICE_PCI_HOT_RESET) {\n\t\tstruct vfio_pci_hot_reset hdr;\n\t\tint32_t *group_fds;\n\t\tstruct vfio_pci_group_entry *groups;\n\t\tstruct vfio_pci_group_info info;\n\t\tbool slot = false;\n\t\tint i, count = 0, ret = 0;\n\n\t\tminsz = offsetofend(struct vfio_pci_hot_reset, count);\n\n\t\tif (copy_from_user(&hdr, (void __user *)arg, minsz))\n\t\t\treturn -EFAULT;\n\n\t\tif (hdr.argsz < minsz || hdr.flags)\n\t\t\treturn -EINVAL;\n\n\t\t/* Can we do a slot or bus reset or neither? */\n\t\tif (!pci_probe_reset_slot(vdev->pdev->slot))\n\t\t\tslot = true;\n\t\telse if (pci_probe_reset_bus(vdev->pdev->bus))\n\t\t\treturn -ENODEV;\n\n\t\t/*\n\t\t * We can't let userspace give us an arbitrarily large\n\t\t * buffer to copy, so verify how many we think there\n\t\t * could be. Note groups can have multiple devices so\n\t\t * one group per device is the max.\n\t\t */\n\t\tret = vfio_pci_for_each_slot_or_bus(vdev->pdev,\n\t\t\t\t\t\t vfio_pci_count_devs,\n\t\t\t\t\t\t &count, slot);\n\t\tif (ret)\n\t\t\treturn ret;\n\n\t\t/* Somewhere between 1 and count is OK */\n\t\tif (!hdr.count || hdr.count > count)\n\t\t\treturn -EINVAL;\n\n\t\tgroup_fds = kcalloc(hdr.count, sizeof(*group_fds), GFP_KERNEL);\n\t\tgroups = kcalloc(hdr.count, sizeof(*groups), GFP_KERNEL);\n\t\tif (!group_fds || !groups) {\n\t\t\tkfree(group_fds);\n\t\t\tkfree(groups);\n\t\t\treturn -ENOMEM;\n\t\t}\n\n\t\tif (copy_from_user(group_fds, (void __user *)(arg + minsz),\n\t\t\t\t hdr.count * sizeof(*group_fds))) {\n\t\t\tkfree(group_fds);\n\t\t\tkfree(groups);\n\t\t\treturn -EFAULT;\n\t\t}\n\n\t\t/*\n\t\t * For each group_fd, get the group through the vfio external\n\t\t * user interface and store the group and iommu ID. This\n\t\t * ensures the group is held across the reset.\n\t\t */\n\t\tfor (i = 0; i < hdr.count; i++) {\n\t\t\tstruct vfio_group *group;\n\t\t\tstruct fd f = fdget(group_fds[i]);\n\t\t\tif (!f.file) {\n\t\t\t\tret = -EBADF;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tgroup = vfio_group_get_external_user(f.file);\n\t\t\tfdput(f);\n\t\t\tif (IS_ERR(group)) {\n\t\t\t\tret = PTR_ERR(group);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tgroups[i].group = group;\n\t\t\tgroups[i].id = vfio_external_user_iommu_id(group);\n\t\t}\n\n\t\tkfree(group_fds);\n\n\t\t/* release reference to groups on error */\n\t\tif (ret)\n\t\t\tgoto hot_reset_release;\n\n\t\tinfo.count = hdr.count;\n\t\tinfo.groups = groups;\n\n\t\t/*\n\t\t * Test whether all the affected devices are contained\n\t\t * by the set of groups provided by the user.\n\t\t */\n\t\tret = vfio_pci_for_each_slot_or_bus(vdev->pdev,\n\t\t\t\t\t\t vfio_pci_validate_devs,\n\t\t\t\t\t\t &info, slot);\n\t\tif (!ret)\n\t\t\t/* User has access, do the reset */\n\t\t\tret = slot ? pci_try_reset_slot(vdev->pdev->slot) :\n\t\t\t\t pci_try_reset_bus(vdev->pdev->bus);\n\nhot_reset_release:\n\t\tfor (i--; i >= 0; i--)\n\t\t\tvfio_group_put_external_user(groups[i].group);\n\n\t\tkfree(groups);\n\t\treturn ret;\n\t}\n\n\treturn -ENOTTY;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-190'], 'message': 'vfio/pci: Fix integer overflows, bitmask check\n\nThe VFIO_DEVICE_SET_IRQS ioctl did not sufficiently sanitize\nuser-supplied integers, potentially allowing memory corruption. This\npatch adds appropriate integer overflow checks, checks the range bounds\nfor VFIO_IRQ_SET_DATA_NONE, and also verifies that only single element\nin the VFIO_IRQ_SET_DATA_TYPE_MASK bitmask is set.\nVFIO_IRQ_SET_ACTION_TYPE_MASK is already correctly checked later in\nvfio_pci_set_irqs_ioctl().\n\nFurthermore, a kzalloc is changed to a kcalloc because the use of a\nkzalloc with an integer multiplication allowed an integer overflow\ncondition to be reached without this patch. kcalloc checks for overflow\nand should prevent a similar occurrence.\n\nSigned-off-by: Vlad Tsyrklevich \nSigned-off-by: Alex Williamson '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: struct l2tp_packet_t *l2tp_packet_alloc(int ver, int msg_type,\n\t\t\t\t\tconst struct sockaddr_in *addr, int H,\n\t\t\t\t\tconst char *secret, size_t secret_len)\n{\n\tstruct l2tp_packet_t *pack = mempool_alloc(pack_pool);\n\tif (!pack)\n\t\treturn NULL;\n\n\tmemset(pack, 0, sizeof(*pack));\n\tINIT_LIST_HEAD(&pack->attrs);\n\tpack->hdr.ver = ver;\n\tpack->hdr.T = 1;\n\tpack->hdr.L = 1;\n\tpack->hdr.S = 1;\n\tmemcpy(&pack->addr, addr, sizeof(*addr));\n\tpack->hide_avps = H;\n\tpack->secret = secret;\n\tpack->secret_len = secret_len;\n\n\tif (msg_type) {\n\t\tif (l2tp_packet_add_int16(pack, Message_Type, msg_type, 1)) {\n\t\t\tmempool_free(pack);\n\t\t\treturn NULL;\n\t\t}\n\t}\n\n\treturn pack;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-125', 'CWE-120'], 'message': 'l2tp: fix RCE through buffer overflow & fix LE/BE compatibility\n\nUnsufficent checks of valid l2tp header & avp length cause possible\nRCE through buffer overflow, reported by https://github.com/WinMin\nswings & leommxj, Chaitin Security Research Lab. Add missed header\nlength and avp length validation to fix the issue.\n\nOrder of struct bitfields is implementation-defined so current code\ndoesn't play well with big-endian arch. switch to explicit flag bit\nchecking/gathering to fix the issue.\n\nRFC 2661 and 3931 requires that length, seqeuence flags must be set\nand offset flag must not be set, so avp-premissive can't help in\nthis cases.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: PHPAPI int php_swoole_unserialize(void *buffer, size_t len, zval *return_value, zval *object_args, long flag)\n{\n SBucketType type = *(SBucketType*) (buffer);\n zend_uchar real_type = type.data_type;\n buffer += sizeof (SBucketType);\n switch (real_type)\n {\n case IS_NULL:\n case IS_TRUE:\n case IS_FALSE:\n Z_TYPE_INFO_P(return_value) = real_type;\n break;\n case IS_LONG:\n swoole_unserialize_long(buffer, return_value, type);\n Z_TYPE_INFO_P(return_value) = real_type;\n break;\n case IS_DOUBLE:\n swoole_unserialize_raw(buffer, return_value);\n Z_TYPE_INFO_P(return_value) = real_type;\n break;\n case IS_STRING:\n len -= sizeof (SBucketType);\n zend_string *str = swoole_unserialize_string(buffer, len);\n ZVAL_STR(return_value, str);\n break;\n case IS_ARRAY:\n {\n if (swoole_seria_check_eof(buffer, len) < 0)\n {\n php_error_docref(NULL TSRMLS_CC, E_NOTICE, \"detect the error eof\");\n return SW_FALSE;\n }\n unser_start = buffer - sizeof (SBucketType);\n uint32_t num = 0;\n buffer = get_array_real_len(buffer, type.data_len, &num);\n if (!swoole_unserialize_arr(buffer, return_value, num, flag))\n {\n return SW_FALSE;\n }\n break;\n }\n case IS_UNDEF:\n if (swoole_seria_check_eof(buffer, len) < 0)\n {\n php_error_docref(NULL TSRMLS_CC, E_NOTICE, \"detect the error eof\");\n return SW_FALSE;\n }\n unser_start = buffer - sizeof (SBucketType);\n if (!swoole_unserialize_object(buffer, return_value, type.data_len, object_args, flag))\n {\n return SW_FALSE;\n }\n break;\n default:\n php_error_docref(NULL TSRMLS_CC, E_NOTICE, \"the type is not supported by swoole serialize.\");\n return SW_FALSE;\n }\n\n return SW_TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-502'], 'message': 'add buffer end check'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: esis_print(netdissect_options *ndo,\n const uint8_t *pptr, u_int length)\n{\n\tconst uint8_t *optr;\n\tu_int li,esis_pdu_type,source_address_length, source_address_number;\n\tconst struct esis_header_t *esis_header;\n\n\tif (!ndo->ndo_eflag)\n\t\tND_PRINT((ndo, \"ES-IS\"));\n\n\tif (length <= 2) {\n\t\tND_PRINT((ndo, ndo->ndo_qflag ? \"bad pkt!\" : \"no header at all!\"));\n\t\treturn;\n\t}\n\n\tesis_header = (const struct esis_header_t *) pptr;\n ND_TCHECK(*esis_header);\n li = esis_header->length_indicator;\n optr = pptr;\n\n /*\n * Sanity checking of the header.\n */\n\n if (esis_header->nlpid != NLPID_ESIS) {\n ND_PRINT((ndo, \" nlpid 0x%02x packet not supported\", esis_header->nlpid));\n return;\n }\n\n if (esis_header->version != ESIS_VERSION) {\n ND_PRINT((ndo, \" version %d packet not supported\", esis_header->version));\n return;\n }\n\n\tif (li > length) {\n ND_PRINT((ndo, \" length indicator(%u) > PDU size (%u)!\", li, length));\n return;\n\t}\n\n\tif (li < sizeof(struct esis_header_t) + 2) {\n ND_PRINT((ndo, \" length indicator %u < min PDU size:\", li));\n while (pptr < ndo->ndo_snapend)\n ND_PRINT((ndo, \"%02X\", *pptr++));\n return;\n\t}\n\n esis_pdu_type = esis_header->type & ESIS_PDU_TYPE_MASK;\n\n if (ndo->ndo_vflag < 1) {\n ND_PRINT((ndo, \"%s%s, length %u\",\n ndo->ndo_eflag ? \"\" : \", \",\n tok2str(esis_pdu_values,\"unknown type (%u)\",esis_pdu_type),\n length));\n return;\n } else\n ND_PRINT((ndo, \"%slength %u\\n\\t%s (%u)\",\n ndo->ndo_eflag ? \"\" : \", \",\n length,\n tok2str(esis_pdu_values,\"unknown type: %u\", esis_pdu_type),\n esis_pdu_type));\n\n ND_PRINT((ndo, \", v: %u%s\", esis_header->version, esis_header->version == ESIS_VERSION ? \"\" : \"unsupported\" ));\n ND_PRINT((ndo, \", checksum: 0x%04x\", EXTRACT_16BITS(esis_header->cksum)));\n\n osi_print_cksum(ndo, pptr, EXTRACT_16BITS(esis_header->cksum), 7, li);\n\n ND_PRINT((ndo, \", holding time: %us, length indicator: %u\",\n EXTRACT_16BITS(esis_header->holdtime), li));\n\n if (ndo->ndo_vflag > 1)\n print_unknown_data(ndo, optr, \"\\n\\t\", sizeof(struct esis_header_t));\n\n\tpptr += sizeof(struct esis_header_t);\n\tli -= sizeof(struct esis_header_t);\n\n\tswitch (esis_pdu_type) {\n\tcase ESIS_PDU_REDIRECT: {\n\t\tconst uint8_t *dst, *snpa, *neta;\n\t\tu_int dstl, snpal, netal;\n\n\t\tND_TCHECK(*pptr);\n\t\tif (li < 1) {\n\t\t\tND_PRINT((ndo, \", bad redirect/li\"));\n\t\t\treturn;\n\t\t}\n\t\tdstl = *pptr;\n\t\tpptr++;\n\t\tli--;\n\t\tND_TCHECK2(*pptr, dstl);\n\t\tif (li < dstl) {\n\t\t\tND_PRINT((ndo, \", bad redirect/li\"));\n\t\t\treturn;\n\t\t}\n\t\tdst = pptr;\n\t\tpptr += dstl;\n li -= dstl;\n\t\tND_PRINT((ndo, \"\\n\\t %s\", isonsap_string(ndo, dst, dstl)));\n\n\t\tND_TCHECK(*pptr);\n\t\tif (li < 1) {\n\t\t\tND_PRINT((ndo, \", bad redirect/li\"));\n\t\t\treturn;\n\t\t}\n\t\tsnpal = *pptr;\n\t\tpptr++;\n\t\tli--;\n\t\tND_TCHECK2(*pptr, snpal);\n\t\tif (li < snpal) {\n\t\t\tND_PRINT((ndo, \", bad redirect/li\"));\n\t\t\treturn;\n\t\t}\n\t\tsnpa = pptr;\n\t\tpptr += snpal;\n li -= snpal;\n\t\tND_TCHECK(*pptr);\n\t\tif (li < 1) {\n\t\t\tND_PRINT((ndo, \", bad redirect/li\"));\n\t\t\treturn;\n\t\t}\n\t\tnetal = *pptr;\n\t\tpptr++;\n\t\tND_TCHECK2(*pptr, netal);\n\t\tif (li < netal) {\n\t\t\tND_PRINT((ndo, \", bad redirect/li\"));\n\t\t\treturn;\n\t\t}\n\t\tneta = pptr;\n\t\tpptr += netal;\n li -= netal;\n\n\t\tif (netal == 0)\n\t\t\tND_PRINT((ndo, \"\\n\\t %s\", etheraddr_string(ndo, snpa)));\n\t\telse\n\t\t\tND_PRINT((ndo, \"\\n\\t %s\", isonsap_string(ndo, neta, netal)));\n\t\tbreak;\n\t}\n\n\tcase ESIS_PDU_ESH:\n ND_TCHECK(*pptr);\n if (li < 1) {\n ND_PRINT((ndo, \", bad esh/li\"));\n return;\n }\n source_address_number = *pptr;\n pptr++;\n li--;\n\n ND_PRINT((ndo, \"\\n\\t Number of Source Addresses: %u\", source_address_number));\n\n while (source_address_number > 0) {\n ND_TCHECK(*pptr);\n \tif (li < 1) {\n ND_PRINT((ndo, \", bad esh/li\"));\n \t return;\n \t}\n source_address_length = *pptr;\n pptr++;\n \tli--;\n\n ND_TCHECK2(*pptr, source_address_length);\n \tif (li < source_address_length) {\n ND_PRINT((ndo, \", bad esh/li\"));\n \t return;\n \t}\n ND_PRINT((ndo, \"\\n\\t NET (length: %u): %s\",\n source_address_length,\n isonsap_string(ndo, pptr, source_address_length)));\n pptr += source_address_length;\n li -= source_address_length;\n source_address_number--;\n }\n\n break;\n\n\tcase ESIS_PDU_ISH: {\n ND_TCHECK(*pptr);\n if (li < 1) {\n ND_PRINT((ndo, \", bad ish/li\"));\n return;\n }\n source_address_length = *pptr;\n pptr++;\n li--;\n ND_TCHECK2(*pptr, source_address_length);\n if (li < source_address_length) {\n ND_PRINT((ndo, \", bad ish/li\"));\n return;\n }\n ND_PRINT((ndo, \"\\n\\t NET (length: %u): %s\", source_address_length, isonsap_string(ndo, pptr, source_address_length)));\n pptr += source_address_length;\n li -= source_address_length;\n break;\n\t}\n\n\tdefault:\n\t\tif (ndo->ndo_vflag <= 1) {\n\t\t\tif (pptr < ndo->ndo_snapend)\n\t\t\t\tprint_unknown_data(ndo, pptr, \"\\n\\t \", ndo->ndo_snapend - pptr);\n\t\t}\n\t\treturn;\n\t}\n\n /* now walk the options */\n while (li != 0) {\n u_int op, opli;\n const uint8_t *tptr;\n\n if (li < 2) {\n ND_PRINT((ndo, \", bad opts/li\"));\n return;\n }\n ND_TCHECK2(*pptr, 2);\n op = *pptr++;\n opli = *pptr++;\n li -= 2;\n if (opli > li) {\n ND_PRINT((ndo, \", opt (%d) too long\", op));\n return;\n }\n li -= opli;\n tptr = pptr;\n\n ND_PRINT((ndo, \"\\n\\t %s Option #%u, length %u, value: \",\n tok2str(esis_option_values,\"Unknown\",op),\n op,\n opli));\n\n switch (op) {\n\n case ESIS_OPTION_ES_CONF_TIME:\n if (opli == 2) {\n ND_TCHECK2(*pptr, 2);\n ND_PRINT((ndo, \"%us\", EXTRACT_16BITS(tptr)));\n } else\n ND_PRINT((ndo, \"(bad length)\"));\n break;\n\n case ESIS_OPTION_PROTOCOLS:\n while (opli>0) {\n ND_TCHECK(*pptr);\n ND_PRINT((ndo, \"%s (0x%02x)\",\n tok2str(nlpid_values,\n \"unknown\",\n *tptr),\n *tptr));\n if (opli>1) /* further NPLIDs ? - put comma */\n ND_PRINT((ndo, \", \"));\n tptr++;\n opli--;\n }\n break;\n\n /*\n * FIXME those are the defined Options that lack a decoder\n * you are welcome to contribute code ;-)\n */\n\n case ESIS_OPTION_QOS_MAINTENANCE:\n case ESIS_OPTION_SECURITY:\n case ESIS_OPTION_PRIORITY:\n case ESIS_OPTION_ADDRESS_MASK:\n case ESIS_OPTION_SNPA_MASK:\n\n default:\n print_unknown_data(ndo, tptr, \"\\n\\t \", opli);\n break;\n }\n if (ndo->ndo_vflag > 1)\n print_unknown_data(ndo, pptr, \"\\n\\t \", opli);\n pptr += opli;\n }\ntrunc:\n\treturn;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13016/ES-IS: Fix printing of addresses in RD PDUs.\n\nAlways print the SNPA, and flag it as such; only print it as a MAC\naddress if it's 6 bytes long.\n\nIdentify the NET as such.\n\nThis fixes a buffer over-read discovered by Bhargava Shastry,\nSecT/TU Berlin.\n\nAdd tests using the capture files supplied by the reporter(s), modified\nso the capture files won't be rejected as an invalid capture.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int f2fs_read_data_page(struct file *file, struct page *page)\n{\n\tstruct inode *inode = page->mapping->host;\n\tint ret = -EAGAIN;\n\n\ttrace_f2fs_readpage(page, DATA);\n\n\t/* If the file has inline data, try to read it directly */\n\tif (f2fs_has_inline_data(inode))\n\t\tret = f2fs_read_inline_data(inode, page);\n\tif (ret == -EAGAIN)\n\t\tret = f2fs_mpage_readpages(page->mapping, NULL, page, 1, false);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'f2fs: support swap file w/ DIO\n\nSigned-off-by: Jaegeuk Kim '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int fuse_kern_mount(const char *mountpoint, struct fuse_args *args)\n{\n struct mount_opts mo;\n int res = -1;\n char *mnt_opts = NULL;\n#ifdef __SOLARIS__\n struct solaris_mount_opts smo;\n struct fuse_args sa = FUSE_ARGS_INIT(0, NULL);\n#endif /* __SOLARIS__ */\n\n memset(&mo, 0, sizeof(mo));\n#ifndef __SOLARIS__\n if (getuid())\n\t mo.flags = MS_NOSUID | MS_NODEV;\n#else /* __SOLARIS__ */\n mo.flags = 0;\n memset(&smo, 0, sizeof(smo));\n if (args != NULL) {\n \twhile (args->argv[sa.argc] != NULL)\n\t\tfuse_opt_add_arg(&sa, args->argv[sa.argc]);\n }\n#endif /* __SOLARIS__ */\n\n if (args &&\n fuse_opt_parse(args, &mo, fuse_mount_opts, fuse_mount_opt_proc) == -1)\n#ifndef __SOLARIS__\n return -1;\n#else /* __SOLARIS__ */\n goto out; /* if SOLARIS, clean up 'sa' */\n\n /*\n * In Solaris, nosuid is equivalent to nosetuid + nodevices. We only\n * have MS_NOSUID for mount flags (no MS_(NO)SETUID, etc.). But if\n * we set that as a default, it restricts specifying just nosetuid\n * or nodevices; there is no way for the user to specify setuid +\n * nodevices or vice-verse. So we parse the existing options, then\n * add restrictive defaults if needed.\n */\n if (fuse_opt_parse(&sa, &smo, solaris_mnt_opts, NULL) == -1)\n goto out;\n if (smo.nosuid || (!smo.nodevices && !smo.devices\n && !smo.nosetuid && !smo.setuid)) {\n mo.flags |= MS_NOSUID;\n } else {\n /*\n * Defaults; if neither nodevices|devices,nosetuid|setuid has\n * been specified, add the default negative option string. If\n * both have been specified (i.e., -osuid,nosuid), leave them\n * alone; the last option will have precedence.\n */\n if (!smo.nodevices && !smo.devices)\n if (fuse_opt_add_opt(&mo.kernel_opts, \"nodevices\") == -1)\n goto out;\n if (!smo.nosetuid && !smo.setuid)\n if (fuse_opt_add_opt(&mo.kernel_opts, \"nosetuid\") == -1)\n goto out;\n }\n#endif /* __SOLARIS__ */\n\n if (mo.allow_other && mo.allow_root) {\n fprintf(stderr, \"fuse: 'allow_other' and 'allow_root' options are mutually exclusive\\n\");\n goto out;\n }\n res = 0;\n if (mo.ishelp)\n goto out;\n\n res = -1;\n if (get_mnt_flag_opts(&mnt_opts, mo.flags) == -1)\n goto out;\n#ifndef __SOLARIS__\n if (!(mo.flags & MS_NODEV) && fuse_opt_add_opt(&mnt_opts, \"dev\") == -1)\n goto out;\n if (!(mo.flags & MS_NOSUID) && fuse_opt_add_opt(&mnt_opts, \"suid\") == -1)\n goto out;\n if (mo.kernel_opts && fuse_opt_add_opt(&mnt_opts, mo.kernel_opts) == -1)\n goto out;\n if (mo.mtab_opts && fuse_opt_add_opt(&mnt_opts, mo.mtab_opts) == -1)\n goto out;\n if (mo.fusermount_opts && fuse_opt_add_opt(&mnt_opts, mo.fusermount_opts) < 0)\n goto out;\n res = fusermount(0, 0, 0, mnt_opts ? mnt_opts : \"\", mountpoint);\n#else /* __SOLARIS__ */\n if (mo.kernel_opts && fuse_opt_add_opt(&mnt_opts, mo.kernel_opts) == -1)\n goto out;\n if (mo.mtab_opts && fuse_opt_add_opt(&mnt_opts, mo.mtab_opts) == -1)\n goto out;\n res = fuse_mount_sys(mountpoint, &mo, mnt_opts);\n if (res == -2) {\n if (mo.fusermount_opts &&\n fuse_opt_add_opt(&mnt_opts, mo.fusermount_opts) == -1)\n goto out;\n\n if (mo.subtype) {\n char *tmp_opts = NULL;\n\n res = -1;\n if (fuse_opt_add_opt(&tmp_opts, mnt_opts) == -1 ||\n fuse_opt_add_opt(&tmp_opts, mo.subtype_opt) == -1) {\n free(tmp_opts);\n goto out;\n }\n\n res = fuse_mount_fusermount(mountpoint, tmp_opts, 1);\n free(tmp_opts);\n if (res == -1)\n res = fuse_mount_fusermount(mountpoint, mnt_opts, 0);\n } else {\n res = fuse_mount_fusermount(mountpoint, mnt_opts, 0);\n }\n }\n#endif /* __SOLARIS__ */\n\nout:\n free(mnt_opts);\n#ifdef __SOLARIS__\n fuse_opt_free_args(&sa);\n free(mo.subtype);\n free(mo.subtype_opt);\n#endif /* __SOLARIS__ */\n free(mo.fsname);\n free(mo.fusermount_opts);\n free(mo.kernel_opts);\n free(mo.mtab_opts);\n return res;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Returned an error code when the --help or --version options are used\n\nAccepting --help or --version options may leave the ntfs-3g process in an\nunclean state, so reject them while processing options. Also reject\nthem in libfuse-lite.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: l2tp_ppp_discon_cc_print(netdissect_options *ndo, const u_char *dat, u_int length)\n{\n\tconst uint16_t *ptr = (const uint16_t *)dat;\n\n\tND_PRINT((ndo, \"%04x, \", EXTRACT_16BITS(ptr))); ptr++;\t/* Disconnect Code */\n\tND_PRINT((ndo, \"%04x \", EXTRACT_16BITS(ptr))); ptr++;\t/* Control Protocol Number */\n\tND_PRINT((ndo, \"%s\", tok2str(l2tp_cc_direction2str,\n\t\t\t \"Direction-#%u\", *((const u_char *)ptr++))));\n\n\tif (length > 5) {\n\t\tND_PRINT((ndo, \" \"));\n\t\tprint_string(ndo, (const u_char *)ptr, length-5);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length.\n\nIt's not good enough to check whether all the data specified by the AVP\nlength was captured - you also have to check whether that length is\nlarge enough for all the required data in the AVP.\n\nThis fixes a buffer over-read discovered by Yannick Formaggio.\n\nAdd a test using the capture file supplied by the reporter(s).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void gf_dump_vrml_proto_field(GF_SceneDumper *sdump, GF_Node *node, GF_FieldInfo field)\n{\n\tu32 i, sf_type;\n\tvoid *slot_ptr;\n\n\tDUMP_IND(sdump);\n\tgf_fprintf(sdump->trace, \"trace, \">\\n\");\n\t\t\tsdump->indent++;\n\t\t\tif (!sdump->X3DDump) gf_fprintf(sdump->trace, \"\");\n\t\t\tgf_dump_vrml_node(sdump, field.far_ptr ? *(GF_Node **)field.far_ptr : NULL, 0, NULL);\n\t\t\tif (!sdump->X3DDump) gf_fprintf(sdump->trace, \"\");\n\t\t\tsdump->indent--;\n\t\t\tDUMP_IND(sdump);\n\t\t\tgf_fprintf(sdump->trace, \"\\n\");\n\t\t} else {\n\t\t\tif (sdump->X3DDump) {\n\t\t\t\tgf_fprintf(sdump->trace, \" value=\\\"\");\n\t\t\t} else {\n\t\t\t\tgf_fprintf(sdump->trace, \" %s=\\\"\", GetXMTFieldTypeValueName(field.fieldType));\n\t\t\t}\n\t\t\tgf_dump_vrml_sffield(sdump, field.fieldType, field.far_ptr, 0, node);\n\t\t\tgf_fprintf(sdump->trace, \"\\\"/>\\n\");\n\t\t}\n\t} else {\n\t\tGenMFField *mffield = (GenMFField *) field.far_ptr;\n\t\tsf_type = gf_sg_vrml_get_sf_type(field.fieldType);\n\n\t\tif ((field.eventType==GF_SG_EVENT_FIELD) || (field.eventType==GF_SG_EVENT_EXPOSED_FIELD)) {\n\t\t\tif (sf_type == GF_SG_VRML_SFNODE) {\n\t\t\t\tGF_ChildNodeItem *list = *(GF_ChildNodeItem **)field.far_ptr;\n\t\t\t\tgf_fprintf(sdump->trace, \">\\n\");\n\t\t\t\tsdump->indent++;\n\t\t\t\tif (!sdump->X3DDump) gf_fprintf(sdump->trace, \"\");\n\t\t\t\twhile (list) {\n\t\t\t\t\tgf_dump_vrml_node(sdump, list->node, 1, NULL);\n\t\t\t\t\tlist = list->next;\n\t\t\t\t}\n\t\t\t\tif (!sdump->X3DDump) gf_fprintf(sdump->trace, \"\");\n\t\t\t\tsdump->indent--;\n\t\t\t\tDUMP_IND(sdump);\n\t\t\t\tgf_fprintf(sdump->trace, \"\\n\");\n\t\t\t} else {\n\t\t\t\tif (sdump->X3DDump) {\n\t\t\t\t\tgf_fprintf(sdump->trace, \" value=\\\"\");\n\t\t\t\t} else {\n\t\t\t\t\tgf_fprintf(sdump->trace, \" %s=\\\"\", GetXMTFieldTypeValueName(field.fieldType));\n\t\t\t\t}\n\t\t\t\tif (mffield) {\n\t\t\t\t\tfor (i=0; icount; i++) {\n\t\t\t\t\t\tif (i) gf_fprintf(sdump->trace, \" \");\n\t\t\t\t\t\tif (field.fieldType != GF_SG_VRML_MFNODE) {\n\t\t\t\t\t\t\tgf_sg_vrml_mf_get_item(field.far_ptr, field.fieldType, &slot_ptr, i);\n\t\t\t\t\t\t\tgf_dump_vrml_sffield(sdump, sf_type, slot_ptr, (mffield->count>1) ? 1 : 0, node);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tgf_fprintf(sdump->trace, \"\\\"/>\\n\");\n\t\t\t}\n\t\t}\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'fixed #2232'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: UrlQuery::UrlQuery(const std::string& encoded_str) {\n if (!encoded_str.empty()) {\n // Split into key value pairs separated by '&'.\n for (std::size_t i = 0; i != std::string::npos;) {\n std::size_t j = encoded_str.find_first_of('&', i);\n\n std::string kv;\n if (j == std::string::npos) {\n kv = encoded_str.substr(i);\n i = std::string::npos;\n } else {\n kv = encoded_str.substr(i, j - i);\n i = j + 1;\n }\n\n string_view key;\n string_view value;\n if (SplitKV(kv, '=', false, &key, &value)) {\n parameters_.push_back({ DecodeUnsafe(key), DecodeUnsafe(value) });\n }\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-22'], 'message': 'fix static file serving security issue; fix url path encoding issue'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: process_bitmap_updates(STREAM s)\n{\n\tuint16 num_updates;\n\tuint16 left, top, right, bottom, width, height;\n\tuint16 cx, cy, bpp, Bpp, compress, bufsize, size;\n\tuint8 *data, *bmpdata;\n\tint i;\n\n\tlogger(Protocol, Debug, \"%s()\", __func__);\n\n\tin_uint16_le(s, num_updates);\n\n\tfor (i = 0; i < num_updates; i++)\n\t{\n\t\tin_uint16_le(s, left);\n\t\tin_uint16_le(s, top);\n\t\tin_uint16_le(s, right);\n\t\tin_uint16_le(s, bottom);\n\t\tin_uint16_le(s, width);\n\t\tin_uint16_le(s, height);\n\t\tin_uint16_le(s, bpp);\n\t\tBpp = (bpp + 7) / 8;\n\t\tin_uint16_le(s, compress);\n\t\tin_uint16_le(s, bufsize);\n\n\t\tcx = right - left + 1;\n\t\tcy = bottom - top + 1;\n\n\t\tlogger(Graphics, Debug,\n\t\t \"process_bitmap_updates(), [%d,%d,%d,%d], [%d,%d], bpp=%d, compression=%d\",\n\t\t left, top, right, bottom, width, height, Bpp, compress);\n\n\t\tif (!compress)\n\t\t{\n\t\t\tint y;\n\t\t\tbmpdata = (uint8 *) xmalloc(width * height * Bpp);\n\t\t\tfor (y = 0; y < height; y++)\n\t\t\t{\n\t\t\t\tin_uint8a(s, &bmpdata[(height - y - 1) * (width * Bpp)],\n\t\t\t\t\t width * Bpp);\n\t\t\t}\n\t\t\tui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);\n\t\t\txfree(bmpdata);\n\t\t\tcontinue;\n\t\t}\n\n\n\t\tif (compress & 0x400)\n\t\t{\n\t\t\tsize = bufsize;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tin_uint8s(s, 2);\t/* pad */\n\t\t\tin_uint16_le(s, size);\n\t\t\tin_uint8s(s, 4);\t/* line_size, final_size */\n\t\t}\n\t\tin_uint8p(s, data, size);\n\t\tbmpdata = (uint8 *) xmalloc(width * height * Bpp);\n\t\tif (bitmap_decompress(bmpdata, width, height, data, size, Bpp))\n\t\t{\n\t\t\tui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlogger(Graphics, Warning,\n\t\t\t \"process_bitmap_updates(), failed to decompress bitmap\");\n\t\t}\n\n\t\txfree(bmpdata);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-125', 'CWE-703', 'CWE-787'], 'message': 'Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: lspci_process(STREAM s)\n{\n\tunsigned int pkglen;\n\tstatic char *rest = NULL;\n\tchar *buf;\n\n\tpkglen = s->end - s->p;\n\t/* str_handle_lines requires null terminated strings */\n\tbuf = xmalloc(pkglen + 1);\n\tSTRNCPY(buf, (char *) s->p, pkglen + 1);\n\tstr_handle_lines(buf, &rest, lspci_process_line, NULL);\n\txfree(buf);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-125', 'CWE-703', 'CWE-787'], 'message': 'Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ikev1_nonce_print(netdissect_options *ndo, u_char tpay _U_,\n\t\t const struct isakmp_gen *ext,\n\t\t u_int item_len _U_,\n\t\t const u_char *ep,\n\t\t uint32_t phase _U_, uint32_t doi _U_,\n\t\t uint32_t proto _U_, int depth _U_)\n{\n\tstruct isakmp_gen e;\n\n\tND_PRINT((ndo,\"%s:\", NPSTR(ISAKMP_NPTYPE_NONCE)));\n\n\tND_TCHECK(*ext);\n\tUNALIGNED_MEMCPY(&e, ext, sizeof(e));\n\tND_PRINT((ndo,\" n len=%d\", ntohs(e.len) - 4));\n\tif (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {\n\t\tND_PRINT((ndo,\" \"));\n\t\tif (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))\n\t\t\tgoto trunc;\n\t} else if (1 < ndo->ndo_vflag && 4 < ntohs(e.len)) {\n\t\tND_PRINT((ndo,\" \"));\n\t\tif (!ike_show_somedata(ndo, (const u_char *)(const uint8_t *)(ext + 1), ep))\n\t\t\tgoto trunc;\n\t}\n\treturn (const u_char *)ext + ntohs(e.len);\ntrunc:\n\tND_PRINT((ndo,\" [|%s]\", NPSTR(ISAKMP_NPTYPE_NONCE)));\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-835'], 'message': 'CVE-2017-12990/Fix printing of ISAKMPv1 Notification payload data.\n\nThe closest thing to a specification for the contents of the payload\ndata is draft-ietf-ipsec-notifymsg-04, and nothing in there says that it\nis ever a complete ISAKMP message, so don't dissect types we don't have\nspecific code for as a complete ISAKMP message.\n\nWhile we're at it, fix a comment, and clean up printing of V1 Nonce,\nV2 Authentication payloads, and v2 Notice payloads.\n\nThis fixes an infinite loop discovered by Forcepoint's security\nresearchers Otto Airamo & Antti Levom\u00e4ki.\n\nAdd a test using the capture file supplied by the reporter(s).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int crypto_nivaead_report(struct sk_buff *skb, struct crypto_alg *alg)\n{\n\treturn -ENOSYS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'crypto: user - fix info leaks in report API\n\nThree errors resulting in kernel memory disclosure:\n\n1/ The structures used for the netlink based crypto algorithm report API\nare located on the stack. As snprintf() does not fill the remainder of\nthe buffer with null bytes, those stack bytes will be disclosed to users\nof the API. Switch to strncpy() to fix this.\n\n2/ crypto_report_one() does not initialize all field of struct\ncrypto_user_alg. Fix this to fix the heap info leak.\n\n3/ For the module name we should copy only as many bytes as\nmodule_name() returns -- not as much as the destination buffer could\nhold. But the current code does not and therefore copies random data\nfrom behind the end of the module name, as the module name is always\nshorter than CRYPTO_MAX_ALG_NAME.\n\nAlso switch to use strncpy() to copy the algorithm's name and\ndriver_name. They are strings, after all.\n\nSigned-off-by: Mathias Krause \nCc: Steffen Klassert \nSigned-off-by: Herbert Xu '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int crypto_report_comp(struct sk_buff *skb, struct crypto_alg *alg)\n{\n\tstruct crypto_report_comp rcomp;\n\n\tsnprintf(rcomp.type, CRYPTO_MAX_ALG_NAME, \"%s\", \"compression\");\n\n\tif (nla_put(skb, CRYPTOCFGA_REPORT_COMPRESS,\n\t\t sizeof(struct crypto_report_comp), &rcomp))\n\t\tgoto nla_put_failure;\n\treturn 0;\n\nnla_put_failure:\n\treturn -EMSGSIZE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'crypto: user - fix info leaks in report API\n\nThree errors resulting in kernel memory disclosure:\n\n1/ The structures used for the netlink based crypto algorithm report API\nare located on the stack. As snprintf() does not fill the remainder of\nthe buffer with null bytes, those stack bytes will be disclosed to users\nof the API. Switch to strncpy() to fix this.\n\n2/ crypto_report_one() does not initialize all field of struct\ncrypto_user_alg. Fix this to fix the heap info leak.\n\n3/ For the module name we should copy only as many bytes as\nmodule_name() returns -- not as much as the destination buffer could\nhold. But the current code does not and therefore copies random data\nfrom behind the end of the module name, as the module name is always\nshorter than CRYPTO_MAX_ALG_NAME.\n\nAlso switch to use strncpy() to copy the algorithm's name and\ndriver_name. They are strings, after all.\n\nSigned-off-by: Mathias Krause \nCc: Steffen Klassert \nSigned-off-by: Herbert Xu '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int crypto_blkcipher_report(struct sk_buff *skb, struct crypto_alg *alg)\n{\n\tstruct crypto_report_blkcipher rblkcipher;\n\n\tsnprintf(rblkcipher.type, CRYPTO_MAX_ALG_NAME, \"%s\", \"blkcipher\");\n\tsnprintf(rblkcipher.geniv, CRYPTO_MAX_ALG_NAME, \"%s\",\n\t\t alg->cra_blkcipher.geniv ?: \"\");\n\n\trblkcipher.blocksize = alg->cra_blocksize;\n\trblkcipher.min_keysize = alg->cra_blkcipher.min_keysize;\n\trblkcipher.max_keysize = alg->cra_blkcipher.max_keysize;\n\trblkcipher.ivsize = alg->cra_blkcipher.ivsize;\n\n\tif (nla_put(skb, CRYPTOCFGA_REPORT_BLKCIPHER,\n\t\t sizeof(struct crypto_report_blkcipher), &rblkcipher))\n\t\tgoto nla_put_failure;\n\treturn 0;\n\nnla_put_failure:\n\treturn -EMSGSIZE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'crypto: user - fix info leaks in report API\n\nThree errors resulting in kernel memory disclosure:\n\n1/ The structures used for the netlink based crypto algorithm report API\nare located on the stack. As snprintf() does not fill the remainder of\nthe buffer with null bytes, those stack bytes will be disclosed to users\nof the API. Switch to strncpy() to fix this.\n\n2/ crypto_report_one() does not initialize all field of struct\ncrypto_user_alg. Fix this to fix the heap info leak.\n\n3/ For the module name we should copy only as many bytes as\nmodule_name() returns -- not as much as the destination buffer could\nhold. But the current code does not and therefore copies random data\nfrom behind the end of the module name, as the module name is always\nshorter than CRYPTO_MAX_ALG_NAME.\n\nAlso switch to use strncpy() to copy the algorithm's name and\ndriver_name. They are strings, after all.\n\nSigned-off-by: Mathias Krause \nCc: Steffen Klassert \nSigned-off-by: Herbert Xu '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int dns_transaction_emit_tcp(DnsTransaction *t) {\n _cleanup_close_ int fd = -1;\n _cleanup_(dns_stream_unrefp) DnsStream *s = NULL;\n union sockaddr_union sa;\n int r;\n\n assert(t);\n\n dns_transaction_close_connection(t);\n\n switch (t->scope->protocol) {\n\n case DNS_PROTOCOL_DNS:\n r = dns_transaction_pick_server(t);\n if (r < 0)\n return r;\n\n if (!dns_server_dnssec_supported(t->server) && dns_type_is_dnssec(t->key->type))\n return -EOPNOTSUPP;\n\n r = dns_server_adjust_opt(t->server, t->sent, t->current_feature_level);\n if (r < 0)\n return r;\n\n if (t->server->stream && (DNS_SERVER_FEATURE_LEVEL_IS_TLS(t->current_feature_level) == t->server->stream->encrypted))\n s = dns_stream_ref(t->server->stream);\n else\n fd = dns_scope_socket_tcp(t->scope, AF_UNSPEC, NULL, t->server, dns_port_for_feature_level(t->current_feature_level), &sa);\n\n break;\n\n case DNS_PROTOCOL_LLMNR:\n /* When we already received a reply to this (but it was truncated), send to its sender address */\n if (t->received)\n fd = dns_scope_socket_tcp(t->scope, t->received->family, &t->received->sender, NULL, t->received->sender_port, &sa);\n else {\n union in_addr_union address;\n int family = AF_UNSPEC;\n\n /* Otherwise, try to talk to the owner of a\n * the IP address, in case this is a reverse\n * PTR lookup */\n\n r = dns_name_address(dns_resource_key_name(t->key), &family, &address);\n if (r < 0)\n return r;\n if (r == 0)\n return -EINVAL;\n if (family != t->scope->family)\n return -ESRCH;\n\n fd = dns_scope_socket_tcp(t->scope, family, &address, NULL, LLMNR_PORT, &sa);\n }\n\n break;\n\n default:\n return -EAFNOSUPPORT;\n }\n\n if (!s) {\n if (fd < 0)\n return fd;\n\n r = dns_stream_new(t->scope->manager, &s, t->scope->protocol, fd, &sa);\n if (r < 0)\n return r;\n\n fd = -1;\n\n#if ENABLE_DNS_OVER_TLS\n if (t->scope->protocol == DNS_PROTOCOL_DNS &&\n DNS_SERVER_FEATURE_LEVEL_IS_TLS(t->current_feature_level)) {\n\n assert(t->server);\n r = dnstls_stream_connect_tls(s, t->server);\n if (r < 0)\n return r;\n }\n#endif\n\n if (t->server) {\n dns_stream_unref(t->server->stream);\n t->server->stream = dns_stream_ref(s);\n s->server = dns_server_ref(t->server);\n }\n\n s->complete = on_stream_complete;\n s->on_packet = on_stream_packet;\n\n /* The interface index is difficult to determine if we are\n * connecting to the local host, hence fill this in right away\n * instead of determining it from the socket */\n s->ifindex = dns_scope_ifindex(t->scope);\n }\n\n t->stream = TAKE_PTR(s);\n LIST_PREPEND(transactions_by_stream, t->stream->transactions, t);\n\n r = dns_stream_write_packet(t->stream, t->sent);\n if (r < 0) {\n dns_transaction_close_connection(t);\n return r;\n }\n\n dns_transaction_reset_answer(t);\n\n t->tried_stream = true;\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'resolved: take particular care when detaching DnsServer from its default stream\n\nDnsStream and DnsServer have a symbiotic relationship: one DnsStream is\nthe current \"default\" stream of the server (and thus reffed by it), but\neach stream also refs the server it is connected to. This cyclic\ndependency can result in weird situations: when one is\ndestroyed/unlinked/stopped it needs to unregister itself from the other,\nbut doing this will trigger unregistration of the other. Hence, let's\nmake sure we unregister the stream from the server before destroying it,\nto break this cycle.\n\nMost likely fixes: #10725'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: EbmlElement * EbmlElement::FindNextElement(IOCallback & DataStream, const EbmlSemanticContext & Context, int & UpperLevel,\n uint64 MaxDataSize, bool AllowDummyElt, unsigned int MaxLowerLevel)\n{\n int PossibleID_Length = 0;\n binary PossibleIdNSize[16];\n int PossibleSizeLength;\n uint64 SizeUnknown;\n int ReadIndex = 0; // trick for the algo, start index at 0\n uint32 ReadSize = 0;\n uint64 SizeFound;\n int SizeIdx;\n bool bFound;\n int UpperLevel_original = UpperLevel;\n\n do {\n // read a potential ID\n do {\n assert(ReadIndex < 16);\n // build the ID with the current Read Buffer\n bFound = false;\n binary IdBitMask = 1 << 7;\n for (SizeIdx = 0; SizeIdx < ReadIndex && SizeIdx < 4; SizeIdx++) {\n if (PossibleIdNSize[0] & (IdBitMask >> SizeIdx)) {\n // ID found\n PossibleID_Length = SizeIdx + 1;\n IdBitMask >>= SizeIdx;\n bFound = true;\n break;\n }\n }\n if (bFound) {\n break;\n }\n\n if (ReadIndex >= 4) {\n // ID not found\n // shift left the read octets\n memmove(&PossibleIdNSize[0],&PossibleIdNSize[1], --ReadIndex);\n }\n\n if (MaxDataSize <= ReadSize)\n break;\n if (DataStream.read(&PossibleIdNSize[ReadIndex++], 1) == 0) {\n return NULL; // no more data ?\n }\n ReadSize++;\n\n } while (!bFound);\n\n if (!bFound)\n // we reached the maximum we could read without a proper ID\n return NULL;\n\n SizeIdx = ReadIndex;\n ReadIndex -= PossibleID_Length;\n\n // read the data size\n uint32 _SizeLength;\n PossibleSizeLength = ReadIndex;\n while (1) {\n _SizeLength = PossibleSizeLength;\n SizeFound = ReadCodedSizeValue(&PossibleIdNSize[PossibleID_Length], _SizeLength, SizeUnknown);\n if (_SizeLength != 0) {\n bFound = true;\n break;\n }\n if (PossibleSizeLength >= 8) {\n bFound = false;\n break;\n }\n if (MaxDataSize <= ReadSize) {\n bFound = false;\n break;\n }\n if( DataStream.read( &PossibleIdNSize[SizeIdx++], 1 ) == 0 ) {\n return NULL; // no more data ?\n }\n ReadSize++;\n PossibleSizeLength++;\n }\n\n if (bFound) {\n // find the element in the context and use the correct creator\n EbmlId PossibleID(PossibleIdNSize, PossibleID_Length);\n EbmlElement * Result = CreateElementUsingContext(PossibleID, Context, UpperLevel, false, AllowDummyElt, MaxLowerLevel);\n ///< \\todo continue is misplaced\n if (Result != NULL) {\n if (AllowDummyElt || !Result->IsDummy()) {\n Result->SetSizeLength(_SizeLength);\n\n Result->Size = SizeFound;\n // UpperLevel values\n // -1 : global element\n // 0 : child\n // 1 : same level\n // + : further parent\n if (Result->ValidateSize() && (SizeFound == SizeUnknown || UpperLevel > 0 || MaxDataSize == 0 || MaxDataSize >= (PossibleID_Length + PossibleSizeLength + SizeFound))) {\n if (SizeFound != SizeUnknown || Result->SetSizeInfinite()) {\n Result->SizePosition = DataStream.getFilePointer() - SizeIdx + EBML_ID_LENGTH(PossibleID);\n Result->ElementPosition = Result->SizePosition - EBML_ID_LENGTH(PossibleID);\n // place the file at the beggining of the data\n DataStream.setFilePointer(Result->SizePosition + _SizeLength);\n return Result;\n }\n }\n }\n delete Result;\n }\n }\n\n // recover all the data in the buffer minus one byte\n ReadIndex = SizeIdx - 1;\n memmove(&PossibleIdNSize[0], &PossibleIdNSize[1], ReadIndex);\n UpperLevel = UpperLevel_original;\n } while ( MaxDataSize > DataStream.getFilePointer() - SizeIdx + PossibleID_Length );\n\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-125'], 'message': 'Exit the max size loop when there's nothing left possible to find\n\nDataStream.getFilePointer() is not correct in this context. It might force to\nexit too early.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: char* _single_string_alloc_and_copy( LPCWSTR in )\n{\n char *chr;\n int len = 0;\n\n if ( !in )\n {\n return in;\n }\n\n while ( in[ len ] != 0 )\n {\n len ++;\n }\n\n chr = malloc( len + 1 );\n\n len = 0;\n while ( in[ len ] != 0 )\n {\n chr[ len ] = 0xFF & in[ len ];\n len ++;\n }\n chr[ len ++ ] = '\\0';\n\n return chr;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-369'], 'message': 'New Pre Source'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ip6_append_data(struct sock *sk, int getfrag(void *from, char *to,\n\tint offset, int len, int odd, struct sk_buff *skb),\n\tvoid *from, int length, int transhdrlen,\n\tint hlimit, int tclass, struct ipv6_txoptions *opt, struct flowi6 *fl6,\n\tstruct rt6_info *rt, unsigned int flags, int dontfrag)\n{\n\tstruct inet_sock *inet = inet_sk(sk);\n\tstruct ipv6_pinfo *np = inet6_sk(sk);\n\tstruct inet_cork *cork;\n\tstruct sk_buff *skb, *skb_prev = NULL;\n\tunsigned int maxfraglen, fragheaderlen, mtu;\n\tint exthdrlen;\n\tint dst_exthdrlen;\n\tint hh_len;\n\tint copy;\n\tint err;\n\tint offset = 0;\n\t__u8 tx_flags = 0;\n\n\tif (flags&MSG_PROBE)\n\t\treturn 0;\n\tcork = &inet->cork.base;\n\tif (skb_queue_empty(&sk->sk_write_queue)) {\n\t\t/*\n\t\t * setup for corking\n\t\t */\n\t\tif (opt) {\n\t\t\tif (WARN_ON(np->cork.opt))\n\t\t\t\treturn -EINVAL;\n\n\t\t\tnp->cork.opt = kzalloc(opt->tot_len, sk->sk_allocation);\n\t\t\tif (unlikely(np->cork.opt == NULL))\n\t\t\t\treturn -ENOBUFS;\n\n\t\t\tnp->cork.opt->tot_len = opt->tot_len;\n\t\t\tnp->cork.opt->opt_flen = opt->opt_flen;\n\t\t\tnp->cork.opt->opt_nflen = opt->opt_nflen;\n\n\t\t\tnp->cork.opt->dst0opt = ip6_opt_dup(opt->dst0opt,\n\t\t\t\t\t\t\t sk->sk_allocation);\n\t\t\tif (opt->dst0opt && !np->cork.opt->dst0opt)\n\t\t\t\treturn -ENOBUFS;\n\n\t\t\tnp->cork.opt->dst1opt = ip6_opt_dup(opt->dst1opt,\n\t\t\t\t\t\t\t sk->sk_allocation);\n\t\t\tif (opt->dst1opt && !np->cork.opt->dst1opt)\n\t\t\t\treturn -ENOBUFS;\n\n\t\t\tnp->cork.opt->hopopt = ip6_opt_dup(opt->hopopt,\n\t\t\t\t\t\t\t sk->sk_allocation);\n\t\t\tif (opt->hopopt && !np->cork.opt->hopopt)\n\t\t\t\treturn -ENOBUFS;\n\n\t\t\tnp->cork.opt->srcrt = ip6_rthdr_dup(opt->srcrt,\n\t\t\t\t\t\t\t sk->sk_allocation);\n\t\t\tif (opt->srcrt && !np->cork.opt->srcrt)\n\t\t\t\treturn -ENOBUFS;\n\n\t\t\t/* need source address above miyazawa*/\n\t\t}\n\t\tdst_hold(&rt->dst);\n\t\tcork->dst = &rt->dst;\n\t\tinet->cork.fl.u.ip6 = *fl6;\n\t\tnp->cork.hop_limit = hlimit;\n\t\tnp->cork.tclass = tclass;\n\t\tif (rt->dst.flags & DST_XFRM_TUNNEL)\n\t\t\tmtu = np->pmtudisc == IPV6_PMTUDISC_PROBE ?\n\t\t\t rt->dst.dev->mtu : dst_mtu(&rt->dst);\n\t\telse\n\t\t\tmtu = np->pmtudisc == IPV6_PMTUDISC_PROBE ?\n\t\t\t rt->dst.dev->mtu : dst_mtu(rt->dst.path);\n\t\tif (np->frag_size < mtu) {\n\t\t\tif (np->frag_size)\n\t\t\t\tmtu = np->frag_size;\n\t\t}\n\t\tcork->fragsize = mtu;\n\t\tif (dst_allfrag(rt->dst.path))\n\t\t\tcork->flags |= IPCORK_ALLFRAG;\n\t\tcork->length = 0;\n\t\texthdrlen = (opt ? opt->opt_flen : 0);\n\t\tlength += exthdrlen;\n\t\ttranshdrlen += exthdrlen;\n\t\tdst_exthdrlen = rt->dst.header_len - rt->rt6i_nfheader_len;\n\t} else {\n\t\trt = (struct rt6_info *)cork->dst;\n\t\tfl6 = &inet->cork.fl.u.ip6;\n\t\topt = np->cork.opt;\n\t\ttranshdrlen = 0;\n\t\texthdrlen = 0;\n\t\tdst_exthdrlen = 0;\n\t\tmtu = cork->fragsize;\n\t}\n\n\thh_len = LL_RESERVED_SPACE(rt->dst.dev);\n\n\tfragheaderlen = sizeof(struct ipv6hdr) + rt->rt6i_nfheader_len +\n\t\t\t(opt ? opt->opt_nflen : 0);\n\tmaxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen - sizeof(struct frag_hdr);\n\n\tif (mtu <= sizeof(struct ipv6hdr) + IPV6_MAXPLEN) {\n\t\tif (cork->length + length > sizeof(struct ipv6hdr) + IPV6_MAXPLEN - fragheaderlen) {\n\t\t\tipv6_local_error(sk, EMSGSIZE, fl6, mtu-exthdrlen);\n\t\t\treturn -EMSGSIZE;\n\t\t}\n\t}\n\n\t/* For UDP, check if TX timestamp is enabled */\n\tif (sk->sk_type == SOCK_DGRAM)\n\t\tsock_tx_timestamp(sk, &tx_flags);\n\n\t/*\n\t * Let's try using as much space as possible.\n\t * Use MTU if total length of the message fits into the MTU.\n\t * Otherwise, we need to reserve fragment header and\n\t * fragment alignment (= 8-15 octects, in total).\n\t *\n\t * Note that we may need to \"move\" the data from the tail of\n\t * of the buffer to the new fragment when we split\n\t * the message.\n\t *\n\t * FIXME: It may be fragmented into multiple chunks\n\t * at once if non-fragmentable extension headers\n\t * are too large.\n\t * --yoshfuji\n\t */\n\n\tcork->length += length;\n\tif (length > mtu) {\n\t\tint proto = sk->sk_protocol;\n\t\tif (dontfrag && (proto == IPPROTO_UDP || proto == IPPROTO_RAW)){\n\t\t\tipv6_local_rxpmtu(sk, fl6, mtu-exthdrlen);\n\t\t\treturn -EMSGSIZE;\n\t\t}\n\n\t\tif (proto == IPPROTO_UDP &&\n\t\t (rt->dst.dev->features & NETIF_F_UFO)) {\n\n\t\t\terr = ip6_ufo_append_data(sk, getfrag, from, length,\n\t\t\t\t\t\t hh_len, fragheaderlen,\n\t\t\t\t\t\t transhdrlen, mtu, flags, rt);\n\t\t\tif (err)\n\t\t\t\tgoto error;\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\tif ((skb = skb_peek_tail(&sk->sk_write_queue)) == NULL)\n\t\tgoto alloc_new_skb;\n\n\twhile (length > 0) {\n\t\t/* Check if the remaining data fits into current packet. */\n\t\tcopy = (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - skb->len;\n\t\tif (copy < length)\n\t\t\tcopy = maxfraglen - skb->len;\n\n\t\tif (copy <= 0) {\n\t\t\tchar *data;\n\t\t\tunsigned int datalen;\n\t\t\tunsigned int fraglen;\n\t\t\tunsigned int fraggap;\n\t\t\tunsigned int alloclen;\nalloc_new_skb:\n\t\t\t/* There's no room in the current skb */\n\t\t\tif (skb)\n\t\t\t\tfraggap = skb->len - maxfraglen;\n\t\t\telse\n\t\t\t\tfraggap = 0;\n\t\t\t/* update mtu and maxfraglen if necessary */\n\t\t\tif (skb == NULL || skb_prev == NULL)\n\t\t\t\tip6_append_data_mtu(&mtu, &maxfraglen,\n\t\t\t\t\t\t fragheaderlen, skb, rt,\n\t\t\t\t\t\t np->pmtudisc ==\n\t\t\t\t\t\t IPV6_PMTUDISC_PROBE);\n\n\t\t\tskb_prev = skb;\n\n\t\t\t/*\n\t\t\t * If remaining data exceeds the mtu,\n\t\t\t * we know we need more fragment(s).\n\t\t\t */\n\t\t\tdatalen = length + fraggap;\n\n\t\t\tif (datalen > (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - fragheaderlen)\n\t\t\t\tdatalen = maxfraglen - fragheaderlen - rt->dst.trailer_len;\n\t\t\tif ((flags & MSG_MORE) &&\n\t\t\t !(rt->dst.dev->features&NETIF_F_SG))\n\t\t\t\talloclen = mtu;\n\t\t\telse\n\t\t\t\talloclen = datalen + fragheaderlen;\n\n\t\t\talloclen += dst_exthdrlen;\n\n\t\t\tif (datalen != length + fraggap) {\n\t\t\t\t/*\n\t\t\t\t * this is not the last fragment, the trailer\n\t\t\t\t * space is regarded as data space.\n\t\t\t\t */\n\t\t\t\tdatalen += rt->dst.trailer_len;\n\t\t\t}\n\n\t\t\talloclen += rt->dst.trailer_len;\n\t\t\tfraglen = datalen + fragheaderlen;\n\n\t\t\t/*\n\t\t\t * We just reserve space for fragment header.\n\t\t\t * Note: this may be overallocation if the message\n\t\t\t * (without MSG_MORE) fits into the MTU.\n\t\t\t */\n\t\t\talloclen += sizeof(struct frag_hdr);\n\n\t\t\tif (transhdrlen) {\n\t\t\t\tskb = sock_alloc_send_skb(sk,\n\t\t\t\t\t\talloclen + hh_len,\n\t\t\t\t\t\t(flags & MSG_DONTWAIT), &err);\n\t\t\t} else {\n\t\t\t\tskb = NULL;\n\t\t\t\tif (atomic_read(&sk->sk_wmem_alloc) <=\n\t\t\t\t 2 * sk->sk_sndbuf)\n\t\t\t\t\tskb = sock_wmalloc(sk,\n\t\t\t\t\t\t\t alloclen + hh_len, 1,\n\t\t\t\t\t\t\t sk->sk_allocation);\n\t\t\t\tif (unlikely(skb == NULL))\n\t\t\t\t\terr = -ENOBUFS;\n\t\t\t\telse {\n\t\t\t\t\t/* Only the initial fragment\n\t\t\t\t\t * is time stamped.\n\t\t\t\t\t */\n\t\t\t\t\ttx_flags = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (skb == NULL)\n\t\t\t\tgoto error;\n\t\t\t/*\n\t\t\t *\tFill in the control structures\n\t\t\t */\n\t\t\tskb->protocol = htons(ETH_P_IPV6);\n\t\t\tskb->ip_summed = CHECKSUM_NONE;\n\t\t\tskb->csum = 0;\n\t\t\t/* reserve for fragmentation and ipsec header */\n\t\t\tskb_reserve(skb, hh_len + sizeof(struct frag_hdr) +\n\t\t\t\t dst_exthdrlen);\n\n\t\t\tif (sk->sk_type == SOCK_DGRAM)\n\t\t\t\tskb_shinfo(skb)->tx_flags = tx_flags;\n\n\t\t\t/*\n\t\t\t *\tFind where to start putting bytes\n\t\t\t */\n\t\t\tdata = skb_put(skb, fraglen);\n\t\t\tskb_set_network_header(skb, exthdrlen);\n\t\t\tdata += fragheaderlen;\n\t\t\tskb->transport_header = (skb->network_header +\n\t\t\t\t\t\t fragheaderlen);\n\t\t\tif (fraggap) {\n\t\t\t\tskb->csum = skb_copy_and_csum_bits(\n\t\t\t\t\tskb_prev, maxfraglen,\n\t\t\t\t\tdata + transhdrlen, fraggap, 0);\n\t\t\t\tskb_prev->csum = csum_sub(skb_prev->csum,\n\t\t\t\t\t\t\t skb->csum);\n\t\t\t\tdata += fraggap;\n\t\t\t\tpskb_trim_unique(skb_prev, maxfraglen);\n\t\t\t}\n\t\t\tcopy = datalen - transhdrlen - fraggap;\n\n\t\t\tif (copy < 0) {\n\t\t\t\terr = -EINVAL;\n\t\t\t\tkfree_skb(skb);\n\t\t\t\tgoto error;\n\t\t\t} else if (copy > 0 && getfrag(from, data + transhdrlen, offset, copy, fraggap, skb) < 0) {\n\t\t\t\terr = -EFAULT;\n\t\t\t\tkfree_skb(skb);\n\t\t\t\tgoto error;\n\t\t\t}\n\n\t\t\toffset += copy;\n\t\t\tlength -= datalen - fraggap;\n\t\t\ttranshdrlen = 0;\n\t\t\texthdrlen = 0;\n\t\t\tdst_exthdrlen = 0;\n\n\t\t\t/*\n\t\t\t * Put the packet on the pending queue\n\t\t\t */\n\t\t\t__skb_queue_tail(&sk->sk_write_queue, skb);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (copy > length)\n\t\t\tcopy = length;\n\n\t\tif (!(rt->dst.dev->features&NETIF_F_SG)) {\n\t\t\tunsigned int off;\n\n\t\t\toff = skb->len;\n\t\t\tif (getfrag(from, skb_put(skb, copy),\n\t\t\t\t\t\toffset, copy, off, skb) < 0) {\n\t\t\t\t__skb_trim(skb, off);\n\t\t\t\terr = -EFAULT;\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t} else {\n\t\t\tint i = skb_shinfo(skb)->nr_frags;\n\t\t\tstruct page_frag *pfrag = sk_page_frag(sk);\n\n\t\t\terr = -ENOMEM;\n\t\t\tif (!sk_page_frag_refill(sk, pfrag))\n\t\t\t\tgoto error;\n\n\t\t\tif (!skb_can_coalesce(skb, i, pfrag->page,\n\t\t\t\t\t pfrag->offset)) {\n\t\t\t\terr = -EMSGSIZE;\n\t\t\t\tif (i == MAX_SKB_FRAGS)\n\t\t\t\t\tgoto error;\n\n\t\t\t\t__skb_fill_page_desc(skb, i, pfrag->page,\n\t\t\t\t\t\t pfrag->offset, 0);\n\t\t\t\tskb_shinfo(skb)->nr_frags = ++i;\n\t\t\t\tget_page(pfrag->page);\n\t\t\t}\n\t\t\tcopy = min_t(int, copy, pfrag->size - pfrag->offset);\n\t\t\tif (getfrag(from,\n\t\t\t\t page_address(pfrag->page) + pfrag->offset,\n\t\t\t\t offset, copy, skb->len, skb) < 0)\n\t\t\t\tgoto error_efault;\n\n\t\t\tpfrag->offset += copy;\n\t\t\tskb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);\n\t\t\tskb->len += copy;\n\t\t\tskb->data_len += copy;\n\t\t\tskb->truesize += copy;\n\t\t\tatomic_add(copy, &sk->sk_wmem_alloc);\n\t\t}\n\t\toffset += copy;\n\t\tlength -= copy;\n\t}\n\n\treturn 0;\n\nerror_efault:\n\terr = -EFAULT;\nerror:\n\tcork->length -= length;\n\tIP6_INC_STATS(sock_net(sk), rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-401'], 'message': 'ipv6: udp packets following an UFO enqueued packet need also be handled by UFO\n\nIn the following scenario the socket is corked:\nIf the first UDP packet is larger then the mtu we try to append it to the\nwrite queue via ip6_ufo_append_data. A following packet, which is smaller\nthan the mtu would be appended to the already queued up gso-skb via\nplain ip6_append_data. This causes random memory corruptions.\n\nIn ip6_ufo_append_data we also have to be careful to not queue up the\nsame skb multiple times. So setup the gso frame only when no first skb\nis available.\n\nThis also fixes a shortcoming where we add the current packet's length to\ncork->length but return early because of a packet > mtu with dontfrag set\n(instead of sutracting it again).\n\nFound with trinity.\n\nCc: YOSHIFUJI Hideaki \nSigned-off-by: Hannes Frederic Sowa \nReported-by: Dmitry Vyukov \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int mongo_cursor_get_more( mongo_cursor *cursor ) {\n int res;\n\n if( cursor->limit > 0 && cursor->seen >= cursor->limit ) {\n cursor->err = MONGO_CURSOR_EXHAUSTED;\n return MONGO_ERROR;\n }\n else if( ! cursor->reply ) {\n cursor->err = MONGO_CURSOR_INVALID;\n return MONGO_ERROR;\n }\n else if( ! cursor->reply->fields.cursorID ) {\n cursor->err = MONGO_CURSOR_EXHAUSTED;\n return MONGO_ERROR;\n }\n else {\n char *data;\n int sl = strlen( cursor->ns )+1;\n int limit = 0;\n mongo_message *mm;\n\n if( cursor->limit > 0 )\n limit = cursor->limit - cursor->seen;\n\n mm = mongo_message_create( 16 /*header*/\n +4 /*ZERO*/\n +sl\n +4 /*numToReturn*/\n +8 /*cursorID*/\n , 0, 0, MONGO_OP_GET_MORE );\n data = &mm->data;\n data = mongo_data_append32( data, &ZERO );\n data = mongo_data_append( data, cursor->ns, sl );\n data = mongo_data_append32( data, &limit );\n mongo_data_append64( data, &cursor->reply->fields.cursorID );\n\n bson_free( cursor->reply );\n res = mongo_message_send( cursor->conn, mm );\n if( res != MONGO_OK ) {\n mongo_cursor_destroy( cursor );\n return MONGO_ERROR;\n }\n\n res = mongo_read_response( cursor->conn, &( cursor->reply ) );\n if( res != MONGO_OK ) {\n mongo_cursor_destroy( cursor );\n return MONGO_ERROR;\n }\n cursor->current.data = NULL;\n cursor->seen += cursor->reply->fields.num;\n\n return MONGO_OK;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'don't mix up int and size_t (first pass to fix that)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: MONGO_EXPORT bson_bool_t mongo_cmd_authenticate( mongo *conn, const char *db, const char *user, const char *pass ) {\n bson from_db;\n bson cmd;\n const char *nonce;\n int result;\n\n mongo_md5_state_t st;\n mongo_md5_byte_t digest[16];\n char hex_digest[33];\n\n if( mongo_simple_int_command( conn, db, \"getnonce\", 1, &from_db ) == MONGO_OK ) {\n bson_iterator it;\n bson_find( &it, &from_db, \"nonce\" );\n nonce = bson_iterator_string( &it );\n }\n else {\n return MONGO_ERROR;\n }\n\n mongo_pass_digest( user, pass, hex_digest );\n\n mongo_md5_init( &st );\n mongo_md5_append( &st, ( const mongo_md5_byte_t * )nonce, strlen( nonce ) );\n mongo_md5_append( &st, ( const mongo_md5_byte_t * )user, strlen( user ) );\n mongo_md5_append( &st, ( const mongo_md5_byte_t * )hex_digest, 32 );\n mongo_md5_finish( &st, digest );\n digest2hex( digest, hex_digest );\n\n bson_init( &cmd );\n bson_append_int( &cmd, \"authenticate\", 1 );\n bson_append_string( &cmd, \"user\", user );\n bson_append_string( &cmd, \"nonce\", nonce );\n bson_append_string( &cmd, \"key\", hex_digest );\n bson_finish( &cmd );\n\n bson_destroy( &from_db );\n\n result = mongo_run_command( conn, db, &cmd, NULL );\n\n bson_destroy( &cmd );\n\n return result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'don't mix up int and size_t (first pass to fix that)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static char *mongo_data_append( char *start , const void *data , int len ) {\n memcpy( start , data , len );\n return start + len;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'don't mix up int and size_t (first pass to fix that)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int mongo_env_read_socket( mongo *conn, void *buf, int len ) {\n char *cbuf = buf;\n\n while ( len ) {\n int sent = recv( conn->sock, cbuf, len, 0 );\n if ( sent == 0 || sent == -1 ) {\n __mongo_set_error( conn, MONGO_IO_ERROR, NULL, WSAGetLastError() );\n return MONGO_ERROR;\n }\n cbuf += sent;\n len -= sent;\n }\n\n return MONGO_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'don't mix up int and size_t (first pass to fix that)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void AddBatchOffsets(Tensor* indices, const Tensor& params) {\n int64_t batch_size = 1; // The size of all batch dimensions.\n for (int idx = 0; idx < batch_dims_; ++idx) {\n batch_size *= params.dim_size(idx);\n }\n\n auto indices_flat = indices->flat();\n int64_t const index_inner_size = indices->NumElements() / batch_size;\n int64_t const batch_offset = params.dim_size(batch_dims_);\n for (int64_t batch_idx = 0, dest_idx = 0; batch_idx < batch_size;\n ++batch_idx) {\n for (int64_t idx = 0; idx < index_inner_size; ++idx) {\n indices_flat(dest_idx++) += batch_offset * batch_idx;\n }\n }\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-369'], 'message': 'Prevent division by 0 in `resource_variable_ops.cc`\n\nPiperOrigin-RevId: 387939939\nChange-Id: Ib04902d63756633999959a70613f2eaa30c2c151'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ikev1_attrmap_print(netdissect_options *ndo,\n\t\t const u_char *p, const u_char *ep,\n\t\t const struct attrmap *map, size_t nmap)\n{\n\tint totlen;\n\tuint32_t t, v;\n\n\tif (p[0] & 0x80)\n\t\ttotlen = 4;\n\telse\n\t\ttotlen = 4 + EXTRACT_16BITS(&p[2]);\n\tif (ep < p + totlen) {\n\t\tND_PRINT((ndo,\"[|attr]\"));\n\t\treturn ep + 1;\n\t}\n\n\tND_PRINT((ndo,\"(\"));\n\tt = EXTRACT_16BITS(&p[0]) & 0x7fff;\n\tif (map && t < nmap && map[t].type)\n\t\tND_PRINT((ndo,\"type=%s \", map[t].type));\n\telse\n\t\tND_PRINT((ndo,\"type=#%d \", t));\n\tif (p[0] & 0x80) {\n\t\tND_PRINT((ndo,\"value=\"));\n\t\tv = EXTRACT_16BITS(&p[2]);\n\t\tif (map && t < nmap && v < map[t].nvalue && map[t].value[v])\n\t\t\tND_PRINT((ndo,\"%s\", map[t].value[v]));\n\t\telse\n\t\t\trawprint(ndo, (const uint8_t *)&p[2], 2);\n\t} else {\n\t\tND_PRINT((ndo,\"len=%d value=\", EXTRACT_16BITS(&p[2])));\n\t\trawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2]));\n\t}\n\tND_PRINT((ndo,\")\"));\n\treturn p + totlen;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13039/IKEv1: Do more bounds checking.\n\nHave ikev1_attrmap_print() and ikev1_attr_print() do full bounds\nchecking, and return null on a bounds overflow. Have their callers\ncheck for a null return.\n\nThis fixes a buffer over-read discovered by Bhargava Shastry,\nSecT/TU Berlin.\n\nAdd a test using the capture file supplied by the reporter(s), modified\nso the capture file won't be rejected as an invalid capture.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void Compute(OpKernelContext* context) override {\n const Tensor& input = context->input(0);\n const Tensor& filter = context->input(1);\n\n // Determine relevant sizes from input and filters.\n int stride_rows = 0, stride_cols = 0;\n int rate_rows = 0, rate_cols = 0;\n int64 pad_top = 0, pad_left = 0;\n int64 out_rows = 0, out_cols = 0;\n ParseSizes(context, strides_, rates_, padding_, &stride_rows, &stride_cols,\n &rate_rows, &rate_cols, &pad_top, &pad_left, &out_rows,\n &out_cols);\n\n // Output tensor is of the following dimensions:\n // [ batch, out_rows, out_cols, depth ]\n const int batch = input.dim_size(0);\n const int depth = input.dim_size(3);\n const std::vector out_sizes = {batch, out_rows, out_cols, depth};\n TensorShape out_shape(out_sizes);\n\n Tensor* output = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(0, out_shape, &output));\n\n // If there is nothing to compute, return.\n if (out_shape.num_elements() == 0) {\n return;\n }\n\n functor::Dilation()(\n context->eigen_device(), input.tensor(),\n filter.tensor(), stride_rows, stride_cols, rate_rows, rate_cols,\n pad_top, pad_left, output->tensor());\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Add missing validations in dillation ops.\n\nPiperOrigin-RevId: 372037158\nChange-Id: I4ee304c84a02550c030288a6534000b934fc1599'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: u32 gf_base16_encode(u8 *_in, u32 inSize, u8 *_out, u32 outSize)\n{\n\tu32 i = 0;\n\tunsigned char *in = (unsigned char *)_in;\n\tunsigned char *out = (unsigned char *)_out;\n\n\tif (outSize < (inSize * 2)+1) return 0;\n\n\tfor (i=0; i> 4)];\n\t\tout[2*i+1] = base_16[(in[i] & 0x0f)];\n\t}\n\tout[(inSize * 2)] = 0;\n\n\treturn inSize * 2;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'fixed #2138'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int yr_re_match(\n RE* re,\n const char* target)\n{\n return yr_re_exec(\n re->code,\n (uint8_t*) target,\n strlen(target),\n re->flags | RE_FLAGS_SCAN,\n NULL,\n NULL);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix issue #646 (#648)\n\n* Fix issue #646 and some edge cases with wide regexps using \\b and \\B\r\n\r\n* Rename function IS_WORD_CHAR to _yr_re_is_word_char'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void Compute(OpKernelContext* context) override {\n // Get the input Tensors.\n OpInputList params_nested_splits_in;\n OP_REQUIRES_OK(context, context->input_list(\"params_nested_splits\",\n ¶ms_nested_splits_in));\n const Tensor& params_dense_values_in =\n context->input(params_nested_splits_in.size());\n const Tensor& indices_in =\n context->input(params_nested_splits_in.size() + 1);\n\n DCHECK_GT(params_nested_splits_in.size(), 0); // Enforced by REGISTER_OP.\n SPLITS_TYPE num_params = params_nested_splits_in[0].dim_size(0) - 1;\n OP_REQUIRES_OK(context, ValidateIndices(indices_in, num_params));\n\n OP_REQUIRES(context, params_dense_values_in.dims() > 0,\n errors::InvalidArgument(\"params.rank must be nonzero\"));\n SPLITS_TYPE num_params_dense_values = params_dense_values_in.dim_size(0);\n\n // Calculate the `splits`, and store the value slices that we need to\n // copy in `value_slices`.\n std::vector> value_slices;\n SPLITS_TYPE num_values = 0;\n std::vector> out_splits;\n OP_REQUIRES_OK(context, MakeSplits(indices_in, params_nested_splits_in,\n num_params_dense_values, &out_splits,\n &value_slices, &num_values));\n\n // Write the output tensors.\n OP_REQUIRES_OK(context, WriteSplits(out_splits, context));\n OP_REQUIRES_OK(context,\n WriteValues(params_dense_values_in, value_slices,\n out_splits.size(), num_values, context));\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-369'], 'message': 'Fix heap OOB in `tf.raw_ops.RaggedGather`\n\nPiperOrigin-RevId: 388355464\nChange-Id: If14d96231d1cd7aad7c4d1c22c1bab1576b75717'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static RFlagsAtOffset* r_flag_get_nearest_list(RFlag *f, ut64 off, int dir) {\n\tRFlagsAtOffset *flags = NULL;\n\tRFlagsAtOffset key;\n\tkey.off = off;\n\tif (dir >= 0) {\n\t\tflags = r_skiplist_get_geq (f->by_off, &key);\n\t} else {\n\t\tflags = r_skiplist_get_leq (f->by_off, &key);\n\t}\n\tif (dir == 0 && flags && flags->off != off) {\n\t\treturn NULL;\n\t}\n\treturn flags;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'Fix crash in wasm disassembler'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static unsigned int khugepaged_scan_mm_slot(unsigned int pages,\n\t\t\t\t\t struct page **hpage)\n{\n\tstruct mm_slot *mm_slot;\n\tstruct mm_struct *mm;\n\tstruct vm_area_struct *vma;\n\tint progress = 0;\n\n\tVM_BUG_ON(!pages);\n\tVM_BUG_ON(!spin_is_locked(&khugepaged_mm_lock));\n\n\tif (khugepaged_scan.mm_slot)\n\t\tmm_slot = khugepaged_scan.mm_slot;\n\telse {\n\t\tmm_slot = list_entry(khugepaged_scan.mm_head.next,\n\t\t\t\t struct mm_slot, mm_node);\n\t\tkhugepaged_scan.address = 0;\n\t\tkhugepaged_scan.mm_slot = mm_slot;\n\t}\n\tspin_unlock(&khugepaged_mm_lock);\n\n\tmm = mm_slot->mm;\n\tdown_read(&mm->mmap_sem);\n\tif (unlikely(khugepaged_test_exit(mm)))\n\t\tvma = NULL;\n\telse\n\t\tvma = find_vma(mm, khugepaged_scan.address);\n\n\tprogress++;\n\tfor (; vma; vma = vma->vm_next) {\n\t\tunsigned long hstart, hend;\n\n\t\tcond_resched();\n\t\tif (unlikely(khugepaged_test_exit(mm))) {\n\t\t\tprogress++;\n\t\t\tbreak;\n\t\t}\n\n\t\tif ((!(vma->vm_flags & VM_HUGEPAGE) &&\n\t\t !khugepaged_always()) ||\n\t\t (vma->vm_flags & VM_NOHUGEPAGE)) {\n\t\tskip:\n\t\t\tprogress++;\n\t\t\tcontinue;\n\t\t}\n\t\t/* VM_PFNMAP vmas may have vm_ops null but vm_file set */\n\t\tif (!vma->anon_vma || vma->vm_ops || vma->vm_file)\n\t\t\tgoto skip;\n\t\tif (is_vma_temporary_stack(vma))\n\t\t\tgoto skip;\n\n\t\tVM_BUG_ON(is_linear_pfn_mapping(vma) || is_pfn_mapping(vma));\n\n\t\thstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;\n\t\thend = vma->vm_end & HPAGE_PMD_MASK;\n\t\tif (hstart >= hend)\n\t\t\tgoto skip;\n\t\tif (khugepaged_scan.address > hend)\n\t\t\tgoto skip;\n\t\tif (khugepaged_scan.address < hstart)\n\t\t\tkhugepaged_scan.address = hstart;\n\t\tVM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);\n\n\t\twhile (khugepaged_scan.address < hend) {\n\t\t\tint ret;\n\t\t\tcond_resched();\n\t\t\tif (unlikely(khugepaged_test_exit(mm)))\n\t\t\t\tgoto breakouterloop;\n\n\t\t\tVM_BUG_ON(khugepaged_scan.address < hstart ||\n\t\t\t\t khugepaged_scan.address + HPAGE_PMD_SIZE >\n\t\t\t\t hend);\n\t\t\tret = khugepaged_scan_pmd(mm, vma,\n\t\t\t\t\t\t khugepaged_scan.address,\n\t\t\t\t\t\t hpage);\n\t\t\t/* move to next address */\n\t\t\tkhugepaged_scan.address += HPAGE_PMD_SIZE;\n\t\t\tprogress += HPAGE_PMD_NR;\n\t\t\tif (ret)\n\t\t\t\t/* we released mmap_sem so break loop */\n\t\t\t\tgoto breakouterloop_mmap_sem;\n\t\t\tif (progress >= pages)\n\t\t\t\tgoto breakouterloop;\n\t\t}\n\t}\nbreakouterloop:\n\tup_read(&mm->mmap_sem); /* exit_mmap will destroy ptes after this */\nbreakouterloop_mmap_sem:\n\n\tspin_lock(&khugepaged_mm_lock);\n\tVM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);\n\t/*\n\t * Release the current mm_slot if this mm is about to die, or\n\t * if we scanned all vmas of this mm.\n\t */\n\tif (khugepaged_test_exit(mm) || !vma) {\n\t\t/*\n\t\t * Make sure that if mm_users is reaching zero while\n\t\t * khugepaged runs here, khugepaged_exit will find\n\t\t * mm_slot not pointing to the exiting mm.\n\t\t */\n\t\tif (mm_slot->mm_node.next != &khugepaged_scan.mm_head) {\n\t\t\tkhugepaged_scan.mm_slot = list_entry(\n\t\t\t\tmm_slot->mm_node.next,\n\t\t\t\tstruct mm_slot, mm_node);\n\t\t\tkhugepaged_scan.address = 0;\n\t\t} else {\n\t\t\tkhugepaged_scan.mm_slot = NULL;\n\t\t\tkhugepaged_full_scans++;\n\t\t}\n\n\t\tcollect_mm_slot(mm_slot);\n\t}\n\n\treturn progress;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'mm: thp: fix /dev/zero MAP_PRIVATE and vm_flags cleanups\n\nThe huge_memory.c THP page fault was allowed to run if vm_ops was null\n(which would succeed for /dev/zero MAP_PRIVATE, as the f_op->mmap wouldn't\nsetup a special vma->vm_ops and it would fallback to regular anonymous\nmemory) but other THP logics weren't fully activated for vmas with vm_file\nnot NULL (/dev/zero has a not NULL vma->vm_file).\n\nSo this removes the vm_file checks so that /dev/zero also can safely use\nTHP (the other albeit safer approach to fix this bug would have been to\nprevent the THP initial page fault to run if vm_file was set).\n\nAfter removing the vm_file checks, this also makes huge_memory.c stricter\nin khugepaged for the DEBUG_VM=y case. It doesn't replace the vm_file\ncheck with a is_pfn_mapping check (but it keeps checking for VM_PFNMAP\nunder VM_BUG_ON) because for a is_cow_mapping() mapping VM_PFNMAP should\nonly be allowed to exist before the first page fault, and in turn when\nvma->anon_vma is null (so preventing khugepaged registration). So I tend\nto think the previous comment saying if vm_file was set, VM_PFNMAP might\nhave been set and we could still be registered in khugepaged (despite\nanon_vma was not NULL to be registered in khugepaged) was too paranoid.\nThe is_linear_pfn_mapping check is also I think superfluous (as described\nby comment) but under DEBUG_VM it is safe to stay.\n\nAddresses https://bugzilla.kernel.org/show_bug.cgi?id=33682\n\nSigned-off-by: Andrea Arcangeli \nReported-by: Caspar Zhang \nAcked-by: Mel Gorman \nAcked-by: Rik van Riel \nCc: \t\t[2.6.38.x]\nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline int mk_vhost_fdt_open(int id, unsigned int hash,\n struct session_request *sr)\n{\n int i;\n int fd;\n struct vhost_fdt_hash_table *ht = NULL;\n struct vhost_fdt_hash_chain *hc;\n\n if (config->fdt == MK_FALSE) {\n return open(sr->real_path.data, sr->file_info.flags_read_only);\n }\n\n ht = mk_vhost_fdt_table_lookup(id, sr->host_conf);\n if (mk_unlikely(!ht)) {\n return open(sr->real_path.data, sr->file_info.flags_read_only);\n }\n\n /* We got the hash table, now look around the chains array */\n hc = mk_vhost_fdt_chain_lookup(hash, ht);\n if (hc) {\n /* Increment the readers and return the shared FD */\n hc->readers++;\n return hc->fd;\n }\n\n /*\n * Get here means that no entry exists in the hash table for the\n * requested file descriptor and hash, we must try to open the file\n * and register the entry in the table.\n */\n fd = open(sr->real_path.data, sr->file_info.flags_read_only);\n if (fd == -1) {\n return -1;\n }\n\n /* If chains are full, just return the new FD, bad luck... */\n if (ht->av_slots <= 0) {\n return fd;\n }\n\n /* Register the new entry in an available slot */\n for (i = 0; i < VHOST_FDT_HASHTABLE_CHAINS; i++) {\n hc = &ht->chain[i];\n if (hc->fd == -1) {\n hc->fd = fd;\n hc->hash = hash;\n hc->readers++;\n ht->av_slots--;\n\n sr->vhost_fdt_id = id;\n sr->vhost_fdt_hash = hash;\n\n return fd;\n }\n }\n\n return -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Request: new request session flag to mark those files opened by FDT\n\nThis patch aims to fix a potential DDoS problem that can be caused\nin the server quering repetitive non-existent resources.\n\nWhen serving a static file, the core use Vhost FDT mechanism, but if\nit sends a static error page it does a direct open(2). When closing\nthe resources for the same request it was just calling mk_vhost_close()\nwhich did not clear properly the file descriptor.\n\nThis patch adds a new field on the struct session_request called 'fd_is_fdt',\nwhich contains MK_TRUE or MK_FALSE depending of how fd_file was opened.\n\nThanks to Matthew Daley for report and troubleshoot this\nproblem.\n\nSigned-off-by: Eduardo Silva '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: auth_select_file(struct sc_card *card, const struct sc_path *in_path,\n\t\t\t\t struct sc_file **file_out)\n{\n\tstruct sc_path path;\n\tstruct sc_file *tmp_file = NULL;\n\tsize_t offs, ii;\n\tint rv;\n\n\tLOG_FUNC_CALLED(card->ctx);\n\tassert(card != NULL && in_path != NULL);\n\n\tmemcpy(&path, in_path, sizeof(struct sc_path));\n\n\tsc_log(card->ctx, \"in_path; type=%d, path=%s, out %p\",\n\t\t\tin_path->type, sc_print_path(in_path), file_out);\n\tsc_log(card->ctx, \"current path; type=%d, path=%s\",\n\t\t\tauth_current_df->path.type, sc_print_path(&auth_current_df->path));\n\tif (auth_current_ef)\n\t\tsc_log(card->ctx, \"current file; type=%d, path=%s\",\n\t\t\t\tauth_current_ef->path.type, sc_print_path(&auth_current_ef->path));\n\n\tif (path.type == SC_PATH_TYPE_PARENT || path.type == SC_PATH_TYPE_FILE_ID) {\n\t\tsc_file_free(auth_current_ef);\n\t\tauth_current_ef = NULL;\n\n\t\trv = iso_ops->select_file(card, &path, &tmp_file);\n\t\tLOG_TEST_RET(card->ctx, rv, \"select file failed\");\n\t\tif (!tmp_file)\n\t\t\treturn SC_ERROR_OBJECT_NOT_FOUND;\n\n\t\tif (path.type == SC_PATH_TYPE_PARENT) {\n\t\t\tmemcpy(&tmp_file->path, &auth_current_df->path, sizeof(struct sc_path));\n\t\t\tif (tmp_file->path.len > 2)\n\t\t\t\ttmp_file->path.len -= 2;\n\n\t\t\tsc_file_free(auth_current_df);\n\t\t\tsc_file_dup(&auth_current_df, tmp_file);\n\t\t}\n\t\telse {\n\t\t\tif (tmp_file->type == SC_FILE_TYPE_DF) {\n\t\t\t\tsc_concatenate_path(&tmp_file->path, &auth_current_df->path, &path);\n\n\t\t\t\tsc_file_free(auth_current_df);\n\t\t\t\tsc_file_dup(&auth_current_df, tmp_file);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsc_file_free(auth_current_ef);\n\n\t\t\t\tsc_file_dup(&auth_current_ef, tmp_file);\n\t\t\t\tsc_concatenate_path(&auth_current_ef->path, &auth_current_df->path, &path);\n\t\t\t}\n\t\t}\n\t\tif (file_out)\n\t\t\tsc_file_dup(file_out, tmp_file);\n\n\t\tsc_file_free(tmp_file);\n\t}\n\telse if (path.type == SC_PATH_TYPE_DF_NAME) {\n\t\trv = iso_ops->select_file(card, &path, NULL);\n\t\tif (rv) {\n\t\t\tsc_file_free(auth_current_ef);\n\t\t\tauth_current_ef = NULL;\n\t\t}\n\t\tLOG_TEST_RET(card->ctx, rv, \"select file failed\");\n\t}\n\telse {\n\t\tfor (offs = 0; offs < path.len && offs < auth_current_df->path.len; offs += 2)\n\t\t\tif (path.value[offs] != auth_current_df->path.value[offs] ||\n\t\t\t\t\tpath.value[offs + 1] != auth_current_df->path.value[offs + 1])\n\t\t\t\tbreak;\n\n\t\tsc_log(card->ctx, \"offs %\"SC_FORMAT_LEN_SIZE_T\"u\", offs);\n\t\tif (offs && offs < auth_current_df->path.len) {\n\t\t\tsize_t deep = auth_current_df->path.len - offs;\n\n\t\t\tsc_log(card->ctx, \"deep %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t\t\t deep);\n\t\t\tfor (ii=0; iipath, sizeof(struct sc_path));\n\t\t\t\ttmp_path.type = SC_PATH_TYPE_PARENT;\n\n\t\t\t\trv = auth_select_file (card, &tmp_path, file_out);\n\t\t\t\tLOG_TEST_RET(card->ctx, rv, \"select file failed\");\n\t\t\t}\n\t\t}\n\n\t\tif (path.len - offs > 0) {\n\t\t\tstruct sc_path tmp_path;\n\n\t\t\tmemset(&tmp_path, 0, sizeof(struct sc_path));\n\t\t\ttmp_path.type = SC_PATH_TYPE_FILE_ID;\n\t\t\ttmp_path.len = 2;\n\n\t\t\tfor (ii=0; ii < path.len - offs; ii+=2) {\n\t\t\t\tmemcpy(tmp_path.value, path.value + offs + ii, 2);\n\n\t\t\t\trv = auth_select_file(card, &tmp_path, file_out);\n\t\t\t\tLOG_TEST_RET(card->ctx, rv, \"select file failed\");\n\t\t\t}\n\t\t}\n\t\telse if (path.len - offs == 0 && file_out) {\n\t\t\tif (sc_compare_path(&path, &auth_current_df->path))\n\t\t\t\tsc_file_dup(file_out, auth_current_df);\n\t\t\telse if (auth_current_ef)\n\t\t\t\tsc_file_dup(file_out, auth_current_ef);\n\t\t\telse\n\t\t\t\tLOG_TEST_RET(card->ctx, SC_ERROR_INTERNAL, \"No current EF\");\n\t\t}\n\t}\n\n\tLOG_FUNC_RETURN(card->ctx, 0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'fixed out of bounds reads\n\nThanks to Eric Sesterhenn from X41 D-SEC GmbH\nfor reporting and suggesting security fixes.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: authentic_process_fci(struct sc_card *card, struct sc_file *file,\n\t\t const unsigned char *buf, size_t buflen)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tsize_t taglen;\n\tint rv;\n\tunsigned ii;\n\tconst unsigned char *tag = NULL;\n\tunsigned char ops_DF[8] = {\n\t\tSC_AC_OP_CREATE, SC_AC_OP_DELETE, SC_AC_OP_CRYPTO, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF\n\t};\n\tunsigned char ops_EF[8] = {\n\t\tSC_AC_OP_READ, SC_AC_OP_DELETE, SC_AC_OP_UPDATE, SC_AC_OP_RESIZE, 0xFF, 0xFF, 0xFF, 0xFF\n\t};\n\n\tLOG_FUNC_CALLED(ctx);\n\n\ttag = sc_asn1_find_tag(card->ctx, buf, buflen, 0x6F, &taglen);\n\tif (tag != NULL) {\n\t\tsc_log(ctx, \" FCP length %\"SC_FORMAT_LEN_SIZE_T\"u\", taglen);\n\t\tbuf = tag;\n\t\tbuflen = taglen;\n\t}\n\n\ttag = sc_asn1_find_tag(card->ctx, buf, buflen, 0x62, &taglen);\n\tif (tag != NULL) {\n\t\tsc_log(ctx, \" FCP length %\"SC_FORMAT_LEN_SIZE_T\"u\", taglen);\n\t\tbuf = tag;\n\t\tbuflen = taglen;\n\t}\n\n\trv = iso_ops->process_fci(card, file, buf, buflen);\n\tLOG_TEST_RET(ctx, rv, \"ISO parse FCI failed\");\n\n\tif (!file->sec_attr_len) {\n\t\tsc_log_hex(ctx, \"ACLs not found in data\", buf, buflen);\n\t\tsc_log(ctx, \"Path:%s; Type:%X; PathType:%X\", sc_print_path(&file->path), file->type, file->path.type);\n\t\tif (file->path.type == SC_PATH_TYPE_DF_NAME || file->type == SC_FILE_TYPE_DF) {\n\t\t\tfile->type = SC_FILE_TYPE_DF;\n\t\t}\n\t\telse {\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, \"ACLs tag missing\");\n\t\t}\n\t}\n\n\tsc_log_hex(ctx, \"ACL data\", file->sec_attr, file->sec_attr_len);\n\tfor (ii = 0; ii < file->sec_attr_len / 2; ii++) {\n\t\tunsigned char op = file->type == SC_FILE_TYPE_DF ? ops_DF[ii] : ops_EF[ii];\n\t\tunsigned char acl = *(file->sec_attr + ii*2);\n\t\tunsigned char cred_id = *(file->sec_attr + ii*2 + 1);\n\t\tunsigned sc = acl * 0x100 + cred_id;\n\n\t\tsc_log(ctx, \"ACL(%i) op 0x%X, acl %X:%X\", ii, op, acl, cred_id);\n\t\tif (op == 0xFF)\n\t\t\t;\n\t\telse if (!acl && !cred_id)\n\t\t\tsc_file_add_acl_entry(file, op, SC_AC_NONE, 0);\n\t\telse if (acl == 0xFF)\n\t\t\tsc_file_add_acl_entry(file, op, SC_AC_NEVER, 0);\n\t\telse if (acl & AUTHENTIC_AC_SM_MASK)\n\t\t\tsc_file_add_acl_entry(file, op, SC_AC_SCB, sc);\n\t\telse if (cred_id)\n\t\t\tsc_file_add_acl_entry(file, op, SC_AC_CHV, cred_id);\n\t\telse\n\t\t\tsc_file_add_acl_entry(file, op, SC_AC_NEVER, 0);\n\t}\n\n\tLOG_FUNC_RETURN(ctx, 0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'fixed out of bounds reads\n\nThanks to Eric Sesterhenn from X41 D-SEC GmbH\nfor reporting and suggesting security fixes.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void DoRealForwardFFT(OpKernelContext* ctx, uint64* fft_shape,\n const Tensor& in, Tensor* out) {\n // Create the axes (which are always trailing).\n const auto axes = Eigen::ArrayXi::LinSpaced(FFTRank, 1, FFTRank);\n auto device = ctx->eigen_device();\n auto input = Tensor(in).flat_inner_dims();\n const auto input_dims = input.dimensions();\n\n // Slice input to fft_shape on its inner-most dimensions.\n Eigen::DSizes input_slice_sizes;\n input_slice_sizes[0] = input_dims[0];\n TensorShape temp_shape{input_dims[0]};\n for (int i = 1; i <= FFTRank; ++i) {\n input_slice_sizes[i] = fft_shape[i - 1];\n temp_shape.AddDim(fft_shape[i - 1]);\n }\n\n auto output = out->flat_inner_dims();\n const Eigen::DSizes zero_start_indices;\n\n // Compute the full FFT using a temporary tensor.\n Tensor temp;\n OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum::v(),\n temp_shape, &temp));\n auto full_fft = temp.flat_inner_dims();\n full_fft.device(device) =\n input.slice(zero_start_indices, input_slice_sizes)\n .template fft(axes);\n\n // Slice away the negative frequency components.\n output.device(device) =\n full_fft.slice(zero_start_indices, output.dimensions());\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617', 'CWE-703'], 'message': 'Prevent check fail in FFT\n\nPiperOrigin-RevId: 372031044\nChange-Id: I50994e3e8a5d1342d01bde80256f6bf2730ca299'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus Resize(TfLiteContext* context, TfLiteNode* node) {\n auto* params =\n reinterpret_cast(node->builtin_data);\n TF_LITE_ENSURE(context, NumInputs(node) == 2 || NumInputs(node) == 3);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* hash;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &hash));\n TF_LITE_ENSURE_EQ(context, NumDimensions(hash), 2);\n // Support up to 32 bits.\n TF_LITE_ENSURE(context, SizeOfDimension(hash, 1) <= 32);\n\n const TfLiteTensor* input;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 1, &input));\n TF_LITE_ENSURE(context, NumDimensions(input) >= 1);\n\n if (NumInputs(node) == 3) {\n const TfLiteTensor* weight;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 2, &weight));\n TF_LITE_ENSURE_EQ(context, NumDimensions(weight), 1);\n TF_LITE_ENSURE_EQ(context, SizeOfDimension(weight, 0),\n SizeOfDimension(input, 0));\n }\n\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));\n TfLiteIntArray* outputSize = TfLiteIntArrayCreate(1);\n switch (params->type) {\n case kTfLiteLshProjectionSparse:\n outputSize->data[0] = SizeOfDimension(hash, 0);\n break;\n case kTfLiteLshProjectionDense:\n outputSize->data[0] = SizeOfDimension(hash, 0) * SizeOfDimension(hash, 1);\n break;\n default:\n return kTfLiteError;\n }\n return context->ResizeTensor(context, output, outputSize);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-369'], 'message': 'Prevent division by 0 in LSH projection.\n\nPiperOrigin-RevId: 387225857\nChange-Id: Iaeb572a763618c64f503e0026f6dd9fd769bf50c'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void Compute(OpKernelContext* c) override {\n core::RefCountPtr v;\n OP_REQUIRES_OK(c, LookupResource(c, HandleFromInput(c, 0), &v));\n OP_REQUIRES_OK(c, EnsureSparseVariableAccess(c, v.get()));\n // NOTE: We hold the lock for the whole gather operation instead\n // of increasing the reference count of v->tensor() to avoid a\n // situation where a write to the same variable will see a\n // reference count greater than one and make a copy of the\n // (potentially very large) tensor buffer.\n tf_shared_lock ml(*v->mu());\n const Tensor& params = *v->tensor();\n const Tensor& indices = c->input(1);\n OP_REQUIRES(\n c, TensorShapeUtils::IsVectorOrHigher(params.shape()),\n errors::InvalidArgument(\"params must be at least 1 dimensional\"));\n\n // Check that we have enough index space\n const int64_t N = indices.NumElements();\n OP_REQUIRES(\n c, params.dim_size(0) <= std::numeric_limits::max(),\n errors::InvalidArgument(\"params.shape[0] too large for \",\n DataTypeString(DataTypeToEnum::v()),\n \" indexing: \", params.dim_size(0), \" > \",\n std::numeric_limits::max()));\n\n // The result shape is params.shape[:batch_dims] +\n // indices.shape[batch_dims:] + params.shape[batch_dims+1:].\n TensorShape result_shape;\n for (int i = 0; i < batch_dims_; ++i) {\n result_shape.AddDim(params.dim_size(i));\n }\n for (int i = batch_dims_; i < indices.dims(); ++i) {\n result_shape.AddDim(indices.dim_size(i));\n }\n for (int i = batch_dims_ + 1; i < params.dims(); ++i) {\n result_shape.AddDim(params.dim_size(i));\n }\n\n Tensor* out = nullptr;\n Tensor tmp;\n if (params.dtype() == DT_VARIANT) {\n tmp = Tensor(DT_VARIANT, result_shape);\n c->set_output(0, tmp);\n out = &tmp;\n } else {\n OP_REQUIRES_OK(c, c->allocate_output(0, result_shape, &out));\n }\n\n if (N > 0) {\n Tensor tmp_indices;\n\n // Points to the original or updated (if batch_dims is set) indices.\n const Tensor* op_indices = &indices;\n if (batch_dims_ > 0) {\n OP_REQUIRES_OK(c, c->allocate_temp(indices.dtype(), indices.shape(),\n &tmp_indices));\n functor::DenseUpdate copy_functor;\n copy_functor(c->eigen_device(), tmp_indices.flat(),\n indices.flat());\n\n AddBatchOffsets(&tmp_indices, params);\n op_indices = &tmp_indices;\n }\n\n int64_t gather_dim_size = 1;\n for (int idx = 0; idx <= batch_dims_; ++idx) {\n gather_dim_size *= params.dim_size(idx);\n }\n int64_t inner_size = 1;\n for (int i = batch_dims_ + 1; i < params.dims(); ++i) {\n inner_size *= params.dim_size(i);\n }\n auto params_flat = params.shaped({1, gather_dim_size, inner_size});\n const auto indices_flat = op_indices->flat();\n auto out_flat = out->shaped({1, N, out->NumElements() / N});\n\n functor::GatherFunctor functor;\n int64_t bad_i = functor(c, params_flat, indices_flat, out_flat);\n\n OP_REQUIRES(\n c, bad_i < 0,\n errors::InvalidArgument(\n \"indices\", SliceDebugString(indices.shape(), bad_i), \" = \",\n indices_flat(bad_i), \" is not in [0, \", params.dim_size(0), \")\"));\n }\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-369'], 'message': 'Prevent heap oob access in `resource_variable_ops.cc`\n\nPiperOrigin-RevId: 387936433\nChange-Id: I9e71ddaa8dbd51ec6afbf163a6b3b591f193b4f6'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: R_API int r_sys_cmd_str_full(const char *cmd, const char *input, char **output, int *len, char **sterr) {\n\tchar *mysterr = NULL;\n\tif (!sterr) {\n\t\tsterr = &mysterr;\n\t}\n\tchar buffer[1024], *outputptr = NULL;\n\tchar *inputptr = (char *)input;\n\tint pid, bytes = 0, status;\n\tint sh_in[2], sh_out[2], sh_err[2];\n\n\tif (len) {\n\t\t*len = 0;\n\t}\n\tif (pipe (sh_in)) {\n\t\treturn false;\n\t}\n\tif (output) {\n\t\tif (pipe (sh_out)) {\n\t\t\tclose (sh_in[0]);\n\t\t\tclose (sh_in[1]);\n\t\t\tclose (sh_out[0]);\n\t\t\tclose (sh_out[1]);\n\t\t\treturn false;\n\t\t}\n\t}\n\tif (pipe (sh_err)) {\n\t\tclose (sh_in[0]);\n\t\tclose (sh_in[1]);\n\t\treturn false;\n\t}\n\n\tswitch ((pid = r_sys_fork ())) {\n\tcase -1:\n\t\treturn false;\n\tcase 0:\n\t\tdup2 (sh_in[0], 0);\n\t\tclose (sh_in[0]);\n\t\tclose (sh_in[1]);\n\t\tif (output) {\n\t\t\tdup2 (sh_out[1], 1);\n\t\t\tclose (sh_out[0]);\n\t\t\tclose (sh_out[1]);\n\t\t}\n\t\tif (sterr) {\n\t\t\tdup2 (sh_err[1], 2);\n\t\t} else {\n\t\t\tclose (2);\n\t\t}\n\t\tclose (sh_err[0]);\n\t\tclose (sh_err[1]);\n\t\texit (r_sandbox_system (cmd, 0));\n\tdefault:\n\t\toutputptr = strdup (\"\");\n\t\tif (!outputptr) {\n\t\t\treturn false;\n\t\t}\n\t\tif (sterr) {\n\t\t\t*sterr = strdup (\"\");\n\t\t\tif (!*sterr) {\n\t\t\t\tfree (outputptr);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tif (output) {\n\t\t\tclose (sh_out[1]);\n\t\t}\n\t\tclose (sh_err[1]);\n\t\tclose (sh_in[0]);\n\t\tif (!inputptr || !*inputptr) {\n\t\t\tclose (sh_in[1]);\n\t\t}\n\t\t// we should handle broken pipes somehow better\n\t\tr_sys_signal (SIGPIPE, SIG_IGN);\n\t\tfor (;;) {\n\t\t\tfd_set rfds, wfds;\n\t\t\tint nfd;\n\t\t\tFD_ZERO (&rfds);\n\t\t\tFD_ZERO (&wfds);\n\t\t\tif (output) {\n\t\t\t\tFD_SET (sh_out[0], &rfds);\n\t\t\t}\n\t\t\tif (sterr) {\n\t\t\t\tFD_SET (sh_err[0], &rfds);\n\t\t\t}\n\t\t\tif (inputptr && *inputptr) {\n\t\t\t\tFD_SET (sh_in[1], &wfds);\n\t\t\t}\n\t\t\tmemset (buffer, 0, sizeof (buffer));\n\t\t\tnfd = select (sh_err[0] + 1, &rfds, &wfds, NULL, NULL);\n\t\t\tif (nfd < 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (output && FD_ISSET (sh_out[0], &rfds)) {\n\t\t\t\tif (!(bytes = read (sh_out[0], buffer, sizeof (buffer)-1))) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbuffer[sizeof (buffer) - 1] = '\\0';\n\t\t\t\tif (len) {\n\t\t\t\t\t*len += bytes;\n\t\t\t\t}\n\t\t\t\toutputptr = r_str_append (outputptr, buffer);\n\t\t\t} else if (FD_ISSET (sh_err[0], &rfds) && sterr) {\n\t\t\t\tif (!read (sh_err[0], buffer, sizeof (buffer)-1)) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbuffer[sizeof (buffer) - 1] = '\\0';\n\t\t\t\t*sterr = r_str_append (*sterr, buffer);\n\t\t\t} else if (FD_ISSET (sh_in[1], &wfds) && inputptr && *inputptr) {\n\t\t\t\tint inputptr_len = strlen (inputptr);\n\t\t\t\tbytes = write (sh_in[1], inputptr, inputptr_len);\n\t\t\t\tif (bytes != inputptr_len) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tinputptr += bytes;\n\t\t\t\tif (!*inputptr) {\n\t\t\t\t\tclose (sh_in[1]);\n\t\t\t\t\t/* If neither stdout nor stderr should be captured,\n\t\t\t\t\t * abort now - nothing more to do for select(). */\n\t\t\t\t\tif (!output && !sterr) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (output) {\n\t\t\tclose (sh_out[0]);\n\t\t}\n\t\tclose (sh_err[0]);\n\t\tclose (sh_in[1]);\n\t\twaitpid (pid, &status, 0);\n\t\tbool ret = true;\n\t\tif (status) {\n\t\t\t// char *escmd = r_str_escape (cmd);\n\t\t\t// eprintf (\"error code %d (%s): %s\\n\", WEXITSTATUS (status), escmd, *sterr);\n\t\t\t// eprintf (\"(%s)\\n\", output);\n\t\t\t// eprintf (\"%s: failed command '%s'\\n\", __func__, escmd);\n\t\t\t// free (escmd);\n\t\t\tret = false;\n\t\t}\n\n\t\tif (output) {\n\t\t\t*output = outputptr;\n\t\t} else {\n\t\t\tfree (outputptr);\n\t\t}\n\t\treturn ret;\n\t}\n\treturn false;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-78'], 'message': 'Fix command injection on PDB download (#16966)\n\n* Fix r_sys_mkdirp with absolute path on Windows\r\n* Fix build with --with-openssl\r\n* Use RBuffer in r_socket_http_answer()\r\n* r_socket_http_answer: Fix read for big responses\r\n* Implement r_str_escape_sh()\r\n* Cleanup r_socket_connect() on Windows\r\n* Fix socket being created without a protocol\r\n* Fix socket connect with SSL ##socket\r\n* Use select() in r_socket_ready()\r\n* Fix read failing if received only protocol answer\r\n* Fix double-free\r\n* r_socket_http_get: Fail if req. SSL with no support\r\n* Follow redirects in r_socket_http_answer()\r\n* Fix r_socket_http_get result length with R2_CURL=1\r\n* Also follow redirects\r\n* Avoid using curl for downloading PDBs\r\n* Use r_socket_http_get() on UNIXs\r\n* Use WinINet API on Windows for r_socket_http_get()\r\n* Fix command injection\r\n* Fix r_sys_cmd_str_full output for binary data\r\n* Validate GUID on PDB download\r\n* Pass depth to socket_http_get_recursive()\r\n* Remove 'r_' and '__' from static function names\r\n* Fix is_valid_guid\r\n* Fix for comments'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool all_tests () {\n\tmu_run_test (test_r_str_newf);\n\tmu_run_test (test_r_str_replace_char_once);\n\tmu_run_test (test_r_str_replace_char);\n\tmu_run_test (test_r_str_replace);\n\tmu_run_test (test_r_str_bits64);\n\tmu_run_test (test_r_str_rwx);\n\tmu_run_test (test_r_str_rwx_i);\n\tmu_run_test (test_r_str_bool);\n\tmu_run_test (test_r_str_trim);\n\tmu_run_test (test_r_str_case);\n\tmu_run_test (test_r_str_split);\n\tmu_run_test (test_r_str_tokenize);\n\tmu_run_test (test_r_str_char_count);\n\tmu_run_test (test_r_str_word_count);\n\tmu_run_test (test_r_str_ichr);\n\tmu_run_test (test_r_str_lchr);\n\tmu_run_test (test_r_sub_str_lchr);\n\tmu_run_test (test_r_sub_str_rchr);\n\tmu_run_test (test_r_str_rchr);\n\tmu_run_test (test_r_str_ansi_len);\n\tmu_run_test (test_r_str_len_utf8_ansi);\n\tmu_run_test (test_r_str_utf8_charsize);\n\tmu_run_test (test_r_str_utf8_charsize_prev);\n\tmu_run_test (test_r_str_sanitize_sdb_key);\n\tmu_run_test (test_r_str_unescape);\n\tmu_run_test (test_r_str_constpool);\n\tmu_run_test (test_r_str_format_msvc_argv);\n\tmu_run_test (test_r_str_str_xy);\n\treturn tests_passed != tests_run;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-78'], 'message': 'Fix command injection on PDB download (#16966)\n\n* Fix r_sys_mkdirp with absolute path on Windows\r\n* Fix build with --with-openssl\r\n* Use RBuffer in r_socket_http_answer()\r\n* r_socket_http_answer: Fix read for big responses\r\n* Implement r_str_escape_sh()\r\n* Cleanup r_socket_connect() on Windows\r\n* Fix socket being created without a protocol\r\n* Fix socket connect with SSL ##socket\r\n* Use select() in r_socket_ready()\r\n* Fix read failing if received only protocol answer\r\n* Fix double-free\r\n* r_socket_http_get: Fail if req. SSL with no support\r\n* Follow redirects in r_socket_http_answer()\r\n* Fix r_socket_http_get result length with R2_CURL=1\r\n* Also follow redirects\r\n* Avoid using curl for downloading PDBs\r\n* Use r_socket_http_get() on UNIXs\r\n* Use WinINet API on Windows for r_socket_http_get()\r\n* Fix command injection\r\n* Fix r_sys_cmd_str_full output for binary data\r\n* Validate GUID on PDB download\r\n* Pass depth to socket_http_get_recursive()\r\n* Remove 'r_' and '__' from static function names\r\n* Fix is_valid_guid\r\n* Fix for comments'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int __socket_slurp (RSocket *s, ut8 *buf, int bufsz) {\n\tint i;\n\tint chsz = 1;\n\t// r_socket_block_time (s, 1, 1, 0);\n\tif (r_socket_read_block (s, (ut8 *) buf, 1) != 1) {\n\t\treturn 0;\n\t}\n\tfor (i = 1; i < bufsz; i += chsz) {\n\t\tbuf[i] =0;\n\t\tr_socket_block_time (s, 1, 0, 1000);\n\t\tint olen = r_socket_read_block (s, (ut8 *) buf + i , chsz);\n\t\tif (olen != chsz) {\n\t\t\tbuf[i] = 0;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn i;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-78'], 'message': 'Fix command injection on PDB download (#16966)\n\n* Fix r_sys_mkdirp with absolute path on Windows\r\n* Fix build with --with-openssl\r\n* Use RBuffer in r_socket_http_answer()\r\n* r_socket_http_answer: Fix read for big responses\r\n* Implement r_str_escape_sh()\r\n* Cleanup r_socket_connect() on Windows\r\n* Fix socket being created without a protocol\r\n* Fix socket connect with SSL ##socket\r\n* Use select() in r_socket_ready()\r\n* Fix read failing if received only protocol answer\r\n* Fix double-free\r\n* r_socket_http_get: Fail if req. SSL with no support\r\n* Follow redirects in r_socket_http_answer()\r\n* Fix r_socket_http_get result length with R2_CURL=1\r\n* Also follow redirects\r\n* Avoid using curl for downloading PDBs\r\n* Use r_socket_http_get() on UNIXs\r\n* Use WinINet API on Windows for r_socket_http_get()\r\n* Fix command injection\r\n* Fix r_sys_cmd_str_full output for binary data\r\n* Validate GUID on PDB download\r\n* Pass depth to socket_http_get_recursive()\r\n* Remove 'r_' and '__' from static function names\r\n* Fix is_valid_guid\r\n* Fix for comments'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: unique_ptr IOBuf::takeOwnership(\n void* buf,\n std::size_t capacity,\n std::size_t offset,\n std::size_t length,\n FreeFunction freeFn,\n void* userData,\n bool freeOnError,\n TakeOwnershipOption option) {\n // do not allow only user data without a freeFn\n // since we use that for folly::sizedFree\n\n DCHECK(\n !userData || (userData && freeFn) ||\n (userData && !freeFn && (option == TakeOwnershipOption::STORE_SIZE)));\n\n HeapFullStorage* storage = nullptr;\n auto rollback = makeGuard([&] {\n if (storage) {\n free(storage);\n }\n takeOwnershipError(freeOnError, buf, freeFn, userData);\n });\n\n size_t requiredStorage = sizeof(HeapFullStorage);\n size_t mallocSize = goodMallocSize(requiredStorage);\n storage = static_cast(checkedMalloc(mallocSize));\n\n new (&storage->hs.prefix)\n HeapPrefix(kIOBufInUse | kSharedInfoInUse, mallocSize);\n new (&storage->shared)\n SharedInfo(freeFn, userData, true /*useHeapFullStorage*/);\n\n auto result = unique_ptr(new (&storage->hs.buf) IOBuf(\n InternalConstructor(),\n packFlagsAndSharedInfo(0, &storage->shared),\n static_cast(buf),\n capacity,\n static_cast(buf) + offset,\n length));\n\n rollback.dismiss();\n\n if (io_buf_alloc_cb) {\n io_buf_alloc_cb(storage, mallocSize);\n if (userData && !freeFn && (option == TakeOwnershipOption::STORE_SIZE)) {\n // Even though we did not allocate the buffer, call io_buf_alloc_cb()\n // since we will call io_buf_free_cb() on destruction, and we want these\n // calls to be 1:1.\n io_buf_alloc_cb(buf, capacity);\n }\n }\n\n return result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': '[folly] Add additional overflow checks to IOBuf - CVE-2021-24036\n\nSummary:\nAs per title\n\nCVE-2021-24036\n\nReviewed By: jan\n\nDifferential Revision: D27938605\n\nfbshipit-source-id: 7481c54ae6fbb7b67b15b3631d5357c2f7043f9c'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void Rp_test(js_State *J)\n{\n\tjs_Regexp *re;\n\tconst char *text;\n\tint opts;\n\tResub m;\n\n\tre = js_toregexp(J, 0);\n\ttext = js_tostring(J, 1);\n\n\topts = 0;\n\tif (re->flags & JS_REGEXP_G) {\n\t\tif (re->last > strlen(text)) {\n\t\t\tre->last = 0;\n\t\t\tjs_pushboolean(J, 0);\n\t\t\treturn;\n\t\t}\n\t\tif (re->last > 0) {\n\t\t\ttext += re->last;\n\t\t\topts |= REG_NOTBOL;\n\t\t}\n\t}\n\n\tif (!js_regexec(re->prog, text, &m, opts)) {\n\t\tif (re->flags & JS_REGEXP_G)\n\t\t\tre->last = re->last + (m.sub[0].ep - text);\n\t\tjs_pushboolean(J, 1);\n\t\treturn;\n\t}\n\n\tif (re->flags & JS_REGEXP_G)\n\t\tre->last = 0;\n\n\tjs_pushboolean(J, 0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-674', 'CWE-787'], 'message': 'Bug 700937: Limit recursion in regexp matcher.\n\nAlso handle negative return code as an error in the JS bindings.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: sixel_allocator_calloc(\n sixel_allocator_t /* in */ *allocator, /* allocator object */\n size_t /* in */ nelm, /* number of elements */\n size_t /* in */ elsize) /* size of element */\n{\n /* precondition */\n assert(allocator);\n assert(allocator->fn_calloc);\n\n return allocator->fn_calloc(nelm, elsize);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Introduce SIXEL_ALLOCATE_BYTES_MAX macro and limit allocation size to 128MB(#74)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: GF_Err gf_isom_get_text_description(GF_ISOFile *movie, u32 trackNumber, u32 descriptionIndex, GF_TextSampleDescriptor **out_desc)\n{\n\tGF_TrackBox *trak;\n\tu32 i;\n\tBool is_qt_text = GF_FALSE;\n\tGF_Tx3gSampleEntryBox *txt;\n\n\tif (!descriptionIndex || !out_desc) return GF_BAD_PARAM;\n\n\ttrak = gf_isom_get_track_from_file(movie, trackNumber);\n\tif (!trak || !trak->Media) return GF_BAD_PARAM;\n\n\tswitch (trak->Media->handler->handlerType) {\n\tcase GF_ISOM_MEDIA_TEXT:\n\tcase GF_ISOM_MEDIA_SUBT:\n\t\tbreak;\n\tdefault:\n\t\treturn GF_BAD_PARAM;\n\t}\n\n\ttxt = (GF_Tx3gSampleEntryBox*)gf_list_get(trak->Media->information->sampleTable->SampleDescription->child_boxes, descriptionIndex - 1);\n\tif (!txt) return GF_BAD_PARAM;\n\tswitch (txt->type) {\n\tcase GF_ISOM_BOX_TYPE_TX3G:\n\t\tbreak;\n\tcase GF_ISOM_BOX_TYPE_TEXT:\n\t\tis_qt_text = GF_TRUE;\n\t\tbreak;\n\tdefault:\n\t\treturn GF_BAD_PARAM;\n\t}\n\n\t(*out_desc) = (GF_TextSampleDescriptor *) gf_odf_desc_new(GF_ODF_TX3G_TAG);\n\tif (! (*out_desc) ) return GF_OUT_OF_MEM;\n\t(*out_desc)->back_color = txt->back_color;\n\t(*out_desc)->default_pos = txt->default_box;\n\t(*out_desc)->default_style = txt->default_style;\n\t(*out_desc)->displayFlags = txt->displayFlags;\n\t(*out_desc)->vert_justif = txt->vertical_justification;\n\t(*out_desc)->horiz_justif = txt->horizontal_justification;\n\tif (is_qt_text) {\n\t\tGF_TextSampleEntryBox *qt_txt = (GF_TextSampleEntryBox *) txt;\n\t\tif (qt_txt->textName) {\n\t\t\t(*out_desc)->font_count = 1;\n\t\t\t(*out_desc)->fonts = (GF_FontRecord *) gf_malloc(sizeof(GF_FontRecord));\n\t\t\t(*out_desc)->fonts[0].fontName = gf_strdup(qt_txt->textName);\n\t\t}\n\t} else {\n\t\t(*out_desc)->font_count = txt->font_table->entry_count;\n\t\t(*out_desc)->fonts = (GF_FontRecord *) gf_malloc(sizeof(GF_FontRecord) * txt->font_table->entry_count);\n\t\tfor (i=0; ifont_table->entry_count; i++) {\n\t\t\t(*out_desc)->fonts[i].fontID = txt->font_table->fonts[i].fontID;\n\t\t\tif (txt->font_table->fonts[i].fontName)\n\t\t\t\t(*out_desc)->fonts[i].fontName = gf_strdup(txt->font_table->fonts[i].fontName);\n\t\t}\n\t}\n\treturn GF_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'fixed #1768'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static struct sk_buff *udp6_ufo_fragment(struct sk_buff *skb, u32 features)\n{\n\tstruct sk_buff *segs = ERR_PTR(-EINVAL);\n\tunsigned int mss;\n\tunsigned int unfrag_ip6hlen, unfrag_len;\n\tstruct frag_hdr *fptr;\n\tu8 *mac_start, *prevhdr;\n\tu8 nexthdr;\n\tu8 frag_hdr_sz = sizeof(struct frag_hdr);\n\tint offset;\n\t__wsum csum;\n\n\tmss = skb_shinfo(skb)->gso_size;\n\tif (unlikely(skb->len <= mss))\n\t\tgoto out;\n\n\tif (skb_gso_ok(skb, features | NETIF_F_GSO_ROBUST)) {\n\t\t/* Packet is from an untrusted source, reset gso_segs. */\n\t\tint type = skb_shinfo(skb)->gso_type;\n\n\t\tif (unlikely(type & ~(SKB_GSO_UDP | SKB_GSO_DODGY) ||\n\t\t\t !(type & (SKB_GSO_UDP))))\n\t\t\tgoto out;\n\n\t\tskb_shinfo(skb)->gso_segs = DIV_ROUND_UP(skb->len, mss);\n\n\t\tsegs = NULL;\n\t\tgoto out;\n\t}\n\n\t/* Do software UFO. Complete and fill in the UDP checksum as HW cannot\n\t * do checksum of UDP packets sent as multiple IP fragments.\n\t */\n\toffset = skb->csum_start - skb_headroom(skb);\n\tcsum = skb_checksum(skb, offset, skb->len- offset, 0);\n\toffset += skb->csum_offset;\n\t*(__sum16 *)(skb->data + offset) = csum_fold(csum);\n\tskb->ip_summed = CHECKSUM_NONE;\n\n\t/* Check if there is enough headroom to insert fragment header. */\n\tif ((skb_headroom(skb) < frag_hdr_sz) &&\n\t pskb_expand_head(skb, frag_hdr_sz, 0, GFP_ATOMIC))\n\t\tgoto out;\n\n\t/* Find the unfragmentable header and shift it left by frag_hdr_sz\n\t * bytes to insert fragment header.\n\t */\n\tunfrag_ip6hlen = ip6_find_1stfragopt(skb, &prevhdr);\n\tnexthdr = *prevhdr;\n\t*prevhdr = NEXTHDR_FRAGMENT;\n\tunfrag_len = skb_network_header(skb) - skb_mac_header(skb) +\n\t\t unfrag_ip6hlen;\n\tmac_start = skb_mac_header(skb);\n\tmemmove(mac_start-frag_hdr_sz, mac_start, unfrag_len);\n\n\tskb->mac_header -= frag_hdr_sz;\n\tskb->network_header -= frag_hdr_sz;\n\n\tfptr = (struct frag_hdr *)(skb_network_header(skb) + unfrag_ip6hlen);\n\tfptr->nexthdr = nexthdr;\n\tfptr->reserved = 0;\n\tipv6_select_ident(fptr);\n\n\t/* Fragment the skb. ipv6 header and the remaining fields of the\n\t * fragment header are updated in ipv6_gso_segment()\n\t */\n\tsegs = skb_segment(skb, features);\n\nout:\n\treturn segs;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'ipv6: udp: fix the wrong headroom check\n\nAt this point, skb->data points to skb_transport_header.\nSo, headroom check is wrong.\n\nFor some case:bridge(UFO is on) + eth device(UFO is off),\nthere is no enough headroom for IPv6 frag head.\nBut headroom check is always false.\n\nThis will bring about data be moved to there prior to skb->head,\nwhen adding IPv6 frag header to skb.\n\nSigned-off-by: Shan Wei \nAcked-by: Herbert Xu \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void faad_resetbits(bitfile *ld, int bits)\n{\n uint32_t tmp;\n int words = bits >> 5;\n int remainder = bits & 0x1F;\n\n ld->bytes_left = ld->buffer_size - words*4;\n\n if (ld->bytes_left >= 4)\n {\n tmp = getdword(&ld->start[words]);\n ld->bytes_left -= 4;\n } else {\n tmp = getdword_n(&ld->start[words], ld->bytes_left);\n ld->bytes_left = 0;\n }\n ld->bufa = tmp;\n\n if (ld->bytes_left >= 4)\n {\n tmp = getdword(&ld->start[words+1]);\n ld->bytes_left -= 4;\n } else {\n tmp = getdword_n(&ld->start[words+1], ld->bytes_left);\n ld->bytes_left = 0;\n }\n ld->bufb = tmp;\n\n ld->bits_left = 32 - remainder;\n ld->tail = &ld->start[words+2];\n\n /* recheck for reading too many bytes */\n ld->error = 0;\n// if (ld->bytes_left == 0)\n// ld->no_more_reading = 1;\n// if (ld->bytes_left < 0)\n// ld->error = 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix a couple buffer overflows\n\nhttps://hackerone.com/reports/502816\nhttps://hackerone.com/reports/507858\n\nhttps://github.com/videolan/vlc/blob/master/contrib/src/faad2/faad2-fix-overflows.patch'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static ssize_t available_instances_show(struct mdev_type *mtype,\n\t\t\t\t\tstruct mdev_type_attribute *attr,\n\t\t\t\t\tchar *buf)\n{\n\tconst struct mbochs_type *type =\n\t\t&mbochs_types[mtype_get_type_group_id(mtype)];\n\tint count = (max_mbytes - mbochs_used_mbytes) / type->mbytes;\n\n\treturn sprintf(buf, \"%d\\n\", count);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-401'], 'message': 'vfio/mbochs: Fix missing error unwind of mbochs_used_mbytes\n\nConvert mbochs to use an atomic scheme for this like mtty was changed\ninto. The atomic fixes various race conditions with probing. Add the\nmissing error unwind. Also add the missing kfree of mdev_state->pages.\n\nFixes: 681c1615f891 (\"vfio/mbochs: Convert to use vfio_register_group_dev()\")\nReported-by: Cornelia Huck \nCo-developed-by: Alex Williamson \nReviewed-by: Christoph Hellwig \nSigned-off-by: Jason Gunthorpe \nReviewed-by: Cornelia Huck \nLink: https://lore.kernel.org/r/2-v4-9ea22c5e6afb+1adf-vfio_reflck_jgg@nvidia.com\nSigned-off-by: Alex Williamson '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static CURLcode imap_parse_url_path(struct connectdata *conn)\n{\n /* the imap struct is already inited in imap_connect() */\n struct imap_conn *imapc = &conn->proto.imapc;\n struct SessionHandle *data = conn->data;\n const char *path = data->state.path;\n int len;\n\n if(!*path)\n path = \"INBOX\";\n\n /* url decode the path and use this mailbox */\n imapc->mailbox = curl_easy_unescape(data, path, 0, &len);\n if(!imapc->mailbox)\n return CURLE_OUT_OF_MEMORY;\n\n return CURLE_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-89'], 'message': 'URL sanitize: reject URLs containing bad data\n\nProtocols (IMAP, POP3 and SMTP) that use the path part of a URL in a\ndecoded manner now use the new Curl_urldecode() function to reject URLs\nwith embedded control codes (anything that is or decodes to a byte value\nless than 32).\n\nURLs containing such codes could easily otherwise be used to do harm and\nallow users to do unintended actions with otherwise innocent tools and\napplications. Like for example using a URL like\npop3://pop3.example.com/1%0d%0aDELE%201 when the app wants a URL to get\na mail and instead this would delete one.\n\nThis flaw is considered a security vulnerability: CVE-2012-0036\n\nSecurity advisory at: http://curl.haxx.se/docs/adv_20120124.html\n\nReported by: Dan Fandrich'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void Compute(OpKernelContext* const context) override {\n core::RefCountPtr resource;\n // Get the resource.\n OP_REQUIRES_OK(context, LookupResource(context, HandleFromInput(context, 0),\n &resource));\n\n // Get the inputs.\n OpInputList bucketized_features_list;\n OP_REQUIRES_OK(context, context->input_list(\"bucketized_features\",\n &bucketized_features_list));\n std::vector::ConstMatrix> bucketized_features;\n bucketized_features.reserve(bucketized_features_list.size());\n ConvertVectorsToMatrices(bucketized_features_list, bucketized_features);\n const int batch_size = bucketized_features[0].dimension(0);\n\n const Tensor* cached_tree_ids_t;\n OP_REQUIRES_OK(context,\n context->input(\"cached_tree_ids\", &cached_tree_ids_t));\n const auto cached_tree_ids = cached_tree_ids_t->vec();\n\n const Tensor* cached_node_ids_t;\n OP_REQUIRES_OK(context,\n context->input(\"cached_node_ids\", &cached_node_ids_t));\n const auto cached_node_ids = cached_node_ids_t->vec();\n\n // Allocate outputs.\n Tensor* output_partial_logits_t = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(\"partial_logits\",\n {batch_size, logits_dimension_},\n &output_partial_logits_t));\n auto output_partial_logits = output_partial_logits_t->matrix();\n\n Tensor* output_tree_ids_t = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(\"tree_ids\", {batch_size},\n &output_tree_ids_t));\n auto output_tree_ids = output_tree_ids_t->vec();\n\n Tensor* output_node_ids_t = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(\"node_ids\", {batch_size},\n &output_node_ids_t));\n auto output_node_ids = output_node_ids_t->vec();\n\n // Indicate that the latest tree was used.\n const int32 latest_tree = resource->num_trees() - 1;\n\n if (latest_tree < 0) {\n // Ensemble was empty. Output the very first node.\n output_node_ids.setZero();\n output_tree_ids = cached_tree_ids;\n // All the predictions are zeros.\n output_partial_logits.setZero();\n } else {\n output_tree_ids.setConstant(latest_tree);\n auto do_work = [&resource, &bucketized_features, &cached_tree_ids,\n &cached_node_ids, &output_partial_logits,\n &output_node_ids, latest_tree,\n this](int32 start, int32 end) {\n for (int32 i = start; i < end; ++i) {\n int32 tree_id = cached_tree_ids(i);\n int32 node_id = cached_node_ids(i);\n std::vector partial_tree_logits(logits_dimension_, 0.0);\n\n if (node_id >= 0) {\n // If the tree was pruned, returns the node id into which the\n // current_node_id was pruned, as well the correction of the cached\n // logit prediction.\n resource->GetPostPruneCorrection(tree_id, node_id, &node_id,\n &partial_tree_logits);\n // Logic in the loop adds the cached node value again if it is a\n // leaf. If it is not a leaf anymore we need to subtract the old\n // node's value. The following logic handles both of these cases.\n const auto& node_logits = resource->node_value(tree_id, node_id);\n if (!node_logits.empty()) {\n DCHECK_EQ(node_logits.size(), logits_dimension_);\n for (int32 j = 0; j < logits_dimension_; ++j) {\n partial_tree_logits[j] -= node_logits[j];\n }\n }\n } else {\n // No cache exists, start from the very first node.\n node_id = 0;\n }\n std::vector partial_all_logits(logits_dimension_, 0.0);\n while (true) {\n if (resource->is_leaf(tree_id, node_id)) {\n const auto& leaf_logits = resource->node_value(tree_id, node_id);\n DCHECK_EQ(leaf_logits.size(), logits_dimension_);\n // Tree is done\n const float tree_weight = resource->GetTreeWeight(tree_id);\n for (int32 j = 0; j < logits_dimension_; ++j) {\n partial_all_logits[j] +=\n tree_weight * (partial_tree_logits[j] + leaf_logits[j]);\n partial_tree_logits[j] = 0;\n }\n // Stop if it was the latest tree.\n if (tree_id == latest_tree) {\n break;\n }\n // Move onto other trees.\n ++tree_id;\n node_id = 0;\n } else {\n node_id =\n resource->next_node(tree_id, node_id, i, bucketized_features);\n }\n }\n output_node_ids(i) = node_id;\n for (int32 j = 0; j < logits_dimension_; ++j) {\n output_partial_logits(i, j) = partial_all_logits[j];\n }\n }\n };\n // 30 is the magic number. The actual value might be a function of (the\n // number of layers) * (cpu cycles spent on each layer), but this value\n // would work for many cases. May be tuned later.\n const int64 cost = 30;\n thread::ThreadPool* const worker_threads =\n context->device()->tensorflow_cpu_worker_threads()->workers;\n Shard(worker_threads->NumThreads(), worker_threads, batch_size,\n /*cost_per_unit=*/cost, do_work);\n }\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-197'], 'message': 'Prevent integer truncation from 64 to 32 bits.\n\nThe `tensorflow::Shard` functions last argument must be a 2 argument function where both arguments are `int64` (`long long`, 64 bits). However, there are usages where code passes in a function where arguments are `int` or `int32` (32 bits). In these cases, it is possible that the integer truncation would later cause a segfault or other unexpected behavior.\n\nPiperOrigin-RevId: 332560414\nChange-Id: Ief649406babc8d4f60b3e7a9d573cbcc5ce5b767'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int lookup(struct sip_msg* _m, char* _t, char* _f, char* _s)\n{\n\tunsigned int flags;\n\turecord_t* r;\n\tstr aor, uri;\n\tucontact_t* ptr,*it;\n\tint res;\n\tint ret;\n\tstr path_dst;\n\tstr flags_s;\n\tpv_value_t val;\n\tint_str istr;\n\tstr sip_instance = {0,0},call_id = {0,0};\n\n\tflags = 0;\n\tif (_f && _f[0]!=0) {\n\t\tif (fixup_get_svalue( _m, (gparam_p)_f, &flags_s)!=0) {\n\t\t\tLM_ERR(\"invalid owner uri parameter\");\n\t\t\treturn -1;\n\t\t}\n\t\tfor( res=0 ; res< flags_s.len ; res++ ) {\n\t\t\tswitch (flags_s.s[res]) {\n\t\t\t\tcase 'm': flags |= REG_LOOKUP_METHODFILTER_FLAG; break;\n\t\t\t\tcase 'b': flags |= REG_LOOKUP_NOBRANCH_FLAG; break;\n\t\t\t\tdefault: LM_WARN(\"unsuported flag %c \\n\",flags_s.s[res]);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (_s) {\n\t\tif (pv_get_spec_value( _m, (pv_spec_p)_s, &val)!=0) {\n\t\t\tLM_ERR(\"failed to get PV value\\n\");\n\t\t\treturn -1;\n\t\t}\n\t\tif ( (val.flags&PV_VAL_STR)==0 ) {\n\t\t\tLM_ERR(\"PV vals is not string\\n\");\n\t\t\treturn -1;\n\t\t}\n\t\turi = val.rs;\n\t} else {\n\t\tif (_m->new_uri.s) uri = _m->new_uri;\n\t\telse uri = _m->first_line.u.request.uri;\n\t}\n\n\tif (extract_aor(&uri, &aor,&sip_instance,&call_id) < 0) {\n\t\tLM_ERR(\"failed to extract address of record\\n\");\n\t\treturn -3;\n\t}\n\n\tget_act_time();\n\n\tul.lock_udomain((udomain_t*)_t, &aor);\n\tres = ul.get_urecord((udomain_t*)_t, &aor, &r);\n\tif (res > 0) {\n\t\tLM_DBG(\"'%.*s' Not found in usrloc\\n\", aor.len, ZSW(aor.s));\n\t\tul.unlock_udomain((udomain_t*)_t, &aor);\n\t\treturn -1;\n\t}\n\n\tptr = r->contacts;\n\tret = -1;\n\t/* look first for an un-expired and suported contact */\nsearch_valid_contact:\n\twhile ( (ptr) &&\n\t!(VALID_CONTACT(ptr,act_time) && (ret=-2) && allowed_method(_m,ptr,flags)))\n\t\tptr = ptr->next;\n\tif (ptr==0) {\n\t\t/* nothing found */\n\t\tLM_DBG(\"nothing found !\\n\");\n\t\tgoto done;\n\t}\n\n\tif (sip_instance.len && sip_instance.s) {\n\t\tLM_DBG(\"ruri has gruu in lookup\\n\");\n\t\t/* uri has GRUU */\n\t\tif (ptr->instance.len-2 != sip_instance.len || \n\t\t\t\tmemcmp(ptr->instance.s+1,sip_instance.s,sip_instance.len)) {\n\t\t\tLM_DBG(\"no match to sip instace - [%.*s] - [%.*s]\\n\",ptr->instance.len-2,ptr->instance.s+1,\n\t\t\t\t\tsip_instance.len,sip_instance.s);\n\t\t\t/* not the targeted instance, search some more */\n\t\t\tptr = ptr->next;\n\t\t\tgoto search_valid_contact;\n\t\t}\n\n\t\tLM_DBG(\"matched sip instace\\n\");\n\t}\n\n\tif (call_id.len && call_id.s) {\n\t\t/* decide whether GRUU is expired or not\n\t\t *\n\t\t * first - match call-id */\n\t\tif (ptr->callid.len != call_id.len ||\n\t\t\t\tmemcmp(ptr->callid.s,call_id.s,call_id.len)) {\n\t\t\tLM_DBG(\"no match to call id - [%.*s] - [%.*s]\\n\",ptr->callid.len,ptr->callid.s,\n\t\t\t\t\tcall_id.len,call_id.s);\n\t\t\tptr = ptr->next;\n\t\t\tgoto search_valid_contact;\n\t\t}\n\n\t\t/* matched call-id, check if there are newer contacts with\n\t\t * same sip instace bup newer last_modified */\n\n\t\tit = ptr->next;\n\t\twhile ( it ) {\n\t\t\tif (VALID_CONTACT(it,act_time)) {\n\t\t\t\tif (it->instance.len-2 == sip_instance.len &&\n\t\t\t\t\t\tmemcmp(it->instance.s+1,sip_instance.s,sip_instance.len) == 0)\n\t\t\t\t\tif (it->last_modified > ptr->last_modified) {\n\t\t\t\t\t\t/* same instance id, but newer modified -> expired GRUU, no match at all */\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (it != NULL) {\n\t\t\tret = -1;\n\t\t\tgoto done;\n\t\t}\n\t}\n\n\tLM_DBG(\"found a complete match\\n\");\n\n\tret = 1;\n\tif (ptr) {\n\t\tLM_DBG(\"setting as ruri <%.*s>\\n\",ptr->c.len,ptr->c.s);\n\t\tif (set_ruri(_m, &ptr->c) < 0) {\n\t\t\tLM_ERR(\"unable to rewrite Request-URI\\n\");\n\t\t\tret = -3;\n\t\t\tgoto done;\n\t\t}\n\n\t\t/* If a Path is present, use first path-uri in favour of\n\t\t * received-uri because in that case the last hop towards the uac\n\t\t * has to handle NAT. - agranig */\n\t\tif (ptr->path.s && ptr->path.len) {\n\t\t\tif (get_path_dst_uri(&ptr->path, &path_dst) < 0) {\n\t\t\t\tLM_ERR(\"failed to get dst_uri for Path\\n\");\n\t\t\t\tret = -3;\n\t\t\t\tgoto done;\n\t\t\t}\n\t\t\tif (set_path_vector(_m, &ptr->path) < 0) {\n\t\t\t\tLM_ERR(\"failed to set path vector\\n\");\n\t\t\t\tret = -3;\n\t\t\t\tgoto done;\n\t\t\t}\n\t\t\tif (set_dst_uri(_m, &path_dst) < 0) {\n\t\t\t\tLM_ERR(\"failed to set dst_uri of Path\\n\");\n\t\t\t\tret = -3;\n\t\t\t\tgoto done;\n\t\t\t}\n\t\t} else if (ptr->received.s && ptr->received.len) {\n\t\t\tif (set_dst_uri(_m, &ptr->received) < 0) {\n\t\t\t\tret = -3;\n\t\t\t\tgoto done;\n\t\t\t}\n\t\t}\n\n\t\tset_ruri_q(ptr->q);\n\n\t\tsetbflag( 0, ptr->cflags);\n\n\t\tif (ptr->sock)\n\t\t\t_m->force_send_socket = ptr->sock;\n\n\t\t/* populate the 'attributes' avp */\n\t\tif (attr_avp_name != -1) {\n\t\t\tistr.s = ptr->attr;\n\t\t\tif (add_avp_last(AVP_VAL_STR, attr_avp_name, istr) != 0) {\n\t\t\t\tLM_ERR(\"Failed to populate attr avp!\\n\");\n\t\t\t}\n\t\t}\n\n\t\tptr = ptr->next;\n\t}\n\n\t/* Append branches if enabled */\n\t/* If we got to this point and the URI had a ;gr parameter and it was matched\n\t * to a contact. No point in branching */\n\tif ( flags®_LOOKUP_NOBRANCH_FLAG || (sip_instance.len && sip_instance.s) ) goto done;\n\tLM_DBG(\"looking for branches\\n\");\n\n\tfor( ; ptr ; ptr = ptr->next ) {\n\t\tif (VALID_CONTACT(ptr, act_time) && allowed_method(_m,ptr,flags)) {\n\t\t\tpath_dst.len = 0;\n\t\t\tif(ptr->path.s && ptr->path.len \n\t\t\t&& get_path_dst_uri(&ptr->path, &path_dst) < 0) {\n\t\t\t\tLM_ERR(\"failed to get dst_uri for Path\\n\");\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t/* The same as for the first contact applies for branches \n\t\t\t * regarding path vs. received. */\n\t\t\tLM_DBG(\"setting branch <%.*s>\\n\",ptr->c.len,ptr->c.s);\n\t\t\tif (append_branch(_m,&ptr->c,path_dst.len?&path_dst:&ptr->received,\n\t\t\t&ptr->path, ptr->q, ptr->cflags, ptr->sock) == -1) {\n\t\t\t\tLM_ERR(\"failed to append a branch\\n\");\n\t\t\t\t/* Also give a chance to the next branches*/\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t/* populate the 'attributes' avp */\n\t\t\tif (attr_avp_name != -1) {\n\t\t\t\tistr.s = ptr->attr;\n\t\t\t\tif (add_avp_last(AVP_VAL_STR, attr_avp_name, istr) != 0) {\n\t\t\t\t\tLM_ERR(\"Failed to populate attr avp!\\n\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\ndone:\n\tul.release_urecord(r);\n\tul.unlock_udomain((udomain_t*)_t, &aor);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': 'backport from 1.9 (rev #9980)\nfixed temporary GRUU bug that lead to infinite loop\nCredits to Tolga Tarhan\n\n\n\ngit-svn-id: svn+ssh://svn.code.sf.net/p/opensips/svn/trunk@9982 689a6050-402a-0410-94f2-e92a70836424'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: print_bacp_config_options(netdissect_options *ndo,\n const u_char *p, int length)\n{\n\tint len, opt;\n\n\tif (length < 2)\n\t\treturn 0;\n\tND_TCHECK2(*p, 2);\n\tlen = p[1];\n\topt = p[0];\n\tif (length < len)\n\t\treturn 0;\n\tif (len < 2) {\n\t\tND_PRINT((ndo, \"\\n\\t %s Option (0x%02x), length %u (length bogus, should be >= 2)\",\n\t\t tok2str(bacconfopts_values, \"Unknown\", opt),\n\t\t opt,\n\t\t len));\n\t\treturn 0;\n\t}\n\n\tND_PRINT((ndo, \"\\n\\t %s Option (0x%02x), length %u\",\n\t tok2str(bacconfopts_values, \"Unknown\", opt),\n\t opt,\n\t len));\n\n\tswitch (opt) {\n\tcase BACPOPT_FPEER:\n\t\tif (len != 6) {\n\t\t\tND_PRINT((ndo, \" (length bogus, should be = 6)\"));\n\t\t\treturn len;\n\t\t}\n\t\tND_TCHECK2(*(p + 2), 4);\n\t\tND_PRINT((ndo, \": Magic-Num 0x%08x\", EXTRACT_32BITS(p + 2)));\n\t\tbreak;\n\tdefault:\n\t\t/*\n\t\t * Unknown option; dump it as raw bytes now if we're\n\t\t * not going to do so below.\n\t\t */\n\t\tif (ndo->ndo_vflag < 2)\n\t\t\tprint_unknown_data(ndo, &p[2], \"\\n\\t \", len - 2);\n\t\tbreak;\n\t}\n\tif (ndo->ndo_vflag > 1)\n\t\tprint_unknown_data(ndo, &p[2], \"\\n\\t \", len - 2); /* exclude TLV header */\n\n\treturn len;\n\ntrunc:\n\tND_PRINT((ndo, \"[|bacp]\"));\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13029/PPP: Fix a bounds check, and clean up other bounds checks.\n\nFor configuration protocol options, use ND_TCHECK() and\nND_TCHECK_nBITS() macros, passing them the appropriate pointer argument.\nThis fixes one case where the ND_TCHECK2() call they replace was not\nchecking enough bytes.\n\nThis fixes a buffer over-read discovered by Bhargava Shastry,\nSecT/TU Berlin.\n\nAdd a test using the capture file supplied by the reporter(s), modified\nso the capture file won't be rejected as an invalid capture.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,\n\t\t\t uint32_t guest_irq, bool set)\n{\n\tstruct kvm_kernel_irq_routing_entry *e;\n\tstruct kvm_irq_routing_table *irq_rt;\n\tstruct kvm_lapic_irq irq;\n\tstruct kvm_vcpu *vcpu;\n\tstruct vcpu_data vcpu_info;\n\tint idx, ret = -EINVAL;\n\n\tif (!kvm_arch_has_assigned_device(kvm) ||\n\t\t!irq_remapping_cap(IRQ_POSTING_CAP) ||\n\t\t!kvm_vcpu_apicv_active(kvm->vcpus[0]))\n\t\treturn 0;\n\n\tidx = srcu_read_lock(&kvm->irq_srcu);\n\tirq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);\n\tBUG_ON(guest_irq >= irq_rt->nr_rt_entries);\n\n\thlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {\n\t\tif (e->type != KVM_IRQ_ROUTING_MSI)\n\t\t\tcontinue;\n\t\t/*\n\t\t * VT-d PI cannot support posting multicast/broadcast\n\t\t * interrupts to a vCPU, we still use interrupt remapping\n\t\t * for these kind of interrupts.\n\t\t *\n\t\t * For lowest-priority interrupts, we only support\n\t\t * those with single CPU as the destination, e.g. user\n\t\t * configures the interrupts via /proc/irq or uses\n\t\t * irqbalance to make the interrupts single-CPU.\n\t\t *\n\t\t * We will support full lowest-priority interrupt later.\n\t\t */\n\n\t\tkvm_set_msi_irq(kvm, e, &irq);\n\t\tif (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {\n\t\t\t/*\n\t\t\t * Make sure the IRTE is in remapped mode if\n\t\t\t * we don't handle it in posted mode.\n\t\t\t */\n\t\t\tret = irq_set_vcpu_affinity(host_irq, NULL);\n\t\t\tif (ret < 0) {\n\t\t\t\tprintk(KERN_INFO\n\t\t\t\t \"failed to back to remapped mode, irq: %u\\n\",\n\t\t\t\t host_irq);\n\t\t\t\tgoto out;\n\t\t\t}\n\n\t\t\tcontinue;\n\t\t}\n\n\t\tvcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));\n\t\tvcpu_info.vector = irq.vector;\n\n\t\ttrace_kvm_pi_irte_update(vcpu->vcpu_id, host_irq, e->gsi,\n\t\t\t\tvcpu_info.vector, vcpu_info.pi_desc_addr, set);\n\n\t\tif (set)\n\t\t\tret = irq_set_vcpu_affinity(host_irq, &vcpu_info);\n\t\telse {\n\t\t\t/* suppress notification event before unposting */\n\t\t\tpi_set_sn(vcpu_to_pi_desc(vcpu));\n\t\t\tret = irq_set_vcpu_affinity(host_irq, NULL);\n\t\t\tpi_clear_sn(vcpu_to_pi_desc(vcpu));\n\t\t}\n\n\t\tif (ret < 0) {\n\t\t\tprintk(KERN_INFO \"%s: failed to update PI IRTE\\n\",\n\t\t\t\t\t__func__);\n\t\t\tgoto out;\n\t\t}\n\t}\n\n\tret = 0;\nout:\n\tsrcu_read_unlock(&kvm->irq_srcu, idx);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-617'], 'message': 'KVM: VMX: Do not BUG() on out-of-bounds guest IRQ\n\nThe value of the guest_irq argument to vmx_update_pi_irte() is\nultimately coming from a KVM_IRQFD API call. Do not BUG() in\nvmx_update_pi_irte() if the value is out-of bounds. (Especially,\nsince KVM as a whole seems to hang after that.)\n\nInstead, print a message only once if we find that we don't have a\nroute for a certain IRQ (which can be out-of-bounds or within the\narray).\n\nThis fixes CVE-2017-1000252.\n\nFixes: efc644048ecde54 (\"KVM: x86: Update IRTE for posted-interrupts\")\nSigned-off-by: Jan H. Sch\u00f6nherr \nSigned-off-by: Paolo Bonzini '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int smacker_decode_tree(BitstreamContext *bc, HuffContext *hc,\n uint32_t prefix, int length)\n{\n if (!bitstream_read_bit(bc)) { // Leaf\n if(hc->current >= 256){\n av_log(NULL, AV_LOG_ERROR, \"Tree size exceeded!\\n\");\n return AVERROR_INVALIDDATA;\n }\n if(length){\n hc->bits[hc->current] = prefix;\n hc->lengths[hc->current] = length;\n } else {\n hc->bits[hc->current] = 0;\n hc->lengths[hc->current] = 0;\n }\n hc->values[hc->current] = bitstream_read(bc, 8);\n hc->current++;\n if(hc->maxlength < length)\n hc->maxlength = length;\n return 0;\n } else { //Node\n int r;\n length++;\n r = smacker_decode_tree(bc, hc, prefix, length);\n if(r)\n return r;\n return smacker_decode_tree(bc, hc, prefix | (1 << (length - 1)), length);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'smacker: add sanity check for length in smacker_decode_tree()\n\nSigned-off-by: Michael Niedermayer \n\nBug-Id: 1098\nCc: libav-stable@libav.org\nSigned-off-by: Sean McGovern '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int inotify_release(struct inode *ignored, struct file *file)\n{\n\tstruct fsnotify_group *group = file->private_data;\n\tstruct user_struct *user = group->inotify_data.user;\n\n\tpr_debug(\"%s: group=%p\\n\", __func__, group);\n\n\tfsnotify_clear_marks_by_group(group);\n\n\t/* free this group, matching get was inotify_init->fsnotify_obtain_group */\n\tfsnotify_put_group(group);\n\n\tatomic_dec(&user->inotify_devs);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'inotify: fix double free/corruption of stuct user\n\nOn an error path in inotify_init1 a normal user can trigger a double\nfree of struct user. This is a regression introduced by a2ae4cc9a16e\n(\"inotify: stop kernel memory leak on file creation failure\").\n\nWe fix this by making sure that if a group exists the user reference is\ndropped when the group is cleaned up. We should not explictly drop the\nreference on error and also drop the reference when the group is cleaned\nup.\n\nThe new lifetime rules are that an inotify group lives from\ninotify_new_group to the last fsnotify_put_group. Since the struct user\nand inotify_devs are directly tied to this lifetime they are only\nchanged/updated in those two locations. We get rid of all special\ncasing of struct user or user->inotify_devs.\n\nSigned-off-by: Eric Paris \nCc: stable@kernel.org (2.6.37 and up)\nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int string_scan_range(RList *list, RBinFile *bf, int min,\n\t\t\t const ut64 from, const ut64 to, int type) {\n\tut8 tmp[R_STRING_SCAN_BUFFER_SIZE];\n\tut64 str_start, needle = from;\n\tint count = 0, i, rc, runes;\n\tint str_type = R_STRING_TYPE_DETECT;\n\n\tif (type == -1) {\n\t\ttype = R_STRING_TYPE_DETECT;\n\t}\n\tif (from >= to) {\n\t\teprintf (\"Invalid range to find strings 0x%llx .. 0x%llx\\n\", from, to);\n\t\treturn -1;\n\t}\n\tut8 *buf = calloc (to - from, 1);\n\tif (!buf || !min) {\n\t\treturn -1;\n\t}\n\tr_buf_read_at (bf->buf, from, buf, to - from);\n\t// may oobread\n\twhile (needle < to) {\n\t\trc = r_utf8_decode (buf + needle - from, to - needle, NULL);\n\t\tif (!rc) {\n\t\t\tneedle++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (type == R_STRING_TYPE_DETECT) {\n\t\t\tchar *w = (char *)buf + needle + rc - from;\n\t\t\tif ((to - needle) > 5) {\n\t\t\t\tbool is_wide32 = needle + rc + 2 < to && !w[0] && !w[1] && !w[2] && w[3] && !w[4];\n\t\t\t\tif (is_wide32) {\n\t\t\t\t\tstr_type = R_STRING_TYPE_WIDE32;\n\t\t\t\t} else {\n\t\t\t\t\tbool is_wide = needle + rc + 2 < to && !w[0] && w[1] && !w[2];\n\t\t\t\t\tstr_type = is_wide? R_STRING_TYPE_WIDE: R_STRING_TYPE_ASCII;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tstr_type = R_STRING_TYPE_ASCII;\n\t\t\t}\n\t\t} else {\n\t\t\tstr_type = type;\n\t\t}\n\t\trunes = 0;\n\t\tstr_start = needle;\n\n\t\t/* Eat a whole C string */\n\t\tfor (rc = i = 0; i < sizeof (tmp) - 3 && needle < to; i += rc) {\n\t\t\tRRune r = {0};\n\n\t\t\tif (str_type == R_STRING_TYPE_WIDE32) {\n\t\t\t\trc = r_utf32le_decode (buf + needle - from, to - needle, &r);\n\t\t\t\tif (rc) {\n\t\t\t\t\trc = 4;\n\t\t\t\t}\n\t\t\t} else if (str_type == R_STRING_TYPE_WIDE) {\n\t\t\t\trc = r_utf16le_decode (buf + needle - from, to - needle, &r);\n\t\t\t\tif (rc == 1) {\n\t\t\t\t\trc = 2;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trc = r_utf8_decode (buf + needle - from, to - needle, &r);\n\t\t\t\tif (rc > 1) {\n\t\t\t\t\tstr_type = R_STRING_TYPE_UTF8;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/* Invalid sequence detected */\n\t\t\tif (!rc) {\n\t\t\t\tneedle++;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tneedle += rc;\n\n\t\t\tif (r_isprint (r) && r != '\\\\') {\n\t\t\t\tif (str_type == R_STRING_TYPE_WIDE32) {\n\t\t\t\t\tif (r == 0xff) {\n\t\t\t\t\t\tr = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\trc = r_utf8_encode (&tmp[i], r);\n\t\t\t\trunes++;\n\t\t\t\t/* Print the escape code */\n\t\t\t} else if (r && r < 0x100 && strchr (\"\\b\\v\\f\\n\\r\\t\\a\\033\\\\\", (char)r)) {\n\t\t\t\tif ((i + 32) < sizeof (tmp) && r < 93) {\n\t\t\t\t\ttmp[i + 0] = '\\\\';\n\t\t\t\t\ttmp[i + 1] = \" abtnvfr e \"\n\t\t\t\t\t \" \"\n\t\t\t\t\t \" \"\n\t\t\t\t\t \" \\\\\"[r];\n\t\t\t\t} else {\n\t\t\t\t\t// string too long\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\trc = 2;\n\t\t\t\trunes++;\n\t\t\t} else {\n\t\t\t\t/* \\0 marks the end of C-strings */\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\ttmp[i++] = '\\0';\n\n\t\tif (runes >= min) {\n\t\t\tif (str_type == R_STRING_TYPE_ASCII) {\n\t\t\t\t// reduce false positives\n\t\t\t\tint j;\n\t\t\t\tfor (j = 0; j < i; j++) {\n\t\t\t\t\tchar ch = tmp[j];\n\t\t\t\t\tif (ch != '\\n' && ch != '\\r' && ch != '\\t') {\n\t\t\t\t\t\tif (!IS_PRINTABLE (tmp[j])) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tRBinString *bs = R_NEW0 (RBinString);\n\t\t\tif (!bs) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbs->type = str_type;\n\t\t\tbs->length = runes;\n\t\t\tbs->size = needle - str_start;\n\t\t\tbs->ordinal = count++;\n\t\t\t// TODO: move into adjust_offset\n\t\t\tswitch (str_type) {\n\t\t\tcase R_STRING_TYPE_WIDE:\n\t\t\t\tif (str_start -from> 1) {\n\t\t\t\t\tconst ut8 *p = buf + str_start - 2 - from;\n\t\t\t\t\tif (p[0] == 0xff && p[1] == 0xfe) {\n\t\t\t\t\t\tstr_start -= 2; // \\xff\\xfe\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase R_STRING_TYPE_WIDE32:\n\t\t\t\tif (str_start -from> 3) {\n\t\t\t\t\tconst ut8 *p = buf + str_start - 4 - from;\n\t\t\t\t\tif (p[0] == 0xff && p[1] == 0xfe) {\n\t\t\t\t\t\tstr_start -= 4; // \\xff\\xfe\\x00\\x00\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbs->paddr = bs->vaddr = str_start;\n\t\t\tbs->string = r_str_ndup ((const char *)tmp, i);\n\t\t\tif (list) {\n\t\t\t\tr_list_append (list, bs);\n\t\t\t} else {\n\t\t\t\tprint_string (bs, bf);\n\t\t\t\tr_bin_string_free (bs);\n\t\t\t}\n\t\t}\n\t}\n\tfree (buf);\n\treturn count;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix #9902 - Fix oobread in RBin.string_scan_range'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static enum AVPixelFormat h263_get_format(AVCodecContext *avctx)\n{\n /* MPEG-4 Studio Profile only, not supported by hardware */\n if (avctx->bits_per_raw_sample > 8) {\n av_assert1(avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO);\n return avctx->pix_fmt;\n }\n\n if (avctx->codec->id == AV_CODEC_ID_MSS2)\n return AV_PIX_FMT_YUV420P;\n\n if (CONFIG_GRAY && (avctx->flags & AV_CODEC_FLAG_GRAY)) {\n if (avctx->color_range == AVCOL_RANGE_UNSPECIFIED)\n avctx->color_range = AVCOL_RANGE_MPEG;\n return AV_PIX_FMT_GRAY8;\n }\n\n return avctx->pix_fmt = ff_get_format(avctx, avctx->codec->pix_fmts);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-617'], 'message': 'avcodec/mpeg4videodec: Remove use of FF_PROFILE_MPEG4_SIMPLE_STUDIO as indicator of studio profile\n\nThe profile field is changed by code inside and outside the decoder,\nits not a reliable indicator of the internal codec state.\nMaintaining it consistency with studio_profile is messy.\nIts easier to just avoid it and use only studio_profile\n\nFixes: assertion failure\nFixes: ffmpeg_crash_9.avi\n\nFound-by: Thuan Pham, Marcel B\u00f6hme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart\nSigned-off-by: Michael Niedermayer '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: NO_INLINE JsVar *jspeFactorDelete() {\n JSP_ASSERT_MATCH(LEX_R_DELETE);\n JsVar *parent = 0;\n JsVar *a = jspeFactorMember(jspeFactor(), &parent);\n JsVar *result = 0;\n if (JSP_SHOULD_EXECUTE) {\n bool ok = false;\n if (jsvIsName(a) && !jsvIsNewChild(a)) {\n // if no parent, check in root?\n if (!parent && jsvIsChild(execInfo.root, a))\n parent = jsvLockAgain(execInfo.root);\n\n if (jsvHasChildren(parent)) {\n // else remove properly.\n if (jsvIsArray(parent)) {\n // For arrays, we must make sure we don't change the length\n JsVarInt l = jsvGetArrayLength(parent);\n jsvRemoveChild(parent, a);\n jsvSetArrayLength(parent, l, false);\n } else {\n jsvRemoveChild(parent, a);\n }\n ok = true;\n }\n }\n\n result = jsvNewFromBool(ok);\n }\n jsvUnLock2(a, parent);\n return result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix potential corruption issue caused by `delete [].__proto__` (fix #2142)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static const char* ConvertScalar(PyObject* v, float* out) {\n return ConvertOneFloat(v, out);\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-476'], 'message': 'Fix segfault when attempting to convert string to float16.\n\nTo make sure this gets fixed, add test for converting string to any numeric type.\n\nPiperOrigin-RevId: 286650886\nChange-Id: I81f770ec2bbd33a863e8057ce198c679912fa8e0'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: const char *setup_git_directory_gently(int *nongit_ok)\n{\n\tstatic struct strbuf cwd = STRBUF_INIT;\n\tstruct strbuf dir = STRBUF_INIT, gitdir = STRBUF_INIT;\n\tconst char *prefix = NULL;\n\tstruct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;\n\n\t/*\n\t * We may have read an incomplete configuration before\n\t * setting-up the git directory. If so, clear the cache so\n\t * that the next queries to the configuration reload complete\n\t * configuration (including the per-repo config file that we\n\t * ignored previously).\n\t */\n\tgit_config_clear();\n\n\t/*\n\t * Let's assume that we are in a git repository.\n\t * If it turns out later that we are somewhere else, the value will be\n\t * updated accordingly.\n\t */\n\tif (nongit_ok)\n\t\t*nongit_ok = 0;\n\n\tif (strbuf_getcwd(&cwd))\n\t\tdie_errno(_(\"Unable to read current working directory\"));\n\tstrbuf_addbuf(&dir, &cwd);\n\n\tswitch (setup_git_directory_gently_1(&dir, &gitdir, 1)) {\n\tcase GIT_DIR_EXPLICIT:\n\t\tprefix = setup_explicit_git_dir(gitdir.buf, &cwd, &repo_fmt, nongit_ok);\n\t\tbreak;\n\tcase GIT_DIR_DISCOVERED:\n\t\tif (dir.len < cwd.len && chdir(dir.buf))\n\t\t\tdie(_(\"cannot change to '%s'\"), dir.buf);\n\t\tprefix = setup_discovered_git_dir(gitdir.buf, &cwd, dir.len,\n\t\t\t\t\t\t &repo_fmt, nongit_ok);\n\t\tbreak;\n\tcase GIT_DIR_BARE:\n\t\tif (dir.len < cwd.len && chdir(dir.buf))\n\t\t\tdie(_(\"cannot change to '%s'\"), dir.buf);\n\t\tprefix = setup_bare_git_dir(&cwd, dir.len, &repo_fmt, nongit_ok);\n\t\tbreak;\n\tcase GIT_DIR_HIT_CEILING:\n\t\tif (!nongit_ok)\n\t\t\tdie(_(\"not a git repository (or any of the parent directories): %s\"),\n\t\t\t DEFAULT_GIT_DIR_ENVIRONMENT);\n\t\t*nongit_ok = 1;\n\t\tbreak;\n\tcase GIT_DIR_HIT_MOUNT_POINT:\n\t\tif (!nongit_ok)\n\t\t\tdie(_(\"not a git repository (or any parent up to mount point %s)\\n\"\n\t\t\t \"Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).\"),\n\t\t\t dir.buf);\n\t\t*nongit_ok = 1;\n\t\tbreak;\n\tcase GIT_DIR_INVALID_OWNERSHIP:\n\t\tif (!nongit_ok) {\n\t\t\tstruct strbuf quoted = STRBUF_INIT;\n\n\t\t\tsq_quote_buf_pretty("ed, dir.buf);\n\t\t\tdie(_(\"unsafe repository ('%s' is owned by someone else)\\n\"\n\t\t\t \"To add an exception for this directory, call:\\n\"\n\t\t\t \"\\n\"\n\t\t\t \"\\tgit config --global --add safe.directory %s\"),\n\t\t\t dir.buf, quoted.buf);\n\t\t}\n\t\t*nongit_ok = 1;\n\t\tbreak;\n\tcase GIT_DIR_NONE:\n\t\t/*\n\t\t * As a safeguard against setup_git_directory_gently_1 returning\n\t\t * this value, fallthrough to BUG. Otherwise it is possible to\n\t\t * set startup_info->have_repository to 1 when we did nothing to\n\t\t * find a repository.\n\t\t */\n\tdefault:\n\t\tBUG(\"unhandled setup_git_directory_1() result\");\n\t}\n\n\t/*\n\t * At this point, nongit_ok is stable. If it is non-NULL and points\n\t * to a non-zero value, then this means that we haven't found a\n\t * repository and that the caller expects startup_info to reflect\n\t * this.\n\t *\n\t * Regardless of the state of nongit_ok, startup_info->prefix and\n\t * the GIT_PREFIX environment variable must always match. For details\n\t * see Documentation/config/alias.txt.\n\t */\n\tif (nongit_ok && *nongit_ok) {\n\t\tstartup_info->have_repository = 0;\n\t\tstartup_info->prefix = NULL;\n\t\tsetenv(GIT_PREFIX_ENVIRONMENT, \"\", 1);\n\t} else {\n\t\tstartup_info->have_repository = 1;\n\t\tstartup_info->prefix = prefix;\n\t\tif (prefix)\n\t\t\tsetenv(GIT_PREFIX_ENVIRONMENT, prefix, 1);\n\t\telse\n\t\t\tsetenv(GIT_PREFIX_ENVIRONMENT, \"\", 1);\n\t}\n\n\t/*\n\t * Not all paths through the setup code will call 'set_git_dir()' (which\n\t * directly sets up the environment) so in order to guarantee that the\n\t * environment is in a consistent state after setup, explicitly setup\n\t * the environment if we have a repository.\n\t *\n\t * NEEDSWORK: currently we allow bogus GIT_DIR values to be set in some\n\t * code paths so we also need to explicitly setup the environment if\n\t * the user has set GIT_DIR. It may be beneficial to disallow bogus\n\t * GIT_DIR values at some point in the future.\n\t */\n\tif (/* GIT_DIR_EXPLICIT, GIT_DIR_DISCOVERED, GIT_DIR_BARE */\n\t startup_info->have_repository ||\n\t /* GIT_DIR_EXPLICIT */\n\t getenv(GIT_DIR_ENVIRONMENT)) {\n\t\tif (!the_repository->gitdir) {\n\t\t\tconst char *gitdir = getenv(GIT_DIR_ENVIRONMENT);\n\t\t\tif (!gitdir)\n\t\t\t\tgitdir = DEFAULT_GIT_DIR_ENVIRONMENT;\n\t\t\tsetup_git_env(gitdir);\n\t\t}\n\t\tif (startup_info->have_repository)\n\t\t\trepo_set_hash_algo(the_repository, repo_fmt.hash_algo);\n\t}\n\n\tstrbuf_release(&dir);\n\tstrbuf_release(&gitdir);\n\tclear_repository_format(&repo_fmt);\n\n\treturn prefix;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-22'], 'message': 'setup: tighten ownership checks post CVE-2022-24765\n\n8959555cee7 (setup_git_directory(): add an owner check for the top-level\ndirectory, 2022-03-02), adds a function to check for ownership of\nrepositories using a directory that is representative of it, and ways to\nadd exempt a specific repository from said check if needed, but that\ncheck didn't account for owership of the gitdir, or (when used) the\ngitfile that points to that gitdir.\n\nAn attacker could create a git repository in a directory that they can\nwrite into but that is owned by the victim to work around the fix that\nwas introduced with CVE-2022-24765 to potentially run code as the\nvictim.\n\nAn example that could result in privilege escalation to root in *NIX would\nbe to set a repository in a shared tmp directory by doing (for example):\n\n $ git -C /tmp init\n\nTo avoid that, extend the ensure_valid_ownership function to be able to\ncheck for all three paths.\n\nThis will have the side effect of tripling the number of stat() calls\nwhen a repository is detected, but the effect is expected to be likely\nminimal, as it is done only once during the directory walk in which Git\nlooks for a repository.\n\nAdditionally make sure to resolve the gitfile (if one was used) to find\nthe relevant gitdir for checking.\n\nWhile at it change the message printed on failure so it is clear we are\nreferring to the repository by its worktree (or gitdir if it is bare) and\nnot to a specific directory.\n\nHelped-by: Junio C Hamano \nHelped-by: Johannes Schindelin \nSigned-off-by: Carlo Marcelo Arenas Bel\u00f3n '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TPMI_RH_HIERARCHY_AUTH_Unmarshal(TPMI_RH_HIERARCHY_AUTH *target, BYTE **buffer, INT32 *size)\n{\n TPM_RC rc = TPM_RC_SUCCESS;\n \n if (rc == TPM_RC_SUCCESS) {\n\trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n }\n if (rc == TPM_RC_SUCCESS) {\n\tswitch (*target) {\n\t case TPM_RH_OWNER:\n\t case TPM_RH_PLATFORM:\n\t case TPM_RH_ENDORSEMENT:\n\t case TPM_RH_LOCKOUT:\n\t break;\n\t default:\n\t rc = TPM_RC_VALUE;\n\t}\n }\n return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Restore original value if unmarshalled value was illegal\n\nRestore the original value of the memory location where data from\na stream was unmarshalled and the unmarshalled value was found to\nbe illegal. The goal is to not keep illegal values in memory.\n\nSigned-off-by: Stefan Berger '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TPMI_ALG_SYM_Unmarshal(TPMI_ALG_SYM *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n{\n TPM_RC rc = TPM_RC_SUCCESS;\n\n if (rc == TPM_RC_SUCCESS) {\n\trc = TPM_ALG_ID_Unmarshal(target, buffer, size); \n }\n if (rc == TPM_RC_SUCCESS) {\n\tswitch (*target) {\n#if ALG_AES\n\t case TPM_ALG_AES:\n#endif\n#if ALG_SM4\n\t case TPM_ALG_SM4:\t\t\n#endif\n#if ALG_CAMELLIA\n\t case TPM_ALG_CAMELLIA:\t\n#endif\n#if ALG_TDES\t\t// libtpms added begin\n\t case TPM_ALG_TDES:\n#endif\t\t\t// libtpms added end\n#if ALG_XOR\n\t case TPM_ALG_XOR:\t\t\n#endif\n\t break;\n\t case TPM_ALG_NULL:\n\t if (allowNull) {\n\t\tbreak;\n\t }\n\t default:\n\t rc = TPM_RC_SYMMETRIC;\n\t}\n }\n return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Restore original value if unmarshalled value was illegal\n\nRestore the original value of the memory location where data from\na stream was unmarshalled and the unmarshalled value was found to\nbe illegal. The goal is to not keep illegal values in memory.\n\nSigned-off-by: Stefan Berger '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TPMI_ALG_SIG_SCHEME_Unmarshal(TPMI_ALG_SIG_SCHEME *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n{\n TPM_RC rc = TPM_RC_SUCCESS;\n\n if (rc == TPM_RC_SUCCESS) {\n\trc = TPM_ALG_ID_Unmarshal(target, buffer, size); \n }\n if (rc == TPM_RC_SUCCESS) {\n\tswitch (*target) {\n#if ALG_HMAC\t\t\n\t case TPM_ALG_HMAC:\n#endif\n#if ALG_RSASSA\t\n\t case TPM_ALG_RSASSA:\n#endif\n#if ALG_RSAPSS\t\n\t case TPM_ALG_RSAPSS:\n#endif\n#if ALG_ECDSA\t\t\n\t case TPM_ALG_ECDSA:\n#endif\n#if ALG_ECDAA\t\t\n\t case TPM_ALG_ECDAA:\n#endif\n#if ALG_SM2\t\t\n\t case TPM_ALG_SM2:\n#endif\n#if ALG_ECSCHNORR\t\n\t case TPM_ALG_ECSCHNORR:\n#endif\n\t break;\n\t case TPM_ALG_NULL:\n\t if (allowNull) {\n\t\tbreak;\n\t }\n\t default:\n\t rc = TPM_RC_SCHEME;\n\t}\n }\n return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Restore original value if unmarshalled value was illegal\n\nRestore the original value of the memory location where data from\na stream was unmarshalled and the unmarshalled value was found to\nbe illegal. The goal is to not keep illegal values in memory.\n\nSigned-off-by: Stefan Berger '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TPMI_CAMELLIA_KEY_BITS_Unmarshal(TPMI_CAMELLIA_KEY_BITS *target, BYTE **buffer, INT32 *size)\n{\n TPM_RC rc = TPM_RC_SUCCESS;\n\n if (rc == TPM_RC_SUCCESS) {\n\trc = TPM_KEY_BITS_Unmarshal(target, buffer, size); \n }\n if (rc == TPM_RC_SUCCESS) {\n\tswitch (*target) {\n\t case 128:\n\t break;\n\t default:\n\t rc = TPM_RC_VALUE;\n\t}\n }\n return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Restore original value if unmarshalled value was illegal\n\nRestore the original value of the memory location where data from\na stream was unmarshalled and the unmarshalled value was found to\nbe illegal. The goal is to not keep illegal values in memory.\n\nSigned-off-by: Stefan Berger '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TPMI_SH_AUTH_SESSION_Unmarshal(TPMI_SH_AUTH_SESSION *target, BYTE **buffer, INT32 *size, BOOL allowPwd)\n{\n TPM_RC rc = TPM_RC_SUCCESS;\n\n if (rc == TPM_RC_SUCCESS) {\n\trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n }\n if (rc == TPM_RC_SUCCESS) {\n\tBOOL isNotHmacSession = (*target < HMAC_SESSION_FIRST ) || (*target > HMAC_SESSION_LAST);\n\tBOOL isNotPolicySession = (*target < POLICY_SESSION_FIRST) || (*target > POLICY_SESSION_LAST);\n\tBOOL isNotLegalPwd = (*target != TPM_RS_PW) || !allowPwd;\n\tif (isNotHmacSession &&\n\t isNotPolicySession &&\n\t isNotLegalPwd) {\n\t rc = TPM_RC_VALUE;\n\t}\n }\n return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Restore original value if unmarshalled value was illegal\n\nRestore the original value of the memory location where data from\na stream was unmarshalled and the unmarshalled value was found to\nbe illegal. The goal is to not keep illegal values in memory.\n\nSigned-off-by: Stefan Berger '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TPMI_SH_HMAC_Unmarshal(TPMI_SH_HMAC *target, BYTE **buffer, INT32 *size)\n{\n TPM_RC rc = TPM_RC_SUCCESS;\n \n if (rc == TPM_RC_SUCCESS) {\n\trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n }\n if (rc == TPM_RC_SUCCESS) {\n\tBOOL isNotHmacSession = (*target < HMAC_SESSION_FIRST ) || (*target > HMAC_SESSION_LAST);\n\tif (isNotHmacSession) {\n\t rc = TPM_RC_VALUE;\n\t}\n }\n return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Restore original value if unmarshalled value was illegal\n\nRestore the original value of the memory location where data from\na stream was unmarshalled and the unmarshalled value was found to\nbe illegal. The goal is to not keep illegal values in memory.\n\nSigned-off-by: Stefan Berger '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TPMI_DH_OBJECT_Unmarshal(TPMI_DH_OBJECT *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n{\n TPM_RC rc = TPM_RC_SUCCESS;\n \n if (rc == TPM_RC_SUCCESS) {\n\trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n }\n if (rc == TPM_RC_SUCCESS) {\n\tBOOL isNotTransient = (*target < TRANSIENT_FIRST) || (*target > TRANSIENT_LAST);\n\tBOOL isNotPersistent = (*target < PERSISTENT_FIRST) || (*target > PERSISTENT_LAST);\n\tBOOL isNotLegalNull = (*target != TPM_RH_NULL) || !allowNull;\n\tif (isNotTransient &&\n\t isNotPersistent &&\n\t isNotLegalNull) {\n\t rc = TPM_RC_VALUE;\n\t}\n }\n return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Restore original value if unmarshalled value was illegal\n\nRestore the original value of the memory location where data from\na stream was unmarshalled and the unmarshalled value was found to\nbe illegal. The goal is to not keep illegal values in memory.\n\nSigned-off-by: Stefan Berger '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: }\n\nvoid print_udta(GF_ISOFile *file, u32 track_number, Bool has_itags)\n{\n\tu32 i, count;\n\n\tcount = gf_isom_get_udta_count(file, track_number);\n\tif (!count) return;\n\n\tif (has_itags) {\n\t\tfor (i=0; i \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'fixed #1765'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ikev1_ke_print(netdissect_options *ndo, u_char tpay _U_,\n\t const struct isakmp_gen *ext, u_int item_len _U_,\n\t const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_,\n\t uint32_t proto _U_, int depth _U_)\n{\n\tstruct isakmp_gen e;\n\n\tND_PRINT((ndo,\"%s:\", NPSTR(ISAKMP_NPTYPE_KE)));\n\n\tND_TCHECK(*ext);\n\tUNALIGNED_MEMCPY(&e, ext, sizeof(e));\n\tND_PRINT((ndo,\" key len=%d\", ntohs(e.len) - 4));\n\tif (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {\n\t\tND_PRINT((ndo,\" \"));\n\t\tif (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))\n\t\t\tgoto trunc;\n\t}\n\treturn (const u_char *)ext + ntohs(e.len);\ntrunc:\n\tND_PRINT((ndo,\" [|%s]\", NPSTR(ISAKMP_NPTYPE_KE)));\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13690/IKEv2: Fix some bounds checks.\n\nUse a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2()\nand provide the correct length.\n\nWhile we're at it, remove the blank line between some checks and the\nUNALIGNED_MEMCPY()s they protect.\n\nAlso, note the places where we print the entire payload.\n\nThis fixes a buffer over-read discovered by Bhargava Shastry,\nSecT/TU Berlin.\n\nAdd a test using the capture file supplied by the reporter(s).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ikev1_sig_print(netdissect_options *ndo, u_char tpay _U_,\n\t\tconst struct isakmp_gen *ext, u_int item_len _U_,\n\t\tconst u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_,\n\t\tuint32_t proto _U_, int depth _U_)\n{\n\tstruct isakmp_gen e;\n\n\tND_PRINT((ndo,\"%s:\", NPSTR(ISAKMP_NPTYPE_SIG)));\n\n\tND_TCHECK(*ext);\n\tUNALIGNED_MEMCPY(&e, ext, sizeof(e));\n\tND_PRINT((ndo,\" len=%d\", ntohs(e.len) - 4));\n\tif (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {\n\t\tND_PRINT((ndo,\" \"));\n\t\tif (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))\n\t\t\tgoto trunc;\n\t}\n\treturn (const u_char *)ext + ntohs(e.len);\ntrunc:\n\tND_PRINT((ndo,\" [|%s]\", NPSTR(ISAKMP_NPTYPE_SIG)));\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13690/IKEv2: Fix some bounds checks.\n\nUse a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2()\nand provide the correct length.\n\nWhile we're at it, remove the blank line between some checks and the\nUNALIGNED_MEMCPY()s they protect.\n\nAlso, note the places where we print the entire payload.\n\nThis fixes a buffer over-read discovered by Bhargava Shastry,\nSecT/TU Berlin.\n\nAdd a test using the capture file supplied by the reporter(s).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static ssize_t oz_cdev_write(struct file *filp, const char __user *buf,\n\t\tsize_t count, loff_t *fpos)\n{\n\tstruct oz_pd *pd;\n\tstruct oz_elt_buf *eb;\n\tstruct oz_elt_info *ei;\n\tstruct oz_elt *elt;\n\tstruct oz_app_hdr *app_hdr;\n\tstruct oz_serial_ctx *ctx;\n\n\tspin_lock_bh(&g_cdev.lock);\n\tpd = g_cdev.active_pd;\n\tif (pd)\n\t\toz_pd_get(pd);\n\tspin_unlock_bh(&g_cdev.lock);\n\tif (pd == NULL)\n\t\treturn -ENXIO;\n\tif (!(pd->state & OZ_PD_S_CONNECTED))\n\t\treturn -EAGAIN;\n\teb = &pd->elt_buff;\n\tei = oz_elt_info_alloc(eb);\n\tif (ei == NULL) {\n\t\tcount = 0;\n\t\tgoto out;\n\t}\n\telt = (struct oz_elt *)ei->data;\n\tapp_hdr = (struct oz_app_hdr *)(elt+1);\n\telt->length = sizeof(struct oz_app_hdr) + count;\n\telt->type = OZ_ELT_APP_DATA;\n\tei->app_id = OZ_APPID_SERIAL;\n\tei->length = elt->length + sizeof(struct oz_elt);\n\tapp_hdr->app_id = OZ_APPID_SERIAL;\n\tif (copy_from_user(app_hdr+1, buf, count))\n\t\tgoto out;\n\tspin_lock_bh(&pd->app_lock[OZ_APPID_USB-1]);\n\tctx = (struct oz_serial_ctx *)pd->app_ctx[OZ_APPID_SERIAL-1];\n\tif (ctx) {\n\t\tapp_hdr->elt_seq_num = ctx->tx_seq_num++;\n\t\tif (ctx->tx_seq_num == 0)\n\t\t\tctx->tx_seq_num = 1;\n\t\tspin_lock(&eb->lock);\n\t\tif (oz_queue_elt_info(eb, 0, 0, ei) == 0)\n\t\t\tei = NULL;\n\t\tspin_unlock(&eb->lock);\n\t}\n\tspin_unlock_bh(&pd->app_lock[OZ_APPID_USB-1]);\nout:\n\tif (ei) {\n\t\tcount = 0;\n\t\tspin_lock_bh(&eb->lock);\n\t\toz_elt_info_free(eb, ei);\n\t\tspin_unlock_bh(&eb->lock);\n\t}\n\toz_pd_put(pd);\n\treturn count;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'staging: ozwpan: prevent overflow in oz_cdev_write()\n\nWe need to check \"count\" so we don't overflow the ei->data buffer.\n\nReported-by: Nico Golde \nReported-by: Fabian Yamaguchi \nSigned-off-by: Dan Carpenter \nCc: stable@kernel.org\nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int mxf_read_index_entry_array(AVIOContext *pb, MXFIndexTableSegment *segment)\n{\n int i, length;\n\n segment->nb_index_entries = avio_rb32(pb);\n\n length = avio_rb32(pb);\n\n if (!(segment->temporal_offset_entries=av_calloc(segment->nb_index_entries, sizeof(*segment->temporal_offset_entries))) ||\n !(segment->flag_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->flag_entries))) ||\n !(segment->stream_offset_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->stream_offset_entries)))) {\n av_freep(&segment->temporal_offset_entries);\n av_freep(&segment->flag_entries);\n return AVERROR(ENOMEM);\n }\n\n for (i = 0; i < segment->nb_index_entries; i++) {\n segment->temporal_offset_entries[i] = avio_r8(pb);\n avio_r8(pb); /* KeyFrameOffset */\n segment->flag_entries[i] = avio_r8(pb);\n segment->stream_offset_entries[i] = avio_rb64(pb);\n avio_skip(pb, length - 11);\n }\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-834'], 'message': 'avformat/mxfdec: Fix DoS issues in mxf_read_index_entry_array()\n\nFixes: 20170829A.mxf\n\nCo-Author: \u5f20\u6d2a\u4eae(\u671b\u521d)\" \nFound-by: Xiaohei and Wangchu from Alibaba Security Team\nSigned-off-by: Michael Niedermayer '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static struct net_device *_init_airo_card( unsigned short irq, int port,\n\t\t\t\t\t int is_pcmcia, struct pci_dev *pci,\n\t\t\t\t\t struct device *dmdev )\n{\n\tstruct net_device *dev;\n\tstruct airo_info *ai;\n\tint i, rc;\n\tCapabilityRid cap_rid;\n\n\t/* Create the network device object. */\n\tdev = alloc_netdev(sizeof(*ai), \"\", ether_setup);\n\tif (!dev) {\n\t\tairo_print_err(\"\", \"Couldn't alloc_etherdev\");\n\t\treturn NULL;\n\t}\n\n\tai = dev->ml_priv = netdev_priv(dev);\n\tai->wifidev = NULL;\n\tai->flags = 1 << FLAG_RADIO_DOWN;\n\tai->jobs = 0;\n\tai->dev = dev;\n\tif (pci && (pci->device == 0x5000 || pci->device == 0xa504)) {\n\t\tairo_print_dbg(\"\", \"Found an MPI350 card\");\n\t\tset_bit(FLAG_MPI, &ai->flags);\n\t}\n\tspin_lock_init(&ai->aux_lock);\n\tsema_init(&ai->sem, 1);\n\tai->config.len = 0;\n\tai->pci = pci;\n\tinit_waitqueue_head (&ai->thr_wait);\n\tai->tfm = NULL;\n\tadd_airo_dev(ai);\n\n\tif (airo_networks_allocate (ai))\n\t\tgoto err_out_free;\n\tairo_networks_initialize (ai);\n\n\tskb_queue_head_init (&ai->txq);\n\n\t/* The Airo-specific entries in the device structure. */\n\tif (test_bit(FLAG_MPI,&ai->flags))\n\t\tdev->netdev_ops = &mpi_netdev_ops;\n\telse\n\t\tdev->netdev_ops = &airo_netdev_ops;\n\tdev->wireless_handlers = &airo_handler_def;\n\tai->wireless_data.spy_data = &ai->spy_data;\n\tdev->wireless_data = &ai->wireless_data;\n\tdev->irq = irq;\n\tdev->base_addr = port;\n\n\tSET_NETDEV_DEV(dev, dmdev);\n\n\treset_card (dev, 1);\n\tmsleep(400);\n\n\tif (!is_pcmcia) {\n\t\tif (!request_region(dev->base_addr, 64, DRV_NAME)) {\n\t\t\trc = -EBUSY;\n\t\t\tairo_print_err(dev->name, \"Couldn't request region\");\n\t\t\tgoto err_out_nets;\n\t\t}\n\t}\n\n\tif (test_bit(FLAG_MPI,&ai->flags)) {\n\t\tif (mpi_map_card(ai, pci)) {\n\t\t\tairo_print_err(\"\", \"Could not map memory\");\n\t\t\tgoto err_out_res;\n\t\t}\n\t}\n\n\tif (probe) {\n\t\tif (setup_card(ai, dev->dev_addr, 1) != SUCCESS) {\n\t\t\tairo_print_err(dev->name, \"MAC could not be enabled\" );\n\t\t\trc = -EIO;\n\t\t\tgoto err_out_map;\n\t\t}\n\t} else if (!test_bit(FLAG_MPI,&ai->flags)) {\n\t\tai->bap_read = fast_bap_read;\n\t\tset_bit(FLAG_FLASHING, &ai->flags);\n\t}\n\n\tstrcpy(dev->name, \"eth%d\");\n\trc = register_netdev(dev);\n\tif (rc) {\n\t\tairo_print_err(dev->name, \"Couldn't register_netdev\");\n\t\tgoto err_out_map;\n\t}\n\tai->wifidev = init_wifidev(ai, dev);\n\tif (!ai->wifidev)\n\t\tgoto err_out_reg;\n\n\trc = readCapabilityRid(ai, &cap_rid, 1);\n\tif (rc != SUCCESS) {\n\t\trc = -EIO;\n\t\tgoto err_out_wifi;\n\t}\n\t/* WEP capability discovery */\n\tai->wep_capable = (cap_rid.softCap & cpu_to_le16(0x02)) ? 1 : 0;\n\tai->max_wep_idx = (cap_rid.softCap & cpu_to_le16(0x80)) ? 3 : 0;\n\n\tairo_print_info(dev->name, \"Firmware version %x.%x.%02d\",\n\t ((le16_to_cpu(cap_rid.softVer) >> 8) & 0xF),\n\t (le16_to_cpu(cap_rid.softVer) & 0xFF),\n\t le16_to_cpu(cap_rid.softSubVer));\n\n\t/* Test for WPA support */\n\t/* Only firmware versions 5.30.17 or better can do WPA */\n\tif (le16_to_cpu(cap_rid.softVer) > 0x530\n\t || (le16_to_cpu(cap_rid.softVer) == 0x530\n\t && le16_to_cpu(cap_rid.softSubVer) >= 17)) {\n\t\tairo_print_info(ai->dev->name, \"WPA supported.\");\n\n\t\tset_bit(FLAG_WPA_CAPABLE, &ai->flags);\n\t\tai->bssListFirst = RID_WPA_BSSLISTFIRST;\n\t\tai->bssListNext = RID_WPA_BSSLISTNEXT;\n\t\tai->bssListRidLen = sizeof(BSSListRid);\n\t} else {\n\t\tairo_print_info(ai->dev->name, \"WPA unsupported with firmware \"\n\t\t\t\"versions older than 5.30.17.\");\n\n\t\tai->bssListFirst = RID_BSSLISTFIRST;\n\t\tai->bssListNext = RID_BSSLISTNEXT;\n\t\tai->bssListRidLen = sizeof(BSSListRid) - sizeof(BSSListRidExtra);\n\t}\n\n\tset_bit(FLAG_REGISTERED,&ai->flags);\n\tairo_print_info(dev->name, \"MAC enabled %pM\", dev->dev_addr);\n\n\t/* Allocate the transmit buffers */\n\tif (probe && !test_bit(FLAG_MPI,&ai->flags))\n\t\tfor( i = 0; i < MAX_FIDS; i++ )\n\t\t\tai->fids[i] = transmit_allocate(ai,AIRO_DEF_MTU,i>=MAX_FIDS/2);\n\n\tif (setup_proc_entry(dev, dev->ml_priv) < 0)\n\t\tgoto err_out_wifi;\n\n\treturn dev;\n\nerr_out_wifi:\n\tunregister_netdev(ai->wifidev);\n\tfree_netdev(ai->wifidev);\nerr_out_reg:\n\tunregister_netdev(dev);\nerr_out_map:\n\tif (test_bit(FLAG_MPI,&ai->flags) && pci) {\n\t\tpci_free_consistent(pci, PCI_SHARED_LEN, ai->shared, ai->shared_dma);\n\t\tiounmap(ai->pciaux);\n\t\tiounmap(ai->pcimem);\n\t\tmpi_unmap_card(ai->pci);\n\t}\nerr_out_res:\n\tif (!is_pcmcia)\n\t release_region( dev->base_addr, 64 );\nerr_out_nets:\n\tairo_networks_free(ai);\nerr_out_free:\n\tdel_airo_dev(ai);\n\tfree_netdev(dev);\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-264'], 'message': 'net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared\n\nAfter the last patch, We are left in a state in which only drivers calling\nether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real\nhardware call ether_setup for their net_devices and don't hold any state in\ntheir skbs. There are a handful of drivers that violate this assumption of\ncourse, and need to be fixed up. This patch identifies those drivers, and marks\nthem as not being able to support the safe transmission of skbs by clearning the\nIFF_TX_SKB_SHARING flag in priv_flags\n\nSigned-off-by: Neil Horman \nCC: Karsten Keil \nCC: \"David S. Miller\" \nCC: Jay Vosburgh \nCC: Andy Gospodarek \nCC: Patrick McHardy \nCC: Krzysztof Halasa \nCC: \"John W. Linville\" \nCC: Greg Kroah-Hartman \nCC: Marcel Holtmann \nCC: Johannes Berg \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void hostap_setup_dev(struct net_device *dev, local_info_t *local,\n\t\t int type)\n{\n\tstruct hostap_interface *iface;\n\n\tiface = netdev_priv(dev);\n\tether_setup(dev);\n\n\t/* kernel callbacks */\n\tif (iface) {\n\t\t/* Currently, we point to the proper spy_data only on\n\t\t * the main_dev. This could be fixed. Jean II */\n\t\tiface->wireless_data.spy_data = &iface->spy_data;\n\t\tdev->wireless_data = &iface->wireless_data;\n\t}\n\tdev->wireless_handlers = &hostap_iw_handler_def;\n\tdev->watchdog_timeo = TX_TIMEOUT;\n\n\tswitch(type) {\n\tcase HOSTAP_INTERFACE_AP:\n\t\tdev->tx_queue_len = 0;\t/* use main radio device queue */\n\t\tdev->netdev_ops = &hostap_mgmt_netdev_ops;\n\t\tdev->type = ARPHRD_IEEE80211;\n\t\tdev->header_ops = &hostap_80211_ops;\n\t\tbreak;\n\tcase HOSTAP_INTERFACE_MASTER:\n\t\tdev->netdev_ops = &hostap_master_ops;\n\t\tbreak;\n\tdefault:\n\t\tdev->tx_queue_len = 0;\t/* use main radio device queue */\n\t\tdev->netdev_ops = &hostap_netdev_ops;\n\t}\n\n\tdev->mtu = local->mtu;\n\n\n\tSET_ETHTOOL_OPS(dev, &prism2_ethtool_ops);\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-264'], 'message': 'net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared\n\nAfter the last patch, We are left in a state in which only drivers calling\nether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real\nhardware call ether_setup for their net_devices and don't hold any state in\ntheir skbs. There are a handful of drivers that violate this assumption of\ncourse, and need to be fixed up. This patch identifies those drivers, and marks\nthem as not being able to support the safe transmission of skbs by clearning the\nIFF_TX_SKB_SHARING flag in priv_flags\n\nSigned-off-by: Neil Horman \nCC: Karsten Keil \nCC: \"David S. Miller\" \nCC: Jay Vosburgh \nCC: Andy Gospodarek \nCC: Patrick McHardy \nCC: Krzysztof Halasa \nCC: \"John W. Linville\" \nCC: Greg Kroah-Hartman \nCC: Marcel Holtmann \nCC: Johannes Berg \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: smb_send_kvec(struct TCP_Server_Info *server, struct kvec *iov, size_t n_vec,\n\t\tsize_t *sent)\n{\n\tint rc = 0;\n\tint i = 0;\n\tstruct msghdr smb_msg;\n\tunsigned int remaining;\n\tsize_t first_vec = 0;\n\tstruct socket *ssocket = server->ssocket;\n\n\t*sent = 0;\n\n\tif (ssocket == NULL)\n\t\treturn -ENOTSOCK; /* BB eventually add reconnect code here */\n\n\tsmb_msg.msg_name = (struct sockaddr *) &server->dstaddr;\n\tsmb_msg.msg_namelen = sizeof(struct sockaddr);\n\tsmb_msg.msg_control = NULL;\n\tsmb_msg.msg_controllen = 0;\n\tif (server->noblocksnd)\n\t\tsmb_msg.msg_flags = MSG_DONTWAIT + MSG_NOSIGNAL;\n\telse\n\t\tsmb_msg.msg_flags = MSG_NOSIGNAL;\n\n\tremaining = 0;\n\tfor (i = 0; i < n_vec; i++)\n\t\tremaining += iov[i].iov_len;\n\n\ti = 0;\n\twhile (remaining) {\n\t\t/*\n\t\t * If blocking send, we try 3 times, since each can block\n\t\t * for 5 seconds. For nonblocking we have to try more\n\t\t * but wait increasing amounts of time allowing time for\n\t\t * socket to clear. The overall time we wait in either\n\t\t * case to send on the socket is about 15 seconds.\n\t\t * Similarly we wait for 15 seconds for a response from\n\t\t * the server in SendReceive[2] for the server to send\n\t\t * a response back for most types of requests (except\n\t\t * SMB Write past end of file which can be slow, and\n\t\t * blocking lock operations). NFS waits slightly longer\n\t\t * than CIFS, but this can make it take longer for\n\t\t * nonresponsive servers to be detected and 15 seconds\n\t\t * is more than enough time for modern networks to\n\t\t * send a packet. In most cases if we fail to send\n\t\t * after the retries we will kill the socket and\n\t\t * reconnect which may clear the network problem.\n\t\t */\n\t\trc = kernel_sendmsg(ssocket, &smb_msg, &iov[first_vec],\n\t\t\t\t n_vec - first_vec, remaining);\n\t\tif (rc == -ENOSPC || rc == -EAGAIN) {\n\t\t\t/*\n\t\t\t * Catch if a low level driver returns -ENOSPC. This\n\t\t\t * WARN_ON will be removed by 3.10 if no one reports\n\t\t\t * seeing this.\n\t\t\t */\n\t\t\tWARN_ON_ONCE(rc == -ENOSPC);\n\t\t\ti++;\n\t\t\tif (i >= 14 || (!server->noblocksnd && (i > 2))) {\n\t\t\t\tcERROR(1, \"sends on sock %p stuck for 15 \"\n\t\t\t\t\t \"seconds\", ssocket);\n\t\t\t\trc = -EAGAIN;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tmsleep(1 << i);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (rc < 0)\n\t\t\tbreak;\n\n\t\t/* send was at least partially successful */\n\t\t*sent += rc;\n\n\t\tif (rc == remaining) {\n\t\t\tremaining = 0;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (rc > remaining) {\n\t\t\tcERROR(1, \"sent %d requested %d\", rc, remaining);\n\t\t\tbreak;\n\t\t}\n\n\t\tif (rc == 0) {\n\t\t\t/* should never happen, letting socket clear before\n\t\t\t retrying is our only obvious option here */\n\t\t\tcERROR(1, \"tcp sent no data\");\n\t\t\tmsleep(500);\n\t\t\tcontinue;\n\t\t}\n\n\t\tremaining -= rc;\n\n\t\t/* the line below resets i */\n\t\tfor (i = first_vec; i < n_vec; i++) {\n\t\t\tif (iov[i].iov_len) {\n\t\t\t\tif (rc > iov[i].iov_len) {\n\t\t\t\t\trc -= iov[i].iov_len;\n\t\t\t\t\tiov[i].iov_len = 0;\n\t\t\t\t} else {\n\t\t\t\t\tiov[i].iov_base += rc;\n\t\t\t\t\tiov[i].iov_len -= rc;\n\t\t\t\t\tfirst_vec = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\ti = 0; /* in case we get ENOSPC on the next send */\n\t\trc = 0;\n\t}\n\treturn rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'cifs: move check for NULL socket into smb_send_rqst\n\nCai reported this oops:\n\n[90701.616664] BUG: unable to handle kernel NULL pointer dereference at 0000000000000028\n[90701.625438] IP: [] kernel_setsockopt+0x2e/0x60\n[90701.632167] PGD fea319067 PUD 103fda4067 PMD 0\n[90701.637255] Oops: 0000 [#1] SMP\n[90701.640878] Modules linked in: des_generic md4 nls_utf8 cifs dns_resolver binfmt_misc tun sg igb iTCO_wdt iTCO_vendor_support lpc_ich pcspkr i2c_i801 i2c_core i7core_edac edac_core ioatdma dca mfd_core coretemp kvm_intel kvm crc32c_intel microcode sr_mod cdrom ata_generic sd_mod pata_acpi crc_t10dif ata_piix libata megaraid_sas dm_mirror dm_region_hash dm_log dm_mod\n[90701.677655] CPU 10\n[90701.679808] Pid: 9627, comm: ls Tainted: G W 3.7.1+ #10 QCI QSSC-S4R/QSSC-S4R\n[90701.688950] RIP: 0010:[] [] kernel_setsockopt+0x2e/0x60\n[90701.698383] RSP: 0018:ffff88177b431bb8 EFLAGS: 00010206\n[90701.704309] RAX: ffff88177b431fd8 RBX: 00007ffffffff000 RCX: ffff88177b431bec\n[90701.712271] RDX: 0000000000000003 RSI: 0000000000000006 RDI: 0000000000000000\n[90701.720223] RBP: ffff88177b431bc8 R08: 0000000000000004 R09: 0000000000000000\n[90701.728185] R10: 0000000000000001 R11: 0000000000000000 R12: 0000000000000001\n[90701.736147] R13: ffff88184ef92000 R14: 0000000000000023 R15: ffff88177b431c88\n[90701.744109] FS: 00007fd56a1a47c0(0000) GS:ffff88105fc40000(0000) knlGS:0000000000000000\n[90701.753137] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b\n[90701.759550] CR2: 0000000000000028 CR3: 000000104f15f000 CR4: 00000000000007e0\n[90701.767512] DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000\n[90701.775465] DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400\n[90701.783428] Process ls (pid: 9627, threadinfo ffff88177b430000, task ffff88185ca4cb60)\n[90701.792261] Stack:\n[90701.794505] 0000000000000023 ffff88177b431c50 ffff88177b431c38 ffffffffa014fcb1\n[90701.802809] ffff88184ef921bc 0000000000000000 00000001ffffffff ffff88184ef921c0\n[90701.811123] ffff88177b431c08 ffffffff815ca3d9 ffff88177b431c18 ffff880857758000\n[90701.819433] Call Trace:\n[90701.822183] [] smb_send_rqst+0x71/0x1f0 [cifs]\n[90701.828991] [] ? schedule+0x29/0x70\n[90701.834736] [] smb_sendv+0x3d/0x40 [cifs]\n[90701.841062] [] smb_send+0x26/0x30 [cifs]\n[90701.847291] [] send_nt_cancel+0x6f/0xd0 [cifs]\n[90701.854102] [] SendReceive+0x18e/0x360 [cifs]\n[90701.860814] [] CIFSFindFirst+0x1a8/0x3f0 [cifs]\n[90701.867724] [] ? build_path_from_dentry+0xf1/0x260 [cifs]\n[90701.875601] [] ? build_path_from_dentry+0xf1/0x260 [cifs]\n[90701.883477] [] cifs_query_dir_first+0x26/0x30 [cifs]\n[90701.890869] [] initiate_cifs_search+0xed/0x250 [cifs]\n[90701.898354] [] ? fillonedir+0x100/0x100\n[90701.904486] [] cifs_readdir+0x45b/0x8f0 [cifs]\n[90701.911288] [] ? fillonedir+0x100/0x100\n[90701.917410] [] ? fillonedir+0x100/0x100\n[90701.923533] [] ? fillonedir+0x100/0x100\n[90701.929657] [] vfs_readdir+0xb8/0xe0\n[90701.935490] [] sys_getdents+0x8f/0x110\n[90701.941521] [] system_call_fastpath+0x16/0x1b\n[90701.948222] Code: 66 90 55 65 48 8b 04 25 f0 c6 00 00 48 89 e5 53 48 83 ec 08 83 fe 01 48 8b 98 48 e0 ff ff 48 c7 80 48 e0 ff ff ff ff ff ff 74 22 <48> 8b 47 28 ff 50 68 65 48 8b 14 25 f0 c6 00 00 48 89 9a 48 e0\n[90701.970313] RIP [] kernel_setsockopt+0x2e/0x60\n[90701.977125] RSP \n[90701.981018] CR2: 0000000000000028\n[90701.984809] ---[ end trace 24bd602971110a43 ]---\n\nThis is likely due to a race vs. a reconnection event.\n\nThe current code checks for a NULL socket in smb_send_kvec, but that's\ntoo late. By the time that check is done, the socket will already have\nbeen passed to kernel_setsockopt. Move the check into smb_send_rqst, so\nthat it's checked earlier.\n\nIn truth, this is a bit of a half-assed fix. The -ENOTSOCK error\nreturn here looks like it could bubble back up to userspace. The locking\nrules around the ssocket pointer are really unclear as well. There are\ncases where the ssocket pointer is changed without holding the srv_mutex,\nbut I'm not clear whether there's a potential race here yet or not.\n\nThis code seems like it could benefit from some fundamental re-think of\nhow the socket handling should behave. Until then though, this patch\nshould at least fix the above oops in most cases.\n\nCc: # 3.7+\nReported-and-Tested-by: CAI Qian \nSigned-off-by: Jeff Layton \nSigned-off-by: Steve French '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void AveragePool(const uint8* input_data, const Dims<4>& input_dims, int stride,\n int pad_width, int pad_height, int filter_width,\n int filter_height, int32 output_activation_min,\n int32 output_activation_max, uint8* output_data,\n const Dims<4>& output_dims) {\n AveragePool(input_data, input_dims, stride, stride, pad_width, pad_height,\n filter_width, filter_height, output_activation_min,\n output_activation_max, output_data, output_dims);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-835'], 'message': 'Prevent a division by 0 in average ops.\n\nPiperOrigin-RevId: 385184660\nChange-Id: I7affd4554f9b336fca29ac68f633232c094d0bd3'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: inline void AveragePool(const PoolParams& params,\n const RuntimeShape& input_shape,\n const int8_t* input_data,\n const RuntimeShape& output_shape, int8_t* output_data) {\n TFLITE_DCHECK_LE(params.quantized_activation_min,\n params.quantized_activation_max);\n TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 4);\n TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 4);\n const int batches = MatchingDim(input_shape, 0, output_shape, 0);\n const int depth = MatchingDim(input_shape, 3, output_shape, 3);\n const int input_height = input_shape.Dims(1);\n const int input_width = input_shape.Dims(2);\n const int output_height = output_shape.Dims(1);\n const int output_width = output_shape.Dims(2);\n const int stride_height = params.stride_height;\n const int stride_width = params.stride_width;\n for (int batch = 0; batch < batches; ++batch) {\n for (int out_y = 0; out_y < output_height; ++out_y) {\n for (int out_x = 0; out_x < output_width; ++out_x) {\n for (int channel = 0; channel < depth; ++channel) {\n const int in_x_origin =\n (out_x * stride_width) - params.padding_values.width;\n const int in_y_origin =\n (out_y * stride_height) - params.padding_values.height;\n // Compute the boundaries of the filter region clamped so as to\n // ensure that the filter window fits in the input array.\n const int filter_x_start = std::max(0, -in_x_origin);\n const int filter_x_end =\n std::min(params.filter_width, input_width - in_x_origin);\n const int filter_y_start = std::max(0, -in_y_origin);\n const int filter_y_end =\n std::min(params.filter_height, input_height - in_y_origin);\n int32_t acc = 0;\n int filter_count = 0;\n for (int filter_y = filter_y_start; filter_y < filter_y_end;\n ++filter_y) {\n for (int filter_x = filter_x_start; filter_x < filter_x_end;\n ++filter_x) {\n const int in_x = in_x_origin + filter_x;\n const int in_y = in_y_origin + filter_y;\n acc +=\n input_data[Offset(input_shape, batch, in_y, in_x, channel)];\n filter_count++;\n }\n }\n // Round to the closest integer value.\n acc = acc > 0 ? (acc + filter_count / 2) / filter_count\n : (acc - filter_count / 2) / filter_count;\n acc = std::max(acc, params.quantized_activation_min);\n acc = std::min(acc, params.quantized_activation_max);\n output_data[Offset(output_shape, batch, out_y, out_x, channel)] =\n static_cast(acc);\n }\n }\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-835'], 'message': 'Prevent a division by 0 in average ops.\n\nPiperOrigin-RevId: 385184660\nChange-Id: I7affd4554f9b336fca29ac68f633232c094d0bd3'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: lexer_current_is_literal (parser_context_t *context_p, /**< context */\n const lexer_lit_location_t *right_ident_p) /**< identifier */\n{\n JERRY_ASSERT (context_p->token.type == LEXER_LITERAL\n && context_p->token.lit_location.type == LEXER_IDENT_LITERAL);\n\n lexer_lit_location_t *left_ident_p = &context_p->token.lit_location;\n\n JERRY_ASSERT (left_ident_p->length > 0 && right_ident_p->length > 0);\n\n if (left_ident_p->length != right_ident_p->length)\n {\n return false;\n }\n\n if (!left_ident_p->has_escape && !right_ident_p->has_escape)\n {\n return memcmp (left_ident_p->char_p, right_ident_p->char_p, left_ident_p->length) == 0;\n }\n\n return lexer_compare_identifiers (context_p, left_ident_p, right_ident_p);\n} /* lexer_current_is_literal */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Improve parse_identifier (#4691)\n\nAscii string length is no longer computed during string allocation.\r\n\r\nJerryScript-DCO-1.0-Signed-off-by: Daniel Batiz batizjob@gmail.com'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: parser_module_handle_module_specifier (parser_context_t *context_p, /**< parser context */\n ecma_module_node_t **node_list_p) /**< target node list */\n{\n if (context_p->token.type != LEXER_LITERAL\n || context_p->token.lit_location.type != LEXER_STRING_LITERAL\n || context_p->token.lit_location.length == 0)\n {\n parser_raise_error (context_p, PARSER_ERR_STRING_EXPECTED);\n }\n\n lexer_construct_literal_object (context_p, &context_p->token.lit_location, LEXER_STRING_LITERAL);\n\n lexer_literal_t *path_p = context_p->lit_object.literal_p;\n\n lexer_next_token (context_p);\n\n /* The lexer_next_token may throw an error, so the path is constructed after its call. */\n ecma_string_t *path_string_p = ecma_new_ecma_string_from_utf8 (path_p->u.char_p, path_p->prop.length);\n\n ecma_module_node_t *node_p = JERRY_CONTEXT (module_current_p)->imports_p;\n ecma_module_node_t *last_node_p = NULL;\n\n /* Check if we have an import node with the same module request. */\n\n while (node_p != NULL)\n {\n if (ecma_compare_ecma_strings (ecma_get_string_from_value (node_p->u.path_or_module), path_string_p))\n {\n ecma_deref_ecma_string (path_string_p);\n break;\n }\n\n last_node_p = node_p;\n node_p = node_p->next_p;\n }\n\n if (node_p == NULL)\n {\n node_p = (ecma_module_node_t *) jmem_heap_alloc_block_null_on_error (sizeof (ecma_module_node_t));\n\n if (node_p == NULL)\n {\n ecma_deref_ecma_string (path_string_p);\n parser_raise_error (context_p, PARSER_ERR_OUT_OF_MEMORY);\n }\n\n if (last_node_p == NULL)\n {\n JERRY_CONTEXT (module_current_p)->imports_p = node_p;\n }\n else\n {\n last_node_p->next_p = node_p;\n }\n\n node_p->next_p = NULL;\n node_p->module_names_p = NULL;\n node_p->u.path_or_module = ecma_make_string_value (path_string_p);\n }\n\n /* Append to imports. */\n if (node_list_p == NULL)\n {\n parser_module_append_names (context_p, &node_p->module_names_p);\n return;\n }\n\n ecma_value_t *module_object_p = &node_p->u.path_or_module;\n\n node_p = *node_list_p;\n last_node_p = NULL;\n\n while (node_p != NULL)\n {\n if (node_p->u.module_object_p == module_object_p)\n {\n parser_module_append_names (context_p, &node_p->module_names_p);\n return;\n }\n\n last_node_p = node_p;\n node_p = node_p->next_p;\n }\n\n node_p = (ecma_module_node_t *) parser_malloc (context_p, sizeof (ecma_module_node_t));\n\n if (last_node_p == NULL)\n {\n *node_list_p = node_p;\n }\n else\n {\n last_node_p->next_p = node_p;\n }\n\n node_p->next_p = NULL;\n node_p->module_names_p = context_p->module_names_p;\n node_p->u.module_object_p = module_object_p;\n\n context_p->module_names_p = NULL;\n} /* parser_module_handle_module_specifier */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Improve parse_identifier (#4691)\n\nAscii string length is no longer computed during string allocation.\r\n\r\nJerryScript-DCO-1.0-Signed-off-by: Daniel Batiz batizjob@gmail.com'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: main (void)\n{\n TEST_INIT ();\n\n const lit_utf8_byte_t *ptrs[test_sub_iters];\n ecma_number_t numbers[test_sub_iters];\n lit_utf8_byte_t strings[test_sub_iters][max_characters_in_string + 1];\n lit_utf8_size_t lengths[test_sub_iters];\n\n jmem_init ();\n\n for (uint32_t i = 0; i < test_iters; i++)\n {\n memset (numbers, 0, sizeof (ecma_number_t) * test_sub_iters);\n memset (lengths, 0, sizeof (lit_utf8_size_t) * test_sub_iters);\n memset (ptrs, 0, sizeof (lit_utf8_byte_t *) * test_sub_iters);\n\n for (uint32_t j = 0; j < test_sub_iters; j++)\n {\n int type = rand () % 3;\n if (type == 0)\n {\n lengths[j] = (lit_utf8_size_t) (rand () % max_characters_in_string + 1);\n generate_string (strings[j], lengths[j]);\n ecma_find_or_create_literal_string (strings[j], lengths[j]);\n strings[j][lengths[j]] = '\\0';\n ptrs[j] = strings[j];\n TEST_ASSERT (ptrs[j]);\n }\n else if (type == 1)\n {\n lit_magic_string_id_t msi = (lit_magic_string_id_t) (rand () % LIT_NON_INTERNAL_MAGIC_STRING__COUNT);\n ptrs[j] = lit_get_magic_string_utf8 (msi);\n TEST_ASSERT (ptrs[j]);\n lengths[j] = (lit_utf8_size_t) lit_zt_utf8_string_size (ptrs[j]);\n ecma_find_or_create_literal_string (ptrs[j], lengths[j]);\n }\n else\n {\n ecma_number_t num = generate_number ();\n lengths[j] = ecma_number_to_utf8_string (num, strings[j], max_characters_in_string);\n ecma_find_or_create_literal_number (num);\n }\n }\n\n /* Add empty string. */\n ecma_find_or_create_literal_string (NULL, 0);\n\n for (uint32_t j = 0; j < test_sub_iters; j++)\n {\n ecma_value_t lit1;\n ecma_value_t lit2;\n if (ptrs[j])\n {\n lit1 = ecma_find_or_create_literal_string (ptrs[j], lengths[j]);\n lit2 = ecma_find_or_create_literal_string (ptrs[j], lengths[j]);\n TEST_ASSERT (ecma_is_value_string (lit1));\n TEST_ASSERT (ecma_is_value_string (lit2));\n TEST_ASSERT (lit1 == lit2);\n }\n else\n {\n lit1 = ecma_find_or_create_literal_number (numbers[j]);\n lit2 = ecma_find_or_create_literal_number (numbers[j]);\n TEST_ASSERT (ecma_is_value_number (lit1));\n TEST_ASSERT (ecma_is_value_number (lit2));\n TEST_ASSERT (lit1 == lit2);\n }\n }\n\n /* Check empty string exists. */\n TEST_ASSERT (ecma_find_or_create_literal_string (NULL, 0) != JMEM_CP_NULL);\n }\n\n ecma_finalize_lit_storage ();\n jmem_finalize ();\n return 0;\n} /* main */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Improve parse_identifier (#4691)\n\nAscii string length is no longer computed during string allocation.\r\n\r\nJerryScript-DCO-1.0-Signed-off-by: Daniel Batiz batizjob@gmail.com'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: scanner_check_variables (parser_context_t *context_p) /**< context */\n{\n scanner_info_t *info_p = context_p->next_scanner_info_p;\n const uint8_t *next_data_p = (const uint8_t *) (info_p + 1);\n lexer_lit_location_t literal;\n\n JERRY_ASSERT (info_p->type == SCANNER_TYPE_FUNCTION);\n\n literal.char_p = info_p->source_p - 1;\n\n while (next_data_p[0] != SCANNER_STREAM_TYPE_END)\n {\n uint32_t type = next_data_p[0] & SCANNER_STREAM_TYPE_MASK;\n const uint8_t *data_p = next_data_p;\n\n JERRY_ASSERT (type != SCANNER_STREAM_TYPE_HOLE\n && !SCANNER_STREAM_TYPE_IS_ARG (type)\n && !SCANNER_STREAM_TYPE_IS_ARG_FUNC (type));\n JERRY_ASSERT (data_p[0] & SCANNER_STREAM_NO_REG);\n\n if (!(data_p[0] & SCANNER_STREAM_UINT16_DIFF))\n {\n if (data_p[2] != 0)\n {\n literal.char_p += data_p[2];\n next_data_p += 2 + 1;\n }\n else\n {\n memcpy (&literal.char_p, data_p + 2 + 1, sizeof (uintptr_t));\n next_data_p += 2 + 1 + sizeof (uintptr_t);\n }\n }\n else\n {\n int32_t diff = ((int32_t) data_p[2]) | ((int32_t) data_p[3]) << 8;\n\n if (diff <= (intptr_t) UINT8_MAX)\n {\n diff = -diff;\n }\n\n literal.char_p += diff;\n next_data_p += 2 + 2;\n }\n\n literal.length = data_p[1];\n literal.type = LEXER_IDENT_LITERAL;\n literal.has_escape = (data_p[0] & SCANNER_STREAM_HAS_ESCAPE) ? 1 : 0;\n\n lexer_construct_literal_object (context_p, &literal, LEXER_NEW_IDENT_LITERAL);\n literal.char_p += data_p[1];\n\n#if JERRY_MODULE_SYSTEM\n if (type == SCANNER_STREAM_TYPE_IMPORT)\n {\n continue;\n }\n#endif /* JERRY_MODULE_SYSTEM */\n\n context_p->lit_object.literal_p->status_flags |= LEXER_FLAG_USED;\n\n uint16_t opcode;\n if (type == SCANNER_STREAM_TYPE_VAR || type == SCANNER_STREAM_TYPE_FUNC)\n {\n opcode = CBC_CHECK_VAR;\n }\n else\n {\n opcode = CBC_CHECK_LET;\n }\n\n parser_emit_cbc_literal (context_p, opcode, context_p->lit_object.index);\n }\n\n parser_flush_cbc (context_p);\n} /* scanner_check_variables */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Improve parse_identifier (#4691)\n\nAscii string length is no longer computed during string allocation.\r\n\r\nJerryScript-DCO-1.0-Signed-off-by: Daniel Batiz batizjob@gmail.com'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: av_cold int ff_vc2enc_init_transforms(VC2TransformContext *s, int p_width, int p_height)\n{\n s->vc2_subband_dwt[VC2_TRANSFORM_9_7] = vc2_subband_dwt_97;\n s->vc2_subband_dwt[VC2_TRANSFORM_5_3] = vc2_subband_dwt_53;\n\n s->buffer = av_malloc(2*p_width*p_height*sizeof(dwtcoef));\n if (!s->buffer)\n return 1;\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'vc2enc_dwt: pad the temporary buffer by the slice size\n\nSince non-Haar wavelets need to look into pixels outside the frame, we\nneed to pad the buffer. The old factor of two seemed to be a workaround\nthat fact and only padded to the left and bottom. This correctly pads\nby the slice size and as such reduces memory usage and potential\nexploits.\nReported by Liu Bingchang.\n\nIdeally, there should be no temporary buffer but the encoder is designed\nto deinterleave the coefficients into the classical wavelet structure\nwith the lower frequency values in the top left corner.\n\nSigned-off-by: Rostislav Pehlivanov \n(cherry picked from commit 3228ac730c11eca49d5680d5550128e397061c85)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: proto_register_sysdig_event(void)\n{\n /* XXX Match up with Sysdig's names. */\n static hf_register_info hf[] = {\n { &hf_se_cpu_id,\n { \"CPU ID\", \"sysdig.cpu_id\",\n FT_UINT16, BASE_DEC, NULL, 0, NULL, HFILL }\n },\n { &hf_se_thread_id,\n { \"Thread ID\", \"sysdig.thread_id\",\n FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL }\n },\n { &hf_se_event_length,\n { \"Event length\", \"sysdig.event_len\",\n FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL }\n },\n { &hf_se_nparams,\n { \"Number of parameters\", \"sysdig.nparams\",\n FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL }\n },\n { &hf_se_event_type,\n { \"Event type\", \"sysdig.event_type\",\n FT_UINT16, BASE_DEC, VALS(event_type_vals), 0, NULL, HFILL }\n },\n { &hf_se_param_lens,\n { \"Parameter lengths\", \"sysdig.param.lens\",\n FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL }\n },\n { &hf_se_param_len,\n { \"Parameter length\", \"sysdig.param.len\",\n FT_UINT16, BASE_DEC, NULL, 0, NULL, HFILL }\n },\n\n/* Header field registration. Automatically generated by tools/generate-sysdig-event.py */\n { &hf_param_ID_bytes, { \"ID\", \"sysdig.param.syscall.ID\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_action_uint32, { \"action\", \"sysdig.param.cpu_hotplug.action\", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_addr_bytes, { \"addr\", \"sysdig.param.ptrace.addr\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_addr_uint64, { \"addr\", \"sysdig.param.page_fault.addr\", FT_UINT64, BASE_HEX, NULL, 0, NULL, HFILL } },\n { &hf_param_args_string, { \"Program arguments\", \"sysdig.param.execve.args\", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_argument_uint64, { \"I/O control: argument\", \"sysdig.param.ioctl.argument\", FT_UINT64, BASE_HEX, NULL, 0, NULL, HFILL } },\n { &hf_param_backlog_uint32, { \"backlog\", \"sysdig.param.listen.backlog\", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_cgroups_bytes, { \"cgroups\", \"sysdig.param.execve.cgroups\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_clockid_uint8, { \"clockid\", \"sysdig.param.timerfd_create.clockid\", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_cmd_bytes, { \"cmd\", \"sysdig.param.semctl.cmd\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_cmd_int64, { \"cmd\", \"sysdig.param.bpf.cmd\", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_comm_string, { \"Command\", \"sysdig.param.execve.comm\", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_cpu_sys_uint64, { \"cpu_sys\", \"sysdig.param.procinfo.cpu_sys\", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_cpu_uint32, { \"cpu\", \"sysdig.param.cpu_hotplug.cpu\", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_cpu_usr_uint64, { \"cpu_usr\", \"sysdig.param.procinfo.cpu_usr\", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_cur_int64, { \"cur\", \"sysdig.param.setrlimit.cur\", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_cwd_string, { \"Current working directory\", \"sysdig.param.execve.cwd\", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_data_bytes, { \"data\", \"sysdig.param.ptrace.data\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_desc_string, { \"desc\", \"sysdig.param.notification.desc\", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_description_string, { \"description\", \"sysdig.param.infra.description\", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_dev_string, { \"dev\", \"sysdig.param.mount.dev\", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_dev_uint32, { \"dev\", \"sysdig.param.openat.dev\", FT_UINT32, BASE_HEX, NULL, 0, NULL, HFILL } },\n { &hf_param_dir_string, { \"dir\", \"sysdig.param.mount.dir\", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_dirfd_int64, { \"dirfd\", \"sysdig.param.openat.dirfd\", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_domain_bytes, { \"domain\", \"sysdig.param.socketpair.domain\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_dpid_bytes, { \"dpid\", \"sysdig.param.signaldeliver.dpid\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_dqb_bhardlimit_uint64, { \"dqb_bhardlimit\", \"sysdig.param.quotactl.dqb_bhardlimit\", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_dqb_bsoftlimit_uint64, { \"dqb_bsoftlimit\", \"sysdig.param.quotactl.dqb_bsoftlimit\", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_dqb_btime_bytes, { \"dqb_btime\", \"sysdig.param.quotactl.dqb_btime\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_dqb_curspace_uint64, { \"dqb_curspace\", \"sysdig.param.quotactl.dqb_curspace\", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_dqb_ihardlimit_uint64, { \"dqb_ihardlimit\", \"sysdig.param.quotactl.dqb_ihardlimit\", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_dqb_isoftlimit_uint64, { \"dqb_isoftlimit\", \"sysdig.param.quotactl.dqb_isoftlimit\", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_dqb_itime_bytes, { \"dqb_itime\", \"sysdig.param.quotactl.dqb_itime\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_dqi_bgrace_bytes, { \"dqi_bgrace\", \"sysdig.param.quotactl.dqi_bgrace\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_dqi_flags_bytes, { \"dqi_flags\", \"sysdig.param.quotactl.dqi_flags\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_dqi_igrace_bytes, { \"dqi_igrace\", \"sysdig.param.quotactl.dqi_igrace\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_egid_bytes, { \"egid\", \"sysdig.param.getresgid.egid\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_env_string, { \"env\", \"sysdig.param.execve.env\", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_error_bytes, { \"error\", \"sysdig.param.page_fault.error\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_euid_bytes, { \"euid\", \"sysdig.param.getresuid.euid\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_event_data_uint64, { \"event_data\", \"sysdig.param.sysdigevent.event_data\", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_event_type_uint32, { \"event_type\", \"sysdig.param.sysdigevent.event_type\", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_exe_string, { \"exe\", \"sysdig.param.execve.exe\", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_fd1_int64, { \"fd1\", \"sysdig.param.pipe.fd1\", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_fd2_int64, { \"fd2\", \"sysdig.param.pipe.fd2\", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_fd_in_int64, { \"fd_in\", \"sysdig.param.splice.fd_in\", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_fd_int64, { \"fd\", \"sysdig.param.openat.fd\", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_fd_out_int64, { \"fd_out\", \"sysdig.param.splice.fd_out\", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_fdlimit_int64, { \"fdlimit\", \"sysdig.param.vfork.fdlimit\", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_fdlimit_uint64, { \"fdlimit\", \"sysdig.param.execve.fdlimit\", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_fds_bytes, { \"fds\", \"sysdig.param.ppoll.fds\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_filename_string, { \"filename\", \"sysdig.param.execve.filename\", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_flags_bytes, { \"flags\", \"sysdig.param.linkat.flags\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_flags_uint32, { \"flags\", \"sysdig.param.accept.flags\", FT_UINT32, BASE_HEX, NULL, 0, NULL, HFILL } },\n { &hf_param_gid_bytes, { \"gid\", \"sysdig.param.getgid.gid\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_gid_uint32, { \"gid\", \"sysdig.param.vfork.gid\", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_how_bytes, { \"how\", \"sysdig.param.shutdown.how\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_id_int64, { \"id\", \"sysdig.param.tracer.id\", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_id_string, { \"id\", \"sysdig.param.notification.id\", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_id_uint32, { \"id\", \"sysdig.param.quotactl.id\", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_image_string, { \"image\", \"sysdig.param.container.image\", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_in_fd_int64, { \"in_fd\", \"sysdig.param.sendfile.in_fd\", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_initval_uint64, { \"initval\", \"sysdig.param.eventfd.initval\", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_ino_uint64, { \"ino\", \"sysdig.param.pipe.ino\", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_interval_bytes, { \"interval\", \"sysdig.param.nanosleep.interval\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_ip_uint64, { \"ip\", \"sysdig.param.page_fault.ip\", FT_UINT64, BASE_HEX, NULL, 0, NULL, HFILL } },\n { &hf_param_json_string, { \"json\", \"sysdig.param.container.json\", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_key_int32, { \"key\", \"sysdig.param.semget.key\", FT_INT32, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_length_uint64, { \"length\", \"sysdig.param.munmap.length\", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_level_bytes, { \"level\", \"sysdig.param.getsockopt.level\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_linkdirfd_int64, { \"linkdirfd\", \"sysdig.param.symlinkat.linkdirfd\", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_linkpath_string, { \"linkpath\", \"sysdig.param.symlinkat.linkpath\", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_loginuid_int32, { \"loginuid\", \"sysdig.param.execve.loginuid\", FT_INT32, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_mask_uint32, { \"mask\", \"sysdig.param.signalfd.mask\", FT_UINT32, BASE_HEX, NULL, 0, NULL, HFILL } },\n { &hf_param_max_int64, { \"max\", \"sysdig.param.setrlimit.max\", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_maxevents_bytes, { \"maxevents\", \"sysdig.param.epoll_wait.maxevents\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_mode_bytes, { \"mode\", \"sysdig.param.access.mode\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_mode_uint32, { \"mode\", \"sysdig.param.openat.mode\", FT_UINT32, BASE_OCT, NULL, 0, NULL, HFILL } },\n { &hf_param_name_string, { \"name\", \"sysdig.param.openat.name\", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_nativeID_uint16, { \"nativeID\", \"sysdig.param.syscall.nativeID\", FT_UINT16, BASE_DEC, VALS(nativeID_uint16_vals), 0, NULL, HFILL } },\n { &hf_param_newcur_int64, { \"newcur\", \"sysdig.param.prlimit.newcur\", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_newdir_int64, { \"newdir\", \"sysdig.param.linkat.newdir\", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_newdirfd_int64, { \"newdirfd\", \"sysdig.param.renameat.newdirfd\", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_newmax_int64, { \"newmax\", \"sysdig.param.prlimit.newmax\", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_newpath_string, { \"newpath\", \"sysdig.param.linkat.newpath\", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_next_bytes, { \"next\", \"sysdig.param.switch.next\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_nsems_int32, { \"nsems\", \"sysdig.param.semget.nsems\", FT_INT32, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_nsops_uint32, { \"nsops\", \"sysdig.param.semop.nsops\", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_nstype_bytes, { \"nstype\", \"sysdig.param.setns.nstype\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_offset_uint64, { \"offset\", \"sysdig.param.sendfile.offset\", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_oldcur_int64, { \"oldcur\", \"sysdig.param.prlimit.oldcur\", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_olddir_int64, { \"olddir\", \"sysdig.param.linkat.olddir\", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_olddirfd_int64, { \"olddirfd\", \"sysdig.param.renameat.olddirfd\", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_oldmax_int64, { \"oldmax\", \"sysdig.param.prlimit.oldmax\", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_oldpath_string, { \"oldpath\", \"sysdig.param.linkat.oldpath\", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_op_bytes, { \"op\", \"sysdig.param.futex.op\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_op_uint64, { \"op\", \"sysdig.param.seccomp.op\", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_operation_bytes, { \"operation\", \"sysdig.param.flock.operation\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_optlen_uint32, { \"optlen\", \"sysdig.param.getsockopt.optlen\", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_optname_bytes, { \"optname\", \"sysdig.param.getsockopt.optname\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_out_fd_int64, { \"out_fd\", \"sysdig.param.sendfile.out_fd\", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_path_string, { \"path\", \"sysdig.param.mkdirat.path\", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_peer_uint64, { \"peer\", \"sysdig.param.socketpair.peer\", FT_UINT64, BASE_HEX, NULL, 0, NULL, HFILL } },\n { &hf_param_pgft_maj_uint64, { \"pgft_maj\", \"sysdig.param.execve.pgft_maj\", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_pgft_min_uint64, { \"pgft_min\", \"sysdig.param.execve.pgft_min\", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_pgid_bytes, { \"pgid\", \"sysdig.param.setpgid.pgid\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_pgoffset_uint64, { \"pgoffset\", \"sysdig.param.mmap2.pgoffset\", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_pid_bytes, { \"pid\", \"sysdig.param.setpgid.pid\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_pos_uint64, { \"pos\", \"sysdig.param.pwritev.pos\", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_prot_bytes, { \"prot\", \"sysdig.param.mmap2.prot\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_proto_uint32, { \"proto\", \"sysdig.param.socketpair.proto\", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_ptid_bytes, { \"ptid\", \"sysdig.param.execve.ptid\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_queuelen_uint32, { \"queuelen\", \"sysdig.param.accept.queuelen\", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_queuemax_uint32, { \"queuemax\", \"sysdig.param.accept.queuemax\", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_queuepct_uint8, { \"Accept queue per connection\", \"sysdig.param.accept.queuepct\", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_quota_fmt_bytes, { \"quota_fmt\", \"sysdig.param.quotactl.quota_fmt\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_quota_fmt_out_bytes, { \"quota_fmt_out\", \"sysdig.param.quotactl.quota_fmt_out\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_quotafilepath_string, { \"quotafilepath\", \"sysdig.param.quotactl.quotafilepath\", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_ratio_uint32, { \"ratio\", \"sysdig.param.drop.ratio\", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_request_bytes, { \"request\", \"sysdig.param.ptrace.request\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_request_uint64, { \"I/O control: request\", \"sysdig.param.ioctl.request\", FT_UINT64, BASE_HEX, NULL, 0, NULL, HFILL } },\n { &hf_param_res_bytes, { \"res\", \"sysdig.param.linkat.res\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_res_int64, { \"res\", \"sysdig.param.fcntl.res\", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_res_or_fd_bytes, { \"res_or_fd\", \"sysdig.param.bpf.res_or_fd\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_res_uint64, { \"res\", \"sysdig.param.mmap2.res\", FT_UINT64, BASE_HEX, NULL, 0, NULL, HFILL } },\n { &hf_param_resource_bytes, { \"resource\", \"sysdig.param.prlimit.resource\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_rgid_bytes, { \"rgid\", \"sysdig.param.getresgid.rgid\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_ruid_bytes, { \"ruid\", \"sysdig.param.getresuid.ruid\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_scope_string, { \"scope\", \"sysdig.param.infra.scope\", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_sem_flg_0_bytes, { \"sem_flg_0\", \"sysdig.param.semop.sem_flg_0\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_sem_flg_1_bytes, { \"sem_flg_1\", \"sysdig.param.semop.sem_flg_1\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_sem_num_0_uint16, { \"sem_num_0\", \"sysdig.param.semop.sem_num_0\", FT_UINT16, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_sem_num_1_uint16, { \"sem_num_1\", \"sysdig.param.semop.sem_num_1\", FT_UINT16, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_sem_op_0_int16, { \"sem_op_0\", \"sysdig.param.semop.sem_op_0\", FT_INT16, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_sem_op_1_int16, { \"sem_op_1\", \"sysdig.param.semop.sem_op_1\", FT_INT16, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_semflg_bytes, { \"semflg\", \"sysdig.param.semget.semflg\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_semid_int32, { \"semid\", \"sysdig.param.semctl.semid\", FT_INT32, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_semnum_int32, { \"semnum\", \"sysdig.param.semctl.semnum\", FT_INT32, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_sgid_bytes, { \"sgid\", \"sysdig.param.getresgid.sgid\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_sig_bytes, { \"sig\", \"sysdig.param.signaldeliver.sig\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_sigmask_bytes, { \"sigmask\", \"sysdig.param.ppoll.sigmask\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_size_uint32, { \"size\", \"sysdig.param.pwritev.size\", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_size_uint64, { \"size\", \"sysdig.param.sendfile.size\", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_source_string, { \"source\", \"sysdig.param.infra.source\", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_source_uint64, { \"source\", \"sysdig.param.socketpair.source\", FT_UINT64, BASE_HEX, NULL, 0, NULL, HFILL } },\n { &hf_param_special_string, { \"special\", \"sysdig.param.quotactl.special\", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_spid_bytes, { \"spid\", \"sysdig.param.signaldeliver.spid\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_status_bytes, { \"status\", \"sysdig.param.procexit.status\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_suid_bytes, { \"suid\", \"sysdig.param.getresuid.suid\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_tags_bytes, { \"tags\", \"sysdig.param.tracer.tags\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_target_string, { \"target\", \"sysdig.param.symlinkat.target\", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_tid_bytes, { \"tid\", \"sysdig.param.execve.tid\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_timeout_bytes, { \"timeout\", \"sysdig.param.ppoll.timeout\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_timeout_int64, { \"timeout\", \"sysdig.param.poll.timeout\", FT_INT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_tty_int32, { \"tty\", \"sysdig.param.execve.tty\", FT_INT32, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_tuple_bytes, { \"tuple\", \"sysdig.param.accept.tuple\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_type_bytes, { \"type\", \"sysdig.param.quotactl.type\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_type_string, { \"type\", \"sysdig.param.mount.type\", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_type_uint32, { \"type\", \"sysdig.param.container.type\", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_uid_bytes, { \"uid\", \"sysdig.param.getuid.uid\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_uid_uint32, { \"uid\", \"sysdig.param.vfork.uid\", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_val_bytes, { \"val\", \"sysdig.param.getsockopt.val\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_val_int32, { \"val\", \"sysdig.param.semctl.val\", FT_INT32, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_val_uint64, { \"val\", \"sysdig.param.futex.val\", FT_UINT64, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_vm_rss_uint32, { \"vm_rss\", \"sysdig.param.execve.vm_rss\", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_vm_size_uint32, { \"vm_size\", \"sysdig.param.execve.vm_size\", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_vm_swap_uint32, { \"vm_swap\", \"sysdig.param.execve.vm_swap\", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },\n { &hf_param_vpid_bytes, { \"vpid\", \"sysdig.param.vfork.vpid\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_vtid_bytes, { \"vtid\", \"sysdig.param.vfork.vtid\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_whence_bytes, { \"whence\", \"sysdig.param.llseek.whence\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_ret_bytes, { \"ret\", \"sysdig.param.procexit.ret\", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } },\n { &hf_param_core_uint8, { \"core\", \"sysdig.param.procexit.core\", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } },\n };\n\n /* Setup protocol subtree array */\n static gint *ett[] = {\n &ett_sysdig_event,\n &ett_sysdig_parm_lens,\n &ett_sysdig_syscall\n };\n\n /* Register the protocol name and description */\n proto_sysdig_event = proto_register_protocol(\"Sysdig System Call\",\n \"Sysdig Event\", \"sysdig\");\n\n /* Required function calls to register the header fields and subtrees */\n proto_register_field_array(proto_sysdig_event, hf, array_length(hf));\n proto_register_subtree_array(ett, array_length(ett));\n\n register_dissector(\"sysdig\", dissect_sysdig_event, proto_sysdig_event);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'dissectors: re-generated sysdig events using provided tool.\n\nSigned-off-by: Federico Di Pierro '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int prepend_path(const struct path *path,\n\t\t\tconst struct path *root,\n\t\t\tchar **buffer, int *buflen)\n{\n\tstruct dentry *dentry;\n\tstruct vfsmount *vfsmnt;\n\tstruct mount *mnt;\n\tint error = 0;\n\tunsigned seq, m_seq = 0;\n\tchar *bptr;\n\tint blen;\n\n\trcu_read_lock();\nrestart_mnt:\n\tread_seqbegin_or_lock(&mount_lock, &m_seq);\n\tseq = 0;\n\trcu_read_lock();\nrestart:\n\tbptr = *buffer;\n\tblen = *buflen;\n\terror = 0;\n\tdentry = path->dentry;\n\tvfsmnt = path->mnt;\n\tmnt = real_mount(vfsmnt);\n\tread_seqbegin_or_lock(&rename_lock, &seq);\n\twhile (dentry != root->dentry || vfsmnt != root->mnt) {\n\t\tstruct dentry * parent;\n\n\t\tif (dentry == vfsmnt->mnt_root || IS_ROOT(dentry)) {\n\t\t\tstruct mount *parent = ACCESS_ONCE(mnt->mnt_parent);\n\t\t\t/* Global root? */\n\t\t\tif (mnt != parent) {\n\t\t\t\tdentry = ACCESS_ONCE(mnt->mnt_mountpoint);\n\t\t\t\tmnt = parent;\n\t\t\t\tvfsmnt = &mnt->mnt;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!error)\n\t\t\t\terror = is_mounted(vfsmnt) ? 1 : 2;\n\t\t\tbreak;\n\t\t}\n\t\tparent = dentry->d_parent;\n\t\tprefetch(parent);\n\t\terror = prepend_name(&bptr, &blen, &dentry->d_name);\n\t\tif (error)\n\t\t\tbreak;\n\n\t\tdentry = parent;\n\t}\n\tif (!(seq & 1))\n\t\trcu_read_unlock();\n\tif (need_seqretry(&rename_lock, seq)) {\n\t\tseq = 1;\n\t\tgoto restart;\n\t}\n\tdone_seqretry(&rename_lock, seq);\n\n\tif (!(m_seq & 1))\n\t\trcu_read_unlock();\n\tif (need_seqretry(&mount_lock, m_seq)) {\n\t\tm_seq = 1;\n\t\tgoto restart_mnt;\n\t}\n\tdone_seqretry(&mount_lock, m_seq);\n\n\tif (error >= 0 && bptr == *buffer) {\n\t\tif (--blen < 0)\n\t\t\terror = -ENAMETOOLONG;\n\t\telse\n\t\t\t*--bptr = '/';\n\t}\n\t*buffer = bptr;\n\t*buflen = blen;\n\treturn error;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-401', 'CWE-254'], 'message': 'dcache: Handle escaped paths in prepend_path\n\nA rename can result in a dentry that by walking up d_parent\nwill never reach it's mnt_root. For lack of a better term\nI call this an escaped path.\n\nprepend_path is called by four different functions __d_path,\nd_absolute_path, d_path, and getcwd.\n\n__d_path only wants to see paths are connected to the root it passes\nin. So __d_path needs prepend_path to return an error.\n\nd_absolute_path similarly wants to see paths that are connected to\nsome root. Escaped paths are not connected to any mnt_root so\nd_absolute_path needs prepend_path to return an error greater\nthan 1. So escaped paths will be treated like paths on lazily\nunmounted mounts.\n\ngetcwd needs to prepend \"(unreachable)\" so getcwd also needs\nprepend_path to return an error.\n\nd_path is the interesting hold out. d_path just wants to print\nsomething, and does not care about the weird cases. Which raises\nthe question what should be printed?\n\nGiven that / should result in -ENOENT I\nbelieve it is desirable for escaped paths to be printed as empty\npaths. As there are not really any meaninful path components when\nconsidered from the perspective of a mount tree.\n\nSo tweak prepend_path to return an empty path with an new error\ncode of 3 when it encounters an escaped path.\n\nSigned-off-by: \"Eric W. Biederman\" \nSigned-off-by: Al Viro '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int ghash_final(struct shash_desc *desc, u8 *dst)\n{\n\tstruct ghash_desc_ctx *dctx = shash_desc_ctx(desc);\n\tstruct ghash_ctx *ctx = crypto_shash_ctx(desc->tfm);\n\tu8 *buf = dctx->buffer;\n\n\tghash_flush(ctx, dctx);\n\tmemcpy(dst, buf, GHASH_BLOCK_SIZE);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'crypto: ghash - Avoid null pointer dereference if no key is set\n\nThe ghash_update function passes a pointer to gf128mul_4k_lle which will\nbe NULL if ghash_setkey is not called or if the most recent call to\nghash_setkey failed to allocate memory. This causes an oops. Fix this\nup by returning an error code in the null case.\n\nThis is trivially triggered from unprivileged userspace through the\nAF_ALG interface by simply writing to the socket without setting a key.\n\nThe ghash_final function has a similar issue, but triggering it requires\na memory allocation failure in ghash_setkey _after_ at least one\nsuccessful call to ghash_update.\n\n BUG: unable to handle kernel NULL pointer dereference at 00000670\n IP: [] gf128mul_4k_lle+0x23/0x60 [gf128mul]\n *pde = 00000000\n Oops: 0000 [#1] PREEMPT SMP\n Modules linked in: ghash_generic gf128mul algif_hash af_alg nfs lockd nfs_acl sunrpc bridge ipv6 stp llc\n\n Pid: 1502, comm: hashatron Tainted: G W 3.1.0-rc9-00085-ge9308cf #32 Bochs Bochs\n EIP: 0060:[] EFLAGS: 00000202 CPU: 0\n EIP is at gf128mul_4k_lle+0x23/0x60 [gf128mul]\n EAX: d69db1f0 EBX: d6b8ddac ECX: 00000004 EDX: 00000000\n ESI: 00000670 EDI: d6b8ddac EBP: d6b8ddc8 ESP: d6b8dda4\n DS: 007b ES: 007b FS: 00d8 GS: 0033 SS: 0068\n Process hashatron (pid: 1502, ti=d6b8c000 task=d6810000 task.ti=d6b8c000)\n Stack:\n 00000000 d69db1f0 00000163 00000000 d6b8ddc8 c101a520 d69db1f0 d52aa000\n 00000ff0 d6b8dde8 d88d310f d6b8a3f8 d52aa000 00001000 d88d502c d6b8ddfc\n 00001000 d6b8ddf4 c11676ed d69db1e8 d6b8de24 c11679ad d52aa000 00000000\n Call Trace:\n [] ? kmap_atomic_prot+0x37/0xa6\n [] ghash_update+0x85/0xbe [ghash_generic]\n [] crypto_shash_update+0x18/0x1b\n [] shash_ahash_update+0x22/0x36\n [] shash_async_update+0xb/0xd\n [] hash_sendpage+0xba/0xf2 [algif_hash]\n [] kernel_sendpage+0x39/0x4e\n [] ? 0xd88cdfff\n [] sock_sendpage+0x37/0x3e\n [] ? kernel_sendpage+0x4e/0x4e\n [] pipe_to_sendpage+0x56/0x61\n [] splice_from_pipe_feed+0x58/0xcd\n [] ? splice_from_pipe_begin+0x10/0x10\n [] __splice_from_pipe+0x36/0x55\n [] ? splice_from_pipe_begin+0x10/0x10\n [] splice_from_pipe+0x51/0x64\n [] ? default_file_splice_write+0x2c/0x2c\n [] generic_splice_sendpage+0x13/0x15\n [] ? splice_from_pipe_begin+0x10/0x10\n [] do_splice_from+0x5d/0x67\n [] sys_splice+0x2bf/0x363\n [] ? sysenter_exit+0xf/0x16\n [] ? trace_hardirqs_on_caller+0x10e/0x13f\n [] sysenter_do_call+0x12/0x32\n Code: 83 c4 0c 5b 5e 5f c9 c3 55 b9 04 00 00 00 89 e5 57 8d 7d e4 56 53 8d 5d e4 83 ec 18 89 45 e0 89 55 dc 0f b6 70 0f c1 e6 04 01 d6 a5 be 0f 00 00 00 4e 89 d8 e8 48 ff ff ff 8b 45 e0 89 da 0f\n EIP: [] gf128mul_4k_lle+0x23/0x60 [gf128mul] SS:ESP 0068:d6b8dda4\n CR2: 0000000000000670\n ---[ end trace 4eaa2a86a8e2da24 ]---\n note: hashatron[1502] exited with preempt_count 1\n BUG: scheduling while atomic: hashatron/1502/0x10000002\n INFO: lockdep is turned off.\n [...]\n\nSigned-off-by: Nick Bowler \nCc: stable@kernel.org [2.6.37+]\nSigned-off-by: Herbert Xu '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: hb_set_clear (hb_set_t *set)\n{\n if (unlikely (hb_object_is_immutable (set)))\n return;\n\n set->clear ();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': '[set] Make all operators null-safe again\n\nChanged my mind.\n\nAlso for hb_map_clear().\n\nPart of https://github.com/harfbuzz/harfbuzz/pull/3162'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: SYSCALL_DEFINE5(osf_getsysinfo, unsigned long, op, void __user *, buffer,\n\t\tunsigned long, nbytes, int __user *, start, void __user *, arg)\n{\n\tunsigned long w;\n\tstruct percpu_struct *cpu;\n\n\tswitch (op) {\n\tcase GSI_IEEE_FP_CONTROL:\n\t\t/* Return current software fp control & status bits. */\n\t\t/* Note that DU doesn't verify available space here. */\n\n \t\tw = current_thread_info()->ieee_state & IEEE_SW_MASK;\n \t\tw = swcr_update_status(w, rdfpcr());\n\t\tif (put_user(w, (unsigned long __user *) buffer))\n\t\t\treturn -EFAULT;\n\t\treturn 0;\n\n\tcase GSI_IEEE_STATE_AT_SIGNAL:\n\t\t/*\n\t\t * Not sure anybody will ever use this weird stuff. These\n\t\t * ops can be used (under OSF/1) to set the fpcr that should\n\t\t * be used when a signal handler starts executing.\n\t\t */\n\t\tbreak;\n\n \tcase GSI_UACPROC:\n\t\tif (nbytes < sizeof(unsigned int))\n\t\t\treturn -EINVAL;\n \t\tw = (current_thread_info()->flags >> UAC_SHIFT) & UAC_BITMASK;\n \t\tif (put_user(w, (unsigned int __user *)buffer))\n \t\t\treturn -EFAULT;\n \t\treturn 1;\n\n\tcase GSI_PROC_TYPE:\n\t\tif (nbytes < sizeof(unsigned long))\n\t\t\treturn -EINVAL;\n\t\tcpu = (struct percpu_struct*)\n\t\t ((char*)hwrpb + hwrpb->processor_offset);\n\t\tw = cpu->type;\n\t\tif (put_user(w, (unsigned long __user*)buffer))\n\t\t\treturn -EFAULT;\n\t\treturn 1;\n\n\tcase GSI_GET_HWRPB:\n\t\tif (nbytes < sizeof(*hwrpb))\n\t\t\treturn -EINVAL;\n\t\tif (copy_to_user(buffer, hwrpb, nbytes) != 0)\n\t\t\treturn -EFAULT;\n\t\treturn 1;\n\n\tdefault:\n\t\tbreak;\n\t}\n\n\treturn -EOPNOTSUPP;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-264', 'CWE-189'], 'message': 'alpha: fix several security issues\n\nFix several security issues in Alpha-specific syscalls. Untested, but\nmostly trivial.\n\n1. Signedness issue in osf_getdomainname allows copying out-of-bounds\nkernel memory to userland.\n\n2. Signedness issue in osf_sysinfo allows copying large amounts of\nkernel memory to userland.\n\n3. Typo (?) in osf_getsysinfo bounds minimum instead of maximum copy\nsize, allowing copying large amounts of kernel memory to userland.\n\n4. Usage of user pointer in osf_wait4 while under KERNEL_DS allows\nprivilege escalation via writing return value of sys_wait4 to kernel\nmemory.\n\nSigned-off-by: Dan Rosenberg \nCc: Richard Henderson \nCc: Ivan Kokshaysky \nCc: Matt Turner \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool canContinue() override { return true; } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'CVE-2021-43825\n\nResponse filter manager crash\n\nSigned-off-by: Yan Avlasov '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int ext4_ext_convert_to_initialized(handle_t *handle,\n\t\t\t\t\t struct inode *inode,\n\t\t\t\t\t struct ext4_map_blocks *map,\n\t\t\t\t\t struct ext4_ext_path *path)\n{\n\tstruct ext4_extent *ex, newex, orig_ex;\n\tstruct ext4_extent *ex1 = NULL;\n\tstruct ext4_extent *ex2 = NULL;\n\tstruct ext4_extent *ex3 = NULL;\n\tstruct ext4_extent_header *eh;\n\text4_lblk_t ee_block, eof_block;\n\tunsigned int allocated, ee_len, depth;\n\text4_fsblk_t newblock;\n\tint err = 0;\n\tint ret = 0;\n\tint may_zeroout;\n\n\text_debug(\"ext4_ext_convert_to_initialized: inode %lu, logical\"\n\t\t\"block %llu, max_blocks %u\\n\", inode->i_ino,\n\t\t(unsigned long long)map->m_lblk, map->m_len);\n\n\teof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>\n\t\tinode->i_sb->s_blocksize_bits;\n\tif (eof_block < map->m_lblk + map->m_len)\n\t\teof_block = map->m_lblk + map->m_len;\n\n\tdepth = ext_depth(inode);\n\teh = path[depth].p_hdr;\n\tex = path[depth].p_ext;\n\tee_block = le32_to_cpu(ex->ee_block);\n\tee_len = ext4_ext_get_actual_len(ex);\n\tallocated = ee_len - (map->m_lblk - ee_block);\n\tnewblock = map->m_lblk - ee_block + ext4_ext_pblock(ex);\n\n\tex2 = ex;\n\torig_ex.ee_block = ex->ee_block;\n\torig_ex.ee_len = cpu_to_le16(ee_len);\n\text4_ext_store_pblock(&orig_ex, ext4_ext_pblock(ex));\n\n\t/*\n\t * It is safe to convert extent to initialized via explicit\n\t * zeroout only if extent is fully insde i_size or new_size.\n\t */\n\tmay_zeroout = ee_block + ee_len <= eof_block;\n\n\terr = ext4_ext_get_access(handle, inode, path + depth);\n\tif (err)\n\t\tgoto out;\n\t/* If extent has less than 2*EXT4_EXT_ZERO_LEN zerout directly */\n\tif (ee_len <= 2*EXT4_EXT_ZERO_LEN && may_zeroout) {\n\t\terr = ext4_ext_zeroout(inode, &orig_ex);\n\t\tif (err)\n\t\t\tgoto fix_extent_len;\n\t\t/* update the extent length and mark as initialized */\n\t\tex->ee_block = orig_ex.ee_block;\n\t\tex->ee_len = orig_ex.ee_len;\n\t\text4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex));\n\t\text4_ext_dirty(handle, inode, path + depth);\n\t\t/* zeroed the full extent */\n\t\treturn allocated;\n\t}\n\n\t/* ex1: ee_block to map->m_lblk - 1 : uninitialized */\n\tif (map->m_lblk > ee_block) {\n\t\tex1 = ex;\n\t\tex1->ee_len = cpu_to_le16(map->m_lblk - ee_block);\n\t\text4_ext_mark_uninitialized(ex1);\n\t\tex2 = &newex;\n\t}\n\t/*\n\t * for sanity, update the length of the ex2 extent before\n\t * we insert ex3, if ex1 is NULL. This is to avoid temporary\n\t * overlap of blocks.\n\t */\n\tif (!ex1 && allocated > map->m_len)\n\t\tex2->ee_len = cpu_to_le16(map->m_len);\n\t/* ex3: to ee_block + ee_len : uninitialised */\n\tif (allocated > map->m_len) {\n\t\tunsigned int newdepth;\n\t\t/* If extent has less than EXT4_EXT_ZERO_LEN zerout directly */\n\t\tif (allocated <= EXT4_EXT_ZERO_LEN && may_zeroout) {\n\t\t\t/*\n\t\t\t * map->m_lblk == ee_block is handled by the zerouout\n\t\t\t * at the beginning.\n\t\t\t * Mark first half uninitialized.\n\t\t\t * Mark second half initialized and zero out the\n\t\t\t * initialized extent\n\t\t\t */\n\t\t\tex->ee_block = orig_ex.ee_block;\n\t\t\tex->ee_len = cpu_to_le16(ee_len - allocated);\n\t\t\text4_ext_mark_uninitialized(ex);\n\t\t\text4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex));\n\t\t\text4_ext_dirty(handle, inode, path + depth);\n\n\t\t\tex3 = &newex;\n\t\t\tex3->ee_block = cpu_to_le32(map->m_lblk);\n\t\t\text4_ext_store_pblock(ex3, newblock);\n\t\t\tex3->ee_len = cpu_to_le16(allocated);\n\t\t\terr = ext4_ext_insert_extent(handle, inode, path,\n\t\t\t\t\t\t\tex3, 0);\n\t\t\tif (err == -ENOSPC) {\n\t\t\t\terr = ext4_ext_zeroout(inode, &orig_ex);\n\t\t\t\tif (err)\n\t\t\t\t\tgoto fix_extent_len;\n\t\t\t\tex->ee_block = orig_ex.ee_block;\n\t\t\t\tex->ee_len = orig_ex.ee_len;\n\t\t\t\text4_ext_store_pblock(ex,\n\t\t\t\t\text4_ext_pblock(&orig_ex));\n\t\t\t\text4_ext_dirty(handle, inode, path + depth);\n\t\t\t\t/* blocks available from map->m_lblk */\n\t\t\t\treturn allocated;\n\n\t\t\t} else if (err)\n\t\t\t\tgoto fix_extent_len;\n\n\t\t\t/*\n\t\t\t * We need to zero out the second half because\n\t\t\t * an fallocate request can update file size and\n\t\t\t * converting the second half to initialized extent\n\t\t\t * implies that we can leak some junk data to user\n\t\t\t * space.\n\t\t\t */\n\t\t\terr = ext4_ext_zeroout(inode, ex3);\n\t\t\tif (err) {\n\t\t\t\t/*\n\t\t\t\t * We should actually mark the\n\t\t\t\t * second half as uninit and return error\n\t\t\t\t * Insert would have changed the extent\n\t\t\t\t */\n\t\t\t\tdepth = ext_depth(inode);\n\t\t\t\text4_ext_drop_refs(path);\n\t\t\t\tpath = ext4_ext_find_extent(inode, map->m_lblk,\n\t\t\t\t\t\t\t path);\n\t\t\t\tif (IS_ERR(path)) {\n\t\t\t\t\terr = PTR_ERR(path);\n\t\t\t\t\treturn err;\n\t\t\t\t}\n\t\t\t\t/* get the second half extent details */\n\t\t\t\tex = path[depth].p_ext;\n\t\t\t\terr = ext4_ext_get_access(handle, inode,\n\t\t\t\t\t\t\t\tpath + depth);\n\t\t\t\tif (err)\n\t\t\t\t\treturn err;\n\t\t\t\text4_ext_mark_uninitialized(ex);\n\t\t\t\text4_ext_dirty(handle, inode, path + depth);\n\t\t\t\treturn err;\n\t\t\t}\n\n\t\t\t/* zeroed the second half */\n\t\t\treturn allocated;\n\t\t}\n\t\tex3 = &newex;\n\t\tex3->ee_block = cpu_to_le32(map->m_lblk + map->m_len);\n\t\text4_ext_store_pblock(ex3, newblock + map->m_len);\n\t\tex3->ee_len = cpu_to_le16(allocated - map->m_len);\n\t\text4_ext_mark_uninitialized(ex3);\n\t\terr = ext4_ext_insert_extent(handle, inode, path, ex3, 0);\n\t\tif (err == -ENOSPC && may_zeroout) {\n\t\t\terr = ext4_ext_zeroout(inode, &orig_ex);\n\t\t\tif (err)\n\t\t\t\tgoto fix_extent_len;\n\t\t\t/* update the extent length and mark as initialized */\n\t\t\tex->ee_block = orig_ex.ee_block;\n\t\t\tex->ee_len = orig_ex.ee_len;\n\t\t\text4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex));\n\t\t\text4_ext_dirty(handle, inode, path + depth);\n\t\t\t/* zeroed the full extent */\n\t\t\t/* blocks available from map->m_lblk */\n\t\t\treturn allocated;\n\n\t\t} else if (err)\n\t\t\tgoto fix_extent_len;\n\t\t/*\n\t\t * The depth, and hence eh & ex might change\n\t\t * as part of the insert above.\n\t\t */\n\t\tnewdepth = ext_depth(inode);\n\t\t/*\n\t\t * update the extent length after successful insert of the\n\t\t * split extent\n\t\t */\n\t\tee_len -= ext4_ext_get_actual_len(ex3);\n\t\torig_ex.ee_len = cpu_to_le16(ee_len);\n\t\tmay_zeroout = ee_block + ee_len <= eof_block;\n\n\t\tdepth = newdepth;\n\t\text4_ext_drop_refs(path);\n\t\tpath = ext4_ext_find_extent(inode, map->m_lblk, path);\n\t\tif (IS_ERR(path)) {\n\t\t\terr = PTR_ERR(path);\n\t\t\tgoto out;\n\t\t}\n\t\teh = path[depth].p_hdr;\n\t\tex = path[depth].p_ext;\n\t\tif (ex2 != &newex)\n\t\t\tex2 = ex;\n\n\t\terr = ext4_ext_get_access(handle, inode, path + depth);\n\t\tif (err)\n\t\t\tgoto out;\n\n\t\tallocated = map->m_len;\n\n\t\t/* If extent has less than EXT4_EXT_ZERO_LEN and we are trying\n\t\t * to insert a extent in the middle zerout directly\n\t\t * otherwise give the extent a chance to merge to left\n\t\t */\n\t\tif (le16_to_cpu(orig_ex.ee_len) <= EXT4_EXT_ZERO_LEN &&\n\t\t\tmap->m_lblk != ee_block && may_zeroout) {\n\t\t\terr = ext4_ext_zeroout(inode, &orig_ex);\n\t\t\tif (err)\n\t\t\t\tgoto fix_extent_len;\n\t\t\t/* update the extent length and mark as initialized */\n\t\t\tex->ee_block = orig_ex.ee_block;\n\t\t\tex->ee_len = orig_ex.ee_len;\n\t\t\text4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex));\n\t\t\text4_ext_dirty(handle, inode, path + depth);\n\t\t\t/* zero out the first half */\n\t\t\t/* blocks available from map->m_lblk */\n\t\t\treturn allocated;\n\t\t}\n\t}\n\t/*\n\t * If there was a change of depth as part of the\n\t * insertion of ex3 above, we need to update the length\n\t * of the ex1 extent again here\n\t */\n\tif (ex1 && ex1 != ex) {\n\t\tex1 = ex;\n\t\tex1->ee_len = cpu_to_le16(map->m_lblk - ee_block);\n\t\text4_ext_mark_uninitialized(ex1);\n\t\tex2 = &newex;\n\t}\n\t/* ex2: map->m_lblk to map->m_lblk + maxblocks-1 : initialised */\n\tex2->ee_block = cpu_to_le32(map->m_lblk);\n\text4_ext_store_pblock(ex2, newblock);\n\tex2->ee_len = cpu_to_le16(allocated);\n\tif (ex2 != ex)\n\t\tgoto insert;\n\t/*\n\t * New (initialized) extent starts from the first block\n\t * in the current extent. i.e., ex2 == ex\n\t * We have to see if it can be merged with the extent\n\t * on the left.\n\t */\n\tif (ex2 > EXT_FIRST_EXTENT(eh)) {\n\t\t/*\n\t\t * To merge left, pass \"ex2 - 1\" to try_to_merge(),\n\t\t * since it merges towards right _only_.\n\t\t */\n\t\tret = ext4_ext_try_to_merge(inode, path, ex2 - 1);\n\t\tif (ret) {\n\t\t\terr = ext4_ext_correct_indexes(handle, inode, path);\n\t\t\tif (err)\n\t\t\t\tgoto out;\n\t\t\tdepth = ext_depth(inode);\n\t\t\tex2--;\n\t\t}\n\t}\n\t/*\n\t * Try to Merge towards right. This might be required\n\t * only when the whole extent is being written to.\n\t * i.e. ex2 == ex and ex3 == NULL.\n\t */\n\tif (!ex3) {\n\t\tret = ext4_ext_try_to_merge(inode, path, ex2);\n\t\tif (ret) {\n\t\t\terr = ext4_ext_correct_indexes(handle, inode, path);\n\t\t\tif (err)\n\t\t\t\tgoto out;\n\t\t}\n\t}\n\t/* Mark modified extent as dirty */\n\terr = ext4_ext_dirty(handle, inode, path + depth);\n\tgoto out;\ninsert:\n\terr = ext4_ext_insert_extent(handle, inode, path, &newex, 0);\n\tif (err == -ENOSPC && may_zeroout) {\n\t\terr = ext4_ext_zeroout(inode, &orig_ex);\n\t\tif (err)\n\t\t\tgoto fix_extent_len;\n\t\t/* update the extent length and mark as initialized */\n\t\tex->ee_block = orig_ex.ee_block;\n\t\tex->ee_len = orig_ex.ee_len;\n\t\text4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex));\n\t\text4_ext_dirty(handle, inode, path + depth);\n\t\t/* zero out the first half */\n\t\treturn allocated;\n\t} else if (err)\n\t\tgoto fix_extent_len;\nout:\n\text4_ext_show_leaf(inode, path);\n\treturn err ? err : allocated;\n\nfix_extent_len:\n\tex->ee_block = orig_ex.ee_block;\n\tex->ee_len = orig_ex.ee_len;\n\text4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex));\n\text4_ext_mark_uninitialized(ex);\n\text4_ext_dirty(handle, inode, path + depth);\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'ext4: reimplement convert and split_unwritten\n\nReimplement ext4_ext_convert_to_initialized() and\next4_split_unwritten_extents() using ext4_split_extent()\n\nSigned-off-by: Yongqiang Yang \nSigned-off-by: \"Theodore Ts'o\" \nTested-by: Allison Henderson '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static struct nfs4_state *nfs4_try_open_cached(struct nfs4_opendata *opendata)\n{\n\tstruct nfs4_state *state = opendata->state;\n\tstruct nfs_inode *nfsi = NFS_I(state->inode);\n\tstruct nfs_delegation *delegation;\n\tint open_mode = opendata->o_arg.open_flags & (FMODE_READ|FMODE_WRITE|O_EXCL);\n\tnfs4_stateid stateid;\n\tint ret = -EAGAIN;\n\n\tfor (;;) {\n\t\tif (can_open_cached(state, open_mode)) {\n\t\t\tspin_lock(&state->owner->so_lock);\n\t\t\tif (can_open_cached(state, open_mode)) {\n\t\t\t\tupdate_open_stateflags(state, open_mode);\n\t\t\t\tspin_unlock(&state->owner->so_lock);\n\t\t\t\tgoto out_return_state;\n\t\t\t}\n\t\t\tspin_unlock(&state->owner->so_lock);\n\t\t}\n\t\trcu_read_lock();\n\t\tdelegation = rcu_dereference(nfsi->delegation);\n\t\tif (delegation == NULL ||\n\t\t !can_open_delegated(delegation, open_mode)) {\n\t\t\trcu_read_unlock();\n\t\t\tbreak;\n\t\t}\n\t\t/* Save the delegation */\n\t\tmemcpy(stateid.data, delegation->stateid.data, sizeof(stateid.data));\n\t\trcu_read_unlock();\n\t\tret = nfs_may_open(state->inode, state->owner->so_cred, open_mode);\n\t\tif (ret != 0)\n\t\t\tgoto out;\n\t\tret = -EAGAIN;\n\n\t\t/* Try to update the stateid using the delegation */\n\t\tif (update_open_stateid(state, NULL, &stateid, open_mode))\n\t\t\tgoto out_return_state;\n\t}\nout:\n\treturn ERR_PTR(ret);\nout_return_state:\n\tatomic_inc(&state->count);\n\treturn state;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'NFSv4: Convert the open and close ops to use fmode\n\nSigned-off-by: Trond Myklebust '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void nfs_set_open_stateid_locked(struct nfs4_state *state, nfs4_stateid *stateid, int open_flags)\n{\n\tif (test_bit(NFS_DELEGATED_STATE, &state->flags) == 0)\n\t\tmemcpy(state->stateid.data, stateid->data, sizeof(state->stateid.data));\n\tmemcpy(state->open_stateid.data, stateid->data, sizeof(state->open_stateid.data));\n\tswitch (open_flags) {\n\t\tcase FMODE_READ:\n\t\t\tset_bit(NFS_O_RDONLY_STATE, &state->flags);\n\t\t\tbreak;\n\t\tcase FMODE_WRITE:\n\t\t\tset_bit(NFS_O_WRONLY_STATE, &state->flags);\n\t\t\tbreak;\n\t\tcase FMODE_READ|FMODE_WRITE:\n\t\t\tset_bit(NFS_O_RDWR_STATE, &state->flags);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'NFSv4: Convert the open and close ops to use fmode\n\nSigned-off-by: Trond Myklebust '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int update_open_stateid(struct nfs4_state *state, nfs4_stateid *open_stateid, nfs4_stateid *delegation, int open_flags)\n{\n\tstruct nfs_inode *nfsi = NFS_I(state->inode);\n\tstruct nfs_delegation *deleg_cur;\n\tint ret = 0;\n\n\topen_flags &= (FMODE_READ|FMODE_WRITE);\n\n\trcu_read_lock();\n\tdeleg_cur = rcu_dereference(nfsi->delegation);\n\tif (deleg_cur == NULL)\n\t\tgoto no_delegation;\n\n\tspin_lock(&deleg_cur->lock);\n\tif (nfsi->delegation != deleg_cur ||\n\t (deleg_cur->type & open_flags) != open_flags)\n\t\tgoto no_delegation_unlock;\n\n\tif (delegation == NULL)\n\t\tdelegation = &deleg_cur->stateid;\n\telse if (memcmp(deleg_cur->stateid.data, delegation->data, NFS4_STATEID_SIZE) != 0)\n\t\tgoto no_delegation_unlock;\n\n\tnfs_mark_delegation_referenced(deleg_cur);\n\t__update_open_stateid(state, open_stateid, &deleg_cur->stateid, open_flags);\n\tret = 1;\nno_delegation_unlock:\n\tspin_unlock(&deleg_cur->lock);\nno_delegation:\n\trcu_read_unlock();\n\n\tif (!ret && open_stateid != NULL) {\n\t\t__update_open_stateid(state, open_stateid, NULL, open_flags);\n\t\tret = 1;\n\t}\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'NFSv4: Convert the open and close ops to use fmode\n\nSigned-off-by: Trond Myklebust '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void CLASS lossy_dng_load_raw()\n{\n struct jpeg_decompress_struct cinfo;\n struct jpeg_error_mgr jerr;\n JSAMPARRAY buf;\n JSAMPLE (*pixel)[3];\n unsigned sorder=order, ntags, opcode, deg, i, j, c;\n unsigned save=data_offset-4, trow=0, tcol=0, row, col;\n ushort cur[3][256];\n double coeff[9], tot;\n\n if (meta_offset) {\n fseek (ifp, meta_offset, SEEK_SET);\n order = 0x4d4d;\n ntags = get4();\n while (ntags--) {\n opcode = get4(); get4(); get4();\n if (opcode != 8)\n { fseek (ifp, get4(), SEEK_CUR); continue; }\n fseek (ifp, 20, SEEK_CUR);\n if ((c = get4()) > 2) break;\n fseek (ifp, 12, SEEK_CUR);\n if ((deg = get4()) > 8) break;\n for (i=0; i <= deg && i < 9; i++)\n\tcoeff[i] = getreal(12);\n for (i=0; i < 256; i++) {\n\tfor (tot=j=0; j <= deg; j++)\n\t tot += coeff[j] * pow(i/255.0, (int)j);\n\tcur[c][i] = tot*0xffff;\n }\n }\n order = sorder;\n } else {\n gamma_curve (1/2.4, 12.92, 1, 255);\n FORC3 memcpy (cur[c], curve, sizeof cur[0]);\n }\n cinfo.err = jpeg_std_error (&jerr);\n jpeg_create_decompress (&cinfo);\n while (trow < raw_height) {\n fseek (ifp, save+=4, SEEK_SET);\n if (tile_length < INT_MAX)\n fseek (ifp, get4(), SEEK_SET);\n#ifdef LIBRAW_LIBRARY_BUILD\n if(libraw_internal_data.internal_data.input->jpeg_src(&cinfo) == -1)\n {\n jpeg_destroy_decompress(&cinfo);\n throw LIBRAW_EXCEPTION_DECODE_JPEG;\n }\n#else\n jpeg_stdio_src (&cinfo, ifp);\n#endif\n jpeg_read_header (&cinfo, TRUE);\n jpeg_start_decompress (&cinfo);\n buf = (*cinfo.mem->alloc_sarray)\n\t((j_common_ptr) &cinfo, JPOOL_IMAGE, cinfo.output_width*3, 1);\n#ifdef LIBRAW_LIBRARY_BUILD\n try {\n#endif\n while (cinfo.output_scanline < cinfo.output_height &&\n\t(row = trow + cinfo.output_scanline) < height) {\n#ifdef LIBRAW_LIBRARY_BUILD\n checkCancel();\n#endif\n jpeg_read_scanlines (&cinfo, buf, 1);\n pixel = (JSAMPLE (*)[3]) buf[0];\n for (col=0; col < cinfo.output_width && tcol+col < width; col++) {\n\tFORC3 image[row*width+tcol+col][c] = cur[c][pixel[col][c]];\n }\n }\n#ifdef LIBRAW_LIBRARY_BUILD\n } catch(...) {\n jpeg_destroy_decompress (&cinfo);\n throw;\n }\n#endif\n jpeg_abort_decompress (&cinfo);\n if ((tcol += tile_width) >= raw_width)\n trow += tile_length + (tcol = 0);\n }\n jpeg_destroy_decompress (&cinfo);\n maximum = 0xffff;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': '0.18.17'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int track_header(VividasDemuxContext *viv, AVFormatContext *s, uint8_t *buf, int size)\n{\n int i, j, ret;\n int64_t off;\n int val_1;\n int num_video;\n AVIOContext pb0, *pb = &pb0;\n\n ffio_init_context(pb, buf, size, 0, NULL, NULL, NULL, NULL);\n\n ffio_read_varlen(pb); // track_header_len\n avio_r8(pb); // '1'\n\n val_1 = ffio_read_varlen(pb);\n\n for (i=0;iid = i;\n\n st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;\n st->codecpar->codec_id = AV_CODEC_ID_VP6;\n\n off = avio_tell(pb);\n off += ffio_read_varlen(pb);\n avio_r8(pb); // '3'\n avio_r8(pb); // val_7\n num = avio_rl32(pb); // frame_time\n den = avio_rl32(pb); // time_base\n avpriv_set_pts_info(st, 64, num, den);\n st->nb_frames = avio_rl32(pb); // n frames\n st->codecpar->width = avio_rl16(pb); // width\n st->codecpar->height = avio_rl16(pb); // height\n avio_r8(pb); // val_8\n avio_rl32(pb); // val_9\n\n avio_seek(pb, off, SEEK_SET);\n }\n\n off = avio_tell(pb);\n off += ffio_read_varlen(pb); // val_10\n avio_r8(pb); // '4'\n viv->num_audio = avio_r8(pb);\n avio_seek(pb, off, SEEK_SET);\n\n if (viv->num_audio != 1)\n av_log(s, AV_LOG_WARNING, \"number of audio tracks %d is not 1\\n\", viv->num_audio);\n\n for(i=0;inum_audio;i++) {\n int q;\n AVStream *st = avformat_new_stream(s, NULL);\n if (!st)\n return AVERROR(ENOMEM);\n\n st->id = num_video + i;\n\n st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;\n st->codecpar->codec_id = AV_CODEC_ID_VORBIS;\n\n off = avio_tell(pb);\n off += ffio_read_varlen(pb); // length\n avio_r8(pb); // '5'\n avio_r8(pb); //codec_id\n avio_rl16(pb); //codec_subid\n st->codecpar->channels = avio_rl16(pb); // channels\n st->codecpar->sample_rate = avio_rl32(pb); // sample_rate\n avio_seek(pb, 10, SEEK_CUR); // data_1\n q = avio_r8(pb);\n avio_seek(pb, q, SEEK_CUR); // data_2\n avio_r8(pb); // zeropad\n\n if (avio_tell(pb) < off) {\n int num_data;\n int xd_size = 0;\n int data_len[256];\n int offset = 1;\n uint8_t *p;\n ffio_read_varlen(pb); // val_13\n avio_r8(pb); // '19'\n ffio_read_varlen(pb); // len_3\n num_data = avio_r8(pb);\n for (j = 0; j < num_data; j++) {\n uint64_t len = ffio_read_varlen(pb);\n if (len > INT_MAX/2 - xd_size) {\n return AVERROR_INVALIDDATA;\n }\n data_len[j] = len;\n xd_size += len;\n }\n\n ret = ff_alloc_extradata(st->codecpar, 64 + xd_size + xd_size / 255);\n if (ret < 0)\n return ret;\n\n p = st->codecpar->extradata;\n p[0] = 2;\n\n for (j = 0; j < num_data - 1; j++) {\n unsigned delta = av_xiphlacing(&p[offset], data_len[j]);\n if (delta > data_len[j]) {\n return AVERROR_INVALIDDATA;\n }\n offset += delta;\n }\n\n for (j = 0; j < num_data; j++) {\n int ret = avio_read(pb, &p[offset], data_len[j]);\n if (ret < data_len[j]) {\n st->codecpar->extradata_size = 0;\n av_freep(&st->codecpar->extradata);\n break;\n }\n offset += data_len[j];\n }\n\n if (offset < st->codecpar->extradata_size)\n st->codecpar->extradata_size = offset;\n }\n }\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'avformat/vividas: improve extradata packing checks in track_header()\n\nFixes: out of array accesses\nFixes: 26622/clusterfuzz-testcase-minimized-ffmpeg_dem_VIVIDAS_fuzzer-6581200338288640\n\nFound-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg\nSigned-off-by: Michael Niedermayer '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int ecryptfs_parse_options(struct ecryptfs_sb_info *sbi, char *options)\n{\n\tchar *p;\n\tint rc = 0;\n\tint sig_set = 0;\n\tint cipher_name_set = 0;\n\tint fn_cipher_name_set = 0;\n\tint cipher_key_bytes;\n\tint cipher_key_bytes_set = 0;\n\tint fn_cipher_key_bytes;\n\tint fn_cipher_key_bytes_set = 0;\n\tstruct ecryptfs_mount_crypt_stat *mount_crypt_stat =\n\t\t&sbi->mount_crypt_stat;\n\tsubstring_t args[MAX_OPT_ARGS];\n\tint token;\n\tchar *sig_src;\n\tchar *cipher_name_dst;\n\tchar *cipher_name_src;\n\tchar *fn_cipher_name_dst;\n\tchar *fn_cipher_name_src;\n\tchar *fnek_dst;\n\tchar *fnek_src;\n\tchar *cipher_key_bytes_src;\n\tchar *fn_cipher_key_bytes_src;\n\n\tif (!options) {\n\t\trc = -EINVAL;\n\t\tgoto out;\n\t}\n\tecryptfs_init_mount_crypt_stat(mount_crypt_stat);\n\twhile ((p = strsep(&options, \",\")) != NULL) {\n\t\tif (!*p)\n\t\t\tcontinue;\n\t\ttoken = match_token(p, tokens, args);\n\t\tswitch (token) {\n\t\tcase ecryptfs_opt_sig:\n\t\tcase ecryptfs_opt_ecryptfs_sig:\n\t\t\tsig_src = args[0].from;\n\t\t\trc = ecryptfs_add_global_auth_tok(mount_crypt_stat,\n\t\t\t\t\t\t\t sig_src, 0);\n\t\t\tif (rc) {\n\t\t\t\tprintk(KERN_ERR \"Error attempting to register \"\n\t\t\t\t \"global sig; rc = [%d]\\n\", rc);\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tsig_set = 1;\n\t\t\tbreak;\n\t\tcase ecryptfs_opt_cipher:\n\t\tcase ecryptfs_opt_ecryptfs_cipher:\n\t\t\tcipher_name_src = args[0].from;\n\t\t\tcipher_name_dst =\n\t\t\t\tmount_crypt_stat->\n\t\t\t\tglobal_default_cipher_name;\n\t\t\tstrncpy(cipher_name_dst, cipher_name_src,\n\t\t\t\tECRYPTFS_MAX_CIPHER_NAME_SIZE);\n\t\t\tcipher_name_dst[ECRYPTFS_MAX_CIPHER_NAME_SIZE] = '\\0';\n\t\t\tcipher_name_set = 1;\n\t\t\tbreak;\n\t\tcase ecryptfs_opt_ecryptfs_key_bytes:\n\t\t\tcipher_key_bytes_src = args[0].from;\n\t\t\tcipher_key_bytes =\n\t\t\t\t(int)simple_strtol(cipher_key_bytes_src,\n\t\t\t\t\t\t &cipher_key_bytes_src, 0);\n\t\t\tmount_crypt_stat->global_default_cipher_key_size =\n\t\t\t\tcipher_key_bytes;\n\t\t\tcipher_key_bytes_set = 1;\n\t\t\tbreak;\n\t\tcase ecryptfs_opt_passthrough:\n\t\t\tmount_crypt_stat->flags |=\n\t\t\t\tECRYPTFS_PLAINTEXT_PASSTHROUGH_ENABLED;\n\t\t\tbreak;\n\t\tcase ecryptfs_opt_xattr_metadata:\n\t\t\tmount_crypt_stat->flags |=\n\t\t\t\tECRYPTFS_XATTR_METADATA_ENABLED;\n\t\t\tbreak;\n\t\tcase ecryptfs_opt_encrypted_view:\n\t\t\tmount_crypt_stat->flags |=\n\t\t\t\tECRYPTFS_XATTR_METADATA_ENABLED;\n\t\t\tmount_crypt_stat->flags |=\n\t\t\t\tECRYPTFS_ENCRYPTED_VIEW_ENABLED;\n\t\t\tbreak;\n\t\tcase ecryptfs_opt_fnek_sig:\n\t\t\tfnek_src = args[0].from;\n\t\t\tfnek_dst =\n\t\t\t\tmount_crypt_stat->global_default_fnek_sig;\n\t\t\tstrncpy(fnek_dst, fnek_src, ECRYPTFS_SIG_SIZE_HEX);\n\t\t\tmount_crypt_stat->global_default_fnek_sig[\n\t\t\t\tECRYPTFS_SIG_SIZE_HEX] = '\\0';\n\t\t\trc = ecryptfs_add_global_auth_tok(\n\t\t\t\tmount_crypt_stat,\n\t\t\t\tmount_crypt_stat->global_default_fnek_sig,\n\t\t\t\tECRYPTFS_AUTH_TOK_FNEK);\n\t\t\tif (rc) {\n\t\t\t\tprintk(KERN_ERR \"Error attempting to register \"\n\t\t\t\t \"global fnek sig [%s]; rc = [%d]\\n\",\n\t\t\t\t mount_crypt_stat->global_default_fnek_sig,\n\t\t\t\t rc);\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tmount_crypt_stat->flags |=\n\t\t\t\t(ECRYPTFS_GLOBAL_ENCRYPT_FILENAMES\n\t\t\t\t | ECRYPTFS_GLOBAL_ENCFN_USE_MOUNT_FNEK);\n\t\t\tbreak;\n\t\tcase ecryptfs_opt_fn_cipher:\n\t\t\tfn_cipher_name_src = args[0].from;\n\t\t\tfn_cipher_name_dst =\n\t\t\t\tmount_crypt_stat->global_default_fn_cipher_name;\n\t\t\tstrncpy(fn_cipher_name_dst, fn_cipher_name_src,\n\t\t\t\tECRYPTFS_MAX_CIPHER_NAME_SIZE);\n\t\t\tmount_crypt_stat->global_default_fn_cipher_name[\n\t\t\t\tECRYPTFS_MAX_CIPHER_NAME_SIZE] = '\\0';\n\t\t\tfn_cipher_name_set = 1;\n\t\t\tbreak;\n\t\tcase ecryptfs_opt_fn_cipher_key_bytes:\n\t\t\tfn_cipher_key_bytes_src = args[0].from;\n\t\t\tfn_cipher_key_bytes =\n\t\t\t\t(int)simple_strtol(fn_cipher_key_bytes_src,\n\t\t\t\t\t\t &fn_cipher_key_bytes_src, 0);\n\t\t\tmount_crypt_stat->global_default_fn_cipher_key_bytes =\n\t\t\t\tfn_cipher_key_bytes;\n\t\t\tfn_cipher_key_bytes_set = 1;\n\t\t\tbreak;\n\t\tcase ecryptfs_opt_unlink_sigs:\n\t\t\tmount_crypt_stat->flags |= ECRYPTFS_UNLINK_SIGS;\n\t\t\tbreak;\n\t\tcase ecryptfs_opt_mount_auth_tok_only:\n\t\t\tmount_crypt_stat->flags |=\n\t\t\t\tECRYPTFS_GLOBAL_MOUNT_AUTH_TOK_ONLY;\n\t\t\tbreak;\n\t\tcase ecryptfs_opt_err:\n\t\tdefault:\n\t\t\tprintk(KERN_WARNING\n\t\t\t \"%s: eCryptfs: unrecognized option [%s]\\n\",\n\t\t\t __func__, p);\n\t\t}\n\t}\n\tif (!sig_set) {\n\t\trc = -EINVAL;\n\t\tecryptfs_printk(KERN_ERR, \"You must supply at least one valid \"\n\t\t\t\t\"auth tok signature as a mount \"\n\t\t\t\t\"parameter; see the eCryptfs README\\n\");\n\t\tgoto out;\n\t}\n\tif (!cipher_name_set) {\n\t\tint cipher_name_len = strlen(ECRYPTFS_DEFAULT_CIPHER);\n\n\t\tBUG_ON(cipher_name_len >= ECRYPTFS_MAX_CIPHER_NAME_SIZE);\n\t\tstrcpy(mount_crypt_stat->global_default_cipher_name,\n\t\t ECRYPTFS_DEFAULT_CIPHER);\n\t}\n\tif ((mount_crypt_stat->flags & ECRYPTFS_GLOBAL_ENCRYPT_FILENAMES)\n\t && !fn_cipher_name_set)\n\t\tstrcpy(mount_crypt_stat->global_default_fn_cipher_name,\n\t\t mount_crypt_stat->global_default_cipher_name);\n\tif (!cipher_key_bytes_set)\n\t\tmount_crypt_stat->global_default_cipher_key_size = 0;\n\tif ((mount_crypt_stat->flags & ECRYPTFS_GLOBAL_ENCRYPT_FILENAMES)\n\t && !fn_cipher_key_bytes_set)\n\t\tmount_crypt_stat->global_default_fn_cipher_key_bytes =\n\t\t\tmount_crypt_stat->global_default_cipher_key_size;\n\tmutex_lock(&key_tfm_list_mutex);\n\tif (!ecryptfs_tfm_exists(mount_crypt_stat->global_default_cipher_name,\n\t\t\t\t NULL)) {\n\t\trc = ecryptfs_add_new_key_tfm(\n\t\t\tNULL, mount_crypt_stat->global_default_cipher_name,\n\t\t\tmount_crypt_stat->global_default_cipher_key_size);\n\t\tif (rc) {\n\t\t\tprintk(KERN_ERR \"Error attempting to initialize \"\n\t\t\t \"cipher with name = [%s] and key size = [%td]; \"\n\t\t\t \"rc = [%d]\\n\",\n\t\t\t mount_crypt_stat->global_default_cipher_name,\n\t\t\t mount_crypt_stat->global_default_cipher_key_size,\n\t\t\t rc);\n\t\t\trc = -EINVAL;\n\t\t\tmutex_unlock(&key_tfm_list_mutex);\n\t\t\tgoto out;\n\t\t}\n\t}\n\tif ((mount_crypt_stat->flags & ECRYPTFS_GLOBAL_ENCRYPT_FILENAMES)\n\t && !ecryptfs_tfm_exists(\n\t\t mount_crypt_stat->global_default_fn_cipher_name, NULL)) {\n\t\trc = ecryptfs_add_new_key_tfm(\n\t\t\tNULL, mount_crypt_stat->global_default_fn_cipher_name,\n\t\t\tmount_crypt_stat->global_default_fn_cipher_key_bytes);\n\t\tif (rc) {\n\t\t\tprintk(KERN_ERR \"Error attempting to initialize \"\n\t\t\t \"cipher with name = [%s] and key size = [%td]; \"\n\t\t\t \"rc = [%d]\\n\",\n\t\t\t mount_crypt_stat->global_default_fn_cipher_name,\n\t\t\t mount_crypt_stat->global_default_fn_cipher_key_bytes,\n\t\t\t rc);\n\t\t\trc = -EINVAL;\n\t\t\tmutex_unlock(&key_tfm_list_mutex);\n\t\t\tgoto out;\n\t\t}\n\t}\n\tmutex_unlock(&key_tfm_list_mutex);\n\trc = ecryptfs_init_global_auth_toks(mount_crypt_stat);\n\tif (rc)\n\t\tprintk(KERN_WARNING \"One or more global auth toks could not \"\n\t\t \"properly register; rc = [%d]\\n\", rc);\nout:\n\treturn rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362', 'CWE-284', 'CWE-264'], 'message': 'Ecryptfs: Add mount option to check uid of device being mounted = expect uid\n\nClose a TOCTOU race for mounts done via ecryptfs-mount-private. The mount\nsource (device) can be raced when the ownership test is done in userspace.\nProvide Ecryptfs a means to force the uid check at mount time.\n\nSigned-off-by: John Johansen \nCc: \nSigned-off-by: Tyler Hicks '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus PrepareImpl(TfLiteContext* context, TfLiteNode* node) {\n auto* params =\n reinterpret_cast(node->builtin_data);\n OpData* data = reinterpret_cast(node->user_data);\n // Check we have all the inputs and outputs we need.\n TF_LITE_ENSURE(context, node->inputs->size == 2 || node->inputs->size == 3);\n // Shuffled formats need a workspace to store the shuffled input activations.\n const int expected_outputs_count =\n params->weights_format == kTfLiteFullyConnectedWeightsFormatDefault ? 1\n : 2;\n TF_LITE_ENSURE_EQ(context, node->outputs->size, expected_outputs_count);\n\n const TfLiteTensor* input;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n const TfLiteTensor* filter;\n TF_LITE_ENSURE_OK(context,\n GetInputSafe(context, node, kWeightsTensor, &filter));\n const TfLiteTensor* bias =\n (node->inputs->size == 3)\n ? GetOptionalInputTensor(context, node, kBiasTensor)\n : nullptr;\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context,\n GetOutputSafe(context, node, kOutputTensor, &output));\n\n // Check proper datatype match among all Input Tensors\n TF_LITE_ENSURE_STATUS(\n CheckTypes(context, input, filter, bias, output, params));\n\n // Check all the parameters of tensor match within themselves and match the\n // input configuration.\n int input_size = 1;\n for (int i = 0; i < input->dims->size; i++) {\n input_size *= input->dims->data[i];\n }\n\n TF_LITE_ENSURE_EQ(context, NumDimensions(filter), 2);\n const int batch_size = input_size / filter->dims->data[1];\n const int num_units = filter->dims->data[0];\n\n if (bias) {\n TF_LITE_ENSURE_EQ(context, NumElements(bias), SizeOfDimension(filter, 0));\n }\n\n // Note that quantized inference requires that all tensors have their\n // parameters set. This is usually done during quantized training.\n if (input->type == kTfLiteUInt8 || input->type == kTfLiteInt8 ||\n input->type == kTfLiteInt16) {\n double real_multiplier = 0.0;\n TF_LITE_ENSURE_STATUS(GetQuantizedConvolutionMultipler(\n context, input, filter, bias, output, &real_multiplier));\n int exponent;\n QuantizeMultiplier(real_multiplier, &data->output_multiplier, &exponent);\n data->output_shift = exponent;\n TF_LITE_ENSURE_STATUS(CalculateActivationRangeQuantized(\n context, params->activation, output, &data->output_activation_min,\n &data->output_activation_max));\n }\n\n if (input->type == kTfLiteInt16 && output->type == kTfLiteInt16) {\n TF_LITE_ENSURE_EQ(context, input->params.zero_point, 0);\n TF_LITE_ENSURE_EQ(context, output->params.zero_point, 0);\n }\n\n // If we have to perform on-the-fly quantization (with quantized weights and\n // float inputs) first we need to quantize the inputs. Allocate a temporary\n // buffer to store the intermediate quantized values.\n // Additionally, we allocate a temporary buffer to store the accumulated\n // quantized values prior to multiplication by the scaling factor.\n const bool is_hybrid =\n (input->type == kTfLiteFloat32 &&\n (filter->type == kTfLiteUInt8 || filter->type == kTfLiteInt8));\n const bool is_sparse = filter->sparsity != nullptr;\n if (is_hybrid) {\n TfLiteIntArrayFree(node->temporaries);\n data->compute_row_sums = true;\n if (is_sparse) {\n node->temporaries = TfLiteIntArrayCreate(6);\n } else {\n node->temporaries = TfLiteIntArrayCreate(5);\n }\n node->temporaries->data[0] = data->scratch_tensor_index;\n\n TfLiteTensor* input_quantized;\n TF_LITE_ENSURE_OK(context, GetTemporarySafe(context, node, /*index=*/0,\n &input_quantized));\n input_quantized->type = filter->type;\n input_quantized->allocation_type = kTfLiteArenaRw;\n\n TfLiteIntArray* input_quantized_size = TfLiteIntArrayCopy(input->dims);\n TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, input_quantized,\n input_quantized_size));\n\n node->temporaries->data[1] = data->scratch_tensor_index + 1;\n TfLiteTensor* scaling_factors;\n TF_LITE_ENSURE_OK(context, GetTemporarySafe(context, node, /*index=*/1,\n &scaling_factors));\n scaling_factors->type = kTfLiteFloat32;\n scaling_factors->allocation_type = kTfLiteArenaRw;\n\n int scaling_dims[1] = {batch_size};\n if (!TfLiteIntArrayEqualsArray(scaling_factors->dims, 1, scaling_dims)) {\n TfLiteIntArray* scaling_factors_size = TfLiteIntArrayCreate(1);\n scaling_factors_size->data[0] = batch_size;\n TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, scaling_factors,\n scaling_factors_size));\n }\n\n node->temporaries->data[2] = data->scratch_tensor_index + 2;\n TfLiteTensor* accum_scratch;\n TF_LITE_ENSURE_OK(\n context, GetTemporarySafe(context, node, /*index=*/2, &accum_scratch));\n accum_scratch->type = kTfLiteInt32;\n accum_scratch->allocation_type = kTfLiteArenaRw;\n int accum_scratch_dims[2] = {num_units, batch_size};\n if (!TfLiteIntArrayEqualsArray(accum_scratch->dims, 2,\n accum_scratch_dims)) {\n TfLiteIntArray* accum_size = TfLiteIntArrayCreate(2);\n accum_size->data[0] = num_units;\n accum_size->data[1] = batch_size;\n TF_LITE_ENSURE_OK(\n context, context->ResizeTensor(context, accum_scratch, accum_size));\n }\n\n node->temporaries->data[3] = data->scratch_tensor_index + 3;\n TfLiteTensor* input_offsets;\n TF_LITE_ENSURE_OK(\n context, GetTemporarySafe(context, node, /*index=*/3, &input_offsets));\n input_offsets->type = kTfLiteInt32;\n input_offsets->allocation_type = kTfLiteArenaRw;\n if (!TfLiteIntArrayEqualsArray(input_offsets->dims, 1, scaling_dims)) {\n TfLiteIntArray* input_offsets_size = TfLiteIntArrayCreate(1);\n input_offsets_size->data[0] = batch_size;\n TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, input_offsets,\n input_offsets_size));\n }\n node->temporaries->data[4] = data->scratch_tensor_index + 4;\n TfLiteTensor* row_sums;\n TF_LITE_ENSURE_OK(context,\n GetTemporarySafe(context, node, /*index=*/4, &row_sums));\n row_sums->type = kTfLiteInt32;\n row_sums->allocation_type = kTfLiteArenaRwPersistent;\n int row_sums_dims[1] = {num_units};\n if (!TfLiteIntArrayEqualsArray(row_sums->dims, 1, row_sums_dims)) {\n TfLiteIntArray* row_sums_size = TfLiteIntArrayCreate(1);\n row_sums_size->data[0] = row_sums_dims[0];\n TF_LITE_ENSURE_OK(\n context, context->ResizeTensor(context, row_sums, row_sums_size));\n }\n\n if (is_sparse) {\n data->ledger_initialized = false;\n node->temporaries->data[5] = data->scratch_tensor_index + 5;\n TfLiteTensor* filter_ledger =\n &context->tensors[node->temporaries->data[5]];\n auto status =\n CreateLedgerTensor(filter->sparsity, context, filter_ledger);\n if (status != kTfLiteOk) return status;\n }\n }\n\n // Resize output.\n TfLiteIntArray* output_size_array = nullptr;\n if (params->keep_num_dims) {\n // When number of dimensions are kept the filter operates along the last\n // dimensions. In other words, for an input tensor with shape\n // [batch_size, ..., n_inputs] and a filter of shape [n_inputs, n_units]\n // this Op produces an output of shape [batch_size, ..., n_units].\n TF_LITE_ENSURE_EQ(context, input->dims->data[input->dims->size - 1],\n SizeOfDimension(filter, 1));\n output_size_array = TfLiteIntArrayCopy(input->dims);\n output_size_array->data[output_size_array->size - 1] = num_units;\n } else {\n // Otherwise, the output is (potentially flattened to) a 2-D matrix.\n output_size_array = TfLiteIntArrayCreate(2);\n output_size_array->data[0] = batch_size;\n output_size_array->data[1] = num_units;\n }\n TF_LITE_ENSURE_OK(context,\n context->ResizeTensor(context, output, output_size_array));\n\n return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-369'], 'message': 'Prevent division by 0 in `fully_connected.cc`\n\nPiperOrigin-RevId: 385137282\nChange-Id: If201e69b6e0048f0be001330b4b977e2b46db2cb'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int parse_import_ptr(struct MACH0_(obj_t)* bin, struct reloc_t *reloc, int idx) {\n\tint i, j, sym, wordsize;\n\tut32 stype;\n\twordsize = MACH0_(get_bits)(bin) / 8;\n\tif (idx < 0 || idx >= bin->nsymtab) {\n\t\treturn 0;\n\t}\n\tif ((bin->symtab[idx].n_desc & REFERENCE_TYPE) == REFERENCE_FLAG_UNDEFINED_LAZY) {\n\t\tstype = S_LAZY_SYMBOL_POINTERS;\n\t} else {\n\t\tstype = S_NON_LAZY_SYMBOL_POINTERS;\n\t}\n\n\treloc->offset = 0;\n\treloc->addr = 0;\n\treloc->addend = 0;\n#define CASE(T) case (T / 8): reloc->type = R_BIN_RELOC_ ## T; break\n\tswitch (wordsize) {\n\t\tCASE(8);\n\t\tCASE(16);\n\t\tCASE(32);\n\t\tCASE(64);\n\t\tdefault: return false;\n\t}\n#undef CASE\n\n\tfor (i = 0; i < bin->nsects; i++) {\n\t\tif ((bin->sects[i].flags & SECTION_TYPE) == stype) {\n\t\t\tfor (j=0, sym=-1; bin->sects[i].reserved1+j < bin->nindirectsyms; j++)\n\t\t\t\tif (idx == bin->indirectsyms[bin->sects[i].reserved1 + j]) {\n\t\t\t\t\tsym = j;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\treloc->offset = sym == -1 ? 0 : bin->sects[i].offset + sym * wordsize;\n\t\t\treloc->addr = sym == -1 ? 0 : bin->sects[i].addr + sym * wordsize;\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-415', 'CWE-125'], 'message': 'Fix #9970 - heap oobread in mach0 parser (#10026)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int MqttClient_WaitType(MqttClient *client, void *packet_obj,\n byte wait_type, word16 wait_packet_id, int timeout_ms)\n{\n int rc;\n word16 packet_id;\n MqttPacketType packet_type;\n#ifdef WOLFMQTT_MULTITHREAD\n MqttPendResp *pendResp;\n int readLocked;\n#endif\n MqttMsgStat* mms_stat;\n int waitMatchFound;\n\n if (client == NULL || packet_obj == NULL) {\n return MQTT_CODE_ERROR_BAD_ARG;\n }\n\n /* all packet type structures must have MqttMsgStat at top */\n mms_stat = (MqttMsgStat*)packet_obj;\n\nwait_again:\n\n /* initialize variables */\n packet_id = 0;\n packet_type = MQTT_PACKET_TYPE_RESERVED;\n#ifdef WOLFMQTT_MULTITHREAD\n pendResp = NULL;\n readLocked = 0;\n#endif\n waitMatchFound = 0;\n\n#ifdef WOLFMQTT_DEBUG_CLIENT\n PRINTF(\"MqttClient_WaitType: Type %s (%d), ID %d\",\n MqttPacket_TypeDesc((MqttPacketType)wait_type),\n wait_type, wait_packet_id);\n#endif\n\n switch ((int)*mms_stat)\n {\n case MQTT_MSG_BEGIN:\n {\n #ifdef WOLFMQTT_MULTITHREAD\n /* Lock recv socket mutex */\n rc = wm_SemLock(&client->lockRecv);\n if (rc != 0) {\n PRINTF(\"MqttClient_WaitType: recv lock error!\");\n return rc;\n }\n readLocked = 1;\n #endif\n\n /* reset the packet state */\n client->packet.stat = MQTT_PK_BEGIN;\n }\n FALL_THROUGH;\n\n #ifdef WOLFMQTT_V5\n case MQTT_MSG_AUTH:\n #endif\n case MQTT_MSG_WAIT:\n {\n #ifdef WOLFMQTT_MULTITHREAD\n /* Check to see if packet type and id have already completed */\n pendResp = NULL;\n rc = wm_SemLock(&client->lockClient);\n if (rc == 0) {\n if (MqttClient_RespList_Find(client, (MqttPacketType)wait_type, \n wait_packet_id, &pendResp)) {\n if (pendResp->packetDone) {\n /* pending response is already done, so return */\n rc = pendResp->packet_ret;\n #ifdef WOLFMQTT_DEBUG_CLIENT\n PRINTF(\"PendResp already Done %p: Rc %d\", pendResp, rc);\n #endif\n MqttClient_RespList_Remove(client, pendResp);\n wm_SemUnlock(&client->lockClient);\n wm_SemUnlock(&client->lockRecv);\n return rc;\n }\n }\n wm_SemUnlock(&client->lockClient);\n }\n else {\n break; /* error */\n }\n #endif /* WOLFMQTT_MULTITHREAD */\n\n *mms_stat = MQTT_MSG_WAIT;\n\n /* Wait for packet */\n rc = MqttPacket_Read(client, client->rx_buf, client->rx_buf_len,\n timeout_ms);\n /* handle failure */\n if (rc <= 0) {\n break;\n }\n\n /* capture length read */\n client->packet.buf_len = rc;\n\n /* Decode Packet - get type and id */\n rc = MqttClient_DecodePacket(client, client->rx_buf,\n client->packet.buf_len, NULL, &packet_type, NULL, &packet_id);\n if (rc < 0) {\n break;\n }\n\n #ifdef WOLFMQTT_DEBUG_CLIENT\n PRINTF(\"Read Packet: Len %d, Type %d, ID %d\",\n client->packet.buf_len, packet_type, packet_id);\n #endif\n\n *mms_stat = MQTT_MSG_READ;\n }\n FALL_THROUGH;\n\n case MQTT_MSG_READ:\n case MQTT_MSG_READ_PAYLOAD:\n {\n MqttPacketType use_packet_type;\n void* use_packet_obj;\n\n #ifdef WOLFMQTT_MULTITHREAD\n readLocked = 1; /* if in this state read is locked */\n #endif\n\n /* read payload state only happens for publish messages */\n if (*mms_stat == MQTT_MSG_READ_PAYLOAD) {\n packet_type = MQTT_PACKET_TYPE_PUBLISH;\n }\n\n /* Determine if we received data for this request */\n if ((wait_type == MQTT_PACKET_TYPE_ANY ||\n wait_type == packet_type ||\n MqttIsPubRespPacket(packet_type) == MqttIsPubRespPacket(wait_type)) &&\n (wait_packet_id == 0 || wait_packet_id == packet_id))\n {\n use_packet_obj = packet_obj;\n waitMatchFound = 1;\n }\n else {\n /* use generic packet object */\n use_packet_obj = &client->msg;\n }\n use_packet_type = packet_type;\n\n #ifdef WOLFMQTT_MULTITHREAD\n /* Check to see if we have a pending response for this packet */\n pendResp = NULL;\n rc = wm_SemLock(&client->lockClient);\n if (rc == 0) {\n if (MqttClient_RespList_Find(client, packet_type, packet_id,\n &pendResp)) {\n /* we found packet match this incoming read packet */\n pendResp->packetProcessing = 1;\n use_packet_obj = pendResp->packet_obj;\n use_packet_type = pendResp->packet_type;\n /* req from another thread... not a match */\n waitMatchFound = 0;\n }\n wm_SemUnlock(&client->lockClient);\n }\n else {\n break; /* error */\n }\n #endif /* WOLFMQTT_MULTITHREAD */\n\n /* Perform packet handling for publish callback and QoS */\n rc = MqttClient_HandlePacket(client, use_packet_type,\n use_packet_obj, timeout_ms);\n\n #ifdef WOLFMQTT_NONBLOCK\n if (rc == MQTT_CODE_CONTINUE) {\n /* we have received some data, so keep the recv\n mutex lock active and return */\n return rc;\n }\n #endif\n\n /* handle success case */\n if (rc >= 0) {\n rc = MQTT_CODE_SUCCESS;\n }\n\n #ifdef WOLFMQTT_MULTITHREAD\n if (pendResp) {\n /* Mark pending response entry done */\n if (wm_SemLock(&client->lockClient) == 0) {\n pendResp->packetDone = 1;\n pendResp->packet_ret = rc;\n #ifdef WOLFMQTT_DEBUG_CLIENT\n PRINTF(\"PendResp Done %p\", pendResp);\n #endif\n pendResp = NULL;\n wm_SemUnlock(&client->lockClient);\n }\n }\n #endif /* WOLFMQTT_MULTITHREAD */\n break;\n }\n\n case MQTT_MSG_WRITE:\n case MQTT_MSG_WRITE_PAYLOAD:\n default:\n {\n #ifdef WOLFMQTT_DEBUG_CLIENT\n PRINTF(\"MqttClient_WaitType: Invalid state %d!\", *mms_stat);\n #endif\n rc = MQTT_CODE_ERROR_STAT;\n break;\n }\n } /* switch (*mms_stat) */\n\n#ifdef WOLFMQTT_NONBLOCK\n if (rc != MQTT_CODE_CONTINUE)\n#endif\n {\n /* reset state */\n *mms_stat = MQTT_MSG_BEGIN;\n }\n\n#ifdef WOLFMQTT_MULTITHREAD\n if (readLocked) {\n wm_SemUnlock(&client->lockRecv);\n }\n#endif\n if (rc < 0) {\n #ifdef WOLFMQTT_DEBUG_CLIENT\n PRINTF(\"MqttClient_WaitType: Failure: %s (%d)\",\n MqttClient_ReturnCodeToString(rc), rc);\n #endif\n return rc;\n }\n\n if (!waitMatchFound) {\n /* if we get here, then the we are still waiting for a packet */\n goto wait_again;\n }\n\n return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix wolfmqtt-fuzzer: Null-dereference WRITE in MqttProps_Free'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: CreateStatistics(CreateStatsStmt *stmt)\n{\n\tint16\t\tattnums[STATS_MAX_DIMENSIONS];\n\tint\t\t\tnattnums = 0;\n\tint\t\t\tnumcols;\n\tchar\t *namestr;\n\tNameData\tstxname;\n\tOid\t\t\tstatoid;\n\tOid\t\t\tnamespaceId;\n\tOid\t\t\tstxowner = GetUserId();\n\tHeapTuple\thtup;\n\tDatum\t\tvalues[Natts_pg_statistic_ext];\n\tbool\t\tnulls[Natts_pg_statistic_ext];\n\tint2vector *stxkeys;\n\tList\t *stxexprs = NIL;\n\tDatum\t\texprsDatum;\n\tRelation\tstatrel;\n\tRelation\trel = NULL;\n\tOid\t\t\trelid;\n\tObjectAddress parentobject,\n\t\t\t\tmyself;\n\tDatum\t\ttypes[4];\t\t/* one for each possible type of statistic */\n\tint\t\t\tntypes;\n\tArrayType *stxkind;\n\tbool\t\tbuild_ndistinct;\n\tbool\t\tbuild_dependencies;\n\tbool\t\tbuild_mcv;\n\tbool\t\tbuild_expressions;\n\tbool\t\trequested_type = false;\n\tint\t\t\ti;\n\tListCell *cell;\n\tListCell *cell2;\n\n\tAssert(IsA(stmt, CreateStatsStmt));\n\n\t/*\n\t * Examine the FROM clause. Currently, we only allow it to be a single\n\t * simple table, but later we'll probably allow multiple tables and JOIN\n\t * syntax. The grammar is already prepared for that, so we have to check\n\t * here that what we got is what we can support.\n\t */\n\tif (list_length(stmt->relations) != 1)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t errmsg(\"only a single relation is allowed in CREATE STATISTICS\")));\n\n\tforeach(cell, stmt->relations)\n\t{\n\t\tNode\t *rln = (Node *) lfirst(cell);\n\n\t\tif (!IsA(rln, RangeVar))\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t errmsg(\"only a single relation is allowed in CREATE STATISTICS\")));\n\n\t\t/*\n\t\t * CREATE STATISTICS will influence future execution plans but does\n\t\t * not interfere with currently executing plans. So it should be\n\t\t * enough to take only ShareUpdateExclusiveLock on relation,\n\t\t * conflicting with ANALYZE and other DDL that sets statistical\n\t\t * information, but not with normal queries.\n\t\t */\n\t\trel = relation_openrv((RangeVar *) rln, ShareUpdateExclusiveLock);\n\n\t\t/* Restrict to allowed relation types */\n\t\tif (rel->rd_rel->relkind != RELKIND_RELATION &&\n\t\t\trel->rd_rel->relkind != RELKIND_MATVIEW &&\n\t\t\trel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&\n\t\t\trel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_WRONG_OBJECT_TYPE),\n\t\t\t\t\t errmsg(\"cannot define statistics for relation \\\"%s\\\"\",\n\t\t\t\t\t\t\tRelationGetRelationName(rel)),\n\t\t\t\t\t errdetail_relkind_not_supported(rel->rd_rel->relkind)));\n\n\t\t/* You must own the relation to create stats on it */\n\t\tif (!pg_class_ownercheck(RelationGetRelid(rel), stxowner))\n\t\t\taclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(rel->rd_rel->relkind),\n\t\t\t\t\t\t RelationGetRelationName(rel));\n\n\t\t/* Creating statistics on system catalogs is not allowed */\n\t\tif (!allowSystemTableMods && IsSystemRelation(rel))\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),\n\t\t\t\t\t errmsg(\"permission denied: \\\"%s\\\" is a system catalog\",\n\t\t\t\t\t\t\tRelationGetRelationName(rel))));\n\t}\n\n\tAssert(rel);\n\trelid = RelationGetRelid(rel);\n\n\t/*\n\t * If the node has a name, split it up and determine creation namespace.\n\t * If not, put the object in the same namespace as the relation, and cons\n\t * up a name for it. (This can happen either via \"CREATE STATISTICS ...\"\n\t * or via \"CREATE TABLE ... (LIKE)\".)\n\t */\n\tif (stmt->defnames)\n\t\tnamespaceId = QualifiedNameGetCreationNamespace(stmt->defnames,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t&namestr);\n\telse\n\t{\n\t\tnamespaceId = RelationGetNamespace(rel);\n\t\tnamestr = ChooseExtendedStatisticName(RelationGetRelationName(rel),\n\t\t\t\t\t\t\t\t\t\t\t ChooseExtendedStatisticNameAddition(stmt->exprs),\n\t\t\t\t\t\t\t\t\t\t\t \"stat\",\n\t\t\t\t\t\t\t\t\t\t\t namespaceId);\n\t}\n\tnamestrcpy(&stxname, namestr);\n\n\t/*\n\t * Deal with the possibility that the statistics object already exists.\n\t */\n\tif (SearchSysCacheExists2(STATEXTNAMENSP,\n\t\t\t\t\t\t\t CStringGetDatum(namestr),\n\t\t\t\t\t\t\t ObjectIdGetDatum(namespaceId)))\n\t{\n\t\tif (stmt->if_not_exists)\n\t\t{\n\t\t\tereport(NOTICE,\n\t\t\t\t\t(errcode(ERRCODE_DUPLICATE_OBJECT),\n\t\t\t\t\t errmsg(\"statistics object \\\"%s\\\" already exists, skipping\",\n\t\t\t\t\t\t\tnamestr)));\n\t\t\trelation_close(rel, NoLock);\n\t\t\treturn InvalidObjectAddress;\n\t\t}\n\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_DUPLICATE_OBJECT),\n\t\t\t\t errmsg(\"statistics object \\\"%s\\\" already exists\", namestr)));\n\t}\n\n\t/*\n\t * Make sure no more than STATS_MAX_DIMENSIONS columns are used. There\n\t * might be duplicates and so on, but we'll deal with those later.\n\t */\n\tnumcols = list_length(stmt->exprs);\n\tif (numcols > STATS_MAX_DIMENSIONS)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_TOO_MANY_COLUMNS),\n\t\t\t\t errmsg(\"cannot have more than %d columns in statistics\",\n\t\t\t\t\t\tSTATS_MAX_DIMENSIONS)));\n\n\t/*\n\t * Convert the expression list to a simple array of attnums, but also keep\n\t * a list of more complex expressions. While at it, enforce some\n\t * constraints - we don't allow extended statistics on system attributes,\n\t * and we require the data type to have a less-than operator.\n\t *\n\t * There are many ways to \"mask\" a simple attribute reference as an\n\t * expression, for example \"(a+0)\" etc. We can't possibly detect all of\n\t * them, but we handle at least the simple case with the attribute in\n\t * parens. There'll always be a way around this, if the user is determined\n\t * (like the \"(a+0)\" example), but this makes it somewhat consistent with\n\t * how indexes treat attributes/expressions.\n\t */\n\tforeach(cell, stmt->exprs)\n\t{\n\t\tStatsElem *selem = lfirst_node(StatsElem, cell);\n\n\t\tif (selem->name)\t\t/* column reference */\n\t\t{\n\t\t\tchar\t *attname;\n\t\t\tHeapTuple\tatttuple;\n\t\t\tForm_pg_attribute attForm;\n\t\t\tTypeCacheEntry *type;\n\n\t\t\tattname = selem->name;\n\n\t\t\tatttuple = SearchSysCacheAttName(relid, attname);\n\t\t\tif (!HeapTupleIsValid(atttuple))\n\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t(errcode(ERRCODE_UNDEFINED_COLUMN),\n\t\t\t\t\t\t errmsg(\"column \\\"%s\\\" does not exist\",\n\t\t\t\t\t\t\t\tattname)));\n\t\t\tattForm = (Form_pg_attribute) GETSTRUCT(atttuple);\n\n\t\t\t/* Disallow use of system attributes in extended stats */\n\t\t\tif (attForm->attnum <= 0)\n\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t\t errmsg(\"statistics creation on system columns is not supported\")));\n\n\t\t\t/* Disallow data types without a less-than operator */\n\t\t\ttype = lookup_type_cache(attForm->atttypid, TYPECACHE_LT_OPR);\n\t\t\tif (type->lt_opr == InvalidOid)\n\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t\t errmsg(\"column \\\"%s\\\" cannot be used in statistics because its type %s has no default btree operator class\",\n\t\t\t\t\t\t\t\tattname, format_type_be(attForm->atttypid))));\n\n\t\t\tattnums[nattnums] = attForm->attnum;\n\t\t\tnattnums++;\n\t\t\tReleaseSysCache(atttuple);\n\t\t}\n\t\telse if (IsA(selem->expr, Var)) /* column reference in parens */\n\t\t{\n\t\t\tVar\t\t *var = (Var *) selem->expr;\n\t\t\tTypeCacheEntry *type;\n\n\t\t\t/* Disallow use of system attributes in extended stats */\n\t\t\tif (var->varattno <= 0)\n\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t\t errmsg(\"statistics creation on system columns is not supported\")));\n\n\t\t\t/* Disallow data types without a less-than operator */\n\t\t\ttype = lookup_type_cache(var->vartype, TYPECACHE_LT_OPR);\n\t\t\tif (type->lt_opr == InvalidOid)\n\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t\t errmsg(\"column \\\"%s\\\" cannot be used in statistics because its type %s has no default btree operator class\",\n\t\t\t\t\t\t\t\tget_attname(relid, var->varattno, false), format_type_be(var->vartype))));\n\n\t\t\tattnums[nattnums] = var->varattno;\n\t\t\tnattnums++;\n\t\t}\n\t\telse\t\t\t\t\t/* expression */\n\t\t{\n\t\t\tNode\t *expr = selem->expr;\n\t\t\tOid\t\t\tatttype;\n\t\t\tTypeCacheEntry *type;\n\t\t\tBitmapset *attnums = NULL;\n\t\t\tint\t\t\tk;\n\n\t\t\tAssert(expr != NULL);\n\n\t\t\t/* Disallow expressions referencing system attributes. */\n\t\t\tpull_varattnos(expr, 1, &attnums);\n\n\t\t\tk = -1;\n\t\t\twhile ((k = bms_next_member(attnums, k)) >= 0)\n\t\t\t{\n\t\t\t\tAttrNumber\tattnum = k + FirstLowInvalidHeapAttributeNumber;\n\n\t\t\t\tif (attnum <= 0)\n\t\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t\t\t errmsg(\"statistics creation on system columns is not supported\")));\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Disallow data types without a less-than operator.\n\t\t\t *\n\t\t\t * We ignore this for statistics on a single expression, in which\n\t\t\t * case we'll build the regular statistics only (and that code can\n\t\t\t * deal with such data types).\n\t\t\t */\n\t\t\tif (list_length(stmt->exprs) > 1)\n\t\t\t{\n\t\t\t\tatttype = exprType(expr);\n\t\t\t\ttype = lookup_type_cache(atttype, TYPECACHE_LT_OPR);\n\t\t\t\tif (type->lt_opr == InvalidOid)\n\t\t\t\t\tereport(ERROR,\n\t\t\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t\t\t errmsg(\"expression cannot be used in multivariate statistics because its type %s has no default btree operator class\",\n\t\t\t\t\t\t\t\t\tformat_type_be(atttype))));\n\t\t\t}\n\n\t\t\tstxexprs = lappend(stxexprs, expr);\n\t\t}\n\t}\n\n\t/*\n\t * Parse the statistics kinds.\n\t *\n\t * First check that if this is the case with a single expression, there\n\t * are no statistics kinds specified (we don't allow that for the simple\n\t * CREATE STATISTICS form).\n\t */\n\tif ((list_length(stmt->exprs) == 1) && (list_length(stxexprs) == 1))\n\t{\n\t\t/* statistics kinds not specified */\n\t\tif (list_length(stmt->stat_types) > 0)\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t errmsg(\"when building statistics on a single expression, statistics kinds may not be specified\")));\n\t}\n\n\t/* OK, let's check that we recognize the statistics kinds. */\n\tbuild_ndistinct = false;\n\tbuild_dependencies = false;\n\tbuild_mcv = false;\n\tforeach(cell, stmt->stat_types)\n\t{\n\t\tchar\t *type = strVal(lfirst(cell));\n\n\t\tif (strcmp(type, \"ndistinct\") == 0)\n\t\t{\n\t\t\tbuild_ndistinct = true;\n\t\t\trequested_type = true;\n\t\t}\n\t\telse if (strcmp(type, \"dependencies\") == 0)\n\t\t{\n\t\t\tbuild_dependencies = true;\n\t\t\trequested_type = true;\n\t\t}\n\t\telse if (strcmp(type, \"mcv\") == 0)\n\t\t{\n\t\t\tbuild_mcv = true;\n\t\t\trequested_type = true;\n\t\t}\n\t\telse\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_SYNTAX_ERROR),\n\t\t\t\t\t errmsg(\"unrecognized statistics kind \\\"%s\\\"\",\n\t\t\t\t\t\t\ttype)));\n\t}\n\n\t/*\n\t * If no statistic type was specified, build them all (but only when the\n\t * statistics is defined on more than one column/expression).\n\t */\n\tif ((!requested_type) && (numcols >= 2))\n\t{\n\t\tbuild_ndistinct = true;\n\t\tbuild_dependencies = true;\n\t\tbuild_mcv = true;\n\t}\n\n\t/*\n\t * When there are non-trivial expressions, build the expression stats\n\t * automatically. This allows calculating good estimates for stats that\n\t * consider per-clause estimates (e.g. functional dependencies).\n\t */\n\tbuild_expressions = (list_length(stxexprs) > 0);\n\n\t/*\n\t * Check that at least two columns were specified in the statement, or\n\t * that we're building statistics on a single expression.\n\t */\n\tif ((numcols < 2) && (list_length(stxexprs) != 1))\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),\n\t\t\t\t errmsg(\"extended statistics require at least 2 columns\")));\n\n\t/*\n\t * Sort the attnums, which makes detecting duplicates somewhat easier, and\n\t * it does not hurt (it does not matter for the contents, unlike for\n\t * indexes, for example).\n\t */\n\tqsort(attnums, nattnums, sizeof(int16), compare_int16);\n\n\t/*\n\t * Check for duplicates in the list of columns. The attnums are sorted so\n\t * just check consecutive elements.\n\t */\n\tfor (i = 1; i < nattnums; i++)\n\t{\n\t\tif (attnums[i] == attnums[i - 1])\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_DUPLICATE_COLUMN),\n\t\t\t\t\t errmsg(\"duplicate column name in statistics definition\")));\n\t}\n\n\t/*\n\t * Check for duplicate expressions. We do two loops, counting the\n\t * occurrences of each expression. This is O(N^2) but we only allow small\n\t * number of expressions and it's not executed often.\n\t *\n\t * XXX We don't cross-check attributes and expressions, because it does\n\t * not seem worth it. In principle we could check that expressions don't\n\t * contain trivial attribute references like \"(a)\", but the reasoning is\n\t * similar to why we don't bother with extracting columns from\n\t * expressions. It's either expensive or very easy to defeat for\n\t * determined user, and there's no risk if we allow such statistics (the\n\t * statistics is useless, but harmless).\n\t */\n\tforeach(cell, stxexprs)\n\t{\n\t\tNode\t *expr1 = (Node *) lfirst(cell);\n\t\tint\t\t\tcnt = 0;\n\n\t\tforeach(cell2, stxexprs)\n\t\t{\n\t\t\tNode\t *expr2 = (Node *) lfirst(cell2);\n\n\t\t\tif (equal(expr1, expr2))\n\t\t\t\tcnt += 1;\n\t\t}\n\n\t\t/* every expression should find at least itself */\n\t\tAssert(cnt >= 1);\n\n\t\tif (cnt > 1)\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_DUPLICATE_COLUMN),\n\t\t\t\t\t errmsg(\"duplicate expression in statistics definition\")));\n\t}\n\n\t/* Form an int2vector representation of the sorted column list */\n\tstxkeys = buildint2vector(attnums, nattnums);\n\n\t/* construct the char array of enabled statistic types */\n\tntypes = 0;\n\tif (build_ndistinct)\n\t\ttypes[ntypes++] = CharGetDatum(STATS_EXT_NDISTINCT);\n\tif (build_dependencies)\n\t\ttypes[ntypes++] = CharGetDatum(STATS_EXT_DEPENDENCIES);\n\tif (build_mcv)\n\t\ttypes[ntypes++] = CharGetDatum(STATS_EXT_MCV);\n\tif (build_expressions)\n\t\ttypes[ntypes++] = CharGetDatum(STATS_EXT_EXPRESSIONS);\n\tAssert(ntypes > 0 && ntypes <= lengthof(types));\n\tstxkind = construct_array_builtin(types, ntypes, CHAROID);\n\n\t/* convert the expressions (if any) to a text datum */\n\tif (stxexprs != NIL)\n\t{\n\t\tchar\t *exprsString;\n\n\t\texprsString = nodeToString(stxexprs);\n\t\texprsDatum = CStringGetTextDatum(exprsString);\n\t\tpfree(exprsString);\n\t}\n\telse\n\t\texprsDatum = (Datum) 0;\n\n\tstatrel = table_open(StatisticExtRelationId, RowExclusiveLock);\n\n\t/*\n\t * Everything seems fine, so let's build the pg_statistic_ext tuple.\n\t */\n\tmemset(values, 0, sizeof(values));\n\tmemset(nulls, false, sizeof(nulls));\n\n\tstatoid = GetNewOidWithIndex(statrel, StatisticExtOidIndexId,\n\t\t\t\t\t\t\t\t Anum_pg_statistic_ext_oid);\n\tvalues[Anum_pg_statistic_ext_oid - 1] = ObjectIdGetDatum(statoid);\n\tvalues[Anum_pg_statistic_ext_stxrelid - 1] = ObjectIdGetDatum(relid);\n\tvalues[Anum_pg_statistic_ext_stxname - 1] = NameGetDatum(&stxname);\n\tvalues[Anum_pg_statistic_ext_stxnamespace - 1] = ObjectIdGetDatum(namespaceId);\n\tvalues[Anum_pg_statistic_ext_stxstattarget - 1] = Int32GetDatum(-1);\n\tvalues[Anum_pg_statistic_ext_stxowner - 1] = ObjectIdGetDatum(stxowner);\n\tvalues[Anum_pg_statistic_ext_stxkeys - 1] = PointerGetDatum(stxkeys);\n\tvalues[Anum_pg_statistic_ext_stxkind - 1] = PointerGetDatum(stxkind);\n\n\tvalues[Anum_pg_statistic_ext_stxexprs - 1] = exprsDatum;\n\tif (exprsDatum == (Datum) 0)\n\t\tnulls[Anum_pg_statistic_ext_stxexprs - 1] = true;\n\n\t/* insert it into pg_statistic_ext */\n\thtup = heap_form_tuple(statrel->rd_att, values, nulls);\n\tCatalogTupleInsert(statrel, htup);\n\theap_freetuple(htup);\n\n\trelation_close(statrel, RowExclusiveLock);\n\n\t/*\n\t * We used to create the pg_statistic_ext_data tuple too, but it's not\n\t * clear what value should the stxdinherit flag have (it depends on\n\t * whether the rel is partitioned, contains data, etc.)\n\t */\n\n\tInvokeObjectPostCreateHook(StatisticExtRelationId, statoid, 0);\n\n\t/*\n\t * Invalidate relcache so that others see the new statistics object.\n\t */\n\tCacheInvalidateRelcache(rel);\n\n\trelation_close(rel, NoLock);\n\n\t/*\n\t * Add an AUTO dependency on each column used in the stats, so that the\n\t * stats object goes away if any or all of them get dropped.\n\t */\n\tObjectAddressSet(myself, StatisticExtRelationId, statoid);\n\n\t/* add dependencies for plain column references */\n\tfor (i = 0; i < nattnums; i++)\n\t{\n\t\tObjectAddressSubSet(parentobject, RelationRelationId, relid, attnums[i]);\n\t\trecordDependencyOn(&myself, &parentobject, DEPENDENCY_AUTO);\n\t}\n\n\t/*\n\t * If there are no dependencies on a column, give the statistics object an\n\t * auto dependency on the whole table. In most cases, this will be\n\t * redundant, but it might not be if the statistics expressions contain no\n\t * Vars (which might seem strange but possible). This is consistent with\n\t * what we do for indexes in index_create.\n\t *\n\t * XXX We intentionally don't consider the expressions before adding this\n\t * dependency, because recordDependencyOnSingleRelExpr may not create any\n\t * dependencies for whole-row Vars.\n\t */\n\tif (!nattnums)\n\t{\n\t\tObjectAddressSet(parentobject, RelationRelationId, relid);\n\t\trecordDependencyOn(&myself, &parentobject, DEPENDENCY_AUTO);\n\t}\n\n\t/*\n\t * Store dependencies on anything mentioned in statistics expressions,\n\t * just like we do for index expressions.\n\t */\n\tif (stxexprs)\n\t\trecordDependencyOnSingleRelExpr(&myself,\n\t\t\t\t\t\t\t\t\t\t(Node *) stxexprs,\n\t\t\t\t\t\t\t\t\t\trelid,\n\t\t\t\t\t\t\t\t\t\tDEPENDENCY_NORMAL,\n\t\t\t\t\t\t\t\t\t\tDEPENDENCY_AUTO, false);\n\n\t/*\n\t * Also add dependencies on namespace and owner. These are required\n\t * because the stats object might have a different namespace and/or owner\n\t * than the underlying table(s).\n\t */\n\tObjectAddressSet(parentobject, NamespaceRelationId, namespaceId);\n\trecordDependencyOn(&myself, &parentobject, DEPENDENCY_NORMAL);\n\n\trecordDependencyOnOwner(StatisticExtRelationId, statoid, stxowner);\n\n\t/*\n\t * XXX probably there should be a recordDependencyOnCurrentExtension call\n\t * here too, but we'd have to add support for ALTER EXTENSION ADD/DROP\n\t * STATISTICS, which is more work than it seems worth.\n\t */\n\n\t/* Add any requested comment */\n\tif (stmt->stxcomment != NULL)\n\t\tCreateComments(statoid, StatisticExtRelationId, 0,\n\t\t\t\t\t stmt->stxcomment);\n\n\t/* Return stats object's address */\n\treturn myself;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-94'], 'message': 'In extensions, don't replace objects not belonging to the extension.\n\nPreviously, if an extension script did CREATE OR REPLACE and there was\nan existing object not belonging to the extension, it would overwrite\nthe object and adopt it into the extension. This is problematic, first\nbecause the overwrite is probably unintentional, and second because we\ndidn't change the object's ownership. Thus a hostile user could create\nan object in advance of an expected CREATE EXTENSION command, and would\nthen have ownership rights on an extension object, which could be\nmodified for trojan-horse-type attacks.\n\nHence, forbid CREATE OR REPLACE of an existing object unless it already\nbelongs to the extension. (Note that we've always forbidden replacing\nan object that belongs to some other extension; only the behavior for\npreviously-free-standing objects changes here.)\n\nFor the same reason, also fail CREATE IF NOT EXISTS when there is\nan existing object that doesn't belong to the extension.\n\nOur thanks to Sven Klemm for reporting this problem.\n\nSecurity: CVE-2022-2625'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void DISOpticalFlowImpl::calc(InputArray I0, InputArray I1, InputOutputArray flow)\n{\n CV_Assert(!I0.empty() && I0.depth() == CV_8U && I0.channels() == 1);\n CV_Assert(!I1.empty() && I1.depth() == CV_8U && I1.channels() == 1);\n CV_Assert(I0.sameSize(I1));\n CV_Assert(I0.isContinuous());\n CV_Assert(I1.isContinuous());\n\n CV_OCL_RUN(flow.isUMat() &&\n (patch_size == 8) && (use_spatial_propagation == true),\n ocl_calc(I0, I1, flow));\n\n Mat I0Mat = I0.getMat();\n Mat I1Mat = I1.getMat();\n bool use_input_flow = false;\n if (flow.sameSize(I0) && flow.depth() == CV_32F && flow.channels() == 2)\n use_input_flow = true;\n else\n flow.create(I1Mat.size(), CV_32FC2);\n Mat flowMat = flow.getMat();\n coarsest_scale = min((int)(log(max(I0Mat.cols, I0Mat.rows) / (4.0 * patch_size)) / log(2.0) + 0.5), /* Original code serach for maximal movement of width/4 */\n (int)(log(min(I0Mat.cols, I0Mat.rows) / patch_size) / log(2.0))); /* Deepest pyramid level greater or equal than patch*/\n int num_stripes = getNumThreads();\n\n prepareBuffers(I0Mat, I1Mat, flowMat, use_input_flow);\n Ux[coarsest_scale].setTo(0.0f);\n Uy[coarsest_scale].setTo(0.0f);\n\n for (int i = coarsest_scale; i >= finest_scale; i--)\n {\n w = I0s[i].cols;\n h = I0s[i].rows;\n ws = 1 + (w - patch_size) / patch_stride;\n hs = 1 + (h - patch_size) / patch_stride;\n\n precomputeStructureTensor(I0xx_buf, I0yy_buf, I0xy_buf, I0x_buf, I0y_buf, I0xs[i], I0ys[i]);\n if (use_spatial_propagation)\n {\n /* Use a fixed number of stripes regardless the number of threads to make inverse search\n * with spatial propagation reproducible\n */\n parallel_for_(Range(0, 8), PatchInverseSearch_ParBody(*this, 8, hs, Sx, Sy, Ux[i], Uy[i], I0s[i],\n I1s_ext[i], I0xs[i], I0ys[i], 2, i));\n }\n else\n {\n parallel_for_(Range(0, num_stripes),\n PatchInverseSearch_ParBody(*this, num_stripes, hs, Sx, Sy, Ux[i], Uy[i], I0s[i], I1s_ext[i],\n I0xs[i], I0ys[i], 1, i));\n }\n\n parallel_for_(Range(0, num_stripes),\n Densification_ParBody(*this, num_stripes, I0s[i].rows, Ux[i], Uy[i], Sx, Sy, I0s[i], I1s[i]));\n if (variational_refinement_iter > 0)\n variational_refinement_processors[i]->calcUV(I0s[i], I1s[i], Ux[i], Uy[i]);\n\n if (i > finest_scale)\n {\n resize(Ux[i], Ux[i - 1], Ux[i - 1].size());\n resize(Uy[i], Uy[i - 1], Uy[i - 1].size());\n Ux[i - 1] *= 2;\n Uy[i - 1] *= 2;\n }\n }\n Mat uxy[] = {Ux[finest_scale], Uy[finest_scale]};\n merge(uxy, 2, U);\n resize(U, flowMat, flowMat.size());\n flowMat *= 1 << finest_scale;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-369'], 'message': 'video:fixed DISOpticalFlow segfault from small img'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static MagickBooleanType WriteMAPImage(const ImageInfo *image_info,Image *image,\n ExceptionInfo *exception)\n{\n MagickBooleanType\n status;\n\n register const Quantum\n *p;\n\n register ssize_t\n i,\n x;\n\n register unsigned char\n *q;\n\n size_t\n depth,\n packet_size;\n\n ssize_t\n y;\n\n unsigned char\n *colormap,\n *pixels;\n\n /*\n Open output image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);\n if (status == MagickFalse)\n return(status);\n (void) TransformImageColorspace(image,sRGBColorspace,exception);\n /*\n Allocate colormap.\n */\n if (IsPaletteImage(image) == MagickFalse)\n (void) SetImageType(image,PaletteType,exception);\n depth=GetImageQuantumDepth(image,MagickTrue);\n packet_size=(size_t) (depth/8);\n pixels=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size*\n sizeof(*pixels));\n packet_size=(size_t) (image->colors > 256 ? 6UL : 3UL);\n colormap=(unsigned char *) AcquireQuantumMemory(image->colors,packet_size*\n sizeof(*colormap));\n if ((pixels == (unsigned char *) NULL) ||\n (colormap == (unsigned char *) NULL))\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n /*\n Write colormap to file.\n */\n q=colormap;\n q=colormap;\n if (image->colors <= 256)\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n *q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].red);\n *q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].green);\n *q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].blue);\n }\n else\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].red) >> 8);\n *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].red) & 0xff);\n *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].green) >> 8);\n *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].green) & 0xff);;\n *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].blue) >> 8);\n *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].blue) & 0xff);\n }\n (void) WriteBlob(image,packet_size*image->colors,colormap);\n colormap=(unsigned char *) RelinquishMagickMemory(colormap);\n /*\n Write image pixels to file.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n q=pixels;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (image->colors > 256)\n *q++=(unsigned char) ((size_t) GetPixelIndex(image,p) >> 8);\n *q++=(unsigned char) GetPixelIndex(image,p);\n p+=GetPixelChannels(image);\n }\n (void) WriteBlob(image,(size_t) (q-pixels),pixels);\n }\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n (void) CloseBlob(image);\n return(status);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-772', 'CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/573'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: xfs_acl_from_disk(struct xfs_acl *aclp)\n{\n\tstruct posix_acl_entry *acl_e;\n\tstruct posix_acl *acl;\n\tstruct xfs_acl_entry *ace;\n\tint count, i;\n\n\tcount = be32_to_cpu(aclp->acl_cnt);\n\tif (count > XFS_ACL_MAX_ENTRIES)\n\t\treturn ERR_PTR(-EFSCORRUPTED);\n\n\tacl = posix_acl_alloc(count, GFP_KERNEL);\n\tif (!acl)\n\t\treturn ERR_PTR(-ENOMEM);\n\n\tfor (i = 0; i < count; i++) {\n\t\tacl_e = &acl->a_entries[i];\n\t\tace = &aclp->acl_entry[i];\n\n\t\t/*\n\t\t * The tag is 32 bits on disk and 16 bits in core.\n\t\t *\n\t\t * Because every access to it goes through the core\n\t\t * format first this is not a problem.\n\t\t */\n\t\tacl_e->e_tag = be32_to_cpu(ace->ae_tag);\n\t\tacl_e->e_perm = be16_to_cpu(ace->ae_perm);\n\n\t\tswitch (acl_e->e_tag) {\n\t\tcase ACL_USER:\n\t\tcase ACL_GROUP:\n\t\t\tacl_e->e_id = be32_to_cpu(ace->ae_id);\n\t\t\tbreak;\n\t\tcase ACL_USER_OBJ:\n\t\tcase ACL_GROUP_OBJ:\n\t\tcase ACL_MASK:\n\t\tcase ACL_OTHER:\n\t\t\tacl_e->e_id = ACL_UNDEFINED_ID;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tgoto fail;\n\t\t}\n\t}\n\treturn acl;\n\nfail:\n\tposix_acl_release(acl);\n\treturn ERR_PTR(-EINVAL);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190', 'CWE-189'], 'message': 'xfs: fix acl count validation in xfs_acl_from_disk()\n\nCommit fa8b18ed didn't prevent the integer overflow and possible\nmemory corruption. \"count\" can go negative and bypass the check.\n\nSigned-off-by: Xi Wang \nReviewed-by: Christoph Hellwig \nSigned-off-by: Ben Myers '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: vqp_print(netdissect_options *ndo, register const u_char *pptr, register u_int len)\n{\n const struct vqp_common_header_t *vqp_common_header;\n const struct vqp_obj_tlv_t *vqp_obj_tlv;\n\n const u_char *tptr;\n uint16_t vqp_obj_len;\n uint32_t vqp_obj_type;\n int tlen;\n uint8_t nitems;\n\n tptr=pptr;\n tlen = len;\n vqp_common_header = (const struct vqp_common_header_t *)pptr;\n ND_TCHECK(*vqp_common_header);\n\n /*\n * Sanity checking of the header.\n */\n if (VQP_EXTRACT_VERSION(vqp_common_header->version) != VQP_VERSION) {\n\tND_PRINT((ndo, \"VQP version %u packet not supported\",\n VQP_EXTRACT_VERSION(vqp_common_header->version)));\n\treturn;\n }\n\n /* in non-verbose mode just lets print the basic Message Type */\n if (ndo->ndo_vflag < 1) {\n ND_PRINT((ndo, \"VQPv%u %s Message, error-code %s (%u), length %u\",\n VQP_EXTRACT_VERSION(vqp_common_header->version),\n tok2str(vqp_msg_type_values, \"unknown (%u)\",vqp_common_header->msg_type),\n tok2str(vqp_error_code_values, \"unknown (%u)\",vqp_common_header->error_code),\n\t vqp_common_header->error_code,\n len));\n return;\n }\n\n /* ok they seem to want to know everything - lets fully decode it */\n nitems = vqp_common_header->nitems;\n ND_PRINT((ndo, \"\\n\\tVQPv%u, %s Message, error-code %s (%u), seq 0x%08x, items %u, length %u\",\n VQP_EXTRACT_VERSION(vqp_common_header->version),\n\t tok2str(vqp_msg_type_values, \"unknown (%u)\",vqp_common_header->msg_type),\n\t tok2str(vqp_error_code_values, \"unknown (%u)\",vqp_common_header->error_code),\n\t vqp_common_header->error_code,\n EXTRACT_32BITS(&vqp_common_header->sequence),\n nitems,\n len));\n\n /* skip VQP Common header */\n tptr+=sizeof(const struct vqp_common_header_t);\n tlen-=sizeof(const struct vqp_common_header_t);\n\n while (nitems > 0 && tlen > 0) {\n\n vqp_obj_tlv = (const struct vqp_obj_tlv_t *)tptr;\n vqp_obj_type = EXTRACT_32BITS(vqp_obj_tlv->obj_type);\n vqp_obj_len = EXTRACT_16BITS(vqp_obj_tlv->obj_length);\n tptr+=sizeof(struct vqp_obj_tlv_t);\n tlen-=sizeof(struct vqp_obj_tlv_t);\n\n ND_PRINT((ndo, \"\\n\\t %s Object (0x%08x), length %u, value: \",\n tok2str(vqp_obj_values, \"Unknown\", vqp_obj_type),\n vqp_obj_type, vqp_obj_len));\n\n /* basic sanity check */\n if (vqp_obj_type == 0 || vqp_obj_len ==0) {\n return;\n }\n\n /* did we capture enough for fully decoding the object ? */\n ND_TCHECK2(*tptr, vqp_obj_len);\n\n switch(vqp_obj_type) {\n\tcase VQP_OBJ_IP_ADDRESS:\n ND_PRINT((ndo, \"%s (0x%08x)\", ipaddr_string(ndo, tptr), EXTRACT_32BITS(tptr)));\n break;\n /* those objects have similar semantics - fall through */\n case VQP_OBJ_PORT_NAME:\n\tcase VQP_OBJ_VLAN_NAME:\n\tcase VQP_OBJ_VTP_DOMAIN:\n\tcase VQP_OBJ_ETHERNET_PKT:\n safeputs(ndo, tptr, vqp_obj_len);\n break;\n /* those objects have similar semantics - fall through */\n\tcase VQP_OBJ_MAC_ADDRESS:\n\tcase VQP_OBJ_MAC_NULL:\n\t ND_PRINT((ndo, \"%s\", etheraddr_string(ndo, tptr)));\n break;\n default:\n if (ndo->ndo_vflag <= 1)\n print_unknown_data(ndo,tptr, \"\\n\\t \", vqp_obj_len);\n break;\n }\n\ttptr += vqp_obj_len;\n\ttlen -= vqp_obj_len;\n\tnitems--;\n }\n return;\ntrunc:\n ND_PRINT((ndo, \"\\n\\t[|VQP]\"));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13045/VQP: add some bounds checks\n\nThis fixes a buffer over-read discovered by Bhargava Shastry,\nSecT/TU Berlin.\n\nAdd a test using the capture file supplied by the reporter(s).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: find_by_thp(struct tang_keys_info* tki, const char* target)\n{\n if (!tki) {\n return NULL;\n }\n\n json_auto_t* keys = json_deep_copy(tki->m_keys);\n json_array_extend(keys, tki->m_rotated_keys);\n\n size_t idx;\n json_t* jwk;\n const char** hashes = supported_hashes();\n json_array_foreach(keys, idx, jwk) {\n for (int i = 0; hashes[i]; i++) {\n __attribute__ ((__cleanup__(cleanup_str))) char* thumbprint = jwk_thumbprint(jwk, hashes[i]);\n if (!thumbprint || strcmp(thumbprint, target) != 0) {\n continue;\n }\n\n if (jwk_valid_for_deriving_keys(jwk)) {\n return json_incref(jwk);\n } else if (jwk_valid_for_signing(jwk)) {\n json_auto_t* sign = json_deep_copy(tki->m_sign);\n if (json_array_append(sign, jwk) == -1) {\n return NULL;\n }\n json_auto_t* jws = jwk_sign(tki->m_payload, sign);\n if (!jws) {\n return NULL;\n }\n return json_incref(jws);\n }\n }\n }\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'keys: move signing part out of find_by_thp() and to find_jws() (#81)\n\nHandle just signing keys in find_jws(), to make sure we are\r\nresponding only to proper queries.\r\n\r\nTests were also failing to detect this issue and were updated\r\naccordingly.\r\n\r\nIssue discovered by Twitter Kernel and OS team during a source\r\ncode audit while evaluating Tang/Clevis for their needs.\r\n\r\nFixes CVE-2021-4076'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: explicit ReverseSequenceOp(OpKernelConstruction* context)\n : OpKernel(context) {\n OP_REQUIRES_OK(context, context->GetAttr(\"batch_dim\", &batch_dim_));\n OP_REQUIRES_OK(context, context->GetAttr(\"seq_dim\", &seq_dim_));\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'Add missing validations to reverse_sequence_op\n\nPiperOrigin-RevId: 372178683\nChange-Id: Iac97ebab5b342f1262c77a7d9bcb4267b305ce5b'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int xfrm6_tunnel_rcv(struct sk_buff *skb)\n{\n\tstruct ipv6hdr *iph = ipv6_hdr(skb);\n\t__be32 spi;\n\n\tspi = xfrm6_tunnel_spi_lookup((xfrm_address_t *)&iph->saddr);\n\treturn xfrm6_rcv_spi(skb, spi);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': '[IPV6]: Fix slab corruption running ip6sic\n\nFrom: Eric Sesterhenn \n\nSigned-off-by: Andrew Morton \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void _moddeinit(module_unload_intent_t intent)\n{\n\tservice_named_unbind_command(\"chanserv\", &cs_flags);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284'], 'message': 'chanserv/flags: make Anope FLAGS compatibility an option\n\nPreviously, ChanServ FLAGS behavior could be modified by registering or\ndropping the keyword nicks \"LIST\", \"CLEAR\", and \"MODIFY\".\nNow, a configuration option is available that when turned on (default),\ndisables registration of these keyword nicks and enables this\ncompatibility feature. When turned off, registration of these keyword\nnicks is possible, and compatibility to Anope's FLAGS command is\ndisabled.\n\nFixes atheme/atheme#397'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int hugetlbfs_statfs(struct dentry *dentry, struct kstatfs *buf)\n{\n\tstruct hugetlbfs_sb_info *sbinfo = HUGETLBFS_SB(dentry->d_sb);\n\tstruct hstate *h = hstate_inode(dentry->d_inode);\n\n\tbuf->f_type = HUGETLBFS_MAGIC;\n\tbuf->f_bsize = huge_page_size(h);\n\tif (sbinfo) {\n\t\tspin_lock(&sbinfo->stat_lock);\n\t\t/* If no limits set, just report 0 for max/free/used\n\t\t * blocks, like simple_statfs() */\n\t\tif (sbinfo->max_blocks >= 0) {\n\t\t\tbuf->f_blocks = sbinfo->max_blocks;\n\t\t\tbuf->f_bavail = buf->f_bfree = sbinfo->free_blocks;\n\t\t\tbuf->f_files = sbinfo->max_inodes;\n\t\t\tbuf->f_ffree = sbinfo->free_inodes;\n\t\t}\n\t\tspin_unlock(&sbinfo->stat_lock);\n\t}\n\tbuf->f_namelen = NAME_MAX;\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'hugepages: fix use after free bug in \"quota\" handling\n\nhugetlbfs_{get,put}_quota() are badly named. They don't interact with the\ngeneral quota handling code, and they don't much resemble its behaviour.\nRather than being about maintaining limits on on-disk block usage by\nparticular users, they are instead about maintaining limits on in-memory\npage usage (including anonymous MAP_PRIVATE copied-on-write pages)\nassociated with a particular hugetlbfs filesystem instance.\n\nWorse, they work by having callbacks to the hugetlbfs filesystem code from\nthe low-level page handling code, in particular from free_huge_page().\nThis is a layering violation of itself, but more importantly, if the\nkernel does a get_user_pages() on hugepages (which can happen from KVM\namongst others), then the free_huge_page() can be delayed until after the\nassociated inode has already been freed. If an unmount occurs at the\nwrong time, even the hugetlbfs superblock where the \"quota\" limits are\nstored may have been freed.\n\nAndrew Barry proposed a patch to fix this by having hugepages, instead of\nstoring a pointer to their address_space and reaching the superblock from\nthere, had the hugepages store pointers directly to the superblock,\nbumping the reference count as appropriate to avoid it being freed.\nAndrew Morton rejected that version, however, on the grounds that it made\nthe existing layering violation worse.\n\nThis is a reworked version of Andrew's patch, which removes the extra, and\nsome of the existing, layering violation. It works by introducing the\nconcept of a hugepage \"subpool\" at the lower hugepage mm layer - that is a\nfinite logical pool of hugepages to allocate from. hugetlbfs now creates\na subpool for each filesystem instance with a page limit set, and a\npointer to the subpool gets added to each allocated hugepage, instead of\nthe address_space pointer used now. The subpool has its own lifetime and\nis only freed once all pages in it _and_ all other references to it (i.e.\nsuperblocks) are gone.\n\nsubpools are optional - a NULL subpool pointer is taken by the code to\nmean that no subpool limits are in effect.\n\nPrevious discussion of this bug found in: \"Fix refcounting in hugetlbfs\nquota handling.\". See: https://lkml.org/lkml/2011/8/11/28 or\nhttp://marc.info/?l=linux-mm&m=126928970510627&w=1\n\nv2: Fixed a bug spotted by Hillf Danton, and removed the extra parameter to\nalloc_huge_page() - since it already takes the vma, it is not necessary.\n\nSigned-off-by: Andrew Barry \nSigned-off-by: David Gibson \nCc: Hugh Dickins \nCc: Mel Gorman \nCc: Minchan Kim \nCc: Hillf Danton \nCc: Paul Mackerras \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int encrypt_stream(FILE *infp, FILE *outfp, unsigned char* passwd, int passlen)\n{\n aes_context aes_ctx;\n sha256_context sha_ctx;\n aescrypt_hdr aeshdr;\n sha256_t digest;\n unsigned char IV[16];\n unsigned char iv_key[48];\n unsigned i, j;\n size_t bytes_read;\n unsigned char buffer[32];\n unsigned char ipad[64], opad[64];\n time_t current_time;\n pid_t process_id;\n void *aesrand;\n unsigned char tag_buffer[256];\n\n /*\n * Open the source for random data. Note that while the entropy\n * might be lower with /dev/urandom than /dev/random, it will not\n * fail to produce something. Also, we're going to hash the result\n * anyway.\n */\n if ((aesrand = aesrandom_open()) == NULL)\n {\n perror(\"Error open random:\");\n return -1;\n }\n\n /*\n * Create the 16-octet IV and 32-octet encryption key\n * used for encrypting the plaintext file. We do\n * not trust the rand() function, so we improve on\n * that by also hashing the random digits and using\n * only a portion of the hash. This IV and key\n * generation could be replaced with any good random\n * source of data.\n */\n memset(iv_key, 0, 48);\n for (i=0; i<48; i+=16)\n {\n memset(buffer, 0, 32);\n sha256_starts(&sha_ctx);\n for(j=0; j<256; j++)\n {\n if ((bytes_read = aesrandom_read(aesrand, buffer, 32)) != 32)\n {\n fprintf(stderr, \"Error: Couldn't read from random : %u\\n\",\n (unsigned) bytes_read);\n aesrandom_close(aesrand);\n return -1;\n }\n sha256_update(&sha_ctx, buffer, 32);\n }\n sha256_finish(&sha_ctx, digest);\n memcpy(iv_key+i, digest, 16);\n }\n\n /*\n * Write an AES signature at the head of the file, along\n * with the AES file format version number.\n */\n buffer[0] = 'A';\n buffer[1] = 'E';\n buffer[2] = 'S';\n buffer[3] = (unsigned char) 0x02; /* Version 2 */\n buffer[4] = '\\0'; /* Reserved for version 0 */\n if (fwrite(buffer, 1, 5, outfp) != 5)\n {\n fprintf(stderr, \"Error: Could not write out header data\\n\");\n aesrandom_close(aesrand);\n return -1;\n }\n\n /* Write out the CREATED-BY tag */\n j = 11 + /* \"CREATED-BY\\0\" */\n strlen(PACKAGE_NAME) + /* Program name */\n 1 + /* Space */\n strlen(PACKAGE_VERSION); /* Program version ID */\n\n /*\n * Our extension buffer is only 256 octets long, so\n * let's not write an extension if it is too big\n */\n if (j < 256)\n {\n buffer[0] = '\\0';\n buffer[1] = (unsigned char) (j & 0xff);\n if (fwrite(buffer, 1, 2, outfp) != 2)\n {\n fprintf(stderr, \"Error: Could not write tag to AES file (1)\\n\");\n aesrandom_close(aesrand);\n return -1;\n }\n\n strncpy((char *)tag_buffer, \"CREATED_BY\", 255);\n tag_buffer[255] = '\\0';\n if (fwrite(tag_buffer, 1, 11, outfp) != 11)\n {\n fprintf(stderr, \"Error: Could not write tag to AES file (2)\\n\");\n aesrandom_close(aesrand);\n return -1;\n }\n\n sprintf((char *)tag_buffer, \"%s %s\", PACKAGE_NAME, PACKAGE_VERSION);\n j = strlen((char *)tag_buffer);\n if (fwrite(tag_buffer, 1, j, outfp) != j)\n {\n fprintf(stderr, \"Error: Could not write tag to AES file (3)\\n\");\n aesrandom_close(aesrand);\n return -1;\n }\n }\n\n /* Write out the \"container\" extension */\n buffer[0] = '\\0';\n buffer[1] = (unsigned char) 128;\n if (fwrite(buffer, 1, 2, outfp) != 2)\n {\n fprintf(stderr, \"Error: Could not write tag to AES file (4)\\n\");\n aesrandom_close(aesrand);\n return -1;\n }\n memset(tag_buffer, 0, 128);\n if (fwrite(tag_buffer, 1, 128, outfp) != 128)\n {\n fprintf(stderr, \"Error: Could not write tag to AES file (5)\\n\");\n aesrandom_close(aesrand);\n return -1;\n }\n\n /* Write out 0x0000 to indicate that no more extensions exist */\n buffer[0] = '\\0';\n buffer[1] = '\\0';\n if (fwrite(buffer, 1, 2, outfp) != 2)\n {\n fprintf(stderr, \"Error: Could not write tag to AES file (6)\\n\");\n aesrandom_close(aesrand);\n return -1;\n }\n\n /*\n * We will use an initialization vector comprised of the current time\n * process ID, and random data, all hashed together with SHA-256.\n */\n sha256_starts( &sha_ctx);\n current_time = time(NULL);\n sha256_update( &sha_ctx, (unsigned char *)&time, sizeof(current_time));\n process_id = getpid();\n sha256_update( &sha_ctx, (unsigned char *)&process_id, sizeof(process_id));\n\n for (i=0; i<256; i++)\n {\n if (aesrandom_read(aesrand, buffer, 32) != 32)\n {\n fprintf(stderr, \"Error: Couldn't read from /dev/random\\n\");\n aesrandom_close(aesrand);\n return -1;\n }\n sha256_update( &sha_ctx,\n buffer,\n 32);\n }\n\n sha256_finish( &sha_ctx, digest);\n\n memcpy(IV, digest, 16);\n\n /* We're finished collecting random data */\n aesrandom_close(aesrand);\n\n /* Write the initialization vector to the file */\n if (fwrite(IV, 1, 16, outfp) != 16)\n {\n fprintf(stderr, \"Error: Could not write out initialization vector\\n\");\n return -1;\n }\n \n /* Hash the IV and password 8192 times */\n memset(digest, 0, 32);\n memcpy(digest, IV, 16);\n for(i=0; i<8192; i++)\n {\n sha256_starts( &sha_ctx);\n sha256_update( &sha_ctx, digest, 32);\n sha256_update( &sha_ctx,\n passwd,\n (unsigned long)passlen);\n sha256_finish( &sha_ctx,\n digest);\n }\n\n /* Set the AES encryption key */\n aes_set_key(&aes_ctx, digest, 256);\n\n /*\n * Set the ipad and opad arrays with values as\n * per RFC 2104 (HMAC). HMAC is defined as\n * H(K XOR opad, H(K XOR ipad, text))\n */\n memset(ipad, 0x36, 64);\n memset(opad, 0x5C, 64);\n\n for(i=0; i<32; i++)\n {\n ipad[i] ^= digest[i];\n opad[i] ^= digest[i];\n }\n\n sha256_starts(&sha_ctx);\n sha256_update(&sha_ctx, ipad, 64);\n\n /*\n * Encrypt the IV and key used to encrypt the plaintext file,\n * writing that encrypted text to the output file.\n */\n for(i=0; i<48; i+=16)\n {\n /*\n * Place the next 16 octets of IV and key buffer into\n * the input buffer.\n */\n memcpy(buffer, iv_key+i, 16);\n\n /*\n * XOR plain text block with previous encrypted\n * output (i.e., use CBC)\n */\n for(j=0; j<16; j++)\n {\n buffer[j] ^= IV[j];\n }\n\n /* Encrypt the contents of the buffer */\n aes_encrypt(&aes_ctx, buffer, buffer);\n \n /* Concatenate the \"text\" as we compute the HMAC */\n sha256_update(&sha_ctx, buffer, 16);\n\n /* Write the encrypted block */\n if (fwrite(buffer, 1, 16, outfp) != 16)\n {\n fprintf(stderr, \"Error: Could not write iv_key data\\n\");\n return -1;\n }\n \n /* Update the IV (CBC mode) */\n memcpy(IV, buffer, 16);\n }\n\n /* Write the HMAC */\n sha256_finish(&sha_ctx, digest);\n sha256_starts(&sha_ctx);\n sha256_update(&sha_ctx, opad, 64);\n sha256_update(&sha_ctx, digest, 32);\n sha256_finish(&sha_ctx, digest);\n /* Write the encrypted block */\n if (fwrite(digest, 1, 32, outfp) != 32)\n {\n fprintf(stderr, \"Error: Could not write iv_key HMAC\\n\");\n return -1;\n }\n\n /* Re-load the IV and encryption key with the IV and\n * key to now encrypt the datafile. Also, reset the HMAC\n * computation.\n */\n memcpy(IV, iv_key, 16);\n\n /* Set the AES encryption key */\n aes_set_key(&aes_ctx, iv_key+16, 256);\n\n /*\n * Set the ipad and opad arrays with values as\n * per RFC 2104 (HMAC). HMAC is defined as\n * H(K XOR opad, H(K XOR ipad, text))\n */\n memset(ipad, 0x36, 64);\n memset(opad, 0x5C, 64);\n\n for(i=0; i<32; i++)\n {\n ipad[i] ^= iv_key[i+16];\n opad[i] ^= iv_key[i+16];\n }\n\n /* Wipe the IV and encryption key from memory */\n memset_secure(iv_key, 0, 48);\n\n sha256_starts(&sha_ctx);\n sha256_update(&sha_ctx, ipad, 64);\n\n /* Initialize the last_block_size value to 0 */\n aeshdr.last_block_size = 0;\n\n while ((bytes_read = fread(buffer, 1, 16, infp)) > 0)\n {\n /*\n * XOR plain text block with previous encrypted\n * output (i.e., use CBC)\n */\n for(i=0; i<16; i++)\n {\n buffer[i] ^= IV[i];\n }\n\n /* Encrypt the contents of the buffer */\n aes_encrypt(&aes_ctx, buffer, buffer);\n \n /* Concatenate the \"text\" as we compute the HMAC */\n sha256_update(&sha_ctx, buffer, 16);\n\n /* Write the encrypted block */\n if (fwrite(buffer, 1, 16, outfp) != 16)\n {\n fprintf(stderr, \"Error: Could not write to output file\\n\");\n return -1;\n }\n \n /* Update the IV (CBC mode) */\n memcpy(IV, buffer, 16);\n\n /* Assume this number of octets is the file modulo */\n aeshdr.last_block_size = bytes_read;\n }\n\n /* Check to see if we had a read error */\n if (ferror(infp))\n {\n fprintf(stderr, \"Error: Couldn't read input file\\n\");\n return -1;\n }\n\n /* Write the file size modulo */\n buffer[0] = (char) (aeshdr.last_block_size & 0x0F);\n if (fwrite(buffer, 1, 1, outfp) != 1)\n {\n fprintf(stderr, \"Error: Could not write the file size modulo\\n\");\n return -1;\n }\n\n /* Write the HMAC */\n sha256_finish(&sha_ctx, digest);\n sha256_starts(&sha_ctx);\n sha256_update(&sha_ctx, opad, 64);\n sha256_update(&sha_ctx, digest, 32);\n sha256_finish(&sha_ctx, digest);\n if (fwrite(digest, 1, 32, outfp) != 32)\n {\n fprintf(stderr, \"Error: Could not write the file HMAC\\n\");\n return -1;\n }\n\n /* Flush the output buffer to ensure all data is written to disk */\n if (fflush(outfp))\n {\n fprintf(stderr, \"Error: Could not flush output file buffer\\n\");\n return -1;\n }\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-287', 'CWE-787'], 'message': 'Fixed security issue with passwords entered via a prompt'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: net_bind(short unsigned *port, int type, const char *log_service_name)\n{\n struct addrinfo hints = { 0 };\n struct addrinfo *servinfo;\n struct addrinfo *ptr;\n const char *cfgaddr;\n char addr[INET6_ADDRSTRLEN];\n char strport[8];\n int yes = 1;\n int no = 0;\n int fd;\n int ret;\n\n cfgaddr = cfg_getstr(cfg_getsec(cfg, \"general\"), \"bind_address\");\n\n hints.ai_socktype = (type & (SOCK_STREAM | SOCK_DGRAM)); // filter since type can be SOCK_STREAM | SOCK_NONBLOCK\n hints.ai_family = (cfg_getbool(cfg_getsec(cfg, \"general\"), \"ipv6\")) ? AF_INET6 : AF_INET;\n hints.ai_flags = cfgaddr ? 0 : AI_PASSIVE;\n\n snprintf(strport, sizeof(strport), \"%hu\", *port);\n ret = getaddrinfo(cfgaddr, strport, &hints, &servinfo);\n if (ret < 0)\n {\n DPRINTF(E_LOG, L_MISC, \"Failure creating '%s' service, could not resolve '%s' (port %s): %s\\n\", log_service_name, cfgaddr ? cfgaddr : \"(ANY)\", strport, gai_strerror(ret));\n return -1;\n }\n\n for (ptr = servinfo, fd = -1; ptr != NULL; ptr = ptr->ai_next)\n {\n if (fd >= 0)\n\tclose(fd);\n\n fd = socket(ptr->ai_family, type | SOCK_CLOEXEC, ptr->ai_protocol);\n if (fd < 0)\n\tcontinue;\n\n // TODO libevent sets this, we do the same?\n ret = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &yes, sizeof(yes));\n if (ret < 0)\n\tcontinue;\n\n ret = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));\n if (ret < 0)\n\tcontinue;\n\n if (ptr->ai_family == AF_INET6)\n\t{\n\t // We want to be sure the service is dual stack\n\t ret = setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &no, sizeof(no));\n\t if (ret < 0)\n\t continue;\n\t}\n\n ret = bind(fd, ptr->ai_addr, ptr->ai_addrlen);\n if (ret < 0)\n\tcontinue;\n\n break;\n }\n\n freeaddrinfo(servinfo);\n\n if (!ptr)\n {\n DPRINTF(E_LOG, L_MISC, \"Could not create service '%s' with address %s, port %hu: %s\\n\", log_service_name, cfgaddr ? cfgaddr : \"(ANY)\", *port, strerror(errno));\n goto error;\n }\n\n // Get the port that was assigned\n ret = getsockname(fd, ptr->ai_addr, &ptr->ai_addrlen);\n if (ret < 0)\n {\n DPRINTF(E_LOG, L_MISC, \"Could not find address of service '%s': %s\\n\", log_service_name, strerror(errno));\n goto error;\n }\n\n net_port_get(port, (union net_sockaddr *)ptr->ai_addr);\n net_address_get(addr, sizeof(addr), (union net_sockaddr *)ptr->ai_addr);\n\n DPRINTF(E_DBG, L_MISC, \"Service '%s' bound to %s, port %hu, socket %d\\n\", log_service_name, addr, *port, fd);\n\n return fd;\n\n error:\n close(fd);\n return -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': '[misc] Fix use-after-free in net_bind()\n\nThanks to Ba Jinsheng for reporting this bug'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: v8::Local CreateNativeEvent(\n v8::Isolate* isolate,\n v8::Local sender,\n content::RenderFrameHost* frame,\n electron::mojom::ElectronBrowser::MessageSyncCallback callback) {\n v8::Local event;\n if (frame && callback) {\n gin::Handle native_event = Event::Create(isolate);\n native_event->SetCallback(std::move(callback));\n event = v8::Local::Cast(native_event.ToV8());\n } else {\n // No need to create native event if we do not need to send reply.\n event = CreateEvent(isolate);\n }\n\n Dictionary dict(isolate, event);\n dict.Set(\"sender\", sender);\n // Should always set frameId even when callback is null.\n if (frame)\n dict.Set(\"frameId\", frame->GetRoutingID());\n return event;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-668'], 'message': 'fix: restrict sendToFrame to same-process frames by default (#26875)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: agoo_http_code_message(int code) {\n const char\t*msg = \"\";\n \n switch (code) {\n case 100:\tmsg = \"Continue\";\t\t\t\tbreak;\n case 101:\tmsg = \"Switching Protocols\";\t\t\tbreak;\n case 102:\tmsg = \"Processing\";\t\t\t\tbreak;\n case 200:\tmsg = \"OK\";\t\t\t\t\tbreak;\n case 201:\tmsg = \"Created\";\t\t\t\tbreak;\n case 202:\tmsg = \"Accepted\";\t\t\t\tbreak;\n case 203:\tmsg = \"Non-authoritative Information\";\t\tbreak;\n case 204:\tmsg = \"No Content\";\t\t\t\tbreak;\n case 205:\tmsg = \"Reset Content\";\t\t\t\tbreak;\n case 206:\tmsg = \"Partial Content\";\t\t\tbreak;\n case 207:\tmsg = \"Multi-Status\";\t\t\t\tbreak;\n case 208:\tmsg = \"Already Reported\";\t\t\tbreak;\n case 226:\tmsg = \"IM Used\";\t\t\t\tbreak;\n case 300:\tmsg = \"Multiple Choices\";\t\t\tbreak;\n case 301:\tmsg = \"Moved Permanently\";\t\t\tbreak;\n case 302:\tmsg = \"Found\";\t\t\t\t\tbreak;\n case 303:\tmsg = \"See Other\";\t\t\t\tbreak;\n case 304:\tmsg = \"Not Modified\";\t\t\t\tbreak;\n case 305:\tmsg = \"Use Proxy\";\t\t\t\tbreak;\n case 307:\tmsg = \"Temporary Redirect\";\t\t\tbreak;\n case 308:\tmsg = \"Permanent Redirect\";\t\t\tbreak;\n case 400:\tmsg = \"Bad Request\";\t\t\t\tbreak;\n case 401:\tmsg = \"Unauthorized\";\t\t\t\tbreak;\n case 402:\tmsg = \"Payment Required\";\t\t\tbreak;\n case 403:\tmsg = \"Forbidden\";\t\t\t\tbreak;\n case 404:\tmsg = \"Not Found\";\t\t\t\tbreak;\n case 405:\tmsg = \"Method Not Allowed\";\t\t\tbreak;\n case 406:\tmsg = \"Not Acceptable\";\t\t\t\tbreak;\n case 407:\tmsg = \"Proxy Authentication Required\";\t\tbreak;\n case 408:\tmsg = \"Request Timeout\";\t\t\tbreak;\n case 409:\tmsg = \"Conflict\";\t\t\t\tbreak;\n case 410:\tmsg = \"Gone\";\t\t\t\t\tbreak;\n case 411:\tmsg = \"Length Required\";\t\t\tbreak;\n case 412:\tmsg = \"Precondition Failed\";\t\t\tbreak;\n case 413:\tmsg = \"Payload Too Large\";\t\t\tbreak;\n case 414:\tmsg = \"Request-URI Too Long\";\t\t\tbreak;\n case 415:\tmsg = \"Unsupported Media Type\";\t\t\tbreak;\n case 416:\tmsg = \"Requested Range Not Satisfiable\";\tbreak;\n case 417:\tmsg = \"Expectation Failed\";\t\t\tbreak;\n case 418:\tmsg = \"I'm a teapot\";\t\t\t\tbreak;\n case 421:\tmsg = \"Misdirected Request\";\t\t\tbreak;\n case 422:\tmsg = \"Unprocessable Entity\";\t\t\tbreak;\n case 423:\tmsg = \"Locked\";\t\t\t\t\tbreak;\n case 424:\tmsg = \"Failed Dependency\";\t\t\tbreak;\n case 426:\tmsg = \"Upgrade Required\";\t\t\tbreak;\n case 428:\tmsg = \"Precondition Required\";\t\t\tbreak;\n case 429:\tmsg = \"Too Many Requests\";\t\t\tbreak;\n case 431:\tmsg = \"Request Header Fields Too Large\";\tbreak;\n case 444:\tmsg = \"Connection Closed Without Response\";\tbreak;\n case 451:\tmsg = \"Unavailable For Legal Reasons\";\t\tbreak;\n case 499:\tmsg = \"Client Closed Request\";\t\t\tbreak;\n case 500:\tmsg = \"Internal Server Error\";\t\t\tbreak;\n case 501:\tmsg = \"Not Implemented\";\t\t\tbreak;\n case 502:\tmsg = \"Bad Gateway\";\t\t\t\tbreak;\n case 503:\tmsg = \"Service Unavailable\";\t\t\tbreak;\n case 504:\tmsg = \"Gateway Timeout\";\t\t\tbreak;\n case 505:\tmsg = \"HTTP Version Not Supported\";\t\tbreak;\n case 506:\tmsg = \"Variant Also Negotiates\";\t\tbreak;\n case 507:\tmsg = \"Insufficient Storage\";\t\t\tbreak;\n case 508:\tmsg = \"Loop Detected\";\t\t\t\tbreak;\n case 510:\tmsg = \"Not Extended\";\t\t\t\tbreak;\n case 511:\tmsg = \"Network Authentication Required\";\tbreak;\n case 599:\tmsg = \"Network Connect Timeout Error\";\t\tbreak;\n default:\t\t\t\t\t\t\tbreak;\n }\n return msg;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-444', 'CWE-61'], 'message': 'Remote addr (#99)\n\n* REMOTE_ADDR added\r\n\r\n* Ready for merge'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: std::istream& operator>>\n (std::istream& is, Nef_polyhedron_2& NP)\n{\n typedef typename Nef_polyhedron_2::Decorator Decorator;\n CGAL::PM_io_parser I(is, NP.pm());\n if (I.check_sep(\"Nef_polyhedron_2<\") &&\n I.check_sep(NP.EK.output_identifier()) &&\n I.check_sep(\">\")) I.read();\n else {\n std::cerr << \"Nef_polyhedron_2 input corrupted.\" << std::endl;\n NP = Nef_polyhedron_2();\n }\n typename Nef_polyhedron_2::Topological_explorer D(NP.explorer());\n D.check_integrity_and_topological_planarity();\n return is;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-269'], 'message': 'Fix Nef_2 and Nef_S2 IO'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void Lua::setParamsTable(lua_State* vm, const char* table_name,\n\t\t\t const char* query) const {\n char outbuf[FILENAME_MAX];\n char *where;\n char *tok;\n\n char *query_string = query ? strdup(query) : NULL;\n\n lua_newtable(L);\n\n if (query_string) {\n // ntop->getTrace()->traceEvent(TRACE_WARNING, \"[HTTP] %s\", query_string);\n\n tok = strtok_r(query_string, \"&\", &where);\n\n while(tok != NULL) {\n char *_equal;\n\n if(strncmp(tok, \"csrf\", strlen(\"csrf\")) /* Do not put csrf into the params table */\n\t && (_equal = strchr(tok, '='))) {\n\tchar *decoded_buf;\n int len;\n\n _equal[0] = '\\0';\n _equal = &_equal[1];\n len = strlen(_equal);\n\n purifyHTTPParameter(tok), purifyHTTPParameter(_equal);\n\n // ntop->getTrace()->traceEvent(TRACE_WARNING, \"%s = %s\", tok, _equal);\n\n if((decoded_buf = (char*)malloc(len+1)) != NULL) {\n\n Utils::urlDecode(_equal, decoded_buf, len+1);\n\n\t Utils::purifyHTTPparam(tok, true, false);\n\t Utils::purifyHTTPparam(decoded_buf, false, false);\n\n\t /* Now make sure that decoded_buf is not a file path */\n\t FILE *fd;\n\t if((decoded_buf[0] == '.')\n\t && ((fd = fopen(decoded_buf, \"r\"))\n\t\t || (fd = fopen(realpath(decoded_buf, outbuf), \"r\")))) {\n\n\t ntop->getTrace()->traceEvent(TRACE_WARNING, \"Discarded '%s'='%s' as argument is a valid file path\",\n\t\t\t\t\t tok, decoded_buf);\n\t decoded_buf[0] = '\\0';\n\t fclose(fd);\n\t }\n\n\t /* ntop->getTrace()->traceEvent(TRACE_WARNING, \"'%s'='%s'\", tok, decoded_buf); */\n\n\t /* put tok and the decoded buffer in to the table */\n\t lua_push_str_table_entry(vm, tok, decoded_buf);\n\n free(decoded_buf);\n } else\n ntop->getTrace()->traceEvent(TRACE_WARNING, \"Not enough memory\");\n }\n\n tok = strtok_r(NULL, \"&\", &where);\n } /* while */\n }\n\n if(query_string) free(query_string);\n\n if(table_name)\n lua_setglobal(L, table_name);\n else\n lua_setglobal(L, (char*)\"_GET\"); /* Default */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Security fix: prevents empty host from being used'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void Compute(OpKernelContext *ctx) override {\n // (0) validations\n const Tensor *a_indices, *b_indices, *a_values_t, *b_values_t, *a_shape,\n *b_shape, *thresh_t;\n\n OP_REQUIRES_OK(ctx, ctx->input(\"a_indices\", &a_indices));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_indices\", &b_indices));\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsMatrix(a_indices->shape()) &&\n TensorShapeUtils::IsMatrix(b_indices->shape()),\n errors::InvalidArgument(\n \"Input indices should be matrices but received shapes: \",\n a_indices->shape().DebugString(), \" and \",\n b_indices->shape().DebugString()));\n const int64 a_nnz = a_indices->dim_size(0);\n const int64 b_nnz = b_indices->dim_size(0);\n\n OP_REQUIRES_OK(ctx, ctx->input(\"a_values\", &a_values_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_values\", &b_values_t));\n\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(a_values_t->shape()) &&\n TensorShapeUtils::IsVector(b_values_t->shape()),\n errors::InvalidArgument(\n \"Input values should be vectors but received shapes: \",\n a_values_t->shape().DebugString(), \" and \",\n b_values_t->shape().DebugString()));\n auto a_values = ctx->input(1).vec();\n auto b_values = ctx->input(4).vec();\n OP_REQUIRES(\n ctx, a_values.size() == a_nnz && b_values.size() == b_nnz,\n errors::InvalidArgument(\"Expected \", a_nnz, \" and \", b_nnz,\n \" non-empty input values, got \",\n a_values.size(), \" and \", b_values.size()));\n\n OP_REQUIRES_OK(ctx, ctx->input(\"a_shape\", &a_shape));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_shape\", &b_shape));\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(a_shape->shape()) &&\n TensorShapeUtils::IsVector(b_shape->shape()),\n errors::InvalidArgument(\n \"Input shapes should be a vector but received shapes \",\n a_shape->shape().DebugString(), \" and \",\n b_shape->shape().DebugString()));\n OP_REQUIRES(\n ctx, a_shape->IsSameSize(*b_shape),\n errors::InvalidArgument(\n \"Operands do not have the same ranks; got shapes: \",\n a_shape->SummarizeValue(10), \" and \", b_shape->SummarizeValue(10)));\n const auto a_shape_flat = a_shape->flat();\n const auto b_shape_flat = b_shape->flat();\n for (int i = 0; i < a_shape->NumElements(); ++i) {\n OP_REQUIRES(ctx, a_shape_flat(i) == b_shape_flat(i),\n errors::InvalidArgument(\n \"Operands' shapes do not match: got \", a_shape_flat(i),\n \" and \", b_shape_flat(i), \" for dimension \", i));\n }\n\n OP_REQUIRES_OK(ctx, ctx->input(\"thresh\", &thresh_t));\n OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(thresh_t->shape()),\n errors::InvalidArgument(\n \"The magnitude threshold must be a scalar: got shape \",\n thresh_t->shape().DebugString()));\n // std::abs() so that it works for complex{64,128} values as well\n const Treal thresh = thresh_t->scalar()();\n\n // (1) do a pass over inputs, and append values and indices to vectors\n auto a_indices_mat = a_indices->matrix();\n auto b_indices_mat = b_indices->matrix();\n std::vector> entries_to_copy; // from_a?, idx\n entries_to_copy.reserve(a_nnz + b_nnz);\n std::vector out_values;\n const int num_dims = a_shape->dim_size(0);\n\n // The input and output sparse tensors are assumed to be ordered along\n // increasing dimension number.\n int64 i = 0, j = 0;\n T s;\n while (i < a_nnz && j < b_nnz) {\n switch (sparse::DimComparator::cmp(a_indices_mat, b_indices_mat, i, j,\n num_dims)) {\n case -1:\n entries_to_copy.emplace_back(true, i);\n out_values.push_back(a_values(i));\n ++i;\n break;\n case 0:\n s = a_values(i) + b_values(j);\n if (thresh <= std::abs(s)) {\n entries_to_copy.emplace_back(true, i);\n out_values.push_back(s);\n }\n ++i;\n ++j;\n break;\n case 1:\n entries_to_copy.emplace_back(false, j);\n out_values.push_back(b_values(j));\n ++j;\n break;\n }\n }\n\n#define HANDLE_LEFTOVERS(A_OR_B, IDX, IS_A) \\\n while (IDX < A_OR_B##_nnz) { \\\n entries_to_copy.emplace_back(IS_A, IDX); \\\n out_values.push_back(A_OR_B##_values(IDX)); \\\n ++IDX; \\\n }\n\n // at most one of these calls appends new values\n HANDLE_LEFTOVERS(a, i, true);\n HANDLE_LEFTOVERS(b, j, false);\n#undef HANDLE_LEFTOVERS\n\n // (2) allocate and fill output tensors\n const int64 sum_nnz = out_values.size();\n Tensor *out_indices_t, *out_values_t;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_output(0, TensorShape({sum_nnz, num_dims}),\n &out_indices_t));\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(1, TensorShape({sum_nnz}), &out_values_t));\n auto out_indices_mat = out_indices_t->matrix();\n auto out_values_flat = out_values_t->vec();\n\n for (i = 0; i < sum_nnz; ++i) {\n const bool from_a = entries_to_copy[i].first;\n const int64 idx = entries_to_copy[i].second;\n out_indices_mat.chip<0>(i) =\n from_a ? a_indices_mat.chip<0>(idx) : b_indices_mat.chip<0>(idx);\n }\n if (sum_nnz > 0) {\n std::copy_n(out_values.begin(), sum_nnz, &out_values_flat(0));\n }\n ctx->set_output(2, *a_shape);\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-369', 'CWE-787'], 'message': 'Fix `tf.raw_ops.SparseAdd ` invalid memory access failure.\n\nPiperOrigin-RevId: 370568774\nChange-Id: I5f73b31c865f2948a1c8dfb7ebd22b3cfb6405bf'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: CreateSchemaCommand(CreateSchemaStmt *stmt, const char *queryString,\n\t\t\t\t\tint stmt_location, int stmt_len)\n{\n\tconst char *schemaName = stmt->schemaname;\n\tOid\t\t\tnamespaceId;\n\tOverrideSearchPath *overridePath;\n\tList\t *parsetree_list;\n\tListCell *parsetree_item;\n\tOid\t\t\towner_uid;\n\tOid\t\t\tsaved_uid;\n\tint\t\t\tsave_sec_context;\n\tAclResult\taclresult;\n\tObjectAddress address;\n\n\tGetUserIdAndSecContext(&saved_uid, &save_sec_context);\n\n\t/*\n\t * Who is supposed to own the new schema?\n\t */\n\tif (stmt->authrole)\n\t\towner_uid = get_rolespec_oid(stmt->authrole, false);\n\telse\n\t\towner_uid = saved_uid;\n\n\t/* fill schema name with the user name if not specified */\n\tif (!schemaName)\n\t{\n\t\tHeapTuple\ttuple;\n\n\t\ttuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(owner_uid));\n\t\tif (!HeapTupleIsValid(tuple))\n\t\t\telog(ERROR, \"cache lookup failed for role %u\", owner_uid);\n\t\tschemaName =\n\t\t\tpstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));\n\t\tReleaseSysCache(tuple);\n\t}\n\n\t/*\n\t * To create a schema, must have schema-create privilege on the current\n\t * database and must be able to become the target role (this does not\n\t * imply that the target role itself must have create-schema privilege).\n\t * The latter provision guards against \"giveaway\" attacks. Note that a\n\t * superuser will always have both of these privileges a fortiori.\n\t */\n\taclresult = pg_database_aclcheck(MyDatabaseId, saved_uid, ACL_CREATE);\n\tif (aclresult != ACLCHECK_OK)\n\t\taclcheck_error(aclresult, OBJECT_DATABASE,\n\t\t\t\t\t get_database_name(MyDatabaseId));\n\n\tcheck_is_member_of_role(saved_uid, owner_uid);\n\n\t/* Additional check to protect reserved schema names */\n\tif (!allowSystemTableMods && IsReservedName(schemaName))\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_RESERVED_NAME),\n\t\t\t\t errmsg(\"unacceptable schema name \\\"%s\\\"\", schemaName),\n\t\t\t\t errdetail(\"The prefix \\\"pg_\\\" is reserved for system schemas.\")));\n\n\t/*\n\t * If if_not_exists was given and the schema already exists, bail out.\n\t * (Note: we needn't check this when not if_not_exists, because\n\t * NamespaceCreate will complain anyway.) We could do this before making\n\t * the permissions checks, but since CREATE TABLE IF NOT EXISTS makes its\n\t * creation-permission check first, we do likewise.\n\t */\n\tif (stmt->if_not_exists &&\n\t\tSearchSysCacheExists1(NAMESPACENAME, PointerGetDatum(schemaName)))\n\t{\n\t\tereport(NOTICE,\n\t\t\t\t(errcode(ERRCODE_DUPLICATE_SCHEMA),\n\t\t\t\t errmsg(\"schema \\\"%s\\\" already exists, skipping\",\n\t\t\t\t\t\tschemaName)));\n\t\treturn InvalidOid;\n\t}\n\n\t/*\n\t * If the requested authorization is different from the current user,\n\t * temporarily set the current user so that the object(s) will be created\n\t * with the correct ownership.\n\t *\n\t * (The setting will be restored at the end of this routine, or in case of\n\t * error, transaction abort will clean things up.)\n\t */\n\tif (saved_uid != owner_uid)\n\t\tSetUserIdAndSecContext(owner_uid,\n\t\t\t\t\t\t\t save_sec_context | SECURITY_LOCAL_USERID_CHANGE);\n\n\t/* Create the schema's namespace */\n\tnamespaceId = NamespaceCreate(schemaName, owner_uid, false);\n\n\t/* Advance cmd counter to make the namespace visible */\n\tCommandCounterIncrement();\n\n\t/*\n\t * Temporarily make the new namespace be the front of the search path, as\n\t * well as the default creation target namespace. This will be undone at\n\t * the end of this routine, or upon error.\n\t */\n\toverridePath = GetOverrideSearchPath(CurrentMemoryContext);\n\toverridePath->schemas = lcons_oid(namespaceId, overridePath->schemas);\n\t/* XXX should we clear overridePath->useTemp? */\n\tPushOverrideSearchPath(overridePath);\n\n\t/*\n\t * Report the new schema to possibly interested event triggers. Note we\n\t * must do this here and not in ProcessUtilitySlow because otherwise the\n\t * objects created below are reported before the schema, which would be\n\t * wrong.\n\t */\n\tObjectAddressSet(address, NamespaceRelationId, namespaceId);\n\tEventTriggerCollectSimpleCommand(address, InvalidObjectAddress,\n\t\t\t\t\t\t\t\t\t (Node *) stmt);\n\n\t/*\n\t * Examine the list of commands embedded in the CREATE SCHEMA command, and\n\t * reorganize them into a sequentially executable order with no forward\n\t * references. Note that the result is still a list of raw parsetrees ---\n\t * we cannot, in general, run parse analysis on one statement until we\n\t * have actually executed the prior ones.\n\t */\n\tparsetree_list = transformCreateSchemaStmt(stmt);\n\n\t/*\n\t * Execute each command contained in the CREATE SCHEMA. Since the grammar\n\t * allows only utility commands in CREATE SCHEMA, there is no need to pass\n\t * them through parse_analyze() or the rewriter; we can just hand them\n\t * straight to ProcessUtility.\n\t */\n\tforeach(parsetree_item, parsetree_list)\n\t{\n\t\tNode\t *stmt = (Node *) lfirst(parsetree_item);\n\t\tPlannedStmt *wrapper;\n\n\t\t/* need to make a wrapper PlannedStmt */\n\t\twrapper = makeNode(PlannedStmt);\n\t\twrapper->commandType = CMD_UTILITY;\n\t\twrapper->canSetTag = false;\n\t\twrapper->utilityStmt = stmt;\n\t\twrapper->stmt_location = stmt_location;\n\t\twrapper->stmt_len = stmt_len;\n\n\t\t/* do this step */\n\t\tProcessUtility(wrapper,\n\t\t\t\t\t queryString,\n\t\t\t\t\t PROCESS_UTILITY_SUBCOMMAND,\n\t\t\t\t\t NULL,\n\t\t\t\t\t NULL,\n\t\t\t\t\t None_Receiver,\n\t\t\t\t\t NULL);\n\n\t\t/* make sure later steps can see the object created here */\n\t\tCommandCounterIncrement();\n\t}\n\n\t/* Reset search path to normal state */\n\tPopOverrideSearchPath();\n\n\t/* Reset current user and security context */\n\tSetUserIdAndSecContext(saved_uid, save_sec_context);\n\n\treturn namespaceId;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-94'], 'message': 'In extensions, don't replace objects not belonging to the extension.\n\nPreviously, if an extension script did CREATE OR REPLACE and there was\nan existing object not belonging to the extension, it would overwrite\nthe object and adopt it into the extension. This is problematic, first\nbecause the overwrite is probably unintentional, and second because we\ndidn't change the object's ownership. Thus a hostile user could create\nan object in advance of an expected CREATE EXTENSION command, and would\nthen have ownership rights on an extension object, which could be\nmodified for trojan-horse-type attacks.\n\nHence, forbid CREATE OR REPLACE of an existing object unless it already\nbelongs to the extension. (Note that we've always forbidden replacing\nan object that belongs to some other extension; only the behavior for\npreviously-free-standing objects changes here.)\n\nFor the same reason, also fail CREATE IF NOT EXISTS when there is\nan existing object that doesn't belong to the extension.\n\nOur thanks to Sven Klemm for reporting this problem.\n\nSecurity: CVE-2022-2625'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: dhcpv4_print(netdissect_options *ndo,\n const u_char *cp, u_int length, int indent)\n{\n u_int i, t;\n const u_char *tlv, *value;\n uint8_t type, optlen;\n\n i = 0;\n while (i < length) {\n tlv = cp + i;\n type = (uint8_t)tlv[0];\n optlen = (uint8_t)tlv[1];\n value = tlv + 2;\n\n ND_PRINT((ndo, \"\\n\"));\n for (t = indent; t > 0; t--)\n ND_PRINT((ndo, \"\\t\"));\n\n ND_PRINT((ndo, \"%s\", tok2str(dh4opt_str, \"Unknown\", type)));\n ND_PRINT((ndo,\" (%u)\", optlen + 2 ));\n\n switch (type) {\n case DH4OPT_DNS_SERVERS:\n case DH4OPT_NTP_SERVERS: {\n if (optlen < 4 || optlen % 4 != 0) {\n return -1;\n }\n for (t = 0; t < optlen; t += 4)\n ND_PRINT((ndo, \" %s\", ipaddr_string(ndo, value + t)));\n }\n break;\n case DH4OPT_DOMAIN_SEARCH: {\n const u_char *tp = value;\n while (tp < value + optlen) {\n ND_PRINT((ndo, \" \"));\n if ((tp = ns_nprint(ndo, tp, value + optlen)) == NULL)\n return -1;\n }\n }\n break;\n }\n\n i += 2 + optlen;\n }\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13044/HNCP: add DHCPv4-Data bounds checks\n\ndhcpv4_print() in print-hncp.c had the same bug as dhcpv6_print(), apply\na fix along the same lines.\n\nThis fixes a buffer over-read discovered by Bhargava Shastry,\nSecT/TU Berlin.\n\nAdd a test using the capture file supplied by the reporter(s).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: Status UncompressElement(const CompressedElement& compressed,\n std::vector* out) {\n int num_components = compressed.component_metadata_size();\n out->clear();\n out->reserve(num_components);\n\n // Step 1: Prepare the memory that we will uncompress into.\n std::vector iov(num_components);\n // We use tstring for access to resize_uninitialized.\n std::vector tensor_proto_strs;\n // num_components is a conservative estimate. It is important to reserve\n // vector space so that the vector doesn't resize itself, which could\n // invalidate pointers to its strings' data.\n tensor_proto_strs.reserve(num_components);\n int64 total_size = 0;\n for (int i = 0; i < num_components; ++i) {\n const CompressedComponentMetadata& metadata =\n compressed.component_metadata(i);\n if (DataTypeCanUseMemcpy(metadata.dtype())) {\n out->emplace_back(metadata.dtype(), metadata.tensor_shape());\n TensorBuffer* buffer = DMAHelper::buffer(&out->back());\n iov[i].iov_base = buffer->data();\n iov[i].iov_len = buffer->size();\n } else {\n // Allocate an empty Tensor. We will fill it out later after\n // uncompressing into the tensor_proto_str.\n out->emplace_back();\n tensor_proto_strs.emplace_back();\n tstring& tensor_proto_str = tensor_proto_strs.back();\n tensor_proto_str.resize_uninitialized(metadata.tensor_size_bytes());\n iov[i].iov_base = tensor_proto_str.mdata();\n iov[i].iov_len = tensor_proto_str.size();\n }\n total_size += iov[i].iov_len;\n }\n\n // Step 2: Uncompress into the iovec.\n const std::string& compressed_data = compressed.data();\n size_t uncompressed_size;\n if (!port::Snappy_GetUncompressedLength(\n compressed_data.data(), compressed_data.size(), &uncompressed_size)) {\n return errors::Internal(\n \"Could not get snappy uncompressed length. Compressed data size: \",\n compressed_data.size());\n }\n if (uncompressed_size != static_cast(total_size)) {\n return errors::Internal(\n \"Uncompressed size mismatch. Snappy expects \", uncompressed_size,\n \" whereas the tensor metadata suggests \", total_size);\n }\n if (!port::Snappy_UncompressToIOVec(compressed_data.data(),\n compressed_data.size(), iov.data(),\n num_components)) {\n return errors::Internal(\"Failed to perform snappy decompression.\");\n }\n\n // Step 3: Deserialize tensor proto strings to tensors.\n int tensor_proto_strs_index = 0;\n for (int i = 0; i < num_components; ++i) {\n if (DataTypeCanUseMemcpy(compressed.component_metadata(i).dtype())) {\n continue;\n }\n TensorProto tp;\n if (!tp.ParseFromString(tensor_proto_strs[tensor_proto_strs_index++])) {\n return errors::Internal(\"Could not parse TensorProto\");\n }\n if (!out->at(i).FromProto(tp)) {\n return errors::Internal(\"Could not parse Tensor\");\n }\n }\n return Status::OK();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-125'], 'message': 'Fix accessing possible nullptr in tensorflow::data::CompressElement and UncompressElement which are used in tf.data.service.\n\nPiperOrigin-RevId: 373920841\nChange-Id: Ia88d78aee09fa19bb53a0f163fd19620d0c68743'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: DNSResult DNS::GetResult()\n{\n\t/* Fetch dns query response and decide where it belongs */\n\tDNSHeader header;\n\tDNSRequest *req;\n\tunsigned char buffer[sizeof(DNSHeader)];\n\tirc::sockets::sockaddrs from;\n\tmemset(&from, 0, sizeof(from));\n\tsocklen_t x = sizeof(from);\n\n\tint length = ServerInstance->SE->RecvFrom(this, (char*)buffer, sizeof(DNSHeader), 0, &from.sa, &x);\n\n\t/* Did we get the whole header? */\n\tif (length < 12)\n\t{\n\t\tServerInstance->Logs->Log(\"RESOLVER\",DEBUG,\"GetResult didn't get a full packet (len=%d)\", length);\n\t\t/* Nope - something screwed up. */\n\t\treturn DNSResult(-1,\"\",0,\"\");\n\t}\n\n\t/* Check wether the reply came from a different DNS\n\t * server to the one we sent it to, or the source-port\n\t * is not 53.\n\t * A user could in theory still spoof dns packets anyway\n\t * but this is less trivial than just sending garbage\n\t * to the server, which is possible without this check.\n\t *\n\t * -- Thanks jilles for pointing this one out.\n\t */\n\tif (from != myserver)\n\t{\n\t\tstd::string server1 = from.str();\n\t\tstd::string server2 = myserver.str();\n\t\tServerInstance->Logs->Log(\"RESOLVER\",DEBUG,\"Got a result from the wrong server! Bad NAT or DNS forging attempt? '%s' != '%s'\",\n\t\t\tserver1.c_str(), server2.c_str());\n\t\treturn DNSResult(-1,\"\",0,\"\");\n\t}\n\n\t/* Put the read header info into a header class */\n\tDNS::FillHeader(&header,buffer,length - 12);\n\n\t/* Get the id of this request.\n\t * Its a 16 bit value stored in two char's,\n\t * so we use logic shifts to create the value.\n\t */\n\tunsigned long this_id = header.id[1] + (header.id[0] << 8);\n\n\t/* Do we have a pending request matching this id? */\n\tif (!requests[this_id])\n\t{\n\t\t/* Somehow we got a DNS response for a request we never made... */\n\t\tServerInstance->Logs->Log(\"RESOLVER\",DEBUG,\"Hmm, got a result that we didn't ask for (id=%lx). Ignoring.\", this_id);\n\t\treturn DNSResult(-1,\"\",0,\"\");\n\t}\n\telse\n\t{\n\t\t/* Remove the query from the list of pending queries */\n\t\treq = requests[this_id];\n\t\trequests[this_id] = NULL;\n\t}\n\n\t/* Inform the DNSRequest class that it has a result to be read.\n\t * When its finished it will return a DNSInfo which is a pair of\n\t * unsigned char* resource record data, and an error message.\n\t */\n\tDNSInfo data = req->ResultIsReady(header, length);\n\tstd::string resultstr;\n\n\t/* Check if we got a result, if we didnt, its an error */\n\tif (data.first == NULL)\n\t{\n\t\t/* An error.\n\t\t * Mask the ID with the value of ERROR_MASK, so that\n\t\t * the dns_deal_with_classes() function knows that its\n\t\t * an error response and needs to be treated uniquely.\n\t\t * Put the error message in the second field.\n\t\t */\n\t\tstd::string ro = req->orig;\n\t\tdelete req;\n\t\treturn DNSResult(this_id | ERROR_MASK, data.second, 0, ro);\n\t}\n\telse\n\t{\n\t\tunsigned long ttl = req->ttl;\n\t\tchar formatted[128];\n\n\t\t/* Forward lookups come back as binary data. We must format them into ascii */\n\t\tswitch (req->type)\n\t\t{\n\t\t\tcase DNS_QUERY_A:\n\t\t\t\tsnprintf(formatted,16,\"%u.%u.%u.%u\",data.first[0],data.first[1],data.first[2],data.first[3]);\n\t\t\t\tresultstr = formatted;\n\t\t\tbreak;\n\n\t\t\tcase DNS_QUERY_AAAA:\n\t\t\t{\n\t\t\t\tif (!inet_ntop(AF_INET6, data.first, formatted, sizeof(formatted)))\n\t\t\t\t{\n\t\t\t\t\tstd::string ro = req->orig;\n\t\t\t\t\tdelete req;\n\t\t\t\t\treturn DNSResult(this_id | ERROR_MASK, \"inet_ntop() failed\", 0, ro);\n\t\t\t\t}\n\n\t\t\t\tresultstr = formatted;\n\n\t\t\t\t/* Special case. Sending ::1 around between servers\n\t\t\t\t * and to clients is dangerous, because the : on the\n\t\t\t\t * start makes the client or server interpret the IP\n\t\t\t\t * as the last parameter on the line with a value \":1\".\n\t\t\t\t */\n\t\t\t\tif (*formatted == ':')\n\t\t\t\t\tresultstr.insert(0, \"0\");\n\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase DNS_QUERY_CNAME:\n\t\t\t\t/* Identical handling to PTR */\n\n\t\t\tcase DNS_QUERY_PTR:\n\t\t\t\t/* Reverse lookups just come back as char* */\n\t\t\t\tresultstr = std::string((const char*)data.first);\n\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Build the reply with the id and hostname/ip in it */\n\t\tstd::string ro = req->orig;\n\t\tDNSResult result = DNSResult(this_id,resultstr,ttl,ro,req->type);\n\t\tdelete req;\n\t\treturn result;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-416'], 'message': 'Reject replies to DNS PTR requests that contain invalid characters\n\nFixes issue #1033 reported by @ping86'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int mxf_read_primer_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)\n{\n MXFContext *mxf = arg;\n int item_num = avio_rb32(pb);\n int item_len = avio_rb32(pb);\n\n if (item_len != 18) {\n avpriv_request_sample(pb, \"Primer pack item length %d\", item_len);\n return AVERROR_PATCHWELCOME;\n }\n if (item_num > 65536) {\n av_log(mxf->fc, AV_LOG_ERROR, \"item_num %d is too large\\n\", item_num);\n return AVERROR_INVALIDDATA;\n }\n mxf->local_tags = av_calloc(item_num, item_len);\n if (!mxf->local_tags)\n return AVERROR(ENOMEM);\n mxf->local_tags_count = item_num;\n avio_read(pb, mxf->local_tags, item_num*item_len);\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'avformat/mxfdec: Fix Sign error in mxf_read_primer_pack()\n\nFixes: 20170829B.mxf\n\nCo-Author: \u5f20\u6d2a\u4eae(\u671b\u521d)\" \nFound-by: Xiaohei and Wangchu from Alibaba Security Team\nSigned-off-by: Michael Niedermayer \n(cherry picked from commit 9d00fb9d70ee8c0cc7002b89318c5be00f1bbdad)\nSigned-off-by: Michael Niedermayer '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: size_t srvstr_get_path_req(TALLOC_CTX *mem_ctx, struct smb_request *req,\n\t\t\t\t char **pp_dest, const char *src, int flags,\n\t\t\t\t NTSTATUS *err)\n{\n\tssize_t bufrem = smbreq_bufrem(req, src);\n\n\tif (bufrem < 0) {\n\t\t*err = NT_STATUS_INVALID_PARAMETER;\n\t\treturn 0;\n\t}\n\n\tif (req->posix_pathnames) {\n\t\treturn srvstr_get_path_internal(mem_ctx,\n\t\t\t\t(const char *)req->inbuf,\n\t\t\t\treq->flags2,\n\t\t\t\tpp_dest,\n\t\t\t\tsrc,\n\t\t\t\tbufrem,\n\t\t\t\tflags,\n\t\t\t\ttrue,\n\t\t\t\terr);\n\t} else {\n\t\treturn srvstr_get_path_internal(mem_ctx,\n\t\t\t\t(const char *)req->inbuf,\n\t\t\t\treq->flags2,\n\t\t\t\tpp_dest,\n\t\t\t\tsrc,\n\t\t\t\tbufrem,\n\t\t\t\tflags,\n\t\t\t\tfalse,\n\t\t\t\terr);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'CVE-2022-32742: s3: smbd: Harden the smbreq_bufrem() macro.\n\nFixes the raw.write.bad-write test.\n\nNB. We need the two (==0) changes in source3/smbd/smb2_reply.c\nas the gcc optimizer now knows that the return from\nsmbreq_bufrem() can never be less than zero.\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=15085\n\nRemove knownfail.\n\nSigned-off-by: Jeremy Allison \nReviewed-by: David Disseldorp \n\nAutobuild-User(master): Jule Anger \nAutobuild-Date(master): Wed Jul 27 11:46:46 UTC 2022 on sn-devel-184'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int bcm_release(struct socket *sock)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct net *net;\n\tstruct bcm_sock *bo;\n\tstruct bcm_op *op, *next;\n\n\tif (!sk)\n\t\treturn 0;\n\n\tnet = sock_net(sk);\n\tbo = bcm_sk(sk);\n\n\t/* remove bcm_ops, timer, rx_unregister(), etc. */\n\n\tspin_lock(&bcm_notifier_lock);\n\twhile (bcm_busy_notifier == bo) {\n\t\tspin_unlock(&bcm_notifier_lock);\n\t\tschedule_timeout_uninterruptible(1);\n\t\tspin_lock(&bcm_notifier_lock);\n\t}\n\tlist_del(&bo->notifier);\n\tspin_unlock(&bcm_notifier_lock);\n\n\tlock_sock(sk);\n\n\tlist_for_each_entry_safe(op, next, &bo->tx_ops, list)\n\t\tbcm_remove_op(op);\n\n\tlist_for_each_entry_safe(op, next, &bo->rx_ops, list) {\n\t\t/*\n\t\t * Don't care if we're bound or not (due to netdev problems)\n\t\t * can_rx_unregister() is always a save thing to do here.\n\t\t */\n\t\tif (op->ifindex) {\n\t\t\t/*\n\t\t\t * Only remove subscriptions that had not\n\t\t\t * been removed due to NETDEV_UNREGISTER\n\t\t\t * in bcm_notifier()\n\t\t\t */\n\t\t\tif (op->rx_reg_dev) {\n\t\t\t\tstruct net_device *dev;\n\n\t\t\t\tdev = dev_get_by_index(net, op->ifindex);\n\t\t\t\tif (dev) {\n\t\t\t\t\tbcm_rx_unreg(dev, op);\n\t\t\t\t\tdev_put(dev);\n\t\t\t\t}\n\t\t\t}\n\t\t} else\n\t\t\tcan_rx_unregister(net, NULL, op->can_id,\n\t\t\t\t\t REGMASK(op->can_id),\n\t\t\t\t\t bcm_rx_handler, op);\n\n\t\tbcm_remove_op(op);\n\t}\n\n#if IS_ENABLED(CONFIG_PROC_FS)\n\t/* remove procfs entry */\n\tif (net->can.bcmproc_dir && bo->bcm_proc_read)\n\t\tremove_proc_entry(bo->procname, net->can.bcmproc_dir);\n#endif /* CONFIG_PROC_FS */\n\n\t/* remove device reference */\n\tif (bo->bound) {\n\t\tbo->bound = 0;\n\t\tbo->ifindex = 0;\n\t}\n\n\tsock_orphan(sk);\n\tsock->sk = NULL;\n\n\trelease_sock(sk);\n\tsock_put(sk);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'can: bcm: delay release of struct bcm_op after synchronize_rcu()\n\ncan_rx_register() callbacks may be called concurrently to the call to\ncan_rx_unregister(). The callbacks and callback data, though, are\nprotected by RCU and the struct sock reference count.\n\nSo the callback data is really attached to the life of sk, meaning\nthat it should be released on sk_destruct. However, bcm_remove_op()\ncalls tasklet_kill(), and RCU callbacks may be called under RCU\nsoftirq, so that cannot be used on kernels before the introduction of\nHRTIMER_MODE_SOFT.\n\nHowever, bcm_rx_handler() is called under RCU protection, so after\ncalling can_rx_unregister(), we may call synchronize_rcu() in order to\nwait for any RCU read-side critical sections to finish. That is,\nbcm_rx_handler() won't be called anymore for those ops. So, we only\nfree them, after we do that synchronize_rcu().\n\nFixes: ffd980f976e7 (\"[CAN]: Add broadcast manager (bcm) protocol\")\nLink: https://lore.kernel.org/r/20210619161813.2098382-1-cascardo@canonical.com\nCc: linux-stable \nReported-by: syzbot+0f7e7e5e2f4f40fa89c0@syzkaller.appspotmail.com\nReported-by: Norbert Slusarek \nSigned-off-by: Thadeu Lima de Souza Cascardo \nAcked-by: Oliver Hartkopp \nSigned-off-by: Marc Kleine-Budde '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: Status ImmutableExecutorState::BuildControlFlowInfo(const Graph* g,\n ControlFlowInfo* cf_info) {\n const int num_nodes = g->num_node_ids();\n cf_info->frame_names.resize(num_nodes);\n std::vector parent_nodes;\n parent_nodes.resize(num_nodes);\n std::vector visited;\n visited.resize(num_nodes);\n\n string frame_name;\n std::deque ready;\n\n // Initialize with the root nodes.\n for (Node* n : g->nodes()) {\n if (n->in_edges().empty()) {\n visited[n->id()] = true;\n cf_info->unique_frame_names.insert(frame_name);\n ready.push_back(n);\n }\n }\n\n while (!ready.empty()) {\n Node* curr_node = ready.front();\n int curr_id = curr_node->id();\n ready.pop_front();\n\n Node* parent = nullptr;\n if (IsEnter(curr_node)) {\n // Enter a child frame.\n TF_RETURN_IF_ERROR(\n GetNodeAttr(curr_node->attrs(), \"frame_name\", &frame_name));\n parent = curr_node;\n } else if (IsExit(curr_node)) {\n // Exit to the parent frame.\n parent = parent_nodes[curr_id];\n frame_name = cf_info->frame_names[parent->id()];\n parent = parent_nodes[parent->id()];\n } else {\n parent = parent_nodes[curr_id];\n frame_name = cf_info->frame_names[curr_id];\n }\n\n for (const Edge* out_edge : curr_node->out_edges()) {\n Node* out = out_edge->dst();\n if (IsSink(out)) continue;\n const int out_id = out->id();\n\n // Add to ready queue if not visited.\n bool is_visited = visited[out_id];\n if (!is_visited) {\n ready.push_back(out);\n visited[out_id] = true;\n\n // Process the node 'out'.\n cf_info->frame_names[out_id] = frame_name;\n parent_nodes[out_id] = parent;\n cf_info->unique_frame_names.insert(frame_name);\n }\n }\n }\n\n return Status::OK();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fix a NPE issue in invalid Exit op. Now it will report an error instead of crash.\n\nPiperOrigin-RevId: 404089902\nChange-Id: Ia6ec55445ea70ad045a4d339d354959ad0618f2a'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: STATIC U8 *\nS_reghop4(U8 *s, SSize_t off, const U8* llim, const U8* rlim)\n{\n PERL_ARGS_ASSERT_REGHOP4;\n\n if (off >= 0) {\n while (off-- && s < rlim) {\n /* XXX could check well-formedness here */\n s += UTF8SKIP(s);\n }\n }\n else {\n while (off++ && s > llim) {\n s--;\n if (UTF8_IS_CONTINUED(*s)) {\n while (s > llim && UTF8_IS_CONTINUATION(*s))\n s--;\n }\n /* XXX could check well-formedness here */\n }\n }\n return s; ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'PATCH [perl #123562] Regexp-matching \"hangs\"\n\nThe regex engine got into an infinite loop because of the malformation.\nIt is trying to back-up over a sequence of UTF-8 continuation bytes.\nBut the character just before the sequence should be a start byte. If\nnot, there is a malformation. I added a test to croak if that isn't the\ncase so that it doesn't just infinitely loop. I did this also in the\nsimilar areas of regexec.c.\n\nComments long ago added to the code suggested that we check for\nmalformations in the vicinity of the new tests. But that was never\ndone. These new tests should be good enough to prevent looping, anyway.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: CBINDInstallDlg::RegisterService() {\n\tSC_HANDLE hSCManager;\n\tSC_HANDLE hService;\n\tCString StartName;\n\n\tif (m_accountName == LOCAL_SERVICE)\n\t\tStartName = LOCAL_SERVICE;\n\telse\n\t\tStartName = \".\\\\\" + m_accountName;\n\t/*\n\t * We need to change the service rather than create it\n\t * if the service already exists. Do nothing if we are already\n\t * using that account\n\t */\n\tif (m_serviceExists == TRUE) {\n\t\tif (m_accountUsed == FALSE) {\n\t\t\tUpdateService(StartName);\n\t\t\tSetItemStatus(IDC_REG_SERVICE);\n\t\t\treturn;\n\t\t} else {\n\t\t\tSetItemStatus(IDC_REG_SERVICE);\n\t\t\treturn;\n\t\t}\n\t}\n\n\tSetCurrent(IDS_OPEN_SCM);\n\thSCManager= OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);\n\tif (!hSCManager)\n\t\tthrow(Exception(IDS_ERR_OPEN_SCM, GetErrMessage()));\n\n\tDWORD dwStart = SERVICE_DEMAND_START;\n\tif (m_autoStart)\n\t\tdwStart = SERVICE_AUTO_START;\n\n\tDWORD dwServiceType = SERVICE_WIN32_OWN_PROCESS;\n\n\tCString namedLoc;\n\tnamedLoc.Format(\"%s\\\\bin\\\\named.exe\", m_targetDir);\n\n\tSetCurrent(IDS_CREATE_SERVICE);\n\thService = CreateService(hSCManager, BIND_SERVICE_NAME,\n\t\tBIND_DISPLAY_NAME, SERVICE_ALL_ACCESS, dwServiceType, dwStart,\n\t\tSERVICE_ERROR_NORMAL, namedLoc, NULL, NULL, NULL, StartName,\n\t\tm_accountPassword);\n\n\tif (!hService && GetLastError() != ERROR_SERVICE_EXISTS)\n\t\tthrow(Exception(IDS_ERR_CREATE_SERVICE, GetErrMessage()));\n\n\tif (hService)\n\t\tCloseServiceHandle(hService);\n\n\tif (hSCManager)\n\t\tCloseServiceHandle(hSCManager);\n\n\tSetItemStatus(IDC_REG_SERVICE);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284'], 'message': '[master] quote service registry paths\n\n4532.\t[security]\tThe BIND installer on Windows used an unquoted\n service path, which can enable privilege escalation.\n\t\t\t(CVE-2017-3141) [RT #45229]'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TEST_F(QuantizedConv2DTest, OddPadding) {\n const int stride = 2;\n TF_ASSERT_OK(NodeDefBuilder(\"quantized_conv_op\", \"QuantizedConv2D\")\n .Input(FakeInput(DT_QUINT8))\n .Input(FakeInput(DT_QUINT8))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Attr(\"out_type\", DataTypeToEnum::v())\n .Attr(\"strides\", {1, stride, stride, 1})\n .Attr(\"padding\", \"SAME\")\n .Finalize(node_def()));\n TF_ASSERT_OK(InitOp());\n\n const int depth = 1;\n const int image_width = 4;\n const int image_height = 4;\n const int image_batch_count = 1;\n AddInputFromArray(\n TensorShape({image_batch_count, image_height, image_width, depth}),\n {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16});\n const int filter_size = 3;\n const int filter_count = 1;\n AddInputFromArray(\n TensorShape({filter_size, filter_size, depth, filter_count}),\n {1, 2, 3, 4, 5, 6, 7, 8, 9});\n AddInputFromArray(TensorShape({1}), {0});\n AddInputFromArray(TensorShape({1}), {255.0f});\n AddInputFromArray(TensorShape({1}), {0});\n AddInputFromArray(TensorShape({1}), {255.0f});\n\n TF_ASSERT_OK(RunOpKernel());\n const int expected_width = image_width / stride;\n const int expected_height = (image_height * filter_count) / stride;\n Tensor expected(DT_QINT32, TensorShape({image_batch_count, expected_height,\n expected_width, filter_count}));\n test::FillValues(&expected, {348, 252, 274, 175});\n test::ExpectTensorEqual(expected, *GetOutput(0));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-476'], 'message': 'Fix undefined behavior in QuantizedConv2D\n\nAdded more input validation and tests. Prior to this, we could get\n`nullptr` exceptions when attempting to access 0th elements of 0-sized\ninputs, leading to security vulnerability bugs.\n\nAlso needed to modify `quantized_conv_ops_test.cc` for consistency.\nPreviously the CPU kernel did technically support passing tensors\nof rank larger than 0 for min/max values. However, the XLA kernels do not.\n\nPiperOrigin-RevId: 445518507'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void close_connection(h2o_http2_conn_t *conn)\n{\n conn->state = H2O_HTTP2_CONN_STATE_IS_CLOSING;\n\n if (conn->_write.buf_in_flight != NULL || h2o_timeout_is_linked(&conn->_write.timeout_entry)) {\n /* there is a pending write, let on_write_complete actually close the connection */\n } else {\n close_connection_now(conn);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'h2: use after free on premature connection close #920\n\nlib/http2/connection.c:on_read() calls parse_input(), which might free\n`conn`. It does so in particular if the connection preface isn't\nthe expected one in expect_preface(). `conn` is then used after the free\nin `if (h2o_timeout_is_linked(&conn->_write.timeout_entry)`.\nWe fix this by adding a return value to close_connection that returns a\nnegative value if `conn` has been free'd and can't be used anymore.\n\nCredits for finding the bug to Tim Newsham.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline int ccid_hc_tx_getsockopt(struct ccid *ccid, struct sock *sk,\n\t\t\t\t\tconst int optname, int len,\n\t\t\t\t\tu32 __user *optval, int __user *optlen)\n{\n\tint rc = -ENOPROTOOPT;\n\tif (ccid->ccid_ops->ccid_hc_tx_getsockopt != NULL)\n\t\trc = ccid->ccid_ops->ccid_hc_tx_getsockopt(sk, optname, len,\n\t\t\t\t\t\t optval, optlen);\n\treturn rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'dccp: check ccid before dereferencing\n\nccid_hc_rx_getsockopt() and ccid_hc_tx_getsockopt() might be called with\na NULL ccid pointer leading to a NULL pointer dereference. This could\nlead to a privilege escalation if the attacker is able to map page 0 and\nprepare it with a fake ccid_ops pointer.\n\nSigned-off-by: Mathias Krause \nCc: Gerrit Renker \nCc: stable@vger.kernel.org\nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: nfa_t::nfa_t(const RESpec &spec)\n : max_size(estimate_size(spec.res))\n , size(0)\n , states(new nfa_state_t[max_size])\n , charset(spec.charset)\n , rules(spec.rules)\n , tags(spec.tags)\n , root(NULL)\n , ncores(0)\n{\n const size_t nre = spec.res.size();\n\n if (nre == 0) return;\n\n for (size_t i = 0; i < nre; ++i) {\n rtn_ctx_t ctx = {spec.opts, *this, i};\n\n nfa_state_t *s = &states[size++];\n s->make_fin(i);\n s = re_to_nfa(ctx, spec.res[i], s);\n\n if (root) {\n nfa_state_t *t = &states[size++];\n t->make_alt(i, root, s);\n root = t;\n } else {\n root = s;\n }\n }\n\n // In-degree and topological index are used by POSIX disambiguation;\n // the number of core states is used for both POSIX and leftmost.\n ncores = stats(root);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Limit maximum allowed NFA and DFA size.\n\nInstead of failing with an out of memory exception or crashing with a\nstack overflow, emit an error message and exit. This is a partial fix\nfor bug #394 \"Stack overflow due to recursion in src/dfa/dead_rules.cc\",\nwhere re2c hit stack overflow on a counted repetition regexp with high\nupper bound.\n\nThe patch adds the following limits:\n 1. the number of NFA states\n 2. NFA depth (maximum length of a non-looping path from start to end)\n 3. the number of DFA states\n 3. total DFA size (sum total of all NFA substates in all DFA states)\n\nThere are tests for the first three limits, but not for the DFA size as\nall examples that trigger this behavior take a long time to finish (a\nfew seconds), which increases test run time almost twice.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: vhost_scsi_send_evt(struct vhost_scsi *vs,\n\t\t struct vhost_scsi_tpg *tpg,\n\t\t struct se_lun *lun,\n\t\t u32 event,\n\t\t u32 reason)\n{\n\tstruct vhost_scsi_evt *evt;\n\n\tevt = vhost_scsi_allocate_evt(vs, event, reason);\n\tif (!evt)\n\t\treturn;\n\n\tif (tpg && lun) {\n\t\t/* TODO: share lun setup code with virtio-scsi.ko */\n\t\t/*\n\t\t * Note: evt->event is zeroed when we allocate it and\n\t\t * lun[4-7] need to be zero according to virtio-scsi spec.\n\t\t */\n\t\tevt->event.lun[0] = 0x01;\n\t\tevt->event.lun[1] = tpg->tport_tpgt & 0xFF;\n\t\tif (lun->unpacked_lun >= 256)\n\t\t\tevt->event.lun[2] = lun->unpacked_lun >> 8 | 0x40 ;\n\t\tevt->event.lun[3] = lun->unpacked_lun & 0xFF;\n\t}\n\n\tllist_add(&evt->list, &vs->vs_event_list);\n\tvhost_work_queue(&vs->dev, &vs->vs_event_work);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-119'], 'message': 'vhost/scsi: potential memory corruption\n\nThis code in vhost_scsi_make_tpg() is confusing because we limit \"tpgt\"\nto UINT_MAX but the data type of \"tpg->tport_tpgt\" and that is a u16.\n\nI looked at the context and it turns out that in\nvhost_scsi_set_endpoint(), \"tpg->tport_tpgt\" is used as an offset into\nthe vs_tpg[] array which has VHOST_SCSI_MAX_TARGET (256) elements so\nanything higher than 255 then it is invalid. I have made that the limit\nnow.\n\nIn vhost_scsi_send_evt() we mask away values higher than 255, but now\nthat the limit has changed, we don't need the mask.\n\nSigned-off-by: Dan Carpenter \nSigned-off-by: Nicholas Bellinger '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void ProcessGpsInfo(unsigned char * DirStart, unsigned char * OffsetBase, unsigned ExifLength)\r\n{\r\n int de;\r\n unsigned a;\r\n int NumDirEntries;\r\n\r\n NumDirEntries = Get16u(DirStart);\r\n #define DIR_ENTRY_ADDR(Start, Entry) (Start+2+12*(Entry))\r\n\r\n if (ShowTags){\r\n printf(\"(dir has %d entries)\\n\",NumDirEntries);\r\n }\r\n\r\n ImageInfo.GpsInfoPresent = TRUE;\r\n strcpy(ImageInfo.GpsLat, \"? ?\");\r\n strcpy(ImageInfo.GpsLong, \"? ?\");\r\n ImageInfo.GpsAlt[0] = 0; \r\n\r\n for (de=0;de OffsetBase+ExifLength){\r\n ErrNonfatal(\"GPS info directory goes past end of exif\",0,0);\r\n return;\r\n }\r\n\r\n Tag = Get16u(DirEntry);\r\n Format = Get16u(DirEntry+2);\r\n Components = Get32u(DirEntry+4);\r\n\r\n if (Components > 0x10000){\r\n //Components count too large could cause overflow on subsequent check\r\n ErrNonfatal(\"Bad components count %x\", Components,0);\r\n continue;\r\n }\r\n\r\n if ((Format-1) >= NUM_FORMATS) {\r\n // (-1) catches illegal zero case as unsigned underflows to positive large.\r\n ErrNonfatal(\"Illegal number format %d for Exif gps tag %04x\", Format, Tag);\r\n continue;\r\n }\r\n\r\n ComponentSize = BytesPerFormat[Format];\r\n ByteCount = Components * ComponentSize;\r\n\r\n if (ByteCount > 4){\r\n unsigned OffsetVal;\r\n OffsetVal = Get32u(DirEntry+8);\r\n // If its bigger than 4 bytes, the dir entry contains an offset.\r\n if (OffsetVal > 0x1000000 || OffsetVal+ByteCount > ExifLength){\r\n // Max exif in jpeg is 64k, so any offset bigger than that is bogus.\r\n // Bogus pointer offset and / or bytecount value\r\n ErrNonfatal(\"Illegal value pointer for Exif gps tag %04x\", Tag,0);\r\n continue;\r\n }\r\n ValuePtr = OffsetBase+OffsetVal;\r\n }else{\r\n // 4 bytes or less and value is in the dir entry itself\r\n ValuePtr = DirEntry+8;\r\n }\r\n\r\n switch(Tag){\r\n char FmtString[21];\r\n char TempString[50];\r\n double Values[3];\r\n\r\n case TAG_GPS_LAT_REF:\r\n ImageInfo.GpsLat[0] = ValuePtr[0];\r\n break;\r\n\r\n case TAG_GPS_LONG_REF:\r\n ImageInfo.GpsLong[0] = ValuePtr[0];\r\n break;\r\n\r\n case TAG_GPS_LAT:\r\n case TAG_GPS_LONG:\r\n if (Format != FMT_URATIONAL){\r\n ErrNonfatal(\"Inappropriate format (%d) for Exif GPS coordinates!\", Format, 0);\r\n }\r\n strcpy(FmtString, \"%0.0fd %0.0fm %0.0fs\");\r\n for (a=0;a<3;a++){\r\n int den, digits;\r\n\r\n den = Get32s(ValuePtr+4+a*ComponentSize);\r\n digits = 0;\r\n while (den > 1 && digits <= 6){\r\n den = den / 10;\r\n digits += 1;\r\n }\r\n if (digits > 6) digits = 6;\r\n FmtString[1+a*7] = (char)('2'+digits+(digits ? 1 : 0));\r\n FmtString[3+a*7] = (char)('0'+digits);\r\n\r\n Values[a] = ConvertAnyFormat(ValuePtr+a*ComponentSize, Format);\r\n }\r\r\n\r\n snprintf(TempString, sizeof(TempString), FmtString, Values[0], Values[1], Values[2]);\r\n\r\n if (Tag == TAG_GPS_LAT){\r\n strncpy(ImageInfo.GpsLat+2, TempString, 29);\r\n }else{\r\n strncpy(ImageInfo.GpsLong+2, TempString, 29);\r\n }\r\n break;\r\n\r\n case TAG_GPS_ALT_REF:\r\n ImageInfo.GpsAlt[0] = (char)(ValuePtr[0] ? '-' : ' ');\r\n break;\r\n\r\n case TAG_GPS_ALT:\r\n snprintf(ImageInfo.GpsAlt+1, sizeof(ImageInfo.GpsAlt)-1,\r\n \"%.2fm\", ConvertAnyFormat(ValuePtr, Format));\r\n break;\r\n }\r\n\r\n if (ShowTags){\r\n // Show tag value.\r\n if (Tag < MAX_GPS_TAG){\r\n printf(\" GPS%s =\", GpsTags[Tag]);\r\n }else{\r\n // Show unknown tag\r\n printf(\" Illegal GPS tag %04x=\", Tag);\r\n }\r\n\r\n switch(Format){\r\n case FMT_UNDEFINED:\r\n // Undefined is typically an ascii string.\r\n\r\n case FMT_STRING:\r\n // String arrays printed without function call (different from int arrays)\r\n {\r\n printf(\"\\\"\");\r\n for (a=0;a= 32){\r\n if (ZeroSkipped){\r\n printf(\"?\");\r\n ZeroSkipped = 0;\r\n }\r\n putchar(ValuePtr[a]);\r\n }else{\r\n if (ValuePtr[a] == 0){\r\n ZeroSkipped = 1;\r\n }\r\n }\r\n }\r\n printf(\"\\\"\\n\");\r\n }\r\n break;\r\n\r\n default:\r\n // Handle arrays of numbers later (will there ever be?)\r\n for (a=0;;){\r\n PrintFormatNumber(ValuePtr+a*ComponentSize, Format, ByteCount);\r\n if (++a >= Components) break;\r\n printf(\", \");\r\n }\r\n printf(\"\\n\");\r\n }\r\n }\r\n }\r\n}\r ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'Make pointer range checks more consistent.\n Also twiddle the unused floating point print code (not used in real exif files),\n but fuzz testing hits it. New code is equivalent but doesn't cause bus error (don't understand why, but this is all a very bogus thing anyway, just trying to avoid fuzz testing hits.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: Status ModularFrameDecoder::DecodeGroup(const Rect& rect, BitReader* reader,\n int minShift, int maxShift,\n const ModularStreamId& stream,\n bool zerofill,\n PassesDecoderState* dec_state,\n ImageBundle* output) {\n JXL_DASSERT(stream.kind == ModularStreamId::kModularDC ||\n stream.kind == ModularStreamId::kModularAC);\n const size_t xsize = rect.xsize();\n const size_t ysize = rect.ysize();\n Image gi(xsize, ysize, full_image.bitdepth, 0);\n // start at the first bigger-than-groupsize non-metachannel\n size_t c = full_image.nb_meta_channels;\n for (; c < full_image.channel.size(); c++) {\n Channel& fc = full_image.channel[c];\n if (fc.w > frame_dim.group_dim || fc.h > frame_dim.group_dim) break;\n }\n size_t beginc = c;\n for (; c < full_image.channel.size(); c++) {\n Channel& fc = full_image.channel[c];\n int shift = std::min(fc.hshift, fc.vshift);\n if (shift > maxShift) continue;\n if (shift < minShift) continue;\n Rect r(rect.x0() >> fc.hshift, rect.y0() >> fc.vshift,\n rect.xsize() >> fc.hshift, rect.ysize() >> fc.vshift, fc.w, fc.h);\n if (r.xsize() == 0 || r.ysize() == 0) continue;\n Channel gc(r.xsize(), r.ysize());\n gc.hshift = fc.hshift;\n gc.vshift = fc.vshift;\n gi.channel.emplace_back(std::move(gc));\n }\n if (zerofill) {\n int gic = 0;\n for (c = beginc; c < full_image.channel.size(); c++) {\n Channel& fc = full_image.channel[c];\n int shift = std::min(fc.hshift, fc.vshift);\n if (shift > maxShift) continue;\n if (shift < minShift) continue;\n Rect r(rect.x0() >> fc.hshift, rect.y0() >> fc.vshift,\n rect.xsize() >> fc.hshift, rect.ysize() >> fc.vshift, fc.w, fc.h);\n if (r.xsize() == 0 || r.ysize() == 0) continue;\n for (size_t y = 0; y < r.ysize(); ++y) {\n pixel_type* const JXL_RESTRICT row_out = r.Row(&fc.plane, y);\n memset(row_out, 0, r.xsize() * sizeof(*row_out));\n }\n gic++;\n }\n return true;\n }\n ModularOptions options;\n if (!ModularGenericDecompress(\n reader, gi, /*header=*/nullptr, stream.ID(frame_dim), &options,\n /*undo_transforms=*/-1, &tree, &code, &context_map))\n return JXL_FAILURE(\"Failed to decode modular group\");\n if (minShift == 0) {\n // Undo global transforms that have been pushed to the group level\n for (auto t : global_transform) {\n JXL_RETURN_IF_ERROR(t.Inverse(gi, global_header.wp_header));\n }\n if (!use_full_image) {\n JXL_RETURN_IF_ERROR(ModularImageToDecodedRect(\n gi, dec_state, nullptr, output, rect.Crop(dec_state->decoded)));\n return true;\n }\n }\n int gic = 0;\n for (c = beginc; c < full_image.channel.size(); c++) {\n Channel& fc = full_image.channel[c];\n int shift = std::min(fc.hshift, fc.vshift);\n if (shift > maxShift) continue;\n if (shift < minShift) continue;\n Rect r(rect.x0() >> fc.hshift, rect.y0() >> fc.vshift,\n rect.xsize() >> fc.hshift, rect.ysize() >> fc.vshift, fc.w, fc.h);\n if (r.xsize() == 0 || r.ysize() == 0) continue;\n CopyImageTo(/*rect_from=*/Rect(0, 0, r.xsize(), r.ysize()),\n /*from=*/gi.channel[gic].plane,\n /*rect_to=*/r, /*to=*/&fc.plane);\n gic++;\n }\n return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'fix use_full_image==false case (#365)\n\nSome fixes to the case where the full modular image is skipped:\r\n\r\n- don't assume that everything happens at the modular AC group level (minShift==0), there can also be upsampling causing channels to have nonzero shift even when there's no Squeeze\r\n- for partial decodes (when zerofill is true), don't try to fill the full image when it's not used. Instead initialize the decoded image with zeroes and skip the decoding.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: QueueHandle_t xQueueGenericCreate( const UBaseType_t uxQueueLength,\r\n const UBaseType_t uxItemSize,\r\n const uint8_t ucQueueType )\r\n {\r\n Queue_t * pxNewQueue;\r\n size_t xQueueSizeInBytes;\r\n uint8_t * pucQueueStorage;\r\n\r\n configASSERT( uxQueueLength > ( UBaseType_t ) 0 );\r\n\r\n /* Allocate enough space to hold the maximum number of items that\r\n * can be in the queue at any time. It is valid for uxItemSize to be\r\n * zero in the case the queue is used as a semaphore. */\r\n xQueueSizeInBytes = ( size_t ) ( uxQueueLength * uxItemSize ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */\r\n\r\n /* Check for multiplication overflow. */\r\n configASSERT( ( uxItemSize == 0 ) || ( uxQueueLength == ( xQueueSizeInBytes / uxItemSize ) ) );\r\n\r\n /* Allocate the queue and storage area. Justification for MISRA\r\n * deviation as follows: pvPortMalloc() always ensures returned memory\r\n * blocks are aligned per the requirements of the MCU stack. In this case\r\n * pvPortMalloc() must return a pointer that is guaranteed to meet the\r\n * alignment requirements of the Queue_t structure - which in this case\r\n * is an int8_t *. Therefore, whenever the stack alignment requirements\r\n * are greater than or equal to the pointer to char requirements the cast\r\n * is safe. In other cases alignment requirements are not strict (one or\r\n * two bytes). */\r\n pxNewQueue = ( Queue_t * ) pvPortMalloc( sizeof( Queue_t ) + xQueueSizeInBytes ); /*lint !e9087 !e9079 see comment above. */\r\n\r\n if( pxNewQueue != NULL )\r\n {\r\n /* Jump past the queue structure to find the location of the queue\r\n * storage area. */\r\n pucQueueStorage = ( uint8_t * ) pxNewQueue;\r\n pucQueueStorage += sizeof( Queue_t ); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */\r\n\r\n #if ( configSUPPORT_STATIC_ALLOCATION == 1 )\r\n {\r\n /* Queues can be created either statically or dynamically, so\r\n * note this task was created dynamically in case it is later\r\n * deleted. */\r\n pxNewQueue->ucStaticallyAllocated = pdFALSE;\r\n }\r\n #endif /* configSUPPORT_STATIC_ALLOCATION */\r\n\r\n prvInitialiseNewQueue( uxQueueLength, uxItemSize, pucQueueStorage, ucQueueType, pxNewQueue );\r\n }\r\n else\r\n {\r\n traceQUEUE_CREATE_FAILED( ucQueueType );\r\n mtCOVERAGE_TEST_MARKER();\r\n }\r\n\r\n return pxNewQueue;\r\n }\r ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-190'], 'message': 'add assert for addition overflow on queue creation (#225)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void Compute(OpKernelContext* context) override {\n const Tensor& image = context->input(0);\n OP_REQUIRES(context, image.dims() == 3,\n errors::InvalidArgument(\"image must be 3-dimensional\",\n image.shape().DebugString()));\n OP_REQUIRES(\n context,\n FastBoundsCheck(image.NumElements(), std::numeric_limits::max()),\n errors::InvalidArgument(\"image cannot have >= int32 max elements\"));\n const int32 height = static_cast(image.dim_size(0));\n const int32 width = static_cast(image.dim_size(1));\n const int32 channels = static_cast(image.dim_size(2));\n\n // In some cases, we pass width*channels*2 to png.\n const int32 max_row_width = std::numeric_limits::max() / 2;\n\n OP_REQUIRES(context, FastBoundsCheck(width * channels, max_row_width),\n errors::InvalidArgument(\"image too wide to encode\"));\n\n OP_REQUIRES(context, channels >= 1 && channels <= 4,\n errors::InvalidArgument(\n \"image must have 1, 2, 3, or 4 channels, got \", channels));\n\n // Encode image to png string\n Tensor* output = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(0, TensorShape({}), &output));\n if (desired_channel_bits_ == 8) {\n OP_REQUIRES(context,\n png::WriteImageToBuffer(\n image.flat().data(), width, height,\n width * channels, channels, desired_channel_bits_,\n compression_, &output->scalar()(), nullptr),\n errors::Internal(\"PNG encoding failed\"));\n } else {\n OP_REQUIRES(context,\n png::WriteImageToBuffer(\n image.flat().data(), width, height,\n width * channels * 2, channels, desired_channel_bits_,\n compression_, &output->scalar()(), nullptr),\n errors::Internal(\"PNG encoding failed\"));\n }\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-754', 'CWE-787'], 'message': 'Fix null CHECK issue with `tf.raw_ops.EncodePng`.\n\nPiperOrigin-RevId: 369717714\nChange-Id: I24136cd99c20b8466671f4f93b670ef6f6dd1250'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: boost::optional SaplingOutgoingPlaintext::decrypt(\n const SaplingOutCiphertext &ciphertext,\n const uint256& ovk,\n const uint256& cv,\n const uint256& cm,\n const uint256& epk\n)\n{\n auto pt = AttemptSaplingOutDecryption(ciphertext, ovk, cv, cm, epk);\n if (!pt) {\n return boost::none;\n }\n\n // Deserialize from the plaintext\n CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n ss << pt.get();\n\n SaplingOutgoingPlaintext ret;\n ss >> ret;\n\n assert(ss.size() == 0);\n\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-755', 'CWE-787'], 'message': 'Ignore exceptions when deserializing note plaintexts'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int nci_extract_activation_params_iso_dep(struct nci_dev *ndev,\n\t\t\tstruct nci_rf_intf_activated_ntf *ntf, __u8 *data)\n{\n\tstruct activation_params_nfca_poll_iso_dep *nfca_poll;\n\tstruct activation_params_nfcb_poll_iso_dep *nfcb_poll;\n\n\tswitch (ntf->activation_rf_tech_and_mode) {\n\tcase NCI_NFC_A_PASSIVE_POLL_MODE:\n\t\tnfca_poll = &ntf->activation_params.nfca_poll_iso_dep;\n\t\tnfca_poll->rats_res_len = *data++;\n\t\tpr_debug(\"rats_res_len %d\\n\", nfca_poll->rats_res_len);\n\t\tif (nfca_poll->rats_res_len > 0) {\n\t\t\tmemcpy(nfca_poll->rats_res,\n\t\t\t data, nfca_poll->rats_res_len);\n\t\t}\n\t\tbreak;\n\n\tcase NCI_NFC_B_PASSIVE_POLL_MODE:\n\t\tnfcb_poll = &ntf->activation_params.nfcb_poll_iso_dep;\n\t\tnfcb_poll->attrib_res_len = *data++;\n\t\tpr_debug(\"attrib_res_len %d\\n\", nfcb_poll->attrib_res_len);\n\t\tif (nfcb_poll->attrib_res_len > 0) {\n\t\t\tmemcpy(nfcb_poll->attrib_res,\n\t\t\t data, nfcb_poll->attrib_res_len);\n\t\t}\n\t\tbreak;\n\n\tdefault:\n\t\tpr_err(\"unsupported activation_rf_tech_and_mode 0x%x\\n\",\n\t\t ntf->activation_rf_tech_and_mode);\n\t\treturn NCI_STATUS_RF_PROTOCOL_ERROR;\n\t}\n\n\treturn NCI_STATUS_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'NFC: Prevent multiple buffer overflows in NCI\n\nFix multiple remotely-exploitable stack-based buffer overflows due to\nthe NCI code pulling length fields directly from incoming frames and\ncopying too much data into statically-sized arrays.\n\nSigned-off-by: Dan Rosenberg \nCc: stable@kernel.org\nCc: security@kernel.org\nCc: Lauro Ramos Venancio \nCc: Aloisio Almeida Jr \nCc: Samuel Ortiz \nCc: David S. Miller \nAcked-by: Ilan Elias \nSigned-off-by: Samuel Ortiz '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: wf_cliprdr_server_file_contents_request(CliprdrClientContext* context,\n const CLIPRDR_FILE_CONTENTS_REQUEST* fileContentsRequest)\n{\n\tDWORD uSize = 0;\n\tBYTE* pData = NULL;\n\tHRESULT hRet = S_OK;\n\tFORMATETC vFormatEtc;\n\tLPDATAOBJECT pDataObj = NULL;\n\tSTGMEDIUM vStgMedium;\n\tBOOL bIsStreamFile = TRUE;\n\tstatic LPSTREAM pStreamStc = NULL;\n\tstatic UINT32 uStreamIdStc = 0;\n\twfClipboard* clipboard;\n\tUINT rc = ERROR_INTERNAL_ERROR;\n\tUINT sRc;\n\tUINT32 cbRequested;\n\n\tif (!context || !fileContentsRequest)\n\t\treturn ERROR_INTERNAL_ERROR;\n\n\tclipboard = (wfClipboard*)context->custom;\n\n\tif (!clipboard)\n\t\treturn ERROR_INTERNAL_ERROR;\n\n\tcbRequested = fileContentsRequest->cbRequested;\n\tif (fileContentsRequest->dwFlags == FILECONTENTS_SIZE)\n\t\tcbRequested = sizeof(UINT64);\n\n\tpData = (BYTE*)calloc(1, cbRequested);\n\n\tif (!pData)\n\t\tgoto error;\n\n\thRet = OleGetClipboard(&pDataObj);\n\n\tif (FAILED(hRet))\n\t{\n\t\tWLog_ERR(TAG, \"filecontents: get ole clipboard failed.\");\n\t\tgoto error;\n\t}\n\n\tZeroMemory(&vFormatEtc, sizeof(FORMATETC));\n\tZeroMemory(&vStgMedium, sizeof(STGMEDIUM));\n\tvFormatEtc.cfFormat = RegisterClipboardFormat(CFSTR_FILECONTENTS);\n\tvFormatEtc.tymed = TYMED_ISTREAM;\n\tvFormatEtc.dwAspect = 1;\n\tvFormatEtc.lindex = fileContentsRequest->listIndex;\n\tvFormatEtc.ptd = NULL;\n\n\tif ((uStreamIdStc != fileContentsRequest->streamId) || !pStreamStc)\n\t{\n\t\tLPENUMFORMATETC pEnumFormatEtc;\n\t\tULONG CeltFetched;\n\t\tFORMATETC vFormatEtc2;\n\n\t\tif (pStreamStc)\n\t\t{\n\t\t\tIStream_Release(pStreamStc);\n\t\t\tpStreamStc = NULL;\n\t\t}\n\n\t\tbIsStreamFile = FALSE;\n\t\thRet = IDataObject_EnumFormatEtc(pDataObj, DATADIR_GET, &pEnumFormatEtc);\n\n\t\tif (hRet == S_OK)\n\t\t{\n\t\t\tdo\n\t\t\t{\n\t\t\t\thRet = IEnumFORMATETC_Next(pEnumFormatEtc, 1, &vFormatEtc2, &CeltFetched);\n\n\t\t\t\tif (hRet == S_OK)\n\t\t\t\t{\n\t\t\t\t\tif (vFormatEtc2.cfFormat == RegisterClipboardFormat(CFSTR_FILECONTENTS))\n\t\t\t\t\t{\n\t\t\t\t\t\thRet = IDataObject_GetData(pDataObj, &vFormatEtc, &vStgMedium);\n\n\t\t\t\t\t\tif (hRet == S_OK)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpStreamStc = vStgMedium.pstm;\n\t\t\t\t\t\t\tuStreamIdStc = fileContentsRequest->streamId;\n\t\t\t\t\t\t\tbIsStreamFile = TRUE;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} while (hRet == S_OK);\n\t\t}\n\t}\n\n\tif (bIsStreamFile == TRUE)\n\t{\n\t\tif (fileContentsRequest->dwFlags == FILECONTENTS_SIZE)\n\t\t{\n\t\t\tSTATSTG vStatStg;\n\t\t\tZeroMemory(&vStatStg, sizeof(STATSTG));\n\t\t\thRet = IStream_Stat(pStreamStc, &vStatStg, STATFLAG_NONAME);\n\n\t\t\tif (hRet == S_OK)\n\t\t\t{\n\t\t\t\t*((UINT32*)&pData[0]) = vStatStg.cbSize.LowPart;\n\t\t\t\t*((UINT32*)&pData[4]) = vStatStg.cbSize.HighPart;\n\t\t\t\tuSize = cbRequested;\n\t\t\t}\n\t\t}\n\t\telse if (fileContentsRequest->dwFlags == FILECONTENTS_RANGE)\n\t\t{\n\t\t\tLARGE_INTEGER dlibMove;\n\t\t\tULARGE_INTEGER dlibNewPosition;\n\t\t\tdlibMove.HighPart = fileContentsRequest->nPositionHigh;\n\t\t\tdlibMove.LowPart = fileContentsRequest->nPositionLow;\n\t\t\thRet = IStream_Seek(pStreamStc, dlibMove, STREAM_SEEK_SET, &dlibNewPosition);\n\n\t\t\tif (SUCCEEDED(hRet))\n\t\t\t\thRet = IStream_Read(pStreamStc, pData, cbRequested, (PULONG)&uSize);\n\t\t}\n\t}\n\telse\n\t{\n\t\tif (fileContentsRequest->dwFlags == FILECONTENTS_SIZE)\n\t\t{\n\t\t\t*((UINT32*)&pData[0]) =\n\t\t\t clipboard->fileDescriptor[fileContentsRequest->listIndex]->nFileSizeLow;\n\t\t\t*((UINT32*)&pData[4]) =\n\t\t\t clipboard->fileDescriptor[fileContentsRequest->listIndex]->nFileSizeHigh;\n\t\t\tuSize = cbRequested;\n\t\t}\n\t\telse if (fileContentsRequest->dwFlags == FILECONTENTS_RANGE)\n\t\t{\n\t\t\tBOOL bRet;\n\t\t\tbRet = wf_cliprdr_get_file_contents(\n\t\t\t clipboard->file_names[fileContentsRequest->listIndex], pData,\n\t\t\t fileContentsRequest->nPositionLow, fileContentsRequest->nPositionHigh, cbRequested,\n\t\t\t &uSize);\n\n\t\t\tif (bRet == FALSE)\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"get file contents failed.\");\n\t\t\t\tuSize = 0;\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t}\n\t}\n\n\trc = CHANNEL_RC_OK;\nerror:\n\n\tif (pDataObj)\n\t\tIDataObject_Release(pDataObj);\n\n\tif (uSize == 0)\n\t{\n\t\tfree(pData);\n\t\tpData = NULL;\n\t}\n\n\tsRc =\n\t cliprdr_send_response_filecontents(clipboard, fileContentsRequest->streamId, uSize, pData);\n\tfree(pData);\n\n\tif (sRc != CHANNEL_RC_OK)\n\t\treturn sRc;\n\n\treturn rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fixed missing input checks for file contents request\n\nreported by Valentino Ricotta (Thalium)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TPML_CC_Unmarshal(TPML_CC *target, BYTE **buffer, INT32 *size)\n{\n TPM_RC rc = TPM_RC_SUCCESS;\n \n UINT32 i;\n if (rc == TPM_RC_SUCCESS) {\n\trc = UINT32_Unmarshal(&target->count, buffer, size);\n }\n if (rc == TPM_RC_SUCCESS) {\n\tif (target->count > MAX_CAP_CC) {\n\t rc = TPM_RC_SIZE;\n\t}\n }\n for (i = 0 ; (rc == TPM_RC_SUCCESS) && (i < target->count) ; i++) {\n\trc = TPM_CC_Unmarshal(&target->commandCodes[i], buffer, size);\n }\n return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Reset TPM2B buffer sizes after test fails for valid buffer size\n\nReset the buffer size indicator in a TPM2B type of buffer after it failed\nthe test for the maximum buffer size it allows. This prevents having bad\nbuffer sizes in memory that can come to haunt us when writing the volatile\nstate for example.\n\nSigned-off-by: Stefan Berger '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TPML_TAGGED_PCR_PROPERTY_Unmarshal(TPML_TAGGED_PCR_PROPERTY *target, BYTE **buffer, INT32 *size)\n{\n TPM_RC rc = TPM_RC_SUCCESS;\n\n UINT32 i;\n if (rc == TPM_RC_SUCCESS) {\n\trc = UINT32_Unmarshal(&target->count, buffer, size);\n }\n if (rc == TPM_RC_SUCCESS) {\n\tif (target->count > MAX_PCR_PROPERTIES) {\n\t rc = TPM_RC_SIZE;\n\t}\n }\n for (i = 0 ; (rc == TPM_RC_SUCCESS) && (i < target->count) ; i++) {\n\trc = TPMS_TAGGED_PCR_SELECT_Unmarshal(&target->pcrProperty[i], buffer, size);\n }\n return rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Reset TPM2B buffer sizes after test fails for valid buffer size\n\nReset the buffer size indicator in a TPM2B type of buffer after it failed\nthe test for the maximum buffer size it allows. This prevents having bad\nbuffer sizes in memory that can come to haunt us when writing the volatile\nstate for example.\n\nSigned-off-by: Stefan Berger '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static __u8 *sp_report_fixup(struct hid_device *hdev, __u8 *rdesc,\n\t\tunsigned int *rsize)\n{\n\tif (*rsize >= 107 && rdesc[104] == 0x26 && rdesc[105] == 0x80 &&\n\t\t\trdesc[106] == 0x03) {\n\t\thid_info(hdev, \"fixing up Sunplus Wireless Desktop report descriptor\\n\");\n\t\trdesc[105] = rdesc[110] = 0x03;\n\t\trdesc[106] = rdesc[111] = 0x21;\n\t}\n\treturn rdesc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'HID: fix a couple of off-by-ones\n\nThere are a few very theoretical off-by-one bugs in report descriptor size\nchecking when performing a pre-parsing fixup. Fix those.\n\nCc: stable@vger.kernel.org\nReported-by: Ben Hawkes \nReviewed-by: Benjamin Tissoires \nSigned-off-by: Jiri Kosina '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int read_fragment_table(long long *directory_table_end)\n{\n\tint res, i;\n\tint bytes = SQUASHFS_FRAGMENT_BYTES(sBlk.s.fragments);\n\tint indexes = SQUASHFS_FRAGMENT_INDEXES(sBlk.s.fragments);\n\tlong long fragment_table_index[indexes];\n\n\tTRACE(\"read_fragment_table: %d fragments, reading %d fragment indexes \"\n\t\t\"from 0x%llx\\n\", sBlk.s.fragments, indexes,\n\t\tsBlk.s.fragment_table_start);\n\n\tif(sBlk.s.fragments == 0) {\n\t\t*directory_table_end = sBlk.s.fragment_table_start;\n\t\treturn TRUE;\n\t}\n\n\tfragment_table = malloc(bytes);\n\tif(fragment_table == NULL)\n\t\tEXIT_UNSQUASH(\"read_fragment_table: failed to allocate \"\n\t\t\t\"fragment table\\n\");\n\n\tres = read_fs_bytes(fd, sBlk.s.fragment_table_start,\n\t\tSQUASHFS_FRAGMENT_INDEX_BYTES(sBlk.s.fragments),\n\t\tfragment_table_index);\n\tif(res == FALSE) {\n\t\tERROR(\"read_fragment_table: failed to read fragment table \"\n\t\t\t\"index\\n\");\n\t\treturn FALSE;\n\t}\n\tSQUASHFS_INSWAP_FRAGMENT_INDEXES(fragment_table_index, indexes);\n\n\tfor(i = 0; i < indexes; i++) {\n\t\tint expected = (i + 1) != indexes ? SQUASHFS_METADATA_SIZE :\n\t\t\t\t\tbytes & (SQUASHFS_METADATA_SIZE - 1);\n\t\tint length = read_block(fd, fragment_table_index[i], NULL,\n\t\t\texpected, ((char *) fragment_table) + (i *\n\t\t\tSQUASHFS_METADATA_SIZE));\n\t\tTRACE(\"Read fragment table block %d, from 0x%llx, length %d\\n\",\n\t\t\ti, fragment_table_index[i], length);\n\t\tif(length == FALSE) {\n\t\t\tERROR(\"read_fragment_table: failed to read fragment \"\n\t\t\t\t\"table index\\n\");\n\t\t\treturn FALSE;\n\t\t}\n\t}\n\n\tfor(i = 0; i < sBlk.s.fragments; i++) \n\t\tSQUASHFS_INSWAP_FRAGMENT_ENTRY(&fragment_table[i]);\n\n\t*directory_table_end = fragment_table_index[0];\n\treturn TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-190'], 'message': 'unsquashfs-4: Add more sanity checks + fix CVE-2015-4645/6\n\nAdd more filesystem table sanity checks to Unsquashfs-4 and\nalso properly fix CVE-2015-4645 and CVE-2015-4646.\n\nThe CVEs were raised due to Unsquashfs having variable\noveflow and stack overflow in a number of vulnerable\nfunctions.\n\nThe suggested patch only \"fixed\" one such function and fixed\nit badly, and so it was buggy and introduced extra bugs!\n\nThe suggested patch was not only buggy, but, it used the\nessentially wrong approach too. It was \"fixing\" the\nsymptom but not the cause. The symptom is wrong values\ncausing overflow, the cause is filesystem corruption.\nThis corruption should be detected and the filesystem\nrejected *before* trying to allocate memory.\n\nThis patch applies the following fixes:\n\n1. The filesystem super-block tables are checked, and the values\n must match across the filesystem.\n\n This will trap corrupted filesystems created by Mksquashfs.\n\n2. The maximum (theorectical) size the filesystem tables could grow\n to, were analysed, and some variables were increased from int to\n long long.\n\n This analysis has been added as comments.\n\n3. Stack allocation was removed, and a shared buffer (which is\n checked and increased as necessary) is used to read the\n table indexes.\n\nSigned-off-by: Phillip Lougher '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: icmp6_nodeinfo_print(netdissect_options *ndo, u_int icmp6len, const u_char *bp, const u_char *ep)\n{\n\tconst struct icmp6_nodeinfo *ni6;\n\tconst struct icmp6_hdr *dp;\n\tconst u_char *cp;\n\tsize_t siz, i;\n\tint needcomma;\n\n\tif (ep < bp)\n\t\treturn;\n\tdp = (const struct icmp6_hdr *)bp;\n\tni6 = (const struct icmp6_nodeinfo *)bp;\n\tsiz = ep - bp;\n\n\tswitch (ni6->ni_type) {\n\tcase ICMP6_NI_QUERY:\n\t\tif (siz == sizeof(*dp) + 4) {\n\t\t\t/* KAME who-are-you */\n\t\t\tND_PRINT((ndo,\" who-are-you request\"));\n\t\t\tbreak;\n\t\t}\n\t\tND_PRINT((ndo,\" node information query\"));\n\n\t\tND_TCHECK2(*dp, sizeof(*ni6));\n\t\tni6 = (const struct icmp6_nodeinfo *)dp;\n\t\tND_PRINT((ndo,\" (\"));\t/*)*/\n\t\tswitch (EXTRACT_16BITS(&ni6->ni_qtype)) {\n\t\tcase NI_QTYPE_NOOP:\n\t\t\tND_PRINT((ndo,\"noop\"));\n\t\t\tbreak;\n\t\tcase NI_QTYPE_SUPTYPES:\n\t\t\tND_PRINT((ndo,\"supported qtypes\"));\n\t\t\ti = EXTRACT_16BITS(&ni6->ni_flags);\n\t\t\tif (i)\n\t\t\t\tND_PRINT((ndo,\" [%s]\", (i & 0x01) ? \"C\" : \"\"));\n\t\t\tbreak;\n\t\tcase NI_QTYPE_FQDN:\n\t\t\tND_PRINT((ndo,\"DNS name\"));\n\t\t\tbreak;\n\t\tcase NI_QTYPE_NODEADDR:\n\t\t\tND_PRINT((ndo,\"node addresses\"));\n\t\t\ti = ni6->ni_flags;\n\t\t\tif (!i)\n\t\t\t\tbreak;\n\t\t\t/* NI_NODEADDR_FLAG_TRUNCATE undefined for query */\n\t\t\tND_PRINT((ndo,\" [%s%s%s%s%s%s]\",\n\t\t\t (i & NI_NODEADDR_FLAG_ANYCAST) ? \"a\" : \"\",\n\t\t\t (i & NI_NODEADDR_FLAG_GLOBAL) ? \"G\" : \"\",\n\t\t\t (i & NI_NODEADDR_FLAG_SITELOCAL) ? \"S\" : \"\",\n\t\t\t (i & NI_NODEADDR_FLAG_LINKLOCAL) ? \"L\" : \"\",\n\t\t\t (i & NI_NODEADDR_FLAG_COMPAT) ? \"C\" : \"\",\n\t\t\t (i & NI_NODEADDR_FLAG_ALL) ? \"A\" : \"\"));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tND_PRINT((ndo,\"unknown\"));\n\t\t\tbreak;\n\t\t}\n\n\t\tif (ni6->ni_qtype == NI_QTYPE_NOOP ||\n\t\t ni6->ni_qtype == NI_QTYPE_SUPTYPES) {\n\t\t\tif (siz != sizeof(*ni6))\n\t\t\t\tif (ndo->ndo_vflag)\n\t\t\t\t\tND_PRINT((ndo,\", invalid len\"));\n\t\t\t/*(*/\n\t\t\tND_PRINT((ndo,\")\"));\n\t\t\tbreak;\n\t\t}\n\n\n\t\t/* XXX backward compat, icmp-name-lookup-03 */\n\t\tif (siz == sizeof(*ni6)) {\n\t\t\tND_PRINT((ndo,\", 03 draft\"));\n\t\t\t/*(*/\n\t\t\tND_PRINT((ndo,\")\"));\n\t\t\tbreak;\n\t\t}\n\n\t\tswitch (ni6->ni_code) {\n\t\tcase ICMP6_NI_SUBJ_IPV6:\n\t\t\tif (!ND_TTEST2(*dp,\n\t\t\t sizeof(*ni6) + sizeof(struct in6_addr)))\n\t\t\t\tbreak;\n\t\t\tif (siz != sizeof(*ni6) + sizeof(struct in6_addr)) {\n\t\t\t\tif (ndo->ndo_vflag)\n\t\t\t\t\tND_PRINT((ndo,\", invalid subject len\"));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tND_PRINT((ndo,\", subject=%s\",\n ip6addr_string(ndo, ni6 + 1)));\n\t\t\tbreak;\n\t\tcase ICMP6_NI_SUBJ_FQDN:\n\t\t\tND_PRINT((ndo,\", subject=DNS name\"));\n\t\t\tcp = (const u_char *)(ni6 + 1);\n\t\t\tif (cp[0] == ep - cp - 1) {\n\t\t\t\t/* icmp-name-lookup-03, pascal string */\n\t\t\t\tif (ndo->ndo_vflag)\n\t\t\t\t\tND_PRINT((ndo,\", 03 draft\"));\n\t\t\t\tcp++;\n\t\t\t\tND_PRINT((ndo,\", \\\"\"));\n\t\t\t\twhile (cp < ep) {\n\t\t\t\t\tsafeputchar(ndo, *cp);\n\t\t\t\t\tcp++;\n\t\t\t\t}\n\t\t\t\tND_PRINT((ndo,\"\\\"\"));\n\t\t\t} else\n\t\t\t\tdnsname_print(ndo, cp, ep);\n\t\t\tbreak;\n\t\tcase ICMP6_NI_SUBJ_IPV4:\n\t\t\tif (!ND_TTEST2(*dp, sizeof(*ni6) + sizeof(struct in_addr)))\n\t\t\t\tbreak;\n\t\t\tif (siz != sizeof(*ni6) + sizeof(struct in_addr)) {\n\t\t\t\tif (ndo->ndo_vflag)\n\t\t\t\t\tND_PRINT((ndo,\", invalid subject len\"));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tND_PRINT((ndo,\", subject=%s\",\n ipaddr_string(ndo, ni6 + 1)));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tND_PRINT((ndo,\", unknown subject\"));\n\t\t\tbreak;\n\t\t}\n\n\t\t/*(*/\n\t\tND_PRINT((ndo,\")\"));\n\t\tbreak;\n\n\tcase ICMP6_NI_REPLY:\n\t\tif (icmp6len > siz) {\n\t\t\tND_PRINT((ndo,\"[|icmp6: node information reply]\"));\n\t\t\tbreak;\n\t\t}\n\n\t\tneedcomma = 0;\n\n\t\tni6 = (const struct icmp6_nodeinfo *)dp;\n\t\tND_PRINT((ndo,\" node information reply\"));\n\t\tND_PRINT((ndo,\" (\"));\t/*)*/\n\t\tswitch (ni6->ni_code) {\n\t\tcase ICMP6_NI_SUCCESS:\n\t\t\tif (ndo->ndo_vflag) {\n\t\t\t\tND_PRINT((ndo,\"success\"));\n\t\t\t\tneedcomma++;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase ICMP6_NI_REFUSED:\n\t\t\tND_PRINT((ndo,\"refused\"));\n\t\t\tneedcomma++;\n\t\t\tif (siz != sizeof(*ni6))\n\t\t\t\tif (ndo->ndo_vflag)\n\t\t\t\t\tND_PRINT((ndo,\", invalid length\"));\n\t\t\tbreak;\n\t\tcase ICMP6_NI_UNKNOWN:\n\t\t\tND_PRINT((ndo,\"unknown\"));\n\t\t\tneedcomma++;\n\t\t\tif (siz != sizeof(*ni6))\n\t\t\t\tif (ndo->ndo_vflag)\n\t\t\t\t\tND_PRINT((ndo,\", invalid length\"));\n\t\t\tbreak;\n\t\t}\n\n\t\tif (ni6->ni_code != ICMP6_NI_SUCCESS) {\n\t\t\t/*(*/\n\t\t\tND_PRINT((ndo,\")\"));\n\t\t\tbreak;\n\t\t}\n\n\t\tswitch (EXTRACT_16BITS(&ni6->ni_qtype)) {\n\t\tcase NI_QTYPE_NOOP:\n\t\t\tif (needcomma)\n\t\t\t\tND_PRINT((ndo,\", \"));\n\t\t\tND_PRINT((ndo,\"noop\"));\n\t\t\tif (siz != sizeof(*ni6))\n\t\t\t\tif (ndo->ndo_vflag)\n\t\t\t\t\tND_PRINT((ndo,\", invalid length\"));\n\t\t\tbreak;\n\t\tcase NI_QTYPE_SUPTYPES:\n\t\t\tif (needcomma)\n\t\t\t\tND_PRINT((ndo,\", \"));\n\t\t\tND_PRINT((ndo,\"supported qtypes\"));\n\t\t\ti = EXTRACT_16BITS(&ni6->ni_flags);\n\t\t\tif (i)\n\t\t\t\tND_PRINT((ndo,\" [%s]\", (i & 0x01) ? \"C\" : \"\"));\n\t\t\tbreak;\n\t\tcase NI_QTYPE_FQDN:\n\t\t\tif (needcomma)\n\t\t\t\tND_PRINT((ndo,\", \"));\n\t\t\tND_PRINT((ndo,\"DNS name\"));\n\t\t\tcp = (const u_char *)(ni6 + 1) + 4;\n\t\t\tif (cp[0] == ep - cp - 1) {\n\t\t\t\t/* icmp-name-lookup-03, pascal string */\n\t\t\t\tif (ndo->ndo_vflag)\n\t\t\t\t\tND_PRINT((ndo,\", 03 draft\"));\n\t\t\t\tcp++;\n\t\t\t\tND_PRINT((ndo,\", \\\"\"));\n\t\t\t\twhile (cp < ep) {\n\t\t\t\t\tsafeputchar(ndo, *cp);\n\t\t\t\t\tcp++;\n\t\t\t\t}\n\t\t\t\tND_PRINT((ndo,\"\\\"\"));\n\t\t\t} else\n\t\t\t\tdnsname_print(ndo, cp, ep);\n\t\t\tif ((EXTRACT_16BITS(&ni6->ni_flags) & 0x01) != 0)\n\t\t\t\tND_PRINT((ndo,\" [TTL=%u]\", EXTRACT_32BITS(ni6 + 1)));\n\t\t\tbreak;\n\t\tcase NI_QTYPE_NODEADDR:\n\t\t\tif (needcomma)\n\t\t\t\tND_PRINT((ndo,\", \"));\n\t\t\tND_PRINT((ndo,\"node addresses\"));\n\t\t\ti = sizeof(*ni6);\n\t\t\twhile (i < siz) {\n\t\t\t\tif (i + sizeof(struct in6_addr) + sizeof(int32_t) > siz)\n\t\t\t\t\tbreak;\n\t\t\t\tND_PRINT((ndo,\" %s\", ip6addr_string(ndo, bp + i)));\n\t\t\t\ti += sizeof(struct in6_addr);\n\t\t\t\tND_PRINT((ndo,\"(%d)\", (int32_t)EXTRACT_32BITS(bp + i)));\n\t\t\t\ti += sizeof(int32_t);\n\t\t\t}\n\t\t\ti = ni6->ni_flags;\n\t\t\tif (!i)\n\t\t\t\tbreak;\n\t\t\tND_PRINT((ndo,\" [%s%s%s%s%s%s%s]\",\n (i & NI_NODEADDR_FLAG_ANYCAST) ? \"a\" : \"\",\n (i & NI_NODEADDR_FLAG_GLOBAL) ? \"G\" : \"\",\n (i & NI_NODEADDR_FLAG_SITELOCAL) ? \"S\" : \"\",\n (i & NI_NODEADDR_FLAG_LINKLOCAL) ? \"L\" : \"\",\n (i & NI_NODEADDR_FLAG_COMPAT) ? \"C\" : \"\",\n (i & NI_NODEADDR_FLAG_ALL) ? \"A\" : \"\",\n (i & NI_NODEADDR_FLAG_TRUNCATE) ? \"T\" : \"\"));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (needcomma)\n\t\t\t\tND_PRINT((ndo,\", \"));\n\t\t\tND_PRINT((ndo,\"unknown\"));\n\t\t\tbreak;\n\t\t}\n\n\t\t/*(*/\n\t\tND_PRINT((ndo,\")\"));\n\t\tbreak;\n\t}\n\treturn;\n\ntrunc:\n\tND_PRINT((ndo, \"[|icmp6]\"));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'CVE-2017-13041/ICMP6: Add more bounds checks.\n\nThis fixes a buffer over-read discovered by Kim Gwan Yeong.\n\nAdd a test using the capture file supplied by the reporter(s).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void Compute(OpKernelContext *ctx) override {\n const Tensor *indices_t, *values_t, *shape_t, *reduction_axes_t;\n OP_REQUIRES_OK(ctx, ctx->input(\"input_indices\", &indices_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"input_values\", &values_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"input_shape\", &shape_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"reduction_axes\", &reduction_axes_t));\n\n OP_REQUIRES_OK(ctx, ValidateInputs(shape_t, reduction_axes_t));\n\n // TODO(zongheng): we will call Reorder() below, which will modify\n // in-place the underlying indices and values buffers. To avoid\n // surprises of this kernel being stateful, we work around the above by\n // making deep copies here. Remove this if/when we change Reorder()'s\n // semantics.\n const auto shape_vec = shape_t->vec();\n SparseTensor sp;\n OP_REQUIRES_OK(ctx, SparseTensor::Create(\n tensor::DeepCopy(*indices_t), tensor::DeepCopy(*values_t),\n TensorShape(shape_vec), &sp));\n ReduceDetails reduction = SparseTensorReduceHelper(\n sp, reduction_axes_t->flat(), keep_dims_);\n\n Tensor *out_values;\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(0, reduction.reduced_shape, &out_values));\n auto out_flat = out_values->flat();\n out_flat.setZero();\n\n Tensor tmp_reduced_val;\n OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum::value,\n TensorShape({}), &tmp_reduced_val));\n auto reduced_val = tmp_reduced_val.scalar();\n\n // Compute strides, and use it to convert coords to flat index. The\n // coordinates returned by .group() have the same ndims as group_by_dims.\n gtl::InlinedVector output_strides(reduction.group_by_dims.size());\n if (!output_strides.empty()) { // Do this iff we don't reduce all.\n output_strides.back() = 1;\n for (int d = output_strides.size() - 2; d >= 0; --d) {\n output_strides[d] =\n output_strides[d + 1] * shape_vec(reduction.group_by_dims[d + 1]);\n }\n }\n\n auto CoordinatesToFlatIndex = [](ArraySlice coords,\n ArraySlice strides) -> int64 {\n if (strides.empty()) { // Reduce all.\n return 0;\n }\n CHECK_EQ(coords.size(), strides.size());\n int64_t idx = 0;\n for (int i = 0; i < coords.size(); ++i) {\n idx += coords[i] * strides[i];\n }\n return idx;\n };\n\n // Each group maps one-on-one onto a value in the reduced tensor.\n // g.group() provides the coordinates of a particular reduced value.\n sp.Reorder(reduction.reorder_dims);\n for (const auto &g : sp.group(reduction.group_by_dims)) {\n Op::template Run(ctx, reduced_val, g.template values());\n const int64_t idx = CoordinatesToFlatIndex(g.group(), output_strides);\n out_flat(idx) = reduced_val();\n VLOG(2) << \"coords: \" << absl::StrJoin(g.group(), \",\")\n << \"; idx: \" << idx << \"; group \" << Op::Name() << \": \"\n << reduced_val();\n }\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Prevent heap OOB in sparse reduction ops.\n\nPiperOrigin-RevId: 387934524\nChange-Id: I894aa30f1e454f09b471d565b4a325da49322c1a'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int parse_video_info(AVIOContext *pb, AVStream *st)\n{\n uint16_t size_asf; // ASF-specific Format Data size\n uint32_t size_bmp; // BMP_HEADER-specific Format Data size\n unsigned int tag;\n\n st->codecpar->width = avio_rl32(pb);\n st->codecpar->height = avio_rl32(pb);\n avio_skip(pb, 1); // skip reserved flags\n size_asf = avio_rl16(pb);\n tag = ff_get_bmp_header(pb, st, &size_bmp);\n st->codecpar->codec_tag = tag;\n st->codecpar->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag);\n size_bmp = FFMAX(size_asf, size_bmp);\n\n if (size_bmp > BMP_HEADER_SIZE) {\n int ret;\n st->codecpar->extradata_size = size_bmp - BMP_HEADER_SIZE;\n if (!(st->codecpar->extradata = av_malloc(st->codecpar->extradata_size +\n AV_INPUT_BUFFER_PADDING_SIZE))) {\n st->codecpar->extradata_size = 0;\n return AVERROR(ENOMEM);\n }\n memset(st->codecpar->extradata + st->codecpar->extradata_size , 0,\n AV_INPUT_BUFFER_PADDING_SIZE);\n if ((ret = avio_read(pb, st->codecpar->extradata,\n st->codecpar->extradata_size)) < 0)\n return ret;\n }\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'avformat/asfdec_o: Check size_bmp more fully\n\nFixes: integer overflow and out of array access\nFixes: asfo-crash-46080c4341572a7137a162331af77f6ded45cbd7\n\nFound-by: Paul Ch \nSigned-off-by: Michael Niedermayer '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void handle_debug_usb_rx(const void *msg, size_t len)\n{\n if (msg_tiny_flag) {\n uint8_t buf[64];\n memcpy(buf, msg, sizeof(buf));\n\n uint16_t msgId = buf[4] | ((uint16_t)buf[3]) << 8;\n uint32_t msgSize = buf[8] |\n ((uint32_t)buf[7]) << 8 |\n ((uint32_t)buf[6]) << 16 |\n ((uint32_t)buf[5]) << 24;\n\n if (msgSize > 64 - 9) {\n (*msg_failure)(FailureType_Failure_UnexpectedMessage, \"Malformed tiny packet\");\n return;\n }\n\n // Determine callback handler and message map type.\n const MessagesMap_t *entry = message_map_entry(DEBUG_MSG, msgId, IN_MSG);\n if (!entry) {\n (*msg_failure)(FailureType_Failure_UnexpectedMessage, \"Unknown message\");\n return;\n }\n\n tiny_dispatch(entry, buf + 9, msgSize);\n } else {\n usb_rx_helper(msg, len, DEBUG_MSG);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'board: factor out tiny_dispatch\n\nAnd add stronger checks on what tiny_msg's are allowed to be decoded.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int fallocate_chunk(struct inode *inode, loff_t offset, loff_t len,\n\t\t\t int mode)\n{\n\tstruct gfs2_inode *ip = GFS2_I(inode);\n\tstruct buffer_head *dibh;\n\tint error;\n\tu64 start = offset >> PAGE_CACHE_SHIFT;\n\tunsigned int start_offset = offset & ~PAGE_CACHE_MASK;\n\tu64 end = (offset + len - 1) >> PAGE_CACHE_SHIFT;\n\tpgoff_t curr;\n\tstruct page *page;\n\tunsigned int end_offset = (offset + len) & ~PAGE_CACHE_MASK;\n\tunsigned int from, to;\n\n\tif (!end_offset)\n\t\tend_offset = PAGE_CACHE_SIZE;\n\n\terror = gfs2_meta_inode_buffer(ip, &dibh);\n\tif (unlikely(error))\n\t\tgoto out;\n\n\tgfs2_trans_add_bh(ip->i_gl, dibh, 1);\n\n\tif (gfs2_is_stuffed(ip)) {\n\t\terror = gfs2_unstuff_dinode(ip, NULL);\n\t\tif (unlikely(error))\n\t\t\tgoto out;\n\t}\n\n\tcurr = start;\n\toffset = start << PAGE_CACHE_SHIFT;\n\tfrom = start_offset;\n\tto = PAGE_CACHE_SIZE;\n\twhile (curr <= end) {\n\t\tpage = grab_cache_page_write_begin(inode->i_mapping, curr,\n\t\t\t\t\t\t AOP_FLAG_NOFS);\n\t\tif (unlikely(!page)) {\n\t\t\terror = -ENOMEM;\n\t\t\tgoto out;\n\t\t}\n\n\t\tif (curr == end)\n\t\t\tto = end_offset;\n\t\terror = write_empty_blocks(page, from, to, mode);\n\t\tif (!error && offset + to > inode->i_size &&\n\t\t !(mode & FALLOC_FL_KEEP_SIZE)) {\n\t\t\ti_size_write(inode, offset + to);\n\t\t}\n\t\tunlock_page(page);\n\t\tpage_cache_release(page);\n\t\tif (error)\n\t\t\tgoto out;\n\t\tcurr++;\n\t\toffset += PAGE_CACHE_SIZE;\n\t\tfrom = 0;\n\t}\n\n\tmark_inode_dirty(inode);\n\n\tbrelse(dibh);\n\nout:\n\treturn error;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'GFS2: rewrite fallocate code to write blocks directly\n\nGFS2's fallocate code currently goes through the page cache. Since it's only\nwriting to the end of the file or to holes in it, it doesn't need to, and it\nwas causing issues on low memory environments. This patch pulls in some of\nSteve's block allocation work, and uses it to simply allocate the blocks for\nthe file, and zero them out at allocation time. It provides a slight\nperformance increase, and it dramatically simplifies the code.\n\nSigned-off-by: Benjamin Marzinski \nSigned-off-by: Steven Whitehouse '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void vidioc_fill_name(char *buf, int len, int nr)\n{\n\tif (card_label[nr] != NULL) {\n\t\tsnprintf(buf, len, card_label[nr]);\n\t} else {\n\t\tsnprintf(buf, len, \"Dummy video device (0x%04X)\", nr);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'add explicit format specifier to printf() invocations\n\nCWE-134'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static struct vm_area_struct *vma_to_resize(unsigned long addr,\n\tunsigned long old_len, unsigned long new_len, unsigned long *p)\n{\n\tstruct mm_struct *mm = current->mm;\n\tstruct vm_area_struct *vma = find_vma(mm, addr);\n\n\tif (!vma || vma->vm_start > addr)\n\t\tgoto Efault;\n\n\tif (is_vm_hugetlb_page(vma))\n\t\tgoto Einval;\n\n\t/* We can't remap across vm area boundaries */\n\tif (old_len > vma->vm_end - addr)\n\t\tgoto Efault;\n\n\tif (vma->vm_flags & (VM_DONTEXPAND | VM_PFNMAP)) {\n\t\tif (new_len > old_len)\n\t\t\tgoto Efault;\n\t}\n\n\tif (vma->vm_flags & VM_LOCKED) {\n\t\tunsigned long locked, lock_limit;\n\t\tlocked = mm->locked_vm << PAGE_SHIFT;\n\t\tlock_limit = rlimit(RLIMIT_MEMLOCK);\n\t\tlocked += new_len - old_len;\n\t\tif (locked > lock_limit && !capable(CAP_IPC_LOCK))\n\t\t\tgoto Eagain;\n\t}\n\n\tif (!may_expand_vm(mm, (new_len - old_len) >> PAGE_SHIFT))\n\t\tgoto Enomem;\n\n\tif (vma->vm_flags & VM_ACCOUNT) {\n\t\tunsigned long charged = (new_len - old_len) >> PAGE_SHIFT;\n\t\tif (security_vm_enough_memory(charged))\n\t\t\tgoto Efault;\n\t\t*p = charged;\n\t}\n\n\treturn vma;\n\nEfault:\t/* very odd choice for most of the cases, but... */\n\treturn ERR_PTR(-EFAULT);\nEinval:\n\treturn ERR_PTR(-EINVAL);\nEnomem:\n\treturn ERR_PTR(-ENOMEM);\nEagain:\n\treturn ERR_PTR(-EAGAIN);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'mm: avoid wrapping vm_pgoff in mremap()\n\nThe normal mmap paths all avoid creating a mapping where the pgoff\ninside the mapping could wrap around due to overflow. However, an\nexpanding mremap() can take such a non-wrapping mapping and make it\nbigger and cause a wrapping condition.\n\nNoticed by Robert Swiecki when running a system call fuzzer, where it\ncaused a BUG_ON() due to terminally confusing the vma_prio_tree code. A\nvma dumping patch by Hugh then pinpointed the crazy wrapped case.\n\nReported-and-tested-by: Robert Swiecki \nAcked-by: Hugh Dickins \nCc: stable@kernel.org\nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void readStructEnd() {\n lastFieldId_ = nestedStructFieldIds_.back();\n nestedStructFieldIds_.pop_back();\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-522', 'CWE-674'], 'message': 'Attempt to make CarbonProtocolReader::skip tail recursive\n\nReviewed By: edenzik\n\nDifferential Revision: D17967570\n\nfbshipit-source-id: fdc32e190a521349c7c8f4d6081902fa18eb0284'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int ptrace_check_attach(struct task_struct *child, bool ignore_state)\n{\n\tint ret = -ESRCH;\n\n\t/*\n\t * We take the read lock around doing both checks to close a\n\t * possible race where someone else was tracing our child and\n\t * detached between these two checks. After this locked check,\n\t * we are sure that this is our traced child and that can only\n\t * be changed by us so it's not changing right after this.\n\t */\n\tread_lock(&tasklist_lock);\n\tif ((child->ptrace & PT_PTRACED) && child->parent == current) {\n\t\t/*\n\t\t * child->sighand can't be NULL, release_task()\n\t\t * does ptrace_unlink() before __exit_signal().\n\t\t */\n\t\tspin_lock_irq(&child->sighand->siglock);\n\t\tWARN_ON_ONCE(task_is_stopped(child));\n\t\tif (ignore_state || (task_is_traced(child) &&\n\t\t\t\t !(child->jobctl & JOBCTL_LISTENING)))\n\t\t\tret = 0;\n\t\tspin_unlock_irq(&child->sighand->siglock);\n\t}\n\tread_unlock(&tasklist_lock);\n\n\tif (!ret && !ignore_state)\n\t\tret = wait_task_inactive(child, TASK_TRACED) ? 0 : -ESRCH;\n\n\t/* All systems go.. */\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-362'], 'message': 'ptrace: ensure arch_ptrace/ptrace_request can never race with SIGKILL\n\nputreg() assumes that the tracee is not running and pt_regs_access() can\nsafely play with its stack. However a killed tracee can return from\nptrace_stop() to the low-level asm code and do RESTORE_REST, this means\nthat debugger can actually read/modify the kernel stack until the tracee\ndoes SAVE_REST again.\n\nset_task_blockstep() can race with SIGKILL too and in some sense this\nrace is even worse, the very fact the tracee can be woken up breaks the\nlogic.\n\nAs Linus suggested we can clear TASK_WAKEKILL around the arch_ptrace()\ncall, this ensures that nobody can ever wakeup the tracee while the\ndebugger looks at it. Not only this fixes the mentioned problems, we\ncan do some cleanups/simplifications in arch_ptrace() paths.\n\nProbably ptrace_unfreeze_traced() needs more callers, for example it\nmakes sense to make the tracee killable for oom-killer before\naccess_process_vm().\n\nWhile at it, add the comment into may_ptrace_stop() to explain why\nptrace_stop() still can't rely on SIGKILL and signal_pending_state().\n\nReported-by: Salman Qazi \nReported-by: Suleiman Souhlal \nSuggested-by: Linus Torvalds \nSigned-off-by: Oleg Nesterov \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: juniper_mlppp_print(netdissect_options *ndo,\n const struct pcap_pkthdr *h, register const u_char *p)\n{\n struct juniper_l2info_t l2info;\n\n l2info.pictype = DLT_JUNIPER_MLPPP;\n if (juniper_parse_header(ndo, p, h, &l2info) == 0)\n return l2info.header_len;\n\n /* suppress Bundle-ID if frame was captured on a child-link\n * best indicator if the cookie looks like a proto */\n if (ndo->ndo_eflag &&\n EXTRACT_16BITS(&l2info.cookie) != PPP_OSI &&\n EXTRACT_16BITS(&l2info.cookie) != (PPP_ADDRESS << 8 | PPP_CONTROL))\n ND_PRINT((ndo, \"Bundle-ID %u: \", l2info.bundle));\n\n p+=l2info.header_len;\n\n /* first try the LSQ protos */\n switch(l2info.proto) {\n case JUNIPER_LSQ_L3_PROTO_IPV4:\n /* IP traffic going to the RE would not have a cookie\n * -> this must be incoming IS-IS over PPP\n */\n if (l2info.cookie[4] == (JUNIPER_LSQ_COOKIE_RE|JUNIPER_LSQ_COOKIE_DIR))\n ppp_print(ndo, p, l2info.length);\n else\n ip_print(ndo, p, l2info.length);\n return l2info.header_len;\n case JUNIPER_LSQ_L3_PROTO_IPV6:\n ip6_print(ndo, p,l2info.length);\n return l2info.header_len;\n case JUNIPER_LSQ_L3_PROTO_MPLS:\n mpls_print(ndo, p, l2info.length);\n return l2info.header_len;\n case JUNIPER_LSQ_L3_PROTO_ISO:\n isoclns_print(ndo, p, l2info.length, l2info.caplen);\n return l2info.header_len;\n default:\n break;\n }\n\n /* zero length cookie ? */\n switch (EXTRACT_16BITS(&l2info.cookie)) {\n case PPP_OSI:\n ppp_print(ndo, p - 2, l2info.length + 2);\n break;\n case (PPP_ADDRESS << 8 | PPP_CONTROL): /* fall through */\n default:\n ppp_print(ndo, p, l2info.length);\n break;\n }\n\n return l2info.header_len;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print().\n\nThis fixes a buffer over-read discovered by Kamil Frankowicz.\n\nDon't pass the remaining caplen - that's too hard to get right, and we\nwere getting it wrong in at least one case; just use ND_TTEST().\n\nAdd a test using the capture file supplied by the reporter(s).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ethertype_print(netdissect_options *ndo,\n u_short ether_type, const u_char *p,\n u_int length, u_int caplen,\n const struct lladdr_info *src, const struct lladdr_info *dst)\n{\n\tswitch (ether_type) {\n\n\tcase ETHERTYPE_IP:\n\t ip_print(ndo, p, length);\n\t\treturn (1);\n\n\tcase ETHERTYPE_IPV6:\n\t\tip6_print(ndo, p, length);\n\t\treturn (1);\n\n\tcase ETHERTYPE_ARP:\n\tcase ETHERTYPE_REVARP:\n\t arp_print(ndo, p, length, caplen);\n\t\treturn (1);\n\n\tcase ETHERTYPE_DN:\n\t\tdecnet_print(ndo, p, length, caplen);\n\t\treturn (1);\n\n\tcase ETHERTYPE_ATALK:\n\t\tif (ndo->ndo_vflag)\n\t\t\tND_PRINT((ndo, \"et1 \"));\n\t\tatalk_print(ndo, p, length);\n\t\treturn (1);\n\n\tcase ETHERTYPE_AARP:\n\t\taarp_print(ndo, p, length);\n\t\treturn (1);\n\n\tcase ETHERTYPE_IPX:\n\t\tND_PRINT((ndo, \"(NOV-ETHII) \"));\n\t\tipx_print(ndo, p, length);\n\t\treturn (1);\n\n\tcase ETHERTYPE_ISO:\n\t\tif (length == 0 || caplen == 0) {\n\t\t\tND_PRINT((ndo, \" [|osi]\"));\n\t\t\treturn (1);\n\t\t}\n\t\tisoclns_print(ndo, p + 1, length - 1, caplen - 1);\n\t\treturn(1);\n\n\tcase ETHERTYPE_PPPOED:\n\tcase ETHERTYPE_PPPOES:\n\tcase ETHERTYPE_PPPOED2:\n\tcase ETHERTYPE_PPPOES2:\n\t\tpppoe_print(ndo, p, length);\n\t\treturn (1);\n\n\tcase ETHERTYPE_EAPOL:\n\t eap_print(ndo, p, length);\n\t\treturn (1);\n\n\tcase ETHERTYPE_RRCP:\n\t rrcp_print(ndo, p, length, src, dst);\n\t\treturn (1);\n\n\tcase ETHERTYPE_PPP:\n\t\tif (length) {\n\t\t\tND_PRINT((ndo, \": \"));\n\t\t\tppp_print(ndo, p, length);\n\t\t}\n\t\treturn (1);\n\n\tcase ETHERTYPE_MPCP:\n\t mpcp_print(ndo, p, length);\n\t\treturn (1);\n\n\tcase ETHERTYPE_SLOW:\n\t slow_print(ndo, p, length);\n\t\treturn (1);\n\n\tcase ETHERTYPE_CFM:\n\tcase ETHERTYPE_CFM_OLD:\n\t\tcfm_print(ndo, p, length);\n\t\treturn (1);\n\n\tcase ETHERTYPE_LLDP:\n\t\tlldp_print(ndo, p, length);\n\t\treturn (1);\n\n case ETHERTYPE_NSH:\n nsh_print(ndo, p, length);\n return (1);\n\n case ETHERTYPE_LOOPBACK:\n\t\tloopback_print(ndo, p, length);\n return (1);\n\n\tcase ETHERTYPE_MPLS:\n\tcase ETHERTYPE_MPLS_MULTI:\n\t\tmpls_print(ndo, p, length);\n\t\treturn (1);\n\n\tcase ETHERTYPE_TIPC:\n\t\ttipc_print(ndo, p, length, caplen);\n\t\treturn (1);\n\n\tcase ETHERTYPE_MS_NLB_HB:\n\t\tmsnlb_print(ndo, p);\n\t\treturn (1);\n\n case ETHERTYPE_GEONET_OLD:\n case ETHERTYPE_GEONET:\n geonet_print(ndo, p, length, src);\n return (1);\n\n case ETHERTYPE_CALM_FAST:\n calm_fast_print(ndo, p, length, src);\n return (1);\n\n\tcase ETHERTYPE_AOE:\n\t\taoe_print(ndo, p, length);\n\t\treturn (1);\n\n\tcase ETHERTYPE_MEDSA:\n\t\tmedsa_print(ndo, p, length, caplen, src, dst);\n\t\treturn (1);\n\n\tcase ETHERTYPE_LAT:\n\tcase ETHERTYPE_SCA:\n\tcase ETHERTYPE_MOPRC:\n\tcase ETHERTYPE_MOPDL:\n\tcase ETHERTYPE_IEEE1905_1:\n\t\t/* default_print for now */\n\tdefault:\n\t\treturn (0);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print().\n\nThis fixes a buffer over-read discovered by Kamil Frankowicz.\n\nDon't pass the remaining caplen - that's too hard to get right, and we\nwere getting it wrong in at least one case; just use ND_TTEST().\n\nAdd a test using the capture file supplied by the reporter(s).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void SFS_ObjectMethodCall(ScriptParser *parser)\n{\n\tif (parser->codec->LastError) return;\n\tSFS_Expression(parser);\n\tSFS_AddString(parser, \".\");\n\tSFS_Identifier(parser);\n\tSFS_AddString(parser, \"(\");\n\tSFS_Params(parser);\n\tSFS_AddString(parser, \")\");\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'fixed #2238'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: xfs_ioctl_setattr(\n\txfs_inode_t\t\t*ip,\n\tstruct fsxattr\t\t*fa,\n\tint\t\t\tmask)\n{\n\tstruct xfs_mount\t*mp = ip->i_mount;\n\tstruct xfs_trans\t*tp;\n\tunsigned int\t\tlock_flags = 0;\n\tstruct xfs_dquot\t*udqp = NULL;\n\tstruct xfs_dquot\t*pdqp = NULL;\n\tstruct xfs_dquot\t*olddquot = NULL;\n\tint\t\t\tcode;\n\n\ttrace_xfs_ioctl_setattr(ip);\n\n\tif (mp->m_flags & XFS_MOUNT_RDONLY)\n\t\treturn XFS_ERROR(EROFS);\n\tif (XFS_FORCED_SHUTDOWN(mp))\n\t\treturn XFS_ERROR(EIO);\n\n\t/*\n\t * Disallow 32bit project ids when projid32bit feature is not enabled.\n\t */\n\tif ((mask & FSX_PROJID) && (fa->fsx_projid > (__uint16_t)-1) &&\n\t\t\t!xfs_sb_version_hasprojid32bit(&ip->i_mount->m_sb))\n\t\treturn XFS_ERROR(EINVAL);\n\n\t/*\n\t * If disk quotas is on, we make sure that the dquots do exist on disk,\n\t * before we start any other transactions. Trying to do this later\n\t * is messy. We don't care to take a readlock to look at the ids\n\t * in inode here, because we can't hold it across the trans_reserve.\n\t * If the IDs do change before we take the ilock, we're covered\n\t * because the i_*dquot fields will get updated anyway.\n\t */\n\tif (XFS_IS_QUOTA_ON(mp) && (mask & FSX_PROJID)) {\n\t\tcode = xfs_qm_vop_dqalloc(ip, ip->i_d.di_uid,\n\t\t\t\t\t ip->i_d.di_gid, fa->fsx_projid,\n\t\t\t\t\t XFS_QMOPT_PQUOTA, &udqp, NULL, &pdqp);\n\t\tif (code)\n\t\t\treturn code;\n\t}\n\n\t/*\n\t * For the other attributes, we acquire the inode lock and\n\t * first do an error checking pass.\n\t */\n\ttp = xfs_trans_alloc(mp, XFS_TRANS_SETATTR_NOT_SIZE);\n\tcode = xfs_trans_reserve(tp, &M_RES(mp)->tr_ichange, 0, 0);\n\tif (code)\n\t\tgoto error_return;\n\n\tlock_flags = XFS_ILOCK_EXCL;\n\txfs_ilock(ip, lock_flags);\n\n\t/*\n\t * CAP_FOWNER overrides the following restrictions:\n\t *\n\t * The user ID of the calling process must be equal\n\t * to the file owner ID, except in cases where the\n\t * CAP_FSETID capability is applicable.\n\t */\n\tif (!inode_owner_or_capable(VFS_I(ip))) {\n\t\tcode = XFS_ERROR(EPERM);\n\t\tgoto error_return;\n\t}\n\n\t/*\n\t * Do a quota reservation only if projid is actually going to change.\n\t * Only allow changing of projid from init_user_ns since it is a\n\t * non user namespace aware identifier.\n\t */\n\tif (mask & FSX_PROJID) {\n\t\tif (current_user_ns() != &init_user_ns) {\n\t\t\tcode = XFS_ERROR(EINVAL);\n\t\t\tgoto error_return;\n\t\t}\n\n\t\tif (XFS_IS_QUOTA_RUNNING(mp) &&\n\t\t XFS_IS_PQUOTA_ON(mp) &&\n\t\t xfs_get_projid(ip) != fa->fsx_projid) {\n\t\t\tASSERT(tp);\n\t\t\tcode = xfs_qm_vop_chown_reserve(tp, ip, udqp, NULL,\n\t\t\t\t\t\tpdqp, capable(CAP_FOWNER) ?\n\t\t\t\t\t\tXFS_QMOPT_FORCE_RES : 0);\n\t\t\tif (code)\t/* out of quota */\n\t\t\t\tgoto error_return;\n\t\t}\n\t}\n\n\tif (mask & FSX_EXTSIZE) {\n\t\t/*\n\t\t * Can't change extent size if any extents are allocated.\n\t\t */\n\t\tif (ip->i_d.di_nextents &&\n\t\t ((ip->i_d.di_extsize << mp->m_sb.sb_blocklog) !=\n\t\t fa->fsx_extsize)) {\n\t\t\tcode = XFS_ERROR(EINVAL);\t/* EFBIG? */\n\t\t\tgoto error_return;\n\t\t}\n\n\t\t/*\n\t\t * Extent size must be a multiple of the appropriate block\n\t\t * size, if set at all. It must also be smaller than the\n\t\t * maximum extent size supported by the filesystem.\n\t\t *\n\t\t * Also, for non-realtime files, limit the extent size hint to\n\t\t * half the size of the AGs in the filesystem so alignment\n\t\t * doesn't result in extents larger than an AG.\n\t\t */\n\t\tif (fa->fsx_extsize != 0) {\n\t\t\txfs_extlen_t size;\n\t\t\txfs_fsblock_t extsize_fsb;\n\n\t\t\textsize_fsb = XFS_B_TO_FSB(mp, fa->fsx_extsize);\n\t\t\tif (extsize_fsb > MAXEXTLEN) {\n\t\t\t\tcode = XFS_ERROR(EINVAL);\n\t\t\t\tgoto error_return;\n\t\t\t}\n\n\t\t\tif (XFS_IS_REALTIME_INODE(ip) ||\n\t\t\t ((mask & FSX_XFLAGS) &&\n\t\t\t (fa->fsx_xflags & XFS_XFLAG_REALTIME))) {\n\t\t\t\tsize = mp->m_sb.sb_rextsize <<\n\t\t\t\t mp->m_sb.sb_blocklog;\n\t\t\t} else {\n\t\t\t\tsize = mp->m_sb.sb_blocksize;\n\t\t\t\tif (extsize_fsb > mp->m_sb.sb_agblocks / 2) {\n\t\t\t\t\tcode = XFS_ERROR(EINVAL);\n\t\t\t\t\tgoto error_return;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (fa->fsx_extsize % size) {\n\t\t\t\tcode = XFS_ERROR(EINVAL);\n\t\t\t\tgoto error_return;\n\t\t\t}\n\t\t}\n\t}\n\n\n\tif (mask & FSX_XFLAGS) {\n\t\t/*\n\t\t * Can't change realtime flag if any extents are allocated.\n\t\t */\n\t\tif ((ip->i_d.di_nextents || ip->i_delayed_blks) &&\n\t\t (XFS_IS_REALTIME_INODE(ip)) !=\n\t\t (fa->fsx_xflags & XFS_XFLAG_REALTIME)) {\n\t\t\tcode = XFS_ERROR(EINVAL);\t/* EFBIG? */\n\t\t\tgoto error_return;\n\t\t}\n\n\t\t/*\n\t\t * If realtime flag is set then must have realtime data.\n\t\t */\n\t\tif ((fa->fsx_xflags & XFS_XFLAG_REALTIME)) {\n\t\t\tif ((mp->m_sb.sb_rblocks == 0) ||\n\t\t\t (mp->m_sb.sb_rextsize == 0) ||\n\t\t\t (ip->i_d.di_extsize % mp->m_sb.sb_rextsize)) {\n\t\t\t\tcode = XFS_ERROR(EINVAL);\n\t\t\t\tgoto error_return;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * Can't modify an immutable/append-only file unless\n\t\t * we have appropriate permission.\n\t\t */\n\t\tif ((ip->i_d.di_flags &\n\t\t\t\t(XFS_DIFLAG_IMMUTABLE|XFS_DIFLAG_APPEND) ||\n\t\t (fa->fsx_xflags &\n\t\t\t\t(XFS_XFLAG_IMMUTABLE | XFS_XFLAG_APPEND))) &&\n\t\t !capable(CAP_LINUX_IMMUTABLE)) {\n\t\t\tcode = XFS_ERROR(EPERM);\n\t\t\tgoto error_return;\n\t\t}\n\t}\n\n\txfs_trans_ijoin(tp, ip, 0);\n\n\t/*\n\t * Change file ownership. Must be the owner or privileged.\n\t */\n\tif (mask & FSX_PROJID) {\n\t\t/*\n\t\t * CAP_FSETID overrides the following restrictions:\n\t\t *\n\t\t * The set-user-ID and set-group-ID bits of a file will be\n\t\t * cleared upon successful return from chown()\n\t\t */\n\t\tif ((ip->i_d.di_mode & (S_ISUID|S_ISGID)) &&\n\t\t !inode_capable(VFS_I(ip), CAP_FSETID))\n\t\t\tip->i_d.di_mode &= ~(S_ISUID|S_ISGID);\n\n\t\t/*\n\t\t * Change the ownerships and register quota modifications\n\t\t * in the transaction.\n\t\t */\n\t\tif (xfs_get_projid(ip) != fa->fsx_projid) {\n\t\t\tif (XFS_IS_QUOTA_RUNNING(mp) && XFS_IS_PQUOTA_ON(mp)) {\n\t\t\t\tolddquot = xfs_qm_vop_chown(tp, ip,\n\t\t\t\t\t\t\t&ip->i_pdquot, pdqp);\n\t\t\t}\n\t\t\txfs_set_projid(ip, fa->fsx_projid);\n\n\t\t\t/*\n\t\t\t * We may have to rev the inode as well as\n\t\t\t * the superblock version number since projids didn't\n\t\t\t * exist before DINODE_VERSION_2 and SB_VERSION_NLINK.\n\t\t\t */\n\t\t\tif (ip->i_d.di_version == 1)\n\t\t\t\txfs_bump_ino_vers2(tp, ip);\n\t\t}\n\n\t}\n\n\tif (mask & FSX_EXTSIZE)\n\t\tip->i_d.di_extsize = fa->fsx_extsize >> mp->m_sb.sb_blocklog;\n\tif (mask & FSX_XFLAGS) {\n\t\txfs_set_diflags(ip, fa->fsx_xflags);\n\t\txfs_diflags_to_linux(ip);\n\t}\n\n\txfs_trans_ichgtime(tp, ip, XFS_ICHGTIME_CHG);\n\txfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);\n\n\tXFS_STATS_INC(xs_ig_attrchg);\n\n\t/*\n\t * If this is a synchronous mount, make sure that the\n\t * transaction goes to disk before returning to the user.\n\t * This is slightly sub-optimal in that truncates require\n\t * two sync transactions instead of one for wsync filesystems.\n\t * One for the truncate and one for the timestamps since we\n\t * don't want to change the timestamps unless we're sure the\n\t * truncate worked. Truncates are less than 1% of the laddis\n\t * mix so this probably isn't worth the trouble to optimize.\n\t */\n\tif (mp->m_flags & XFS_MOUNT_WSYNC)\n\t\txfs_trans_set_sync(tp);\n\tcode = xfs_trans_commit(tp, 0);\n\txfs_iunlock(ip, lock_flags);\n\n\t/*\n\t * Release any dquot(s) the inode had kept before chown.\n\t */\n\txfs_qm_dqrele(olddquot);\n\txfs_qm_dqrele(udqp);\n\txfs_qm_dqrele(pdqp);\n\n\treturn code;\n\n error_return:\n\txfs_qm_dqrele(udqp);\n\txfs_qm_dqrele(pdqp);\n\txfs_trans_cancel(tp, 0);\n\tif (lock_flags)\n\t\txfs_iunlock(ip, lock_flags);\n\treturn code;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'fs,userns: Change inode_capable to capable_wrt_inode_uidgid\n\nThe kernel has no concept of capabilities with respect to inodes; inodes\nexist independently of namespaces. For example, inode_capable(inode,\nCAP_LINUX_IMMUTABLE) would be nonsense.\n\nThis patch changes inode_capable to check for uid and gid mappings and\nrenames it to capable_wrt_inode_uidgid, which should make it more\nobvious what it does.\n\nFixes CVE-2014-4014.\n\nCc: Theodore Ts'o \nCc: Serge Hallyn \nCc: \"Eric W. Biederman\" \nCc: Dave Chinner \nCc: stable@vger.kernel.org\nSigned-off-by: Andy Lutomirski \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: mrb_vm_exec(mrb_state *mrb, struct RProc *proc, mrb_code *pc)\n{\n /* mrb_assert(mrb_proc_cfunc_p(proc)) */\n mrb_irep *irep = proc->body.irep;\n mrb_value *pool = irep->pool;\n mrb_sym *syms = irep->syms;\n mrb_code i;\n int ai = mrb_gc_arena_save(mrb);\n struct mrb_jmpbuf *prev_jmp = mrb->jmp;\n struct mrb_jmpbuf c_jmp;\n\n#ifdef DIRECT_THREADED\n static void *optable[] = {\n &&L_OP_NOP, &&L_OP_MOVE,\n &&L_OP_LOADL, &&L_OP_LOADI, &&L_OP_LOADSYM, &&L_OP_LOADNIL,\n &&L_OP_LOADSELF, &&L_OP_LOADT, &&L_OP_LOADF,\n &&L_OP_GETGLOBAL, &&L_OP_SETGLOBAL, &&L_OP_GETSPECIAL, &&L_OP_SETSPECIAL,\n &&L_OP_GETIV, &&L_OP_SETIV, &&L_OP_GETCV, &&L_OP_SETCV,\n &&L_OP_GETCONST, &&L_OP_SETCONST, &&L_OP_GETMCNST, &&L_OP_SETMCNST,\n &&L_OP_GETUPVAR, &&L_OP_SETUPVAR,\n &&L_OP_JMP, &&L_OP_JMPIF, &&L_OP_JMPNOT,\n &&L_OP_ONERR, &&L_OP_RESCUE, &&L_OP_POPERR, &&L_OP_RAISE, &&L_OP_EPUSH, &&L_OP_EPOP,\n &&L_OP_SEND, &&L_OP_SENDB, &&L_OP_FSEND,\n &&L_OP_CALL, &&L_OP_SUPER, &&L_OP_ARGARY, &&L_OP_ENTER,\n &&L_OP_KARG, &&L_OP_KDICT, &&L_OP_RETURN, &&L_OP_TAILCALL, &&L_OP_BLKPUSH,\n &&L_OP_ADD, &&L_OP_ADDI, &&L_OP_SUB, &&L_OP_SUBI, &&L_OP_MUL, &&L_OP_DIV,\n &&L_OP_EQ, &&L_OP_LT, &&L_OP_LE, &&L_OP_GT, &&L_OP_GE,\n &&L_OP_ARRAY, &&L_OP_ARYCAT, &&L_OP_ARYPUSH, &&L_OP_AREF, &&L_OP_ASET, &&L_OP_APOST,\n &&L_OP_STRING, &&L_OP_STRCAT, &&L_OP_HASH,\n &&L_OP_LAMBDA, &&L_OP_RANGE, &&L_OP_OCLASS,\n &&L_OP_CLASS, &&L_OP_MODULE, &&L_OP_EXEC,\n &&L_OP_METHOD, &&L_OP_SCLASS, &&L_OP_TCLASS,\n &&L_OP_DEBUG, &&L_OP_STOP, &&L_OP_ERR,\n };\n#endif\n\n mrb_bool exc_catched = FALSE;\nRETRY_TRY_BLOCK:\n\n MRB_TRY(&c_jmp) {\n\n if (exc_catched) {\n exc_catched = FALSE;\n if (mrb->exc && mrb->exc->tt == MRB_TT_BREAK)\n goto L_BREAK;\n goto L_RAISE;\n }\n mrb->jmp = &c_jmp;\n mrb->c->ci->proc = proc;\n mrb->c->ci->nregs = irep->nregs;\n\n#define regs (mrb->c->stack)\n INIT_DISPATCH {\n CASE(OP_NOP) {\n /* do nothing */\n NEXT;\n }\n\n CASE(OP_MOVE) {\n /* A B R(A) := R(B) */\n int a = GETARG_A(i);\n int b = GETARG_B(i);\n regs[a] = regs[b];\n NEXT;\n }\n\n CASE(OP_LOADL) {\n /* A Bx R(A) := Pool(Bx) */\n int a = GETARG_A(i);\n int bx = GETARG_Bx(i);\n#ifdef MRB_WORD_BOXING\n mrb_value val = pool[bx];\n#ifndef MRB_WITHOUT_FLOAT\n if (mrb_float_p(val)) {\n val = mrb_float_value(mrb, mrb_float(val));\n }\n#endif\n regs[a] = val;\n#else\n regs[a] = pool[bx];\n#endif\n NEXT;\n }\n\n CASE(OP_LOADI) {\n /* A sBx R(A) := sBx */\n int a = GETARG_A(i);\n mrb_int bx = GETARG_sBx(i);\n SET_INT_VALUE(regs[a], bx);\n NEXT;\n }\n\n CASE(OP_LOADSYM) {\n /* A Bx R(A) := Syms(Bx) */\n int a = GETARG_A(i);\n int bx = GETARG_Bx(i);\n SET_SYM_VALUE(regs[a], syms[bx]);\n NEXT;\n }\n\n CASE(OP_LOADSELF) {\n /* A R(A) := self */\n int a = GETARG_A(i);\n regs[a] = regs[0];\n NEXT;\n }\n\n CASE(OP_LOADT) {\n /* A R(A) := true */\n int a = GETARG_A(i);\n SET_TRUE_VALUE(regs[a]);\n NEXT;\n }\n\n CASE(OP_LOADF) {\n /* A R(A) := false */\n int a = GETARG_A(i);\n SET_FALSE_VALUE(regs[a]);\n NEXT;\n }\n\n CASE(OP_GETGLOBAL) {\n /* A Bx R(A) := getglobal(Syms(Bx)) */\n int a = GETARG_A(i);\n int bx = GETARG_Bx(i);\n mrb_value val = mrb_gv_get(mrb, syms[bx]);\n regs[a] = val;\n NEXT;\n }\n\n CASE(OP_SETGLOBAL) {\n /* A Bx setglobal(Syms(Bx), R(A)) */\n int a = GETARG_A(i);\n int bx = GETARG_Bx(i);\n mrb_gv_set(mrb, syms[bx], regs[a]);\n NEXT;\n }\n\n CASE(OP_GETSPECIAL) {\n /* A Bx R(A) := Special[Bx] */\n int a = GETARG_A(i);\n int bx = GETARG_Bx(i);\n mrb_value val = mrb_vm_special_get(mrb, bx);\n regs[a] = val;\n NEXT;\n }\n\n CASE(OP_SETSPECIAL) {\n /* A Bx Special[Bx] := R(A) */\n int a = GETARG_A(i);\n int bx = GETARG_Bx(i);\n mrb_vm_special_set(mrb, bx, regs[a]);\n NEXT;\n }\n\n CASE(OP_GETIV) {\n /* A Bx R(A) := ivget(Bx) */\n int a = GETARG_A(i);\n int bx = GETARG_Bx(i);\n mrb_value val = mrb_vm_iv_get(mrb, syms[bx]);\n regs[a] = val;\n NEXT;\n }\n\n CASE(OP_SETIV) {\n /* A Bx ivset(Syms(Bx),R(A)) */\n int a = GETARG_A(i);\n int bx = GETARG_Bx(i);\n mrb_vm_iv_set(mrb, syms[bx], regs[a]);\n NEXT;\n }\n\n CASE(OP_GETCV) {\n /* A Bx R(A) := cvget(Syms(Bx)) */\n int a = GETARG_A(i);\n int bx = GETARG_Bx(i);\n mrb_value val;\n ERR_PC_SET(mrb, pc);\n val = mrb_vm_cv_get(mrb, syms[bx]);\n ERR_PC_CLR(mrb);\n regs[a] = val;\n NEXT;\n }\n\n CASE(OP_SETCV) {\n /* A Bx cvset(Syms(Bx),R(A)) */\n int a = GETARG_A(i);\n int bx = GETARG_Bx(i);\n mrb_vm_cv_set(mrb, syms[bx], regs[a]);\n NEXT;\n }\n\n CASE(OP_GETCONST) {\n /* A Bx R(A) := constget(Syms(Bx)) */\n mrb_value val;\n int a = GETARG_A(i);\n int bx = GETARG_Bx(i);\n mrb_sym sym = syms[bx];\n\n ERR_PC_SET(mrb, pc);\n val = mrb_vm_const_get(mrb, sym);\n ERR_PC_CLR(mrb);\n regs[a] = val;\n NEXT;\n }\n\n CASE(OP_SETCONST) {\n /* A Bx constset(Syms(Bx),R(A)) */\n int a = GETARG_A(i);\n int bx = GETARG_Bx(i);\n mrb_vm_const_set(mrb, syms[bx], regs[a]);\n NEXT;\n }\n\n CASE(OP_GETMCNST) {\n /* A Bx R(A) := R(A)::Syms(Bx) */\n mrb_value val;\n int a = GETARG_A(i);\n int bx = GETARG_Bx(i);\n\n ERR_PC_SET(mrb, pc);\n val = mrb_const_get(mrb, regs[a], syms[bx]);\n ERR_PC_CLR(mrb);\n regs[a] = val;\n NEXT;\n }\n\n CASE(OP_SETMCNST) {\n /* A Bx R(A+1)::Syms(Bx) := R(A) */\n int a = GETARG_A(i);\n int bx = GETARG_Bx(i);\n mrb_const_set(mrb, regs[a+1], syms[bx], regs[a]);\n NEXT;\n }\n\n CASE(OP_GETUPVAR) {\n /* A B C R(A) := uvget(B,C) */\n int a = GETARG_A(i);\n int b = GETARG_B(i);\n int c = GETARG_C(i);\n mrb_value *regs_a = regs + a;\n struct REnv *e = uvenv(mrb, c);\n\n if (!e) {\n *regs_a = mrb_nil_value();\n }\n else {\n *regs_a = e->stack[b];\n }\n NEXT;\n }\n\n CASE(OP_SETUPVAR) {\n /* A B C uvset(B,C,R(A)) */\n int a = GETARG_A(i);\n int b = GETARG_B(i);\n int c = GETARG_C(i);\n\n struct REnv *e = uvenv(mrb, c);\n\n if (e) {\n mrb_value *regs_a = regs + a;\n\n if (b < MRB_ENV_STACK_LEN(e)) {\n e->stack[b] = *regs_a;\n mrb_write_barrier(mrb, (struct RBasic*)e);\n }\n }\n NEXT;\n }\n\n CASE(OP_JMP) {\n /* sBx pc+=sBx */\n int sbx = GETARG_sBx(i);\n pc += sbx;\n JUMP;\n }\n\n CASE(OP_JMPIF) {\n /* A sBx if R(A) pc+=sBx */\n int a = GETARG_A(i);\n int sbx = GETARG_sBx(i);\n if (mrb_test(regs[a])) {\n pc += sbx;\n JUMP;\n }\n NEXT;\n }\n\n CASE(OP_JMPNOT) {\n /* A sBx if !R(A) pc+=sBx */\n int a = GETARG_A(i);\n int sbx = GETARG_sBx(i);\n if (!mrb_test(regs[a])) {\n pc += sbx;\n JUMP;\n }\n NEXT;\n }\n\n CASE(OP_ONERR) {\n /* sBx pc+=sBx on exception */\n int sbx = GETARG_sBx(i);\n if (mrb->c->rsize <= mrb->c->ci->ridx) {\n if (mrb->c->rsize == 0) mrb->c->rsize = RESCUE_STACK_INIT_SIZE;\n else mrb->c->rsize *= 2;\n mrb->c->rescue = (mrb_code **)mrb_realloc(mrb, mrb->c->rescue, sizeof(mrb_code*) * mrb->c->rsize);\n }\n mrb->c->rescue[mrb->c->ci->ridx++] = pc + sbx;\n NEXT;\n }\n\n CASE(OP_RESCUE) {\n /* A B R(A) := exc; clear(exc); R(B) := matched (bool) */\n int a = GETARG_A(i);\n int b = GETARG_B(i);\n int c = GETARG_C(i);\n mrb_value exc;\n\n if (c == 0) {\n exc = mrb_obj_value(mrb->exc);\n mrb->exc = 0;\n }\n else { /* continued; exc taken from R(A) */\n exc = regs[a];\n }\n if (b != 0) {\n mrb_value e = regs[b];\n struct RClass *ec;\n\n switch (mrb_type(e)) {\n case MRB_TT_CLASS:\n case MRB_TT_MODULE:\n break;\n default:\n {\n mrb_value exc;\n\n exc = mrb_exc_new_str_lit(mrb, E_TYPE_ERROR,\n \"class or module required for rescue clause\");\n mrb_exc_set(mrb, exc);\n goto L_RAISE;\n }\n }\n ec = mrb_class_ptr(e);\n regs[b] = mrb_bool_value(mrb_obj_is_kind_of(mrb, exc, ec));\n }\n if (a != 0 && c == 0) {\n regs[a] = exc;\n }\n NEXT;\n }\n\n CASE(OP_POPERR) {\n /* A A.times{rescue_pop()} */\n int a = GETARG_A(i);\n\n mrb->c->ci->ridx -= a;\n NEXT;\n }\n\n CASE(OP_RAISE) {\n /* A raise(R(A)) */\n int a = GETARG_A(i);\n\n mrb_exc_set(mrb, regs[a]);\n goto L_RAISE;\n }\n\n CASE(OP_EPUSH) {\n /* Bx ensure_push(SEQ[Bx]) */\n int bx = GETARG_Bx(i);\n struct RProc *p;\n\n p = mrb_closure_new(mrb, irep->reps[bx]);\n /* push ensure_stack */\n if (mrb->c->esize <= mrb->c->eidx+1) {\n if (mrb->c->esize == 0) mrb->c->esize = ENSURE_STACK_INIT_SIZE;\n else mrb->c->esize *= 2;\n mrb->c->ensure = (struct RProc **)mrb_realloc(mrb, mrb->c->ensure, sizeof(struct RProc*) * mrb->c->esize);\n }\n mrb->c->ensure[mrb->c->eidx++] = p;\n mrb->c->ensure[mrb->c->eidx] = NULL;\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_EPOP) {\n /* A A.times{ensure_pop().call} */\n int a = GETARG_A(i);\n mrb_callinfo *ci = mrb->c->ci;\n int n, epos = ci->epos;\n mrb_value self = regs[0];\n struct RClass *target_class = ci->target_class;\n\n if (mrb->c->eidx <= epos) {\n NEXT;\n }\n\n if (a > mrb->c->eidx - epos)\n a = mrb->c->eidx - epos;\n pc = pc + 1;\n for (n=0; nc->ensure[epos+n];\n mrb->c->ensure[epos+n] = NULL;\n if (proc == NULL) continue;\n irep = proc->body.irep;\n ci = cipush(mrb);\n ci->mid = ci[-1].mid;\n ci->argc = 0;\n ci->proc = proc;\n ci->stackent = mrb->c->stack;\n ci->nregs = irep->nregs;\n ci->target_class = target_class;\n ci->pc = pc;\n ci->acc = ci[-1].nregs;\n mrb->c->stack += ci->acc;\n stack_extend(mrb, ci->nregs);\n regs[0] = self;\n pc = irep->iseq;\n }\n pool = irep->pool;\n syms = irep->syms;\n mrb->c->eidx = epos;\n JUMP;\n }\n\n CASE(OP_LOADNIL) {\n /* A R(A) := nil */\n int a = GETARG_A(i);\n\n SET_NIL_VALUE(regs[a]);\n NEXT;\n }\n\n CASE(OP_SENDB) {\n /* A B C R(A) := call(R(A),Syms(B),R(A+1),...,R(A+C),&R(A+C+1))*/\n /* fall through */\n };\n\n L_SEND:\n CASE(OP_SEND) {\n /* A B C R(A) := call(R(A),Syms(B),R(A+1),...,R(A+C)) */\n int a = GETARG_A(i);\n int n = GETARG_C(i);\n int argc = (n == CALL_MAXARGS) ? -1 : n;\n int bidx = (argc < 0) ? a+2 : a+n+1;\n mrb_method_t m;\n struct RClass *c;\n mrb_callinfo *ci = mrb->c->ci;\n mrb_value recv, blk;\n mrb_sym mid = syms[GETARG_B(i)];\n\n mrb_assert(bidx < ci->nregs);\n\n recv = regs[a];\n if (GET_OPCODE(i) != OP_SENDB) {\n SET_NIL_VALUE(regs[bidx]);\n blk = regs[bidx];\n }\n else {\n blk = regs[bidx];\n if (!mrb_nil_p(blk) && mrb_type(blk) != MRB_TT_PROC) {\n blk = mrb_convert_type(mrb, blk, MRB_TT_PROC, \"Proc\", \"to_proc\");\n /* The stack might have been reallocated during mrb_convert_type(),\n see #3622 */\n regs[bidx] = blk;\n }\n }\n c = mrb_class(mrb, recv);\n m = mrb_method_search_vm(mrb, &c, mid);\n if (MRB_METHOD_UNDEF_P(m)) {\n mrb_sym missing = mrb_intern_lit(mrb, \"method_missing\");\n m = mrb_method_search_vm(mrb, &c, missing);\n if (MRB_METHOD_UNDEF_P(m) || (missing == mrb->c->ci->mid && mrb_obj_eq(mrb, regs[0], recv))) {\n mrb_value args = (argc < 0) ? regs[a+1] : mrb_ary_new_from_values(mrb, n, regs+a+1);\n ERR_PC_SET(mrb, pc);\n mrb_method_missing(mrb, mid, recv, args);\n }\n if (argc >= 0) {\n if (a+2 >= irep->nregs) {\n stack_extend(mrb, a+3);\n }\n regs[a+1] = mrb_ary_new_from_values(mrb, n, regs+a+1);\n regs[a+2] = blk;\n argc = -1;\n }\n mrb_ary_unshift(mrb, regs[a+1], mrb_symbol_value(mid));\n mid = missing;\n }\n\n /* push callinfo */\n ci = cipush(mrb);\n ci->mid = mid;\n ci->stackent = mrb->c->stack;\n ci->target_class = c;\n ci->argc = argc;\n\n ci->pc = pc + 1;\n ci->acc = a;\n\n /* prepare stack */\n mrb->c->stack += a;\n\n if (MRB_METHOD_CFUNC_P(m)) {\n ci->nregs = (argc < 0) ? 3 : n+2;\n if (MRB_METHOD_PROC_P(m)) {\n struct RProc *p = MRB_METHOD_PROC(m);\n\n ci->proc = p;\n recv = p->body.func(mrb, recv);\n }\n else {\n recv = MRB_METHOD_FUNC(m)(mrb, recv);\n }\n mrb_gc_arena_restore(mrb, ai);\n mrb_gc_arena_shrink(mrb, ai);\n if (mrb->exc) goto L_RAISE;\n ci = mrb->c->ci;\n if (GET_OPCODE(i) == OP_SENDB) {\n if (mrb_type(blk) == MRB_TT_PROC) {\n struct RProc *p = mrb_proc_ptr(blk);\n if (p && !MRB_PROC_STRICT_P(p) && MRB_PROC_ENV(p) == ci[-1].env) {\n p->flags |= MRB_PROC_ORPHAN;\n }\n }\n }\n if (!ci->target_class) { /* return from context modifying method (resume/yield) */\n if (ci->acc == CI_ACC_RESUMED) {\n mrb->jmp = prev_jmp;\n return recv;\n }\n else {\n mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc));\n proc = ci[-1].proc;\n irep = proc->body.irep;\n pool = irep->pool;\n syms = irep->syms;\n }\n }\n mrb->c->stack[0] = recv;\n /* pop stackpos */\n mrb->c->stack = ci->stackent;\n pc = ci->pc;\n cipop(mrb);\n JUMP;\n }\n else {\n /* setup environment for calling method */\n proc = ci->proc = MRB_METHOD_PROC(m);\n irep = proc->body.irep;\n pool = irep->pool;\n syms = irep->syms;\n ci->nregs = irep->nregs;\n stack_extend(mrb, (argc < 0 && ci->nregs < 3) ? 3 : ci->nregs);\n pc = irep->iseq;\n JUMP;\n }\n }\n\n CASE(OP_FSEND) {\n /* A B C R(A) := fcall(R(A),Syms(B),R(A+1),... ,R(A+C-1)) */\n /* not implemented yet */\n NEXT;\n }\n\n CASE(OP_CALL) {\n /* A R(A) := self.call(frame.argc, frame.argv) */\n mrb_callinfo *ci;\n mrb_value recv = mrb->c->stack[0];\n struct RProc *m = mrb_proc_ptr(recv);\n\n /* replace callinfo */\n ci = mrb->c->ci;\n ci->target_class = MRB_PROC_TARGET_CLASS(m);\n ci->proc = m;\n if (MRB_PROC_ENV_P(m)) {\n mrb_sym mid;\n struct REnv *e = MRB_PROC_ENV(m);\n\n mid = e->mid;\n if (mid) ci->mid = mid;\n if (!e->stack) {\n e->stack = mrb->c->stack;\n }\n }\n\n /* prepare stack */\n if (MRB_PROC_CFUNC_P(m)) {\n recv = MRB_PROC_CFUNC(m)(mrb, recv);\n mrb_gc_arena_restore(mrb, ai);\n mrb_gc_arena_shrink(mrb, ai);\n if (mrb->exc) goto L_RAISE;\n /* pop stackpos */\n ci = mrb->c->ci;\n mrb->c->stack = ci->stackent;\n regs[ci->acc] = recv;\n pc = ci->pc;\n cipop(mrb);\n irep = mrb->c->ci->proc->body.irep;\n pool = irep->pool;\n syms = irep->syms;\n JUMP;\n }\n else {\n /* setup environment for calling method */\n proc = m;\n irep = m->body.irep;\n if (!irep) {\n mrb->c->stack[0] = mrb_nil_value();\n goto L_RETURN;\n }\n pool = irep->pool;\n syms = irep->syms;\n ci->nregs = irep->nregs;\n stack_extend(mrb, ci->nregs);\n if (ci->argc < 0) {\n if (irep->nregs > 3) {\n stack_clear(regs+3, irep->nregs-3);\n }\n }\n else if (ci->argc+2 < irep->nregs) {\n stack_clear(regs+ci->argc+2, irep->nregs-ci->argc-2);\n }\n if (MRB_PROC_ENV_P(m)) {\n regs[0] = MRB_PROC_ENV(m)->stack[0];\n }\n pc = irep->iseq;\n JUMP;\n }\n }\n\n CASE(OP_SUPER) {\n /* A C R(A) := super(R(A+1),... ,R(A+C+1)) */\n int a = GETARG_A(i);\n int n = GETARG_C(i);\n int argc = (n == CALL_MAXARGS) ? -1 : n;\n int bidx = (argc < 0) ? a+2 : a+n+1;\n mrb_method_t m;\n struct RClass *c;\n mrb_callinfo *ci = mrb->c->ci;\n mrb_value recv, blk;\n mrb_sym mid = ci->mid;\n struct RClass* target_class = MRB_PROC_TARGET_CLASS(ci->proc);\n\n mrb_assert(bidx < ci->nregs);\n\n if (mid == 0 || !target_class) {\n mrb_value exc = mrb_exc_new_str_lit(mrb, E_NOMETHOD_ERROR, \"super called outside of method\");\n mrb_exc_set(mrb, exc);\n goto L_RAISE;\n }\n if (target_class->tt == MRB_TT_MODULE) {\n target_class = ci->target_class;\n if (target_class->tt != MRB_TT_ICLASS) {\n mrb_value exc = mrb_exc_new_str_lit(mrb, E_RUNTIME_ERROR, \"superclass info lost [mruby limitations]\");\n mrb_exc_set(mrb, exc);\n goto L_RAISE;\n }\n }\n recv = regs[0];\n if (!mrb_obj_is_kind_of(mrb, recv, target_class)) {\n mrb_value exc = mrb_exc_new_str_lit(mrb, E_TYPE_ERROR,\n \"self has wrong type to call super in this context\");\n mrb_exc_set(mrb, exc);\n goto L_RAISE;\n }\n blk = regs[bidx];\n if (!mrb_nil_p(blk) && mrb_type(blk) != MRB_TT_PROC) {\n blk = mrb_convert_type(mrb, blk, MRB_TT_PROC, \"Proc\", \"to_proc\");\n /* The stack or ci stack might have been reallocated during\n mrb_convert_type(), see #3622 and #3784 */\n regs[bidx] = blk;\n ci = mrb->c->ci;\n }\n c = target_class->super;\n m = mrb_method_search_vm(mrb, &c, mid);\n if (MRB_METHOD_UNDEF_P(m)) {\n mrb_sym missing = mrb_intern_lit(mrb, \"method_missing\");\n\n if (mid != missing) {\n c = mrb_class(mrb, recv);\n }\n m = mrb_method_search_vm(mrb, &c, missing);\n if (MRB_METHOD_UNDEF_P(m)) {\n mrb_value args = (argc < 0) ? regs[a+1] : mrb_ary_new_from_values(mrb, n, regs+a+1);\n ERR_PC_SET(mrb, pc);\n mrb_method_missing(mrb, mid, recv, args);\n }\n mid = missing;\n if (argc >= 0) {\n if (a+2 >= ci->nregs) {\n stack_extend(mrb, a+3);\n }\n regs[a+1] = mrb_ary_new_from_values(mrb, n, regs+a+1);\n regs[a+2] = blk;\n argc = -1;\n }\n mrb_ary_unshift(mrb, regs[a+1], mrb_symbol_value(ci->mid));\n }\n\n /* push callinfo */\n ci = cipush(mrb);\n ci->mid = mid;\n ci->stackent = mrb->c->stack;\n ci->target_class = c;\n ci->pc = pc + 1;\n ci->argc = argc;\n\n /* prepare stack */\n mrb->c->stack += a;\n mrb->c->stack[0] = recv;\n\n if (MRB_METHOD_CFUNC_P(m)) {\n mrb_value v;\n ci->nregs = (argc < 0) ? 3 : n+2;\n if (MRB_METHOD_PROC_P(m)) {\n ci->proc = MRB_METHOD_PROC(m);\n }\n v = MRB_METHOD_CFUNC(m)(mrb, recv);\n mrb_gc_arena_restore(mrb, ai);\n if (mrb->exc) goto L_RAISE;\n ci = mrb->c->ci;\n if (!ci->target_class) { /* return from context modifying method (resume/yield) */\n if (ci->acc == CI_ACC_RESUMED) {\n mrb->jmp = prev_jmp;\n return v;\n }\n else {\n mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc));\n proc = ci[-1].proc;\n irep = proc->body.irep;\n pool = irep->pool;\n syms = irep->syms;\n }\n }\n mrb->c->stack[0] = v;\n /* pop stackpos */\n mrb->c->stack = ci->stackent;\n pc = ci->pc;\n cipop(mrb);\n JUMP;\n }\n else {\n /* fill callinfo */\n ci->acc = a;\n\n /* setup environment for calling method */\n proc = ci->proc = MRB_METHOD_PROC(m);\n irep = proc->body.irep;\n pool = irep->pool;\n syms = irep->syms;\n ci->nregs = irep->nregs;\n stack_extend(mrb, (argc < 0 && ci->nregs < 3) ? 3 : ci->nregs);\n pc = irep->iseq;\n JUMP;\n }\n }\n\n CASE(OP_ARGARY) {\n /* A Bx R(A) := argument array (16=6:1:5:4) */\n int a = GETARG_A(i);\n int bx = GETARG_Bx(i);\n int m1 = (bx>>10)&0x3f;\n int r = (bx>>9)&0x1;\n int m2 = (bx>>4)&0x1f;\n int lv = (bx>>0)&0xf;\n mrb_value *stack;\n\n if (mrb->c->ci->mid == 0 || mrb->c->ci->target_class == NULL) {\n mrb_value exc;\n\n L_NOSUPER:\n exc = mrb_exc_new_str_lit(mrb, E_NOMETHOD_ERROR, \"super called outside of method\");\n mrb_exc_set(mrb, exc);\n goto L_RAISE;\n }\n if (lv == 0) stack = regs + 1;\n else {\n struct REnv *e = uvenv(mrb, lv-1);\n if (!e) goto L_NOSUPER;\n if (MRB_ENV_STACK_LEN(e) <= m1+r+m2+1)\n goto L_NOSUPER;\n stack = e->stack + 1;\n }\n if (r == 0) {\n regs[a] = mrb_ary_new_from_values(mrb, m1+m2, stack);\n }\n else {\n mrb_value *pp = NULL;\n struct RArray *rest;\n int len = 0;\n\n if (mrb_array_p(stack[m1])) {\n struct RArray *ary = mrb_ary_ptr(stack[m1]);\n\n pp = ARY_PTR(ary);\n len = (int)ARY_LEN(ary);\n }\n regs[a] = mrb_ary_new_capa(mrb, m1+len+m2);\n rest = mrb_ary_ptr(regs[a]);\n if (m1 > 0) {\n stack_copy(ARY_PTR(rest), stack, m1);\n }\n if (len > 0) {\n stack_copy(ARY_PTR(rest)+m1, pp, len);\n }\n if (m2 > 0) {\n stack_copy(ARY_PTR(rest)+m1+len, stack+m1+1, m2);\n }\n ARY_SET_LEN(rest, m1+len+m2);\n }\n regs[a+1] = stack[m1+r+m2];\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_ENTER) {\n /* Ax arg setup according to flags (23=5:5:1:5:5:1:1) */\n /* number of optional arguments times OP_JMP should follow */\n mrb_aspec ax = GETARG_Ax(i);\n int m1 = MRB_ASPEC_REQ(ax);\n int o = MRB_ASPEC_OPT(ax);\n int r = MRB_ASPEC_REST(ax);\n int m2 = MRB_ASPEC_POST(ax);\n /* unused\n int k = MRB_ASPEC_KEY(ax);\n int kd = MRB_ASPEC_KDICT(ax);\n int b = MRB_ASPEC_BLOCK(ax);\n */\n int argc = mrb->c->ci->argc;\n mrb_value *argv = regs+1;\n mrb_value *argv0 = argv;\n int len = m1 + o + r + m2;\n mrb_value *blk = &argv[argc < 0 ? 1 : argc];\n\n if (argc < 0) {\n struct RArray *ary = mrb_ary_ptr(regs[1]);\n argv = ARY_PTR(ary);\n argc = (int)ARY_LEN(ary);\n mrb_gc_protect(mrb, regs[1]);\n }\n if (mrb->c->ci->proc && MRB_PROC_STRICT_P(mrb->c->ci->proc)) {\n if (argc >= 0) {\n if (argc < m1 + m2 || (r == 0 && argc > len)) {\n argnum_error(mrb, m1+m2);\n goto L_RAISE;\n }\n }\n }\n else if (len > 1 && argc == 1 && mrb_array_p(argv[0])) {\n mrb_gc_protect(mrb, argv[0]);\n argc = (int)RARRAY_LEN(argv[0]);\n argv = RARRAY_PTR(argv[0]);\n }\n if (argc < len) {\n int mlen = m2;\n if (argc < m1+m2) {\n if (m1 < argc)\n mlen = argc - m1;\n else\n mlen = 0;\n }\n regs[len+1] = *blk; /* move block */\n SET_NIL_VALUE(regs[argc+1]);\n if (argv0 != argv) {\n value_move(®s[1], argv, argc-mlen); /* m1 + o */\n }\n if (argc < m1) {\n stack_clear(®s[argc+1], m1-argc);\n }\n if (mlen) {\n value_move(®s[len-m2+1], &argv[argc-mlen], mlen);\n }\n if (mlen < m2) {\n stack_clear(®s[len-m2+mlen+1], m2-mlen);\n }\n if (r) {\n regs[m1+o+1] = mrb_ary_new_capa(mrb, 0);\n }\n if (o == 0 || argc < m1+m2) pc++;\n else\n pc += argc - m1 - m2 + 1;\n }\n else {\n int rnum = 0;\n if (argv0 != argv) {\n regs[len+1] = *blk; /* move block */\n value_move(®s[1], argv, m1+o);\n }\n if (r) {\n rnum = argc-m1-o-m2;\n regs[m1+o+1] = mrb_ary_new_from_values(mrb, rnum, argv+m1+o);\n }\n if (m2) {\n if (argc-m2 > m1) {\n value_move(®s[m1+o+r+1], &argv[m1+o+rnum], m2);\n }\n }\n if (argv0 == argv) {\n regs[len+1] = *blk; /* move block */\n }\n pc += o + 1;\n }\n mrb->c->ci->argc = len;\n /* clear local (but non-argument) variables */\n if (irep->nlocals-len-2 > 0) {\n stack_clear(®s[len+2], irep->nlocals-len-2);\n }\n JUMP;\n }\n\n CASE(OP_KARG) {\n /* A B C R(A) := kdict[Syms(B)]; if C kdict.rm(Syms(B)) */\n /* if C == 2; raise unless kdict.empty? */\n /* OP_JMP should follow to skip init code */\n NEXT;\n }\n\n CASE(OP_KDICT) {\n /* A C R(A) := kdict */\n NEXT;\n }\n\n L_RETURN:\n i = MKOP_AB(OP_RETURN, GETARG_A(i), OP_R_NORMAL);\n /* fall through */\n CASE(OP_RETURN) {\n /* A B return R(A) (B=normal,in-block return/break) */\n mrb_callinfo *ci;\n\n#define ecall_adjust() do {\\\n ptrdiff_t cioff = ci - mrb->c->cibase;\\\n ecall(mrb);\\\n ci = mrb->c->cibase + cioff;\\\n} while (0)\n\n ci = mrb->c->ci;\n if (ci->mid) {\n mrb_value blk;\n\n if (ci->argc < 0) {\n blk = regs[2];\n }\n else {\n blk = regs[ci->argc+1];\n }\n if (mrb_type(blk) == MRB_TT_PROC) {\n struct RProc *p = mrb_proc_ptr(blk);\n\n if (!MRB_PROC_STRICT_P(p) &&\n ci > mrb->c->cibase && MRB_PROC_ENV(p) == ci[-1].env) {\n p->flags |= MRB_PROC_ORPHAN;\n }\n }\n }\n\n if (mrb->exc) {\n mrb_callinfo *ci0;\n\n L_RAISE:\n ci0 = ci = mrb->c->ci;\n if (ci == mrb->c->cibase) {\n if (ci->ridx == 0) goto L_FTOP;\n goto L_RESCUE;\n }\n while (ci[0].ridx == ci[-1].ridx) {\n cipop(mrb);\n mrb->c->stack = ci->stackent;\n if (ci->acc == CI_ACC_SKIP && prev_jmp) {\n mrb->jmp = prev_jmp;\n MRB_THROW(prev_jmp);\n }\n ci = mrb->c->ci;\n if (ci == mrb->c->cibase) {\n if (ci->ridx == 0) {\n L_FTOP: /* fiber top */\n if (mrb->c == mrb->root_c) {\n mrb->c->stack = mrb->c->stbase;\n goto L_STOP;\n }\n else {\n struct mrb_context *c = mrb->c;\n\n while (c->eidx > ci->epos) {\n ecall_adjust();\n }\n if (c->fib) {\n mrb_write_barrier(mrb, (struct RBasic*)c->fib);\n }\n mrb->c->status = MRB_FIBER_TERMINATED;\n mrb->c = c->prev;\n c->prev = NULL;\n goto L_RAISE;\n }\n }\n break;\n }\n /* call ensure only when we skip this callinfo */\n if (ci[0].ridx == ci[-1].ridx) {\n while (mrb->c->eidx > ci->epos) {\n ecall_adjust();\n }\n }\n }\n L_RESCUE:\n if (ci->ridx == 0) goto L_STOP;\n proc = ci->proc;\n irep = proc->body.irep;\n pool = irep->pool;\n syms = irep->syms;\n if (ci < ci0) {\n mrb->c->stack = ci[1].stackent;\n }\n stack_extend(mrb, irep->nregs);\n pc = mrb->c->rescue[--ci->ridx];\n }\n else {\n int acc;\n mrb_value v;\n struct RProc *dst;\n\n ci = mrb->c->ci;\n v = regs[GETARG_A(i)];\n mrb_gc_protect(mrb, v);\n switch (GETARG_B(i)) {\n case OP_R_RETURN:\n /* Fall through to OP_R_NORMAL otherwise */\n if (ci->acc >=0 && MRB_PROC_ENV_P(proc) && !MRB_PROC_STRICT_P(proc)) {\n mrb_callinfo *cibase = mrb->c->cibase;\n dst = top_proc(mrb, proc);\n\n if (MRB_PROC_ENV_P(dst)) {\n struct REnv *e = MRB_PROC_ENV(dst);\n\n if (!MRB_ENV_STACK_SHARED_P(e) || e->cxt != mrb->c) {\n localjump_error(mrb, LOCALJUMP_ERROR_RETURN);\n goto L_RAISE;\n }\n }\n while (cibase <= ci && ci->proc != dst) {\n if (ci->acc < 0) {\n localjump_error(mrb, LOCALJUMP_ERROR_RETURN);\n goto L_RAISE;\n }\n ci--;\n }\n if (ci <= cibase) {\n localjump_error(mrb, LOCALJUMP_ERROR_RETURN);\n goto L_RAISE;\n }\n break;\n }\n case OP_R_NORMAL:\n NORMAL_RETURN:\n if (ci == mrb->c->cibase) {\n struct mrb_context *c;\n\n if (!mrb->c->prev) { /* toplevel return */\n localjump_error(mrb, LOCALJUMP_ERROR_RETURN);\n goto L_RAISE;\n }\n if (mrb->c->prev->ci == mrb->c->prev->cibase) {\n mrb_value exc = mrb_exc_new_str_lit(mrb, E_FIBER_ERROR, \"double resume\");\n mrb_exc_set(mrb, exc);\n goto L_RAISE;\n }\n while (mrb->c->eidx > 0) {\n ecall(mrb);\n }\n /* automatic yield at the end */\n c = mrb->c;\n c->status = MRB_FIBER_TERMINATED;\n mrb->c = c->prev;\n c->prev = NULL;\n mrb->c->status = MRB_FIBER_RUNNING;\n ci = mrb->c->ci;\n }\n break;\n case OP_R_BREAK:\n if (MRB_PROC_STRICT_P(proc)) goto NORMAL_RETURN;\n if (MRB_PROC_ORPHAN_P(proc)) { \n mrb_value exc;\n\n L_BREAK_ERROR:\n exc = mrb_exc_new_str_lit(mrb, E_LOCALJUMP_ERROR,\n \"break from proc-closure\");\n mrb_exc_set(mrb, exc);\n goto L_RAISE;\n }\n if (!MRB_PROC_ENV_P(proc) || !MRB_ENV_STACK_SHARED_P(MRB_PROC_ENV(proc))) {\n goto L_BREAK_ERROR;\n }\n else {\n struct REnv *e = MRB_PROC_ENV(proc);\n\n if (e == mrb->c->cibase->env && proc != mrb->c->cibase->proc) {\n goto L_BREAK_ERROR;\n }\n if (e->cxt != mrb->c) {\n goto L_BREAK_ERROR;\n }\n }\n while (mrb->c->eidx > mrb->c->ci->epos) {\n ecall_adjust();\n }\n /* break from fiber block */\n if (ci == mrb->c->cibase && ci->pc) {\n struct mrb_context *c = mrb->c;\n\n mrb->c = c->prev;\n c->prev = NULL;\n ci = mrb->c->ci;\n }\n if (ci->acc < 0) {\n mrb_gc_arena_restore(mrb, ai);\n mrb->c->vmexec = FALSE;\n mrb->exc = (struct RObject*)break_new(mrb, proc, v);\n mrb->jmp = prev_jmp;\n MRB_THROW(prev_jmp);\n }\n if (FALSE) {\n L_BREAK:\n v = ((struct RBreak*)mrb->exc)->val;\n proc = ((struct RBreak*)mrb->exc)->proc;\n mrb->exc = NULL;\n ci = mrb->c->ci;\n }\n mrb->c->stack = ci->stackent;\n proc = proc->upper;\n while (mrb->c->cibase < ci && ci[-1].proc != proc) {\n if (ci[-1].acc == CI_ACC_SKIP) {\n while (ci < mrb->c->ci) {\n cipop(mrb);\n }\n goto L_BREAK_ERROR;\n }\n ci--;\n }\n if (ci == mrb->c->cibase) {\n goto L_BREAK_ERROR;\n }\n break;\n default:\n /* cannot happen */\n break;\n }\n while (ci < mrb->c->ci) {\n cipop(mrb);\n }\n ci[0].ridx = ci[-1].ridx;\n while (mrb->c->eidx > ci->epos) {\n ecall_adjust();\n }\n if (mrb->c->vmexec && !ci->target_class) {\n mrb_gc_arena_restore(mrb, ai);\n mrb->c->vmexec = FALSE;\n mrb->jmp = prev_jmp;\n return v;\n }\n acc = ci->acc;\n mrb->c->stack = ci->stackent;\n cipop(mrb);\n if (acc == CI_ACC_SKIP || acc == CI_ACC_DIRECT) {\n mrb_gc_arena_restore(mrb, ai);\n mrb->jmp = prev_jmp;\n return v;\n }\n pc = ci->pc;\n ci = mrb->c->ci;\n DEBUG(fprintf(stderr, \"from :%s\\n\", mrb_sym2name(mrb, ci->mid)));\n proc = mrb->c->ci->proc;\n irep = proc->body.irep;\n pool = irep->pool;\n syms = irep->syms;\n\n regs[acc] = v;\n mrb_gc_arena_restore(mrb, ai);\n }\n JUMP;\n }\n\n CASE(OP_TAILCALL) {\n /* A B C return call(R(A),Syms(B),R(A+1),... ,R(A+C+1)) */\n int a = GETARG_A(i);\n int b = GETARG_B(i);\n int n = GETARG_C(i);\n mrb_method_t m;\n struct RClass *c;\n mrb_callinfo *ci;\n mrb_value recv;\n mrb_sym mid = syms[b];\n\n recv = regs[a];\n c = mrb_class(mrb, recv);\n m = mrb_method_search_vm(mrb, &c, mid);\n if (MRB_METHOD_UNDEF_P(m)) {\n mrb_value sym = mrb_symbol_value(mid);\n mrb_sym missing = mrb_intern_lit(mrb, \"method_missing\");\n m = mrb_method_search_vm(mrb, &c, missing);\n if (MRB_METHOD_UNDEF_P(m)) {\n mrb_value args;\n\n if (n == CALL_MAXARGS) {\n args = regs[a+1];\n }\n else {\n args = mrb_ary_new_from_values(mrb, n, regs+a+1);\n }\n ERR_PC_SET(mrb, pc);\n mrb_method_missing(mrb, mid, recv, args);\n }\n mid = missing;\n if (n == CALL_MAXARGS) {\n mrb_ary_unshift(mrb, regs[a+1], sym);\n }\n else {\n value_move(regs+a+2, regs+a+1, ++n);\n regs[a+1] = sym;\n }\n }\n\n /* replace callinfo */\n ci = mrb->c->ci;\n ci->mid = mid;\n ci->target_class = c;\n if (n == CALL_MAXARGS) {\n ci->argc = -1;\n }\n else {\n ci->argc = n;\n }\n\n /* move stack */\n value_move(mrb->c->stack, ®s[a], ci->argc+1);\n\n if (MRB_METHOD_CFUNC_P(m)) {\n mrb_value v = MRB_METHOD_CFUNC(m)(mrb, recv);\n mrb->c->stack[0] = v;\n mrb_gc_arena_restore(mrb, ai);\n goto L_RETURN;\n }\n else {\n /* setup environment for calling method */\n struct RProc *p = MRB_METHOD_PROC(m);\n irep = p->body.irep;\n pool = irep->pool;\n syms = irep->syms;\n if (ci->argc < 0) {\n stack_extend(mrb, (irep->nregs < 3) ? 3 : irep->nregs);\n }\n else {\n stack_extend(mrb, irep->nregs);\n }\n pc = irep->iseq;\n }\n JUMP;\n }\n\n CASE(OP_BLKPUSH) {\n /* A Bx R(A) := block (16=6:1:5:4) */\n int a = GETARG_A(i);\n int bx = GETARG_Bx(i);\n int m1 = (bx>>10)&0x3f;\n int r = (bx>>9)&0x1;\n int m2 = (bx>>4)&0x1f;\n int lv = (bx>>0)&0xf;\n mrb_value *stack;\n\n if (lv == 0) stack = regs + 1;\n else {\n struct REnv *e = uvenv(mrb, lv-1);\n if (!e || (!MRB_ENV_STACK_SHARED_P(e) && e->mid == 0) ||\n MRB_ENV_STACK_LEN(e) <= m1+r+m2+1) {\n localjump_error(mrb, LOCALJUMP_ERROR_YIELD);\n goto L_RAISE;\n }\n stack = e->stack + 1;\n }\n if (mrb_nil_p(stack[m1+r+m2])) {\n localjump_error(mrb, LOCALJUMP_ERROR_YIELD);\n goto L_RAISE;\n }\n regs[a] = stack[m1+r+m2];\n NEXT;\n }\n\n#define TYPES2(a,b) ((((uint16_t)(a))<<8)|(((uint16_t)(b))&0xff))\n#define OP_MATH_BODY(op,v1,v2) do {\\\n v1(regs[a]) = v1(regs[a]) op v2(regs[a+1]);\\\n} while(0)\n\n CASE(OP_ADD) {\n /* A B C R(A) := R(A)+R(A+1) (Syms[B]=:+,C=1)*/\n int a = GETARG_A(i);\n\n /* need to check if op is overridden */\n switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\n case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM):\n {\n mrb_int x, y, z;\n mrb_value *regs_a = regs + a;\n\n x = mrb_fixnum(regs_a[0]);\n y = mrb_fixnum(regs_a[1]);\n if (mrb_int_add_overflow(x, y, &z)) {\n#ifndef MRB_WITHOUT_FLOAT\n SET_FLOAT_VALUE(mrb, regs_a[0], (mrb_float)x + (mrb_float)y);\n break;\n#endif\n }\n SET_INT_VALUE(regs[a], z);\n }\n break;\n#ifndef MRB_WITHOUT_FLOAT\n case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT):\n {\n mrb_int x = mrb_fixnum(regs[a]);\n mrb_float y = mrb_float(regs[a+1]);\n SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x + y);\n }\n break;\n case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM):\n#ifdef MRB_WORD_BOXING\n {\n mrb_float x = mrb_float(regs[a]);\n mrb_int y = mrb_fixnum(regs[a+1]);\n SET_FLOAT_VALUE(mrb, regs[a], x + y);\n }\n#else\n OP_MATH_BODY(+,mrb_float,mrb_fixnum);\n#endif\n break;\n case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\n#ifdef MRB_WORD_BOXING\n {\n mrb_float x = mrb_float(regs[a]);\n mrb_float y = mrb_float(regs[a+1]);\n SET_FLOAT_VALUE(mrb, regs[a], x + y);\n }\n#else\n OP_MATH_BODY(+,mrb_float,mrb_float);\n#endif\n break;\n#endif\n case TYPES2(MRB_TT_STRING,MRB_TT_STRING):\n regs[a] = mrb_str_plus(mrb, regs[a], regs[a+1]);\n break;\n default:\n goto L_SEND;\n }\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_SUB) {\n /* A B C R(A) := R(A)-R(A+1) (Syms[B]=:-,C=1)*/\n int a = GETARG_A(i);\n\n /* need to check if op is overridden */\n switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\n case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM):\n {\n mrb_int x, y, z;\n\n x = mrb_fixnum(regs[a]);\n y = mrb_fixnum(regs[a+1]);\n if (mrb_int_sub_overflow(x, y, &z)) {\n#ifndef MRB_WITHOUT_FLOAT\n SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x - (mrb_float)y);\n break;\n#endif\n }\n SET_INT_VALUE(regs[a], z);\n }\n break;\n#ifndef MRB_WITHOUT_FLOAT\n case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT):\n {\n mrb_int x = mrb_fixnum(regs[a]);\n mrb_float y = mrb_float(regs[a+1]);\n SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x - y);\n }\n break;\n case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM):\n#ifdef MRB_WORD_BOXING\n {\n mrb_float x = mrb_float(regs[a]);\n mrb_int y = mrb_fixnum(regs[a+1]);\n SET_FLOAT_VALUE(mrb, regs[a], x - y);\n }\n#else\n OP_MATH_BODY(-,mrb_float,mrb_fixnum);\n#endif\n break;\n case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\n#ifdef MRB_WORD_BOXING\n {\n mrb_float x = mrb_float(regs[a]);\n mrb_float y = mrb_float(regs[a+1]);\n SET_FLOAT_VALUE(mrb, regs[a], x - y);\n }\n#else\n OP_MATH_BODY(-,mrb_float,mrb_float);\n#endif\n break;\n#endif\n default:\n goto L_SEND;\n }\n NEXT;\n }\n\n CASE(OP_MUL) {\n /* A B C R(A) := R(A)*R(A+1) (Syms[B]=:*,C=1)*/\n int a = GETARG_A(i);\n\n /* need to check if op is overridden */\n switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\n case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM):\n {\n mrb_int x, y, z;\n\n x = mrb_fixnum(regs[a]);\n y = mrb_fixnum(regs[a+1]);\n if (mrb_int_mul_overflow(x, y, &z)) {\n#ifndef MRB_WITHOUT_FLOAT\n SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x * (mrb_float)y);\n break;\n#endif\n }\n SET_INT_VALUE(regs[a], z);\n }\n break;\n#ifndef MRB_WITHOUT_FLOAT\n case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT):\n {\n mrb_int x = mrb_fixnum(regs[a]);\n mrb_float y = mrb_float(regs[a+1]);\n SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x * y);\n }\n break;\n case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM):\n#ifdef MRB_WORD_BOXING\n {\n mrb_float x = mrb_float(regs[a]);\n mrb_int y = mrb_fixnum(regs[a+1]);\n SET_FLOAT_VALUE(mrb, regs[a], x * y);\n }\n#else\n OP_MATH_BODY(*,mrb_float,mrb_fixnum);\n#endif\n break;\n case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\n#ifdef MRB_WORD_BOXING\n {\n mrb_float x = mrb_float(regs[a]);\n mrb_float y = mrb_float(regs[a+1]);\n SET_FLOAT_VALUE(mrb, regs[a], x * y);\n }\n#else\n OP_MATH_BODY(*,mrb_float,mrb_float);\n#endif\n break;\n#endif\n default:\n goto L_SEND;\n }\n NEXT;\n }\n\n CASE(OP_DIV) {\n /* A B C R(A) := R(A)/R(A+1) (Syms[B]=:/,C=1)*/\n int a = GETARG_A(i);\n#ifndef MRB_WITHOUT_FLOAT\n double x, y, f;\n#endif\n\n /* need to check if op is overridden */\n switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\n case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM):\n#ifdef MRB_WITHOUT_FLOAT\n {\n mrb_int x = mrb_fixnum(regs[a]);\n mrb_int y = mrb_fixnum(regs[a+1]);\n SET_INT_VALUE(regs[a], y ? x / y : 0);\n }\n break;\n#else\n x = (mrb_float)mrb_fixnum(regs[a]);\n y = (mrb_float)mrb_fixnum(regs[a+1]);\n break;\n case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT):\n x = (mrb_float)mrb_fixnum(regs[a]);\n y = mrb_float(regs[a+1]);\n break;\n case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM):\n x = mrb_float(regs[a]);\n y = (mrb_float)mrb_fixnum(regs[a+1]);\n break;\n case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\n x = mrb_float(regs[a]);\n y = mrb_float(regs[a+1]);\n break;\n#endif\n default:\n goto L_SEND;\n }\n\n#ifndef MRB_WITHOUT_FLOAT\n if (y == 0) {\n if (x > 0) f = INFINITY;\n else if (x < 0) f = -INFINITY;\n else /* if (x == 0) */ f = NAN;\n }\n else {\n f = x / y;\n }\n SET_FLOAT_VALUE(mrb, regs[a], f);\n#endif\n NEXT;\n }\n\n CASE(OP_ADDI) {\n /* A B C R(A) := R(A)+C (Syms[B]=:+)*/\n int a = GETARG_A(i);\n\n /* need to check if + is overridden */\n switch (mrb_type(regs[a])) {\n case MRB_TT_FIXNUM:\n {\n mrb_int x = mrb_fixnum(regs[a]);\n mrb_int y = GETARG_C(i);\n mrb_int z;\n\n if (mrb_int_add_overflow(x, y, &z)) {\n#ifndef MRB_WITHOUT_FLOAT\n SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x + (mrb_float)y);\n break;\n#endif\n }\n SET_INT_VALUE(regs[a], z);\n }\n break;\n#ifndef MRB_WITHOUT_FLOAT\n case MRB_TT_FLOAT:\n#ifdef MRB_WORD_BOXING\n {\n mrb_float x = mrb_float(regs[a]);\n SET_FLOAT_VALUE(mrb, regs[a], x + GETARG_C(i));\n }\n#else\n mrb_float(regs[a]) += GETARG_C(i);\n#endif\n break;\n#endif\n default:\n SET_INT_VALUE(regs[a+1], GETARG_C(i));\n i = MKOP_ABC(OP_SEND, a, GETARG_B(i), 1);\n goto L_SEND;\n }\n NEXT;\n }\n\n CASE(OP_SUBI) {\n /* A B C R(A) := R(A)-C (Syms[B]=:-)*/\n int a = GETARG_A(i);\n mrb_value *regs_a = regs + a;\n\n /* need to check if + is overridden */\n switch (mrb_type(regs_a[0])) {\n case MRB_TT_FIXNUM:\n {\n mrb_int x = mrb_fixnum(regs_a[0]);\n mrb_int y = GETARG_C(i);\n mrb_int z;\n\n if (mrb_int_sub_overflow(x, y, &z)) {\n#ifndef MRB_WITHOUT_FLOAT\n SET_FLOAT_VALUE(mrb, regs_a[0], (mrb_float)x - (mrb_float)y);\n break;\n#endif\n }\n SET_INT_VALUE(regs_a[0], z);\n }\n break;\n#ifndef MRB_WITHOUT_FLOAT\n case MRB_TT_FLOAT:\n#ifdef MRB_WORD_BOXING\n {\n mrb_float x = mrb_float(regs[a]);\n SET_FLOAT_VALUE(mrb, regs[a], x - GETARG_C(i));\n }\n#else\n mrb_float(regs_a[0]) -= GETARG_C(i);\n#endif\n break;\n#endif\n default:\n SET_INT_VALUE(regs_a[1], GETARG_C(i));\n i = MKOP_ABC(OP_SEND, a, GETARG_B(i), 1);\n goto L_SEND;\n }\n NEXT;\n }\n\n#define OP_CMP_BODY(op,v1,v2) (v1(regs[a]) op v2(regs[a+1]))\n\n#ifdef MRB_WITHOUT_FLOAT\n#define OP_CMP(op) do {\\\n int result;\\\n /* need to check if - is overridden */\\\n switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\\\n case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM):\\\n result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\\\n break;\\\n default:\\\n goto L_SEND;\\\n }\\\n if (result) {\\\n SET_TRUE_VALUE(regs[a]);\\\n }\\\n else {\\\n SET_FALSE_VALUE(regs[a]);\\\n }\\\n} while(0)\n#else\n#define OP_CMP(op) do {\\\n int result;\\\n /* need to check if - is overridden */\\\n switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\\\n case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM):\\\n result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\\\n break;\\\n case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT):\\\n result = OP_CMP_BODY(op,mrb_fixnum,mrb_float);\\\n break;\\\n case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM):\\\n result = OP_CMP_BODY(op,mrb_float,mrb_fixnum);\\\n break;\\\n case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\\\n result = OP_CMP_BODY(op,mrb_float,mrb_float);\\\n break;\\\n default:\\\n goto L_SEND;\\\n }\\\n if (result) {\\\n SET_TRUE_VALUE(regs[a]);\\\n }\\\n else {\\\n SET_FALSE_VALUE(regs[a]);\\\n }\\\n} while(0)\n#endif\n\n CASE(OP_EQ) {\n /* A B C R(A) := R(A)==R(A+1) (Syms[B]=:==,C=1)*/\n int a = GETARG_A(i);\n if (mrb_obj_eq(mrb, regs[a], regs[a+1])) {\n SET_TRUE_VALUE(regs[a]);\n }\n else {\n OP_CMP(==);\n }\n NEXT;\n }\n\n CASE(OP_LT) {\n /* A B C R(A) := R(A)R(A+1) (Syms[B]=:>,C=1)*/\n int a = GETARG_A(i);\n OP_CMP(>);\n NEXT;\n }\n\n CASE(OP_GE) {\n /* A B C R(A) := R(A)>=R(A+1) (Syms[B]=:>=,C=1)*/\n int a = GETARG_A(i);\n OP_CMP(>=);\n NEXT;\n }\n\n CASE(OP_ARRAY) {\n /* A B C R(A) := ary_new(R(B),R(B+1)..R(B+C)) */\n int a = GETARG_A(i);\n int b = GETARG_B(i);\n int c = GETARG_C(i);\n mrb_value v = mrb_ary_new_from_values(mrb, c, ®s[b]);\n regs[a] = v;\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_ARYCAT) {\n /* A B mrb_ary_concat(R(A),R(B)) */\n int a = GETARG_A(i);\n int b = GETARG_B(i);\n mrb_value splat = mrb_ary_splat(mrb, regs[b]);\n mrb_ary_concat(mrb, regs[a], splat);\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_ARYPUSH) {\n /* A B R(A).push(R(B)) */\n int a = GETARG_A(i);\n int b = GETARG_B(i);\n mrb_ary_push(mrb, regs[a], regs[b]);\n NEXT;\n }\n\n CASE(OP_AREF) {\n /* A B C R(A) := R(B)[C] */\n int a = GETARG_A(i);\n int b = GETARG_B(i);\n int c = GETARG_C(i);\n mrb_value v = regs[b];\n\n if (!mrb_array_p(v)) {\n if (c == 0) {\n regs[a] = v;\n }\n else {\n SET_NIL_VALUE(regs[a]);\n }\n }\n else {\n v = mrb_ary_ref(mrb, v, c);\n regs[a] = v;\n }\n NEXT;\n }\n\n CASE(OP_ASET) {\n /* A B C R(B)[C] := R(A) */\n int a = GETARG_A(i);\n int b = GETARG_B(i);\n int c = GETARG_C(i);\n mrb_ary_set(mrb, regs[b], c, regs[a]);\n NEXT;\n }\n\n CASE(OP_APOST) {\n /* A B C *R(A),R(A+1)..R(A+C) := R(A) */\n int a = GETARG_A(i);\n mrb_value v = regs[a];\n int pre = GETARG_B(i);\n int post = GETARG_C(i);\n struct RArray *ary;\n int len, idx;\n\n if (!mrb_array_p(v)) {\n v = mrb_ary_new_from_values(mrb, 1, ®s[a]);\n }\n ary = mrb_ary_ptr(v);\n len = (int)ARY_LEN(ary);\n if (len > pre + post) {\n v = mrb_ary_new_from_values(mrb, len - pre - post, ARY_PTR(ary)+pre);\n regs[a++] = v;\n while (post--) {\n regs[a++] = ARY_PTR(ary)[len-post-1];\n }\n }\n else {\n v = mrb_ary_new_capa(mrb, 0);\n regs[a++] = v;\n for (idx=0; idx+prereps[b];\n\n if (c & OP_L_CAPTURE) {\n p = mrb_closure_new(mrb, nirep);\n }\n else {\n p = mrb_proc_new(mrb, nirep);\n p->flags |= MRB_PROC_SCOPE;\n }\n if (c & OP_L_STRICT) p->flags |= MRB_PROC_STRICT;\n regs[a] = mrb_obj_value(p);\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_OCLASS) {\n /* A R(A) := ::Object */\n regs[GETARG_A(i)] = mrb_obj_value(mrb->object_class);\n NEXT;\n }\n\n CASE(OP_CLASS) {\n /* A B R(A) := newclass(R(A),Syms(B),R(A+1)) */\n struct RClass *c = 0, *baseclass;\n int a = GETARG_A(i);\n mrb_value base, super;\n mrb_sym id = syms[GETARG_B(i)];\n\n base = regs[a];\n super = regs[a+1];\n if (mrb_nil_p(base)) {\n baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc);\n base = mrb_obj_value(baseclass);\n }\n c = mrb_vm_define_class(mrb, base, super, id);\n regs[a] = mrb_obj_value(c);\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_MODULE) {\n /* A B R(A) := newmodule(R(A),Syms(B)) */\n struct RClass *c = 0, *baseclass;\n int a = GETARG_A(i);\n mrb_value base;\n mrb_sym id = syms[GETARG_B(i)];\n\n base = regs[a];\n if (mrb_nil_p(base)) {\n baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc);\n base = mrb_obj_value(baseclass);\n }\n c = mrb_vm_define_module(mrb, base, id);\n regs[a] = mrb_obj_value(c);\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_EXEC) {\n /* A Bx R(A) := blockexec(R(A),SEQ[Bx]) */\n int a = GETARG_A(i);\n int bx = GETARG_Bx(i);\n mrb_callinfo *ci;\n mrb_value recv = regs[a];\n struct RProc *p;\n mrb_irep *nirep = irep->reps[bx];\n\n /* prepare closure */\n p = mrb_proc_new(mrb, nirep);\n p->c = NULL;\n mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)proc);\n MRB_PROC_SET_TARGET_CLASS(p, mrb_class_ptr(recv));\n p->flags |= MRB_PROC_SCOPE;\n\n /* prepare call stack */\n ci = cipush(mrb);\n ci->pc = pc + 1;\n ci->acc = a;\n ci->mid = 0;\n ci->stackent = mrb->c->stack;\n ci->argc = 0;\n ci->target_class = mrb_class_ptr(recv);\n\n /* prepare stack */\n mrb->c->stack += a;\n\n /* setup block to call */\n ci->proc = p;\n\n irep = p->body.irep;\n pool = irep->pool;\n syms = irep->syms;\n ci->nregs = irep->nregs;\n stack_extend(mrb, ci->nregs);\n stack_clear(regs+1, ci->nregs-1);\n pc = irep->iseq;\n JUMP;\n }\n\n CASE(OP_METHOD) {\n /* A B R(A).newmethod(Syms(B),R(A+1)) */\n int a = GETARG_A(i);\n struct RClass *c = mrb_class_ptr(regs[a]);\n struct RProc *p = mrb_proc_ptr(regs[a+1]);\n mrb_method_t m;\n\n MRB_METHOD_FROM_PROC(m, p);\n mrb_define_method_raw(mrb, c, syms[GETARG_B(i)], m);\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_SCLASS) {\n /* A B R(A) := R(B).singleton_class */\n int a = GETARG_A(i);\n int b = GETARG_B(i);\n\n regs[a] = mrb_singleton_class(mrb, regs[b]);\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_TCLASS) {\n /* A R(A) := target_class */\n if (!mrb->c->ci->target_class) {\n mrb_value exc = mrb_exc_new_str_lit(mrb, E_TYPE_ERROR, \"no target class or module\");\n mrb_exc_set(mrb, exc);\n goto L_RAISE;\n }\n regs[GETARG_A(i)] = mrb_obj_value(mrb->c->ci->target_class);\n NEXT;\n }\n\n CASE(OP_RANGE) {\n /* A B C R(A) := range_new(R(B),R(B+1),C) */\n int b = GETARG_B(i);\n mrb_value val = mrb_range_new(mrb, regs[b], regs[b+1], GETARG_C(i));\n regs[GETARG_A(i)] = val;\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_DEBUG) {\n /* A B C debug print R(A),R(B),R(C) */\n#ifdef MRB_ENABLE_DEBUG_HOOK\n mrb->debug_op_hook(mrb, irep, pc, regs);\n#else\n#ifndef MRB_DISABLE_STDIO\n printf(\"OP_DEBUG %d %d %d\\n\", GETARG_A(i), GETARG_B(i), GETARG_C(i));\n#else\n abort();\n#endif\n#endif\n NEXT;\n }\n\n CASE(OP_STOP) {\n /* stop VM */\n L_STOP:\n while (mrb->c->eidx > 0) {\n ecall(mrb);\n }\n ERR_PC_CLR(mrb);\n mrb->jmp = prev_jmp;\n if (mrb->exc) {\n return mrb_obj_value(mrb->exc);\n }\n return regs[irep->nlocals];\n }\n\n CASE(OP_ERR) {\n /* Bx raise RuntimeError with message Lit(Bx) */\n mrb_value msg = mrb_str_dup(mrb, pool[GETARG_Bx(i)]);\n mrb_value exc;\n\n if (GETARG_A(i) == 0) {\n exc = mrb_exc_new_str(mrb, E_RUNTIME_ERROR, msg);\n }\n else {\n exc = mrb_exc_new_str(mrb, E_LOCALJUMP_ERROR, msg);\n }\n ERR_PC_SET(mrb, pc);\n mrb_exc_set(mrb, exc);\n goto L_RAISE;\n }\n }\n END_DISPATCH;\n#undef regs\n\n }\n MRB_CATCH(&c_jmp) {\n exc_catched = TRUE;\n goto RETRY_TRY_BLOCK;\n }\n MRB_END_EXC(&c_jmp);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-190'], 'message': 'Check length of env stack before accessing upvar; fix #3995'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: _dwarf_internal_get_pubnames_like_data(Dwarf_Debug dbg,\n const char *secname,\n Dwarf_Small * section_data_ptr,\n Dwarf_Unsigned section_length,\n Dwarf_Global ** globals,\n Dwarf_Signed * return_count,\n Dwarf_Error * error,\n int context_DLA_code,\n int global_DLA_code,\n int length_err_num,\n int version_err_num)\n{\n Dwarf_Small *pubnames_like_ptr = 0;\n Dwarf_Off pubnames_section_offset = 0;\n Dwarf_Small *section_end_ptr = section_data_ptr +section_length;\n\n /* Points to the context for the current set of global names, and\n contains information to identify the compilation-unit that the\n set refers to. */\n Dwarf_Global_Context pubnames_context = 0;\n Dwarf_Bool pubnames_context_on_list = FALSE;\n\n Dwarf_Unsigned version = 0;\n\n /* Offset from the start of compilation-unit for the current\n global. */\n Dwarf_Off die_offset_in_cu = 0;\n\n Dwarf_Unsigned global_count = 0;\n\n /* Used to chain the Dwarf_Global_s structs for\n creating contiguous list of pointers to the structs. */\n Dwarf_Chain head_chain = 0;\n Dwarf_Chain *plast_chain = &head_chain;\n\n /* Points to contiguous block of Dwarf_Global to be returned. */\n Dwarf_Global *ret_globals = 0;\n int mres = 0;\n\n /* Temporary counter. */\n Dwarf_Unsigned i = 0;\n\n if (!dbg || dbg->de_magic != DBG_IS_VALID) {\n _dwarf_error_string(NULL, error, DW_DLE_DBG_NULL,\n \"DW_DLE_DBG_NULL: \"\n \"calling for pubnames-like data Dwarf_Debug \"\n \"either null or it contains\"\n \"a stale Dwarf_Debug pointer\");\n return DW_DLV_ERROR;\n }\n /* We will eventually need the .debug_info data. Load it now. */\n if (!dbg->de_debug_info.dss_data) {\n int res = _dwarf_load_debug_info(dbg, error);\n\n if (res != DW_DLV_OK) {\n return res;\n }\n }\n if (section_data_ptr == NULL) {\n return DW_DLV_NO_ENTRY;\n }\n pubnames_like_ptr = section_data_ptr;\n do {\n Dwarf_Unsigned length = 0;\n int local_extension_size = 0;\n int local_length_size = 0;\n\n /* Some compilers emit padding at the end of each cu's area.\n pubnames_ptr_past_end_cu records the true area end for the\n pubnames(like) content of a cu.\n Essentially the length in the header and the 0\n terminator of the data are redundant information. The\n dwarf2/3 spec does not mention what to do if the length is\n past the 0 terminator. So we take any bytes left\n after the 0 as padding and ignore them. */\n Dwarf_Small *pubnames_ptr_past_end_cu = 0;\n\n pubnames_context_on_list = FALSE;\n pubnames_context = (Dwarf_Global_Context)\n _dwarf_get_alloc(dbg, context_DLA_code, 1);\n if (pubnames_context == NULL) {\n dealloc_globals_chain(dbg,head_chain);\n _dwarf_error(dbg, error, DW_DLE_ALLOC_FAIL);\n return DW_DLV_ERROR;\n }\n /* ========pubnames_context not recorded anywhere yet. */\n /* READ_AREA_LENGTH updates pubnames_like_ptr for consumed\n bytes. */\n if ((pubnames_like_ptr + DWARF_32BIT_SIZE +\n DWARF_HALF_SIZE + DWARF_32BIT_SIZE) >\n /* A minimum size needed */\n section_end_ptr) {\n pubnames_error_length(dbg,error,\n DWARF_32BIT_SIZE + DWARF_HALF_SIZE + DWARF_32BIT_SIZE,\n secname,\n \"header-record\");\n dealloc_globals_chain(dbg,head_chain);\n if (!pubnames_context_on_list) {\n dwarf_dealloc(dbg,pubnames_context,context_DLA_code);\n }\n return DW_DLV_ERROR;\n }\n mres = _dwarf_read_area_length_ck_wrapper(dbg,\n &length,&pubnames_like_ptr,&local_length_size,\n &local_extension_size,section_length,section_end_ptr,\n error);\n if (mres != DW_DLV_OK) {\n dealloc_globals_chain(dbg,head_chain);\n if (!pubnames_context_on_list) {\n dwarf_dealloc(dbg,pubnames_context,context_DLA_code);\n }\n return mres;\n }\n pubnames_context->pu_alloc_type = context_DLA_code;\n pubnames_context->pu_length_size = local_length_size;\n pubnames_context->pu_length = length;\n pubnames_context->pu_extension_size = local_extension_size;\n pubnames_context->pu_dbg = dbg;\n pubnames_context->pu_pub_offset = pubnames_section_offset;\n pubnames_ptr_past_end_cu = pubnames_like_ptr + length;\n pubnames_context->pu_pub_entries_end_ptr =\n pubnames_ptr_past_end_cu;\n\n if ((pubnames_like_ptr + (DWARF_HALF_SIZE) ) >\n /* A minimum size needed */\n section_end_ptr) {\n pubnames_error_length(dbg,error,\n DWARF_HALF_SIZE,\n secname,\"version-number\");\n dealloc_globals_chain(dbg,head_chain);\n if (!pubnames_context_on_list) {\n dwarf_dealloc(dbg,pubnames_context,context_DLA_code);\n }\n return DW_DLV_ERROR;\n }\n mres = _dwarf_read_unaligned_ck_wrapper(dbg,\n &version,pubnames_like_ptr,DWARF_HALF_SIZE,\n section_end_ptr,error);\n if (mres != DW_DLV_OK) {\n dealloc_globals_chain(dbg,head_chain);\n if (!pubnames_context_on_list) {\n dwarf_dealloc(dbg,pubnames_context,context_DLA_code);\n }\n return mres;\n }\n pubnames_context->pu_version = version;\n pubnames_like_ptr += DWARF_HALF_SIZE;\n /* ASSERT: DW_PUBNAMES_VERSION2 == DW_PUBTYPES_VERSION2 */\n if (version != DW_PUBNAMES_VERSION2) {\n dealloc_globals_chain(dbg,head_chain);\n if (!pubnames_context_on_list) {\n dwarf_dealloc(dbg,pubnames_context,context_DLA_code);\n }\n _dwarf_error(dbg, error, version_err_num);\n return DW_DLV_ERROR;\n }\n\n /* Offset of CU header in debug section. */\n if ((pubnames_like_ptr + 3*pubnames_context->pu_length_size)>\n section_end_ptr) {\n pubnames_error_length(dbg,error,\n 3*pubnames_context->pu_length_size,\n secname,\n \"header/DIE offsets\");\n dealloc_globals_chain(dbg,head_chain);\n if (!pubnames_context_on_list) {\n dwarf_dealloc(dbg,pubnames_context,context_DLA_code);\n }\n return DW_DLV_ERROR;\n }\n mres = _dwarf_read_unaligned_ck_wrapper(dbg,\n &pubnames_context->pu_offset_of_cu_header,\n pubnames_like_ptr,\n pubnames_context->pu_length_size,\n section_end_ptr,error);\n if (mres != DW_DLV_OK) {\n dealloc_globals_chain(dbg,head_chain);\n if (!pubnames_context_on_list) {\n dwarf_dealloc(dbg,pubnames_context,context_DLA_code);\n }\n return mres;\n }\n\n pubnames_like_ptr += pubnames_context->pu_length_size;\n\n FIX_UP_OFFSET_IRIX_BUG(dbg,\n pubnames_context->pu_offset_of_cu_header,\n \"pubnames cu header offset\");\n mres = _dwarf_read_unaligned_ck_wrapper(dbg,\n &pubnames_context->pu_info_length,\n pubnames_like_ptr,\n pubnames_context->pu_length_size,\n section_end_ptr,error);\n if (mres != DW_DLV_OK) {\n dealloc_globals_chain(dbg,head_chain);\n if (!pubnames_context_on_list) {\n dwarf_dealloc(dbg,pubnames_context,context_DLA_code);\n }\n return mres;\n }\n pubnames_like_ptr += pubnames_context->pu_length_size;\n\n if (pubnames_like_ptr > (section_data_ptr + section_length)) {\n dealloc_globals_chain(dbg,head_chain);\n if (!pubnames_context_on_list) {\n dwarf_dealloc(dbg,pubnames_context,context_DLA_code);\n }\n _dwarf_error(dbg, error, length_err_num);\n return DW_DLV_ERROR;\n }\n\n /* ====begin pubname */\n /* Read initial offset (of DIE within CU) of a pubname, final\n entry is not a pair, just a zero offset. */\n mres = _dwarf_read_unaligned_ck_wrapper(dbg,\n &die_offset_in_cu,\n pubnames_like_ptr,\n pubnames_context->pu_length_size,\n pubnames_context->pu_pub_entries_end_ptr,error);\n if (mres != DW_DLV_OK) {\n dealloc_globals_chain(dbg,head_chain);\n if (!pubnames_context_on_list) {\n dwarf_dealloc(dbg,pubnames_context,context_DLA_code);\n }\n return mres;\n }\n pubnames_like_ptr += pubnames_context->pu_length_size;\n FIX_UP_OFFSET_IRIX_BUG(dbg,\n die_offset_in_cu, \"offset of die in cu\");\n if (pubnames_like_ptr > (section_data_ptr + section_length)) {\n dealloc_globals_chain(dbg,head_chain);\n if (!pubnames_context_on_list) {\n dwarf_dealloc(dbg,pubnames_context,context_DLA_code);\n }\n _dwarf_error(dbg, error, length_err_num);\n return DW_DLV_ERROR;\n }\n\n /* Loop thru pairs. DIE off with CU followed by string. */\n if (!die_offset_in_cu) {\n if (dbg->de_return_empty_pubnames) {\n int res = 0;\n\n /* Here we have a pubnames CU with no actual\n entries so we fake up an entry to hold the\n header data. There are no 'pairs' here,\n just the end of list zero value. We do this\n only if de_return_empty_pubnames is set\n so that we by default return exactly the same\n data this always returned, yet dwarfdump can\n request the empty-cu records get created\n to test that feature.\n see dwarf_get_globals_header() */\n res = _dwarf_make_global_add_to_chain(dbg,\n global_DLA_code,\n pubnames_context,\n die_offset_in_cu,\n /* It is a fake global, so empty name */\n (unsigned char *)\"\",\n &global_count,\n &pubnames_context_on_list,\n &plast_chain,\n error);\n if (res != DW_DLV_OK) {\n dealloc_globals_chain(dbg,head_chain);\n if (!pubnames_context_on_list) {\n dwarf_dealloc(dbg,pubnames_context,\n context_DLA_code);\n }\n return res;\n }\n /* ========pubnames_context recorded in chain. */\n } else {\n /* The section is empty.\n Nowhere to record pubnames_context); */\n dwarf_dealloc(dbg,pubnames_context,context_DLA_code);\n pubnames_context = 0;\n continue;\n }\n }\n while (die_offset_in_cu) {\n int res = 0;\n unsigned char *glname = 0;\n\n /* non-zero die_offset_in_cu already read, so\n pubnames_like_ptr points to a string. */\n res = _dwarf_check_string_valid(dbg,section_data_ptr,\n pubnames_like_ptr,\n pubnames_context->pu_pub_entries_end_ptr,\n DW_DLE_STRING_OFF_END_PUBNAMES_LIKE,error);\n if (res != DW_DLV_OK) {\n dealloc_globals_chain(dbg,head_chain);\n if (!pubnames_context_on_list) {\n dwarf_dealloc(dbg,pubnames_context,\n context_DLA_code);\n }\n return res;\n }\n glname = (unsigned char *)pubnames_like_ptr;\n pubnames_like_ptr = pubnames_like_ptr +\n strlen((char *) pubnames_like_ptr) + 1;\n /* Already read offset and verified string, glname\n now points to the string. */\n res = _dwarf_make_global_add_to_chain(dbg,\n global_DLA_code,\n pubnames_context,\n die_offset_in_cu,\n glname,\n &global_count,\n &pubnames_context_on_list,\n &plast_chain,\n error);\n if (res != DW_DLV_OK) {\n dealloc_globals_chain(dbg,head_chain);\n if (!pubnames_context_on_list) {\n dwarf_dealloc(dbg,pubnames_context,\n context_DLA_code);\n }\n return res;\n }\n /* ========pubnames_context recorded in chain. */\n /* Ensure room for a next entry to exist. */\n if ((pubnames_like_ptr +\n pubnames_context->pu_length_size ) >\n section_end_ptr) {\n pubnames_error_length(dbg,error,\n 2*pubnames_context->pu_length_size,\n secname,\n \"global record offset\");\n dealloc_globals_chain(dbg,head_chain);\n if (!pubnames_context_on_list) {\n dwarf_dealloc(dbg,pubnames_context,\n context_DLA_code);\n }\n return DW_DLV_ERROR;\n }\n /* Read die offset for the *next* entry */\n mres = _dwarf_read_unaligned_ck_wrapper(dbg,\n &die_offset_in_cu,\n pubnames_like_ptr,\n pubnames_context->pu_length_size,\n pubnames_context->pu_pub_entries_end_ptr,\n error);\n if (mres != DW_DLV_OK) {\n if (!pubnames_context_on_list) {\n dwarf_dealloc(dbg,pubnames_context,\n context_DLA_code);\n }\n dealloc_globals_chain(dbg,head_chain);\n return mres;\n }\n pubnames_like_ptr += pubnames_context->pu_length_size;\n FIX_UP_OFFSET_IRIX_BUG(dbg,\n die_offset_in_cu, \"offset of next die in cu\");\n if (pubnames_like_ptr >\n (section_data_ptr + section_length)) {\n if (!pubnames_context_on_list) {\n dwarf_dealloc(dbg,pubnames_context,\n context_DLA_code);\n }\n dealloc_globals_chain(dbg,head_chain);\n _dwarf_error(dbg, error, length_err_num);\n return DW_DLV_ERROR;\n }\n }\n /* ASSERT: die_offset_in_cu == 0 */\n if (pubnames_like_ptr > pubnames_ptr_past_end_cu) {\n /* This is some kind of error. This simply cannot happen.\n The encoding is wrong or the length in the header for\n this cu's contribution is wrong. */\n _dwarf_error(dbg, error, length_err_num);\n if (!pubnames_context_on_list) {\n dwarf_dealloc(dbg,pubnames_context,context_DLA_code);\n }\n dealloc_globals_chain(dbg,head_chain);\n return DW_DLV_ERROR;\n }\n /* If there is some kind of padding at the end of\n the section,\n as emitted by some compilers, skip over that padding and\n simply ignore the bytes thus passed-over. With most\n compilers, pubnames_like_ptr ==\n pubnames_ptr_past_end_cu at this point */\n {\n Dwarf_Unsigned increment =\n pubnames_context->pu_length_size +\n pubnames_context->pu_length +\n pubnames_context->pu_extension_size;\n pubnames_section_offset += increment;\n }\n pubnames_like_ptr = pubnames_ptr_past_end_cu;\n } while (pubnames_like_ptr < section_end_ptr);\n\n /* Points to contiguous block of Dwarf_Global. */\n ret_globals = (Dwarf_Global *)\n _dwarf_get_alloc(dbg, DW_DLA_LIST, global_count);\n if (ret_globals == NULL) {\n if (!pubnames_context_on_list) {\n dwarf_dealloc(dbg,pubnames_context,context_DLA_code);\n }\n dealloc_globals_chain(dbg,head_chain);\n _dwarf_error(dbg, error, DW_DLE_ALLOC_FAIL);\n return DW_DLV_ERROR;\n }\n\n /* Store pointers to Dwarf_Global_s structs in contiguous block,\n and deallocate the chain. This ignores the various\n headers */\n {\n Dwarf_Chain curr_chain = 0;\n curr_chain = head_chain;\n for (i = 0; i < global_count; i++) {\n Dwarf_Chain prev = 0;\n\n *(ret_globals + i) = curr_chain->ch_item;\n prev = curr_chain;\n curr_chain = curr_chain->ch_next;\n prev->ch_item = 0; /* Not actually necessary. */\n dwarf_dealloc(dbg, prev, DW_DLA_CHAIN);\n }\n }\n *globals = ret_globals;\n *return_count = (Dwarf_Signed) global_count;\n return DW_DLV_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-125'], 'message': 'Fixes vulnerability DW202205-001\nReports error instead of crashing the when reading\na specially crafted (corrupted) .debug_pubnames\nor .debug_pubtypes section.\n\tmodified: src/lib/libdwarf/dwarf_global.c'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static Image *ReadOneJNGImage(MngInfo *mng_info,\n const ImageInfo *image_info, ExceptionInfo *exception)\n{\n Image\n *alpha_image,\n *color_image,\n *image,\n *jng_image;\n\n ImageInfo\n *alpha_image_info,\n *color_image_info;\n\n MagickBooleanType\n logging;\n\n ssize_t\n y;\n\n MagickBooleanType\n status;\n\n png_uint_32\n jng_height,\n jng_width;\n\n png_byte\n jng_color_type,\n jng_image_sample_depth,\n jng_image_compression_method,\n jng_image_interlace_method,\n jng_alpha_sample_depth,\n jng_alpha_compression_method,\n jng_alpha_filter_method,\n jng_alpha_interlace_method;\n\n register const Quantum\n *s;\n\n register ssize_t\n i,\n x;\n\n register Quantum\n *q;\n\n register unsigned char\n *p;\n\n unsigned int\n read_JSEP,\n reading_idat;\n\n size_t\n length;\n\n jng_alpha_compression_method=0;\n jng_alpha_sample_depth=8;\n jng_color_type=0;\n jng_height=0;\n jng_width=0;\n alpha_image=(Image *) NULL;\n color_image=(Image *) NULL;\n alpha_image_info=(ImageInfo *) NULL;\n color_image_info=(ImageInfo *) NULL;\n\n logging=LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Enter ReadOneJNGImage()\");\n\n image=mng_info->image;\n\n if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)\n {\n /*\n Allocate next image structure.\n */\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" AcquireNextImage()\");\n\n AcquireNextImage(image_info,image,exception);\n\n if (GetNextImageInList(image) == (Image *) NULL)\n return(DestroyImageList(image));\n\n image=SyncNextImageInList(image);\n }\n mng_info->image=image;\n\n /*\n Signature bytes have already been read.\n */\n\n read_JSEP=MagickFalse;\n reading_idat=MagickFalse;\n for (;;)\n {\n char\n type[MagickPathExtent];\n\n unsigned char\n *chunk;\n\n unsigned int\n count;\n\n /*\n Read a new JNG chunk.\n */\n status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n 2*GetBlobSize(image));\n\n if (status == MagickFalse)\n break;\n\n type[0]='\\0';\n (void) ConcatenateMagickString(type,\"errr\",MagickPathExtent);\n length=ReadBlobMSBLong(image);\n count=(unsigned int) ReadBlob(image,4,(unsigned char *) type);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Reading JNG chunk type %c%c%c%c, length: %.20g\",\n type[0],type[1],type[2],type[3],(double) length);\n\n if (length > PNG_UINT_31_MAX || count == 0)\n ThrowReaderException(CorruptImageError,\"CorruptImage\");\n\n p=NULL;\n chunk=(unsigned char *) NULL;\n\n if (length != 0)\n {\n if (length > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n chunk=(unsigned char *) AcquireQuantumMemory(length+MagickPathExtent,\n sizeof(*chunk));\n\n if (chunk == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n\n for (i=0; i < (ssize_t) length; i++)\n {\n int\n c;\n\n c=ReadBlobByte(image);\n if (c == EOF)\n break;\n chunk[i]=(unsigned char) c;\n }\n\n p=chunk;\n }\n\n (void) ReadBlobMSBLong(image); /* read crc word */\n\n if (memcmp(type,mng_JHDR,4) == 0)\n {\n if (length == 16)\n {\n jng_width=(size_t) ((p[0] << 24) | (p[1] << 16) |\n (p[2] << 8) | p[3]);\n jng_height=(size_t) ((p[4] << 24) | (p[5] << 16) |\n (p[6] << 8) | p[7]);\n if ((jng_width == 0) || (jng_height == 0))\n ThrowReaderException(CorruptImageError,\n \"NegativeOrZeroImageSize\");\n jng_color_type=p[8];\n jng_image_sample_depth=p[9];\n jng_image_compression_method=p[10];\n jng_image_interlace_method=p[11];\n\n image->interlace=jng_image_interlace_method != 0 ? PNGInterlace :\n NoInterlace;\n\n jng_alpha_sample_depth=p[12];\n jng_alpha_compression_method=p[13];\n jng_alpha_filter_method=p[14];\n jng_alpha_interlace_method=p[15];\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" jng_width: %16lu, jng_height: %16lu\\n\"\n \" jng_color_type: %16d, jng_image_sample_depth: %3d\\n\"\n \" jng_image_compression_method:%3d\",\n (unsigned long) jng_width, (unsigned long) jng_height,\n jng_color_type, jng_image_sample_depth,\n jng_image_compression_method);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" jng_image_interlace_method: %3d\"\n \" jng_alpha_sample_depth: %3d\",\n jng_image_interlace_method,\n jng_alpha_sample_depth);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" jng_alpha_compression_method:%3d\\n\"\n \" jng_alpha_filter_method: %3d\\n\"\n \" jng_alpha_interlace_method: %3d\",\n jng_alpha_compression_method,\n jng_alpha_filter_method,\n jng_alpha_interlace_method);\n }\n }\n\n if (length != 0)\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n continue;\n }\n\n\n if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) &&\n ((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) ||\n (memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0)))\n {\n /*\n o create color_image\n o open color_blob, attached to color_image\n o if (color type has alpha)\n open alpha_blob, attached to alpha_image\n */\n\n color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo));\n\n if (color_image_info == (ImageInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n\n GetImageInfo(color_image_info);\n color_image=AcquireImage(color_image_info,exception);\n\n if (color_image == (Image *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Creating color_blob.\");\n\n (void) AcquireUniqueFilename(color_image->filename);\n status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode,\n exception);\n\n if (status == MagickFalse)\n {\n color_image=DestroyImage(color_image);\n return(DestroyImageList(image));\n }\n\n if ((image_info->ping == MagickFalse) && (jng_color_type >= 12))\n {\n alpha_image_info=(ImageInfo *)\n AcquireMagickMemory(sizeof(ImageInfo));\n\n if (alpha_image_info == (ImageInfo *) NULL)\n {\n color_image=DestroyImage(color_image);\n ThrowReaderException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n\n GetImageInfo(alpha_image_info);\n alpha_image=AcquireImage(alpha_image_info,exception);\n\n if (alpha_image == (Image *) NULL)\n {\n alpha_image_info=DestroyImageInfo(alpha_image_info);\n color_image=DestroyImage(color_image);\n ThrowReaderException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Creating alpha_blob.\");\n\n (void) AcquireUniqueFilename(alpha_image->filename);\n status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode,\n exception);\n\n if (status == MagickFalse)\n {\n alpha_image=DestroyImage(alpha_image);\n alpha_image_info=DestroyImageInfo(alpha_image_info);\n color_image=DestroyImage(color_image);\n return(DestroyImageList(image));\n }\n\n if (jng_alpha_compression_method == 0)\n {\n unsigned char\n data[18];\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Writing IHDR chunk to alpha_blob.\");\n\n (void) WriteBlob(alpha_image,8,(const unsigned char *)\n \"\\211PNG\\r\\n\\032\\n\");\n\n (void) WriteBlobMSBULong(alpha_image,13L);\n PNGType(data,mng_IHDR);\n LogPNGChunk(logging,mng_IHDR,13L);\n PNGLong(data+4,jng_width);\n PNGLong(data+8,jng_height);\n data[12]=jng_alpha_sample_depth;\n data[13]=0; /* color_type gray */\n data[14]=0; /* compression method 0 */\n data[15]=0; /* filter_method 0 */\n data[16]=0; /* interlace_method 0 */\n (void) WriteBlob(alpha_image,17,data);\n (void) WriteBlobMSBULong(alpha_image,crc32(0,data,17));\n }\n }\n reading_idat=MagickTrue;\n }\n\n if (memcmp(type,mng_JDAT,4) == 0)\n {\n /* Copy chunk to color_image->blob */\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Copying JDAT chunk data to color_blob.\");\n\n if (length != 0)\n {\n (void) WriteBlob(color_image,length,chunk);\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n }\n\n continue;\n }\n\n if (memcmp(type,mng_IDAT,4) == 0)\n {\n png_byte\n data[5];\n\n /* Copy IDAT header and chunk data to alpha_image->blob */\n\n if (alpha_image != NULL && image_info->ping == MagickFalse)\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Copying IDAT chunk data to alpha_blob.\");\n\n (void) WriteBlobMSBULong(alpha_image,(size_t) length);\n PNGType(data,mng_IDAT);\n LogPNGChunk(logging,mng_IDAT,length);\n (void) WriteBlob(alpha_image,4,data);\n (void) WriteBlob(alpha_image,length,chunk);\n (void) WriteBlobMSBULong(alpha_image,\n crc32(crc32(0,data,4),chunk,(uInt) length));\n }\n\n if (length != 0)\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n continue;\n }\n\n if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0))\n {\n /* Copy chunk data to alpha_image->blob */\n\n if (alpha_image != NULL && image_info->ping == MagickFalse)\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Copying JDAA chunk data to alpha_blob.\");\n\n (void) WriteBlob(alpha_image,length,chunk);\n }\n\n if (length != 0)\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n continue;\n }\n\n if (memcmp(type,mng_JSEP,4) == 0)\n {\n read_JSEP=MagickTrue;\n\n if (length != 0)\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n continue;\n }\n\n if (memcmp(type,mng_bKGD,4) == 0)\n {\n if (length == 2)\n {\n image->background_color.red=ScaleCharToQuantum(p[1]);\n image->background_color.green=image->background_color.red;\n image->background_color.blue=image->background_color.red;\n }\n\n if (length == 6)\n {\n image->background_color.red=ScaleCharToQuantum(p[1]);\n image->background_color.green=ScaleCharToQuantum(p[3]);\n image->background_color.blue=ScaleCharToQuantum(p[5]);\n }\n\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n continue;\n }\n\n if (memcmp(type,mng_gAMA,4) == 0)\n {\n if (length == 4)\n image->gamma=((float) mng_get_long(p))*0.00001;\n\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n continue;\n }\n\n if (memcmp(type,mng_cHRM,4) == 0)\n {\n if (length == 32)\n {\n image->chromaticity.white_point.x=0.00001*mng_get_long(p);\n image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]);\n image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]);\n image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]);\n image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]);\n image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]);\n image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]);\n image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]);\n }\n\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n continue;\n }\n\n if (memcmp(type,mng_sRGB,4) == 0)\n {\n if (length == 1)\n {\n image->rendering_intent=\n Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]);\n image->gamma=1.000f/2.200f;\n image->chromaticity.red_primary.x=0.6400f;\n image->chromaticity.red_primary.y=0.3300f;\n image->chromaticity.green_primary.x=0.3000f;\n image->chromaticity.green_primary.y=0.6000f;\n image->chromaticity.blue_primary.x=0.1500f;\n image->chromaticity.blue_primary.y=0.0600f;\n image->chromaticity.white_point.x=0.3127f;\n image->chromaticity.white_point.y=0.3290f;\n }\n\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n continue;\n }\n\n if (memcmp(type,mng_oFFs,4) == 0)\n {\n if (length > 8)\n {\n image->page.x=(ssize_t) mng_get_long(p);\n image->page.y=(ssize_t) mng_get_long(&p[4]);\n\n if ((int) p[8] != 0)\n {\n image->page.x/=10000;\n image->page.y/=10000;\n }\n }\n\n if (length != 0)\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n continue;\n }\n\n if (memcmp(type,mng_pHYs,4) == 0)\n {\n if (length > 8)\n {\n image->resolution.x=(double) mng_get_long(p);\n image->resolution.y=(double) mng_get_long(&p[4]);\n if ((int) p[8] == PNG_RESOLUTION_METER)\n {\n image->units=PixelsPerCentimeterResolution;\n image->resolution.x=image->resolution.x/100.0f;\n image->resolution.y=image->resolution.y/100.0f;\n }\n }\n\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n continue;\n }\n\n#if 0\n if (memcmp(type,mng_iCCP,4) == 0)\n {\n /* To do: */\n if (length != 0)\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n continue;\n }\n#endif\n\n if (length != 0)\n chunk=(unsigned char *) RelinquishMagickMemory(chunk);\n\n if (memcmp(type,mng_IEND,4))\n continue;\n\n break;\n }\n\n\n /* IEND found */\n\n /*\n Finish up reading image data:\n\n o read main image from color_blob.\n\n o close color_blob.\n\n o if (color_type has alpha)\n if alpha_encoding is PNG\n read secondary image from alpha_blob via ReadPNG\n if alpha_encoding is JPEG\n read secondary image from alpha_blob via ReadJPEG\n\n o close alpha_blob.\n\n o copy intensity of secondary image into\n alpha samples of main image.\n\n o destroy the secondary image.\n */\n\n if (color_image_info == (ImageInfo *) NULL)\n {\n assert(color_image == (Image *) NULL);\n assert(alpha_image == (Image *) NULL);\n return(DestroyImageList(image));\n }\n\n if (color_image == (Image *) NULL)\n {\n assert(alpha_image == (Image *) NULL);\n return(DestroyImageList(image));\n }\n\n (void) SeekBlob(color_image,0,SEEK_SET);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Reading jng_image from color_blob.\");\n\n assert(color_image_info != (ImageInfo *) NULL);\n (void) FormatLocaleString(color_image_info->filename,MagickPathExtent,\"%s\",\n color_image->filename);\n\n color_image_info->ping=MagickFalse; /* To do: avoid this */\n jng_image=ReadImage(color_image_info,exception);\n\n (void) RelinquishUniqueFileResource(color_image->filename);\n color_image=DestroyImage(color_image);\n color_image_info=DestroyImageInfo(color_image_info);\n\n if (jng_image == (Image *) NULL)\n return(DestroyImageList(image));\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Copying jng_image pixels to main image.\");\n\n image->rows=jng_height;\n image->columns=jng_width;\n\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n s=GetVirtualPixels(jng_image,0,y,image->columns,1,exception);\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n for (x=(ssize_t) image->columns; x != 0; x--)\n {\n SetPixelRed(image,GetPixelRed(jng_image,s),q);\n SetPixelGreen(image,GetPixelGreen(jng_image,s),q);\n SetPixelBlue(image,GetPixelBlue(jng_image,s),q);\n q+=GetPixelChannels(image);\n s+=GetPixelChannels(jng_image);\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n\n jng_image=DestroyImage(jng_image);\n\n if (image_info->ping == MagickFalse)\n {\n if (jng_color_type >= 12)\n {\n if (jng_alpha_compression_method == 0)\n {\n png_byte\n data[5];\n (void) WriteBlobMSBULong(alpha_image,0x00000000L);\n PNGType(data,mng_IEND);\n LogPNGChunk(logging,mng_IEND,0L);\n (void) WriteBlob(alpha_image,4,data);\n (void) WriteBlobMSBULong(alpha_image,crc32(0,data,4));\n }\n\n (void) CloseBlob(alpha_image);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Reading alpha from alpha_blob.\");\n\n (void) FormatLocaleString(alpha_image_info->filename,MagickPathExtent,\n \"%s\",alpha_image->filename);\n\n jng_image=ReadImage(alpha_image_info,exception);\n\n if (jng_image != (Image *) NULL)\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n s=GetVirtualPixels(jng_image,0,y,image->columns,1,\n exception);\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n\n if (image->alpha_trait != UndefinedPixelTrait)\n for (x=(ssize_t) image->columns; x != 0; x--)\n {\n SetPixelAlpha(image,GetPixelRed(jng_image,s),q);\n q+=GetPixelChannels(image);\n s+=GetPixelChannels(jng_image);\n }\n\n else\n for (x=(ssize_t) image->columns; x != 0; x--)\n {\n SetPixelAlpha(image,GetPixelRed(jng_image,s),q);\n if (GetPixelAlpha(image,q) != OpaqueAlpha)\n image->alpha_trait=BlendPixelTrait;\n q+=GetPixelChannels(image);\n s+=GetPixelChannels(jng_image);\n }\n\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n (void) RelinquishUniqueFileResource(alpha_image->filename);\n alpha_image=DestroyImage(alpha_image);\n alpha_image_info=DestroyImageInfo(alpha_image_info);\n if (jng_image != (Image *) NULL)\n jng_image=DestroyImage(jng_image);\n }\n }\n\n /* Read the JNG image. */\n\n if (mng_info->mng_type == 0)\n {\n mng_info->mng_width=jng_width;\n mng_info->mng_height=jng_height;\n }\n\n if (image->page.width == 0 && image->page.height == 0)\n {\n image->page.width=jng_width;\n image->page.height=jng_height;\n }\n\n if (image->page.x == 0 && image->page.y == 0)\n {\n image->page.x=mng_info->x_off[mng_info->object_id];\n image->page.y=mng_info->y_off[mng_info->object_id];\n }\n\n else\n {\n image->page.y=mng_info->y_off[mng_info->object_id];\n }\n\n mng_info->image_found++;\n status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image),\n 2*GetBlobSize(image));\n\n if (status == MagickFalse)\n return(DestroyImageList(image));\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" exit ReadOneJNGImage()\");\n\n return(image);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-772', 'CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/550'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void asmlinkage smm_do_relocation(void *arg)\n{\n\tconst struct smm_module_params *p;\n\tconst struct smm_runtime *runtime;\n\tint cpu;\n\tuintptr_t curr_smbase;\n\tuintptr_t perm_smbase;\n\n\tp = arg;\n\truntime = p->runtime;\n\tcpu = p->cpu;\n\tcurr_smbase = runtime->smbase;\n\n\tif (cpu >= CONFIG_MAX_CPUS) {\n\t\tprintk(BIOS_CRIT,\n\t\t \"Invalid CPU number assigned in SMM stub: %d\\n\", cpu);\n\t\treturn;\n\t}\n\n\t/*\n\t * The permanent handler runs with all cpus concurrently. Precalculate\n\t * the location of the new SMBASE. If using SMM modules then this\n\t * calculation needs to match that of the module loader.\n\t */\n\tperm_smbase = mp_state.perm_smbase;\n\tperm_smbase -= cpu * runtime->save_state_size;\n\n\tprintk(BIOS_DEBUG, \"New SMBASE 0x%08lx\\n\", perm_smbase);\n\n\t/* Setup code checks this callback for validity. */\n\tmp_state.ops.relocation_handler(cpu, curr_smbase, perm_smbase);\n\n\tif (CONFIG(STM)) {\n\t\tuintptr_t mseg;\n\n\t\tmseg = mp_state.perm_smbase +\n\t\t\t(mp_state.perm_smsize - CONFIG_MSEG_SIZE);\n\n\t\tstm_setup(mseg, p->cpu,\n\t\t\t\tperm_smbase,\n\t\t\t\tmp_state.perm_smbase,\n\t\t\t\truntime->start32_offset);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-269'], 'message': 'cpu/x86/smm: Introduce SMM module loader version 2\n\nXeon-SP Skylake Scalable Processor can have 36 CPU threads (18 cores).\nCurrent coreboot SMM is unable to handle more than ~32 CPU threads.\nThis patch introduces a version 2 of the SMM module loader which\naddresses this problem. Having two versions of the SMM module loader\nprevents any issues to current projects. Future Xeon-SP products will\nbe using this version of the SMM loader. Subsequent patches will\nenable board specific functionality for Xeon-SP.\n\nThe reason for moving to version 2 is the state save area begins to\nencroach upon the SMI handling code when more than 32 CPU threads are\nin the system. This can cause system hangs, reboots, etc. The second\nchange is related to staggered entry points with simple near jumps. In\nthe current loader, near jumps will not work because the CPU is jumping\nwithin the same code segment. In version 2, \"far\" address jumps are\nnecessary therefore protected mode must be enabled first. The SMM\nlayout and how the CPUs are staggered are documented in the code.\n\nBy making the modifications above, this allows the smm module loader to\nexpand easily as more CPU threads are added.\n\nTEST=build for Tiogapass platform under OCP mainboard. Enable the\nfollowing in Kconfig.\n select CPU_INTEL_COMMON_SMM\n select SOC_INTEL_COMMON_BLOCK_SMM\n select SMM_TSEG\n select HAVE_SMI_HANDLER\n select ACPI_INTEL_HARDWARE_SLEEP_VALUES\n\nDebug console will show all 36 cores relocated. Further tested by\ngenerating SMI's to port 0xb2 using XDP/ITP HW debugger and ensured all\ncores entering and exiting SMM properly. In addition, booted to Linux\n5.4 kernel and observed no issues during mp init.\n\nChange-Id: I00a23a5f2a46110536c344254868390dbb71854c\nSigned-off-by: Rocky Phagura \nReviewed-on: https://review.coreboot.org/c/coreboot/+/43684\nTested-by: build bot (Jenkins) \nReviewed-by: Angel Pons '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: mobility_print(netdissect_options *ndo,\n const u_char *bp, const u_char *bp2 _U_)\n{\n\tconst struct ip6_mobility *mh;\n\tconst u_char *ep;\n\tunsigned mhlen, hlen;\n\tuint8_t type;\n\n\tmh = (const struct ip6_mobility *)bp;\n\n\t/* 'ep' points to the end of available data. */\n\tep = ndo->ndo_snapend;\n\n\tif (!ND_TTEST(mh->ip6m_len)) {\n\t\t/*\n\t\t * There's not enough captured data to include the\n\t\t * mobility header length.\n\t\t *\n\t\t * Our caller expects us to return the length, however,\n\t\t * so return a value that will run to the end of the\n\t\t * captured data.\n\t\t *\n\t\t * XXX - \"ip6_print()\" doesn't do anything with the\n\t\t * returned length, however, as it breaks out of the\n\t\t * header-processing loop.\n\t\t */\n\t\tmhlen = ep - bp;\n\t\tgoto trunc;\n\t}\n\tmhlen = (mh->ip6m_len + 1) << 3;\n\n\t/* XXX ip6m_cksum */\n\n\tND_TCHECK(mh->ip6m_type);\n\ttype = mh->ip6m_type;\n\tif (type <= IP6M_MAX && mhlen < ip6m_hdrlen[type]) {\n\t\tND_PRINT((ndo, \"(header length %u is too small for type %u)\", mhlen, type));\n\t\tgoto trunc;\n\t}\n\tND_PRINT((ndo, \"mobility: %s\", tok2str(ip6m_str, \"type-#%u\", type)));\n\tswitch (type) {\n\tcase IP6M_BINDING_REQUEST:\n\t\thlen = IP6M_MINLEN;\n\t\tbreak;\n\tcase IP6M_HOME_TEST_INIT:\n\tcase IP6M_CAREOF_TEST_INIT:\n\t\thlen = IP6M_MINLEN;\n\t\tif (ndo->ndo_vflag) {\n\t\t\tND_TCHECK2(*mh, hlen + 8);\n\t\t\tND_PRINT((ndo, \" %s Init Cookie=%08x:%08x\",\n\t\t\t type == IP6M_HOME_TEST_INIT ? \"Home\" : \"Care-of\",\n\t\t\t EXTRACT_32BITS(&bp[hlen]),\n\t\t\t EXTRACT_32BITS(&bp[hlen + 4])));\n\t\t}\n\t\thlen += 8;\n\t\tbreak;\n\tcase IP6M_HOME_TEST:\n\tcase IP6M_CAREOF_TEST:\n\t\tND_TCHECK(mh->ip6m_data16[0]);\n\t\tND_PRINT((ndo, \" nonce id=0x%x\", EXTRACT_16BITS(&mh->ip6m_data16[0])));\n\t\thlen = IP6M_MINLEN;\n\t\tif (ndo->ndo_vflag) {\n\t\t\tND_TCHECK2(*mh, hlen + 8);\n\t\t\tND_PRINT((ndo, \" %s Init Cookie=%08x:%08x\",\n\t\t\t type == IP6M_HOME_TEST ? \"Home\" : \"Care-of\",\n\t\t\t EXTRACT_32BITS(&bp[hlen]),\n\t\t\t EXTRACT_32BITS(&bp[hlen + 4])));\n\t\t}\n\t\thlen += 8;\n\t\tif (ndo->ndo_vflag) {\n\t\t\tND_TCHECK2(*mh, hlen + 8);\n\t\t\tND_PRINT((ndo, \" %s Keygen Token=%08x:%08x\",\n\t\t\t type == IP6M_HOME_TEST ? \"Home\" : \"Care-of\",\n\t\t\t EXTRACT_32BITS(&bp[hlen]),\n\t\t\t EXTRACT_32BITS(&bp[hlen + 4])));\n\t\t}\n\t\thlen += 8;\n\t\tbreak;\n\tcase IP6M_BINDING_UPDATE:\n\t\tND_TCHECK(mh->ip6m_data16[0]);\n\t\tND_PRINT((ndo, \" seq#=%u\", EXTRACT_16BITS(&mh->ip6m_data16[0])));\n\t\thlen = IP6M_MINLEN;\n\t\tND_TCHECK2(*mh, hlen + 1);\n\t\tif (bp[hlen] & 0xf0)\n\t\t\tND_PRINT((ndo, \" \"));\n\t\tif (bp[hlen] & 0x80)\n\t\t\tND_PRINT((ndo, \"A\"));\n\t\tif (bp[hlen] & 0x40)\n\t\t\tND_PRINT((ndo, \"H\"));\n\t\tif (bp[hlen] & 0x20)\n\t\t\tND_PRINT((ndo, \"L\"));\n\t\tif (bp[hlen] & 0x10)\n\t\t\tND_PRINT((ndo, \"K\"));\n\t\t/* Reserved (4bits) */\n\t\thlen += 1;\n\t\t/* Reserved (8bits) */\n\t\thlen += 1;\n\t\tND_TCHECK2(*mh, hlen + 2);\n\t\t/* units of 4 secs */\n\t\tND_PRINT((ndo, \" lifetime=%u\", EXTRACT_16BITS(&bp[hlen]) << 2));\n\t\thlen += 2;\n\t\tbreak;\n\tcase IP6M_BINDING_ACK:\n\t\tND_TCHECK(mh->ip6m_data8[0]);\n\t\tND_PRINT((ndo, \" status=%u\", mh->ip6m_data8[0]));\n\t\tif (mh->ip6m_data8[1] & 0x80)\n\t\t\tND_PRINT((ndo, \" K\"));\n\t\t/* Reserved (7bits) */\n\t\thlen = IP6M_MINLEN;\n\t\tND_TCHECK2(*mh, hlen + 2);\n\t\tND_PRINT((ndo, \" seq#=%u\", EXTRACT_16BITS(&bp[hlen])));\n\t\thlen += 2;\n\t\tND_TCHECK2(*mh, hlen + 2);\n\t\t/* units of 4 secs */\n\t\tND_PRINT((ndo, \" lifetime=%u\", EXTRACT_16BITS(&bp[hlen]) << 2));\n\t\thlen += 2;\n\t\tbreak;\n\tcase IP6M_BINDING_ERROR:\n\t\tND_TCHECK(mh->ip6m_data8[0]);\n\t\tND_PRINT((ndo, \" status=%u\", mh->ip6m_data8[0]));\n\t\t/* Reserved */\n\t\thlen = IP6M_MINLEN;\n\t\tND_TCHECK2(*mh, hlen + 16);\n\t\tND_PRINT((ndo, \" homeaddr %s\", ip6addr_string(ndo, &bp[hlen])));\n\t\thlen += 16;\n\t\tbreak;\n\tdefault:\n\t\tND_PRINT((ndo, \" len=%u\", mh->ip6m_len));\n\t\treturn(mhlen);\n\t\tbreak;\n\t}\n\tif (ndo->ndo_vflag)\n\t\tif (mobility_opt_print(ndo, &bp[hlen], mhlen - hlen))\n\t\t\tgoto trunc;\n\n\treturn(mhlen);\n\n trunc:\n\tND_PRINT((ndo, \"%s\", tstr));\n\treturn(mhlen);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-12985/IPv6: Check for print routines returning -1 when running past the end.\n\nrt6_print(), ah_print(), and esp_print() return -1 if they run up\nagainst the end of the packet while dissecting; if that happens, stop\ndissecting, don't try to fetch the next header value, because 1) *it*\nmight be past the end of the packet and 2) we won't be using it in any\ncase, as we'll be exiting the loop.\n\nAlso, change mobility_print() to return -1 if it runs up against the\nend of the packet, and stop dissecting if it does so.\n\nThis fixes a buffer over-read discovered by Brian 'geeknik' Carpenter.\n\nAdd tests using the capture files supplied by the reporter(s).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: GF_Err gf_isom_apple_enum_tag(GF_ISOFile *mov, u32 idx, GF_ISOiTunesTag *out_tag, const u8 **data, u32 *data_len, u64 *out_int_val, u32 *out_int_val2, u32 *out_flags)\n{\n\tu32 i, child_index;\n\tGF_ListItemBox *info;\n\tGF_ItemListBox *ilst;\n\tGF_MetaBox *meta;\n\tGF_DataBox *dbox = NULL;\n\tu32 itype, tag_val;\n\ts32 tag_idx;\n\t*data = NULL;\n\t*data_len = 0;\n\n\tmeta = (GF_MetaBox *) gf_isom_get_meta_extensions(mov, GF_FALSE);\n\tif (!meta) return GF_URL_ERROR;\n\n\tilst = gf_isom_locate_box(meta->child_boxes, GF_ISOM_BOX_TYPE_ILST, NULL);\n\tif (!ilst) return GF_URL_ERROR;\n\n\tchild_index = i = 0;\n\twhile ( (info=(GF_ListItemBox*)gf_list_enum(ilst->child_boxes, &i))) {\n\t\tGF_DataBox *data_box = NULL;\n\t\tif (gf_itags_find_by_itag(info->type)<0) {\n\t\t\tif (info->type==GF_ISOM_BOX_TYPE_UNKNOWN) {\n\t\t\t\tdata_box = (GF_DataBox *) gf_isom_box_find_child(info->child_boxes, GF_ISOM_BOX_TYPE_DATA);\n\t\t\t\tif (!data_box) continue;\n\t\t\t\ttag_val = ((GF_UnknownBox *)info)->original_4cc;\n\t\t\t}\n\t\t} else {\n\t\t\tdata_box = info->data;\n\t\t\ttag_val = info->type;\n\t\t}\n\t\tif (child_index==idx) {\n\t\t\tdbox = data_box;\n\t\t\tbreak;\n\t\t}\n\t\tchild_index++;\n\t}\n\tif (!dbox) return GF_URL_ERROR;\n\n\t*out_flags = dbox->flags;\n\t*out_tag = tag_val;\n\tif (!dbox->data) {\n\t\t*data = NULL;\n\t\t*data_len = 1;\n\t\treturn GF_OK;\n\t}\n\n\ttag_idx = gf_itags_find_by_itag(info->type);\n\tif (tag_idx<0) {\n\t\t*data = dbox->data;\n\t\t*data_len = dbox->dataSize;\n\t\treturn GF_OK;\n\t}\n\n\tif ((tag_val == GF_ISOM_ITUNE_GENRE) && (dbox->flags == 0) && (dbox->dataSize>=2)) {\n\t\tu32 int_val = dbox->data[0];\n\t\tint_val <<= 8;\n\t\tint_val |= dbox->data[1];\n\t\t*data = NULL;\n\t\t*data_len = 0;\n\t\t*out_int_val = int_val;\n\t\treturn GF_OK;\n\t}\n\n\titype = gf_itags_get_type((u32) tag_idx);\n\tswitch (itype) {\n\tcase GF_ITAG_BOOL:\n\tcase GF_ITAG_INT8:\n\t\tif (dbox->dataSize) *out_int_val = dbox->data[0];\n\t\tbreak;\n\tcase GF_ITAG_INT16:\n\t\tif (dbox->dataSize>1) {\n\t\t\tu16 v = dbox->data[0];\n\t\t\tv<<=8;\n\t\t\tv |= dbox->data[1];\n\t\t\t*out_int_val = v;\n\t\t}\n\t\tbreak;\n\tcase GF_ITAG_INT32:\n\t\tif (dbox->dataSize>3) {\n\t\t\tu32 v = dbox->data[0];\n\t\t\tv<<=8;\n\t\t\tv |= dbox->data[1];\n\t\t\tv<<=8;\n\t\t\tv |= dbox->data[2];\n\t\t\tv<<=8;\n\t\t\tv |= dbox->data[3];\n\t\t\t*out_int_val = v;\n\t\t}\n\t\tbreak;\n\tcase GF_ITAG_INT64:\n\t\tif (dbox->dataSize>3) {\n\t\t\tu64 v = dbox->data[0];\n\t\t\tv<<=8;\n\t\t\tv |= dbox->data[1];\n\t\t\tv<<=8;\n\t\t\tv |= dbox->data[2];\n\t\t\tv<<=8;\n\t\t\tv |= dbox->data[3];\n\t\t\tv<<=8;\n\t\t\tv |= dbox->data[4];\n\t\t\tv<<=8;\n\t\t\tv |= dbox->data[5];\n\t\t\tv<<=8;\n\t\t\tv |= dbox->data[6];\n\t\t\tv<<=8;\n\t\t\tv |= dbox->data[7];\n\t\t\t*out_int_val = v;\n\t\t}\n\t\tbreak;\n\tcase GF_ITAG_FRAC6:\n\tcase GF_ITAG_FRAC8:\n\t\tif (dbox->dataSize>3) {\n\t\t\tu32 v = dbox->data[2];\n\t\t\tv<<=8;\n\t\t\tv |= dbox->data[3];\n\t\t\t*out_int_val = v;\n\t\t\tv = dbox->data[4];\n\t\t\tv<<=8;\n\t\t\tv |= dbox->data[5];\n\t\t\t*out_int_val2 = v;\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\t*data = dbox->data;\n\t\t*data_len = dbox->dataSize;\n\t\tbreak;\n\t}\n\treturn GF_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'fixed #2120'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int ima_lsm_rule_init(struct ima_measure_rule_entry *entry,\n\t\t\t char *args, int lsm_rule, int audit_type)\n{\n\tint result;\n\n\tif (entry->lsm[lsm_rule].rule)\n\t\treturn -EINVAL;\n\n\tentry->lsm[lsm_rule].type = audit_type;\n\tresult = security_filter_rule_init(entry->lsm[lsm_rule].type,\n\t\t\t\t\t Audit_equal, args,\n\t\t\t\t\t &entry->lsm[lsm_rule].rule);\n\treturn result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'ima: fix add LSM rule bug\n\nIf security_filter_rule_init() doesn't return a rule, then not everything\nis as fine as the return code implies.\n\nThis bug only occurs when the LSM (eg. SELinux) is disabled at runtime.\n\nAdding an empty LSM rule causes ima_match_rules() to always succeed,\nignoring any remaining rules.\n\n default IMA TCB policy:\n # PROC_SUPER_MAGIC\n dont_measure fsmagic=0x9fa0\n # SYSFS_MAGIC\n dont_measure fsmagic=0x62656572\n # DEBUGFS_MAGIC\n dont_measure fsmagic=0x64626720\n # TMPFS_MAGIC\n dont_measure fsmagic=0x01021994\n # SECURITYFS_MAGIC\n dont_measure fsmagic=0x73636673\n\n < LSM specific rule >\n dont_measure obj_type=var_log_t\n\n measure func=BPRM_CHECK\n measure func=FILE_MMAP mask=MAY_EXEC\n measure func=FILE_CHECK mask=MAY_READ uid=0\n\nThus without the patch, with the boot parameters 'tcb selinux=0', adding\nthe above 'dont_measure obj_type=var_log_t' rule to the default IMA TCB\nmeasurement policy, would result in nothing being measured. The patch\nprevents the default TCB policy from being replaced.\n\nSigned-off-by: Mimi Zohar \nCc: James Morris \nAcked-by: Serge Hallyn \nCc: David Safford \nCc: \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: CallResult> JSObject::getComputedWithReceiver_RJS(\n Handle selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle,\n Handle<> receiver) {\n // Try the fast-path first: no \"index-like\" properties and the \"name\" already\n // is a valid integer index.\n if (selfHandle->flags_.fastIndexProperties) {\n if (auto arrayIndex = toArrayIndexFastPath(*nameValHandle)) {\n // Do we have this value present in our array storage? If so, return it.\n PseudoHandle<> ourValue = createPseudoHandle(\n getOwnIndexed(selfHandle.get(), runtime, *arrayIndex));\n if (LLVM_LIKELY(!ourValue->isEmpty()))\n return ourValue;\n }\n }\n\n // If nameValHandle is an object, we should convert it to string now,\n // because toString may have side-effect, and we want to do this only\n // once.\n auto converted = toPropertyKeyIfObject(runtime, nameValHandle);\n if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n auto nameValPrimitiveHandle = *converted;\n\n ComputedPropertyDescriptor desc;\n\n // Locate the descriptor. propObj contains the object which may be anywhere\n // along the prototype chain.\n MutableHandle propObj{runtime};\n if (LLVM_UNLIKELY(\n getComputedPrimitiveDescriptor(\n selfHandle, runtime, nameValPrimitiveHandle, propObj, desc) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n\n if (!propObj)\n return createPseudoHandle(HermesValue::encodeUndefinedValue());\n\n if (LLVM_LIKELY(\n !desc.flags.accessor && !desc.flags.hostObject &&\n !desc.flags.proxyObject))\n return createPseudoHandle(\n getComputedSlotValue(propObj.get(), runtime, desc));\n\n if (desc.flags.accessor) {\n auto *accessor = vmcast(\n getComputedSlotValue(propObj.get(), runtime, desc));\n if (!accessor->getter)\n return createPseudoHandle(HermesValue::encodeUndefinedValue());\n\n // Execute the accessor on this object.\n return accessor->getter.get(runtime)->executeCall0(\n runtime->makeHandle(accessor->getter), runtime, receiver);\n } else if (desc.flags.hostObject) {\n SymbolID id{};\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);\n auto propRes = vmcast(selfHandle.get())->get(id);\n if (propRes == ExecutionStatus::EXCEPTION)\n return ExecutionStatus::EXCEPTION;\n return createPseudoHandle(*propRes);\n } else {\n assert(desc.flags.proxyObject && \"descriptor flags are impossible\");\n CallResult> key = toPropertyKey(runtime, nameValPrimitiveHandle);\n if (key == ExecutionStatus::EXCEPTION)\n return ExecutionStatus::EXCEPTION;\n return JSProxy::getComputed(propObj, runtime, *key, receiver);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-843', 'CWE-125'], 'message': '[CVE-2020-1911] Look up HostObject computed properties on the right object in the prototype chain.\n\nSummary:\nThe change in the hermes repository fixes the security vulnerability\nCVE-2020-1911. This vulnerability only affects applications which\nallow evaluation of uncontrolled, untrusted JavaScript code not\nshipped with the app, so React Native apps will generally not be affected.\n\nThis revision includes a test for the bug. The test is generic JSI\ncode, so it is included in the hermes and react-native repositories.\n\nChangelog: [Internal]\n\nReviewed By: tmikov\n\nDifferential Revision: D23322992\n\nfbshipit-source-id: 4e88c974afe1ad33a263f9cac03e9dc98d33649a'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void gf_m2ts_process_pat(GF_M2TS_Demuxer *ts, GF_M2TS_SECTION_ES *ses, GF_List *sections, u8 table_id, u16 ex_table_id, u8 version_number, u8 last_section_number, u32 status)\n{\n\tGF_M2TS_Program *prog;\n\tGF_M2TS_SECTION_ES *pmt;\n\tu32 i, nb_progs, evt_type;\n\tu32 nb_sections;\n\tu32 data_size;\n\tunsigned char *data;\n\tGF_M2TS_Section *section;\n\n\t/*wait for the last section */\n\tif (!(status&GF_M2TS_TABLE_END)) return;\n\n\t/*skip if already received*/\n\tif (status&GF_M2TS_TABLE_REPEAT) {\n\t\tif (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_PAT_REPEAT, NULL);\n\t\treturn;\n\t}\n\n\tnb_sections = gf_list_count(sections);\n\tif (nb_sections > 1) {\n\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"PAT on multiple sections not supported\\n\"));\n\t}\n\n\tsection = (GF_M2TS_Section *)gf_list_get(sections, 0);\n\tdata = section->data;\n\tdata_size = section->data_size;\n\n\tif (!(status&GF_M2TS_TABLE_UPDATE) && gf_list_count(ts->programs)) {\n\t\tif (ts->pat->demux_restarted) {\n\t\t\tts->pat->demux_restarted = 0;\n\t\t} else {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"Multiple different PAT on single TS found, ignoring new PAT declaration (table id %d - extended table id %d)\\n\", table_id, ex_table_id));\n\t\t}\n\t\treturn;\n\t}\n\tnb_progs = data_size / 4;\n\n\tfor (i=0; init) {\n\t\t\t\tts->nit = gf_m2ts_section_filter_new(gf_m2ts_process_nit, 0);\n\t\t\t}\n\t\t} else {\n\t\t\tGF_SAFEALLOC(prog, GF_M2TS_Program);\n\t\t\tif (!prog) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"Fail to allocate program for pid %d\\n\", pid));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tprog->streams = gf_list_new();\n\t\t\tprog->pmt_pid = pid;\n\t\t\tprog->number = number;\n\t\t\tprog->ts = ts;\n\t\t\tgf_list_add(ts->programs, prog);\n\t\t\tGF_SAFEALLOC(pmt, GF_M2TS_SECTION_ES);\n\t\t\tif (!pmt) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"Fail to allocate pmt filter for pid %d\\n\", pid));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tpmt->flags = GF_M2TS_ES_IS_SECTION;\n\t\t\tgf_list_add(prog->streams, pmt);\n\t\t\tpmt->pid = prog->pmt_pid;\n\t\t\tpmt->program = prog;\n\t\t\tts->ess[pmt->pid] = (GF_M2TS_ES *)pmt;\n\t\t\tpmt->sec = gf_m2ts_section_filter_new(gf_m2ts_process_pmt, 0);\n\t\t}\n\t}\n\n\tevt_type = (status&GF_M2TS_TABLE_UPDATE) ? GF_M2TS_EVT_PAT_UPDATE : GF_M2TS_EVT_PAT_FOUND;\n\tif (ts->on_event) ts->on_event(ts, evt_type, NULL);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'be stricter in PAT processing - cf #1269'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void Compute(OpKernelContext* context) override {\n ReshapeSparseTensor(context, context->input(0), context->input(1),\n context->input(2), 0 /* output indices index */,\n 1 /* output shape index */);\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-369'], 'message': 'Fix heap-buffer-overflow issue with `tf.raw_ops.SparseReshape`.\n\nPiperOrigin-RevId: 371218558\nChange-Id: I6a6dc5bf15b50a1d05bdd95e9ba347cb39f40f45'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: pthread_mutex_lock(pthread_mutex_t *mutex)\n{\n\tEnterCriticalSection(mutex);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-125'], 'message': 'Make pthread_mutex static initialisation work on Windows.\n\nThis takes the dynamic initialisation code added to CRYPTO_lock() in e5081719\nand applies it to the Window's pthread_mutex implementation. This allows for\nPTHREAD_MUTEX_INITIALIZER to be used on Windows.\n\nbcook has agreed to place this code in the public domain (as per the rest of\nthe code in pthread.h).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void enable_nmi_window(struct kvm_vcpu *vcpu)\n{\n\tstruct vcpu_svm *svm = to_svm(vcpu);\n\n\tif ((svm->vcpu.arch.hflags & (HF_NMI_MASK | HF_IRET_MASK))\n\t == HF_NMI_MASK)\n\t\treturn; /* IRET will cause a vm exit */\n\n\t/*\n\t * Something prevents NMI from been injected. Single step over possible\n\t * problem (IRET or exception injection or interrupt shadow)\n\t */\n\tsvm->nmi_singlestep = true;\n\tsvm->vmcb->save.rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);\n\tupdate_db_bp_intercept(vcpu);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-399'], 'message': 'KVM: svm: unconditionally intercept #DB\n\nThis is needed to avoid the possibility that the guest triggers\nan infinite stream of #DB exceptions (CVE-2015-8104).\n\nVMX is not affected: because it does not save DR6 in the VMCS,\nit already intercepts #DB unconditionally.\n\nReported-by: Jan Beulich \nCc: stable@vger.kernel.org\nSigned-off-by: Paolo Bonzini '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: telnet_parse(netdissect_options *ndo, const u_char *sp, u_int length, int print)\n{\n\tint i, x;\n\tu_int c;\n\tconst u_char *osp, *p;\n#define FETCH(c, sp, length) \\\n\tdo { \\\n\t\tif (length < 1) \\\n\t\t\tgoto pktend; \\\n\t\tND_TCHECK(*sp); \\\n\t\tc = *sp++; \\\n\t\tlength--; \\\n\t} while (0)\n\n\tosp = sp;\n\n\tFETCH(c, sp, length);\n\tif (c != IAC)\n\t\tgoto pktend;\n\tFETCH(c, sp, length);\n\tif (c == IAC) {\t\t/* ! */\n\t\tif (print)\n\t\t\tND_PRINT((ndo, \"IAC IAC\"));\n\t\tgoto done;\n\t}\n\n\ti = c - TELCMD_FIRST;\n\tif (i < 0 || i > IAC - TELCMD_FIRST)\n\t\tgoto pktend;\n\n\tswitch (c) {\n\tcase DONT:\n\tcase DO:\n\tcase WONT:\n\tcase WILL:\n\tcase SB:\n\t\t/* DONT/DO/WONT/WILL x */\n\t\tFETCH(x, sp, length);\n\t\tif (x >= 0 && x < NTELOPTS) {\n\t\t\tif (print)\n\t\t\t\tND_PRINT((ndo, \"%s %s\", telcmds[i], telopts[x]));\n\t\t} else {\n\t\t\tif (print)\n\t\t\t\tND_PRINT((ndo, \"%s %#x\", telcmds[i], x));\n\t\t}\n\t\tif (c != SB)\n\t\t\tbreak;\n\t\t/* IAC SB .... IAC SE */\n\t\tp = sp;\n\t\twhile (length > (u_int)(p + 1 - sp)) {\n\t\t\tND_TCHECK2(*p, 2);\n\t\t\tif (p[0] == IAC && p[1] == SE)\n\t\t\t\tbreak;\n\t\t\tp++;\n\t\t}\n\t\tif (*p != IAC)\n\t\t\tgoto pktend;\n\n\t\tswitch (x) {\n\t\tcase TELOPT_AUTHENTICATION:\n\t\t\tif (p <= sp)\n\t\t\t\tbreak;\n\t\t\tFETCH(c, sp, length);\n\t\t\tif (print)\n\t\t\t\tND_PRINT((ndo, \" %s\", STR_OR_ID(c, authcmd)));\n\t\t\tif (p <= sp)\n\t\t\t\tbreak;\n\t\t\tFETCH(c, sp, length);\n\t\t\tif (print)\n\t\t\t\tND_PRINT((ndo, \" %s\", STR_OR_ID(c, authtype)));\n\t\t\tbreak;\n\t\tcase TELOPT_ENCRYPT:\n\t\t\tif (p <= sp)\n\t\t\t\tbreak;\n\t\t\tFETCH(c, sp, length);\n\t\t\tif (print)\n\t\t\t\tND_PRINT((ndo, \" %s\", STR_OR_ID(c, enccmd)));\n\t\t\tif (p <= sp)\n\t\t\t\tbreak;\n\t\t\tFETCH(c, sp, length);\n\t\t\tif (print)\n\t\t\t\tND_PRINT((ndo, \" %s\", STR_OR_ID(c, enctype)));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (p <= sp)\n\t\t\t\tbreak;\n\t\t\tFETCH(c, sp, length);\n\t\t\tif (print)\n\t\t\t\tND_PRINT((ndo, \" %s\", STR_OR_ID(c, cmds)));\n\t\t\tbreak;\n\t\t}\n\t\twhile (p > sp) {\n\t\t\tFETCH(x, sp, length);\n\t\t\tif (print)\n\t\t\t\tND_PRINT((ndo, \" %#x\", x));\n\t\t}\n\t\t/* terminating IAC SE */\n\t\tif (print)\n\t\t\tND_PRINT((ndo, \" SE\"));\n\t\tsp += 2;\n\t\tbreak;\n\tdefault:\n\t\tif (print)\n\t\t\tND_PRINT((ndo, \"%s\", telcmds[i]));\n\t\tgoto done;\n\t}\n\ndone:\n\treturn sp - osp;\n\ntrunc:\n\tND_PRINT((ndo, \"%s\", tstr));\npktend:\n\treturn -1;\n#undef FETCH\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-12988/TELNET: Add a missing bounds check.\n\nThis fixes a buffer over-read discovered by Forcepoint's security\nresearchers Otto Airamo & Antti Levom\u00e4ki.\n\nAdd a test using the capture file supplied by the reporter(s).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: __init int intel_pmu_init(void)\n{\n\tunion cpuid10_edx edx;\n\tunion cpuid10_eax eax;\n\tunion cpuid10_ebx ebx;\n\tstruct event_constraint *c;\n\tunsigned int unused;\n\tint version;\n\n\tif (!cpu_has(&boot_cpu_data, X86_FEATURE_ARCH_PERFMON)) {\n\t\tswitch (boot_cpu_data.x86) {\n\t\tcase 0x6:\n\t\t\treturn p6_pmu_init();\n\t\tcase 0xb:\n\t\t\treturn knc_pmu_init();\n\t\tcase 0xf:\n\t\t\treturn p4_pmu_init();\n\t\t}\n\t\treturn -ENODEV;\n\t}\n\n\t/*\n\t * Check whether the Architectural PerfMon supports\n\t * Branch Misses Retired hw_event or not.\n\t */\n\tcpuid(10, &eax.full, &ebx.full, &unused, &edx.full);\n\tif (eax.split.mask_length < ARCH_PERFMON_EVENTS_COUNT)\n\t\treturn -ENODEV;\n\n\tversion = eax.split.version_id;\n\tif (version < 2)\n\t\tx86_pmu = core_pmu;\n\telse\n\t\tx86_pmu = intel_pmu;\n\n\tx86_pmu.version\t\t\t= version;\n\tx86_pmu.num_counters\t\t= eax.split.num_counters;\n\tx86_pmu.cntval_bits\t\t= eax.split.bit_width;\n\tx86_pmu.cntval_mask\t\t= (1ULL << eax.split.bit_width) - 1;\n\n\tx86_pmu.events_maskl\t\t= ebx.full;\n\tx86_pmu.events_mask_len\t\t= eax.split.mask_length;\n\n\tx86_pmu.max_pebs_events\t\t= min_t(unsigned, MAX_PEBS_EVENTS, x86_pmu.num_counters);\n\n\t/*\n\t * Quirk: v2 perfmon does not report fixed-purpose events, so\n\t * assume at least 3 events:\n\t */\n\tif (version > 1)\n\t\tx86_pmu.num_counters_fixed = max((int)edx.split.num_counters_fixed, 3);\n\n\t/*\n\t * v2 and above have a perf capabilities MSR\n\t */\n\tif (version > 1) {\n\t\tu64 capabilities;\n\n\t\trdmsrl(MSR_IA32_PERF_CAPABILITIES, capabilities);\n\t\tx86_pmu.intel_cap.capabilities = capabilities;\n\t}\n\n\tintel_ds_init();\n\n\tx86_add_quirk(intel_arch_events_quirk); /* Install first, so it runs last */\n\n\t/*\n\t * Install the hw-cache-events table:\n\t */\n\tswitch (boot_cpu_data.x86_model) {\n\tcase 14: /* 65 nm core solo/duo, \"Yonah\" */\n\t\tpr_cont(\"Core events, \");\n\t\tbreak;\n\n\tcase 15: /* original 65 nm celeron/pentium/core2/xeon, \"Merom\"/\"Conroe\" */\n\t\tx86_add_quirk(intel_clovertown_quirk);\n\tcase 22: /* single-core 65 nm celeron/core2solo \"Merom-L\"/\"Conroe-L\" */\n\tcase 23: /* current 45 nm celeron/core2/xeon \"Penryn\"/\"Wolfdale\" */\n\tcase 29: /* six-core 45 nm xeon \"Dunnington\" */\n\t\tmemcpy(hw_cache_event_ids, core2_hw_cache_event_ids,\n\t\t sizeof(hw_cache_event_ids));\n\n\t\tintel_pmu_lbr_init_core();\n\n\t\tx86_pmu.event_constraints = intel_core2_event_constraints;\n\t\tx86_pmu.pebs_constraints = intel_core2_pebs_event_constraints;\n\t\tpr_cont(\"Core2 events, \");\n\t\tbreak;\n\n\tcase 26: /* 45 nm nehalem, \"Bloomfield\" */\n\tcase 30: /* 45 nm nehalem, \"Lynnfield\" */\n\tcase 46: /* 45 nm nehalem-ex, \"Beckton\" */\n\t\tmemcpy(hw_cache_event_ids, nehalem_hw_cache_event_ids,\n\t\t sizeof(hw_cache_event_ids));\n\t\tmemcpy(hw_cache_extra_regs, nehalem_hw_cache_extra_regs,\n\t\t sizeof(hw_cache_extra_regs));\n\n\t\tintel_pmu_lbr_init_nhm();\n\n\t\tx86_pmu.event_constraints = intel_nehalem_event_constraints;\n\t\tx86_pmu.pebs_constraints = intel_nehalem_pebs_event_constraints;\n\t\tx86_pmu.enable_all = intel_pmu_nhm_enable_all;\n\t\tx86_pmu.extra_regs = intel_nehalem_extra_regs;\n\n\t\t/* UOPS_ISSUED.STALLED_CYCLES */\n\t\tintel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] =\n\t\t\tX86_CONFIG(.event=0x0e, .umask=0x01, .inv=1, .cmask=1);\n\t\t/* UOPS_EXECUTED.CORE_ACTIVE_CYCLES,c=1,i=1 */\n\t\tintel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_BACKEND] =\n\t\t\tX86_CONFIG(.event=0xb1, .umask=0x3f, .inv=1, .cmask=1);\n\n\t\tx86_add_quirk(intel_nehalem_quirk);\n\n\t\tpr_cont(\"Nehalem events, \");\n\t\tbreak;\n\n\tcase 28: /* Atom */\n\tcase 38: /* Lincroft */\n\tcase 39: /* Penwell */\n\tcase 53: /* Cloverview */\n\tcase 54: /* Cedarview */\n\t\tmemcpy(hw_cache_event_ids, atom_hw_cache_event_ids,\n\t\t sizeof(hw_cache_event_ids));\n\n\t\tintel_pmu_lbr_init_atom();\n\n\t\tx86_pmu.event_constraints = intel_gen_event_constraints;\n\t\tx86_pmu.pebs_constraints = intel_atom_pebs_event_constraints;\n\t\tpr_cont(\"Atom events, \");\n\t\tbreak;\n\n\tcase 37: /* 32 nm nehalem, \"Clarkdale\" */\n\tcase 44: /* 32 nm nehalem, \"Gulftown\" */\n\tcase 47: /* 32 nm Xeon E7 */\n\t\tmemcpy(hw_cache_event_ids, westmere_hw_cache_event_ids,\n\t\t sizeof(hw_cache_event_ids));\n\t\tmemcpy(hw_cache_extra_regs, nehalem_hw_cache_extra_regs,\n\t\t sizeof(hw_cache_extra_regs));\n\n\t\tintel_pmu_lbr_init_nhm();\n\n\t\tx86_pmu.event_constraints = intel_westmere_event_constraints;\n\t\tx86_pmu.enable_all = intel_pmu_nhm_enable_all;\n\t\tx86_pmu.pebs_constraints = intel_westmere_pebs_event_constraints;\n\t\tx86_pmu.extra_regs = intel_westmere_extra_regs;\n\t\tx86_pmu.er_flags |= ERF_HAS_RSP_1;\n\n\t\t/* UOPS_ISSUED.STALLED_CYCLES */\n\t\tintel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] =\n\t\t\tX86_CONFIG(.event=0x0e, .umask=0x01, .inv=1, .cmask=1);\n\t\t/* UOPS_EXECUTED.CORE_ACTIVE_CYCLES,c=1,i=1 */\n\t\tintel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_BACKEND] =\n\t\t\tX86_CONFIG(.event=0xb1, .umask=0x3f, .inv=1, .cmask=1);\n\n\t\tpr_cont(\"Westmere events, \");\n\t\tbreak;\n\n\tcase 42: /* SandyBridge */\n\tcase 45: /* SandyBridge, \"Romely-EP\" */\n\t\tx86_add_quirk(intel_sandybridge_quirk);\n\t\tmemcpy(hw_cache_event_ids, snb_hw_cache_event_ids,\n\t\t sizeof(hw_cache_event_ids));\n\t\tmemcpy(hw_cache_extra_regs, snb_hw_cache_extra_regs,\n\t\t sizeof(hw_cache_extra_regs));\n\n\t\tintel_pmu_lbr_init_snb();\n\n\t\tx86_pmu.event_constraints = intel_snb_event_constraints;\n\t\tx86_pmu.pebs_constraints = intel_snb_pebs_event_constraints;\n\t\tx86_pmu.pebs_aliases = intel_pebs_aliases_snb;\n\t\tx86_pmu.extra_regs = intel_snb_extra_regs;\n\t\t/* all extra regs are per-cpu when HT is on */\n\t\tx86_pmu.er_flags |= ERF_HAS_RSP_1;\n\t\tx86_pmu.er_flags |= ERF_NO_HT_SHARING;\n\n\t\t/* UOPS_ISSUED.ANY,c=1,i=1 to count stall cycles */\n\t\tintel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] =\n\t\t\tX86_CONFIG(.event=0x0e, .umask=0x01, .inv=1, .cmask=1);\n\t\t/* UOPS_DISPATCHED.THREAD,c=1,i=1 to count stall cycles*/\n\t\tintel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_BACKEND] =\n\t\t\tX86_CONFIG(.event=0xb1, .umask=0x01, .inv=1, .cmask=1);\n\n\t\tpr_cont(\"SandyBridge events, \");\n\t\tbreak;\n\tcase 58: /* IvyBridge */\n\tcase 62: /* IvyBridge EP */\n\t\tmemcpy(hw_cache_event_ids, snb_hw_cache_event_ids,\n\t\t sizeof(hw_cache_event_ids));\n\t\tmemcpy(hw_cache_extra_regs, snb_hw_cache_extra_regs,\n\t\t sizeof(hw_cache_extra_regs));\n\n\t\tintel_pmu_lbr_init_snb();\n\n\t\tx86_pmu.event_constraints = intel_ivb_event_constraints;\n\t\tx86_pmu.pebs_constraints = intel_ivb_pebs_event_constraints;\n\t\tx86_pmu.pebs_aliases = intel_pebs_aliases_snb;\n\t\tx86_pmu.extra_regs = intel_snb_extra_regs;\n\t\t/* all extra regs are per-cpu when HT is on */\n\t\tx86_pmu.er_flags |= ERF_HAS_RSP_1;\n\t\tx86_pmu.er_flags |= ERF_NO_HT_SHARING;\n\n\t\t/* UOPS_ISSUED.ANY,c=1,i=1 to count stall cycles */\n\t\tintel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] =\n\t\t\tX86_CONFIG(.event=0x0e, .umask=0x01, .inv=1, .cmask=1);\n\n\t\tpr_cont(\"IvyBridge events, \");\n\t\tbreak;\n\n\n\tdefault:\n\t\tswitch (x86_pmu.version) {\n\t\tcase 1:\n\t\t\tx86_pmu.event_constraints = intel_v1_event_constraints;\n\t\t\tpr_cont(\"generic architected perfmon v1, \");\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t/*\n\t\t\t * default constraints for v2 and up\n\t\t\t */\n\t\t\tx86_pmu.event_constraints = intel_gen_event_constraints;\n\t\t\tpr_cont(\"generic architected perfmon, \");\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (x86_pmu.num_counters > INTEL_PMC_MAX_GENERIC) {\n\t\tWARN(1, KERN_ERR \"hw perf events %d > max(%d), clipping!\",\n\t\t x86_pmu.num_counters, INTEL_PMC_MAX_GENERIC);\n\t\tx86_pmu.num_counters = INTEL_PMC_MAX_GENERIC;\n\t}\n\tx86_pmu.intel_ctrl = (1 << x86_pmu.num_counters) - 1;\n\n\tif (x86_pmu.num_counters_fixed > INTEL_PMC_MAX_FIXED) {\n\t\tWARN(1, KERN_ERR \"hw perf events fixed %d > max(%d), clipping!\",\n\t\t x86_pmu.num_counters_fixed, INTEL_PMC_MAX_FIXED);\n\t\tx86_pmu.num_counters_fixed = INTEL_PMC_MAX_FIXED;\n\t}\n\n\tx86_pmu.intel_ctrl |=\n\t\t((1LL << x86_pmu.num_counters_fixed)-1) << INTEL_PMC_IDX_FIXED;\n\n\tif (x86_pmu.event_constraints) {\n\t\t/*\n\t\t * event on fixed counter2 (REF_CYCLES) only works on this\n\t\t * counter, so do not extend mask to generic counters\n\t\t */\n\t\tfor_each_event_constraint(c, x86_pmu.event_constraints) {\n\t\t\tif (c->cmask != X86_RAW_EVENT_MASK\n\t\t\t || c->idxmsk64 == INTEL_PMC_MSK_FIXED_REF_CYCLES) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tc->idxmsk64 |= (1ULL << x86_pmu.num_counters) - 1;\n\t\t\tc->weight += x86_pmu.num_counters;\n\t\t}\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-401'], 'message': 'perf/x86: Fix offcore_rsp valid mask for SNB/IVB\n\nThe valid mask for both offcore_response_0 and\noffcore_response_1 was wrong for SNB/SNB-EP,\nIVB/IVB-EP. It was possible to write to\nreserved bit and cause a GP fault crashing\nthe kernel.\n\nThis patch fixes the problem by correctly marking the\nreserved bits in the valid mask for all the processors\nmentioned above.\n\nA distinction between desktop and server parts is introduced\nbecause bits 24-30 are only available on the server parts.\n\nThis version of the patch is just a rebase to perf/urgent tree\nand should apply to older kernels as well.\n\nSigned-off-by: Stephane Eranian \nCc: peterz@infradead.org\nCc: jolsa@redhat.com\nCc: gregkh@linuxfoundation.org\nCc: security@kernel.org\nCc: ak@linux.intel.com\nSigned-off-by: Ingo Molnar '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: frag6_print(netdissect_options *ndo, register const u_char *bp, register const u_char *bp2)\n{\n\tregister const struct ip6_frag *dp;\n\tregister const struct ip6_hdr *ip6;\n\n\tdp = (const struct ip6_frag *)bp;\n\tip6 = (const struct ip6_hdr *)bp2;\n\n\tND_TCHECK(dp->ip6f_offlg);\n\n\tif (ndo->ndo_vflag) {\n\t\tND_PRINT((ndo, \"frag (0x%08x:%d|%ld)\",\n\t\t EXTRACT_32BITS(&dp->ip6f_ident),\n\t\t EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK,\n\t\t sizeof(struct ip6_hdr) + EXTRACT_16BITS(&ip6->ip6_plen) -\n\t\t\t (long)(bp - bp2) - sizeof(struct ip6_frag)));\n\t} else {\n\t\tND_PRINT((ndo, \"frag (%d|%ld)\",\n\t\t EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK,\n\t\t sizeof(struct ip6_hdr) + EXTRACT_16BITS(&ip6->ip6_plen) -\n\t\t\t (long)(bp - bp2) - sizeof(struct ip6_frag)));\n\t}\n\n\t/* it is meaningless to decode non-first fragment */\n\tif ((EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK) != 0)\n\t\treturn -1;\n\telse\n\t{\n\t\tND_PRINT((ndo, \" \"));\n\t\treturn sizeof(struct ip6_frag);\n\t}\ntrunc:\n\tND_PRINT((ndo, \"[|frag]\"));\n\treturn -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13031/Check for the presence of the entire IPv6 fragment header.\n\nThis fixes a buffer over-read discovered by Bhargava Shastry,\nSecT/TU Berlin.\n\nAdd a test using the capture file supplied by the reporter(s), modified\nso the capture file won't be rejected as an invalid capture.\n\nClean up some whitespace in tests/TESTLIST while we're at it.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void Compute(OpKernelContext* ctx) override {\n const auto splits = ctx->input(0).flat();\n const auto values = ctx->input(1).flat();\n const Tensor& size_t = ctx->input(2);\n const auto weights = ctx->input(3).flat();\n const int64 weights_size = weights.size();\n\n Tidx size = size_t.scalar()();\n OP_REQUIRES(\n ctx, size >= 0,\n errors::InvalidArgument(\"size (\", size, \") must be non-negative\"));\n\n int num_rows = splits.size() - 1;\n int num_values = values.size();\n int batch_idx = 0;\n\n Tensor* out_t;\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(0, TensorShape({num_rows, size}), &out_t));\n functor::SetZeroFunctor fill;\n fill(ctx->eigen_device(), out_t->flat());\n const auto out = out_t->matrix();\n\n for (int idx = 0; idx < num_values; ++idx) {\n while (idx >= splits(batch_idx)) {\n batch_idx++;\n }\n Tidx bin = values(idx);\n OP_REQUIRES(ctx, bin >= 0,\n errors::InvalidArgument(\"Input must be non-negative\"));\n if (bin < size) {\n if (binary_output_) {\n out(batch_idx - 1, bin) = T(1);\n } else {\n T value = (weights_size > 0) ? weights(idx) : T(1);\n out(batch_idx - 1, bin) += value;\n }\n }\n }\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-787'], 'message': 'Fix an invalid address vulnerability in `tf.raw_ops.RaggedBincount`.\n\nPiperOrigin-RevId: 368293153\nChange-Id: I4b4e493d3fd05e7dc55a55de3a041a80a4f275c3'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline int copy_regset_from_user(struct task_struct *target,\n\t\t\t\t\tconst struct user_regset_view *view,\n\t\t\t\t\tunsigned int setno,\n\t\t\t\t\tunsigned int offset, unsigned int size,\n\t\t\t\t\tconst void __user *data)\n{\n\tconst struct user_regset *regset = &view->regsets[setno];\n\n\tif (!access_ok(VERIFY_READ, data, size))\n\t\treturn -EIO;\n\n\treturn regset->set(target, regset, offset, size, NULL, data);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'regset: Prevent null pointer reference on readonly regsets\n\nThe regset common infrastructure assumed that regsets would always\nhave .get and .set methods, but not necessarily .active methods.\nUnfortunately people have since written regsets without .set methods.\n\nRather than putting in stub functions everywhere, handle regsets with\nnull .get or .set methods explicitly.\n\nSigned-off-by: H. Peter Anvin \nReviewed-by: Oleg Nesterov \nAcked-by: Roland McGrath \nCc: \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: njs_vmcode_await(njs_vm_t *vm, njs_vmcode_await_t *await,\n njs_promise_capability_t *pcap, njs_async_ctx_t *ctx)\n{\n size_t size;\n njs_int_t ret;\n njs_frame_t *frame;\n njs_value_t ctor, val, on_fulfilled, on_rejected, *value;\n njs_promise_t *promise;\n njs_function_t *fulfilled, *rejected;\n njs_native_frame_t *active;\n\n active = &vm->active_frame->native;\n\n value = njs_scope_valid_value(vm, await->retval);\n if (njs_slow_path(value == NULL)) {\n return NJS_ERROR;\n }\n\n njs_set_function(&ctor, &vm->constructors[NJS_OBJ_TYPE_PROMISE]);\n\n promise = njs_promise_resolve(vm, &ctor, value);\n if (njs_slow_path(promise == NULL)) {\n return NJS_ERROR;\n }\n\n if (ctx == NULL) {\n ctx = njs_mp_alloc(vm->mem_pool, sizeof(njs_async_ctx_t));\n if (njs_slow_path(ctx == NULL)) {\n njs_memory_error(vm);\n return NJS_ERROR;\n }\n\n size = njs_function_frame_size(active);\n\n fulfilled = njs_promise_create_function(vm, size);\n if (njs_slow_path(fulfilled == NULL)) {\n return NJS_ERROR;\n }\n\n ctx->await = fulfilled->context;\n ctx->capability = pcap;\n\n ret = njs_function_frame_save(vm, ctx->await, NULL);\n if (njs_slow_path(ret != NJS_OK)) {\n return NJS_ERROR;\n }\n\n } else {\n fulfilled = njs_promise_create_function(vm, 0);\n if (njs_slow_path(fulfilled == NULL)) {\n return NJS_ERROR;\n }\n }\n\n ctx->pc = (u_char *) await + sizeof(njs_vmcode_await_t);\n ctx->index = await->retval;\n\n frame = (njs_frame_t *) active;\n\n if (frame->exception.catch != NULL) {\n ctx->await->native.pc = frame->exception.catch;\n\n } else {\n ctx->await->native.pc = ctx->pc;\n }\n\n fulfilled->context = ctx;\n fulfilled->args_count = 1;\n fulfilled->u.native = njs_await_fulfilled;\n\n rejected = njs_promise_create_function(vm, 0);\n if (njs_slow_path(rejected == NULL)) {\n return NJS_ERROR;\n }\n\n rejected->context = ctx;\n rejected->args_count = 1;\n rejected->u.native = njs_await_rejected;\n\n njs_set_promise(&val, promise);\n njs_set_function(&on_fulfilled, fulfilled);\n njs_set_function(&on_rejected, rejected);\n\n ret = njs_promise_perform_then(vm, &val, &on_fulfilled, &on_rejected, NULL);\n if (njs_slow_path(ret != NJS_OK)) {\n return NJS_ERROR;\n }\n\n (void) njs_vmcode_return(vm, NULL, &vm->retval);\n\n return NJS_AGAIN;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed njs_vmcode_interpreter() when await fails.\n\nPreviously, while interpreting a user function, njs_vmcode_interpreter()\nmight return prematurely when an error happens in await instruction.\nThis is not correct because the current frame has to be unwound (or\nexception caught) first.\n\nThe fix is to exit through only 5 appropriate exit points to ensure\nproper unwinding.\n\nThe patch correctly fixes issue reported in 07ef6c1f04f1 (0.7.3).\n\nThis closes #506 issue on Github.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int on_message_complete(http_parser* self_)\n {\n HTTPParser* self = static_cast(self_);\n\n self->process_message();\n return 0;\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Prevent HTTP pipelining which Crow doesn't support.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: grub_fshelp_read_file (grub_disk_t disk, grub_fshelp_node_t node,\n\t\t void (*read_hook) (grub_disk_addr_t sector,\n\t\t\t\t\t unsigned offset,\n\t\t\t\t\t unsigned length,\n\t\t\t\t\t void *closure),\n\t\t void *closure, int flags,\n\t\t grub_off_t pos, grub_size_t len, char *buf,\n\t\t grub_disk_addr_t (*get_block) (grub_fshelp_node_t node,\n\t\t\t\t\t\t grub_disk_addr_t block),\n\t\t grub_off_t filesize, int log2blocksize)\n{\n grub_disk_addr_t i, blockcnt;\n int blocksize = 1 << (log2blocksize + GRUB_DISK_SECTOR_BITS);\n\n /* Adjust LEN so it we can't read past the end of the file. */\n if (pos + len > filesize)\n len = filesize - pos;\n\n blockcnt = ((len + pos) + blocksize - 1) >>\n (log2blocksize + GRUB_DISK_SECTOR_BITS);\n\n for (i = pos >> (log2blocksize + GRUB_DISK_SECTOR_BITS); i < blockcnt; i++)\n {\n grub_disk_addr_t blknr;\n int blockoff = pos & (blocksize - 1);\n int blockend = blocksize;\n\n int skipfirst = 0;\n\n blknr = get_block (node, i);\n if (grub_errno)\n\treturn -1;\n\n blknr = blknr << log2blocksize;\n\n /* Last block. */\n if (i == blockcnt - 1)\n\t{\n\t blockend = (len + pos) & (blocksize - 1);\n\n\t /* The last portion is exactly blocksize. */\n\t if (! blockend)\n\t blockend = blocksize;\n\t}\n\n /* First block. */\n if (i == (pos >> (log2blocksize + GRUB_DISK_SECTOR_BITS)))\n\t{\n\t skipfirst = blockoff;\n\t blockend -= skipfirst;\n\t}\n\n /* If the block number is 0 this block is not stored on disk but\n\t is zero filled instead. */\n if (blknr)\n\t{\n\t disk->read_hook = read_hook;\n\t disk->closure = closure;\n\n//printf (\"blknr: %d\\n\", blknr);\ngrub_hack_lastoff = blknr * 512;\n\t grub_disk_read_ex (disk, blknr, skipfirst, blockend, buf, flags);\n\t disk->read_hook = 0;\n\t if (grub_errno)\n\t return -1;\n\t}\n else if (buf)\n\tgrub_memset (buf, 0, blockend);\n\n if (buf)\n\tbuf += blocksize - skipfirst;\n }\n\n return len;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-787'], 'message': 'Fix ext2 buffer overflow in r2_sbu_grub_memmove'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: struct lib_t* MACH0_(get_libs)(struct MACH0_(obj_t)* bin) {\n\tstruct lib_t *libs;\n\tint i;\n\n\tif (!bin->nlibs)\n\t\treturn NULL;\n\tif (!(libs = calloc ((bin->nlibs + 1), sizeof(struct lib_t))))\n\t\treturn NULL;\n\tfor (i = 0; i < bin->nlibs; i++) {\n\t\tstrncpy (libs[i].name, bin->libs[i], R_BIN_MACH0_STRING_LENGTH);\n\t\tlibs[i].name[R_BIN_MACH0_STRING_LENGTH-1] = '\\0';\n\t\tlibs[i].last = 0;\n\t}\n\tlibs[i].last = 1;\n\treturn libs;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'Fix null deref and uaf in mach0 parser'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: gql_intro_eval(agooErr err, gqlDoc doc, gqlSel sel, gqlValue result, int depth) {\n struct _gqlField\tfield;\n struct _gqlCobj\tobj;\n\n if (0 == strcmp(\"__type\", sel->name)) {\n\tif (1 < depth) {\n\t return agoo_err_set(err, AGOO_ERR_EVAL, \"__type can only be called from a query root.\");\n\t}\n\tobj.clas = &root_class;\n\tobj.ptr = NULL;\n } else if (0 == strcmp(\"__schema\", sel->name)) {\n\tif (1 < depth) {\n\t return agoo_err_set(err, AGOO_ERR_EVAL, \"__scheme can only be called from a query root.\");\n\t}\n\tobj.clas = &root_class;\n\tobj.ptr = NULL;\n } else {\n\treturn agoo_err_set(err, AGOO_ERR_EVAL, \"%s can only be called from the query root.\", sel->name);\n }\n memset(&field, 0, sizeof(field));\n field.name = sel->name;\n field.type = sel->type;\n\n doc->funcs.resolve = gql_cobj_resolve;\n doc->funcs.type = gql_cobj_ref_type;\n\n return gql_cobj_resolve(err, doc, &obj, &field, sel, result, depth);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'Protect against recursive fragment in schema\n\nReally a error on the developers part but this catches the error.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: DwaCompressor::uncompress\n (const char *inPtr,\n int inSize,\n Imath::Box2i range,\n const char *&outPtr)\n{\n int minX = range.min.x;\n int maxX = std::min (range.max.x, _max[0]);\n int minY = range.min.y;\n int maxY = std::min (range.max.y, _max[1]);\n\n int headerSize = NUM_SIZES_SINGLE*sizeof(Int64);\n if (inSize < headerSize) \n {\n throw Iex::InputExc(\"Error uncompressing DWA data\"\n \"(truncated header).\");\n }\n\n // \n // Flip the counters from XDR to NATIVE\n //\n\n for (int i = 0; i < NUM_SIZES_SINGLE; ++i)\n {\n Int64 *dst = (((Int64 *)inPtr) + i);\n const char *src = (char *)(((Int64 *)inPtr) + i);\n\n Xdr::read (src, *dst);\n }\n\n //\n // Unwind all the counter info\n //\n\n const Int64 *inPtr64 = (const Int64*) inPtr;\n\n Int64 version = *(inPtr64 + VERSION);\n Int64 unknownUncompressedSize = *(inPtr64 + UNKNOWN_UNCOMPRESSED_SIZE);\n Int64 unknownCompressedSize = *(inPtr64 + UNKNOWN_COMPRESSED_SIZE);\n Int64 acCompressedSize = *(inPtr64 + AC_COMPRESSED_SIZE);\n Int64 dcCompressedSize = *(inPtr64 + DC_COMPRESSED_SIZE);\n Int64 rleCompressedSize = *(inPtr64 + RLE_COMPRESSED_SIZE);\n Int64 rleUncompressedSize = *(inPtr64 + RLE_UNCOMPRESSED_SIZE);\n Int64 rleRawSize = *(inPtr64 + RLE_RAW_SIZE);\n \n Int64 totalAcUncompressedCount = *(inPtr64 + AC_UNCOMPRESSED_COUNT); \n Int64 totalDcUncompressedCount = *(inPtr64 + DC_UNCOMPRESSED_COUNT); \n\n Int64 acCompression = *(inPtr64 + AC_COMPRESSION); \n\n Int64 compressedSize = unknownCompressedSize + \n acCompressedSize +\n dcCompressedSize +\n rleCompressedSize;\n\n const char *dataPtr = inPtr + NUM_SIZES_SINGLE * sizeof(Int64);\n\n if (inSize < headerSize + compressedSize) \n {\n throw Iex::InputExc(\"Error uncompressing DWA data\"\n \"(truncated file).\");\n }\n\n if (unknownUncompressedSize < 0 || \n unknownCompressedSize < 0 ||\n acCompressedSize < 0 || \n dcCompressedSize < 0 ||\n rleCompressedSize < 0 || \n rleUncompressedSize < 0 ||\n rleRawSize < 0 || \n totalAcUncompressedCount < 0 || \n totalDcUncompressedCount < 0) \n {\n throw Iex::InputExc(\"Error uncompressing DWA data\"\n \" (corrupt header).\");\n }\n\n if (version < 2) \n initializeLegacyChannelRules();\n else\n {\n unsigned short ruleSize = 0;\n Xdr::read(dataPtr, ruleSize);\n\n if (ruleSize < 0) \n throw Iex::InputExc(\"Error uncompressing DWA data\"\n \" (corrupt header file).\");\n\n headerSize += ruleSize;\n if (inSize < headerSize + compressedSize)\n throw Iex::InputExc(\"Error uncompressing DWA data\"\n \" (truncated file).\");\n\n _channelRules.clear();\n ruleSize -= Xdr::size ();\n while (ruleSize > 0) \n {\n Classifier rule(dataPtr, ruleSize);\n \n _channelRules.push_back(rule);\n ruleSize -= rule.size();\n }\n }\n\n\n size_t outBufferSize = 0;\n initializeBuffers(outBufferSize);\n\n //\n // Allocate _outBuffer, if we haven't done so already\n //\n\n if (_maxScanLineSize * numScanLines() > _outBufferSize) \n {\n _outBufferSize = _maxScanLineSize * numScanLines();\n if (_outBuffer != 0)\n delete[] _outBuffer;\n _outBuffer = new char[_maxScanLineSize * numScanLines()];\n }\n\n\n char *outBufferEnd = _outBuffer;\n\n \n //\n // Find the start of the RLE packed AC components and\n // the DC components for each channel. This will be handy \n // if you want to decode the channels in parallel later on.\n //\n\n char *packedAcBufferEnd = 0; \n\n if (_packedAcBuffer)\n packedAcBufferEnd = _packedAcBuffer;\n\n char *packedDcBufferEnd = 0;\n\n if (_packedDcBuffer)\n packedDcBufferEnd = _packedDcBuffer;\n\n //\n // UNKNOWN data is packed first, followed by the \n // Huffman-compressed AC, then the DC values, \n // and then the zlib compressed RLE data.\n //\n \n const char *compressedUnknownBuf = dataPtr;\n\n const char *compressedAcBuf = compressedUnknownBuf + \n static_cast(unknownCompressedSize);\n const char *compressedDcBuf = compressedAcBuf +\n static_cast(acCompressedSize);\n const char *compressedRleBuf = compressedDcBuf + \n static_cast(dcCompressedSize);\n\n // \n // Sanity check that the version is something we expect. Right now, \n // we can decode version 0, 1, and 2. v1 adds 'end of block' symbols\n // to the AC RLE. v2 adds channel classification rules at the \n // start of the data block.\n //\n\n if ((version < 0) || (version > 2))\n throw Iex::InputExc (\"Invalid version of compressed data block\"); \n\n setupChannelData(minX, minY, maxX, maxY);\n\n // \n // Uncompress the UNKNOWN data into _planarUncBuffer[UNKNOWN]\n //\n\n if (unknownCompressedSize > 0)\n {\n uLongf outSize = static_cast(\n ceil( (float)unknownUncompressedSize * 1.01) + 100);\n\n if (unknownUncompressedSize < 0 || \n outSize > _planarUncBufferSize[UNKNOWN]) \n {\n throw Iex::InputExc(\"Error uncompressing DWA data\"\n \"(corrupt header).\");\n }\n\n if (Z_OK != ::uncompress\n ((Bytef *)_planarUncBuffer[UNKNOWN],\n &outSize,\n (Bytef *)compressedUnknownBuf,\n (uLong)unknownCompressedSize))\n {\n throw Iex::BaseExc(\"Error uncompressing UNKNOWN data.\");\n }\n }\n\n // \n // Uncompress the AC data into _packedAcBuffer\n //\n\n if (acCompressedSize > 0)\n {\n if (totalAcUncompressedCount*sizeof(unsigned short) > _packedAcBufferSize)\n {\n throw Iex::InputExc(\"Error uncompressing DWA data\"\n \"(corrupt header).\");\n }\n\n //\n // Don't trust the user to get it right, look in the file.\n //\n\n switch (acCompression)\n {\n case STATIC_HUFFMAN:\n\n hufUncompress\n (compressedAcBuf, \n (int)acCompressedSize, \n (unsigned short *)_packedAcBuffer, \n (int)totalAcUncompressedCount); \n\n break;\n\n case DEFLATE:\n {\n uLongf destLen =\n (int)(totalAcUncompressedCount) * sizeof (unsigned short);\n\n if (Z_OK != ::uncompress\n ((Bytef *)_packedAcBuffer,\n &destLen,\n (Bytef *)compressedAcBuf,\n (uLong)acCompressedSize))\n {\n throw Iex::InputExc (\"Data decompression (zlib) failed.\");\n }\n\n if (totalAcUncompressedCount * sizeof (unsigned short) !=\n destLen)\n {\n throw Iex::InputExc (\"AC data corrupt.\"); \n }\n }\n break;\n\n default:\n\n throw Iex::NoImplExc (\"Unknown AC Compression\");\n break;\n }\n }\n\n //\n // Uncompress the DC data into _packedDcBuffer\n //\n\n if (dcCompressedSize > 0)\n {\n if (totalDcUncompressedCount*sizeof(unsigned short) > _packedDcBufferSize)\n {\n throw Iex::InputExc(\"Error uncompressing DWA data\"\n \"(corrupt header).\");\n }\n\n if (_zip->uncompress\n (compressedDcBuf, (int)dcCompressedSize, _packedDcBuffer)\n != (int)totalDcUncompressedCount * sizeof (unsigned short))\n {\n throw Iex::BaseExc(\"DC data corrupt.\");\n }\n }\n\n //\n // Uncompress the RLE data into _rleBuffer, then unRLE the results\n // into _planarUncBuffer[RLE]\n //\n\n if (rleRawSize > 0)\n {\n if (rleUncompressedSize > _rleBufferSize ||\n rleRawSize > _planarUncBufferSize[RLE])\n {\n throw Iex::InputExc(\"Error uncompressing DWA data\"\n \"(corrupt header).\");\n }\n \n uLongf dstLen = (uLongf)rleUncompressedSize;\n\n if (Z_OK != ::uncompress\n ((Bytef *)_rleBuffer,\n &dstLen,\n (Bytef *)compressedRleBuf,\n (uLong)rleCompressedSize))\n {\n throw Iex::BaseExc(\"Error uncompressing RLE data.\");\n }\n\n if (dstLen != rleUncompressedSize)\n throw Iex::BaseExc(\"RLE data corrupted\");\n\n if (rleUncompress\n ((int)rleUncompressedSize, \n (int)rleRawSize,\n (signed char *)_rleBuffer,\n _planarUncBuffer[RLE]) != rleRawSize)\n { \n throw Iex::BaseExc(\"RLE data corrupted\");\n }\n }\n\n //\n // Determine the start of each row in the output buffer\n //\n\n std::vector decodedChannels (_channelData.size());\n std::vector< std::vector > rowPtrs (_channelData.size());\n\n for (unsigned int chan = 0; chan < _channelData.size(); ++chan)\n decodedChannels[chan] = false;\n\n outBufferEnd = _outBuffer;\n\n for (int y = minY; y <= maxY; ++y)\n {\n for (unsigned int chan = 0; chan < _channelData.size(); ++chan)\n {\n ChannelData *cd = &_channelData[chan];\n\n if (Imath::modp (y, cd->ySampling) != 0)\n continue;\n\n rowPtrs[chan].push_back (outBufferEnd);\n outBufferEnd += cd->width * Imf::pixelTypeSize (cd->type);\n }\n }\n\n //\n // Setup to decode each block of 3 channels that need to\n // be handled together\n //\n\n for (unsigned int csc = 0; csc < _cscSets.size(); ++csc)\n {\n int rChan = _cscSets[csc].idx[0]; \n int gChan = _cscSets[csc].idx[1]; \n int bChan = _cscSets[csc].idx[2]; \n\n\n LossyDctDecoderCsc decoder\n (rowPtrs[rChan],\n rowPtrs[gChan],\n rowPtrs[bChan],\n packedAcBufferEnd,\n packedDcBufferEnd,\n dwaCompressorToLinear,\n _channelData[rChan].width,\n _channelData[rChan].height,\n _channelData[rChan].type,\n _channelData[gChan].type,\n _channelData[bChan].type);\n\n decoder.execute();\n\n packedAcBufferEnd +=\n decoder.numAcValuesEncoded() * sizeof (unsigned short);\n\n packedDcBufferEnd +=\n decoder.numDcValuesEncoded() * sizeof (unsigned short);\n\n decodedChannels[rChan] = true;\n decodedChannels[gChan] = true;\n decodedChannels[bChan] = true;\n }\n\n //\n // Setup to handle the remaining channels by themselves\n //\n\n for (unsigned int chan = 0; chan < _channelData.size(); ++chan)\n {\n if (decodedChannels[chan])\n continue;\n\n ChannelData *cd = &_channelData[chan];\n int pixelSize = Imf::pixelTypeSize (cd->type);\n\n switch (cd->compression)\n {\n case LOSSY_DCT:\n\n //\n // Setup a single-channel lossy DCT decoder pointing\n // at the output buffer\n //\n\n {\n const unsigned short *linearLut = 0;\n\n if (!cd->pLinear)\n linearLut = dwaCompressorToLinear;\n\n LossyDctDecoder decoder\n (rowPtrs[chan],\n packedAcBufferEnd,\n packedDcBufferEnd,\n linearLut,\n cd->width,\n cd->height,\n cd->type);\n\n decoder.execute(); \n\n packedAcBufferEnd += \n decoder.numAcValuesEncoded() * sizeof (unsigned short);\n\n packedDcBufferEnd += \n decoder.numDcValuesEncoded() * sizeof (unsigned short);\n }\n\n break;\n\n case RLE:\n\n //\n // For the RLE case, the data has been un-RLE'd into\n // planarUncRleEnd[], but is still split out by bytes.\n // We need to rearrange the bytes back into the correct\n // order in the output buffer;\n //\n\n {\n int row = 0;\n\n for (int y = minY; y <= maxY; ++y)\n {\n if (Imath::modp (y, cd->ySampling) != 0)\n continue;\n\n char *dst = rowPtrs[chan][row];\n\n if (pixelSize == 2)\n {\n interleaveByte2 (dst, \n cd->planarUncRleEnd[0],\n cd->planarUncRleEnd[1],\n cd->width);\n \n cd->planarUncRleEnd[0] += cd->width;\n cd->planarUncRleEnd[1] += cd->width;\n }\n else\n {\n for (int x = 0; x < cd->width; ++x)\n {\n for (int byte = 0; byte < pixelSize; ++byte)\n {\n *dst++ = *cd->planarUncRleEnd[byte]++;\n }\n }\n }\n\n row++;\n }\n }\n\n break;\n\n case UNKNOWN:\n\n //\n // In the UNKNOWN case, data is already in planarUncBufferEnd\n // and just needs to copied over to the output buffer\n //\n\n {\n int row = 0;\n int dstScanlineSize = cd->width * Imf::pixelTypeSize (cd->type);\n\n for (int y = minY; y <= maxY; ++y)\n {\n if (Imath::modp (y, cd->ySampling) != 0)\n continue;\n\n memcpy (rowPtrs[chan][row],\n cd->planarUncBufferEnd,\n dstScanlineSize);\n\n cd->planarUncBufferEnd += dstScanlineSize;\n row++;\n }\n }\n\n break;\n\n default:\n\n throw Iex::NoImplExc (\"Unhandled compression scheme case\");\n break;\n }\n\n decodedChannels[chan] = true;\n }\n\n //\n // Return a ptr to _outBuffer\n //\n\n outPtr = _outBuffer;\n return (int)(outBufferEnd - _outBuffer);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284'], 'message': 'Add additional input validation in an attempt to resolve issue #232'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int _hostresolver_getaddrinfo(\n oe_resolver_t* resolver,\n const char* node,\n const char* service,\n const struct oe_addrinfo* hints,\n struct oe_addrinfo** res)\n{\n int ret = OE_EAI_FAIL;\n uint64_t handle = 0;\n struct oe_addrinfo* head = NULL;\n struct oe_addrinfo* tail = NULL;\n struct oe_addrinfo* p = NULL;\n\n OE_UNUSED(resolver);\n\n if (res)\n *res = NULL;\n\n if (!res)\n {\n ret = OE_EAI_SYSTEM;\n OE_RAISE_ERRNO(OE_EINVAL);\n }\n\n /* Get the handle for enumerating addrinfo structures. */\n {\n int retval = OE_EAI_FAIL;\n\n if (oe_syscall_getaddrinfo_open_ocall(\n &retval, node, service, hints, &handle) != OE_OK)\n {\n ret = OE_EAI_SYSTEM;\n OE_RAISE_ERRNO(OE_EINVAL);\n }\n\n if (!handle)\n {\n ret = retval;\n goto done;\n }\n }\n\n /* Enumerate addrinfo structures. */\n for (;;)\n {\n int retval = 0;\n size_t canonnamelen = 0;\n\n if (!(p = oe_calloc(1, sizeof(struct oe_addrinfo))))\n {\n ret = OE_EAI_MEMORY;\n goto done;\n }\n\n /* Determine required size ai_addr and ai_canonname buffers. */\n if (oe_syscall_getaddrinfo_read_ocall(\n &retval,\n handle,\n &p->ai_flags,\n &p->ai_family,\n &p->ai_socktype,\n &p->ai_protocol,\n p->ai_addrlen,\n &p->ai_addrlen,\n NULL,\n canonnamelen,\n &canonnamelen,\n NULL) != OE_OK)\n {\n ret = OE_EAI_SYSTEM;\n OE_RAISE_ERRNO(OE_EINVAL);\n }\n\n /* If this is the final element in the enumeration. */\n if (retval == 1)\n break;\n\n /* Expecting that addr and canonname buffers were too small. */\n if (retval != -1 || oe_errno != OE_ENAMETOOLONG)\n {\n ret = OE_EAI_SYSTEM;\n OE_RAISE_ERRNO(oe_errno);\n }\n\n if (p->ai_addrlen && !(p->ai_addr = oe_calloc(1, p->ai_addrlen)))\n {\n ret = OE_EAI_MEMORY;\n goto done;\n }\n\n if (canonnamelen && !(p->ai_canonname = oe_calloc(1, canonnamelen)))\n {\n ret = OE_EAI_MEMORY;\n goto done;\n }\n\n if (oe_syscall_getaddrinfo_read_ocall(\n &retval,\n handle,\n &p->ai_flags,\n &p->ai_family,\n &p->ai_socktype,\n &p->ai_protocol,\n p->ai_addrlen,\n &p->ai_addrlen,\n p->ai_addr,\n canonnamelen,\n &canonnamelen,\n p->ai_canonname) != OE_OK)\n {\n ret = OE_EAI_SYSTEM;\n OE_RAISE_ERRNO(OE_EINVAL);\n }\n\n /* Append to the list. */\n if (tail)\n {\n tail->ai_next = p;\n tail = p;\n }\n else\n {\n head = p;\n tail = p;\n }\n\n p = NULL;\n }\n\n /* Close the enumeration. */\n if (handle)\n {\n int retval = -1;\n\n if (oe_syscall_getaddrinfo_close_ocall(&retval, handle) != OE_OK)\n {\n ret = OE_EAI_SYSTEM;\n OE_RAISE_ERRNO(OE_EINVAL);\n }\n\n handle = 0;\n\n if (retval != 0)\n {\n ret = OE_EAI_SYSTEM;\n OE_RAISE_ERRNO(oe_errno);\n }\n }\n\n /* If the list is empty. */\n if (!head)\n {\n ret = OE_EAI_SYSTEM;\n OE_RAISE_ERRNO(OE_EINVAL);\n }\n\n *res = head;\n head = NULL;\n tail = NULL;\n ret = 0;\n\ndone:\n\n if (handle)\n {\n int retval;\n oe_syscall_getaddrinfo_close_ocall(&retval, handle);\n }\n\n if (head)\n oe_freeaddrinfo(head);\n\n if (p)\n oe_freeaddrinfo(p);\n\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-552'], 'message': 'Merge pull request from GHSA-525h-wxcc-f66m\n\nSigned-off-by: Ming-Wei Shih '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static ssize_t _hostsock_sendmsg(\n oe_fd_t* sock_,\n const struct oe_msghdr* msg,\n int flags)\n{\n ssize_t ret = -1;\n sock_t* sock = _cast_sock(sock_);\n void* buf = NULL;\n size_t buf_size = 0;\n\n oe_errno = 0;\n\n /* Check the parameters. */\n if (!sock || !msg || (msg->msg_iovlen && !msg->msg_iov))\n OE_RAISE_ERRNO(OE_EINVAL);\n\n /* Flatten the IO vector into contiguous heap memory. */\n if (oe_iov_pack(msg->msg_iov, (int)msg->msg_iovlen, &buf, &buf_size) != 0)\n OE_RAISE_ERRNO(OE_ENOMEM);\n\n /* Call the host. */\n if (oe_syscall_sendmsg_ocall(\n &ret,\n sock->host_fd,\n msg->msg_name,\n msg->msg_namelen,\n buf,\n msg->msg_iovlen,\n buf_size,\n msg->msg_control,\n msg->msg_controllen,\n flags) != OE_OK)\n {\n OE_RAISE_ERRNO(OE_EINVAL);\n }\n\ndone:\n\n if (buf)\n oe_free(buf);\n\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-552'], 'message': 'Merge pull request from GHSA-525h-wxcc-f66m\n\nSigned-off-by: Ming-Wei Shih '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static ssize_t _consolefs_read(oe_fd_t* file_, void* buf, size_t count)\n{\n ssize_t ret = -1;\n file_t* file = _cast_file(file_);\n\n if (!file)\n OE_RAISE_ERRNO(OE_EINVAL);\n\n if (oe_syscall_read_ocall(&ret, file->host_fd, buf, count) != OE_OK)\n OE_RAISE_ERRNO(OE_EINVAL);\n\ndone:\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-552'], 'message': 'Merge pull request from GHSA-525h-wxcc-f66m\n\nSigned-off-by: Ming-Wei Shih '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: PHP_FUNCTION(curl_escape)\n{\n\tchar *str = NULL, *res = NULL;\n\tsize_t str_len = 0;\n\tzval *zid;\n\tphp_curl *ch;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS(), \"rs\", &zid, &str, &str_len) == FAILURE) {\n\t\treturn;\n\t}\n\n\tif ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) {\n\t\tRETURN_FALSE;\n\t}\n\n\tif ((res = curl_easy_escape(ch->cp, str, str_len))) {\n\t\tRETVAL_STRING(res);\n\t\tcurl_free(res);\n\t} else {\n\t\tRETURN_FALSE;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix bug #72674 - check both curl_escape and curl_unescape'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int splice_pipe_to_pipe(struct pipe_inode_info *ipipe,\n\t\t\t struct pipe_inode_info *opipe,\n\t\t\t size_t len, unsigned int flags)\n{\n\tstruct pipe_buffer *ibuf, *obuf;\n\tint ret = 0, nbuf;\n\tbool input_wakeup = false;\n\n\nretry:\n\tret = ipipe_prep(ipipe, flags);\n\tif (ret)\n\t\treturn ret;\n\n\tret = opipe_prep(opipe, flags);\n\tif (ret)\n\t\treturn ret;\n\n\t/*\n\t * Potential ABBA deadlock, work around it by ordering lock\n\t * grabbing by pipe info address. Otherwise two different processes\n\t * could deadlock (one doing tee from A -> B, the other from B -> A).\n\t */\n\tpipe_double_lock(ipipe, opipe);\n\n\tdo {\n\t\tif (!opipe->readers) {\n\t\t\tsend_sig(SIGPIPE, current, 0);\n\t\t\tif (!ret)\n\t\t\t\tret = -EPIPE;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (!ipipe->nrbufs && !ipipe->writers)\n\t\t\tbreak;\n\n\t\t/*\n\t\t * Cannot make any progress, because either the input\n\t\t * pipe is empty or the output pipe is full.\n\t\t */\n\t\tif (!ipipe->nrbufs || opipe->nrbufs >= opipe->buffers) {\n\t\t\t/* Already processed some buffers, break */\n\t\t\tif (ret)\n\t\t\t\tbreak;\n\n\t\t\tif (flags & SPLICE_F_NONBLOCK) {\n\t\t\t\tret = -EAGAIN;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * We raced with another reader/writer and haven't\n\t\t\t * managed to process any buffers. A zero return\n\t\t\t * value means EOF, so retry instead.\n\t\t\t */\n\t\t\tpipe_unlock(ipipe);\n\t\t\tpipe_unlock(opipe);\n\t\t\tgoto retry;\n\t\t}\n\n\t\tibuf = ipipe->bufs + ipipe->curbuf;\n\t\tnbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1);\n\t\tobuf = opipe->bufs + nbuf;\n\n\t\tif (len >= ibuf->len) {\n\t\t\t/*\n\t\t\t * Simply move the whole buffer from ipipe to opipe\n\t\t\t */\n\t\t\t*obuf = *ibuf;\n\t\t\tibuf->ops = NULL;\n\t\t\topipe->nrbufs++;\n\t\t\tipipe->curbuf = (ipipe->curbuf + 1) & (ipipe->buffers - 1);\n\t\t\tipipe->nrbufs--;\n\t\t\tinput_wakeup = true;\n\t\t} else {\n\t\t\t/*\n\t\t\t * Get a reference to this pipe buffer,\n\t\t\t * so we can copy the contents over.\n\t\t\t */\n\t\t\tpipe_buf_get(ipipe, ibuf);\n\t\t\t*obuf = *ibuf;\n\n\t\t\t/*\n\t\t\t * Don't inherit the gift flag, we need to\n\t\t\t * prevent multiple steals of this page.\n\t\t\t */\n\t\t\tobuf->flags &= ~PIPE_BUF_FLAG_GIFT;\n\n\t\t\tobuf->len = len;\n\t\t\topipe->nrbufs++;\n\t\t\tibuf->offset += obuf->len;\n\t\t\tibuf->len -= obuf->len;\n\t\t}\n\t\tret += obuf->len;\n\t\tlen -= obuf->len;\n\t} while (len);\n\n\tpipe_unlock(ipipe);\n\tpipe_unlock(opipe);\n\n\t/*\n\t * If we put data in the output pipe, wakeup any potential readers.\n\t */\n\tif (ret > 0)\n\t\twakeup_pipe_readers(opipe);\n\n\tif (input_wakeup)\n\t\twakeup_pipe_writers(ipipe);\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'fs: prevent page refcount overflow in pipe_buf_get\n\nChange pipe_buf_get() to return a bool indicating whether it succeeded\nin raising the refcount of the page (if the thing in the pipe is a page).\nThis removes another mechanism for overflowing the page refcount. All\ncallers converted to handle a failure.\n\nReported-by: Jann Horn \nSigned-off-by: Matthew Wilcox \nCc: stable@kernel.org\nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int udp_push_pending_frames(struct sock *sk)\n{\n\tstruct udp_sock *up = udp_sk(sk);\n\tstruct inet_sock *inet = inet_sk(sk);\n\tstruct flowi4 *fl4 = &inet->cork.fl.u.ip4;\n\tstruct sk_buff *skb;\n\tint err = 0;\n\n\tskb = ip_finish_skb(sk, fl4);\n\tif (!skb)\n\t\tgoto out;\n\n\terr = udp_send_skb(skb, fl4);\n\nout:\n\tup->len = 0;\n\tup->pending = 0;\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-703'], 'message': 'ipv6: call udp_push_pending_frames when uncorking a socket with AF_INET pending data\n\nWe accidentally call down to ip6_push_pending_frames when uncorking\npending AF_INET data on a ipv6 socket. This results in the following\nsplat (from Dave Jones):\n\nskbuff: skb_under_panic: text:ffffffff816765f6 len:48 put:40 head:ffff88013deb6df0 data:ffff88013deb6dec tail:0x2c end:0xc0 dev:\n------------[ cut here ]------------\nkernel BUG at net/core/skbuff.c:126!\ninvalid opcode: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC\nModules linked in: dccp_ipv4 dccp 8021q garp bridge stp dlci mpoa snd_seq_dummy sctp fuse hidp tun bnep nfnetlink scsi_transport_iscsi rfcomm can_raw can_bcm af_802154 appletalk caif_socket can caif ipt_ULOG x25 rose af_key pppoe pppox ipx phonet irda llc2 ppp_generic slhc p8023 psnap p8022 llc crc_ccitt atm bluetooth\n+netrom ax25 nfc rfkill rds af_rxrpc coretemp hwmon kvm_intel kvm crc32c_intel snd_hda_codec_realtek ghash_clmulni_intel microcode pcspkr snd_hda_codec_hdmi snd_hda_intel snd_hda_codec snd_hwdep usb_debug snd_seq snd_seq_device snd_pcm e1000e snd_page_alloc snd_timer ptp snd pps_core soundcore xfs libcrc32c\nCPU: 2 PID: 8095 Comm: trinity-child2 Not tainted 3.10.0-rc7+ #37\ntask: ffff8801f52c2520 ti: ffff8801e6430000 task.ti: ffff8801e6430000\nRIP: 0010:[] [] skb_panic+0x63/0x65\nRSP: 0018:ffff8801e6431de8 EFLAGS: 00010282\nRAX: 0000000000000086 RBX: ffff8802353d3cc0 RCX: 0000000000000006\nRDX: 0000000000003b90 RSI: ffff8801f52c2ca0 RDI: ffff8801f52c2520\nRBP: ffff8801e6431e08 R08: 0000000000000000 R09: 0000000000000000\nR10: 0000000000000001 R11: 0000000000000001 R12: ffff88022ea0c800\nR13: ffff88022ea0cdf8 R14: ffff8802353ecb40 R15: ffffffff81cc7800\nFS: 00007f5720a10740(0000) GS:ffff880244c00000(0000) knlGS:0000000000000000\nCS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033\nCR2: 0000000005862000 CR3: 000000022843c000 CR4: 00000000001407e0\nDR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000\nDR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000600\nStack:\n ffff88013deb6dec 000000000000002c 00000000000000c0 ffffffff81a3f6e4\n ffff8801e6431e18 ffffffff8159a9aa ffff8801e6431e90 ffffffff816765f6\n ffffffff810b756b 0000000700000002 ffff8801e6431e40 0000fea9292aa8c0\nCall Trace:\n [] skb_push+0x3a/0x40\n [] ip6_push_pending_frames+0x1f6/0x4d0\n [] ? mark_held_locks+0xbb/0x140\n [] udp_v6_push_pending_frames+0x2b9/0x3d0\n [] ? udplite_getfrag+0x20/0x20\n [] udp_lib_setsockopt+0x1aa/0x1f0\n [] ? fget_light+0x387/0x4f0\n [] udpv6_setsockopt+0x34/0x40\n [] sock_common_setsockopt+0x14/0x20\n [] SyS_setsockopt+0x71/0xd0\n [] tracesys+0xdd/0xe2\nCode: 00 00 48 89 44 24 10 8b 87 d8 00 00 00 48 89 44 24 08 48 8b 87 e8 00 00 00 48 c7 c7 c0 04 aa 81 48 89 04 24 31 c0 e8 e1 7e ff ff <0f> 0b 55 48 89 e5 0f 0b 55 48 89 e5 0f 0b 55 48 89 e5 0f 0b 55\nRIP [] skb_panic+0x63/0x65\n RSP \n\nThis patch adds a check if the pending data is of address family AF_INET\nand directly calls udp_push_ending_frames from udp_v6_push_pending_frames\nif that is the case.\n\nThis bug was found by Dave Jones with trinity.\n\n(Also move the initialization of fl6 below the AF_INET check, even if\nnot strictly necessary.)\n\nCc: Dave Jones \nCc: YOSHIFUJI Hideaki \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ext4_xattr_block_set(handle_t *handle, struct inode *inode,\n\t\t struct ext4_xattr_info *i,\n\t\t struct ext4_xattr_block_find *bs)\n{\n\tstruct super_block *sb = inode->i_sb;\n\tstruct buffer_head *new_bh = NULL;\n\tstruct ext4_xattr_search *s = &bs->s;\n\tstruct mb_cache_entry *ce = NULL;\n\tint error = 0;\n\tstruct mb_cache *ext4_mb_cache = EXT4_GET_MB_CACHE(inode);\n\n#define header(x) ((struct ext4_xattr_header *)(x))\n\n\tif (i->value && i->value_len > sb->s_blocksize)\n\t\treturn -ENOSPC;\n\tif (s->base) {\n\t\tce = mb_cache_entry_get(ext4_mb_cache, bs->bh->b_bdev,\n\t\t\t\t\tbs->bh->b_blocknr);\n\t\tBUFFER_TRACE(bs->bh, \"get_write_access\");\n\t\terror = ext4_journal_get_write_access(handle, bs->bh);\n\t\tif (error)\n\t\t\tgoto cleanup;\n\t\tlock_buffer(bs->bh);\n\n\t\tif (header(s->base)->h_refcount == cpu_to_le32(1)) {\n\t\t\tif (ce) {\n\t\t\t\tmb_cache_entry_free(ce);\n\t\t\t\tce = NULL;\n\t\t\t}\n\t\t\tea_bdebug(bs->bh, \"modifying in-place\");\n\t\t\terror = ext4_xattr_set_entry(i, s);\n\t\t\tif (!error) {\n\t\t\t\tif (!IS_LAST_ENTRY(s->first))\n\t\t\t\t\text4_xattr_rehash(header(s->base),\n\t\t\t\t\t\t\t s->here);\n\t\t\t\text4_xattr_cache_insert(ext4_mb_cache,\n\t\t\t\t\tbs->bh);\n\t\t\t}\n\t\t\tunlock_buffer(bs->bh);\n\t\t\tif (error == -EFSCORRUPTED)\n\t\t\t\tgoto bad_block;\n\t\t\tif (!error)\n\t\t\t\terror = ext4_handle_dirty_xattr_block(handle,\n\t\t\t\t\t\t\t\t inode,\n\t\t\t\t\t\t\t\t bs->bh);\n\t\t\tif (error)\n\t\t\t\tgoto cleanup;\n\t\t\tgoto inserted;\n\t\t} else {\n\t\t\tint offset = (char *)s->here - bs->bh->b_data;\n\n\t\t\tunlock_buffer(bs->bh);\n\t\t\tif (ce) {\n\t\t\t\tmb_cache_entry_release(ce);\n\t\t\t\tce = NULL;\n\t\t\t}\n\t\t\tea_bdebug(bs->bh, \"cloning\");\n\t\t\ts->base = kmalloc(bs->bh->b_size, GFP_NOFS);\n\t\t\terror = -ENOMEM;\n\t\t\tif (s->base == NULL)\n\t\t\t\tgoto cleanup;\n\t\t\tmemcpy(s->base, BHDR(bs->bh), bs->bh->b_size);\n\t\t\ts->first = ENTRY(header(s->base)+1);\n\t\t\theader(s->base)->h_refcount = cpu_to_le32(1);\n\t\t\ts->here = ENTRY(s->base + offset);\n\t\t\ts->end = s->base + bs->bh->b_size;\n\t\t}\n\t} else {\n\t\t/* Allocate a buffer where we construct the new block. */\n\t\ts->base = kzalloc(sb->s_blocksize, GFP_NOFS);\n\t\t/* assert(header == s->base) */\n\t\terror = -ENOMEM;\n\t\tif (s->base == NULL)\n\t\t\tgoto cleanup;\n\t\theader(s->base)->h_magic = cpu_to_le32(EXT4_XATTR_MAGIC);\n\t\theader(s->base)->h_blocks = cpu_to_le32(1);\n\t\theader(s->base)->h_refcount = cpu_to_le32(1);\n\t\ts->first = ENTRY(header(s->base)+1);\n\t\ts->here = ENTRY(header(s->base)+1);\n\t\ts->end = s->base + sb->s_blocksize;\n\t}\n\n\terror = ext4_xattr_set_entry(i, s);\n\tif (error == -EFSCORRUPTED)\n\t\tgoto bad_block;\n\tif (error)\n\t\tgoto cleanup;\n\tif (!IS_LAST_ENTRY(s->first))\n\t\text4_xattr_rehash(header(s->base), s->here);\n\ninserted:\n\tif (!IS_LAST_ENTRY(s->first)) {\n\t\tnew_bh = ext4_xattr_cache_find(inode, header(s->base), &ce);\n\t\tif (new_bh) {\n\t\t\t/* We found an identical block in the cache. */\n\t\t\tif (new_bh == bs->bh)\n\t\t\t\tea_bdebug(new_bh, \"keeping\");\n\t\t\telse {\n\t\t\t\t/* The old block is released after updating\n\t\t\t\t the inode. */\n\t\t\t\terror = dquot_alloc_block(inode,\n\t\t\t\t\t\tEXT4_C2B(EXT4_SB(sb), 1));\n\t\t\t\tif (error)\n\t\t\t\t\tgoto cleanup;\n\t\t\t\tBUFFER_TRACE(new_bh, \"get_write_access\");\n\t\t\t\terror = ext4_journal_get_write_access(handle,\n\t\t\t\t\t\t\t\t new_bh);\n\t\t\t\tif (error)\n\t\t\t\t\tgoto cleanup_dquot;\n\t\t\t\tlock_buffer(new_bh);\n\t\t\t\tle32_add_cpu(&BHDR(new_bh)->h_refcount, 1);\n\t\t\t\tea_bdebug(new_bh, \"reusing; refcount now=%d\",\n\t\t\t\t\tle32_to_cpu(BHDR(new_bh)->h_refcount));\n\t\t\t\tunlock_buffer(new_bh);\n\t\t\t\terror = ext4_handle_dirty_xattr_block(handle,\n\t\t\t\t\t\t\t\t inode,\n\t\t\t\t\t\t\t\t new_bh);\n\t\t\t\tif (error)\n\t\t\t\t\tgoto cleanup_dquot;\n\t\t\t}\n\t\t\tmb_cache_entry_release(ce);\n\t\t\tce = NULL;\n\t\t} else if (bs->bh && s->base == bs->bh->b_data) {\n\t\t\t/* We were modifying this block in-place. */\n\t\t\tea_bdebug(bs->bh, \"keeping this block\");\n\t\t\tnew_bh = bs->bh;\n\t\t\tget_bh(new_bh);\n\t\t} else {\n\t\t\t/* We need to allocate a new block */\n\t\t\text4_fsblk_t goal, block;\n\n\t\t\tgoal = ext4_group_first_block_no(sb,\n\t\t\t\t\t\tEXT4_I(inode)->i_block_group);\n\n\t\t\t/* non-extent files can't have physical blocks past 2^32 */\n\t\t\tif (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))\n\t\t\t\tgoal = goal & EXT4_MAX_BLOCK_FILE_PHYS;\n\n\t\t\tblock = ext4_new_meta_blocks(handle, inode, goal, 0,\n\t\t\t\t\t\t NULL, &error);\n\t\t\tif (error)\n\t\t\t\tgoto cleanup;\n\n\t\t\tif (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))\n\t\t\t\tBUG_ON(block > EXT4_MAX_BLOCK_FILE_PHYS);\n\n\t\t\tea_idebug(inode, \"creating block %llu\",\n\t\t\t\t (unsigned long long)block);\n\n\t\t\tnew_bh = sb_getblk(sb, block);\n\t\t\tif (unlikely(!new_bh)) {\n\t\t\t\terror = -ENOMEM;\ngetblk_failed:\n\t\t\t\text4_free_blocks(handle, inode, NULL, block, 1,\n\t\t\t\t\t\t EXT4_FREE_BLOCKS_METADATA);\n\t\t\t\tgoto cleanup;\n\t\t\t}\n\t\t\tlock_buffer(new_bh);\n\t\t\terror = ext4_journal_get_create_access(handle, new_bh);\n\t\t\tif (error) {\n\t\t\t\tunlock_buffer(new_bh);\n\t\t\t\terror = -EIO;\n\t\t\t\tgoto getblk_failed;\n\t\t\t}\n\t\t\tmemcpy(new_bh->b_data, s->base, new_bh->b_size);\n\t\t\tset_buffer_uptodate(new_bh);\n\t\t\tunlock_buffer(new_bh);\n\t\t\text4_xattr_cache_insert(ext4_mb_cache, new_bh);\n\t\t\terror = ext4_handle_dirty_xattr_block(handle,\n\t\t\t\t\t\t\t inode, new_bh);\n\t\t\tif (error)\n\t\t\t\tgoto cleanup;\n\t\t}\n\t}\n\n\t/* Update the inode. */\n\tEXT4_I(inode)->i_file_acl = new_bh ? new_bh->b_blocknr : 0;\n\n\t/* Drop the previous xattr block. */\n\tif (bs->bh && bs->bh != new_bh)\n\t\text4_xattr_release_block(handle, inode, bs->bh);\n\terror = 0;\n\ncleanup:\n\tif (ce)\n\t\tmb_cache_entry_release(ce);\n\tbrelse(new_bh);\n\tif (!(bs->bh && s->base == bs->bh->b_data))\n\t\tkfree(s->base);\n\n\treturn error;\n\ncleanup_dquot:\n\tdquot_free_block(inode, EXT4_C2B(EXT4_SB(sb), 1));\n\tgoto cleanup;\n\nbad_block:\n\tEXT4_ERROR_INODE(inode, \"bad block %llu\",\n\t\t\t EXT4_I(inode)->i_file_acl);\n\tgoto cleanup;\n\n#undef header\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-241', 'CWE-19'], 'message': 'ext4: convert to mbcache2\n\nThe conversion is generally straightforward. The only tricky part is\nthat xattr block corresponding to found mbcache entry can get freed\nbefore we get buffer lock for that block. So we have to check whether\nthe entry is still valid after getting buffer lock.\n\nSigned-off-by: Jan Kara \nSigned-off-by: Theodore Ts'o '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void ion_free(struct ion_client *client, struct ion_handle *handle)\n{\n\tbool valid_handle;\n\n\tBUG_ON(client != handle->client);\n\n\tmutex_lock(&client->lock);\n\tvalid_handle = ion_handle_validate(client, handle);\n\n\tif (!valid_handle) {\n\t\tWARN(1, \"%s: invalid handle passed to free.\\n\", __func__);\n\t\tmutex_unlock(&client->lock);\n\t\treturn;\n\t}\n\tmutex_unlock(&client->lock);\n\tion_handle_put(handle);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-284'], 'message': 'staging/android/ion : fix a race condition in the ion driver\n\nThere is a use-after-free problem in the ion driver.\nThis is caused by a race condition in the ion_ioctl()\nfunction.\n\nA handle has ref count of 1 and two tasks on different\ncpus calls ION_IOC_FREE simultaneously.\n\ncpu 0 cpu 1\n-------------------------------------------------------\nion_handle_get_by_id()\n(ref == 2)\n ion_handle_get_by_id()\n (ref == 3)\n\nion_free()\n(ref == 2)\n\nion_handle_put()\n(ref == 1)\n\n ion_free()\n (ref == 0 so ion_handle_destroy() is\n called\n and the handle is freed.)\n\n ion_handle_put() is called and it\n decreases the slub's next free pointer\n\nThe problem is detected as an unaligned access in the\nspin lock functions since it uses load exclusive\n instruction. In some cases it corrupts the slub's\nfree pointer which causes a mis-aligned access to the\nnext free pointer.(kmalloc returns a pointer like\nffffc0745b4580aa). And it causes lots of other\nhard-to-debug problems.\n\nThis symptom is caused since the first member in the\nion_handle structure is the reference count and the\nion driver decrements the reference after it has been\nfreed.\n\nTo fix this problem client->lock mutex is extended\nto protect all the codes that uses the handle.\n\nSigned-off-by: Eun Taik Lee \nReviewed-by: Laura Abbott \nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: PHP_FUNCTION( msgfmt_format_message )\n{\n\tzval *args;\n\tUChar *spattern = NULL;\n\tint spattern_len = 0;\n\tchar *pattern = NULL;\n\tint pattern_len = 0;\n\tconst char *slocale = NULL;\n\tint slocale_len = 0;\n\tMessageFormatter_object mf = {0};\n\tMessageFormatter_object *mfo = &mf;\n\n\t/* Parse parameters. */\n\tif( zend_parse_method_parameters( ZEND_NUM_ARGS() TSRMLS_CC, getThis(), \"ssa\",\n\t\t &slocale, &slocale_len, &pattern, &pattern_len, &args ) == FAILURE )\n\t{\n\t\tintl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,\n\t\t\t\"msgfmt_format_message: unable to parse input params\", 0 TSRMLS_CC );\n\n\t\tRETURN_FALSE;\n\t}\n\n\tmsgformat_data_init(&mfo->mf_data TSRMLS_CC);\n\n\tif(pattern && pattern_len) {\n\t\tintl_convert_utf8_to_utf16(&spattern, &spattern_len, pattern, pattern_len, &INTL_DATA_ERROR_CODE(mfo));\n\t\tif( U_FAILURE(INTL_DATA_ERROR_CODE((mfo))) )\n\t\t{\n\t\t\tintl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,\n\t\t\t\t\"msgfmt_format_message: error converting pattern to UTF-16\", 0 TSRMLS_CC );\n\t\t\tRETURN_FALSE;\n\t\t}\n\t} else {\n\t\tspattern_len = 0;\n\t\tspattern = NULL;\n\t}\n\n\tif(slocale_len == 0) {\n\t\tslocale = intl_locale_get_default(TSRMLS_C);\n\t}\n\n#ifdef MSG_FORMAT_QUOTE_APOS\n\tif(msgformat_fix_quotes(&spattern, &spattern_len, &INTL_DATA_ERROR_CODE(mfo)) != SUCCESS) {\n\t\tintl_error_set( NULL, U_INVALID_FORMAT_ERROR,\n\t\t\t\"msgfmt_format_message: error converting pattern to quote-friendly format\", 0 TSRMLS_CC );\n\t\tRETURN_FALSE;\n\t}\n#endif\n\n\t/* Create an ICU message formatter. */\n\tMSG_FORMAT_OBJECT(mfo) = umsg_open(spattern, spattern_len, slocale, NULL, &INTL_DATA_ERROR_CODE(mfo));\n\tif(spattern && spattern_len) {\n\t\tefree(spattern);\n\t}\n\tINTL_METHOD_CHECK_STATUS(mfo, \"Creating message formatter failed\");\n\n\tmsgfmt_do_format(mfo, args, return_value TSRMLS_CC);\n\n\t/* drop the temporary formatter */\n\tmsgformat_data_free(&mfo->mf_data TSRMLS_CC);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix bug #73007: add locale length check'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int dnxhd_init_vlc(DNXHDContext *ctx, uint32_t cid, int bitdepth)\n{\n if (cid != ctx->cid) {\n const CIDEntry *cid_table = ff_dnxhd_get_cid_table(cid);\n\n if (!cid_table) {\n av_log(ctx->avctx, AV_LOG_ERROR, \"unsupported cid %\"PRIu32\"\\n\", cid);\n return AVERROR(ENOSYS);\n }\n if (cid_table->bit_depth != bitdepth &&\n cid_table->bit_depth != DNXHD_VARIABLE) {\n av_log(ctx->avctx, AV_LOG_ERROR, \"bit depth mismatches %d %d\\n\",\n cid_table->bit_depth, bitdepth);\n return AVERROR_INVALIDDATA;\n }\n ctx->cid_table = cid_table;\n av_log(ctx->avctx, AV_LOG_VERBOSE, \"Profile cid %\"PRIu32\".\\n\", cid);\n\n ff_free_vlc(&ctx->ac_vlc);\n ff_free_vlc(&ctx->dc_vlc);\n ff_free_vlc(&ctx->run_vlc);\n\n init_vlc(&ctx->ac_vlc, DNXHD_VLC_BITS, 257,\n ctx->cid_table->ac_bits, 1, 1,\n ctx->cid_table->ac_codes, 2, 2, 0);\n init_vlc(&ctx->dc_vlc, DNXHD_DC_VLC_BITS, bitdepth > 8 ? 14 : 12,\n ctx->cid_table->dc_bits, 1, 1,\n ctx->cid_table->dc_codes, 1, 1, 0);\n init_vlc(&ctx->run_vlc, DNXHD_VLC_BITS, 62,\n ctx->cid_table->run_bits, 1, 1,\n ctx->cid_table->run_codes, 2, 2, 0);\n\n ctx->cid = cid;\n }\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-252'], 'message': 'avcodec/dnxhddec: check and propagate function return value\n\nSimilar to CVE-2013-0868, here return value check for 'init_vlc' is needed.\ncrafted DNxHD data can cause unspecified impact.\n\nReviewed-by: Paul B Mahol \nSigned-off-by: James Almer '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: extern \"C\" void *malloc_wrapper(struct _reent *r, size_t size, void *caller)\n{\n void *ptr = NULL;\n#if MBED_MEM_TRACING_ENABLED\n mbed_mem_trace_lock();\n#endif\n#if MBED_HEAP_STATS_ENABLED\n malloc_stats_mutex->lock();\n alloc_info_t *alloc_info = (alloc_info_t *)__real__malloc_r(r, size + sizeof(alloc_info_t));\n if (alloc_info != NULL) {\n alloc_info->size = size;\n alloc_info->signature = MBED_HEAP_STATS_SIGNATURE;\n ptr = (void *)(alloc_info + 1);\n heap_stats.current_size += size;\n heap_stats.total_size += size;\n heap_stats.alloc_cnt += 1;\n if (heap_stats.current_size > heap_stats.max_size) {\n heap_stats.max_size = heap_stats.current_size;\n }\n heap_stats.overhead_size += get_malloc_block_total_size((void *)alloc_info) - size;\n } else {\n heap_stats.alloc_fail_cnt += 1;\n }\n malloc_stats_mutex->unlock();\n#else // #if MBED_HEAP_STATS_ENABLED\n ptr = __real__malloc_r(r, size);\n#endif // #if MBED_HEAP_STATS_ENABLED\n#if MBED_MEM_TRACING_ENABLED\n mbed_mem_trace_malloc(ptr, size, caller);\n mbed_mem_trace_unlock();\n#endif // #if MBED_MEM_TRACING_ENABLED\n return ptr;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Add integer overflow check to the malloc wrappers\n\nAdd a check that the combined size of the buffer to allocate and\nalloc_info_t does not exceed the maximum integer value representable\nby size_t.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: GF_Err gf_hinter_track_process(GF_RTPHinter *tkHint)\n{\n\tGF_Err e;\n\tu32 i, descIndex, duration;\n\tu64 ts;\n\tu8 PadBits;\n\tGF_Fraction ft;\n\tGF_ISOSample *samp;\n\n\ttkHint->HintSample = tkHint->RTPTime = 0;\n\n\ttkHint->TotalSample = gf_isom_get_sample_count(tkHint->file, tkHint->TrackNum);\n\tft.num = tkHint->rtp_p->sl_config.timestampResolution;\n\tft.den = tkHint->OrigTimeScale;\n\n\te = GF_OK;\n\tfor (i=0; iTotalSample; i++) {\n\t\tsamp = gf_isom_get_sample(tkHint->file, tkHint->TrackNum, i+1, &descIndex);\n\t\tif (!samp) return gf_isom_last_error(tkHint->file);\n\n\t\t//setup SL\n\t\ttkHint->CurrentSample = i + 1;\n\n\t\t/*keep same AU indicator if sync shadow - TODO FIXME: this assumes shadows are placed interleaved with\n\t\tthe track content which is the case for GPAC scene carousel generation, but may not always be true*/\n\t\tif (samp->IsRAP==RAP_REDUNDANT) {\n\t\t\ttkHint->rtp_p->sl_header.AU_sequenceNumber -= 1;\n\t\t\tsamp->IsRAP = RAP;\n\t\t}\n\n\t\tts = ft.num * (samp->DTS+samp->CTS_Offset) / ft.den;\n\t\ttkHint->rtp_p->sl_header.compositionTimeStamp = ts;\n\n\t\tts = ft.num * samp->DTS / ft.den;\n\t\ttkHint->rtp_p->sl_header.decodingTimeStamp = ts;\n\t\ttkHint->rtp_p->sl_header.randomAccessPointFlag = samp->IsRAP;\n\n\t\ttkHint->base_offset_in_sample = 0;\n\t\t/*crypted*/\n\t\tif (tkHint->rtp_p->slMap.IV_length) {\n\t\t\tGF_ISMASample *s = gf_isom_get_ismacryp_sample(tkHint->file, tkHint->TrackNum, samp, descIndex);\n\t\t\t/*one byte take for selective_enc flag*/\n\t\t\tif (s->flags & GF_ISOM_ISMA_USE_SEL_ENC) tkHint->base_offset_in_sample += 1;\n\t\t\tif (s->flags & GF_ISOM_ISMA_IS_ENCRYPTED) tkHint->base_offset_in_sample += s->IV_length + s->KI_length;\n\t\t\tgf_free(samp->data);\n\t\t\tsamp->data = s->data;\n\t\t\tsamp->dataLength = s->dataLength;\n\t\t\tgf_rtp_builder_set_cryp_info(tkHint->rtp_p, s->IV, (char*)s->key_indicator, (s->flags & GF_ISOM_ISMA_IS_ENCRYPTED) ? 1 : 0);\n\t\t\ts->data = NULL;\n\t\t\ts->dataLength = 0;\n\t\t\tgf_isom_ismacryp_delete_sample(s);\n\t\t}\n\n\t\tif (tkHint->rtp_p->sl_config.usePaddingFlag) {\n\t\t\tgf_isom_get_sample_padding_bits(tkHint->file, tkHint->TrackNum, i+1, &PadBits);\n\t\t\ttkHint->rtp_p->sl_header.paddingBits = PadBits;\n\t\t} else {\n\t\t\ttkHint->rtp_p->sl_header.paddingBits = 0;\n\t\t}\n\n\t\tduration = gf_isom_get_sample_duration(tkHint->file, tkHint->TrackNum, i+1);\n//\t\tts = (u32) (ft * (s64) (duration));\n\n\t\t/*unpack nal units*/\n\t\tif (tkHint->avc_nalu_size) {\n\t\t\tu32 v, size;\n\t\t\tu32 remain = samp->dataLength;\n\t\t\tchar *ptr = samp->data;\n\n\t\t\ttkHint->rtp_p->sl_header.accessUnitStartFlag = 1;\n\t\t\ttkHint->rtp_p->sl_header.accessUnitEndFlag = 0;\n\t\t\twhile (remain) {\n\t\t\t\tsize = 0;\n\t\t\t\tv = tkHint->avc_nalu_size;\n\t\t\t\tif (v>remain) {\n\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_RTP, (\"[rtp hinter] Broken AVC nalu encapsulation: NALU size length is %d but only %d bytes left in sample %d\\n\", v, remain, tkHint->CurrentSample));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\twhile (v) {\n\t\t\t\t\tsize |= (u8) *ptr;\n\t\t\t\t\tptr++;\n\t\t\t\t\tremain--;\n\t\t\t\t\tv-=1;\n\t\t\t\t\tif (v) size<<=8;\n\t\t\t\t}\n\t\t\t\ttkHint->base_offset_in_sample = samp->dataLength-remain;\n\t\t\t\tif (remain < size) {\n\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_RTP, (\"[rtp hinter] Broken AVC nalu encapsulation: NALU size is %d but only %d bytes left in sample %d\\n\", size, remain, tkHint->CurrentSample));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tremain -= size;\n\t\t\t\ttkHint->rtp_p->sl_header.accessUnitEndFlag = remain ? 0 : 1;\n\t\t\t\te = gf_rtp_builder_process(tkHint->rtp_p, ptr, size, (u8) !remain, samp->dataLength, duration, (u8) (descIndex + GF_RTP_TX3G_SIDX_OFFSET) );\n\t\t\t\tptr += size;\n\t\t\t\ttkHint->rtp_p->sl_header.accessUnitStartFlag = 0;\n\t\t\t}\n\t\t} else {\n\t\t\te = gf_rtp_builder_process(tkHint->rtp_p, samp->data, samp->dataLength, 1, samp->dataLength, duration, (u8) (descIndex + GF_RTP_TX3G_SIDX_OFFSET) );\n\t\t}\n\t\ttkHint->rtp_p->sl_header.packetSequenceNumber += 1;\n\n\t\t//signal some progress\n\t\tgf_set_progress(\"Hinting\", tkHint->CurrentSample, tkHint->TotalSample);\n\n\t\ttkHint->rtp_p->sl_header.AU_sequenceNumber += 1;\n\t\tgf_isom_sample_del(&samp);\n\n\t\tif (e) return e;\n\t}\n\n\t//flush\n\tgf_rtp_builder_process(tkHint->rtp_p, NULL, 0, 1, 0, 0, 0);\n\n\tgf_isom_end_hint_sample(tkHint->file, tkHint->HintTrack, (u8) tkHint->SampleIsRAP);\n\treturn GF_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'fixed #1662'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: CreateStatistics(CreateStatsStmt *stmt)\n{\n\tint16\t\tattnums[STATS_MAX_DIMENSIONS];\n\tint\t\t\tnumcols = 0;\n\tchar\t *namestr;\n\tNameData\tstxname;\n\tOid\t\t\tstatoid;\n\tOid\t\t\tnamespaceId;\n\tOid\t\t\tstxowner = GetUserId();\n\tHeapTuple\thtup;\n\tDatum\t\tvalues[Natts_pg_statistic_ext];\n\tbool\t\tnulls[Natts_pg_statistic_ext];\n\tDatum\t\tdatavalues[Natts_pg_statistic_ext_data];\n\tbool\t\tdatanulls[Natts_pg_statistic_ext_data];\n\tint2vector *stxkeys;\n\tRelation\tstatrel;\n\tRelation\tdatarel;\n\tRelation\trel = NULL;\n\tOid\t\t\trelid;\n\tObjectAddress parentobject,\n\t\t\t\tmyself;\n\tDatum\t\ttypes[3];\t\t/* one for each possible type of statistic */\n\tint\t\t\tntypes;\n\tArrayType *stxkind;\n\tbool\t\tbuild_ndistinct;\n\tbool\t\tbuild_dependencies;\n\tbool\t\tbuild_mcv;\n\tbool\t\trequested_type = false;\n\tint\t\t\ti;\n\tListCell *cell;\n\n\tAssert(IsA(stmt, CreateStatsStmt));\n\n\t/*\n\t * Examine the FROM clause. Currently, we only allow it to be a single\n\t * simple table, but later we'll probably allow multiple tables and JOIN\n\t * syntax. The grammar is already prepared for that, so we have to check\n\t * here that what we got is what we can support.\n\t */\n\tif (list_length(stmt->relations) != 1)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t errmsg(\"only a single relation is allowed in CREATE STATISTICS\")));\n\n\tforeach(cell, stmt->relations)\n\t{\n\t\tNode\t *rln = (Node *) lfirst(cell);\n\n\t\tif (!IsA(rln, RangeVar))\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t errmsg(\"only a single relation is allowed in CREATE STATISTICS\")));\n\n\t\t/*\n\t\t * CREATE STATISTICS will influence future execution plans but does\n\t\t * not interfere with currently executing plans. So it should be\n\t\t * enough to take only ShareUpdateExclusiveLock on relation,\n\t\t * conflicting with ANALYZE and other DDL that sets statistical\n\t\t * information, but not with normal queries.\n\t\t */\n\t\trel = relation_openrv((RangeVar *) rln, ShareUpdateExclusiveLock);\n\n\t\t/* Restrict to allowed relation types */\n\t\tif (rel->rd_rel->relkind != RELKIND_RELATION &&\n\t\t\trel->rd_rel->relkind != RELKIND_MATVIEW &&\n\t\t\trel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&\n\t\t\trel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_WRONG_OBJECT_TYPE),\n\t\t\t\t\t errmsg(\"relation \\\"%s\\\" is not a table, foreign table, or materialized view\",\n\t\t\t\t\t\t\tRelationGetRelationName(rel))));\n\n\t\t/* You must own the relation to create stats on it */\n\t\tif (!pg_class_ownercheck(RelationGetRelid(rel), stxowner))\n\t\t\taclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(rel->rd_rel->relkind),\n\t\t\t\t\t\t RelationGetRelationName(rel));\n\n\t\t/* Creating statistics on system catalogs is not allowed */\n\t\tif (!allowSystemTableMods && IsSystemRelation(rel))\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),\n\t\t\t\t\t errmsg(\"permission denied: \\\"%s\\\" is a system catalog\",\n\t\t\t\t\t\t\tRelationGetRelationName(rel))));\n\t}\n\n\tAssert(rel);\n\trelid = RelationGetRelid(rel);\n\n\t/*\n\t * If the node has a name, split it up and determine creation namespace.\n\t * If not (a possibility not considered by the grammar, but one which can\n\t * occur via the \"CREATE TABLE ... (LIKE)\" command), then we put the\n\t * object in the same namespace as the relation, and cons up a name for\n\t * it.\n\t */\n\tif (stmt->defnames)\n\t\tnamespaceId = QualifiedNameGetCreationNamespace(stmt->defnames,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t&namestr);\n\telse\n\t{\n\t\tnamespaceId = RelationGetNamespace(rel);\n\t\tnamestr = ChooseExtendedStatisticName(RelationGetRelationName(rel),\n\t\t\t\t\t\t\t\t\t\t\t ChooseExtendedStatisticNameAddition(stmt->exprs),\n\t\t\t\t\t\t\t\t\t\t\t \"stat\",\n\t\t\t\t\t\t\t\t\t\t\t namespaceId);\n\t}\n\tnamestrcpy(&stxname, namestr);\n\n\t/*\n\t * Deal with the possibility that the statistics object already exists.\n\t */\n\tif (SearchSysCacheExists2(STATEXTNAMENSP,\n\t\t\t\t\t\t\t CStringGetDatum(namestr),\n\t\t\t\t\t\t\t ObjectIdGetDatum(namespaceId)))\n\t{\n\t\tif (stmt->if_not_exists)\n\t\t{\n\t\t\tereport(NOTICE,\n\t\t\t\t\t(errcode(ERRCODE_DUPLICATE_OBJECT),\n\t\t\t\t\t errmsg(\"statistics object \\\"%s\\\" already exists, skipping\",\n\t\t\t\t\t\t\tnamestr)));\n\t\t\trelation_close(rel, NoLock);\n\t\t\treturn InvalidObjectAddress;\n\t\t}\n\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_DUPLICATE_OBJECT),\n\t\t\t\t errmsg(\"statistics object \\\"%s\\\" already exists\", namestr)));\n\t}\n\n\t/*\n\t * Currently, we only allow simple column references in the expression\n\t * list. That will change someday, and again the grammar already supports\n\t * it so we have to enforce restrictions here. For now, we can convert\n\t * the expression list to a simple array of attnums. While at it, enforce\n\t * some constraints.\n\t */\n\tforeach(cell, stmt->exprs)\n\t{\n\t\tNode\t *expr = (Node *) lfirst(cell);\n\t\tColumnRef *cref;\n\t\tchar\t *attname;\n\t\tHeapTuple\tatttuple;\n\t\tForm_pg_attribute attForm;\n\t\tTypeCacheEntry *type;\n\n\t\tif (!IsA(expr, ColumnRef))\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t errmsg(\"only simple column references are allowed in CREATE STATISTICS\")));\n\t\tcref = (ColumnRef *) expr;\n\n\t\tif (list_length(cref->fields) != 1)\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t errmsg(\"only simple column references are allowed in CREATE STATISTICS\")));\n\t\tattname = strVal((Value *) linitial(cref->fields));\n\n\t\tatttuple = SearchSysCacheAttName(relid, attname);\n\t\tif (!HeapTupleIsValid(atttuple))\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_UNDEFINED_COLUMN),\n\t\t\t\t\t errmsg(\"column \\\"%s\\\" does not exist\",\n\t\t\t\t\t\t\tattname)));\n\t\tattForm = (Form_pg_attribute) GETSTRUCT(atttuple);\n\n\t\t/* Disallow use of system attributes in extended stats */\n\t\tif (attForm->attnum <= 0)\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t errmsg(\"statistics creation on system columns is not supported\")));\n\n\t\t/* Disallow data types without a less-than operator */\n\t\ttype = lookup_type_cache(attForm->atttypid, TYPECACHE_LT_OPR);\n\t\tif (type->lt_opr == InvalidOid)\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t\t errmsg(\"column \\\"%s\\\" cannot be used in statistics because its type %s has no default btree operator class\",\n\t\t\t\t\t\t\tattname, format_type_be(attForm->atttypid))));\n\n\t\t/* Make sure no more than STATS_MAX_DIMENSIONS columns are used */\n\t\tif (numcols >= STATS_MAX_DIMENSIONS)\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_TOO_MANY_COLUMNS),\n\t\t\t\t\t errmsg(\"cannot have more than %d columns in statistics\",\n\t\t\t\t\t\t\tSTATS_MAX_DIMENSIONS)));\n\n\t\tattnums[numcols] = attForm->attnum;\n\t\tnumcols++;\n\t\tReleaseSysCache(atttuple);\n\t}\n\n\t/*\n\t * Check that at least two columns were specified in the statement. The\n\t * upper bound was already checked in the loop above.\n\t */\n\tif (numcols < 2)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),\n\t\t\t\t errmsg(\"extended statistics require at least 2 columns\")));\n\n\t/*\n\t * Sort the attnums, which makes detecting duplicates somewhat easier, and\n\t * it does not hurt (it does not affect the efficiency, unlike for\n\t * indexes, for example).\n\t */\n\tqsort(attnums, numcols, sizeof(int16), compare_int16);\n\n\t/*\n\t * Check for duplicates in the list of columns. The attnums are sorted so\n\t * just check consecutive elements.\n\t */\n\tfor (i = 1; i < numcols; i++)\n\t{\n\t\tif (attnums[i] == attnums[i - 1])\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_DUPLICATE_COLUMN),\n\t\t\t\t\t errmsg(\"duplicate column name in statistics definition\")));\n\t}\n\n\t/* Form an int2vector representation of the sorted column list */\n\tstxkeys = buildint2vector(attnums, numcols);\n\n\t/*\n\t * Parse the statistics kinds.\n\t */\n\tbuild_ndistinct = false;\n\tbuild_dependencies = false;\n\tbuild_mcv = false;\n\tforeach(cell, stmt->stat_types)\n\t{\n\t\tchar\t *type = strVal((Value *) lfirst(cell));\n\n\t\tif (strcmp(type, \"ndistinct\") == 0)\n\t\t{\n\t\t\tbuild_ndistinct = true;\n\t\t\trequested_type = true;\n\t\t}\n\t\telse if (strcmp(type, \"dependencies\") == 0)\n\t\t{\n\t\t\tbuild_dependencies = true;\n\t\t\trequested_type = true;\n\t\t}\n\t\telse if (strcmp(type, \"mcv\") == 0)\n\t\t{\n\t\t\tbuild_mcv = true;\n\t\t\trequested_type = true;\n\t\t}\n\t\telse\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_SYNTAX_ERROR),\n\t\t\t\t\t errmsg(\"unrecognized statistics kind \\\"%s\\\"\",\n\t\t\t\t\t\t\ttype)));\n\t}\n\t/* If no statistic type was specified, build them all. */\n\tif (!requested_type)\n\t{\n\t\tbuild_ndistinct = true;\n\t\tbuild_dependencies = true;\n\t\tbuild_mcv = true;\n\t}\n\n\t/* construct the char array of enabled statistic types */\n\tntypes = 0;\n\tif (build_ndistinct)\n\t\ttypes[ntypes++] = CharGetDatum(STATS_EXT_NDISTINCT);\n\tif (build_dependencies)\n\t\ttypes[ntypes++] = CharGetDatum(STATS_EXT_DEPENDENCIES);\n\tif (build_mcv)\n\t\ttypes[ntypes++] = CharGetDatum(STATS_EXT_MCV);\n\tAssert(ntypes > 0 && ntypes <= lengthof(types));\n\tstxkind = construct_array(types, ntypes, CHAROID, 1, true, 'c');\n\n\tstatrel = table_open(StatisticExtRelationId, RowExclusiveLock);\n\n\t/*\n\t * Everything seems fine, so let's build the pg_statistic_ext tuple.\n\t */\n\tmemset(values, 0, sizeof(values));\n\tmemset(nulls, false, sizeof(nulls));\n\n\tstatoid = GetNewOidWithIndex(statrel, StatisticExtOidIndexId,\n\t\t\t\t\t\t\t\t Anum_pg_statistic_ext_oid);\n\tvalues[Anum_pg_statistic_ext_oid - 1] = ObjectIdGetDatum(statoid);\n\tvalues[Anum_pg_statistic_ext_stxrelid - 1] = ObjectIdGetDatum(relid);\n\tvalues[Anum_pg_statistic_ext_stxname - 1] = NameGetDatum(&stxname);\n\tvalues[Anum_pg_statistic_ext_stxnamespace - 1] = ObjectIdGetDatum(namespaceId);\n\tvalues[Anum_pg_statistic_ext_stxowner - 1] = ObjectIdGetDatum(stxowner);\n\tvalues[Anum_pg_statistic_ext_stxkeys - 1] = PointerGetDatum(stxkeys);\n\tvalues[Anum_pg_statistic_ext_stxkind - 1] = PointerGetDatum(stxkind);\n\n\t/* insert it into pg_statistic_ext */\n\thtup = heap_form_tuple(statrel->rd_att, values, nulls);\n\tCatalogTupleInsert(statrel, htup);\n\theap_freetuple(htup);\n\n\trelation_close(statrel, RowExclusiveLock);\n\n\t/*\n\t * Also build the pg_statistic_ext_data tuple, to hold the actual\n\t * statistics data.\n\t */\n\tdatarel = table_open(StatisticExtDataRelationId, RowExclusiveLock);\n\n\tmemset(datavalues, 0, sizeof(datavalues));\n\tmemset(datanulls, false, sizeof(datanulls));\n\n\tdatavalues[Anum_pg_statistic_ext_data_stxoid - 1] = ObjectIdGetDatum(statoid);\n\n\t/* no statistics built yet */\n\tdatanulls[Anum_pg_statistic_ext_data_stxdndistinct - 1] = true;\n\tdatanulls[Anum_pg_statistic_ext_data_stxddependencies - 1] = true;\n\tdatanulls[Anum_pg_statistic_ext_data_stxdmcv - 1] = true;\n\n\t/* insert it into pg_statistic_ext_data */\n\thtup = heap_form_tuple(datarel->rd_att, datavalues, datanulls);\n\tCatalogTupleInsert(datarel, htup);\n\theap_freetuple(htup);\n\n\trelation_close(datarel, RowExclusiveLock);\n\n\t/*\n\t * Invalidate relcache so that others see the new statistics object.\n\t */\n\tCacheInvalidateRelcache(rel);\n\n\trelation_close(rel, NoLock);\n\n\t/*\n\t * Add an AUTO dependency on each column used in the stats, so that the\n\t * stats object goes away if any or all of them get dropped.\n\t */\n\tObjectAddressSet(myself, StatisticExtRelationId, statoid);\n\n\tfor (i = 0; i < numcols; i++)\n\t{\n\t\tObjectAddressSubSet(parentobject, RelationRelationId, relid, attnums[i]);\n\t\trecordDependencyOn(&myself, &parentobject, DEPENDENCY_AUTO);\n\t}\n\n\t/*\n\t * Also add dependencies on namespace and owner. These are required\n\t * because the stats object might have a different namespace and/or owner\n\t * than the underlying table(s).\n\t */\n\tObjectAddressSet(parentobject, NamespaceRelationId, namespaceId);\n\trecordDependencyOn(&myself, &parentobject, DEPENDENCY_NORMAL);\n\n\trecordDependencyOnOwner(StatisticExtRelationId, statoid, stxowner);\n\n\t/*\n\t * XXX probably there should be a recordDependencyOnCurrentExtension call\n\t * here too, but we'd have to add support for ALTER EXTENSION ADD/DROP\n\t * STATISTICS, which is more work than it seems worth.\n\t */\n\n\t/* Add any requested comment */\n\tif (stmt->stxcomment != NULL)\n\t\tCreateComments(statoid, StatisticExtRelationId, 0,\n\t\t\t\t\t stmt->stxcomment);\n\n\t/* Return stats object's address */\n\treturn myself;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-94'], 'message': 'In extensions, don't replace objects not belonging to the extension.\n\nPreviously, if an extension script did CREATE OR REPLACE and there was\nan existing object not belonging to the extension, it would overwrite\nthe object and adopt it into the extension. This is problematic, first\nbecause the overwrite is probably unintentional, and second because we\ndidn't change the object's ownership. Thus a hostile user could create\nan object in advance of an expected CREATE EXTENSION command, and would\nthen have ownership rights on an extension object, which could be\nmodified for trojan-horse-type attacks.\n\nHence, forbid CREATE OR REPLACE of an existing object unless it already\nbelongs to the extension. (Note that we've always forbidden replacing\nan object that belongs to some other extension; only the behavior for\npreviously-free-standing objects changes here.)\n\nFor the same reason, also fail CREATE IF NOT EXISTS when there is\nan existing object that doesn't belong to the extension.\n\nOur thanks to Sven Klemm for reporting this problem.\n\nSecurity: CVE-2022-2625'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool SNC_io_parser::\nread_edge(Halfedge_handle eh) {\n\n bool OK = true;\n int index;\n#ifdef CGAL_NEF_NATURAL_COORDINATE_INPUT\n typename K::RT hx,hy,hz,hw;\n#endif\n in >> index;\n OK = OK && test_string(\"{\");\n\n in >> index;\n eh->twin() = Edge_of[index];\n OK = OK && test_string(\",\");\n in >> index;\n eh->center_vertex() = Vertex_of[index];\n OK = OK && test_string(\",\");\n in >> index;\n if(index == 0) {\n in >> index;\n eh->out_sedge() = SEdge_of[index];\n } else {\n in >> index;\n eh->incident_sface() = SFace_of[index];\n }\n OK = OK && test_string(\"|\");\n#ifdef CGAL_NEF_NATURAL_COORDINATE_INPUT\n in >> hx >> hy >> hz >> hw;\n eh->point() = Sphere_point(hx,hy,hz);\n#else\n eh->point() =\n Geometry_io::template read_point(in);\n#endif\n OK = OK && test_string(\"}\");\n in >> eh->mark();\n\n return OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix Nef_3'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int htc_connect_service(struct htc_target *target,\n\t\t struct htc_service_connreq *service_connreq,\n\t\t enum htc_endpoint_id *conn_rsp_epid)\n{\n\tstruct sk_buff *skb;\n\tstruct htc_endpoint *endpoint;\n\tstruct htc_conn_svc_msg *conn_msg;\n\tint ret;\n\tunsigned long time_left;\n\n\t/* Find an available endpoint */\n\tendpoint = get_next_avail_ep(target->endpoint);\n\tif (!endpoint) {\n\t\tdev_err(target->dev, \"Endpoint is not available for service %d\\n\",\n\t\t\tservice_connreq->service_id);\n\t\treturn -EINVAL;\n\t}\n\n\tendpoint->service_id = service_connreq->service_id;\n\tendpoint->max_txqdepth = service_connreq->max_send_qdepth;\n\tendpoint->ul_pipeid = service_to_ulpipe(service_connreq->service_id);\n\tendpoint->dl_pipeid = service_to_dlpipe(service_connreq->service_id);\n\tendpoint->ep_callbacks = service_connreq->ep_callbacks;\n\n\tskb = alloc_skb(sizeof(struct htc_conn_svc_msg) +\n\t\t\t sizeof(struct htc_frame_hdr), GFP_ATOMIC);\n\tif (!skb) {\n\t\tdev_err(target->dev, \"Failed to allocate buf to send\"\n\t\t\t\"service connect req\\n\");\n\t\treturn -ENOMEM;\n\t}\n\n\tskb_reserve(skb, sizeof(struct htc_frame_hdr));\n\n\tconn_msg = skb_put(skb, sizeof(struct htc_conn_svc_msg));\n\tconn_msg->service_id = cpu_to_be16(service_connreq->service_id);\n\tconn_msg->msg_id = cpu_to_be16(HTC_MSG_CONNECT_SERVICE_ID);\n\tconn_msg->con_flags = cpu_to_be16(service_connreq->con_flags);\n\tconn_msg->dl_pipeid = endpoint->dl_pipeid;\n\tconn_msg->ul_pipeid = endpoint->ul_pipeid;\n\n\tret = htc_issue_send(target, skb, skb->len, 0, ENDPOINT0);\n\tif (ret)\n\t\tgoto err;\n\n\ttime_left = wait_for_completion_timeout(&target->cmd_wait, HZ);\n\tif (!time_left) {\n\t\tdev_err(target->dev, \"Service connection timeout for: %d\\n\",\n\t\t\tservice_connreq->service_id);\n\t\tkfree_skb(skb);\n\t\treturn -ETIMEDOUT;\n\t}\n\n\t*conn_rsp_epid = target->conn_rsp_epid;\n\treturn 0;\nerr:\n\tkfree_skb(skb);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'ath9k: Fix use-after-free Read in htc_connect_service\n\nThe skb is consumed by htc_send_epid, so it needn't release again.\n\nThe case reported by syzbot:\n\nhttps://lore.kernel.org/linux-usb/000000000000590f6b05a1c05d15@google.com\nusb 1-1: ath9k_htc: Firmware ath9k_htc/htc_9271-1.4.0.fw requested\nusb 1-1: ath9k_htc: Transferred FW: ath9k_htc/htc_9271-1.4.0.fw, size:\n51008\nusb 1-1: Service connection timeout for: 256\n==================================================================\nBUG: KASAN: use-after-free in atomic_read\ninclude/asm-generic/atomic-instrumented.h:26 [inline]\nBUG: KASAN: use-after-free in refcount_read include/linux/refcount.h:134\n[inline]\nBUG: KASAN: use-after-free in skb_unref include/linux/skbuff.h:1042\n[inline]\nBUG: KASAN: use-after-free in kfree_skb+0x32/0x3d0 net/core/skbuff.c:692\nRead of size 4 at addr ffff8881d0957994 by task kworker/1:2/83\n\nCall Trace:\nkfree_skb+0x32/0x3d0 net/core/skbuff.c:692\nhtc_connect_service.cold+0xa9/0x109\ndrivers/net/wireless/ath/ath9k/htc_hst.c:282\nath9k_wmi_connect+0xd2/0x1a0 drivers/net/wireless/ath/ath9k/wmi.c:265\nath9k_init_htc_services.constprop.0+0xb4/0x650\ndrivers/net/wireless/ath/ath9k/htc_drv_init.c:146\nath9k_htc_probe_device+0x25a/0x1d80\ndrivers/net/wireless/ath/ath9k/htc_drv_init.c:959\nath9k_htc_hw_init+0x31/0x60\ndrivers/net/wireless/ath/ath9k/htc_hst.c:501\nath9k_hif_usb_firmware_cb+0x26b/0x500\ndrivers/net/wireless/ath/ath9k/hif_usb.c:1187\nrequest_firmware_work_func+0x126/0x242\ndrivers/base/firmware_loader/main.c:976\nprocess_one_work+0x94b/0x1620 kernel/workqueue.c:2264\nworker_thread+0x96/0xe20 kernel/workqueue.c:2410\nkthread+0x318/0x420 kernel/kthread.c:255\nret_from_fork+0x24/0x30 arch/x86/entry/entry_64.S:352\n\nAllocated by task 83:\nkmem_cache_alloc_node+0xdc/0x330 mm/slub.c:2814\n__alloc_skb+0xba/0x5a0 net/core/skbuff.c:198\nalloc_skb include/linux/skbuff.h:1081 [inline]\nhtc_connect_service+0x2cc/0x840\ndrivers/net/wireless/ath/ath9k/htc_hst.c:257\nath9k_wmi_connect+0xd2/0x1a0 drivers/net/wireless/ath/ath9k/wmi.c:265\nath9k_init_htc_services.constprop.0+0xb4/0x650\ndrivers/net/wireless/ath/ath9k/htc_drv_init.c:146\nath9k_htc_probe_device+0x25a/0x1d80\ndrivers/net/wireless/ath/ath9k/htc_drv_init.c:959\nath9k_htc_hw_init+0x31/0x60\ndrivers/net/wireless/ath/ath9k/htc_hst.c:501\nath9k_hif_usb_firmware_cb+0x26b/0x500\ndrivers/net/wireless/ath/ath9k/hif_usb.c:1187\nrequest_firmware_work_func+0x126/0x242\ndrivers/base/firmware_loader/main.c:976\nprocess_one_work+0x94b/0x1620 kernel/workqueue.c:2264\nworker_thread+0x96/0xe20 kernel/workqueue.c:2410\nkthread+0x318/0x420 kernel/kthread.c:255\nret_from_fork+0x24/0x30 arch/x86/entry/entry_64.S:352\n\nFreed by task 0:\nkfree_skb+0x102/0x3d0 net/core/skbuff.c:690\nath9k_htc_txcompletion_cb+0x1f8/0x2b0\ndrivers/net/wireless/ath/ath9k/htc_hst.c:356\nhif_usb_regout_cb+0x10b/0x1b0\ndrivers/net/wireless/ath/ath9k/hif_usb.c:90\n__usb_hcd_giveback_urb+0x29a/0x550 drivers/usb/core/hcd.c:1650\nusb_hcd_giveback_urb+0x368/0x420 drivers/usb/core/hcd.c:1716\ndummy_timer+0x1258/0x32ae drivers/usb/gadget/udc/dummy_hcd.c:1966\ncall_timer_fn+0x195/0x6f0 kernel/time/timer.c:1404\nexpire_timers kernel/time/timer.c:1449 [inline]\n__run_timers kernel/time/timer.c:1773 [inline]\n__run_timers kernel/time/timer.c:1740 [inline]\nrun_timer_softirq+0x5f9/0x1500 kernel/time/timer.c:1786\n__do_softirq+0x21e/0x950 kernel/softirq.c:292\n\nReported-and-tested-by: syzbot+9505af1ae303dabdc646@syzkaller.appspotmail.com\nSigned-off-by: Qiujun Huang \nSigned-off-by: Kalle Valo \nLink: https://lore.kernel.org/r/20200404041838.10426-2-hqjagain@gmail.com'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool StringMatching::matchString(const char* str1, const char* str2)\n{\n\tstd::string path(str1);\n\tstd::string spec(str2);\n\n\tstd::string base_path(path);\n\tstd::string base_spec(spec);\n\n\treplace_all(base_spec, \"*\", \".*\");\n\treplace_all(base_spec, \"?\", \".\");\n\n\tstd::regex base_spec_regex(base_spec);\n\tstd::smatch base_spec_match;\n\tif (std::regex_match(path, base_spec_match, base_spec_regex))\n\t{\n\t\treturn true;\n\t}\n\n\treplace_all(base_path, \"*\", \".*\");\n\treplace_all(base_path, \"?\", \".\");\n\n\tstd::regex base_path_regex(base_path);\n\tstd::smatch base_path_match;\n\n\tif (std::regex_match(spec, base_path_match, base_path_regex))\n\t{\n\t\treturn true;\n\t}\n\n\treturn false;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284'], 'message': 'check remote permissions (#1387)\n\n* Refs 5346. Blackbox test\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs 5346. one-way string compare\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs 5346. Do not add partition separator on last partition\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs 5346. Uncrustify\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs 5346. Uncrustify\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs 3680. Access control unit testing\r\n\r\nIt only covers Partition and Topic permissions\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs #3680. Fix partition check on Permissions plugin.\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs 3680. Uncrustify\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs 3680. Fix tests on mac\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs 3680. Fix windows tests\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs 3680. Avoid memory leak on test\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* Refs 3680. Proxy data mocks should not return temporary objects\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\n* refs 3680. uncrustify\r\n\r\nSigned-off-by: Iker Luengo \r\n\r\nCo-authored-by: Miguel Company '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int r_core_cmd_subst_i(RCore *core, char *cmd, char *colon) {\n\tconst char *quotestr = \"`\";\n\tconst char *tick = NULL;\n\tchar *ptr, *ptr2, *str;\n\tchar *arroba = NULL;\n\tint i, ret = 0, pipefd;\n\tbool usemyblock = false;\n\tint scr_html = -1;\n\tint scr_color = -1;\n\tbool eos = false;\n\tbool haveQuote = false;\n\n\tif (!cmd) {\n\t\treturn 0;\n\t}\n\tcmd = r_str_trim_head_tail (cmd);\n\n\t/* quoted / raw command */\n\tswitch (*cmd) {\n\tcase '.':\n\t\tif (cmd[1] == '\"') { /* interpret */\n\t\t\treturn r_cmd_call (core->rcmd, cmd);\n\t\t}\n\t\tbreak;\n\tcase '\"':\n\t\tfor (; *cmd; ) {\n\t\t\tint pipefd = -1;\n\t\t\tut64 oseek = UT64_MAX;\n\t\t\tchar *line, *p;\n\t\t\thaveQuote = *cmd == '\"';\n\t\t\tif (haveQuote) {\n\t\t\t//\t*cmd = 0;\n\t\t\t\tcmd++;\n\t\t\t\tp = find_eoq (cmd + 1);\n\t\t\t\tif (!p || !*p) {\n\t\t\t\t\teprintf (\"Missing \\\" in (%s).\", cmd);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\t*p++ = 0;\n\t\t\t\tif (!*p) {\n\t\t\t\t\teos = true;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tchar *sc = strchr (cmd, ';');\n\t\t\t\tif (sc) {\n\t\t\t\t\t*sc = 0;\n\t\t\t\t}\n\t\t\t\tr_core_cmd0 (core, cmd);\n\t\t\t\tif (!sc) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcmd = sc + 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (p[0]) {\n\t\t\t\t// workaround :D\n\t\t\t\tif (p[0] == '@') {\n\t\t\t\t\tp--;\n\t\t\t\t}\n\t\t\t\twhile (p[1] == ';' || IS_WHITESPACE (p[1])) {\n\t\t\t\t\tp++;\n\t\t\t\t}\n\t\t\t\tif (p[1] == '@' || (p[1] && p[2] == '@')) {\n\t\t\t\t\tchar *q = strchr (p + 1, '\"');\n\t\t\t\t\tif (q) {\n\t\t\t\t\t\t*q = 0;\n\t\t\t\t\t}\n\t\t\t\t\thaveQuote = q != NULL;\n\t\t\t\t\toseek = core->offset;\n\t\t\t\t\tr_core_seek (core,\n\t\t\t\t\t\t r_num_math (core->num, p + 2), 1);\n\t\t\t\t\tif (q) {\n\t\t\t\t\t\t*p = '\"';\n\t\t\t\t\t\tp = q;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tp = strchr (p + 1, ';');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (p && *p && p[1] == '>') {\n\t\t\t\t\tstr = p + 2;\n\t\t\t\t\twhile (*str == '>') {\n\t\t\t\t\t\tstr++;\n\t\t\t\t\t}\n\t\t\t\t\twhile (IS_WHITESPACE (*str)) {\n\t\t\t\t\t\tstr++;\n\t\t\t\t\t}\n\t\t\t\t\tr_cons_flush ();\n\t\t\t\t\tpipefd = r_cons_pipe_open (str, 1, p[2] == '>');\n\t\t\t\t}\n\t\t\t}\n\t\t\tline = strdup (cmd);\n\t\t\tline = r_str_replace (line, \"\\\\\\\"\", \"\\\"\", true);\n\t\t\tif (p && *p && p[1] == '|') {\n\t\t\t\tstr = p + 2;\n\t\t\t\twhile (IS_WHITESPACE (*str)) {\n\t\t\t\t\tstr++;\n\t\t\t\t}\n\t\t\t\tr_core_cmd_pipe (core, cmd, str);\n\t\t\t} else {\n\t\t\t\tr_cmd_call (core->rcmd, line);\n\t\t\t}\n\t\t\tfree (line);\n\t\t\tif (oseek != UT64_MAX) {\n\t\t\t\tr_core_seek (core, oseek, 1);\n\t\t\t\toseek = UT64_MAX;\n\t\t\t}\n\t\t\tif (pipefd != -1) {\n\t\t\t\tr_cons_flush ();\n\t\t\t\tr_cons_pipe_close (pipefd);\n\t\t\t}\n\t\t\tif (!p) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (eos) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (haveQuote) {\n\t\t\t\tif (*p == ';') {\n\t\t\t\t\tcmd = p + 1;\n\t\t\t\t} else {\n\t\t\t\t\tif (*p == '\"') {\n\t\t\t\t\t\tcmd = p + 1;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t*p = '\"';\n\t\t\t\t\t\tcmd = p;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcmd = p + 1;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\tcase '(':\n\t\tif (cmd[1] != '*') {\n\t\t\treturn r_cmd_call (core->rcmd, cmd);\n\t\t}\n\t}\n\n// TODO must honor \" and `\n\t/* comments */\n\tif (*cmd != '#') {\n\t\tptr = (char *)r_str_lastbut (cmd, '#', quotestr);\n\t\tif (ptr && (ptr[1] == ' ' || ptr[1] == '\\t')) {\n\t\t\t*ptr = '\\0';\n\t\t}\n\t}\n\n\t/* multiple commands */\n\t// TODO: must honor \" and ` boundaries\n\t//ptr = strrchr (cmd, ';');\n\tif (*cmd != '#') {\n\t\tptr = (char *)r_str_lastbut (cmd, ';', quotestr);\n\t\tif (colon && ptr) {\n\t\t\tint ret ;\n\t\t\t*ptr = '\\0';\n\t\t\tif (r_core_cmd_subst (core, cmd) == -1) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tcmd = ptr + 1;\n\t\t\tret = r_core_cmd_subst (core, cmd);\n\t\t\t*ptr = ';';\n\t\t\treturn ret;\n\t\t\t//r_cons_flush ();\n\t\t}\n\t}\n\n\t// TODO must honor \" and `\n\t/* pipe console to shell process */\n\t//ptr = strchr (cmd, '|');\n\tptr = (char *)r_str_lastbut (cmd, '|', quotestr);\n\tif (ptr) {\n\t\tchar *ptr2 = strchr (cmd, '`');\n\t\tif (!ptr2 || (ptr2 && ptr2 > ptr)) {\n\t\t\tif (!tick || (tick && tick > ptr)) {\n\t\t\t\t*ptr = '\\0';\n\t\t\t\tcmd = r_str_clean (cmd);\n\t\t\t\tif (!strcmp (ptr + 1, \"?\")) { // \"|?\"\n\t\t\t\t\t// TODO: should be disable scr.color in pd| ?\n\t\t\t\t\teprintf (\"Usage: | \\n\");\n\t\t\t\t\teprintf (\" pd|? - show this help\\n\");\n\t\t\t\t\teprintf (\" pd| - disable scr.html and scr.color\\n\");\n\t\t\t\t\teprintf (\" pd|H - enable scr.html, respect scr.color\\n\");\n\t\t\t\t\treturn ret;\n\t\t\t\t} else if (!strcmp (ptr + 1, \"H\")) { // \"|H\"\n\t\t\t\t\tscr_html = r_config_get_i (core->config, \"scr.html\");\n\t\t\t\t\tr_config_set_i (core->config, \"scr.html\", true);\n\t\t\t\t} else if (ptr[1]) { // \"| grep ..\"\n\t\t\t\t\tint value = core->num->value;\n\t\t\t\t\tif (*cmd) {\n\t\t\t\t\t\tr_core_cmd_pipe (core, cmd, ptr + 1);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tr_io_system (core->io, ptr + 1);\n\t\t\t\t\t}\n\t\t\t\t\tcore->num->value = value;\n\t\t\t\t\treturn 0;\n\t\t\t\t} else { // \"|\"\n\t\t\t\t\tscr_html = r_config_get_i (core->config, \"scr.html\");\n\t\t\t\t\tr_config_set_i (core->config, \"scr.html\", 0);\n\t\t\t\t\tscr_color = r_config_get_i (core->config, \"scr.color\");\n\t\t\t\t\tr_config_set_i (core->config, \"scr.color\", false);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// TODO must honor \" and `\n\t/* bool conditions */\n\tptr = (char *)r_str_lastbut (cmd, '&', quotestr);\n\t//ptr = strchr (cmd, '&');\n\twhile (ptr && ptr[1] == '&') {\n\t\t*ptr = '\\0';\n\t\tret = r_cmd_call (core->rcmd, cmd);\n\t\tif (ret == -1) {\n\t\t\teprintf (\"command error(%s)\\n\", cmd);\n\t\t\tif (scr_html != -1) {\n\t\t\t\tr_config_set_i (core->config, \"scr.html\", scr_html);\n\t\t\t}\n\t\t\tif (scr_color != -1) {\n\t\t\t\tr_config_set_i (core->config, \"scr.color\", scr_color);\n\t\t\t}\n\t\t\treturn ret;\n\t\t}\n\t\tfor (cmd = ptr + 2; cmd && *cmd == ' '; cmd++);\n\t\tptr = strchr (cmd, '&');\n\t}\n\n\t/* Out Of Band Input */\n\tfree (core->oobi);\n\tcore->oobi = NULL;\n\n\tptr = strstr (cmd, \"?*\");\n\tif (ptr) {\n\t\tchar *prech = ptr - 1;\n\t\tif (*prech != '~') {\n\t\t\tptr[1] = 0;\n\t\t\tif (*cmd != '#' && strlen (cmd) < 5) {\n\t\t\t\tr_cons_break_push (NULL, NULL);\n\t\t\t\trecursive_help (core, cmd);\n\t\t\t\tr_cons_break_pop ();\n\t\t\t\tr_cons_grep_parsecmd (ptr + 2, \"`\");\n\t\t\t\tif (scr_html != -1) {\n\t\t\t\t\tr_config_set_i (core->config, \"scr.html\", scr_html);\n\t\t\t\t}\n\t\t\tif (scr_color != -1) {\n\t\t\t\tr_config_set_i (core->config, \"scr.color\", scr_color);\n\t\t\t}\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t}\n\n#if 0\n\tptr = strchr (cmd, '<');\n\tif (ptr) {\n\t\tptr[0] = '\\0';\n\t\tif (r_cons_singleton()->is_interactive) {\n\t\t\tif (ptr[1] == '<') {\n\t\t\t\t/* this is a bit mess */\n\t\t\t\t//const char *oprompt = strdup (r_line_singleton ()->prompt);\n\t\t\t\t//oprompt = \">\";\n\t\t\t\tfor (str = ptr + 2; str[0] == ' '; str++) {\n\t\t\t\t\t//nothing to see here\n\t\t\t\t}\n\t\t\t\teprintf (\"==> Reading from stdin until '%s'\\n\", str);\n\t\t\t\tfree (core->oobi);\n\t\t\t\tcore->oobi = malloc (1);\n\t\t\t\tif (core->oobi) {\n\t\t\t\t\tcore->oobi[0] = '\\0';\n\t\t\t\t}\n\t\t\t\tcore->oobi_len = 0;\n\t\t\t\tfor (;;) {\n\t\t\t\t\tchar buf[1024];\n\t\t\t\t\tint ret;\n\t\t\t\t\twrite (1, \"> \", 2);\n\t\t\t\t\tfgets (buf, sizeof (buf) - 1, stdin); // XXX use r_line ??\n\t\t\t\t\tif (feof (stdin)) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tif (*buf) buf[strlen (buf) - 1]='\\0';\n\t\t\t\t\tret = strlen (buf);\n\t\t\t\t\tcore->oobi_len += ret;\n\t\t\t\t\tcore->oobi = realloc (core->oobi, core->oobi_len + 1);\n\t\t\t\t\tif (core->oobi) {\n\t\t\t\t\t\tif (!strcmp (buf, str)) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tstrcat ((char *)core->oobi, buf);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//r_line_set_prompt (oprompt);\n\t\t\t} else {\n\t\t\t\tfor (str = ptr + 1; *str == ' '; str++) {\n\t\t\t\t\t//nothing to see here\n\t\t\t\t}\n\t\t\t\tif (!*str) {\n\t\t\t\t\tgoto next;\n\t\t\t\t}\n\t\t\t\teprintf (\"Slurping file '%s'\\n\", str);\n\t\t\t\tfree (core->oobi);\n\t\t\t\tcore->oobi = (ut8*)r_file_slurp (str, &core->oobi_len);\n\t\t\t\tif (!core->oobi) {\n\t\t\t\t\teprintf (\"cannot open file\\n\");\n\t\t\t\t} else if (ptr == cmd) {\n\t\t\t\t\treturn r_core_cmd_buffer (core, (const char *)core->oobi);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\teprintf (\"Cannot slurp with << in non-interactive mode\\n\");\n\t\t\treturn 0;\n\t\t}\n\t}\nnext:\n#endif\n\t// TODO must honor \" and `\n\t/* pipe console to file */\n\tptr = strchr (cmd, '>');\n\tif (ptr) {\n\t\tint fdn = 1;\n\t\tint pipecolor = r_config_get_i (core->config, \"scr.pipecolor\");\n\t\tint use_editor = false;\n\t\tint ocolor = r_config_get_i (core->config, \"scr.color\");\n\t\t*ptr = '\\0';\n\t\tstr = r_str_trim_head_tail (ptr + 1 + (ptr[1] == '>'));\n\t\tif (!*str) {\n\t\t\teprintf (\"No output?\\n\");\n\t\t\tgoto next2;\n\t\t}\n\t\t/* r_cons_flush() handles interactive output (to the terminal)\n\t\t * differently (e.g. asking about too long output). This conflicts\n\t\t * with piping to a file. Disable it while piping. */\n\t\tif (ptr > (cmd + 1) && ISWHITECHAR (ptr[-2])) {\n\t\t\tchar *fdnum = ptr - 1;\n\t\t\tif (*fdnum == 'H') { // \"H>\"\n\t\t\t\tscr_html = r_config_get_i (core->config, \"scr.html\");\n\t\t\t\tr_config_set_i (core->config, \"scr.html\", true);\n\t\t\t\tpipecolor = true;\n\t\t\t\t*fdnum = 0;\n\t\t\t} else {\n\t\t\t\tif (IS_DIGIT(*fdnum)) {\n\t\t\t\t\tfdn = *fdnum - '0';\n\t\t\t\t}\n\t\t\t\t*fdnum = 0;\n\t\t\t}\n\t\t}\n\t\tr_cons_set_interactive (false);\n\t\tif (!strcmp (str, \"-\")) {\n\t\t\tuse_editor = true;\n\t\t\tstr = r_file_temp (\"dumpedit\");\n\t\t\tr_config_set (core->config, \"scr.color\", \"false\");\n\t\t}\n\t\tif (fdn > 0) {\n\t\t\tpipefd = r_cons_pipe_open (str, fdn, ptr[1] == '>');\n\t\t\tif (pipefd != -1) {\n\t\t\t\tif (!pipecolor) {\n\t\t\t\t\tr_config_set_i (core->config, \"scr.color\", 0);\n\t\t\t\t}\n\t\t\t\tret = r_core_cmd_subst (core, cmd);\n\t\t\t\tr_cons_flush ();\n\t\t\t\tr_cons_pipe_close (pipefd);\n\t\t\t}\n\t\t}\n\t\tr_cons_set_last_interactive ();\n\t\tif (!pipecolor) {\n\t\t\tr_config_set_i (core->config, \"scr.color\", ocolor);\n\t\t}\n\t\tif (use_editor) {\n\t\t\tconst char *editor = r_config_get (core->config, \"cfg.editor\");\n\t\t\tif (editor && *editor) {\n\t\t\t\tr_sys_cmdf (\"%s '%s'\", editor, str);\n\t\t\t\tr_file_rm (str);\n\t\t\t} else {\n\t\t\t\teprintf (\"No cfg.editor configured\\n\");\n\t\t\t}\n\t\t\tr_config_set_i (core->config, \"scr.color\", ocolor);\n\t\t\tfree (str);\n\t\t}\n\t\tif (scr_html != -1) {\n\t\t\tr_config_set_i (core->config, \"scr.html\", scr_html);\n\t\t}\n\t\t\tif (scr_color != -1) {\n\t\t\t\tr_config_set_i (core->config, \"scr.color\", scr_color);\n\t\t\t}\n\t\treturn ret;\n\t}\nnext2:\n\t/* sub commands */\n\tptr = strchr (cmd, '`');\n\tif (ptr) {\n\t\tint empty = 0;\n\t\tint oneline = 1;\n\t\tif (ptr[1] == '`') {\n\t\t\tmemmove (ptr, ptr + 1, strlen (ptr));\n\t\t\toneline = 0;\n\t\t\tempty = 1;\n\t\t}\n\t\tptr2 = strchr (ptr + 1, '`');\n\t\tif (empty) {\n\t\t\t/* do nothing */\n\t\t} else if (!ptr2) {\n\t\t\teprintf (\"parse: Missing backtick in expression.\\n\");\n\t\t\tgoto fail;\n\t\t} else {\n\t\t\tint value = core->num->value;\n\t\t\t*ptr = '\\0';\n\t\t\t*ptr2 = '\\0';\n\t\t\tif (ptr[1] == '!') {\n\t\t\t\tstr = r_core_cmd_str_pipe (core, ptr + 1);\n\t\t\t} else {\n\t\t\t\tstr = r_core_cmd_str (core, ptr + 1);\n\t\t\t}\n\t\t\tif (!str) {\n\t\t\t\tgoto fail;\n\t\t\t}\n\t\t\t// ignore contents if first char is pipe or comment\n\t\t\tif (*str == '|' || *str == '*') {\n\t\t\t\teprintf (\"r_core_cmd_subst_i: invalid backticked command\\n\");\n\t\t\t\tfree (str);\n\t\t\t\tgoto fail;\n\t\t\t}\n\t\t\tif (oneline && str) {\n\t\t\t\tfor (i = 0; str[i]; i++) {\n\t\t\t\t\tif (str[i] == '\\n') {\n\t\t\t\t\t\tstr[i] = ' ';\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tstr = r_str_append (str, ptr2 + 1);\n\t\t\tcmd = r_str_append (strdup (cmd), str);\n\t\t\tcore->num->value = value;\n\t\t\tret = r_core_cmd_subst (core, cmd);\n\t\t\tfree (cmd);\n\t\t\tif (scr_html != -1) {\n\t\t\t\tr_config_set_i (core->config, \"scr.html\", scr_html);\n\t\t\t}\n\t\t\tfree (str);\n\t\t\treturn ret;\n\t\t}\n\t}\n\t// TODO must honor \" and `\n\tcore->fixedblock = false;\n\n\tif (r_str_endswith (cmd, \"~?\") && cmd[2] == '\\0') {\n\t\tr_cons_grep_help ();\n\t\treturn true;\n\t}\n\tif (*cmd != '.') {\n\t\tr_cons_grep_parsecmd (cmd, quotestr);\n\t}\n\n\t/* temporary seek commands */\n\tif (*cmd!= '(' && *cmd != '\"') {\n\t\tptr = strchr (cmd, '@');\n\t\tif (ptr == cmd + 1 && *cmd == '?') {\n\t\t\tptr = NULL;\n\t\t}\n\t} else {\n\t\tptr = NULL;\n\t}\n\n\tcore->tmpseek = ptr? true: false;\n\tint rc = 0;\n\tif (ptr) {\n\t\tchar *f, *ptr2 = strchr (ptr + 1, '!');\n\t\tut64 addr = UT64_MAX;\n\t\tconst char *tmpbits = NULL;\n\t\tconst char *offstr = NULL;\n\t\tut64 tmpbsz = core->blocksize;\n\t\tchar *tmpeval = NULL;\n\t\tut64 tmpoff = core->offset;\n\t\tchar *tmpasm = NULL;\n\t\tint tmpfd = -1;\n\t\tint sz, len;\n\t\tut8 *buf;\n\n\t\t*ptr = '\\0';\n\t\tfor (ptr++; *ptr == ' '; ptr++) {\n\t\t\t//nothing to see here\n\t\t}\n\t\tif (*ptr && ptr[1] == ':') {\n\t\t\t/* do nothing here */\n\t\t} else {\n\t\t\tptr--;\n\t\t}\n\t\tarroba = (ptr[0] && ptr[1] && ptr[2])?\n\t\t\tstrchr (ptr + 2, '@'): NULL;\nrepeat_arroba:\n\t\tif (arroba) {\n\t\t\t*arroba = 0;\n\t\t}\n\t\tif (ptr[1] == '?') {\n\t\t\thelpCmdAt (core);\n\t\t} else if (ptr[0] && ptr[1] == ':' && ptr[2]) {\n\t\t\tusemyblock = true;\n\t\t\tswitch (ptr[0]) {\n\t\t\tcase 'f': // \"@f:\" // slurp file in block\n\t\t\t\tf = r_file_slurp (ptr + 2, &sz);\n\t\t\t\tif (f) {\n\t\t\t\t\tbuf = malloc (sz);\n\t\t\t\t\tif (buf) {\n\t\t\t\t\t\tfree (core->block);\n\t\t\t\t\t\tcore->block = buf;\n\t\t\t\t\t\tcore->blocksize = sz;\n\t\t\t\t\t\tmemcpy (core->block, f, sz);\n\t\t\t\t\t} else {\n\t\t\t\t\t\teprintf (\"cannot alloc %d\", sz);\n\t\t\t\t\t}\n\t\t\t\t\tfree (f);\n\t\t\t\t} else {\n\t\t\t\t\teprintf (\"cannot open '%s'\\n\", ptr + 3);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'r': // \"@r:\" // regname\n\t\t\t\tif (ptr[1] == ':') {\n\t\t\t\t\tut64 regval;\n\t\t\t\t\tchar *mander = strdup (ptr + 2);\n\t\t\t\t\tchar *sep = findSeparator (mander);\n\t\t\t\t\tif (sep) {\n\t\t\t\t\t\tchar ch = *sep;\n\t\t\t\t\t\t*sep = 0;\n\t\t\t\t\t\tregval = r_debug_reg_get (core->dbg, mander);\n\t\t\t\t\t\t*sep = ch;\n\t\t\t\t\t\tchar *numexpr = r_str_newf (\"0x%\"PFMT64x\"%s\", regval, sep);\n\t\t\t\t\t\tregval = r_num_math (core->num, numexpr);\n\t\t\t\t\t\tfree (numexpr);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tregval = r_debug_reg_get (core->dbg, ptr + 2);\n\t\t\t\t\t}\n\t\t\t\t\tr_core_seek (core, regval, 1);\n\t\t\t\t\tfree (mander);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'b': // \"@b:\" // bits\n\t\t\t\ttmpbits = strdup (r_config_get (core->config, \"asm.bits\"));\n\t\t\t\tr_config_set_i (core->config, \"asm.bits\",\n\t\t\t\t\tr_num_math (core->num, ptr + 2));\n\t\t\t\tbreak;\n\t\t\tcase 'i': // \"@i:\"\n\t\t\t\t{\n\t\t\t\t\tut64 addr = r_num_math (core->num, ptr + 2);\n\t\t\t\t\tif (addr) {\n\t\t\t\t\t\tr_core_cmdf (core, \"so %s\", ptr + 2);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'e': // \"@e:\"\n\t\t\t\ttmpeval = parse_tmp_evals (core, ptr + 2);\n\t\t\t\tbreak;\n\t\t\tcase 'x': // \"@x:\" // hexpairs\n\t\t\t\tif (ptr[1] == ':') {\n\t\t\t\t\tbuf = malloc (strlen (ptr + 2) + 1);\n\t\t\t\t\tif (buf) {\n\t\t\t\t\t\tlen = r_hex_str2bin (ptr + 2, buf);\n\t\t\t\t\t\tr_core_block_size (core, R_ABS(len));\n\t\t\t\t\t\tmemcpy (core->block, buf, core->blocksize);\n\t\t\t\t\t\tcore->fixedblock = true;\n\t\t\t\t\t\tfree (buf);\n\t\t\t\t\t} else {\n\t\t\t\t\t\teprintf (\"cannot allocate\\n\");\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\teprintf (\"Invalid @x: syntax\\n\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'k': // \"@k\"\n\t\t\t\t {\n\t\t\t\t\tchar *out = sdb_querys (core->sdb, NULL, 0, ptr + ((ptr[1])? 2: 1));\n\t\t\t\t\tif (out) {\n\t\t\t\t\t\tr_core_seek (core, r_num_math (core->num, out), 1);\n\t\t\t\t\t\tfree (out);\n\t\t\t\t\t}\n\t\t\t\t }\n\t\t\t\tbreak;\n\t\t\tcase 'o': // \"@o:3\"\n\t\t\t\tif (ptr[1] == ':') {\n\t\t\t\t\ttmpfd = core->io->raised;\n\t\t\t\t\tr_io_raise (core->io, atoi (ptr + 2));\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'a': // \"@a:\"\n\t\t\t\tif (ptr[1] == ':') {\n\t\t\t\t\tchar *q = strchr (ptr + 2, ':');\n\t\t\t\t\ttmpasm = strdup (r_config_get (core->config, \"asm.arch\"));\n\t\t\t\t\tif (q) {\n\t\t\t\t\t\t*q++ = 0;\n\t\t\t\t\t\ttmpbits = r_config_get (core->config, \"asm.bits\");\n\t\t\t\t\t\tr_config_set (core->config, \"asm.bits\", q);\n\t\t\t\t\t}\n\t\t\t\t\tr_config_set (core->config, \"asm.arch\", ptr + 2);\n\t\t\t\t\t// TODO: handle asm.bits\n\t\t\t\t} else {\n\t\t\t\t\teprintf (\"Usage: pd 10 @a:arm:32\\n\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 's': // \"@s:\"\n\t\t\t\tlen = strlen (ptr + 2);\n\t\t\t\tr_core_block_size (core, len);\n\t\t\t\tmemcpy (core->block, ptr + 2, len);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tgoto ignore;\n\t\t\t}\n\t\t\t*ptr = '@';\n\t\t\tgoto next_arroba; //ignore; //return ret;\n\t\t}\nignore:\n\t\tptr = r_str_trim_head (ptr + 1);\n\t\tptr--;\n\n\t\tcmd = r_str_clean (cmd);\n\t\tif (ptr2) {\n\t\t\tif (strlen (ptr + 1) == 13 && strlen (ptr2 + 1) == 6 &&\n\t\t\t !memcmp (ptr + 1, \"0x\", 2) &&\n\t\t\t !memcmp (ptr2 + 1, \"0x\", 2)) {\n\t\t\t\t/* 0xXXXX:0xYYYY */\n\t\t\t} else if (strlen (ptr + 1) == 9 && strlen (ptr2 + 1) == 4) {\n\t\t\t\t/* XXXX:YYYY */\n\t\t\t} else {\n\t\t\t\t*ptr2 = '\\0';\n\t\t\t\tif (!ptr2[1]) {\n\t\t\t\t\tgoto fail;\n\t\t\t\t}\n\t\t\t\tr_core_block_size (\n\t\t\t\t\tcore, r_num_math (core->num, ptr2 + 1));\n\t\t\t}\n\t\t}\n\n\t\toffstr = r_str_trim_head (ptr + 1);\n\n\t\taddr = r_num_math (core->num, offstr);\n\t\tif (isalpha ((unsigned char)ptr[1]) && !addr) {\n\t\t\tif (!r_flag_get (core->flags, ptr + 1)) {\n\t\t\t\teprintf (\"Invalid address (%s)\\n\", ptr + 1);\n\t\t\t\tgoto fail;\n\t\t\t}\n\t\t} else {\n\t\t\tchar ch = *offstr;\n\t\t\tif (ch == '-' || ch == '+') {\n\t\t\t\taddr = core->offset + addr;\n\t\t\t}\n\t\t}\nnext_arroba:\n\t\tif (arroba) {\n\t\t\tptr = arroba;\n\t\t\tarroba = NULL;\n\t\t\tgoto repeat_arroba;\n\t\t}\n\t\tif (ptr[1] == '@') {\n\t\t\t// TODO: remove temporally seek (should be done by cmd_foreach)\n\t\t\tif (ptr[2] == '@') {\n\t\t\t\tchar *rule = ptr + 3;\n\t\t\t\twhile (*rule && *rule == ' ') rule++;\n\t\t\t\tret = r_core_cmd_foreach3 (core, cmd, rule);\n\t\t\t} else {\n\t\t\t\tret = r_core_cmd_foreach (core, cmd, ptr + 2);\n\t\t\t}\n\t\t\t//ret = -1; /* do not run out-of-foreach cmd */\n\t\t} else {\n\t\t\tbool tmpseek = false;\n\t\t\tconst char *fromvars[] = { \"anal.from\", \"diff.from\", \"graph.from\",\n\t\t\t\t\"io.buffer.from\", \"lines.from\", \"search.from\", \"zoom.from\", NULL };\n\t\t\tconst char *tovars[] = { \"anal.to\", \"diff.to\", \"graph.to\",\n\t\t\t\t\"io.buffer.to\", \"lines.to\", \"search.to\", \"zoom.to\", NULL };\n\t\t\tut64 curfrom[R_ARRAY_SIZE (fromvars) - 1], curto[R_ARRAY_SIZE (tovars) - 1];\n\n\t\t\t// @..\n\t\t\tif (ptr[1] == '.' && ptr[2] == '.') {\n\t\t\t\tchar *range = ptr + 3;\n\t\t\t\tchar *p = strchr (range, ' ');\n\t\t\t\tif (!p) {\n\t\t\t\t\teprintf (\"Usage: / ABCD @..0x1000 0x3000\\n\");\n\t\t\t\t\tfree (tmpeval);\n\t\t\t\t\tfree (tmpasm);\n\t\t\t\t\tgoto fail;\n\t\t\t\t}\n\t\t\t\t*p = '\\x00';\n\t\t\t\tut64 from = r_num_math (core->num, range);\n\t\t\t\tut64 to = r_num_math (core->num, p + 1);\n\t\t\t\t// save current ranges\n\t\t\t\tfor (i = 0; fromvars[i]; i++) {\n\t\t\t\t\tcurfrom[i] = r_config_get_i (core->config, fromvars[i]);\n\t\t\t\t}\n\t\t\t\tfor (i = 0; tovars[i]; i++) {\n\t\t\t\t\tcurto[i] = r_config_get_i (core->config, tovars[i]);\n\t\t\t\t}\n\t\t\t\t// set new ranges\n\t\t\t\tfor (i = 0; fromvars[i]; i++) {\n\t\t\t\t\tr_config_set_i (core->config, fromvars[i], from);\n\t\t\t\t}\n\t\t\t\tfor (i = 0; tovars[i]; i++) {\n\t\t\t\t\tr_config_set_i (core->config, tovars[i], to);\n\t\t\t\t}\n\t\t\t\ttmpseek = true;\n\t\t\t}\n\t\t\tif (usemyblock) {\n\t\t\t\tif (addr != UT64_MAX) {\n\t\t\t\t\tcore->offset = addr;\n\t\t\t\t}\n\t\t\t\tret = r_cmd_call (core->rcmd, r_str_trim_head (cmd));\n\t\t\t} else {\n\t\t\t\tif (addr != UT64_MAX) {\n\t\t\t\t\tif (!ptr[1] || r_core_seek (core, addr, 1)) {\n\t\t\t\t\t\tr_core_block_read (core);\n\t\t\t\t\t\tret = r_cmd_call (core->rcmd, r_str_trim_head (cmd));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tret = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (tmpseek) {\n\t\t\t\t// restore ranges\n\t\t\t\tfor (i = 0; fromvars[i]; i++) {\n\t\t\t\t\tr_config_set_i (core->config, fromvars[i], curfrom[i]);\n\t\t\t\t}\n\t\t\t\tfor (i = 0; tovars[i]; i++) {\n\t\t\t\t\tr_config_set_i (core->config, tovars[i], curto[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (ptr2) {\n\t\t\t*ptr2 = '!';\n\t\t\tr_core_block_size (core, tmpbsz);\n\t\t}\n\t\tif (tmpasm) {\n\t\t\tr_config_set (core->config, \"asm.arch\", tmpasm);\n\t\t\ttmpasm = NULL;\n\t\t}\n\t\tif (tmpfd != -1) {\n\t\t\tr_io_raise (core->io, tmpfd);\n\t\t}\n\t\tif (tmpbits) {\n\t\t\tr_config_set (core->config, \"asm.bits\", tmpbits);\n\t\t\ttmpbits = NULL;\n\t\t}\n\t\tif (tmpeval) {\n\t\t\tr_core_cmd0 (core, tmpeval);\n\t\t\tR_FREE (tmpeval);\n\t\t}\n\t\tr_core_seek (core, tmpoff, 1);\n\t\t*ptr = '@';\n\t\trc = ret;\n\t\tgoto beach;\n\t}\n\n\trc = cmd? r_cmd_call (core->rcmd, r_str_trim_head (cmd)): false;\nbeach:\n\tif (scr_html != -1) {\n\t\tr_cons_flush ();\n\t\tr_config_set_i (core->config, \"scr.html\", scr_html);\n\t}\n\tif (scr_color != -1) {\n\t\tr_config_set_i (core->config, \"scr.color\", scr_color);\n\t}\n\tcore->fixedblock = false;\n\treturn rc;\nfail:\n\trc = -1;\n\tgoto beach;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix #7727 - undefined pointers and out of band string access fixes'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void WriteProfile(j_compress_ptr jpeg_info,Image *image)\n{\n const char\n *name;\n\n const StringInfo\n *profile;\n\n MagickBooleanType\n iptc;\n\n register ssize_t\n i;\n\n size_t\n length,\n tag_length;\n\n StringInfo\n *custom_profile;\n\n /*\n Save image profile as a APP marker.\n */\n iptc=MagickFalse;\n custom_profile=AcquireStringInfo(65535L);\n ResetImageProfileIterator(image);\n for (name=GetNextImageProfile(image); name != (const char *) NULL; )\n {\n profile=GetImageProfile(image,name);\n if (LocaleCompare(name,\"EXIF\") == 0)\n for (i=0; i < (ssize_t) GetStringInfoLength(profile); i+=65533L)\n {\n length=MagickMin(GetStringInfoLength(profile)-i,65533L);\n jpeg_write_marker(jpeg_info,XML_MARKER,GetStringInfoDatum(profile)+i,\n (unsigned int) length);\n }\n if (LocaleCompare(name,\"ICC\") == 0)\n {\n register unsigned char\n *p;\n\n tag_length=strlen(ICC_PROFILE);\n p=GetStringInfoDatum(custom_profile);\n (void) CopyMagickMemory(p,ICC_PROFILE,tag_length);\n p[tag_length]='\\0';\n for (i=0; i < (ssize_t) GetStringInfoLength(profile); i+=65519L)\n {\n length=MagickMin(GetStringInfoLength(profile)-i,65519L);\n p[12]=(unsigned char) ((i/65519L)+1);\n p[13]=(unsigned char) (GetStringInfoLength(profile)/65519L+1);\n (void) CopyMagickMemory(p+tag_length+3,GetStringInfoDatum(profile)+i,\n length);\n jpeg_write_marker(jpeg_info,ICC_MARKER,GetStringInfoDatum(\n custom_profile),(unsigned int) (length+tag_length+3));\n }\n }\n if (((LocaleCompare(name,\"IPTC\") == 0) ||\n (LocaleCompare(name,\"8BIM\") == 0)) && (iptc == MagickFalse))\n {\n register unsigned char\n *p;\n\n size_t\n roundup;\n\n iptc=MagickTrue;\n p=GetStringInfoDatum(custom_profile);\n for (i=0; i < (ssize_t) GetStringInfoLength(profile); i+=65500L)\n {\n length=MagickMin(GetStringInfoLength(profile)-i,65500L);\n roundup=(size_t) (length & 0x01);\n if (LocaleNCompare((char *) GetStringInfoDatum(profile),\"8BIM\",4) == 0)\n {\n (void) memcpy(p,\"Photoshop 3.0 \",14);\n tag_length=14;\n }\n else\n {\n (void) CopyMagickMemory(p,\"Photoshop 3.0 8BIM\\04\\04\\0\\0\\0\\0\",24);\n tag_length=26;\n p[24]=(unsigned char) (length >> 8);\n p[25]=(unsigned char) (length & 0xff);\n }\n p[13]=0x00;\n (void) memcpy(p+tag_length,GetStringInfoDatum(profile)+i,length);\n if (roundup != 0)\n p[length+tag_length]='\\0';\n jpeg_write_marker(jpeg_info,IPTC_MARKER,GetStringInfoDatum(\n custom_profile),(unsigned int) (length+tag_length+roundup));\n }\n }\n if (LocaleCompare(name,\"XMP\") == 0)\n {\n StringInfo\n *xmp_profile;\n\n /*\n Add namespace to XMP profile.\n */\n xmp_profile=StringToStringInfo(\"http://ns.adobe.com/xap/1.0/ \");\n if (xmp_profile != (StringInfo *) NULL)\n {\n if (profile != (StringInfo *) NULL)\n ConcatenateStringInfo(xmp_profile,profile);\n GetStringInfoDatum(xmp_profile)[28]='\\0';\n for (i=0; i < (ssize_t) GetStringInfoLength(xmp_profile); i+=65533L)\n {\n length=MagickMin(GetStringInfoLength(xmp_profile)-i,65533L);\n jpeg_write_marker(jpeg_info,XML_MARKER,\n GetStringInfoDatum(xmp_profile)+i,(unsigned int) length);\n }\n xmp_profile=DestroyStringInfo(xmp_profile);\n }\n }\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"%s profile: %.20g bytes\",name,(double) GetStringInfoLength(profile));\n name=GetNextImageProfile(image);\n }\n custom_profile=DestroyStringInfo(custom_profile);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Changed the JPEG writer to raise a warning when the exif profile exceeds 65533 bytes and truncate it.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static __init int hardware_setup(void)\n{\n\tint r = -ENOMEM, i, msr;\n\n\trdmsrl_safe(MSR_EFER, &host_efer);\n\n\tfor (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)\n\t\tkvm_define_shared_msr(i, vmx_msr_index[i]);\n\n\tvmx_io_bitmap_a = (unsigned long *)__get_free_page(GFP_KERNEL);\n\tif (!vmx_io_bitmap_a)\n\t\treturn r;\n\n\tvmx_io_bitmap_b = (unsigned long *)__get_free_page(GFP_KERNEL);\n\tif (!vmx_io_bitmap_b)\n\t\tgoto out;\n\n\tvmx_msr_bitmap_legacy = (unsigned long *)__get_free_page(GFP_KERNEL);\n\tif (!vmx_msr_bitmap_legacy)\n\t\tgoto out1;\n\n\tvmx_msr_bitmap_legacy_x2apic =\n\t\t\t\t(unsigned long *)__get_free_page(GFP_KERNEL);\n\tif (!vmx_msr_bitmap_legacy_x2apic)\n\t\tgoto out2;\n\n\tvmx_msr_bitmap_longmode = (unsigned long *)__get_free_page(GFP_KERNEL);\n\tif (!vmx_msr_bitmap_longmode)\n\t\tgoto out3;\n\n\tvmx_msr_bitmap_longmode_x2apic =\n\t\t\t\t(unsigned long *)__get_free_page(GFP_KERNEL);\n\tif (!vmx_msr_bitmap_longmode_x2apic)\n\t\tgoto out4;\n\n\tif (nested) {\n\t\tvmx_msr_bitmap_nested =\n\t\t\t(unsigned long *)__get_free_page(GFP_KERNEL);\n\t\tif (!vmx_msr_bitmap_nested)\n\t\t\tgoto out5;\n\t}\n\n\tvmx_vmread_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);\n\tif (!vmx_vmread_bitmap)\n\t\tgoto out6;\n\n\tvmx_vmwrite_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);\n\tif (!vmx_vmwrite_bitmap)\n\t\tgoto out7;\n\n\tmemset(vmx_vmread_bitmap, 0xff, PAGE_SIZE);\n\tmemset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE);\n\n\t/*\n\t * Allow direct access to the PC debug port (it is often used for I/O\n\t * delays, but the vmexits simply slow things down).\n\t */\n\tmemset(vmx_io_bitmap_a, 0xff, PAGE_SIZE);\n\tclear_bit(0x80, vmx_io_bitmap_a);\n\n\tmemset(vmx_io_bitmap_b, 0xff, PAGE_SIZE);\n\n\tmemset(vmx_msr_bitmap_legacy, 0xff, PAGE_SIZE);\n\tmemset(vmx_msr_bitmap_longmode, 0xff, PAGE_SIZE);\n\tif (nested)\n\t\tmemset(vmx_msr_bitmap_nested, 0xff, PAGE_SIZE);\n\n\tif (setup_vmcs_config(&vmcs_config) < 0) {\n\t\tr = -EIO;\n\t\tgoto out8;\n\t}\n\n\tif (boot_cpu_has(X86_FEATURE_NX))\n\t\tkvm_enable_efer_bits(EFER_NX);\n\n\tif (!cpu_has_vmx_vpid())\n\t\tenable_vpid = 0;\n\tif (!cpu_has_vmx_shadow_vmcs())\n\t\tenable_shadow_vmcs = 0;\n\tif (enable_shadow_vmcs)\n\t\tinit_vmcs_shadow_fields();\n\n\tif (!cpu_has_vmx_ept() ||\n\t !cpu_has_vmx_ept_4levels()) {\n\t\tenable_ept = 0;\n\t\tenable_unrestricted_guest = 0;\n\t\tenable_ept_ad_bits = 0;\n\t}\n\n\tif (!cpu_has_vmx_ept_ad_bits())\n\t\tenable_ept_ad_bits = 0;\n\n\tif (!cpu_has_vmx_unrestricted_guest())\n\t\tenable_unrestricted_guest = 0;\n\n\tif (!cpu_has_vmx_flexpriority())\n\t\tflexpriority_enabled = 0;\n\n\t/*\n\t * set_apic_access_page_addr() is used to reload apic access\n\t * page upon invalidation. No need to do anything if not\n\t * using the APIC_ACCESS_ADDR VMCS field.\n\t */\n\tif (!flexpriority_enabled)\n\t\tkvm_x86_ops->set_apic_access_page_addr = NULL;\n\n\tif (!cpu_has_vmx_tpr_shadow())\n\t\tkvm_x86_ops->update_cr8_intercept = NULL;\n\n\tif (enable_ept && !cpu_has_vmx_ept_2m_page())\n\t\tkvm_disable_largepages();\n\n\tif (!cpu_has_vmx_ple())\n\t\tple_gap = 0;\n\n\tif (!cpu_has_vmx_apicv())\n\t\tenable_apicv = 0;\n\n\tif (cpu_has_vmx_tsc_scaling()) {\n\t\tkvm_has_tsc_control = true;\n\t\tkvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;\n\t\tkvm_tsc_scaling_ratio_frac_bits = 48;\n\t}\n\n\tvmx_disable_intercept_for_msr(MSR_FS_BASE, false);\n\tvmx_disable_intercept_for_msr(MSR_GS_BASE, false);\n\tvmx_disable_intercept_for_msr(MSR_KERNEL_GS_BASE, true);\n\tvmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_CS, false);\n\tvmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_ESP, false);\n\tvmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_EIP, false);\n\tvmx_disable_intercept_for_msr(MSR_IA32_BNDCFGS, true);\n\n\tmemcpy(vmx_msr_bitmap_legacy_x2apic,\n\t\t\tvmx_msr_bitmap_legacy, PAGE_SIZE);\n\tmemcpy(vmx_msr_bitmap_longmode_x2apic,\n\t\t\tvmx_msr_bitmap_longmode, PAGE_SIZE);\n\n\tset_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */\n\n\tif (enable_apicv) {\n\t\tfor (msr = 0x800; msr <= 0x8ff; msr++)\n\t\t\tvmx_disable_intercept_msr_read_x2apic(msr);\n\n\t\t/* According SDM, in x2apic mode, the whole id reg is used.\n\t\t * But in KVM, it only use the highest eight bits. Need to\n\t\t * intercept it */\n\t\tvmx_enable_intercept_msr_read_x2apic(0x802);\n\t\t/* TMCCT */\n\t\tvmx_enable_intercept_msr_read_x2apic(0x839);\n\t\t/* TPR */\n\t\tvmx_disable_intercept_msr_write_x2apic(0x808);\n\t\t/* EOI */\n\t\tvmx_disable_intercept_msr_write_x2apic(0x80b);\n\t\t/* SELF-IPI */\n\t\tvmx_disable_intercept_msr_write_x2apic(0x83f);\n\t}\n\n\tif (enable_ept) {\n\t\tkvm_mmu_set_mask_ptes(0ull,\n\t\t\t(enable_ept_ad_bits) ? VMX_EPT_ACCESS_BIT : 0ull,\n\t\t\t(enable_ept_ad_bits) ? VMX_EPT_DIRTY_BIT : 0ull,\n\t\t\t0ull, VMX_EPT_EXECUTABLE_MASK);\n\t\tept_set_mmio_spte_mask();\n\t\tkvm_enable_tdp();\n\t} else\n\t\tkvm_disable_tdp();\n\n\tupdate_ple_window_actual_max();\n\n\t/*\n\t * Only enable PML when hardware supports PML feature, and both EPT\n\t * and EPT A/D bit features are enabled -- PML depends on them to work.\n\t */\n\tif (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())\n\t\tenable_pml = 0;\n\n\tif (!enable_pml) {\n\t\tkvm_x86_ops->slot_enable_log_dirty = NULL;\n\t\tkvm_x86_ops->slot_disable_log_dirty = NULL;\n\t\tkvm_x86_ops->flush_log_dirty = NULL;\n\t\tkvm_x86_ops->enable_log_dirty_pt_masked = NULL;\n\t}\n\n\tkvm_set_posted_intr_wakeup_handler(wakeup_handler);\n\n\treturn alloc_kvm_area();\n\nout8:\n\tfree_page((unsigned long)vmx_vmwrite_bitmap);\nout7:\n\tfree_page((unsigned long)vmx_vmread_bitmap);\nout6:\n\tif (nested)\n\t\tfree_page((unsigned long)vmx_msr_bitmap_nested);\nout5:\n\tfree_page((unsigned long)vmx_msr_bitmap_longmode_x2apic);\nout4:\n\tfree_page((unsigned long)vmx_msr_bitmap_longmode);\nout3:\n\tfree_page((unsigned long)vmx_msr_bitmap_legacy_x2apic);\nout2:\n\tfree_page((unsigned long)vmx_msr_bitmap_legacy);\nout1:\n\tfree_page((unsigned long)vmx_io_bitmap_b);\nout:\n\tfree_page((unsigned long)vmx_io_bitmap_a);\n\n return r;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'kvm:vmx: more complete state update on APICv on/off\n\nThe function to update APICv on/off state (in particular, to deactivate\nit when enabling Hyper-V SynIC) is incomplete: it doesn't adjust\nAPICv-related fields among secondary processor-based VM-execution\ncontrols. As a result, Windows 2012 guests get stuck when SynIC-based\nauto-EOI interrupt intersected with e.g. an IPI in the guest.\n\nIn addition, the MSR intercept bitmap isn't updated every time \"virtualize\nx2APIC mode\" is toggled. This path can only be triggered by a malicious\nguest, because Windows didn't use x2APIC but rather their own synthetic\nAPIC access MSRs; however a guest running in a SynIC-enabled VM could\nswitch to x2APIC and thus obtain direct access to host APIC MSRs\n(CVE-2016-4440).\n\nThe patch fixes those omissions.\n\nSigned-off-by: Roman Kagan \nReported-by: Steve Rutherford \nReported-by: Yang Zhang \nSigned-off-by: Paolo Bonzini '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static __always_inline ssize_t __mcopy_atomic(struct mm_struct *dst_mm,\n\t\t\t\t\t unsigned long dst_start,\n\t\t\t\t\t unsigned long src_start,\n\t\t\t\t\t unsigned long len,\n\t\t\t\t\t bool zeropage,\n\t\t\t\t\t bool *mmap_changing)\n{\n\tstruct vm_area_struct *dst_vma;\n\tssize_t err;\n\tpmd_t *dst_pmd;\n\tunsigned long src_addr, dst_addr;\n\tlong copied;\n\tstruct page *page;\n\n\t/*\n\t * Sanitize the command parameters:\n\t */\n\tBUG_ON(dst_start & ~PAGE_MASK);\n\tBUG_ON(len & ~PAGE_MASK);\n\n\t/* Does the address range wrap, or is the span zero-sized? */\n\tBUG_ON(src_start + len <= src_start);\n\tBUG_ON(dst_start + len <= dst_start);\n\n\tsrc_addr = src_start;\n\tdst_addr = dst_start;\n\tcopied = 0;\n\tpage = NULL;\nretry:\n\tdown_read(&dst_mm->mmap_sem);\n\n\t/*\n\t * If memory mappings are changing because of non-cooperative\n\t * operation (e.g. mremap) running in parallel, bail out and\n\t * request the user to retry later\n\t */\n\terr = -EAGAIN;\n\tif (mmap_changing && READ_ONCE(*mmap_changing))\n\t\tgoto out_unlock;\n\n\t/*\n\t * Make sure the vma is not shared, that the dst range is\n\t * both valid and fully within a single existing vma.\n\t */\n\terr = -ENOENT;\n\tdst_vma = find_vma(dst_mm, dst_start);\n\tif (!dst_vma)\n\t\tgoto out_unlock;\n\t/*\n\t * Be strict and only allow __mcopy_atomic on userfaultfd\n\t * registered ranges to prevent userland errors going\n\t * unnoticed. As far as the VM consistency is concerned, it\n\t * would be perfectly safe to remove this check, but there's\n\t * no useful usage for __mcopy_atomic ouside of userfaultfd\n\t * registered ranges. This is after all why these are ioctls\n\t * belonging to the userfaultfd and not syscalls.\n\t */\n\tif (!dst_vma->vm_userfaultfd_ctx.ctx)\n\t\tgoto out_unlock;\n\n\tif (dst_start < dst_vma->vm_start ||\n\t dst_start + len > dst_vma->vm_end)\n\t\tgoto out_unlock;\n\n\terr = -EINVAL;\n\t/*\n\t * shmem_zero_setup is invoked in mmap for MAP_ANONYMOUS|MAP_SHARED but\n\t * it will overwrite vm_ops, so vma_is_anonymous must return false.\n\t */\n\tif (WARN_ON_ONCE(vma_is_anonymous(dst_vma) &&\n\t dst_vma->vm_flags & VM_SHARED))\n\t\tgoto out_unlock;\n\n\t/*\n\t * If this is a HUGETLB vma, pass off to appropriate routine\n\t */\n\tif (is_vm_hugetlb_page(dst_vma))\n\t\treturn __mcopy_atomic_hugetlb(dst_mm, dst_vma, dst_start,\n\t\t\t\t\t\tsrc_start, len, zeropage);\n\n\tif (!vma_is_anonymous(dst_vma) && !vma_is_shmem(dst_vma))\n\t\tgoto out_unlock;\n\n\t/*\n\t * Ensure the dst_vma has a anon_vma or this page\n\t * would get a NULL anon_vma when moved in the\n\t * dst_vma.\n\t */\n\terr = -ENOMEM;\n\tif (!(dst_vma->vm_flags & VM_SHARED) &&\n\t unlikely(anon_vma_prepare(dst_vma)))\n\t\tgoto out_unlock;\n\n\twhile (src_addr < src_start + len) {\n\t\tpmd_t dst_pmdval;\n\n\t\tBUG_ON(dst_addr >= dst_start + len);\n\n\t\tdst_pmd = mm_alloc_pmd(dst_mm, dst_addr);\n\t\tif (unlikely(!dst_pmd)) {\n\t\t\terr = -ENOMEM;\n\t\t\tbreak;\n\t\t}\n\n\t\tdst_pmdval = pmd_read_atomic(dst_pmd);\n\t\t/*\n\t\t * If the dst_pmd is mapped as THP don't\n\t\t * override it and just be strict.\n\t\t */\n\t\tif (unlikely(pmd_trans_huge(dst_pmdval))) {\n\t\t\terr = -EEXIST;\n\t\t\tbreak;\n\t\t}\n\t\tif (unlikely(pmd_none(dst_pmdval)) &&\n\t\t unlikely(__pte_alloc(dst_mm, dst_pmd, dst_addr))) {\n\t\t\terr = -ENOMEM;\n\t\t\tbreak;\n\t\t}\n\t\t/* If an huge pmd materialized from under us fail */\n\t\tif (unlikely(pmd_trans_huge(*dst_pmd))) {\n\t\t\terr = -EFAULT;\n\t\t\tbreak;\n\t\t}\n\n\t\tBUG_ON(pmd_none(*dst_pmd));\n\t\tBUG_ON(pmd_trans_huge(*dst_pmd));\n\n\t\terr = mfill_atomic_pte(dst_mm, dst_pmd, dst_vma, dst_addr,\n\t\t\t\t src_addr, &page, zeropage);\n\t\tcond_resched();\n\n\t\tif (unlikely(err == -ENOENT)) {\n\t\t\tvoid *page_kaddr;\n\n\t\t\tup_read(&dst_mm->mmap_sem);\n\t\t\tBUG_ON(!page);\n\n\t\t\tpage_kaddr = kmap(page);\n\t\t\terr = copy_from_user(page_kaddr,\n\t\t\t\t\t (const void __user *) src_addr,\n\t\t\t\t\t PAGE_SIZE);\n\t\t\tkunmap(page);\n\t\t\tif (unlikely(err)) {\n\t\t\t\terr = -EFAULT;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tgoto retry;\n\t\t} else\n\t\t\tBUG_ON(page);\n\n\t\tif (!err) {\n\t\t\tdst_addr += PAGE_SIZE;\n\t\t\tsrc_addr += PAGE_SIZE;\n\t\t\tcopied += PAGE_SIZE;\n\n\t\t\tif (fatal_signal_pending(current))\n\t\t\t\terr = -EINTR;\n\t\t}\n\t\tif (err)\n\t\t\tbreak;\n\t}\n\nout_unlock:\n\tup_read(&dst_mm->mmap_sem);\nout:\n\tif (page)\n\t\tput_page(page);\n\tBUG_ON(copied < 0);\n\tBUG_ON(err > 0);\n\tBUG_ON(!copied && !err);\n\treturn copied ? copied : err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-862', 'CWE-863'], 'message': 'userfaultfd: shmem/hugetlbfs: only allow to register VM_MAYWRITE vmas\n\nAfter the VMA to register the uffd onto is found, check that it has\nVM_MAYWRITE set before allowing registration. This way we inherit all\ncommon code checks before allowing to fill file holes in shmem and\nhugetlbfs with UFFDIO_COPY.\n\nThe userfaultfd memory model is not applicable for readonly files unless\nit's a MAP_PRIVATE.\n\nLink: http://lkml.kernel.org/r/20181126173452.26955-4-aarcange@redhat.com\nFixes: ff62a3421044 (\"hugetlb: implement memfd sealing\")\nSigned-off-by: Andrea Arcangeli \nReviewed-by: Mike Rapoport \nReviewed-by: Hugh Dickins \nReported-by: Jann Horn \nFixes: 4c27fe4c4c84 (\"userfaultfd: shmem: add shmem_mcopy_atomic_pte for userfaultfd support\")\nCc: \nCc: \"Dr. David Alan Gilbert\" \nCc: Mike Kravetz \nCc: Peter Xu \nCc: stable@vger.kernel.org\nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ecall_restore(const char *input, uint64_t input_len, char **output,\n uint64_t *output_len) {\n if (!asylo::primitives::TrustedPrimitives::IsOutsideEnclave(input,\n input_len)) {\n asylo::primitives::TrustedPrimitives::BestEffortAbort(\n \"ecall_restore: input found to not be in untrusted memory.\");\n }\n int result = 0;\n size_t tmp_output_len;\n try {\n result = asylo::Restore(input, static_cast(input_len), output,\n &tmp_output_len);\n } catch (...) {\n LOG(FATAL) << \"Uncaught exception in enclave\";\n }\n\n if (output_len) {\n *output_len = static_cast(tmp_output_len);\n }\n return result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Check for output_len range in ecall_restore\n\nThis may cause vulnerablity if pointing to trusted memory.\n\nThis issue was reported by Qinkun Bao, Zhaofeng Chen, Mingshen Sun, and\nKang Li from Baidu Security.\n\nPiperOrigin-RevId: 322476223\nChange-Id: I8a6406e9f07a20582d4387bd9a3469dfa9cbcb12'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int do_i2c_crc(struct cmd_tbl *cmdtp, int flag, int argc,\n\t\t char *const argv[])\n{\n\tuint\tchip;\n\tulong\taddr;\n\tint\talen;\n\tint\tcount;\n\tuchar\tbyte;\n\tulong\tcrc;\n\tulong\terr;\n\tint ret = 0;\n#if CONFIG_IS_ENABLED(DM_I2C)\n\tstruct udevice *dev;\n#endif\n\n\tif (argc < 4)\n\t\treturn CMD_RET_USAGE;\n\n\t/*\n\t * Chip is always specified.\n\t */\n\tchip = hextoul(argv[1], NULL);\n\n\t/*\n\t * Address is always specified.\n\t */\n\taddr = hextoul(argv[2], NULL);\n\talen = get_alen(argv[2], DEFAULT_ADDR_LEN);\n\tif (alen > 3)\n\t\treturn CMD_RET_USAGE;\n\n#if CONFIG_IS_ENABLED(DM_I2C)\n\tret = i2c_get_cur_bus_chip(chip, &dev);\n\tif (!ret && alen != -1)\n\t\tret = i2c_set_chip_offset_len(dev, alen);\n\tif (ret)\n\t\treturn i2c_report_err(ret, I2C_ERR_READ);\n#endif\n\t/*\n\t * Count is always specified\n\t */\n\tcount = hextoul(argv[3], NULL);\n\n\tprintf (\"CRC32 for %08lx ... %08lx ==> \", addr, addr + count - 1);\n\t/*\n\t * CRC a byte at a time. This is going to be slooow, but hey, the\n\t * memories are small and slow too so hopefully nobody notices.\n\t */\n\tcrc = 0;\n\terr = 0;\n\twhile (count-- > 0) {\n#if CONFIG_IS_ENABLED(DM_I2C)\n\t\tret = dm_i2c_read(dev, addr, &byte, 1);\n#else\n\t\tret = i2c_read(chip, addr, alen, &byte, 1);\n#endif\n\t\tif (ret)\n\t\t\terr++;\n\t\tcrc = crc32(crc, &byte, 1);\n\t\taddr++;\n\t}\n\tif (err > 0)\n\t\ti2c_report_err(ret, I2C_ERR_READ);\n\telse\n\t\tprintf (\"%08lx\\n\", crc);\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'i2c: fix stack buffer overflow vulnerability in i2c md command\n\nWhen running \"i2c md 0 0 80000100\", the function do_i2c_md parses the\nlength into an unsigned int variable named length. The value is then\nmoved to a signed variable:\n\n int nbytes = length;\n #define DISP_LINE_LEN 16\n int linebytes = (nbytes > DISP_LINE_LEN) ? DISP_LINE_LEN : nbytes;\n ret = dm_i2c_read(dev, addr, linebuf, linebytes);\n\nOn systems where integers are 32 bits wide, 0x80000100 is a negative\nvalue to \"nbytes > DISP_LINE_LEN\" is false and linebytes gets assigned\n0x80000100 instead of 16.\n\nThe consequence is that the function which reads from the i2c device\n(dm_i2c_read or i2c_read) is called with a 16-byte stack buffer to fill\nbut with a size parameter which is too large. In some cases, this could\ntrigger a crash. But with some i2c drivers, such as drivers/i2c/nx_i2c.c\n(used with \"nexell,s5pxx18-i2c\" bus), the size is actually truncated to\na 16-bit integer. This is because function i2c_transfer expects an\nunsigned short length. In such a case, an attacker who can control the\nresponse of an i2c device can overwrite the return address of a function\nand execute arbitrary code through Return-Oriented Programming.\n\nFix this issue by using unsigned integers types in do_i2c_md. While at\nit, make also alen unsigned, as signed sizes can cause vulnerabilities\nwhen people forgot to check that they can be negative.\n\nSigned-off-by: Nicolas Iooss \nReviewed-by: Heiko Schocher '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static unsigned int seedsize(struct crypto_alg *alg)\n{\n\tstruct rng_alg *ralg = container_of(alg, struct rng_alg, base);\n\n\treturn alg->cra_rng.rng_make_random ?\n\t alg->cra_rng.seedsize : ralg->seedsize;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-703'], 'message': 'crypto: rng - Remove old low-level rng interface\n\nNow that all rng implementations have switched over to the new\ninterface, we can remove the old low-level interface.\n\nSigned-off-by: Herbert Xu '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: find_file (const char *currpath, grub_fshelp_node_t currroot,\n\t grub_fshelp_node_t *currfound,\n\t struct grub_fshelp_find_file_closure *c)\n{\n#ifndef _MSC_VER\n\tchar fpath[grub_strlen (currpath) + 1];\n#else\n\tchar *fpath = grub_malloc (grub_strlen (currpath) + 1);\n#endif\n char *name = fpath;\n char *next;\n enum grub_fshelp_filetype type = GRUB_FSHELP_DIR;\n grub_fshelp_node_t currnode = currroot;\n grub_fshelp_node_t oldnode = currroot;\n\n c->currroot = currroot;\n\n grub_strncpy (fpath, currpath, grub_strlen (currpath) + 1);\n\n /* Remove all leading slashes. */\n while (*name == '/')\n name++;\n\n if (! *name)\n {\n *currfound = currnode;\n return 0;\n }\n\n for (;;)\n {\n int found;\n struct find_file_closure cc;\n\n /* Extract the actual part from the pathname. */\n next = grub_strchr (name, '/');\n if (next)\n\t{\n\t /* Remove all leading slashes. */\n\t while (*next == '/')\n\t *(next++) = '\\0';\n\t}\n\n /* At this point it is expected that the current node is a\n\t directory, check if this is true. */\n if (type != GRUB_FSHELP_DIR)\n\t{\n\t free_node (currnode, c);\n\t return grub_error (GRUB_ERR_BAD_FILE_TYPE, \"not a directory\");\n\t}\n\n cc.name = name;\n cc.type = &type;\n cc.oldnode = &oldnode;\n cc.currnode = &currnode;\n /* Iterate over the directory. */\n found = c->iterate_dir (currnode, iterate, &cc);\n if (! found)\n\t{\n\t if (grub_errno)\n\t return grub_errno;\n\n\t break;\n\t}\n\n /* Read in the symlink and follow it. */\n if (type == GRUB_FSHELP_SYMLINK)\n\t{\n\t char *symlink;\n\n\t /* Test if the symlink does not loop. */\n\t if (++(c->symlinknest) == 8)\n\t {\n\t free_node (currnode, c);\n\t free_node (oldnode, c);\n\t return grub_error (GRUB_ERR_SYMLINK_LOOP,\n\t\t\t\t \"too deep nesting of symlinks\");\n\t }\n\n\t symlink = c->read_symlink (currnode);\n\t free_node (currnode, c);\n\n\t if (!symlink)\n\t {\n\t free_node (oldnode, c);\n\t return grub_errno;\n\t }\n\n\t /* The symlink is an absolute path, go back to the root inode. */\n\t if (symlink[0] == '/')\n\t {\n\t free_node (oldnode, c);\n\t oldnode = c->rootnode;\n\t }\n\n\t /* Lookup the node the symlink points to. */\n\t find_file (symlink, oldnode, &currnode, c);\n\t type = c->foundtype;\n\t grub_free (symlink);\n\n\t if (grub_errno)\n\t {\n\t free_node (oldnode, c);\n\t return grub_errno;\n\t }\n\t}\n\n free_node (oldnode, c);\n\n /* Found the node! */\n if (! next || *next == '\\0')\n\t{\n\t *currfound = currnode;\n\t c->foundtype = type;\n\t return 0;\n\t}\n\n name = next;\n }\n\n return grub_error (GRUB_ERR_FILE_NOT_FOUND, \"file not found\");\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix #7723 - crash in ext2 GRUB code because of variable size array in stack'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void Compute(OpKernelContext* ctx) override {\n const Tensor* inputs;\n const Tensor* seq_len;\n Tensor* log_prob = nullptr;\n OpOutputList decoded_indices;\n OpOutputList decoded_values;\n OpOutputList decoded_shape;\n OP_REQUIRES_OK(ctx, decode_helper_.ValidateInputsGenerateOutputs(\n ctx, &inputs, &seq_len, &log_prob, &decoded_indices,\n &decoded_values, &decoded_shape));\n\n const TensorShape& inputs_shape = inputs->shape();\n\n std::vector::UnalignedConstMatrix> input_list_t;\n const int64 max_time = inputs_shape.dim_size(0);\n const int64 batch_size = inputs_shape.dim_size(1);\n const int64 num_classes_raw = inputs_shape.dim_size(2);\n OP_REQUIRES(\n ctx, FastBoundsCheck(num_classes_raw, std::numeric_limits::max()),\n errors::InvalidArgument(\"num_classes cannot exceed max int\"));\n const int num_classes = static_cast(num_classes_raw);\n\n auto inputs_t = inputs->tensor();\n\n input_list_t.reserve(max_time);\n for (std::size_t t = 0; t < max_time; ++t) {\n input_list_t.emplace_back(inputs_t.data() + t * batch_size * num_classes,\n batch_size, num_classes);\n }\n auto seq_len_t = seq_len->vec();\n auto log_prob_t = log_prob->matrix();\n\n log_prob_t.setZero();\n\n // Assumption: the blank index is num_classes - 1\n int blank_index = num_classes - 1;\n\n // Perform best path decoding\n std::vector > > sequences(batch_size);\n auto decode = [&](const int64 begin, const int64 end) {\n for (int b = begin; b < end; ++b) {\n sequences[b].resize(1);\n auto &sequence = sequences[b][0];\n int prev_indices = -1;\n for (int t = 0; t < seq_len_t(b); ++t) {\n int max_class_indices;\n log_prob_t(b, 0) +=\n -RowMax(input_list_t[t], b, &max_class_indices);\n if (max_class_indices != blank_index &&\n !(merge_repeated_ && max_class_indices == prev_indices)) {\n sequence.push_back(max_class_indices);\n }\n prev_indices = max_class_indices;\n }\n }\n };\n\n const int64 kCostPerUnit = 50 * max_time * num_classes;\n const int64 total = batch_size;\n const DeviceBase::CpuWorkerThreads& worker_threads =\n *ctx->device()->tensorflow_cpu_worker_threads();\n Shard(worker_threads.num_threads, worker_threads.workers, total,\n kCostPerUnit, decode);\n\n OP_REQUIRES_OK(\n ctx, decode_helper_.StoreAllDecodedSequences(\n sequences, &decoded_indices, &decoded_values, &decoded_shape));\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617', 'CWE-703'], 'message': 'Fix `tf.raw_ops.CTCGreedyDecoder` CHECK failure.\n\nPiperOrigin-RevId: 369960465\nChange-Id: If0b8b3264d5a47a24ac0970ed7b81ce6b4921fae'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int decode_pulses(Pulse *pulse, GetBitContext *gb,\n const uint16_t *swb_offset, int num_swb)\n{\n int i, pulse_swb;\n pulse->num_pulse = get_bits(gb, 2) + 1;\n pulse_swb = get_bits(gb, 6);\n if (pulse_swb >= num_swb)\n return -1;\n pulse->pos[0] = swb_offset[pulse_swb];\n pulse->pos[0] += get_bits(gb, 5);\n if (pulse->pos[0] > 1023)\n return -1;\n pulse->amp[0] = get_bits(gb, 4);\n for (i = 1; i < pulse->num_pulse; i++) {\n pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];\n if (pulse->pos[i] > 1023)\n return -1;\n pulse->amp[i] = get_bits(gb, 4);\n }\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'avcodec/aacdec: Fix pulse position checks in decode_pulses()\n\nFixes out of array read\nFixes: asan_static-oob_1efed25_1887_cov_2013541199_HeyYa_RA10_AAC_192K_30s.rm\nFound-by: Mateusz \"j00ru\" Jurczyk and Gynvael Coldwind\nSigned-off-by: Michael Niedermayer '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: enum ImapAuthRes imap_auth_gss(struct ImapData *idata, const char *method)\n{\n gss_buffer_desc request_buf, send_token;\n gss_buffer_t sec_token;\n gss_name_t target_name;\n gss_ctx_id_t context;\n gss_OID mech_name;\n char server_conf_flags;\n gss_qop_t quality;\n int cflags;\n OM_uint32 maj_stat, min_stat;\n char buf1[GSS_BUFSIZE], buf2[GSS_BUFSIZE];\n unsigned long buf_size;\n int rc;\n\n if (!mutt_bit_isset(idata->capabilities, AGSSAPI))\n return IMAP_AUTH_UNAVAIL;\n\n if (mutt_account_getuser(&idata->conn->account) < 0)\n return IMAP_AUTH_FAILURE;\n\n /* get an IMAP service ticket for the server */\n snprintf(buf1, sizeof(buf1), \"imap@%s\", idata->conn->account.host);\n request_buf.value = buf1;\n request_buf.length = strlen(buf1);\n maj_stat = gss_import_name(&min_stat, &request_buf, gss_nt_service_name, &target_name);\n if (maj_stat != GSS_S_COMPLETE)\n {\n mutt_debug(2, \"Couldn't get service name for [%s]\\n\", buf1);\n return IMAP_AUTH_UNAVAIL;\n }\n else if (DebugLevel >= 2)\n {\n gss_display_name(&min_stat, target_name, &request_buf, &mech_name);\n mutt_debug(2, \"Using service name [%s]\\n\", (char *) request_buf.value);\n gss_release_buffer(&min_stat, &request_buf);\n }\n /* Acquire initial credentials - without a TGT GSSAPI is UNAVAIL */\n sec_token = GSS_C_NO_BUFFER;\n context = GSS_C_NO_CONTEXT;\n\n /* build token */\n maj_stat = gss_init_sec_context(&min_stat, GSS_C_NO_CREDENTIAL, &context, target_name,\n GSS_C_NO_OID, GSS_C_MUTUAL_FLAG | GSS_C_SEQUENCE_FLAG,\n 0, GSS_C_NO_CHANNEL_BINDINGS, sec_token, NULL,\n &send_token, (unsigned int *) &cflags, NULL);\n if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)\n {\n print_gss_error(maj_stat, min_stat);\n mutt_debug(1, \"Error acquiring credentials - no TGT?\\n\");\n gss_release_name(&min_stat, &target_name);\n\n return IMAP_AUTH_UNAVAIL;\n }\n\n /* now begin login */\n mutt_message(_(\"Authenticating (GSSAPI)...\"));\n\n imap_cmd_start(idata, \"AUTHENTICATE GSSAPI\");\n\n /* expect a null continuation response (\"+\") */\n do\n rc = imap_cmd_step(idata);\n while (rc == IMAP_CMD_CONTINUE);\n\n if (rc != IMAP_CMD_RESPOND)\n {\n mutt_debug(2, \"Invalid response from server: %s\\n\", buf1);\n gss_release_name(&min_stat, &target_name);\n goto bail;\n }\n\n /* now start the security context initialisation loop... */\n mutt_debug(2, \"Sending credentials\\n\");\n mutt_b64_encode(buf1, send_token.value, send_token.length, sizeof(buf1) - 2);\n gss_release_buffer(&min_stat, &send_token);\n mutt_str_strcat(buf1, sizeof(buf1), \"\\r\\n\");\n mutt_socket_send(idata->conn, buf1);\n\n while (maj_stat == GSS_S_CONTINUE_NEEDED)\n {\n /* Read server data */\n do\n rc = imap_cmd_step(idata);\n while (rc == IMAP_CMD_CONTINUE);\n\n if (rc != IMAP_CMD_RESPOND)\n {\n mutt_debug(1, \"#1 Error receiving server response.\\n\");\n gss_release_name(&min_stat, &target_name);\n goto bail;\n }\n\n request_buf.length = mutt_b64_decode(buf2, idata->buf + 2);\n request_buf.value = buf2;\n sec_token = &request_buf;\n\n /* Write client data */\n maj_stat = gss_init_sec_context(\n &min_stat, GSS_C_NO_CREDENTIAL, &context, target_name, GSS_C_NO_OID,\n GSS_C_MUTUAL_FLAG | GSS_C_SEQUENCE_FLAG, 0, GSS_C_NO_CHANNEL_BINDINGS,\n sec_token, NULL, &send_token, (unsigned int *) &cflags, NULL);\n if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)\n {\n print_gss_error(maj_stat, min_stat);\n mutt_debug(1, \"Error exchanging credentials\\n\");\n gss_release_name(&min_stat, &target_name);\n\n goto err_abort_cmd;\n }\n mutt_b64_encode(buf1, send_token.value, send_token.length, sizeof(buf1) - 2);\n gss_release_buffer(&min_stat, &send_token);\n mutt_str_strcat(buf1, sizeof(buf1), \"\\r\\n\");\n mutt_socket_send(idata->conn, buf1);\n }\n\n gss_release_name(&min_stat, &target_name);\n\n /* get security flags and buffer size */\n do\n rc = imap_cmd_step(idata);\n while (rc == IMAP_CMD_CONTINUE);\n\n if (rc != IMAP_CMD_RESPOND)\n {\n mutt_debug(1, \"#2 Error receiving server response.\\n\");\n goto bail;\n }\n request_buf.length = mutt_b64_decode(buf2, idata->buf + 2);\n request_buf.value = buf2;\n\n maj_stat = gss_unwrap(&min_stat, context, &request_buf, &send_token, &cflags, &quality);\n if (maj_stat != GSS_S_COMPLETE)\n {\n print_gss_error(maj_stat, min_stat);\n mutt_debug(2, \"Couldn't unwrap security level data\\n\");\n gss_release_buffer(&min_stat, &send_token);\n goto err_abort_cmd;\n }\n mutt_debug(2, \"Credential exchange complete\\n\");\n\n /* first octet is security levels supported. We want NONE */\n server_conf_flags = ((char *) send_token.value)[0];\n if (!(((char *) send_token.value)[0] & GSS_AUTH_P_NONE))\n {\n mutt_debug(2, \"Server requires integrity or privacy\\n\");\n gss_release_buffer(&min_stat, &send_token);\n goto err_abort_cmd;\n }\n\n /* we don't care about buffer size if we don't wrap content. But here it is */\n ((char *) send_token.value)[0] = '\\0';\n buf_size = ntohl(*((long *) send_token.value));\n gss_release_buffer(&min_stat, &send_token);\n mutt_debug(2, \"Unwrapped security level flags: %c%c%c\\n\",\n (server_conf_flags & GSS_AUTH_P_NONE) ? 'N' : '-',\n (server_conf_flags & GSS_AUTH_P_INTEGRITY) ? 'I' : '-',\n (server_conf_flags & GSS_AUTH_P_PRIVACY) ? 'P' : '-');\n mutt_debug(2, \"Maximum GSS token size is %ld\\n\", buf_size);\n\n /* agree to terms (hack!) */\n buf_size = htonl(buf_size); /* not relevant without integrity/privacy */\n memcpy(buf1, &buf_size, 4);\n buf1[0] = GSS_AUTH_P_NONE;\n /* server decides if principal can log in as user */\n strncpy(buf1 + 4, idata->conn->account.user, sizeof(buf1) - 4);\n request_buf.value = buf1;\n request_buf.length = 4 + strlen(idata->conn->account.user);\n maj_stat = gss_wrap(&min_stat, context, 0, GSS_C_QOP_DEFAULT, &request_buf,\n &cflags, &send_token);\n if (maj_stat != GSS_S_COMPLETE)\n {\n mutt_debug(2, \"Error creating login request\\n\");\n goto err_abort_cmd;\n }\n\n mutt_b64_encode(buf1, send_token.value, send_token.length, sizeof(buf1) - 2);\n mutt_debug(2, \"Requesting authorisation as %s\\n\", idata->conn->account.user);\n mutt_str_strcat(buf1, sizeof(buf1), \"\\r\\n\");\n mutt_socket_send(idata->conn, buf1);\n\n /* Joy of victory or agony of defeat? */\n do\n rc = imap_cmd_step(idata);\n while (rc == IMAP_CMD_CONTINUE);\n if (rc == IMAP_CMD_RESPOND)\n {\n mutt_debug(1, \"Unexpected server continuation request.\\n\");\n goto err_abort_cmd;\n }\n if (imap_code(idata->buf))\n {\n /* flush the security context */\n mutt_debug(2, \"Releasing GSS credentials\\n\");\n maj_stat = gss_delete_sec_context(&min_stat, &context, &send_token);\n if (maj_stat != GSS_S_COMPLETE)\n mutt_debug(1, \"Error releasing credentials\\n\");\n\n /* send_token may contain a notification to the server to flush\n * credentials. RFC1731 doesn't specify what to do, and since this\n * support is only for authentication, we'll assume the server knows\n * enough to flush its own credentials */\n gss_release_buffer(&min_stat, &send_token);\n\n return IMAP_AUTH_SUCCESS;\n }\n else\n goto bail;\n\nerr_abort_cmd:\n mutt_socket_send(idata->conn, \"*\\r\\n\");\n do\n rc = imap_cmd_step(idata);\n while (rc == IMAP_CMD_CONTINUE);\n\nbail:\n mutt_error(_(\"GSSAPI authentication failed.\"));\n return IMAP_AUTH_FAILURE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120', 'CWE-119', 'CWE-787'], 'message': 'Check outbuf length in mutt_to_base64()\n\nThe obuf can be overflowed in auth_cram.c, and possibly auth_gss.c.\n\nThanks to Jeriko One for the bug report.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: AppProto AppLayerProtoDetectGetProto(AppLayerProtoDetectThreadCtx *tctx,\n Flow *f,\n uint8_t *buf, uint32_t buflen,\n uint8_t ipproto, uint8_t direction)\n{\n SCEnter();\n SCLogDebug(\"buflen %u for %s direction\", buflen,\n (direction & STREAM_TOSERVER) ? \"toserver\" : \"toclient\");\n\n AppProto alproto = ALPROTO_UNKNOWN;\n\n if (!FLOW_IS_PM_DONE(f, direction)) {\n AppProto pm_results[ALPROTO_MAX];\n uint16_t pm_matches = AppLayerProtoDetectPMGetProto(tctx, f,\n buf, buflen,\n direction,\n ipproto,\n pm_results);\n if (pm_matches > 0) {\n alproto = pm_results[0];\n goto end;\n }\n }\n\n if (!FLOW_IS_PP_DONE(f, direction)) {\n alproto = AppLayerProtoDetectPPGetProto(f, buf, buflen,\n ipproto, direction);\n if (alproto != ALPROTO_UNKNOWN)\n goto end;\n }\n\n /* Look if flow can be found in expectation list */\n if (!FLOW_IS_PE_DONE(f, direction)) {\n alproto = AppLayerProtoDetectPEGetProto(f, ipproto, direction);\n }\n\n end:\n SCReturnUInt(alproto);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'proto/detect: workaround dns misdetected as dcerpc\n\nThe DCERPC UDP detection would misfire on DNS with transaction\nID 0x0400. This would happen as the protocol detection engine\ngives preference to pattern based detection over probing parsers for\nperformance reasons.\n\nThis hack/workaround fixes this specific case by still running the\nprobing parser if DCERPC has been detected on UDP. The probing\nparser result will take precedence.\n\nBug #2736.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: read_packet(int fd, gss_buffer_t buf, int timeout, int first)\n{\n\tint\t ret;\n\n\tstatic uint32_t\t\tlen = 0;\n\tstatic char\t\tlen_buf[4];\n\tstatic int\t\tlen_buf_pos = 0;\n\tstatic char *\t\ttmpbuf = 0;\n\tstatic int\t\ttmpbuf_pos = 0;\n\n\tif (first) {\n\t\tlen_buf_pos = 0;\n\t\treturn -2;\n\t}\n\n\tif (len_buf_pos < 4) {\n\t\tret = timed_read(fd, &len_buf[len_buf_pos], 4 - len_buf_pos,\n\t\t timeout);\n\n\t\tif (ret == -1) {\n\t\t\tif (errno == EINTR || errno == EAGAIN)\n\t\t\t\treturn -2;\n\n\t\t\tLOG(LOG_ERR, (\"%s\", strerror(errno)));\n\t\t\treturn -1;\n\t\t}\n\n\t\tif (ret == 0) {\t\t/* EOF */\n\t\t\t/* Failure to read ANY length just means we're done */\n\t\t\tif (len_buf_pos == 0)\n\t\t\t\treturn 0;\n\n\t\t\t/*\n\t\t\t * Otherwise, we got EOF mid-length, and that's\n\t\t\t * a protocol error.\n\t\t\t */\n\t\t\tLOG(LOG_INFO, (\"EOF reading packet len\"));\n\t\t\treturn -1;\n\t\t}\n\n\t\tlen_buf_pos += ret;\n\t}\n\n\t/* Not done reading the length? */\n\tif (len_buf_pos != 4)\n\t\treturn -2;\n\n\t/* We have the complete length */\n\tlen = ntohl(*(uint32_t *)len_buf);\n\n\t/*\n\t * We make sure recvd length is reasonable, allowing for some\n\t * slop in enc overhead, beyond the actual maximum number of\n\t * bytes of decrypted payload.\n\t */\n\tif (len > GSTD_MAXPACKETCONTENTS + 512) {\n\t\tLOG(LOG_ERR, (\"ridiculous length, %ld\", len));\n\t\treturn -1;\n\t}\n\n\tif (!tmpbuf) {\n\t\tif ((tmpbuf = malloc(len)) == NULL) {\n\t\t\tLOG(LOG_CRIT, (\"malloc failure, %ld bytes\", len));\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tret = timed_read(fd, tmpbuf + tmpbuf_pos, len - tmpbuf_pos, timeout);\n\tif (ret == -1) {\n\t\tif (errno == EINTR || errno == EAGAIN)\n\t\t\treturn -2;\n\n\t\tLOG(LOG_ERR, (\"%s\", strerror(errno)));\n\t\treturn -1;\n\t}\n\n\tif (ret == 0) {\n\t\tLOG(LOG_ERR, (\"EOF while reading packet (len=%d)\", len));\n\t\treturn -1;\n\t}\n\n\ttmpbuf_pos += ret;\n\n\tif (tmpbuf_pos == len) {\n\t\tbuf->length = len;\n\t\tbuf->value = tmpbuf;\n\t\tlen = len_buf_pos = tmpbuf_pos = 0;\n\t\ttmpbuf = NULL;\n\n\t\tLOG(LOG_DEBUG, (\"read packet of length %d\", buf->length));\n\t\treturn 1;\n\t}\n\n\treturn -2;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'knc: fix a couple of memory leaks.\n\nOne of these can be remotely triggered during the authentication\nphase which leads to a remote DoS possibility.\n\nPointed out by: Imre Rad '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void l2cap_sock_close_cb(struct l2cap_chan *chan)\n{\n\tstruct sock *sk = chan->data;\n\n\tl2cap_sock_kill(sk);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Bluetooth: fix use-after-free error in lock_sock_nested()\n\nuse-after-free error in lock_sock_nested is reported:\n\n[ 179.140137][ T3731] =====================================================\n[ 179.142675][ T3731] BUG: KMSAN: use-after-free in lock_sock_nested+0x280/0x2c0\n[ 179.145494][ T3731] CPU: 4 PID: 3731 Comm: kworker/4:2 Not tainted 5.12.0-rc6+ #54\n[ 179.148432][ T3731] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.13.0-1ubuntu1.1 04/01/2014\n[ 179.151806][ T3731] Workqueue: events l2cap_chan_timeout\n[ 179.152730][ T3731] Call Trace:\n[ 179.153301][ T3731] dump_stack+0x24c/0x2e0\n[ 179.154063][ T3731] kmsan_report+0xfb/0x1e0\n[ 179.154855][ T3731] __msan_warning+0x5c/0xa0\n[ 179.155579][ T3731] lock_sock_nested+0x280/0x2c0\n[ 179.156436][ T3731] ? kmsan_get_metadata+0x116/0x180\n[ 179.157257][ T3731] l2cap_sock_teardown_cb+0xb8/0x890\n[ 179.158154][ T3731] ? __msan_metadata_ptr_for_load_8+0x10/0x20\n[ 179.159141][ T3731] ? kmsan_get_metadata+0x116/0x180\n[ 179.159994][ T3731] ? kmsan_get_shadow_origin_ptr+0x84/0xb0\n[ 179.160959][ T3731] ? l2cap_sock_recv_cb+0x420/0x420\n[ 179.161834][ T3731] l2cap_chan_del+0x3e1/0x1d50\n[ 179.162608][ T3731] ? kmsan_get_metadata+0x116/0x180\n[ 179.163435][ T3731] ? kmsan_get_shadow_origin_ptr+0x84/0xb0\n[ 179.164406][ T3731] l2cap_chan_close+0xeea/0x1050\n[ 179.165189][ T3731] ? kmsan_internal_unpoison_shadow+0x42/0x70\n[ 179.166180][ T3731] l2cap_chan_timeout+0x1da/0x590\n[ 179.167066][ T3731] ? __msan_metadata_ptr_for_load_8+0x10/0x20\n[ 179.168023][ T3731] ? l2cap_chan_create+0x560/0x560\n[ 179.168818][ T3731] process_one_work+0x121d/0x1ff0\n[ 179.169598][ T3731] worker_thread+0x121b/0x2370\n[ 179.170346][ T3731] kthread+0x4ef/0x610\n[ 179.171010][ T3731] ? process_one_work+0x1ff0/0x1ff0\n[ 179.171828][ T3731] ? kthread_blkcg+0x110/0x110\n[ 179.172587][ T3731] ret_from_fork+0x1f/0x30\n[ 179.173348][ T3731]\n[ 179.173752][ T3731] Uninit was created at:\n[ 179.174409][ T3731] kmsan_internal_poison_shadow+0x5c/0xf0\n[ 179.175373][ T3731] kmsan_slab_free+0x76/0xc0\n[ 179.176060][ T3731] kfree+0x3a5/0x1180\n[ 179.176664][ T3731] __sk_destruct+0x8af/0xb80\n[ 179.177375][ T3731] __sk_free+0x812/0x8c0\n[ 179.178032][ T3731] sk_free+0x97/0x130\n[ 179.178686][ T3731] l2cap_sock_release+0x3d5/0x4d0\n[ 179.179457][ T3731] sock_close+0x150/0x450\n[ 179.180117][ T3731] __fput+0x6bd/0xf00\n[ 179.180787][ T3731] ____fput+0x37/0x40\n[ 179.181481][ T3731] task_work_run+0x140/0x280\n[ 179.182219][ T3731] do_exit+0xe51/0x3e60\n[ 179.182930][ T3731] do_group_exit+0x20e/0x450\n[ 179.183656][ T3731] get_signal+0x2dfb/0x38f0\n[ 179.184344][ T3731] arch_do_signal_or_restart+0xaa/0xe10\n[ 179.185266][ T3731] exit_to_user_mode_prepare+0x2d2/0x560\n[ 179.186136][ T3731] syscall_exit_to_user_mode+0x35/0x60\n[ 179.186984][ T3731] do_syscall_64+0xc5/0x140\n[ 179.187681][ T3731] entry_SYSCALL_64_after_hwframe+0x44/0xae\n[ 179.188604][ T3731] =====================================================\n\nIn our case, there are two Thread A and B:\n\nContext: Thread A: Context: Thread B:\n\nl2cap_chan_timeout() __se_sys_shutdown()\n l2cap_chan_close() l2cap_sock_shutdown()\n l2cap_chan_del() l2cap_chan_close()\n l2cap_sock_teardown_cb() l2cap_sock_teardown_cb()\n\nOnce l2cap_sock_teardown_cb() excuted, this sock will be marked as SOCK_ZAPPED,\nand can be treated as killable in l2cap_sock_kill() if sock_orphan() has\nexcuted, at this time we close sock through sock_close() which end to call\nl2cap_sock_kill() like Thread C:\n\nContext: Thread C:\n\nsock_close()\n l2cap_sock_release()\n sock_orphan()\n l2cap_sock_kill() #free sock if refcnt is 1\n\nIf C completed, Once A or B reaches l2cap_sock_teardown_cb() again,\nuse-after-free happened.\n\nWe should set chan->data to NULL if sock is destructed, for telling teardown\noperation is not allowed in l2cap_sock_teardown_cb(), and also we should\navoid killing an already killed socket in l2cap_sock_close_cb().\n\nSigned-off-by: Wang ShaoBo \nSigned-off-by: Luiz Augusto von Dentz \nSigned-off-by: Marcel Holtmann '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int nr_recvmsg(struct kiocb *iocb, struct socket *sock,\n\t\t struct msghdr *msg, size_t size, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct sockaddr_ax25 *sax = (struct sockaddr_ax25 *)msg->msg_name;\n\tsize_t copied;\n\tstruct sk_buff *skb;\n\tint er;\n\n\t/*\n\t * This works for seqpacket too. The receiver has ordered the queue for\n\t * us! We do one quick check first though\n\t */\n\n\tlock_sock(sk);\n\tif (sk->sk_state != TCP_ESTABLISHED) {\n\t\trelease_sock(sk);\n\t\treturn -ENOTCONN;\n\t}\n\n\t/* Now we can treat all alike */\n\tif ((skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &er)) == NULL) {\n\t\trelease_sock(sk);\n\t\treturn er;\n\t}\n\n\tskb_reset_transport_header(skb);\n\tcopied = skb->len;\n\n\tif (copied > size) {\n\t\tcopied = size;\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t}\n\n\ter = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);\n\tif (er < 0) {\n\t\tskb_free_datagram(sk, skb);\n\t\trelease_sock(sk);\n\t\treturn er;\n\t}\n\n\tif (sax != NULL) {\n\t\tmemset(sax, 0, sizeof(sax));\n\t\tsax->sax25_family = AF_NETROM;\n\t\tskb_copy_from_linear_data_offset(skb, 7, sax->sax25_call.ax25_call,\n\t\t\t AX25_ADDR_LEN);\n\t}\n\n\tmsg->msg_namelen = sizeof(*sax);\n\n\tskb_free_datagram(sk, skb);\n\n\trelease_sock(sk);\n\treturn copied;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'netrom: fix invalid use of sizeof in nr_recvmsg()\n\nsizeof() when applied to a pointer typed expression gives the size of the\npointer, not that of the pointed data.\nIntroduced by commit 3ce5ef(netrom: fix info leak via msg_name in nr_recvmsg)\n\nSigned-off-by: Wei Yongjun \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: check_entry_size_and_hooks(struct ipt_entry *e,\n\t\t\t struct xt_table_info *newinfo,\n\t\t\t const unsigned char *base,\n\t\t\t const unsigned char *limit,\n\t\t\t const unsigned int *hook_entries,\n\t\t\t const unsigned int *underflows,\n\t\t\t unsigned int valid_hooks)\n{\n\tunsigned int h;\n\tint err;\n\n\tif ((unsigned long)e % __alignof__(struct ipt_entry) != 0 ||\n\t (unsigned char *)e + sizeof(struct ipt_entry) >= limit ||\n\t (unsigned char *)e + e->next_offset > limit) {\n\t\tduprintf(\"Bad offset %p\\n\", e);\n\t\treturn -EINVAL;\n\t}\n\n\tif (e->next_offset\n\t < sizeof(struct ipt_entry) + sizeof(struct xt_entry_target)) {\n\t\tduprintf(\"checking: element %p size %u\\n\",\n\t\t\t e, e->next_offset);\n\t\treturn -EINVAL;\n\t}\n\n\terr = check_entry(e);\n\tif (err)\n\t\treturn err;\n\n\t/* Check hooks & underflows */\n\tfor (h = 0; h < NF_INET_NUMHOOKS; h++) {\n\t\tif (!(valid_hooks & (1 << h)))\n\t\t\tcontinue;\n\t\tif ((unsigned char *)e - base == hook_entries[h])\n\t\t\tnewinfo->hook_entry[h] = hook_entries[h];\n\t\tif ((unsigned char *)e - base == underflows[h]) {\n\t\t\tif (!check_underflow(e)) {\n\t\t\t\tpr_err(\"Underflows must be unconditional and \"\n\t\t\t\t \"use the STANDARD target with \"\n\t\t\t\t \"ACCEPT/DROP\\n\");\n\t\t\t\treturn -EINVAL;\n\t\t\t}\n\t\t\tnewinfo->underflow[h] = underflows[h];\n\t\t}\n\t}\n\n\t/* Clear counters and comefrom */\n\te->counters = ((struct xt_counters) { 0, 0 });\n\te->comefrom = 0;\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'netfilter: x_tables: fix unconditional helper\n\nBen Hawkes says:\n\n In the mark_source_chains function (net/ipv4/netfilter/ip_tables.c) it\n is possible for a user-supplied ipt_entry structure to have a large\n next_offset field. This field is not bounds checked prior to writing a\n counter value at the supplied offset.\n\nProblem is that mark_source_chains should not have been called --\nthe rule doesn't have a next entry, so its supposed to return\nan absolute verdict of either ACCEPT or DROP.\n\nHowever, the function conditional() doesn't work as the name implies.\nIt only checks that the rule is using wildcard address matching.\n\nHowever, an unconditional rule must also not be using any matches\n(no -m args).\n\nThe underflow validator only checked the addresses, therefore\npassing the 'unconditional absolute verdict' test, while\nmark_source_chains also tested for presence of matches, and thus\nproceeeded to the next (not-existent) rule.\n\nUnify this so that all the callers have same idea of 'unconditional rule'.\n\nReported-by: Ben Hawkes \nSigned-off-by: Florian Westphal \nSigned-off-by: Pablo Neira Ayuso '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static bool check_underflow(const struct arpt_entry *e)\n{\n\tconst struct xt_entry_target *t;\n\tunsigned int verdict;\n\n\tif (!unconditional(&e->arp))\n\t\treturn false;\n\tt = arpt_get_target_c(e);\n\tif (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0)\n\t\treturn false;\n\tverdict = ((struct xt_standard_target *)t)->verdict;\n\tverdict = -verdict - 1;\n\treturn verdict == NF_DROP || verdict == NF_ACCEPT;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'netfilter: x_tables: fix unconditional helper\n\nBen Hawkes says:\n\n In the mark_source_chains function (net/ipv4/netfilter/ip_tables.c) it\n is possible for a user-supplied ipt_entry structure to have a large\n next_offset field. This field is not bounds checked prior to writing a\n counter value at the supplied offset.\n\nProblem is that mark_source_chains should not have been called --\nthe rule doesn't have a next entry, so its supposed to return\nan absolute verdict of either ACCEPT or DROP.\n\nHowever, the function conditional() doesn't work as the name implies.\nIt only checks that the rule is using wildcard address matching.\n\nHowever, an unconditional rule must also not be using any matches\n(no -m args).\n\nThe underflow validator only checked the addresses, therefore\npassing the 'unconditional absolute verdict' test, while\nmark_source_chains also tested for presence of matches, and thus\nproceeeded to the next (not-existent) rule.\n\nUnify this so that all the callers have same idea of 'unconditional rule'.\n\nReported-by: Ben Hawkes \nSigned-off-by: Florian Westphal \nSigned-off-by: Pablo Neira Ayuso '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 3);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* start = GetInput(context, node, kStartTensor);\n const TfLiteTensor* limit = GetInput(context, node, kLimitTensor);\n const TfLiteTensor* delta = GetInput(context, node, kDeltaTensor);\n // Make sure all the inputs are scalars.\n TF_LITE_ENSURE_EQ(context, NumDimensions(start), 0);\n TF_LITE_ENSURE_EQ(context, NumDimensions(limit), 0);\n TF_LITE_ENSURE_EQ(context, NumDimensions(delta), 0);\n\n // Currently only supports int32 and float.\n // TODO(b/117912892): Support quantization as well.\n const auto dtype = start->type;\n if (dtype != kTfLiteFloat32 && dtype != kTfLiteInt32) {\n context->ReportError(context, \"Unknown index output data type: %s\",\n TfLiteTypeGetName(dtype));\n return kTfLiteError;\n }\n\n TF_LITE_ENSURE_TYPES_EQ(context, limit->type, dtype);\n TF_LITE_ENSURE_TYPES_EQ(context, delta->type, dtype);\n\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n output->type = dtype;\n\n if (IsConstantTensor(start) && IsConstantTensor(limit) &&\n IsConstantTensor(delta)) {\n return ResizeOutput(context, start, limit, delta, output);\n }\n\n SetTensorToDynamic(output);\n return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus ReluEval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* input = GetInput(context, node, 0);\n TfLiteTensor* output = GetOutput(context, node, 0);\n const ReluOpData* data = reinterpret_cast(node->user_data);\n switch (input->type) {\n case kTfLiteFloat32: {\n optimized_ops::Relu(GetTensorShape(input), GetTensorData(input),\n GetTensorShape(output), GetTensorData(output));\n } break;\n // TODO(renjieliu): We may revisit the quantization calculation logic,\n // the unbounded upper limit is actually hard to quantize.\n case kTfLiteUInt8: {\n QuantizedReluX(0.0f, std::numeric_limits::infinity(),\n input, output, data);\n } break;\n case kTfLiteInt8: {\n QuantizedReluX(0.0f, std::numeric_limits::infinity(),\n input, output, data);\n } break;\n default:\n TF_LITE_KERNEL_LOG(\n context, \"Only float32 & int8/uint8 is supported currently, got %s.\",\n TfLiteTypeGetName(input->type));\n return kTfLiteError;\n }\n return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus PopulateQuantizedLstmParams8x8_8(\n TfLiteContext* context, TfLiteNode* node,\n lstm_eval::IntegerLstmParameter* integer_lstm_param) {\n // Get all tensors.\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n const TfLiteTensor* input_to_input_weights =\n GetOptionalInputTensor(context, node, kInputToInputWeightsTensor);\n const TfLiteTensor* input_to_forget_weights =\n GetInput(context, node, kInputToForgetWeightsTensor);\n const TfLiteTensor* input_to_cell_weights =\n GetInput(context, node, kInputToCellWeightsTensor);\n const TfLiteTensor* input_to_output_weights =\n GetInput(context, node, kInputToOutputWeightsTensor);\n\n const TfLiteTensor* recurrent_to_input_weights =\n GetOptionalInputTensor(context, node, kRecurrentToInputWeightsTensor);\n const TfLiteTensor* recurrent_to_forget_weights =\n GetInput(context, node, kRecurrentToForgetWeightsTensor);\n const TfLiteTensor* recurrent_to_cell_weights =\n GetInput(context, node, kRecurrentToCellWeightsTensor);\n const TfLiteTensor* recurrent_to_output_weights =\n GetInput(context, node, kRecurrentToOutputWeightsTensor);\n\n const TfLiteTensor* cell_to_input_weights =\n GetOptionalInputTensor(context, node, kCellToInputWeightsTensor);\n const TfLiteTensor* cell_to_forget_weights =\n GetOptionalInputTensor(context, node, kCellToForgetWeightsTensor);\n const TfLiteTensor* cell_to_output_weights =\n GetOptionalInputTensor(context, node, kCellToOutputWeightsTensor);\n\n const TfLiteTensor* input_layer_norm_coefficients =\n GetOptionalInputTensor(context, node, kInputLayerNormCoefficientsTensor);\n const TfLiteTensor* forget_layer_norm_coefficients =\n GetOptionalInputTensor(context, node, kForgetLayerNormCoefficientsTensor);\n const TfLiteTensor* cell_layer_norm_coefficients =\n GetOptionalInputTensor(context, node, kCellLayerNormCoefficientsTensor);\n const TfLiteTensor* output_layer_norm_coefficients =\n GetOptionalInputTensor(context, node, kOutputLayerNormCoefficientsTensor);\n\n const TfLiteTensor* input_gate_bias =\n GetOptionalInputTensor(context, node, kInputGateBiasTensor);\n const TfLiteTensor* forget_gate_bias =\n GetInput(context, node, kForgetGateBiasTensor);\n const TfLiteTensor* cell_gate_bias =\n GetInput(context, node, kCellGateBiasTensor);\n const TfLiteTensor* output_gate_bias =\n GetInput(context, node, kOutputGateBiasTensor);\n\n const TfLiteTensor* projection_weights =\n GetOptionalInputTensor(context, node, kProjectionWeightsTensor);\n const TfLiteTensor* projection_bias =\n GetOptionalInputTensor(context, node, kProjectionBiasTensor);\n\n TfLiteTensor* output_state =\n GetVariableInput(context, node, kOutputStateTensor);\n TF_LITE_ENSURE(context, output_state != nullptr);\n TfLiteTensor* cell_state = GetVariableInput(context, node, kCellStateTensor);\n TF_LITE_ENSURE(context, cell_state != nullptr);\n\n // Since we have already checked that weights are all there or none, we can\n // check the existence of only one to get the condition.\n const bool use_cifg = (input_to_input_weights == nullptr);\n const bool use_peephole = (cell_to_output_weights != nullptr);\n const bool is_layer_norm_lstm = (forget_layer_norm_coefficients != nullptr);\n const bool use_projection = (projection_weights != nullptr);\n\n // Weights and states.\n int8_t* input_to_input_weight_ptr = nullptr;\n int8_t* recurrent_to_input_weight_ptr = nullptr;\n int8_t* cell_to_input_weight_ptr = nullptr;\n int8_t* input_to_forget_weight_ptr = nullptr;\n int8_t* recurrent_to_forget_weight_ptr = nullptr;\n int8_t* cell_to_forget_weight_ptr = nullptr;\n int8_t* input_to_cell_weight_ptr = nullptr;\n int8_t* recurrent_to_cell_weight_ptr = nullptr;\n int8_t* input_to_output_weight_ptr = nullptr;\n int8_t* recurrent_to_output_weight_ptr = nullptr;\n int8_t* cell_to_output_weight_ptr = nullptr;\n int8_t* projection_weight_ptr = nullptr;\n int16_t* layer_norm_input_weight_ptr = nullptr;\n int16_t* layer_norm_forget_weight_ptr = nullptr;\n int16_t* layer_norm_cell_weight_ptr = nullptr;\n int16_t* layer_norm_output_weight_ptr = nullptr;\n int32_t* input_gate_bias_ptr = nullptr;\n int32_t* forget_gate_bias_ptr = nullptr;\n int32_t* cell_gate_bias_ptr = nullptr;\n int32_t* output_gate_bias_ptr = nullptr;\n int32_t* projection_bias_ptr = nullptr;\n int16_t* cell_ptr = nullptr;\n int8_t* output_state_ptr = nullptr;\n\n // Scales.\n const float default_scale = 1.0;\n float input_scale = default_scale;\n float input_to_input_weight_scale = default_scale;\n float recurrent_to_input_weight_scale = default_scale;\n float cell_to_input_weight_scale = default_scale;\n float input_to_forget_weight_scale = default_scale;\n float recurrent_to_forget_weight_scale = default_scale;\n float cell_to_forget_weight_scale = default_scale;\n float input_to_cell_weight_scale = default_scale;\n float recurrent_to_cell_weight_scale = default_scale;\n float input_to_output_weight_scale = default_scale;\n float recurrent_to_output_weight_scale = default_scale;\n float cell_to_output_weight_scale = default_scale;\n float projection_weight_scale = default_scale;\n float layer_norm_input_scale = default_scale;\n float layer_norm_forget_scale = default_scale;\n float layer_norm_cell_scale = default_scale;\n float layer_norm_output_scale = default_scale;\n float output_state_scale = default_scale;\n\n // Effective scales.\n float effective_input_to_input_scale = default_scale;\n float effective_recurrent_to_input_scale = default_scale;\n float effective_cell_to_input_scale = default_scale;\n float effective_input_to_forget_scale = default_scale;\n float effective_recurrent_to_forget_scale = default_scale;\n float effective_cell_to_forget_scale = default_scale;\n float effective_input_to_cell_scale = default_scale;\n float effective_recurrent_to_cell_scale = default_scale;\n float effective_input_to_output_scale = default_scale;\n float effective_recurrent_to_output_scale = default_scale;\n float effective_cell_to_output_scale = default_scale;\n float effective_proj_scale = default_scale;\n\n // Zero points\n int input_zp = 0;\n int output_state_zp = 0;\n\n // Populate all the values.\n if (!use_cifg) {\n input_to_input_weight_ptr = input_to_input_weights->data.int8;\n recurrent_to_input_weight_ptr = recurrent_to_input_weights->data.int8;\n input_gate_bias_ptr = input_gate_bias->data.i32;\n input_to_input_weight_scale = input_to_input_weights->params.scale;\n recurrent_to_input_weight_scale = recurrent_to_input_weights->params.scale;\n }\n\n if (use_peephole) {\n if (!use_cifg) {\n cell_to_input_weight_ptr = cell_to_input_weights->data.int8;\n cell_to_input_weight_scale = cell_to_input_weights->params.scale;\n }\n cell_to_forget_weight_ptr = cell_to_forget_weights->data.int8;\n cell_to_output_weight_ptr = cell_to_output_weights->data.int8;\n cell_to_forget_weight_scale = cell_to_forget_weights->params.scale;\n cell_to_output_weight_scale = cell_to_output_weights->params.scale;\n }\n\n if (is_layer_norm_lstm) {\n if (!use_cifg) {\n layer_norm_input_weight_ptr = input_layer_norm_coefficients->data.i16;\n layer_norm_input_scale = input_layer_norm_coefficients->params.scale;\n }\n layer_norm_forget_weight_ptr = forget_layer_norm_coefficients->data.i16;\n layer_norm_forget_scale = forget_layer_norm_coefficients->params.scale;\n layer_norm_cell_weight_ptr = cell_layer_norm_coefficients->data.i16;\n layer_norm_cell_scale = cell_layer_norm_coefficients->params.scale;\n layer_norm_output_weight_ptr = output_layer_norm_coefficients->data.i16;\n layer_norm_output_scale = output_layer_norm_coefficients->params.scale;\n }\n\n if (use_projection) {\n projection_weight_ptr = projection_weights->data.int8;\n projection_weight_scale = projection_weights->params.scale;\n if (projection_bias) {\n projection_bias_ptr = projection_bias->data.i32;\n }\n }\n output_state_scale = output_state->params.scale;\n\n input_to_forget_weight_ptr = input_to_forget_weights->data.int8;\n input_to_forget_weight_scale = input_to_forget_weights->params.scale;\n input_to_cell_weight_ptr = input_to_cell_weights->data.int8;\n input_to_cell_weight_scale = input_to_cell_weights->params.scale;\n input_to_output_weight_ptr = input_to_output_weights->data.int8;\n input_to_output_weight_scale = input_to_output_weights->params.scale;\n recurrent_to_forget_weight_ptr = recurrent_to_forget_weights->data.int8;\n recurrent_to_forget_weight_scale = recurrent_to_forget_weights->params.scale;\n recurrent_to_cell_weight_ptr = recurrent_to_cell_weights->data.int8;\n recurrent_to_cell_weight_scale = recurrent_to_cell_weights->params.scale;\n recurrent_to_output_weight_ptr = recurrent_to_output_weights->data.int8;\n recurrent_to_output_weight_scale = recurrent_to_output_weights->params.scale;\n forget_gate_bias_ptr = forget_gate_bias->data.i32;\n cell_gate_bias_ptr = cell_gate_bias->data.i32;\n output_gate_bias_ptr = output_gate_bias->data.i32;\n output_state_ptr = output_state->data.int8;\n cell_ptr = cell_state->data.i16;\n input_scale = input->params.scale;\n input_zp = input->params.zero_point;\n output_state_zp = output_state->params.zero_point;\n\n std::vector intermediate_scale;\n for (int i = 0; i < 12; ++i) {\n TfLiteTensor* intermediate =\n &context->tensors[node->intermediates->data[i]];\n auto* params = reinterpret_cast(\n intermediate->quantization.params);\n intermediate_scale.push_back(params->scale->data[0]);\n integer_lstm_param->intermediate_zp[i] = params->zero_point->data[0];\n }\n\n // Calculate effective scales.\n if (!use_cifg) {\n effective_input_to_input_scale =\n input_to_input_weight_scale * input_scale / intermediate_scale[1];\n effective_recurrent_to_input_scale = recurrent_to_input_weight_scale *\n output_state_scale /\n intermediate_scale[2];\n }\n effective_input_to_forget_scale =\n input_to_forget_weight_scale * input_scale / intermediate_scale[4];\n effective_recurrent_to_forget_scale = recurrent_to_forget_weight_scale *\n output_state_scale /\n intermediate_scale[5];\n\n effective_input_to_cell_scale =\n input_to_cell_weight_scale * input_scale / intermediate_scale[7];\n effective_recurrent_to_cell_scale = recurrent_to_cell_weight_scale *\n output_state_scale /\n intermediate_scale[8];\n\n effective_input_to_output_scale =\n input_to_output_weight_scale * input_scale / intermediate_scale[10];\n effective_recurrent_to_output_scale = recurrent_to_output_weight_scale *\n output_state_scale /\n intermediate_scale[11];\n effective_proj_scale =\n projection_weight_scale * std::pow(2, -15) / output_state_scale;\n\n if (use_peephole) {\n if (!use_cifg) {\n effective_cell_to_input_scale =\n std::pow(2, -15) * cell_to_input_weight_scale / intermediate_scale[0];\n }\n effective_cell_to_forget_scale =\n std::pow(2, -15) * cell_to_forget_weight_scale / intermediate_scale[3];\n effective_cell_to_output_scale =\n std::pow(2, -15) * cell_to_output_weight_scale / intermediate_scale[9];\n }\n\n // Calculate effecgive scales.\n QuantizeMultiplier(effective_input_to_input_scale,\n &integer_lstm_param->effective_input_to_input_scale_a,\n &integer_lstm_param->effective_input_to_input_scale_b);\n QuantizeMultiplier(effective_recurrent_to_input_scale,\n &integer_lstm_param->effective_recurrent_to_input_scale_a,\n &integer_lstm_param->effective_recurrent_to_input_scale_b);\n QuantizeMultiplier(effective_cell_to_input_scale,\n &integer_lstm_param->effective_cell_to_input_scale_a,\n &integer_lstm_param->effective_cell_to_input_scale_b);\n QuantizeMultiplier(effective_input_to_forget_scale,\n &integer_lstm_param->effective_input_to_forget_scale_a,\n &integer_lstm_param->effective_input_to_forget_scale_b);\n QuantizeMultiplier(\n effective_recurrent_to_forget_scale,\n &integer_lstm_param->effective_recurrent_to_forget_scale_a,\n &integer_lstm_param->effective_recurrent_to_forget_scale_b);\n QuantizeMultiplier(effective_cell_to_forget_scale,\n &integer_lstm_param->effective_cell_to_forget_scale_a,\n &integer_lstm_param->effective_cell_to_forget_scale_b);\n QuantizeMultiplier(effective_input_to_cell_scale,\n &integer_lstm_param->effective_input_to_cell_scale_a,\n &integer_lstm_param->effective_input_to_cell_scale_b);\n QuantizeMultiplier(effective_recurrent_to_cell_scale,\n &integer_lstm_param->effective_recurrent_to_cell_scale_a,\n &integer_lstm_param->effective_recurrent_to_cell_scale_b);\n QuantizeMultiplier(effective_input_to_output_scale,\n &integer_lstm_param->effective_input_to_output_scale_a,\n &integer_lstm_param->effective_input_to_output_scale_b);\n QuantizeMultiplier(\n effective_recurrent_to_output_scale,\n &integer_lstm_param->effective_recurrent_to_output_scale_a,\n &integer_lstm_param->effective_recurrent_to_output_scale_b);\n QuantizeMultiplier(effective_cell_to_output_scale,\n &integer_lstm_param->effective_cell_to_output_scale_a,\n &integer_lstm_param->effective_cell_to_output_scale_b);\n QuantizeMultiplier(effective_proj_scale,\n &integer_lstm_param->effective_proj_scale_a,\n &integer_lstm_param->effective_proj_scale_b);\n QuantizeMultiplier(layer_norm_input_scale,\n &integer_lstm_param->layer_norm_input_scale_a,\n &integer_lstm_param->layer_norm_input_scale_b);\n QuantizeMultiplier(layer_norm_forget_scale,\n &integer_lstm_param->layer_norm_forget_scale_a,\n &integer_lstm_param->layer_norm_forget_scale_b);\n QuantizeMultiplier(layer_norm_cell_scale,\n &integer_lstm_param->layer_norm_cell_scale_a,\n &integer_lstm_param->layer_norm_cell_scale_b);\n QuantizeMultiplier(layer_norm_output_scale,\n &integer_lstm_param->layer_norm_output_scale_a,\n &integer_lstm_param->layer_norm_output_scale_b);\n\n {\n // Intermdiates in flatbuffer holds Wx, Wh and Wx+Wh.\n // effective Wx, Wh is in effective_input/recurrent_to_<...>_scale\n // So use intermediate_scale to hold scale from Wx and Wh to Wx+Wh\n // 0: [1] -> [0]\n // 1: [2] -> [0]\n // and use intermdiate_zp as is.\n const float s_1_0 = intermediate_scale[1] / intermediate_scale[0];\n const float s_2_0 = intermediate_scale[2] / intermediate_scale[0];\n const float s_4_3 = intermediate_scale[4] / intermediate_scale[3];\n const float s_5_3 = intermediate_scale[5] / intermediate_scale[3];\n const float s_7_6 = intermediate_scale[7] / intermediate_scale[6];\n const float s_8_6 = intermediate_scale[8] / intermediate_scale[6];\n const float s_10_9 = intermediate_scale[10] / intermediate_scale[9];\n const float s_11_9 = intermediate_scale[11] / intermediate_scale[9];\n QuantizeMultiplier(s_1_0, &integer_lstm_param->intermediate_scale_a[0],\n &integer_lstm_param->intermediate_scale_b[0]);\n QuantizeMultiplier(s_2_0, &integer_lstm_param->intermediate_scale_a[1],\n &integer_lstm_param->intermediate_scale_b[1]);\n QuantizeMultiplier(s_4_3, &integer_lstm_param->intermediate_scale_a[2],\n &integer_lstm_param->intermediate_scale_b[2]);\n QuantizeMultiplier(s_5_3, &integer_lstm_param->intermediate_scale_a[3],\n &integer_lstm_param->intermediate_scale_b[3]);\n QuantizeMultiplier(s_7_6, &integer_lstm_param->intermediate_scale_a[4],\n &integer_lstm_param->intermediate_scale_b[4]);\n QuantizeMultiplier(s_8_6, &integer_lstm_param->intermediate_scale_a[5],\n &integer_lstm_param->intermediate_scale_b[5]);\n QuantizeMultiplier(s_10_9, &integer_lstm_param->intermediate_scale_a[6],\n &integer_lstm_param->intermediate_scale_b[6]);\n QuantizeMultiplier(s_11_9, &integer_lstm_param->intermediate_scale_a[7],\n &integer_lstm_param->intermediate_scale_b[7]);\n }\n\n // Calculate quantized clip for projection and cell.\n const auto* params = reinterpret_cast(node->builtin_data);\n const float cell_clip = params->cell_clip;\n const float proj_clip = params->proj_clip;\n\n const TfLiteTensor* output_tensor = GetOutput(context, node, kOutputTensor);\n\n auto* cell_state_params = reinterpret_cast(\n cell_state->quantization.params);\n auto* proj_params = reinterpret_cast(\n output_tensor->quantization.params);\n TF_LITE_ENSURE_EQ(context, cell_state_params->scale->data[0], 1.0 / 32768);\n if (cell_clip > 0.0 && cell_clip < 1.0) {\n integer_lstm_param->quantized_cell_clip = static_cast(std::min(\n std::max(cell_clip / cell_state_params->scale->data[0], -32768.0f),\n 32767.0f));\n } else {\n integer_lstm_param->quantized_cell_clip = 0;\n }\n if (proj_clip > 0.0) {\n integer_lstm_param->quantized_proj_clip = static_cast(std::min(\n std::max(proj_clip / proj_params->scale->data[0], -128.0f), 127.0f));\n } else {\n integer_lstm_param->quantized_proj_clip = 0;\n }\n return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n OpContext op_context(context, node);\n OpData* op_data = reinterpret_cast(node->user_data);\n const TfLiteTensor* lhs = GetInput(context, node, kInputLHSTensor);\n const TfLiteTensor* rhs = GetInput(context, node, kInputRHSTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n RuntimeShape orig_lhs_shape = GetTensorShape(lhs);\n RuntimeShape orig_rhs_shape = GetTensorShape(rhs);\n\n bool adj_y = op_context.params->adj_y;\n bool adj_x = op_context.params->adj_x;\n\n const TfLiteTensor* rhs_tensor = adj_y ? rhs : GetTempRhs(context, node, rhs);\n const TfLiteTensor* lhs_tensor = adj_x ? GetTempLhs(context, node, lhs) : lhs;\n if (!adj_y) {\n // TODO(b/154760341) Constant tensors should already be transposed, but\n // we transpose once if necessary for now.\n if (!(IsConstantTensor(rhs) && op_data->rhs_transposed)) {\n TransposeRowsColumns(context, rhs, GetTemporary(context, node, 1));\n op_data->rhs_transposed = true;\n }\n }\n if (adj_x) {\n TransposeRowsColumns(context, lhs, GetTemporary(context, node, 0));\n }\n RuntimeShape rhs_shape =\n adj_y ? orig_rhs_shape : SwapRowColumnDims(orig_rhs_shape);\n RuntimeShape lhs_shape =\n adj_x ? orig_lhs_shape : SwapRowColumnDims(orig_lhs_shape);\n\n switch (rhs->type) {\n case kTfLiteFloat32:\n // Note we pass RHS args first, LHS args second. See note above.\n if (kernel_type == kGenericOptimized) {\n optimized_ops::BatchMatMul(rhs_shape, GetTensorData(rhs_tensor),\n lhs_shape, GetTensorData(lhs_tensor),\n GetTensorShape(output),\n GetTensorData(output),\n CpuBackendContext::GetFromContext(context));\n } else {\n reference_ops::BatchMatMul(rhs_shape, GetTensorData(rhs_tensor),\n lhs_shape, GetTensorData(lhs_tensor),\n GetTensorShape(output),\n GetTensorData(output));\n }\n break;\n case kTfLiteInt8:\n EvalQuantized(context, node, op_data, lhs_shape, lhs_tensor,\n rhs_shape, rhs_tensor, output);\n break;\n default:\n TF_LITE_KERNEL_LOG(context,\n \"Currently BatchMatMul doesn't support type: %s\",\n TfLiteTypeGetName(lhs->type));\n return kTfLiteError;\n }\n return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus CheckLstmTensorDimensionsAndTypes(\n TfLiteContext* context, TfLiteNode* node, int n_input, int n_output,\n int n_cell, int input_to_input_weights_tensor,\n int input_to_forget_weights_tensor, int input_to_cell_weights_tensor,\n int input_to_output_weights_tensor, int recurrent_to_input_weights_tensor,\n int recurrent_to_forget_weights_tensor,\n int recurrent_to_cell_weights_tensor,\n int recurrent_to_output_weights_tensor, int cell_to_input_weights_tensor,\n int cell_to_forget_weights_tensor, int cell_to_output_weights_tensor,\n int input_gate_bias_tensor, int forget_gate_bias_tensor,\n int cell_gate_bias_tensor, int output_gate_bias_tensor,\n int projection_weights_tensor, int projection_bias_tensor) {\n const auto* params = reinterpret_cast(\n node->builtin_data);\n\n // Making sure clipping parameters have valid values.\n // == 0 means no clipping\n // > 0 means clipping\n TF_LITE_ENSURE(context, params->cell_clip >= 0);\n TF_LITE_ENSURE(context, params->proj_clip >= 0);\n\n const TfLiteTensor* input_to_forget_weights =\n GetInput(context, node, input_to_forget_weights_tensor);\n TF_LITE_ENSURE_EQ(context, input_to_forget_weights->dims->size, 2);\n TF_LITE_ENSURE_EQ(context, input_to_forget_weights->dims->data[0], n_cell);\n TF_LITE_ENSURE_EQ(context, input_to_forget_weights->dims->data[1], n_input);\n TF_LITE_ENSURE(context, (input_to_forget_weights->type == kTfLiteFloat32) ||\n (input_to_forget_weights->type == kTfLiteInt8) ||\n (input_to_forget_weights->type == kTfLiteUInt8));\n\n const TfLiteTensor* input_to_input_weights =\n GetOptionalInputTensor(context, node, input_to_input_weights_tensor);\n if (input_to_input_weights != nullptr) {\n TF_LITE_ENSURE_EQ(context, input_to_input_weights->dims->size, 2);\n TF_LITE_ENSURE_EQ(context, input_to_input_weights->dims->data[0], n_cell);\n TF_LITE_ENSURE_EQ(context, input_to_input_weights->dims->data[1], n_input);\n TF_LITE_ENSURE_TYPES_EQ(context, input_to_input_weights->type,\n input_to_forget_weights->type);\n }\n\n const TfLiteTensor* input_to_cell_weights =\n GetInput(context, node, input_to_cell_weights_tensor);\n TF_LITE_ENSURE_EQ(context, input_to_cell_weights->dims->size, 2);\n TF_LITE_ENSURE_EQ(context, input_to_cell_weights->dims->data[0], n_cell);\n TF_LITE_ENSURE_EQ(context, input_to_cell_weights->dims->data[1], n_input);\n TF_LITE_ENSURE_TYPES_EQ(context, input_to_cell_weights->type,\n input_to_forget_weights->type);\n\n const TfLiteTensor* input_to_output_weights =\n GetInput(context, node, input_to_output_weights_tensor);\n TF_LITE_ENSURE_EQ(context, input_to_output_weights->dims->size, 2);\n TF_LITE_ENSURE_EQ(context, input_to_output_weights->dims->data[0], n_cell);\n TF_LITE_ENSURE_EQ(context, input_to_output_weights->dims->data[1], n_input);\n TF_LITE_ENSURE_TYPES_EQ(context, input_to_output_weights->type,\n input_to_forget_weights->type);\n\n const TfLiteTensor* recurrent_to_input_weights =\n GetOptionalInputTensor(context, node, recurrent_to_input_weights_tensor);\n if (recurrent_to_input_weights != nullptr) {\n TF_LITE_ENSURE_EQ(context, recurrent_to_input_weights->dims->size, 2);\n TF_LITE_ENSURE_EQ(context, recurrent_to_input_weights->dims->data[0],\n n_cell);\n TF_LITE_ENSURE_EQ(context, recurrent_to_input_weights->dims->data[1],\n n_output);\n TF_LITE_ENSURE_TYPES_EQ(context, recurrent_to_input_weights->type,\n input_to_forget_weights->type);\n }\n\n const TfLiteTensor* recurrent_to_forget_weights =\n GetInput(context, node, recurrent_to_forget_weights_tensor);\n TF_LITE_ENSURE_EQ(context, recurrent_to_forget_weights->dims->size, 2);\n TF_LITE_ENSURE_EQ(context, recurrent_to_forget_weights->dims->data[0],\n n_cell);\n TF_LITE_ENSURE_EQ(context, recurrent_to_forget_weights->dims->data[1],\n n_output);\n TF_LITE_ENSURE_TYPES_EQ(context, recurrent_to_forget_weights->type,\n input_to_forget_weights->type);\n\n const TfLiteTensor* recurrent_to_cell_weights =\n GetInput(context, node, recurrent_to_cell_weights_tensor);\n TF_LITE_ENSURE_EQ(context, recurrent_to_cell_weights->dims->size, 2);\n TF_LITE_ENSURE_EQ(context, recurrent_to_cell_weights->dims->data[0], n_cell);\n TF_LITE_ENSURE_EQ(context, recurrent_to_cell_weights->dims->data[1],\n n_output);\n TF_LITE_ENSURE_TYPES_EQ(context, recurrent_to_cell_weights->type,\n input_to_forget_weights->type);\n\n // We make sure the input-gate's parameters are either both present (regular\n // LSTM) or not at all (CIFG-LSTM).\n const bool cifg_weights_all_or_none =\n ((input_to_input_weights != nullptr) &&\n (recurrent_to_input_weights != nullptr)) ||\n ((input_to_input_weights == nullptr) &&\n (recurrent_to_input_weights == nullptr));\n TF_LITE_ENSURE(context, cifg_weights_all_or_none == true);\n\n const TfLiteTensor* cell_to_input_weights =\n GetOptionalInputTensor(context, node, cell_to_input_weights_tensor);\n if (cell_to_input_weights != nullptr) {\n TF_LITE_ENSURE_EQ(context, cell_to_input_weights->dims->size, 1);\n TF_LITE_ENSURE_EQ(context, cell_to_input_weights->dims->data[0], n_cell);\n TF_LITE_ENSURE_TYPES_EQ(context, cell_to_input_weights->type,\n input_to_forget_weights->type);\n }\n\n const TfLiteTensor* cell_to_forget_weights =\n GetOptionalInputTensor(context, node, cell_to_forget_weights_tensor);\n if (cell_to_forget_weights != nullptr) {\n TF_LITE_ENSURE_EQ(context, cell_to_forget_weights->dims->size, 1);\n TF_LITE_ENSURE_EQ(context, cell_to_forget_weights->dims->data[0], n_cell);\n TF_LITE_ENSURE_TYPES_EQ(context, cell_to_forget_weights->type,\n input_to_forget_weights->type);\n }\n\n const TfLiteTensor* cell_to_output_weights =\n GetOptionalInputTensor(context, node, cell_to_output_weights_tensor);\n if (cell_to_output_weights != nullptr) {\n TF_LITE_ENSURE_EQ(context, cell_to_output_weights->dims->size, 1);\n TF_LITE_ENSURE_EQ(context, cell_to_output_weights->dims->data[0], n_cell);\n TF_LITE_ENSURE_TYPES_EQ(context, cell_to_output_weights->type,\n input_to_forget_weights->type);\n }\n\n // Making sure the peephole weights are there all or none.\n const bool use_cifg = (input_to_input_weights == nullptr);\n const bool peephole_weights_all_or_none =\n ((cell_to_input_weights != nullptr || use_cifg) &&\n (cell_to_forget_weights != nullptr) &&\n (cell_to_output_weights != nullptr)) ||\n ((cell_to_input_weights == nullptr) &&\n (cell_to_forget_weights == nullptr) &&\n (cell_to_output_weights == nullptr));\n TF_LITE_ENSURE(context, peephole_weights_all_or_none == true);\n\n // Make sure the input gate bias is present only when not a CIFG-LSTM.\n const TfLiteTensor* input_gate_bias =\n GetOptionalInputTensor(context, node, input_gate_bias_tensor);\n if (use_cifg) {\n TF_LITE_ENSURE_EQ(context, input_gate_bias, nullptr);\n } else {\n TF_LITE_ENSURE_EQ(context, input_gate_bias->dims->size, 1);\n TF_LITE_ENSURE_EQ(context, input_gate_bias->dims->data[0], n_cell);\n TF_LITE_ENSURE_TYPES_EQ(context, input_gate_bias->type, kTfLiteFloat32);\n }\n\n const TfLiteTensor* forget_gate_bias =\n GetInput(context, node, forget_gate_bias_tensor);\n TF_LITE_ENSURE_EQ(context, forget_gate_bias->dims->size, 1);\n TF_LITE_ENSURE_EQ(context, forget_gate_bias->dims->data[0], n_cell);\n TF_LITE_ENSURE_TYPES_EQ(context, forget_gate_bias->type, kTfLiteFloat32);\n\n const TfLiteTensor* cell_gate_bias =\n GetInput(context, node, cell_gate_bias_tensor);\n TF_LITE_ENSURE_EQ(context, cell_gate_bias->dims->size, 1);\n TF_LITE_ENSURE_EQ(context, cell_gate_bias->dims->data[0], n_cell);\n TF_LITE_ENSURE_EQ(context, cell_gate_bias->type, kTfLiteFloat32);\n\n const TfLiteTensor* output_gate_bias =\n GetInput(context, node, output_gate_bias_tensor);\n TF_LITE_ENSURE_EQ(context, output_gate_bias->dims->size, 1);\n TF_LITE_ENSURE_EQ(context, output_gate_bias->dims->data[0], n_cell);\n TF_LITE_ENSURE_TYPES_EQ(context, output_gate_bias->type, kTfLiteFloat32);\n\n const TfLiteTensor* projection_weights =\n GetOptionalInputTensor(context, node, projection_weights_tensor);\n if (projection_weights != nullptr) {\n TF_LITE_ENSURE_EQ(context, projection_weights->dims->size, 2);\n TF_LITE_ENSURE_EQ(context, projection_weights->dims->data[0], n_output);\n TF_LITE_ENSURE_EQ(context, projection_weights->dims->data[1], n_cell);\n TF_LITE_ENSURE_TYPES_EQ(context, projection_weights->type,\n input_to_forget_weights->type);\n }\n\n const TfLiteTensor* projection_bias =\n GetOptionalInputTensor(context, node, projection_bias_tensor);\n if (projection_bias != nullptr) {\n TF_LITE_ENSURE_EQ(context, projection_bias->dims->size, 1);\n TF_LITE_ENSURE_EQ(context, projection_bias->dims->data[0], n_output);\n TF_LITE_ENSURE_TYPES_EQ(context, projection_bias->type, kTfLiteFloat32);\n }\n\n // Making sure the projection tensors are consistent:\n // 1) If projection weight is not present, then projection bias should not be\n // present.\n // 2) If projection weight is present, then projection bias is optional.\n // TODO(ghodrat): make sure this is correct.\n const bool projecton_tensors_consistent =\n ((projection_weights != nullptr) || (projection_bias == nullptr));\n TF_LITE_ENSURE(context, projecton_tensors_consistent == true);\n\n return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus UseDynamicOutputTensors(TfLiteContext* context, TfLiteNode* node) {\n for (int i = 0; i < NumOutputs(node); ++i) {\n SetTensorToDynamic(GetOutput(context, node, i));\n }\n return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus EvalHybridPerChannel(TfLiteContext* context, TfLiteNode* node,\n TfLiteDepthwiseConvParams* params,\n OpData* data, const TfLiteTensor* input,\n const TfLiteTensor* filter,\n const TfLiteTensor* bias,\n TfLiteTensor* output) {\n float output_activation_min, output_activation_max;\n CalculateActivationRange(params->activation, &output_activation_min,\n &output_activation_max);\n const int input_size = NumElements(input) / SizeOfDimension(input, 0);\n const int batch_size = SizeOfDimension(input, 0);\n const TfLiteTensor* input_quantized =\n GetTemporary(context, node, data->input_quantized_index);\n int8_t* quantized_input_ptr_batch = input_quantized->data.int8;\n float* scaling_factors_ptr = GetTensorData(\n GetTemporary(context, node, data->scaling_factors_index));\n int32_t* input_offset_ptr = GetTensorData(\n GetTemporary(context, node, data->input_offset_index));\n\n for (int b = 0; b < batch_size; ++b) {\n const int offset = b * input_size;\n tensor_utils::AsymmetricQuantizeFloats(\n GetTensorData(input) + offset, input_size,\n quantized_input_ptr_batch + offset, &scaling_factors_ptr[b],\n &input_offset_ptr[b]);\n }\n\n DepthwiseParams op_params;\n op_params.padding_type = PaddingType::kSame;\n op_params.padding_values.width = data->padding.width;\n op_params.padding_values.height = data->padding.height;\n op_params.stride_width = params->stride_width;\n op_params.stride_height = params->stride_height;\n op_params.dilation_width_factor = params->dilation_width_factor;\n op_params.dilation_height_factor = params->dilation_height_factor;\n op_params.depth_multiplier = params->depth_multiplier;\n\n op_params.weights_offset = 0;\n op_params.float_activation_min = output_activation_min;\n op_params.float_activation_max = output_activation_max;\n const auto* affine_quantization =\n reinterpret_cast(filter->quantization.params);\n if (kernel_type == kReference) {\n reference_integer_ops::DepthwiseConvHybridPerChannel(\n op_params, scaling_factors_ptr, GetTensorShape(input),\n quantized_input_ptr_batch, GetTensorShape(filter),\n GetTensorData(filter), GetTensorShape(bias),\n GetTensorData(bias), GetTensorShape(output),\n GetTensorData(output), affine_quantization->scale->data,\n input_offset_ptr);\n } else {\n optimized_integer_ops::DepthwiseConvHybridPerChannel(\n op_params, scaling_factors_ptr, GetTensorShape(input),\n quantized_input_ptr_batch, GetTensorShape(filter),\n GetTensorData(filter), GetTensorShape(bias),\n GetTensorData(bias), GetTensorShape(output),\n GetTensorData(output), affine_quantization->scale->data,\n input_offset_ptr, CpuBackendContext::GetFromContext(context));\n }\n\n return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus PopulatePrecomputedZPTimesWeightsWithBias(TfLiteContext* context,\n OpData* op_data,\n TfLiteNode* node) {\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n const TfLiteTensor* output_state =\n GetVariableInput(context, node, kOutputStateTensor);\n TF_LITE_ENSURE(context, output_state != nullptr);\n\n const int32_t input_zero_point = -input->params.zero_point;\n const int32_t output_state_zero_point = -output_state->params.zero_point;\n\n const TfLiteTensor* input_to_input_weights =\n GetOptionalInputTensor(context, node, kInputToInputWeightsTensor);\n const TfLiteTensor* input_to_forget_weights =\n GetInput(context, node, kInputToForgetWeightsTensor);\n const TfLiteTensor* input_to_cell_weights =\n GetInput(context, node, kInputToCellWeightsTensor);\n const TfLiteTensor* input_to_output_weights =\n GetInput(context, node, kInputToOutputWeightsTensor);\n\n const TfLiteTensor* recurrent_to_input_weights =\n GetOptionalInputTensor(context, node, kRecurrentToInputWeightsTensor);\n const TfLiteTensor* recurrent_to_forget_weights =\n GetInput(context, node, kRecurrentToForgetWeightsTensor);\n const TfLiteTensor* recurrent_to_cell_weights =\n GetInput(context, node, kRecurrentToCellWeightsTensor);\n const TfLiteTensor* recurrent_to_output_weights =\n GetInput(context, node, kRecurrentToOutputWeightsTensor);\n\n const TfLiteTensor* projection_weights =\n GetOptionalInputTensor(context, node, kProjectionWeightsTensor);\n const TfLiteTensor* projection_bias =\n GetOptionalInputTensor(context, node, kProjectionBiasTensor);\n\n lstm_eval::IntegerLstmParameter* integer_lstm_params =\n &op_data->integer_lstm_param;\n\n const TfLiteTensor* intermediate =\n &context->tensors[node->intermediates->data[4]];\n const auto* params =\n static_cast(intermediate->quantization.params);\n const int32_t hidden_zp = params->zero_point->data[0];\n\n // Get bias and perform zero point calculation.\n // When there is layer normalization, the gate bias does not apply to matmul\n // directly:\n // y = ln(w * x + w * r + w * c) + b.\n const bool is_layer_norm = op_data->use_layer_norm;\n\n // Forget gate.\n const TfLiteTensor* forget_gate_bias =\n is_layer_norm ? nullptr : GetInput(context, node, kForgetGateBiasTensor);\n TF_LITE_ENSURE_OK(\n context,\n PrecomputeZeroPointTimesWeightWithBias(\n context, input_zero_point, input_to_forget_weights, forget_gate_bias,\n &(integer_lstm_params->input_to_forget_effective_bias)));\n\n TF_LITE_ENSURE_OK(\n context,\n PrecomputeZeroPointTimesWeightWithBias(\n context, output_state_zero_point, recurrent_to_forget_weights,\n nullptr, &(integer_lstm_params->recurrent_to_forget_effective_bias)));\n\n // Modulation gate.\n const TfLiteTensor* cell_gate_bias =\n is_layer_norm ? nullptr : GetInput(context, node, kCellGateBiasTensor);\n TF_LITE_ENSURE_OK(\n context,\n PrecomputeZeroPointTimesWeightWithBias(\n context, input_zero_point, input_to_cell_weights, cell_gate_bias,\n &(integer_lstm_params->input_to_cell_effective_bias)));\n TF_LITE_ENSURE_OK(\n context,\n PrecomputeZeroPointTimesWeightWithBias(\n context, output_state_zero_point, recurrent_to_cell_weights, nullptr,\n &(integer_lstm_params->recurrent_to_cell_effective_bias)));\n\n // Output gate.\n const TfLiteTensor* output_gate_bias =\n is_layer_norm ? nullptr : GetInput(context, node, kOutputGateBiasTensor);\n TF_LITE_ENSURE_OK(\n context,\n PrecomputeZeroPointTimesWeightWithBias(\n context, input_zero_point, input_to_output_weights, output_gate_bias,\n &(integer_lstm_params->input_to_output_effective_bias)));\n\n TF_LITE_ENSURE_OK(\n context,\n PrecomputeZeroPointTimesWeightWithBias(\n context, output_state_zero_point, recurrent_to_output_weights,\n nullptr, &(integer_lstm_params->recurrent_to_output_effective_bias)));\n\n // Input gate. The calculation is only meaningful for non-cifg case.\n const TfLiteTensor* input_gate_bias =\n is_layer_norm ? nullptr : GetInput(context, node, kInputGateBiasTensor);\n TF_LITE_ENSURE_OK(\n context,\n PrecomputeZeroPointTimesWeightWithBias(\n context, input_zero_point, input_to_input_weights, input_gate_bias,\n &(integer_lstm_params->input_to_input_effective_bias)));\n TF_LITE_ENSURE_OK(\n context,\n PrecomputeZeroPointTimesWeightWithBias(\n context, output_state_zero_point, recurrent_to_input_weights, nullptr,\n &(integer_lstm_params->recurrent_to_input_effective_bias)));\n\n // Projection bias. The calculation is only meaningful for with projection.\n TF_LITE_ENSURE_OK(context,\n PrecomputeZeroPointTimesWeightWithBias(\n context, hidden_zp, projection_weights, projection_bias,\n &(integer_lstm_params->projection_effective_bias)));\n return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n auto* params =\n reinterpret_cast(node->builtin_data);\n\n int32_t* out_buf = GetOutput(context, node, 0)->data.i32;\n const TfLiteTensor* hash = GetInput(context, node, 0);\n const TfLiteTensor* input = GetInput(context, node, 1);\n const TfLiteTensor* weight =\n NumInputs(node) == 2 ? nullptr : GetInput(context, node, 2);\n\n switch (params->type) {\n case kTfLiteLshProjectionDense:\n DenseLshProjection(hash, input, weight, out_buf);\n break;\n case kTfLiteLshProjectionSparse:\n SparseLshProjection(hash, input, weight, out_buf);\n break;\n default:\n return kTfLiteError;\n }\n\n return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n auto* params = reinterpret_cast(node->builtin_data);\n switch (params->out_type) {\n case kTfLiteInt32:\n output->type = kTfLiteInt32;\n break;\n case kTfLiteInt64:\n output->type = kTfLiteInt64;\n break;\n default:\n context->ReportError(context, \"Unknown shape output data type: %d\",\n params->out_type);\n return kTfLiteError;\n }\n\n // By design, the input shape is always known at the time of Prepare, even\n // if the preceding op that generates |input| is dynamic. Thus, we can\n // always compute the shape immediately, without waiting for Eval.\n SetTensorToPersistentRo(output);\n\n // Shape always produces a 1-dimensional output tensor, where each output\n // element is the length of the corresponding input tensor's dimension.\n TfLiteIntArray* output_size = TfLiteIntArrayCreate(1);\n output_size->data[0] = NumDimensions(input);\n TF_LITE_ENSURE_STATUS(context->ResizeTensor(context, output, output_size));\n\n TFLITE_DCHECK_EQ(NumDimensions(output), 1);\n TFLITE_DCHECK_EQ(SizeOfDimension(output, 0), NumDimensions(input));\n\n // Immediately propagate the known shape to the output tensor. This allows\n // downstream ops that rely on the value to use it during prepare.\n switch (output->type) {\n case kTfLiteInt32:\n ExtractShape(input, GetTensorData(output));\n break;\n case kTfLiteInt64:\n ExtractShape(input, GetTensorData(output));\n break;\n default:\n return kTfLiteError;\n }\n\n return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n const OpData* op_data = reinterpret_cast(node->user_data);\n\n TF_LITE_ENSURE(context, node->inputs->size > 0);\n\n // The first input is the condition.\n const TfLiteTensor* cond = GetInput(context, node, 0);\n // Currently only bool is supported.\n // TODO(ycling): Support other types since TensorFlow also support\n // non-bool types as condition.\n TF_LITE_ENSURE_EQ(context, cond->type, kTfLiteBool);\n TF_LITE_ENSURE_EQ(context, NumElements(cond), 1);\n\n // The first input of the node is the condition. The rest of inputs are\n // passed to the branch subgraphs. Therefore, the number of subgraph inputs\n // will be the number of node inputs - 1.\n int num_inputs = node->inputs->size - 1;\n int num_outputs = node->outputs->size;\n\n Subgraph* this_subgraph = reinterpret_cast(context->impl_);\n auto* subgraphs = this_subgraph->GetSubgraphs();\n TF_LITE_ENSURE(context, op_data->then_subgraph_index < subgraphs->size());\n TF_LITE_ENSURE(context, op_data->else_subgraph_index < subgraphs->size());\n\n Subgraph* then_subgraph = (*subgraphs)[op_data->then_subgraph_index].get();\n Subgraph* else_subgraph = (*subgraphs)[op_data->else_subgraph_index].get();\n\n for (auto* subgraph : {then_subgraph, else_subgraph}) {\n TF_LITE_ENSURE_EQ(context, num_inputs, subgraph->inputs().size());\n TF_LITE_ENSURE_EQ(context, num_outputs, subgraph->outputs().size());\n }\n\n bool has_dynamic_output_tensors = false;\n for (auto* subgraph : {then_subgraph, else_subgraph}) {\n for (int i = 0; i < num_inputs; ++i) {\n // The first input of the node is the condition. The indices of the inputs\n // passed to the subgraphs are offset by 1.\n const TfLiteTensor* input = GetInput(context, node, i + 1);\n std::vector dims(input->dims->data,\n input->dims->data + input->dims->size);\n subgraph->ResizeInputTensor(i, dims);\n TfLiteTensor* subgraph_input = subgraph->tensor(subgraph->inputs()[i]);\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, subgraph_input->type);\n }\n // Note: The `Prepare` function is responsible to run `AllocateTensors` on\n // both subgraphs. It's intentionally not to break out of the loop when\n // finding a dynamic output tensor.\n TF_LITE_ENSURE_OK(context, subgraph->AllocateTensors());\n has_dynamic_output_tensors |= subgraph->HasDynamicTensors();\n }\n\n if (!has_dynamic_output_tensors) {\n for (int i = 0; i < num_outputs; ++i) {\n TfLiteTensor* then_output =\n then_subgraph->tensor(then_subgraph->outputs()[i]);\n TfLiteTensor* else_output =\n else_subgraph->tensor(else_subgraph->outputs()[i]);\n // If the 2 subgraphs have static but different output shapes, the output\n // tensors of the IF op have dynamic sizes.\n if (!TfLiteIntArrayEqual(then_output->dims, else_output->dims)) {\n has_dynamic_output_tensors = true;\n break;\n }\n }\n }\n\n for (int i = 0; i < num_outputs; ++i) {\n TfLiteTensor* output = GetOutput(context, node, i);\n if (has_dynamic_output_tensors) {\n SetTensorToDynamic(output);\n } else {\n // When there's no dynamic output tensors, the 2 subgraph has exactly\n // the same static sized outputs.\n TfLiteTensor* then_output =\n then_subgraph->tensor(then_subgraph->outputs()[i]);\n TfLiteIntArray* output_size = TfLiteIntArrayCopy(then_output->dims);\n TF_LITE_ENSURE_OK(context,\n context->ResizeTensor(context, output, output_size));\n }\n }\n\n return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n OpData* data = reinterpret_cast(node->user_data);\n auto* params = reinterpret_cast(node->builtin_data);\n\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);\n const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n TF_LITE_ENSURE_TYPES_EQ(context, input1->type, input2->type);\n output->type = input2->type;\n\n data->requires_broadcast = !HaveSameShapes(input1, input2);\n\n TfLiteIntArray* output_size = nullptr;\n if (data->requires_broadcast) {\n TF_LITE_ENSURE_OK(context, CalculateShapeForBroadcast(\n context, input1, input2, &output_size));\n } else {\n output_size = TfLiteIntArrayCopy(input1->dims);\n }\n\n // 8bit -> 8bit general quantized path, with general rescalings\n // as well as, 16bit -> 16bit with general rescalings\n bool pot_scale_int16 = true;\n\n bool input1_scale_is_pot = false;\n bool input2_scale_is_pot = false;\n bool output_scale_is_pot = false;\n\n int input1_scale_log2_rounded{0};\n int input2_scale_log2_rounded{0};\n int output_scale_log2_rounded{0};\n\n if (input1->type == kTfLiteInt16 && input2->type == kTfLiteInt16 &&\n output->type == kTfLiteInt16) {\n // In case of 16-bit, there are two implementation:\n // the scale parameter is a general number\n // the scale parameter is POT and\n // zero_point is zero for inputs/output.\n pot_scale_int16 = (input1->params.zero_point == 0) &&\n (input2->params.zero_point == 0) &&\n (output->params.zero_point == 0);\n\n input1_scale_is_pot =\n CheckedLog2(input1->params.scale, &input1_scale_log2_rounded);\n\n input2_scale_is_pot =\n CheckedLog2(input2->params.scale, &input2_scale_log2_rounded);\n\n output_scale_is_pot =\n CheckedLog2(output->params.scale, &output_scale_log2_rounded);\n\n pot_scale_int16 &=\n input1_scale_is_pot && input2_scale_is_pot && output_scale_is_pot;\n }\n\n data->pot_scale_int16 = pot_scale_int16;\n\n if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8 ||\n !pot_scale_int16) {\n TF_LITE_ENSURE_OK(context, PrepareGeneralSubOp(context, input1, input2,\n output, params, data, -1));\n } else if (output->type == kTfLiteInt16) {\n // LSTM-special case with scale parameter of POT\n TF_LITE_ENSURE_OK(context, PrepareInt16SubOpPOT(context, input1, input2,\n output, params, data));\n }\n\n return context->ResizeTensor(context, output, output_size);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n OpData* op_data = reinterpret_cast(node->user_data);\n const int scratch_tensor_index = op_data->scratch_tensor_index;\n\n // Check we have all the inputs and outputs we need.\n bool is_layer_norm_lstm = false;\n if (node->inputs->size == 24) {\n const TfLiteTensor* forget_layer_norm_coefficients = GetOptionalInputTensor(\n context, node, lstm::full::kForgetLayerNormCoefficientsTensor);\n if (forget_layer_norm_coefficients == nullptr) {\n is_layer_norm_lstm = false;\n } else {\n is_layer_norm_lstm = true;\n }\n } else if (node->inputs->size == 20) {\n // This is deprecated and is only kept here for backward compatibility.\n is_layer_norm_lstm = false;\n } else {\n context->ReportError(\n context, \"The LSTM Full kernel expects 20 or 24 inputs. Got %d inputs\",\n node->inputs->size);\n return kTfLiteError;\n }\n TF_LITE_ENSURE_EQ(context, node->outputs->size, 1);\n op_data->is_layer_norm_lstm = is_layer_norm_lstm;\n\n // Inferring batch size, number of outputs and sequence length and\n // number of cells from the input tensors.\n const TfLiteTensor* input = GetInput(context, node, lstm::full::kInputTensor);\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, kTfLiteFloat32);\n TF_LITE_ENSURE(context, input->dims->size > 1);\n const auto* params =\n reinterpret_cast(\n node->builtin_data);\n const bool time_major = params->time_major;\n const int n_batch = time_major ? input->dims->data[1] : input->dims->data[0];\n const int n_input = input->dims->data[2];\n\n const TfLiteTensor* input_to_output_weights =\n GetInput(context, node, lstm::full::kInputToOutputWeightsTensor);\n const int n_cell = input_to_output_weights->dims->data[0];\n TF_LITE_ENSURE_EQ(context, input_to_output_weights->dims->size, 2);\n TF_LITE_ENSURE_EQ(context, input_to_output_weights->dims->data[1], n_input);\n\n const TfLiteTensor* recurrent_to_output_weights =\n GetInput(context, node, lstm::full::kRecurrentToOutputWeightsTensor);\n TF_LITE_ENSURE_EQ(context, recurrent_to_output_weights->dims->size, 2);\n TF_LITE_ENSURE_EQ(context, recurrent_to_output_weights->dims->data[0],\n n_cell);\n const int n_output = recurrent_to_output_weights->dims->data[1];\n\n // Check that input tensor dimensions matches with each other.\n TF_LITE_ENSURE_OK(context,\n CheckInputTensorDimensions(context, node, n_input, n_output,\n n_cell, is_layer_norm_lstm));\n\n // Get the pointer to output, output_state and cell_state buffer tensors.\n TfLiteTensor* output = GetOutput(context, node, lstm::full::kOutputTensor);\n\n TfLiteTensor* output_state =\n GetVariableInput(context, node, lstm::full::kOutputStateTensor);\n TF_LITE_ENSURE(context, output_state != nullptr);\n TfLiteTensor* cell_state =\n GetVariableInput(context, node, lstm::full::kCellStateTensor);\n TF_LITE_ENSURE(context, cell_state != nullptr);\n\n // Check the shape of input state tensors.\n // These tensor may be 1D or 2D. It's fine as long as the total size is\n // correct.\n TF_LITE_ENSURE_EQ(context, NumElements(output_state), n_batch * n_output);\n TF_LITE_ENSURE_EQ(context, NumElements(cell_state), n_batch * n_cell);\n\n // Resize the output tensors.\n TfLiteIntArray* output_size = TfLiteIntArrayCopy(input->dims);\n output_size->data[input->dims->size - 1] = n_output;\n TF_LITE_ENSURE_OK(context,\n context->ResizeTensor(context, output, output_size));\n\n TfLiteIntArrayFree(node->temporaries);\n if (IsHybridOp(input, input_to_output_weights)) {\n node->temporaries = TfLiteIntArrayCreate(kNumTemporaryTensors);\n } else {\n node->temporaries = TfLiteIntArrayCreate(1);\n }\n node->temporaries->data[kScratchBuffer] =\n scratch_tensor_index + kScratchBuffer;\n\n // Create a scratch buffer tensor.\n TfLiteTensor* scratch_buffer = GetTemporary(context, node, kScratchBuffer);\n scratch_buffer->type = input->type;\n scratch_buffer->allocation_type = kTfLiteArenaRw;\n\n const TfLiteTensor* input_to_input_weights = GetOptionalInputTensor(\n context, node, lstm::full::kInputToInputWeightsTensor);\n const bool use_cifg = (input_to_input_weights == nullptr);\n TfLiteIntArray* scratch_buffer_size = TfLiteIntArrayCreate(2);\n scratch_buffer_size->data[0] = n_batch;\n if (use_cifg) {\n // Reserving space for Cell, Forget, Output gates\n scratch_buffer_size->data[1] = n_cell * 3;\n } else {\n // Reserving space for Input, Cell, Forget, Output gates\n scratch_buffer_size->data[1] = n_cell * 4;\n }\n TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, scratch_buffer,\n scratch_buffer_size));\n\n if (IsHybridOp(input, input_to_output_weights)) {\n op_data->compute_row_sums = true;\n // Allocate temporary tensors to store quantized values of input,\n // output_state and cell_state tensors.\n node->temporaries->data[kInputQuantized] =\n scratch_tensor_index + kInputQuantized;\n TfLiteTensor* input_quantized =\n GetTemporary(context, node, kInputQuantized);\n input_quantized->type = input_to_output_weights->type;\n input_quantized->allocation_type = kTfLiteArenaRw;\n if (!TfLiteIntArrayEqual(input_quantized->dims, input->dims)) {\n TfLiteIntArray* input_quantized_size = TfLiteIntArrayCopy(input->dims);\n TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, input_quantized,\n input_quantized_size));\n }\n node->temporaries->data[kOutputStateQuantized] =\n scratch_tensor_index + kOutputStateQuantized;\n TfLiteTensor* output_state_quantized =\n GetTemporary(context, node, kOutputStateQuantized);\n output_state_quantized->type = input_to_output_weights->type;\n output_state_quantized->allocation_type = kTfLiteArenaRw;\n if (!TfLiteIntArrayEqual(output_state_quantized->dims,\n output_state->dims)) {\n TfLiteIntArray* output_state_quantized_size =\n TfLiteIntArrayCopy(output_state->dims);\n TF_LITE_ENSURE_OK(context,\n context->ResizeTensor(context, output_state_quantized,\n output_state_quantized_size));\n }\n node->temporaries->data[kCellStateQuantized] =\n scratch_tensor_index + kCellStateQuantized;\n TfLiteTensor* cell_state_quantized =\n GetTemporary(context, node, kCellStateQuantized);\n cell_state_quantized->type = input_to_output_weights->type;\n cell_state_quantized->allocation_type = kTfLiteArenaRw;\n if (!TfLiteIntArrayEqual(cell_state_quantized->dims, cell_state->dims)) {\n TfLiteIntArray* cell_state_quantized_size =\n TfLiteIntArrayCopy(cell_state->dims);\n TF_LITE_ENSURE_OK(context,\n context->ResizeTensor(context, cell_state_quantized,\n cell_state_quantized_size));\n }\n\n // Allocate temporary tensors to store scaling factors and product scaling\n // factors. The latter is a convenience storage which allows to quantize\n // a vector once (which produces the scaling factors) and multiply it with\n // different matrices (which requires multiplying the scaling factors with\n // the scaling factor of the matrix).\n node->temporaries->data[kInputScalingFactors] =\n op_data->scratch_tensor_index + kInputScalingFactors;\n TfLiteTensor* input_sf = GetTemporary(context, node, kInputScalingFactors);\n input_sf->type = kTfLiteFloat32;\n input_sf->allocation_type = kTfLiteArenaRw;\n int scaling_dims[1] = {n_batch};\n if (!TfLiteIntArrayEqualsArray(input_sf->dims, 1, scaling_dims)) {\n TfLiteIntArray* input_sf_size = TfLiteIntArrayCreate(1);\n input_sf_size->data[0] = n_batch;\n TF_LITE_ENSURE_OK(\n context, context->ResizeTensor(context, input_sf, input_sf_size));\n }\n node->temporaries->data[kOutputStateScalingFactors] =\n op_data->scratch_tensor_index + kOutputStateScalingFactors;\n TfLiteTensor* output_state_sf =\n GetTemporary(context, node, kOutputStateScalingFactors);\n output_state_sf->type = kTfLiteFloat32;\n output_state_sf->allocation_type = kTfLiteArenaRw;\n if (!TfLiteIntArrayEqualsArray(output_state_sf->dims, 1, scaling_dims)) {\n TfLiteIntArray* output_state_sf_size = TfLiteIntArrayCreate(1);\n output_state_sf_size->data[0] = n_batch;\n TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, output_state_sf,\n output_state_sf_size));\n }\n node->temporaries->data[kProductScalingFactors] =\n scratch_tensor_index + kProductScalingFactors;\n TfLiteTensor* prod_scaling_factors =\n GetTemporary(context, node, kProductScalingFactors);\n prod_scaling_factors->type = kTfLiteFloat32;\n prod_scaling_factors->allocation_type = kTfLiteArenaRw;\n if (!TfLiteIntArrayEqualsArray(prod_scaling_factors->dims, 1,\n scaling_dims)) {\n TfLiteIntArray* prod_scaling_factors_size = TfLiteIntArrayCreate(1);\n prod_scaling_factors_size->data[0] = n_batch;\n TF_LITE_ENSURE_OK(context,\n context->ResizeTensor(context, prod_scaling_factors,\n prod_scaling_factors_size));\n }\n\n // Allocate a temporary tensor to store the recovered cell weights. Since\n // this is used for diagonal matrices, only need to store n_cell values.\n node->temporaries->data[kRecoveredCellWeights] =\n scratch_tensor_index + kRecoveredCellWeights;\n TfLiteTensor* recovered_cell_weights =\n GetTemporary(context, node, kRecoveredCellWeights);\n recovered_cell_weights->type = kTfLiteFloat32;\n recovered_cell_weights->allocation_type = kTfLiteArenaRw;\n int recovered_cell_dims[1] = {n_cell};\n if (!TfLiteIntArrayEqualsArray(recovered_cell_weights->dims, 1,\n recovered_cell_dims)) {\n TfLiteIntArray* recovered_cell_weights_size = TfLiteIntArrayCreate(1);\n recovered_cell_weights_size->data[0] = n_cell;\n TF_LITE_ENSURE_OK(context,\n context->ResizeTensor(context, recovered_cell_weights,\n recovered_cell_weights_size));\n }\n\n // Allocate a temporary tensor to store the accumulated int32 values.\n node->temporaries->data[kAccumScratch] =\n scratch_tensor_index + kAccumScratch;\n TfLiteTensor* accum_scratch = GetTemporary(context, node, kAccumScratch);\n accum_scratch->type = kTfLiteInt32;\n accum_scratch->allocation_type = kTfLiteArenaRw;\n int accum_scratch_dims[2] = {n_cell, n_batch};\n if (!TfLiteIntArrayEqualsArray(accum_scratch->dims, 2,\n accum_scratch_dims)) {\n TfLiteIntArray* accum_size = TfLiteIntArrayCreate(2);\n accum_size->data[0] = n_cell;\n accum_size->data[1] = n_batch;\n TF_LITE_ENSURE_OK(\n context, context->ResizeTensor(context, accum_scratch, accum_size));\n }\n node->temporaries->data[kInputZeroPoints] =\n op_data->scratch_tensor_index + kInputZeroPoints;\n TfLiteTensor* input_zp = GetTemporary(context, node, kInputZeroPoints);\n input_zp->type = kTfLiteFloat32;\n input_zp->allocation_type = kTfLiteArenaRw;\n if (!TfLiteIntArrayEqualsArray(input_zp->dims, 1, scaling_dims)) {\n TfLiteIntArray* input_zp_size = TfLiteIntArrayCreate(1);\n input_zp_size->data[0] = n_batch;\n TF_LITE_ENSURE_OK(\n context, context->ResizeTensor(context, input_zp, input_zp_size));\n }\n node->temporaries->data[kOutputStateZeroPoints] =\n op_data->scratch_tensor_index + kOutputStateZeroPoints;\n TfLiteTensor* output_state_zp =\n GetTemporary(context, node, kOutputStateZeroPoints);\n output_state_zp->type = kTfLiteFloat32;\n output_state_zp->allocation_type = kTfLiteArenaRw;\n if (!TfLiteIntArrayEqualsArray(output_state_zp->dims, 1, scaling_dims)) {\n TfLiteIntArray* output_state_zp_size = TfLiteIntArrayCreate(1);\n output_state_zp_size->data[0] = n_batch;\n TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, output_state_zp,\n output_state_zp_size));\n }\n node->temporaries->data[kRowSums] = scratch_tensor_index + kRowSums;\n TfLiteTensor* row_sums = GetTemporary(context, node, kRowSums);\n row_sums->type = kTfLiteInt32;\n row_sums->allocation_type = kTfLiteArenaRwPersistent;\n int row_sums_rows = use_cifg ? 6 : 8;\n const TfLiteTensor* projection_weights = GetOptionalInputTensor(\n context, node, lstm::full::kProjectionWeightsTensor);\n if (projection_weights != nullptr) {\n row_sums_rows += ceil(static_cast(n_output) / n_cell);\n }\n int row_sums_dims[2] = {row_sums_rows, n_cell};\n if (!TfLiteIntArrayEqualsArray(row_sums->dims, 2, row_sums_dims)) {\n TfLiteIntArray* row_sums_size = TfLiteIntArrayCreate(2);\n row_sums_size->data[0] = row_sums_dims[0];\n row_sums_size->data[1] = row_sums_dims[1];\n TF_LITE_ENSURE_OK(\n context, context->ResizeTensor(context, row_sums, row_sums_size));\n }\n }\n return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n // Check we have all the inputs and outputs we need.\n TF_LITE_ENSURE_EQ(context, node->inputs->size, 5);\n TF_LITE_ENSURE_EQ(context, node->outputs->size, 1);\n\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n const TfLiteTensor* input_weights = GetInput(context, node, kWeightsTensor);\n const TfLiteTensor* recurrent_weights =\n GetInput(context, node, kRecurrentWeightsTensor);\n const TfLiteTensor* bias = GetInput(context, node, kBiasTensor);\n const TfLiteTensor* hidden_state =\n GetInput(context, node, kHiddenStateTensor);\n\n // Check all the parameters of tensor match within themselves and match the\n // input configuration.\n auto* params = reinterpret_cast(node->builtin_data);\n const bool time_major = params->time_major;\n const int batch_size =\n (time_major) ? input->dims->data[1] : input->dims->data[0];\n const int max_time =\n (time_major) ? input->dims->data[0] : input->dims->data[1];\n const int num_units = input_weights->dims->data[0];\n TF_LITE_ENSURE_EQ(context, input->dims->data[2],\n input_weights->dims->data[1]);\n TF_LITE_ENSURE_EQ(context, input_weights->dims->data[0], bias->dims->data[0]);\n TF_LITE_ENSURE_EQ(context, recurrent_weights->dims->data[0],\n bias->dims->data[0]);\n TF_LITE_ENSURE_EQ(context, recurrent_weights->dims->data[1],\n bias->dims->data[0]);\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, kTfLiteFloat32);\n TF_LITE_ENSURE_TYPES_EQ(context, input_weights->type,\n recurrent_weights->type);\n TF_LITE_ENSURE_EQ(context, NumDimensions(hidden_state), 2);\n TF_LITE_ENSURE_EQ(context, hidden_state->dims->data[0], batch_size);\n TF_LITE_ENSURE_EQ(context, hidden_state->dims->data[1], num_units);\n\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n // Resize output.\n TfLiteIntArray* output_size_array = TfLiteIntArrayCreate(3);\n output_size_array->data[0] = (time_major) ? max_time : batch_size;\n output_size_array->data[1] = (time_major) ? batch_size : max_time;\n output_size_array->data[2] = num_units;\n TF_LITE_ENSURE_OK(context,\n context->ResizeTensor(context, output, output_size_array));\n\n const bool is_hybrid = IsHybridOp(input, input_weights);\n\n // Allocate temporary tensors to store quantized values of input and\n // hidden_state tensors.\n if (is_hybrid) {\n auto* op_data = reinterpret_cast(node->user_data);\n op_data->compute_row_sums = true;\n TfLiteIntArrayFree(node->temporaries);\n node->temporaries = TfLiteIntArrayCreate(6);\n node->temporaries->data[0] = op_data->scratch_tensor_index;\n TfLiteTensor* input_quantized = GetTemporary(context, node, /*index=*/0);\n input_quantized->type = input_weights->type;\n input_quantized->allocation_type = kTfLiteArenaRw;\n if (!TfLiteIntArrayEqual(input_quantized->dims, input->dims)) {\n TfLiteIntArray* input_quantized_size = TfLiteIntArrayCopy(input->dims);\n TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, input_quantized,\n input_quantized_size));\n }\n node->temporaries->data[1] = op_data->scratch_tensor_index + 1;\n TfLiteTensor* hidden_state_quantized =\n GetTemporary(context, node, /*index=*/1);\n hidden_state_quantized->type = input_weights->type;\n hidden_state_quantized->allocation_type = kTfLiteArenaRw;\n if (!TfLiteIntArrayEqual(hidden_state_quantized->dims,\n hidden_state->dims)) {\n TfLiteIntArray* hidden_state_quantized_size =\n TfLiteIntArrayCopy(hidden_state->dims);\n TF_LITE_ENSURE_OK(context,\n context->ResizeTensor(context, hidden_state_quantized,\n hidden_state_quantized_size));\n }\n node->temporaries->data[2] = op_data->scratch_tensor_index + 2;\n TfLiteTensor* scaling_factors = GetTemporary(context, node, /*index=*/2);\n scaling_factors->type = kTfLiteFloat32;\n scaling_factors->allocation_type = kTfLiteArenaRw;\n int scaling_dims[1] = {batch_size};\n if (!TfLiteIntArrayEqualsArray(scaling_factors->dims, 1, scaling_dims)) {\n TfLiteIntArray* scaling_factors_size = TfLiteIntArrayCreate(1);\n scaling_factors_size->data[0] = batch_size;\n TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, scaling_factors,\n scaling_factors_size));\n }\n node->temporaries->data[3] = op_data->scratch_tensor_index + 3;\n TfLiteTensor* accum_scratch = GetTemporary(context, node, /*index=*/3);\n accum_scratch->type = kTfLiteInt32;\n accum_scratch->allocation_type = kTfLiteArenaRw;\n int accum_scratch_dims[2] = {num_units, batch_size};\n if (!TfLiteIntArrayEqualsArray(accum_scratch->dims, 2,\n accum_scratch_dims)) {\n TfLiteIntArray* accum_scratch_size = TfLiteIntArrayCreate(2);\n accum_scratch_size->data[0] = accum_scratch_dims[0];\n accum_scratch_size->data[1] = accum_scratch_dims[1];\n TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, accum_scratch,\n accum_scratch_size));\n }\n node->temporaries->data[4] = op_data->scratch_tensor_index + 4;\n TfLiteTensor* zero_points = GetTemporary(context, node, /*index=*/4);\n zero_points->type = kTfLiteInt32;\n zero_points->allocation_type = kTfLiteArenaRw;\n int zero_points_dims[1] = {batch_size};\n if (!TfLiteIntArrayEqualsArray(zero_points->dims, 1, zero_points_dims)) {\n TfLiteIntArray* zero_points_size = TfLiteIntArrayCreate(1);\n zero_points_size->data[0] = batch_size;\n TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, zero_points,\n zero_points_size));\n }\n node->temporaries->data[5] = op_data->scratch_tensor_index + 5;\n TfLiteTensor* row_sums = GetTemporary(context, node, /*index=*/5);\n row_sums->type = kTfLiteInt32;\n row_sums->allocation_type = kTfLiteArenaRwPersistent;\n int row_sums_dims[2] = {2, num_units};\n if (!TfLiteIntArrayEqualsArray(row_sums->dims, 2, row_sums_dims)) {\n TfLiteIntArray* row_sums_size = TfLiteIntArrayCreate(2);\n row_sums_size->data[0] = row_sums_dims[0];\n row_sums_size->data[1] = row_sums_dims[1];\n TF_LITE_ENSURE_OK(\n context, context->ResizeTensor(context, row_sums, row_sums_size));\n }\n }\n return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus CheckInputTensorDimensions(TfLiteContext* context,\n TfLiteNode* node, int n_input,\n int n_output, int n_cell,\n bool is_layer_norm_lstm) {\n const auto* params = reinterpret_cast(node->builtin_data);\n\n // Making sure clipping parameters have valid values.\n // == 0 means no clipping\n // > 0 means clipping\n TF_LITE_ENSURE(context, params->cell_clip >= 0);\n TF_LITE_ENSURE(context, params->proj_clip >= 0);\n\n const TfLiteTensor* input_to_input_weights = GetOptionalInputTensor(\n context, node, lstm::full::kInputToInputWeightsTensor);\n if (input_to_input_weights != nullptr) {\n TF_LITE_ENSURE_EQ(context, input_to_input_weights->dims->size, 2);\n TF_LITE_ENSURE_EQ(context, input_to_input_weights->dims->data[0], n_cell);\n TF_LITE_ENSURE_EQ(context, input_to_input_weights->dims->data[1], n_input);\n }\n\n const TfLiteTensor* input_to_forget_weights =\n GetInput(context, node, lstm::full::kInputToForgetWeightsTensor);\n TF_LITE_ENSURE_EQ(context, input_to_forget_weights->dims->size, 2);\n TF_LITE_ENSURE_EQ(context, input_to_forget_weights->dims->data[0], n_cell);\n TF_LITE_ENSURE_EQ(context, input_to_forget_weights->dims->data[1], n_input);\n\n const TfLiteTensor* input_to_cell_weights =\n GetInput(context, node, lstm::full::kInputToCellWeightsTensor);\n TF_LITE_ENSURE_EQ(context, input_to_cell_weights->dims->size, 2);\n TF_LITE_ENSURE_EQ(context, input_to_cell_weights->dims->data[0], n_cell);\n TF_LITE_ENSURE_EQ(context, input_to_cell_weights->dims->data[1], n_input);\n\n const TfLiteTensor* recurrent_to_input_weights = GetOptionalInputTensor(\n context, node, lstm::full::kRecurrentToInputWeightsTensor);\n if (recurrent_to_input_weights != nullptr) {\n TF_LITE_ENSURE_EQ(context, recurrent_to_input_weights->dims->size, 2);\n TF_LITE_ENSURE_EQ(context, recurrent_to_input_weights->dims->data[0],\n n_cell);\n TF_LITE_ENSURE_EQ(context, recurrent_to_input_weights->dims->data[1],\n n_output);\n }\n\n const TfLiteTensor* recurrent_to_forget_weights =\n GetInput(context, node, lstm::full::kRecurrentToForgetWeightsTensor);\n TF_LITE_ENSURE_EQ(context, recurrent_to_forget_weights->dims->size, 2);\n TF_LITE_ENSURE_EQ(context, recurrent_to_forget_weights->dims->data[0],\n n_cell);\n TF_LITE_ENSURE_EQ(context, recurrent_to_forget_weights->dims->data[1],\n n_output);\n\n const TfLiteTensor* recurrent_to_cell_weights =\n GetInput(context, node, lstm::full::kRecurrentToCellWeightsTensor);\n TF_LITE_ENSURE_EQ(context, recurrent_to_cell_weights->dims->size, 2);\n TF_LITE_ENSURE_EQ(context, recurrent_to_cell_weights->dims->data[0], n_cell);\n TF_LITE_ENSURE_EQ(context, recurrent_to_cell_weights->dims->data[1],\n n_output);\n\n // We make sure the input-gate's parameters are either both present (regular\n // LSTM) or not at all (CIFG-LSTM).\n const bool cifg_weights_all_or_none =\n ((input_to_input_weights != nullptr) &&\n (recurrent_to_input_weights != nullptr)) ||\n ((input_to_input_weights == nullptr) &&\n (recurrent_to_input_weights == nullptr));\n TF_LITE_ENSURE(context, cifg_weights_all_or_none == true);\n\n const TfLiteTensor* cell_to_input_weights = GetOptionalInputTensor(\n context, node, lstm::full::kCellToInputWeightsTensor);\n if (cell_to_input_weights != nullptr) {\n TF_LITE_ENSURE_EQ(context, cell_to_input_weights->dims->size, 1);\n TF_LITE_ENSURE_EQ(context, cell_to_input_weights->dims->data[0], n_cell);\n }\n\n const TfLiteTensor* cell_to_forget_weights = GetOptionalInputTensor(\n context, node, lstm::full::kCellToForgetWeightsTensor);\n if (cell_to_forget_weights != nullptr) {\n TF_LITE_ENSURE_EQ(context, cell_to_forget_weights->dims->size, 1);\n TF_LITE_ENSURE_EQ(context, cell_to_forget_weights->dims->data[0], n_cell);\n }\n\n const TfLiteTensor* cell_to_output_weights = GetOptionalInputTensor(\n context, node, lstm::full::kCellToOutputWeightsTensor);\n if (cell_to_output_weights != nullptr) {\n TF_LITE_ENSURE_EQ(context, cell_to_output_weights->dims->size, 1);\n TF_LITE_ENSURE_EQ(context, cell_to_output_weights->dims->data[0], n_cell);\n }\n\n // Making sure the peephole weights are there all or none.\n const bool use_cifg = (input_to_input_weights == nullptr);\n const bool peephole_weights_all_or_none =\n ((cell_to_input_weights != nullptr || use_cifg) &&\n (cell_to_forget_weights != nullptr) &&\n (cell_to_output_weights != nullptr)) ||\n ((cell_to_input_weights == nullptr) &&\n (cell_to_forget_weights == nullptr) &&\n (cell_to_output_weights == nullptr));\n TF_LITE_ENSURE(context, peephole_weights_all_or_none == true);\n\n // Make sure the input gate bias is present only when not a CIFG-LSTM.\n const TfLiteTensor* input_gate_bias =\n GetOptionalInputTensor(context, node, lstm::full::kInputGateBiasTensor);\n if (use_cifg) {\n TF_LITE_ENSURE_EQ(context, input_gate_bias, nullptr);\n } else {\n TF_LITE_ENSURE_EQ(context, input_gate_bias->dims->size, 1);\n TF_LITE_ENSURE_EQ(context, input_gate_bias->dims->data[0], n_cell);\n }\n\n const TfLiteTensor* forget_gate_bias =\n GetInput(context, node, lstm::full::kForgetGateBiasTensor);\n TF_LITE_ENSURE_EQ(context, forget_gate_bias->dims->size, 1);\n TF_LITE_ENSURE_EQ(context, forget_gate_bias->dims->data[0], n_cell);\n\n const TfLiteTensor* cell_gate_bias =\n GetInput(context, node, lstm::full::kCellGateBiasTensor);\n TF_LITE_ENSURE_EQ(context, cell_gate_bias->dims->size, 1);\n TF_LITE_ENSURE_EQ(context, cell_gate_bias->dims->data[0], n_cell);\n\n const TfLiteTensor* output_gate_bias =\n GetInput(context, node, lstm::full::kOutputGateBiasTensor);\n TF_LITE_ENSURE_EQ(context, output_gate_bias->dims->size, 1);\n TF_LITE_ENSURE_EQ(context, output_gate_bias->dims->data[0], n_cell);\n\n const TfLiteTensor* projection_weights = GetOptionalInputTensor(\n context, node, lstm::full::kProjectionWeightsTensor);\n if (projection_weights != nullptr) {\n TF_LITE_ENSURE_EQ(context, projection_weights->dims->size, 2);\n TF_LITE_ENSURE_EQ(context, projection_weights->dims->data[0], n_output);\n TF_LITE_ENSURE_EQ(context, projection_weights->dims->data[1], n_cell);\n }\n\n const TfLiteTensor* projection_bias =\n GetOptionalInputTensor(context, node, lstm::full::kProjectionBiasTensor);\n if (projection_bias != nullptr) {\n TF_LITE_ENSURE_EQ(context, projection_bias->dims->size, 1);\n TF_LITE_ENSURE_EQ(context, projection_bias->dims->data[0], n_output);\n }\n\n // Making sure the projection tensors are consistent:\n // 1) If projection weight is not present, then projection bias should not be\n // present.\n // 2) If projection weight is present, then projection bias is optional.\n // TODO(ghodrat): make sure this is correct.\n const bool projecton_tensors_consistent =\n ((projection_weights != nullptr) || (projection_bias == nullptr));\n TF_LITE_ENSURE(context, projecton_tensors_consistent == true);\n\n if (is_layer_norm_lstm) {\n const TfLiteTensor* input_layer_norm_coefficients = GetOptionalInputTensor(\n context, node, lstm::full::kInputLayerNormCoefficientsTensor);\n if (use_cifg) {\n TF_LITE_ENSURE_EQ(context, input_layer_norm_coefficients, nullptr);\n } else {\n TF_LITE_ENSURE(context, input_layer_norm_coefficients != nullptr);\n TF_LITE_ENSURE_EQ(context, input_layer_norm_coefficients->dims->size, 1);\n TF_LITE_ENSURE_EQ(context, input_layer_norm_coefficients->dims->data[0],\n n_cell);\n TF_LITE_ENSURE_TYPES_EQ(context, input_layer_norm_coefficients->type,\n kTfLiteFloat32);\n }\n\n const TfLiteTensor* forget_layer_norm_coefficients =\n GetInput(context, node, lstm::full::kForgetLayerNormCoefficientsTensor);\n TF_LITE_ENSURE(context, forget_layer_norm_coefficients != nullptr);\n TF_LITE_ENSURE_EQ(context, forget_layer_norm_coefficients->dims->size, 1);\n TF_LITE_ENSURE_EQ(context, forget_layer_norm_coefficients->dims->data[0],\n n_cell);\n TF_LITE_ENSURE_TYPES_EQ(context, forget_layer_norm_coefficients->type,\n kTfLiteFloat32);\n\n const TfLiteTensor* cell_layer_norm_coefficients =\n GetInput(context, node, lstm::full::kCellLayerNormCoefficientsTensor);\n TF_LITE_ENSURE(context, cell_layer_norm_coefficients != nullptr);\n TF_LITE_ENSURE_EQ(context, cell_layer_norm_coefficients->dims->size, 1);\n TF_LITE_ENSURE_EQ(context, cell_layer_norm_coefficients->dims->data[0],\n n_cell);\n TF_LITE_ENSURE_TYPES_EQ(context, cell_layer_norm_coefficients->type,\n kTfLiteFloat32);\n\n const TfLiteTensor* output_layer_norm_coefficients =\n GetInput(context, node, lstm::full::kOutputLayerNormCoefficientsTensor);\n TF_LITE_ENSURE(context, output_layer_norm_coefficients != nullptr);\n TF_LITE_ENSURE_EQ(context, output_layer_norm_coefficients->dims->size, 1);\n TF_LITE_ENSURE_EQ(context, output_layer_norm_coefficients->dims->data[0],\n n_cell);\n TF_LITE_ENSURE_TYPES_EQ(context, output_layer_norm_coefficients->type,\n kTfLiteFloat32);\n }\n\n return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n auto* params = reinterpret_cast(node->builtin_data);\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n const TfLiteTensor* input_weights = GetInput(context, node, kWeightsTensor);\n const TfLiteTensor* recurrent_weights =\n GetInput(context, node, kRecurrentWeightsTensor);\n const TfLiteTensor* bias = GetInput(context, node, kBiasTensor);\n // The hidden_state is a variable input tensor that can be modified.\n TfLiteTensor* hidden_state =\n const_cast(GetInput(context, node, kHiddenStateTensor));\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n switch (input_weights->type) {\n case kTfLiteFloat32:\n return EvalFloat(input, input_weights, recurrent_weights, bias, params,\n hidden_state, output);\n case kTfLiteUInt8:\n case kTfLiteInt8: {\n // TODO(mirkov): implement eval with quantized inputs as well.\n auto* op_data = reinterpret_cast(node->user_data);\n TfLiteTensor* input_quantized = GetTemporary(context, node, 0);\n TfLiteTensor* hidden_state_quantized = GetTemporary(context, node, 1);\n TfLiteTensor* scaling_factors = GetTemporary(context, node, 2);\n TfLiteTensor* accum_scratch = GetTemporary(context, node, 3);\n TfLiteTensor* zero_points = GetTemporary(context, node, 4);\n TfLiteTensor* row_sums = GetTemporary(context, node, 5);\n return EvalHybrid(input, input_weights, recurrent_weights, bias, params,\n input_quantized, hidden_state_quantized,\n scaling_factors, hidden_state, output, zero_points,\n accum_scratch, row_sums, &op_data->compute_row_sums);\n }\n default:\n TF_LITE_KERNEL_LOG(context, \"Type %d not currently supported.\",\n TfLiteTypeGetName(input_weights->type));\n return kTfLiteError;\n }\n return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n ruy::profiler::ScopeLabel label(\"MirrorPad\");\n const TfLiteTensor* input_tensor = GetInput(context, node, 0);\n const TfLiteTensor* padding_matrix = GetInput(context, node, 1);\n auto* params =\n reinterpret_cast(node->builtin_data);\n\n if (params == nullptr) {\n return kTfLiteError;\n }\n const int input_dims = NumDimensions(input_tensor);\n\n TfLiteTensor* output_tensor = GetOutput(context, node, 0);\n if (IsDynamicTensor(output_tensor)) {\n auto output_size = GetPaddedOutputShape(input_tensor, padding_matrix);\n if (output_size == nullptr) {\n return kTfLiteError;\n }\n TF_LITE_ENSURE_STATUS(\n context->ResizeTensor(context, output_tensor, output_size.release()));\n }\n\n std::vector output_dims_num_elements(input_dims, 1);\n std::vector input_dims_num_elements(input_dims, 1);\n for (int i = input_dims - 2; i >= 0; i--) {\n output_dims_num_elements[i] =\n output_dims_num_elements[i + 1] * output_tensor->dims->data[i + 1];\n input_dims_num_elements[i] =\n input_dims_num_elements[i + 1] * input_tensor->dims->data[i + 1];\n }\n\n const int offset =\n params->mode != TfLiteMirrorPaddingMode::kTfLiteMirrorPaddingReflect ? 0\n : 1;\n\n CpuBackendContext* cpu_backend_context =\n CpuBackendContext::GetFromContext(context);\n const int thread_count = cpu_backend_context->max_num_threads();\n TfLiteStatus status = kTfLiteOk;\n const int output_size = NumElements(output_tensor);\n#define TF_LITE_MIRROR_PAD(type) \\\n EvalData eval_data; \\\n eval_data.input_data = GetTensorData(input_tensor); \\\n eval_data.input_dims = input_tensor->dims; \\\n eval_data.input_dims = input_tensor->dims; \\\n eval_data.output_dims_num_elements = &output_dims_num_elements; \\\n eval_data.input_dims_num_elements = &input_dims_num_elements; \\\n eval_data.num_dims = input_dims; \\\n eval_data.offset = offset; \\\n eval_data.output_data = GetTensorData(output_tensor); \\\n eval_data.padding_matrix = padding_matrix; \\\n std::vector> tasks; \\\n tasks.reserve(thread_count); \\\n int start = 0; \\\n for (int i = 0; i < thread_count; ++i) { \\\n int end = start + (output_size - start) / (thread_count - i); \\\n tasks.emplace_back(MirrorPadWorkerTask(&eval_data, start, end)); \\\n start = end; \\\n } \\\n cpu_backend_threadpool::Execute(tasks.size(), tasks.data(), \\\n cpu_backend_context);\n\n switch (output_tensor->type) {\n case kTfLiteFloat32: {\n TF_LITE_MIRROR_PAD(float);\n break;\n }\n case kTfLiteInt32: {\n TF_LITE_MIRROR_PAD(int32_t);\n break;\n }\n case kTfLiteUInt8: {\n TF_LITE_MIRROR_PAD(uint8_t);\n break;\n }\n case kTfLiteInt8: {\n TF_LITE_MIRROR_PAD(int8_t);\n break;\n }\n case kTfLiteInt64: {\n TF_LITE_MIRROR_PAD(int64_t);\n break;\n }\n default:\n status = kTfLiteError;\n break;\n }\n#undef TF_LITE_MIRROR_PAD\n return status;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* lookup = GetInput(context, node, 0);\n const TfLiteTensor* value = GetInput(context, node, 1);\n TfLiteTensor* output = GetOutput(context, node, 0);\n switch (value->type) {\n case kTfLiteFloat32:\n return EvalSimple(context, node, lookup, value, output);\n case kTfLiteUInt8:\n case kTfLiteInt8:\n if (output->type == kTfLiteFloat32) {\n return EvalHybrid(context, node, lookup, value, output);\n } else {\n return EvalSimple(context, node, lookup, value, output);\n }\n default:\n context->ReportError(context, \"Type not currently supported.\");\n return kTfLiteError;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n const int num_elements = NumElements(input);\n switch (input->type) {\n case kTfLiteInt64:\n memset(GetTensorData(output), 0, num_elements * sizeof(int64_t));\n break;\n case kTfLiteInt32:\n memset(GetTensorData(output), 0, num_elements * sizeof(int32_t));\n break;\n case kTfLiteFloat32:\n memset(GetTensorData(output), 0, num_elements * sizeof(float));\n break;\n default:\n context->ReportError(context,\n \"ZerosLike only currently supports int64, int32, \"\n \"and float32, got %d.\",\n input->type);\n return kTfLiteError;\n }\n return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static TfLiteStatus InitTemporaryTensors(TfLiteContext* context,\n TfLiteNode* node) {\n OpData* data = reinterpret_cast(node->user_data);\n // The prepare function may be executed multiple times. But temporary tensors\n // only need to be initiated once.\n if (data->fft_integer_working_area_id != kTensorNotAllocated &&\n data->fft_double_working_area_id != kTensorNotAllocated) {\n return kTfLiteOk;\n }\n\n TfLiteIntArrayFree(node->temporaries);\n // Create two temporary tensors.\n node->temporaries = TfLiteIntArrayCreate(2);\n int first_new_index;\n TF_LITE_ENSURE_STATUS(context->AddTensors(context, 2, &first_new_index));\n node->temporaries->data[kFftIntegerWorkingAreaTensor] = first_new_index;\n data->fft_integer_working_area_id = first_new_index;\n node->temporaries->data[kFftDoubleWorkingAreaTensor] = first_new_index + 1;\n data->fft_double_working_area_id = first_new_index + 1;\n\n // Set up FFT integer working area buffer.\n TfLiteTensor* fft_integer_working_area =\n GetTemporary(context, node, kFftIntegerWorkingAreaTensor);\n fft_integer_working_area->type = kTfLiteInt32;\n // If fft_length is not a constant tensor, fft_integer_working_area will be\n // set to dynamic later in Prepare.\n fft_integer_working_area->allocation_type = kTfLiteArenaRw;\n\n // Set up FFT double working area buffer.\n TfLiteTensor* fft_double_working_area =\n GetTemporary(context, node, kFftDoubleWorkingAreaTensor);\n // fft_double_working_area is a double tensor. Ideally, double should be\n // added into tflite data types. However, since fft_double_working_area is a\n // temporary tensor, and there are no ops having double input/output tensors\n // in tflite at this point, adding double as a tflite data type may confuse\n // users that double is supported. As a results, kTfLiteInt64 is used here\n // for memory allocation. And it will be cast into double in Eval when being\n // used.\n fft_double_working_area->type = kTfLiteInt64;\n // If fft_length is not a constant tensor, fft_double_working_area will be\n // set to dynamic later in Prepare.\n fft_double_working_area->allocation_type = kTfLiteArenaRw;\n\n return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n auto* params =\n reinterpret_cast(node->builtin_data);\n TfLiteTensor* output = GetOutput(context, node, 0);\n const TfLiteTensor* ids = GetInput(context, node, 0);\n const TfLiteTensor* indices = GetInput(context, node, 1);\n const TfLiteTensor* dense_shape = GetInput(context, node, 2);\n const TfLiteTensor* weights = GetInput(context, node, 3);\n const TfLiteTensor* value = GetInput(context, node, 4);\n\n const int lookup_rank = SizeOfDimension(indices, 1);\n const int embedding_rank = NumDimensions(value);\n const int num_lookups = SizeOfDimension(ids, 0);\n const int num_rows = SizeOfDimension(value, 0);\n\n // The last dimension gets replaced by the embedding.\n const int output_rank = (lookup_rank - 1) + (embedding_rank - 1);\n\n // Make sure that the actual dense shape of the sparse tensor represented by\n // (loopkup, indices, dense_shape) is consistent.\n TF_LITE_ENSURE_EQ(context, SizeOfDimension(dense_shape, 0), lookup_rank);\n\n // Resize output tensor.\n TfLiteIntArray* output_shape = TfLiteIntArrayCreate(output_rank);\n int k = 0;\n int embedding_size = 1;\n int lookup_size = 1;\n for (int i = 0; i < lookup_rank - 1; i++, k++) {\n const int dim = dense_shape->data.i32[i];\n lookup_size *= dim;\n output_shape->data[k] = dim;\n }\n for (int i = 1; i < embedding_rank; i++, k++) {\n const int dim = SizeOfDimension(value, i);\n embedding_size *= dim;\n output_shape->data[k] = dim;\n }\n TF_LITE_ENSURE_STATUS(context->ResizeTensor(context, output, output_shape));\n const int output_size = lookup_size * embedding_size;\n TfLiteTensorRealloc(output_size * sizeof(float), output);\n\n float* output_ptr = GetTensorData(output);\n const float* weights_ptr = GetTensorData(weights);\n const float* value_ptr = GetTensorData(value);\n\n std::fill_n(output_ptr, output_size, 0.0f);\n\n // Keep track of the current bucket for aggregation/combination.\n int current_output_offset = 0;\n float current_total_weight = 0.0;\n float current_squares_weight = 0.0;\n int num_elements = 0;\n\n for (int i = 0; i < num_lookups; i++) {\n int idx = ids->data.i32[i];\n if (idx >= num_rows || idx < 0) {\n context->ReportError(context,\n \"Embedding Lookup Sparse: index out of bounds. \"\n \"Got %d, and bounds are [0, %d]\",\n idx, num_rows - 1);\n return kTfLiteError;\n }\n\n // Check where we need to aggregate.\n const int example_indices_offset = i * lookup_rank;\n int output_bucket = 0;\n int stride = 1;\n for (int k = (lookup_rank - 1) - 1; k >= 0; k--) {\n output_bucket += indices->data.i32[example_indices_offset + k] * stride;\n stride *= dense_shape->data.i32[k];\n }\n const int output_offset = output_bucket * embedding_size;\n\n // If we are in a new aggregation bucket and the combiner is not the sum,\n // go back and finalize the result of the previous bucket.\n if (output_offset != current_output_offset) {\n FinalizeAggregation(params->combiner, num_elements, current_total_weight,\n current_squares_weight, embedding_size,\n &output_ptr[current_output_offset]);\n\n // Track next bucket.\n num_elements = 0;\n current_total_weight = 0.0;\n current_squares_weight = 0.0;\n current_output_offset = output_offset;\n }\n\n // Add element to aggregation.\n ++num_elements;\n const int example_embedding_offset = idx * embedding_size;\n const float w = weights_ptr[i];\n current_squares_weight += w * w;\n current_total_weight += w;\n for (int k = 0; k < embedding_size; k++) {\n output_ptr[current_output_offset + k] +=\n value_ptr[example_embedding_offset + k] * w;\n }\n }\n\n // Finalize last bucket.\n FinalizeAggregation(params->combiner, num_elements, current_total_weight,\n current_squares_weight, embedding_size,\n &GetTensorData(output)[current_output_offset]);\n\n return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n // TODO(b/143912164): instead of hardcode the epsilon here, we should read it\n // from tensorflow, i.e., adding a params.\n // We don't compute epsilon for quantized kernel:\n //\n // epsilon_float = (epsilon_quant - zp) * scale\n // so\n // espsilon_quant = epsilon_float / scale + zp\n // We know epsilon_float is just a very small number to avoid division by\n // zero error, and scale is > 1, so the integer value of epsilon for quant\n // is just dominated by the zero point.\n // Also, GetInvSqrtQuantizedMultiplierExp handles the scenario where the sum\n // of input value squared is zero case well.\n // So we don't even need to do handle the epsilon for quantized kernel case.\n const float epsilon = 1e-6f;\n if (output->type == kTfLiteFloat32) {\n#define TF_LITE_L2NORM(type) \\\n tflite::L2NormalizationParams op_params; \\\n op_params.input_zero_point = 0; \\\n type::L2Normalization(op_params, GetTensorShape(input), \\\n GetTensorData(input), GetTensorShape(output), \\\n GetTensorData(output), epsilon)\n\n if (kernel_type == kReference) {\n TF_LITE_L2NORM(reference_ops);\n }\n if (kernel_type == kGenericOptimized) {\n TF_LITE_L2NORM(optimized_ops);\n }\n#undef TF_LITE_L2NORM\n } else if (output->type == kTfLiteUInt8) {\n#define TF_LITE_L2NORM(type) \\\n tflite::L2NormalizationParams op_params; \\\n op_params.input_zero_point = input->params.zero_point; \\\n type::L2Normalization(op_params, GetTensorShape(input), \\\n GetTensorData(input), GetTensorShape(output), \\\n GetTensorData(output))\n\n if (kernel_type == kReference) {\n TF_LITE_L2NORM(reference_ops);\n }\n if (kernel_type == kGenericOptimized) {\n TF_LITE_L2NORM(optimized_ops);\n }\n#undef TF_LITE_L2NORM\n } else if (output->type == kTfLiteInt8) {\n const auto input_shape = GetTensorShape(input);\n const auto output_shape = GetTensorShape(output);\n const int trailing_dim = input_shape.DimensionsCount() - 1;\n const int depth =\n MatchingDim(input_shape, trailing_dim, output_shape, trailing_dim);\n const int outer_size =\n MatchingFlatSizeSkipDim(input_shape, trailing_dim, output_shape);\n reference_integer_ops::L2Normalization(input->params.zero_point, outer_size,\n depth, GetTensorData(input),\n GetTensorData(output));\n } else {\n TF_LITE_KERNEL_LOG(context, \"Output type is %s, requires float.\",\n TfLiteTypeGetName(output->type));\n return kTfLiteError;\n }\n\n return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus NonMaxSuppressionMultiClass(TfLiteContext* context,\n TfLiteNode* node, OpData* op_data) {\n // Get the input tensors\n const TfLiteTensor* input_box_encodings =\n GetInput(context, node, kInputTensorBoxEncodings);\n const TfLiteTensor* input_class_predictions =\n GetInput(context, node, kInputTensorClassPredictions);\n const int num_boxes = input_box_encodings->dims->data[1];\n const int num_classes = op_data->num_classes;\n TF_LITE_ENSURE_EQ(context, input_class_predictions->dims->data[0],\n kBatchSize);\n TF_LITE_ENSURE_EQ(context, input_class_predictions->dims->data[1], num_boxes);\n const int num_classes_with_background =\n input_class_predictions->dims->data[2];\n\n TF_LITE_ENSURE(context, (num_classes_with_background - num_classes <= 1));\n TF_LITE_ENSURE(context, (num_classes_with_background >= num_classes));\n\n const TfLiteTensor* scores;\n switch (input_class_predictions->type) {\n case kTfLiteUInt8: {\n TfLiteTensor* temporary_scores = &context->tensors[op_data->scores_index];\n DequantizeClassPredictions(input_class_predictions, num_boxes,\n num_classes_with_background, temporary_scores);\n scores = temporary_scores;\n } break;\n case kTfLiteFloat32:\n scores = input_class_predictions;\n break;\n default:\n // Unsupported type.\n return kTfLiteError;\n }\n if (op_data->use_regular_non_max_suppression)\n TF_LITE_ENSURE_STATUS(NonMaxSuppressionMultiClassRegularHelper(\n context, node, op_data, GetTensorData(scores)));\n else\n TF_LITE_ENSURE_STATUS(NonMaxSuppressionMultiClassFastHelper(\n context, node, op_data, GetTensorData(scores)));\n\n return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n auto* params = reinterpret_cast(node->builtin_data);\n OpData* data = reinterpret_cast(node->user_data);\n\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);\n const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n TF_LITE_ENSURE_TYPES_EQ(context, input1->type, input2->type);\n\n const bool requires_broadcast = !HaveSameShapes(input1, input2);\n\n TfLiteIntArray* output_size = nullptr;\n if (requires_broadcast) {\n TF_LITE_ENSURE_OK(context, CalculateShapeForBroadcast(\n context, input1, input2, &output_size));\n } else {\n output_size = TfLiteIntArrayCopy(input1->dims);\n }\n\n if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8 ||\n output->type == kTfLiteInt16) {\n TF_LITE_ENSURE_STATUS(CalculateActivationRangeQuantized(\n context, params->activation, output, &data->output_activation_min,\n &data->output_activation_max));\n double real_multiplier =\n input1->params.scale * input2->params.scale / output->params.scale;\n QuantizeMultiplier(real_multiplier, &data->output_multiplier,\n &data->output_shift);\n }\n\n return context->ResizeTensor(context, output, output_size);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': '[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: char *FLTGetIsLikeComparisonCommonExpression(FilterEncodingNode *psFilterNode)\n{\n const size_t bufferSize = 1024;\n char szBuffer[1024];\n char szTmp[256];\n char *pszValue = NULL;\n\n const char *pszWild = NULL;\n const char *pszSingle = NULL;\n const char *pszEscape = NULL;\n int bCaseInsensitive = 0;\n FEPropertyIsLike* propIsLike;\n\n int nLength=0, i=0, iTmp=0;\n\n if (!psFilterNode || !psFilterNode->pOther || !psFilterNode->psLeftNode || !psFilterNode->psRightNode || !psFilterNode->psRightNode->pszValue)\n return NULL;\n\n propIsLike = (FEPropertyIsLike *)psFilterNode->pOther;\n pszWild = propIsLike->pszWildCard;\n pszSingle = propIsLike->pszSingleChar;\n pszEscape = propIsLike->pszEscapeChar;\n bCaseInsensitive = propIsLike->bCaseInsensitive;\n\n if (!pszWild || strlen(pszWild) == 0 || !pszSingle || strlen(pszSingle) == 0 || !pszEscape || strlen(pszEscape) == 0)\n return NULL;\n\n /* -------------------------------------------------------------------- */\n /* Use operand with regular expressions. */\n /* -------------------------------------------------------------------- */\n szBuffer[0] = '\\0';\n sprintf(szTmp, \"%s\", \"(\\\"[\");\n szTmp[4] = '\\0';\n\n strlcat(szBuffer, szTmp, bufferSize);\n\n /* attribute */\n strlcat(szBuffer, psFilterNode->psLeftNode->pszValue, bufferSize);\n szBuffer[strlen(szBuffer)] = '\\0';\n\n /* #3521 */\n if (bCaseInsensitive == 1)\n sprintf(szTmp, \"%s\", \"]\\\" ~* \\\"\");\n else\n sprintf(szTmp, \"%s\", \"]\\\" ~ \\\"\");\n szTmp[7] = '\\0';\n strlcat(szBuffer, szTmp, bufferSize);\n szBuffer[strlen(szBuffer)] = '\\0';\n\n pszValue = psFilterNode->psRightNode->pszValue;\n nLength = strlen(pszValue);\n\n iTmp =0;\n if (nLength > 0 && pszValue[0] != pszWild[0] && pszValue[0] != pszSingle[0] && pszValue[0] != pszEscape[0]) {\n szTmp[iTmp]= '^';\n iTmp++;\n }\n for (i=0; i \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-119'], 'message': 'security fix (patch by EvenR)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: choose_volume(struct archive_read *a, struct iso9660 *iso9660)\n{\n\tstruct file_info *file;\n\tint64_t skipsize;\n\tstruct vd *vd;\n\tconst void *block;\n\tchar seenJoliet;\n\n\tvd = &(iso9660->primary);\n\tif (!iso9660->opt_support_joliet)\n\t\tiso9660->seenJoliet = 0;\n\tif (iso9660->seenJoliet &&\n\t\tvd->location > iso9660->joliet.location)\n\t\t/* This condition is unlikely; by way of caution. */\n\t\tvd = &(iso9660->joliet);\n\n\tskipsize = LOGICAL_BLOCK_SIZE * vd->location;\n\tskipsize = __archive_read_consume(a, skipsize);\n\tif (skipsize < 0)\n\t\treturn ((int)skipsize);\n\tiso9660->current_position = skipsize;\n\n\tblock = __archive_read_ahead(a, vd->size, NULL);\n\tif (block == NULL) {\n\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,\n\t\t \"Failed to read full block when scanning \"\n\t\t \"ISO9660 directory list\");\n\t\treturn (ARCHIVE_FATAL);\n\t}\n\n\t/*\n\t * While reading Root Directory, flag seenJoliet must be zero to\n\t * avoid converting special name 0x00(Current Directory) and\n\t * next byte to UCS2.\n\t */\n\tseenJoliet = iso9660->seenJoliet;/* Save flag. */\n\tiso9660->seenJoliet = 0;\n\tfile = parse_file_info(a, NULL, block);\n\tif (file == NULL)\n\t\treturn (ARCHIVE_FATAL);\n\tiso9660->seenJoliet = seenJoliet;\n\n\t/*\n\t * If the iso image has both RockRidge and Joliet, we preferentially\n\t * use RockRidge Extensions rather than Joliet ones.\n\t */\n\tif (vd == &(iso9660->primary) && iso9660->seenRockridge\n\t && iso9660->seenJoliet)\n\t\tiso9660->seenJoliet = 0;\n\n\tif (vd == &(iso9660->primary) && !iso9660->seenRockridge\n\t && iso9660->seenJoliet) {\n\t\t/* Switch reading data from primary to joliet. */\n\t\tvd = &(iso9660->joliet);\n\t\tskipsize = LOGICAL_BLOCK_SIZE * vd->location;\n\t\tskipsize -= iso9660->current_position;\n\t\tskipsize = __archive_read_consume(a, skipsize);\n\t\tif (skipsize < 0)\n\t\t\treturn ((int)skipsize);\n\t\tiso9660->current_position += skipsize;\n\n\t\tblock = __archive_read_ahead(a, vd->size, NULL);\n\t\tif (block == NULL) {\n\t\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,\n\t\t\t \"Failed to read full block when scanning \"\n\t\t\t \"ISO9660 directory list\");\n\t\t\treturn (ARCHIVE_FATAL);\n\t\t}\n\t\tiso9660->seenJoliet = 0;\n\t\tfile = parse_file_info(a, NULL, block);\n\t\tif (file == NULL)\n\t\t\treturn (ARCHIVE_FATAL);\n\t\tiso9660->seenJoliet = seenJoliet;\n\t}\n\n\t/* Store the root directory in the pending list. */\n\tif (add_entry(a, iso9660, file) != ARCHIVE_OK)\n\t\treturn (ARCHIVE_FATAL);\n\tif (iso9660->seenRockridge) {\n\t\ta->archive.archive_format = ARCHIVE_FORMAT_ISO9660_ROCKRIDGE;\n\t\ta->archive.archive_format_name =\n\t\t \"ISO9660 with Rockridge extensions\";\n\t}\n\n\treturn (ARCHIVE_OK);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Issue 717: Fix integer overflow when computing location of volume descriptor\n\nThe multiplication here defaulted to 'int' but calculations\nof file positions should always use int64_t. A simple cast\nsuffices to fix this since the base location is always 32 bits\nfor ISO, so multiplying by the sector size will never overflow\na 64-bit integer.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: long kvm_arch_vcpu_ioctl(struct file *filp,\n\t\t\t unsigned int ioctl, unsigned long arg)\n{\n\tstruct kvm_vcpu *vcpu = filp->private_data;\n\tvoid __user *argp = (void __user *)arg;\n\n\tswitch (ioctl) {\n\tcase KVM_ARM_VCPU_INIT: {\n\t\tstruct kvm_vcpu_init init;\n\n\t\tif (copy_from_user(&init, argp, sizeof(init)))\n\t\t\treturn -EFAULT;\n\n\t\treturn kvm_vcpu_set_target(vcpu, &init);\n\n\t}\n\tcase KVM_SET_ONE_REG:\n\tcase KVM_GET_ONE_REG: {\n\t\tstruct kvm_one_reg reg;\n\t\tif (copy_from_user(®, argp, sizeof(reg)))\n\t\t\treturn -EFAULT;\n\t\tif (ioctl == KVM_SET_ONE_REG)\n\t\t\treturn kvm_arm_set_reg(vcpu, ®);\n\t\telse\n\t\t\treturn kvm_arm_get_reg(vcpu, ®);\n\t}\n\tcase KVM_GET_REG_LIST: {\n\t\tstruct kvm_reg_list __user *user_list = argp;\n\t\tstruct kvm_reg_list reg_list;\n\t\tunsigned n;\n\n\t\tif (copy_from_user(®_list, user_list, sizeof(reg_list)))\n\t\t\treturn -EFAULT;\n\t\tn = reg_list.n;\n\t\treg_list.n = kvm_arm_num_regs(vcpu);\n\t\tif (copy_to_user(user_list, ®_list, sizeof(reg_list)))\n\t\t\treturn -EFAULT;\n\t\tif (n < reg_list.n)\n\t\t\treturn -E2BIG;\n\t\treturn kvm_arm_copy_reg_indices(vcpu, user_list->reg);\n\t}\n\tdefault:\n\t\treturn -EINVAL;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-284'], 'message': 'ARM: KVM: prevent NULL pointer dereferences with KVM VCPU ioctl\n\nSome ARM KVM VCPU ioctls require the vCPU to be properly initialized\nwith the KVM_ARM_VCPU_INIT ioctl before being used with further\nrequests. KVM_RUN checks whether this initialization has been\ndone, but other ioctls do not.\nNamely KVM_GET_REG_LIST will dereference an array with index -1\nwithout initialization and thus leads to a kernel oops.\nFix this by adding checks before executing the ioctl handlers.\n\n [ Removed superflous comment from static function - Christoffer ]\n\nChanges from v1:\n * moved check into a static function with a meaningful name\n\nSigned-off-by: Andre Przywara \nSigned-off-by: Christoffer Dall '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int mp4boxMain(int argc, char **argv)\n{\n\tu32 i, j;\n\tconst char *gpac_profile = \"0\";\n\tGF_Err e = GF_OK;\n\tnb_tsel_acts = nb_add = nb_cat = nb_track_act = nb_sdp_ex = max_ptime = nb_meta_act = rtp_rate = major_brand = nb_alt_brand_add = nb_alt_brand_rem = car_dur = minor_version = 0;\n\n\tsplit_duration = 0.0;\n\tsplit_start = -1.0;\n\tinterleaving_time = 0;\n\tdash_duration = dash_subduration = 0.0;\n\timport_fps.num = import_fps.den = 0;\n\timport_flags = 0;\n\tsplit_size = 0;\n\tmovie_time = 0;\n\tdump_nal = dump_saps = dump_saps_mode = force_new = 0;\n\tFullInter = HintInter = encode = do_scene_log = old_interleave = do_saf = do_hash = verbose = do_mpd_rip = merge_vtt_cues = get_nb_tracks = GF_FALSE;\n#ifndef GPAC_DISABLE_SCENE_DUMP\n\tdump_mode = GF_SM_DUMP_NONE;\n#endif\n\tFrag = force_ocr = remove_sys_tracks = agg_samples = remove_hint = keep_sys_tracks = remove_root_od = single_group = clean_groups = compress_moov = GF_FALSE;\n\tconv_type = HintIt = needSave = print_sdp = regular_iod = dump_std = open_edit = dump_rtp = dump_cr = dump_srt = dump_ttxt = dump_m2ts = dump_cart = import_subtitle = force_cat = pack_wgt = dash_live = GF_FALSE;\n\tno_fragments_defaults = GF_FALSE;\n\tsingle_traf_per_moof = hls_clock = GF_FALSE;\n tfdt_per_traf = GF_FALSE;\n\tdump_nal_type = 0;\n\tdump_isom = 0;\n\tprint_info = 0;\n\t/*align cat is the new default behaviour for -cat*/\n\talign_cat = GF_TRUE;\n\tsubsegs_per_sidx = 0;\n\ttrack_dump_type = 0;\n\tcrypt = 0;\n\ttime_shift_depth = 0;\n\tfile = NULL;\n\titunes_tags = pes_dump = NULL;\n\tseg_name = dash_ctx_file = NULL;\n\tcompress_top_boxes = NULL;\n\tinitial_moof_sn = 0;\n\tinitial_tfdt = 0;\n\n#ifndef GPAC_DISABLE_SCENE_ENCODER\n\tmemset(&smenc_opts, 0, sizeof(smenc_opts));\n#endif\n\n\ttrackID = stat_level = hint_flags = 0;\n\tprogram_number = 0;\n\tinfo_track_id = 0;\n\tdo_flat = 0;\n\tinName = outName = mediaSource = input_ctx = output_ctx = drm_file = avi2raw = cprt = chap_file = pack_file = raw_cat = high_dynamc_range_filename = use_init_seg = box_patch_filename = NULL;\n\n#ifndef GPAC_DISABLE_SWF_IMPORT\n\tswf_flags = GF_SM_SWF_SPLIT_TIMELINE;\n#endif\n\tswf_flatten_angle = 0.0f;\n\ttmpdir = NULL;\n\n\tfor (i = 1; i < (u32) argc ; i++) {\n\t\tif (!strcmp(argv[i], \"-mem-track\") || !strcmp(argv[i], \"-mem-track-stack\")) {\n#ifdef GPAC_MEMORY_TRACKING\n mem_track = !strcmp(argv[i], \"-mem-track-stack\") ? GF_MemTrackerBackTrace : GF_MemTrackerSimple;\n#else\n\t\t\tfprintf(stderr, \"WARNING - GPAC not compiled with Memory Tracker - ignoring \\\"%s\\\"\\n\", argv[i]);\n#endif\n\t\t\tbreak;\n\t\t}\n\t\telse if (!strcmp(argv[i], \"-p\")) {\n\t\t\tif (i+1<(u32) argc)\n\t\t\t\tgpac_profile = argv[i+1];\n\t\t\telse {\n\t\t\t\tfprintf(stderr, \"Bad argument for -p, expecting profile name but no more args\\n\");\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\t\telse if (!strncmp(argv[i], \"-p=\", 3))\n\t\t\tgpac_profile = argv[i]+3;\n\t}\n\n#ifdef _TWO_DIGIT_EXPONENT\n\t_set_output_format(_TWO_DIGIT_EXPONENT);\n#endif\n\n\t/*init libgpac*/\n\tgf_sys_init(mem_track, gpac_profile);\n\tif (argc < 2) {\n\t\tfprintf(stderr, \"Not enough arguments - check usage with -h\\n\"\n\t\t\t\"MP4Box - GPAC version %s\\n\"\n\t \"%s\\n\", gf_gpac_version(), gf_gpac_copyright());\n\t\tgf_sys_close();\n\t\treturn 0;\n\t}\n\n\thelpout = stdout;\n\n\ti = mp4box_parse_args(argc, argv);\n\tif (i) {\n\t\treturn mp4box_cleanup(i - 1);\n\t}\n\n\tif (!inName && dump_std)\n\t\tinName = \"std\";\n\n\tif (!inName) {\n\t\tif (has_next_arg) {\n\t\t\tfprintf(stderr, \"Broken argument specifier or file name missing - check usage with -h\\n\");\n\t\t} else {\n\t\t\tPrintUsage();\n\t\t}\n\t\treturn mp4box_cleanup(1);\n\t}\n\tif (!strcmp(inName, \"std\")) dump_std = 2;\n\tif (!strcmp(inName, \"stdb\")) {\n\t\tinName = \"std\";\n\t\tdump_std = 1;\n\t}\n\n\tif (!interleaving_time) {\n\t\t/*by default use single fragment per dash segment*/\n\t\tif (dash_duration)\n\t\t\tinterleaving_time = dash_duration;\n\t\telse if (!do_flat) {\n\t\t\tinterleaving_time = DEFAULT_INTERLEAVING_IN_SEC;\n\t\t}\n\t}\n\n\tif (dump_std)\n\t\toutName = \"std\";\n\n\tif (dump_std==2) {\n#ifdef WIN32\n\t\tif ( _setmode(_fileno(stdout), _O_BINARY) == -1 )\n#else\n\t\tif ( freopen(NULL, \"wb\", stdout) == NULL)\n#endif\n\t\t{\n\t\t\tfprintf(stderr, \"Fatal error: cannot reopen stdout in binary mode.\\n\");\n\t\t\treturn mp4box_cleanup(1);\n\t\t}\n\t}\n\n#if !defined(GPAC_DISABLE_STREAMING) && !defined(GPAC_DISABLE_SENG)\n\tif (live_scene) {\n\t\tint ret = live_session(argc, argv);\n\t\treturn mp4box_cleanup(ret);\n\t}\n#endif\n\n\tGF_LOG_Level level = verbose ? GF_LOG_DEBUG : GF_LOG_INFO;\n\tgf_log_set_tool_level(GF_LOG_CONTAINER, level);\n\tgf_log_set_tool_level(GF_LOG_SCENE, level);\n\tgf_log_set_tool_level(GF_LOG_PARSER, level);\n\tgf_log_set_tool_level(GF_LOG_AUTHOR, level);\n\tgf_log_set_tool_level(GF_LOG_CODING, level);\n\tgf_log_set_tool_level(GF_LOG_DASH, level);\n#ifdef GPAC_MEMORY_TRACKING\n\tif (mem_track)\n\t\tgf_log_set_tool_level(GF_LOG_MEMORY, level);\n#endif\n\n\te = gf_sys_set_args(argc, (const char **) argv);\n\tif (e) {\n\t\tfprintf(stderr, \"Error assigning libgpac arguments: %s\\n\", gf_error_to_string(e) );\n\t\treturn mp4box_cleanup(1);\n\t}\n\n\tif (raw_cat) {\n\t\tchar chunk[4096];\n\t\tFILE *fin, *fout;\n\t\ts64 to_copy, done;\n\t\tfin = gf_fopen(raw_cat, \"rb\");\n\t\tif (!fin) return mp4box_cleanup(1);\n\n\t\tfout = gf_fopen(inName, \"a+b\");\n\t\tif (!fout) {\n\t\t\tgf_fclose(fin);\n\t\t\treturn mp4box_cleanup(1);\n\t\t}\n\t\tgf_fseek(fin, 0, SEEK_END);\n\t\tto_copy = gf_ftell(fin);\n\t\tgf_fseek(fin, 0, SEEK_SET);\n\t\tdone = 0;\n\t\twhile (1) {\n\t\t\tu32 nb_bytes = (u32) gf_fread(chunk, 4096, fin);\n\t\t\tgf_fwrite(chunk, nb_bytes, fout);\n\t\t\tdone += nb_bytes;\n\t\t\tfprintf(stderr, \"Appending file %s - %02.2f done\\r\", raw_cat, 100.0*done/to_copy);\n\t\t\tif (done >= to_copy) break;\n\t\t}\n\t\tgf_fclose(fin);\n\t\tgf_fclose(fout);\n\t\treturn mp4box_cleanup(0);\n\t}\n\tif (compress_top_boxes) {\n\t\tif (size_top_box) {\n\t\t\tu64 top_size = do_size_top_boxes(inName, compress_top_boxes, size_top_box);\n\t\t\tfprintf(stdout, LLU\"\\n\", top_size);\n\t\t\treturn mp4box_cleanup(e ? 1 : 0);\n\t\t} else {\n\t\t\te = do_compress_top_boxes(inName, outName, compress_top_boxes, comp_top_box_version, comp_lzma);\n\t\t\treturn mp4box_cleanup(e ? 1 : 0);\n\t\t}\n\t}\n\n\tif (do_mpd_rip) {\n\t\te = rip_mpd(inName, outName);\n\t\treturn mp4box_cleanup(e ? 1 : 0);\n\t}\n\n#ifndef GPAC_DISABLE_CORE_TOOLS\n\tif (do_wget != NULL) {\n\t\te = gf_dm_wget(do_wget, inName, 0, 0, NULL);\n\t\tif (e != GF_OK) {\n\t\t\tfprintf(stderr, \"Cannot retrieve %s: %s\\n\", do_wget, gf_error_to_string(e) );\n\t\t\treturn mp4box_cleanup(1);\n\t\t}\n\t\treturn mp4box_cleanup(0);\n\t}\n#endif\n\n\tif (udp_dest) {\n\t\tGF_Socket *sock = gf_sk_new(GF_SOCK_TYPE_UDP);\n\t\tu16 port = 2345;\n\t\tchar *sep = strrchr(udp_dest, ':');\n\t\tif (sep) {\n\t\t\tsep[0] = 0;\n\t\t\tport = atoi(sep+1);\n\t\t}\n\t\te = gf_sk_bind( sock, \"127.0.0.1\", 0, udp_dest, port, 0);\n\t\tif (sep) sep[0] = ':';\n\t\tif (e) fprintf(stderr, \"Failed to bind socket to %s: %s\\n\", udp_dest, gf_error_to_string(e) );\n\t\telse {\n\t\t\te = gf_sk_send(sock, (u8 *) inName, (u32)strlen(inName));\n\t\t\tif (e) fprintf(stderr, \"Failed to send datagram: %s\\n\", gf_error_to_string(e) );\n\t\t}\n\t\tgf_sk_del(sock);\n\t\treturn 0;\n\t}\n\n#ifndef GPAC_DISABLE_MPD\n\tif (do_mpd) {\n\t\tBool remote = GF_FALSE;\n\t\tGF_MPD *mpd;\n\t\tchar *mpd_base_url = NULL;\n\t\tif (!strnicmp(inName, \"http://\", 7) || !strnicmp(inName, \"https://\", 8)) {\n#if !defined(GPAC_DISABLE_CORE_TOOLS)\n\t\t\te = gf_dm_wget(inName, \"tmp_main.m3u8\", 0, 0, &mpd_base_url);\n\t\t\tif (e != GF_OK) {\n\t\t\t\tfprintf(stderr, \"Cannot retrieve M3U8 (%s): %s\\n\", inName, gf_error_to_string(e));\n\t\t\t\tif (mpd_base_url) gf_free(mpd_base_url);\n\t\t\t\treturn mp4box_cleanup(1);\n\t\t\t}\n\t\t\tremote = GF_TRUE;\n#else\n\t\t\tgf_free(mpd_base_url);\n\t\t\tfprintf(stderr, \"HTTP Downloader disabled in this build\\n\");\n\t\t\treturn mp4box_cleanup(1);\n#endif\n\n\t\t\tif (outName)\n\t\t\t\tstrcpy(outfile, outName);\n\t\t\telse {\n\t\t\t\tconst char *sep = gf_file_basename(inName);\n\t\t\t\tchar *ext = gf_file_ext_start(sep);\n\t\t\t\tif (ext) ext[0] = 0;\n\t\t\t\tsprintf(outfile, \"%s.mpd\", sep);\n\t\t\t\tif (ext) ext[0] = '.';\n\t\t\t}\n\t\t} else {\n\t\t\tif (outName)\n\t\t\t\tstrcpy(outfile, outName);\n\t\t\telse {\n\t\t\t\tchar *dst = strdup(inName);\n\t\t\t\tchar *ext = strstr(dst, \".m3u8\");\n\t\t\t\tif (ext) ext[0] = 0;\n\t\t\t\tsprintf(outfile, \"%s.mpd\", dst);\n\t\t\t\tgf_free(dst);\n\t\t\t}\n\t\t}\n\n\t\tmpd = gf_mpd_new();\n\t\tif (!mpd) {\n\t\t\te = GF_OUT_OF_MEM;\n\t\t\tfprintf(stderr, \"[DASH] Error: MPD creation problem %s\\n\", gf_error_to_string(e));\n\t\t\tmp4box_cleanup(1);\n\t\t}\n\t\tFILE *f = gf_fopen(remote ? \"tmp_main.m3u8\" : inName, \"r\");\n\t\tu32 manif_type = 0;\n\t\tif (f) {\n\t\t\tchar szDATA[1000];\n\t\t\ts32 read;\n\t\t\tszDATA[999]=0;\n\t\t\tread = (s32) gf_fread(szDATA, 999, f);\n\t\t\tif (read<0) read = 0;\n\t\t\tszDATA[read]=0;\n\t\t\tgf_fclose(f);\n\t\t\tif (strstr(szDATA, \"SmoothStreamingMedia\"))\n\t\t\t\tmanif_type = 2;\n\t\t\telse if (strstr(szDATA, \"#EXTM3U\"))\n\t\t\t\tmanif_type = 1;\n\t\t}\n\n\t\tif (manif_type==1) {\n\t\t\te = gf_m3u8_to_mpd(remote ? \"tmp_main.m3u8\" : inName, mpd_base_url ? mpd_base_url : inName, outfile, 0, \"video/mp2t\", GF_TRUE, use_url_template, segment_timeline, NULL, mpd, GF_TRUE, GF_TRUE);\n\t\t} else if (manif_type==2) {\n\t\t\te = gf_mpd_smooth_to_mpd(remote ? \"tmp_main.m3u8\" : inName, mpd, mpd_base_url ? mpd_base_url : inName);\n\t\t} else {\n\t\t\te = GF_NOT_SUPPORTED;\n\t\t}\n\t\tif (!e)\n\t\t\tgf_mpd_write_file(mpd, outfile);\n\n\t\tif (mpd)\n\t\t\tgf_mpd_del(mpd);\n\t\tif (mpd_base_url)\n\t\t\tgf_free(mpd_base_url);\n\n\t\tif (remote) {\n\t\t\tgf_file_delete(\"tmp_main.m3u8\");\n\t\t}\n\t\tif (e != GF_OK) {\n\t\t\tfprintf(stderr, \"Error converting %s (%s) to MPD (%s): %s\\n\", (manif_type==1) ? \"HLS\" : \"Smooth\", inName, outfile, gf_error_to_string(e));\n\t\t\treturn mp4box_cleanup(1);\n\t\t} else {\n\t\t\tfprintf(stderr, \"Done converting %s (%s) to MPD (%s)\\n\", (manif_type==1) ? \"HLS\" : \"Smooth\", inName, outfile);\n\t\t\treturn mp4box_cleanup(0);\n\t\t}\n\t}\n#endif\n\tif (dash_duration && !nb_dash_inputs) {\n\t\tdash_inputs = set_dash_input(dash_inputs, inName, &nb_dash_inputs);\n\t}\n\n\n\tif (do_saf && !encode) {\n\t\tswitch (get_file_type_by_ext(inName)) {\n\t\tcase GF_FILE_TYPE_BT_WRL_X3DV:\n\t\tcase GF_FILE_TYPE_XMT_X3D:\n\t\tcase GF_FILE_TYPE_SVG:\n\t\t\tencode = GF_TRUE;\n\t\t\tbreak;\n\t\tcase GF_FILE_TYPE_NOT_SUPPORTED:\n\t\tcase GF_FILE_TYPE_ISO_MEDIA:\n\t\tcase GF_FILE_TYPE_SWF:\n\t\tcase GF_FILE_TYPE_LSR_SAF:\n\t\t\tbreak;\n\t\t}\n\t}\n\n#ifndef GPAC_DISABLE_SCENE_DUMP\n\tif (dump_mode == GF_SM_DUMP_SVG) {\n\t\tif (strstr(inName, \".srt\") || strstr(inName, \".ttxt\")) import_subtitle = 2;\n\t}\n#endif\n\n\n\tif (import_subtitle && !trackID) {\n\t\t/* We import the subtitle file,\n\t\t i.e. we parse it and store the content as samples of a 3GPP Timed Text track in an ISO file,\n\t\t possibly for later export (e.g. when converting SRT to TTXT, ...) */\n#ifndef GPAC_DISABLE_MEDIA_IMPORT\n\t\tGF_MediaImporter import;\n\t\t/* Prepare the importer */\n\t\tfile = gf_isom_open(\"ttxt_convert\", GF_ISOM_OPEN_WRITE, NULL);\n\t\tif (timescale && file) gf_isom_set_timescale(file, timescale);\n\n\t\tmemset(&import, 0, sizeof(GF_MediaImporter));\n\t\timport.dest = file;\n\t\timport.in_name = inName;\n\t\t/* Start the import */\n\t\te = gf_media_import(&import);\n\t\tif (e) {\n\t\t\tfprintf(stderr, \"Error importing %s: %s\\n\", inName, gf_error_to_string(e));\n\t\t\tgf_isom_delete(file);\n\t\t\tgf_file_delete(\"ttxt_convert\");\n\t\t\treturn mp4box_cleanup(1);\n\t\t}\n\t\t/* Prepare the export */\n\t\tstrcpy(outfile, inName);\n\t\tif (strchr(outfile, '.')) {\n\t\t\twhile (outfile[strlen(outfile)-1] != '.') outfile[strlen(outfile)-1] = 0;\n\t\t\toutfile[strlen(outfile)-1] = 0;\n\t\t}\n#ifndef GPAC_DISABLE_ISOM_DUMP\n\t\t/* Start the export of the track #1, in the appropriate dump type, indicating it's a conversion */\n\t\tdump_isom_timed_text(file, gf_isom_get_track_id(file, 1),\n\t\t\t\t\t\t\t dump_std ? NULL : (outName ? outName : outfile), outName ? GF_TRUE : GF_FALSE,\n\t\t GF_TRUE,\n\t\t (import_subtitle==2) ? GF_TEXTDUMPTYPE_SVG : (dump_srt ? GF_TEXTDUMPTYPE_SRT : GF_TEXTDUMPTYPE_TTXT));\n#endif\n\t\t/* Clean the importer */\n\t\tgf_isom_delete(file);\n\t\tgf_file_delete(\"ttxt_convert\");\n\t\tif (e) {\n\t\t\tfprintf(stderr, \"Error converting %s: %s\\n\", inName, gf_error_to_string(e));\n\t\t\treturn mp4box_cleanup(1);\n\t\t}\n\t\treturn mp4box_cleanup(0);\n#else\n\t\tfprintf(stderr, \"Feature not supported\\n\");\n\t\treturn mp4box_cleanup(1);\n#endif\n\t}\n\n#if !defined(GPAC_DISABLE_MEDIA_IMPORT) && !defined(GPAC_DISABLE_ISOM_WRITE)\n\tif (nb_add || nb_cat) {\n\t\tu32 ipass, nb_pass = 1;\n\t\tchar *mux_args=NULL;\n\t\tGF_FilterSession *fs = NULL;\n\t\tif (nb_add) {\n\n\t\t\tGF_ISOOpenMode open_mode = GF_ISOM_OPEN_EDIT;\n\t\t\tif (force_new) {\n\t\t\t\topen_mode = (do_flat || (force_new==2)) ? GF_ISOM_OPEN_WRITE : GF_ISOM_WRITE_EDIT;\n\t\t\t} else {\n\t\t\t\tFILE *test = gf_fopen(inName, \"rb\");\n\t\t\t\tif (!test) {\n\t\t\t\t\topen_mode = (do_flat) ? GF_ISOM_OPEN_WRITE : GF_ISOM_WRITE_EDIT;\n\t\t\t\t\tif (!outName) outName = inName;\n\t\t\t\t} else {\n\t\t\t\t\tgf_fclose(test);\n\t\t\t\t\tif (! gf_isom_probe_file(inName) ) {\n\t\t\t\t\t\topen_mode = (do_flat) ? GF_ISOM_OPEN_WRITE : GF_ISOM_WRITE_EDIT;\n\t\t\t\t\t\tif (!outName) outName = inName;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\topen_edit = do_flat ? GF_FALSE : GF_TRUE;\n\t\t\tfile = gf_isom_open(inName, open_mode, tmpdir);\n\t\t\tif (!file) {\n\t\t\t\tfprintf(stderr, \"Cannot open destination file %s: %s\\n\", inName, gf_error_to_string(gf_isom_last_error(NULL)) );\n\t\t\t\treturn mp4box_cleanup(1);\n\t\t\t}\n\n\t\t\tif (freeze_box_order)\n\t\t\t\tgf_isom_freeze_order(file);\n\t\t}\n\n\t\tif (do_flat && interleaving_time) {\n\t\t\tchar szSubArg[100];\n\t\t\tgf_isom_set_storage_mode(file, GF_ISOM_STORE_FASTSTART);\n\t\t\tdo_flat = 2;\n\t\t\tnb_pass = 2;\n\t\t\tfs = gf_fs_new_defaults(0);\n\t\t\tif (!fs) {\n\t\t\t\tfprintf(stderr, \"Error creating filter session\\n\");\n\t\t\t\tgf_isom_delete(file);\n\t\t\t\treturn mp4box_cleanup(1);\n\t\t\t}\n\n\t\t\t//mux args\n\t\t\tgf_dynstrcat(&mux_args, \"mp4mx:importer:store=fstart\", \":\");\n\n\t\t\tsprintf(szSubArg, \"file=%p\", file);\n\t\t\tgf_dynstrcat(&mux_args, szSubArg, \":\");\n\t\t\tsprintf(szSubArg, \"cdur=%g\", interleaving_time);\n\t\t\tgf_dynstrcat(&mux_args, szSubArg, \":\");\n\t\t}\n\n\t\tfor (ipass=0; ipass0) && (dash_duration > dash_subduration)) {\n\t\t\tfprintf(stderr, \"Warning: -subdur parameter (%g s) should be greater than segment duration (%g s), using segment duration instead\\n\", dash_subduration, dash_duration);\n\t\t\tdash_subduration = dash_duration;\n\t\t}\n\n\t\tif (dash_mode && dash_live)\n\t\t\tfprintf(stderr, \"Live DASH-ing - press 'q' to quit, 's' to save context and quit\\n\");\n\n\t\tif (!dash_ctx_file && dash_live) {\n\t\t\tu32 r1;\n\t\t\tu64 add = (u64) (intptr_t) &dasher;\n\t\t\tadd ^= gf_net_get_utc();\n\t\t\tr1 = (u32) add ^ (u32) (add/0xFFFFFFFF);\n\t\t\tr1 ^= gf_rand();\n \t\t\tsprintf(szStateFile, \"%s/dasher_%X.xml\", gf_get_default_cache_directory(), r1 );\n\t\t\tdash_ctx_file = szStateFile;\n\t\t\tdyn_state_file = GF_TRUE;\n\t\t} else if (dash_ctx_file) {\n\t\t\tif (force_new)\n\t\t\t\tgf_file_delete(dash_ctx_file);\n\t\t}\n\n\t\tif (dash_profile==GF_DASH_PROFILE_AUTO)\n\t\t\tdash_profile = dash_mode ? GF_DASH_PROFILE_LIVE : GF_DASH_PROFILE_FULL;\n\n\t\tif (!dash_mode) {\n\t\t\ttime_shift_depth = 0;\n\t\t\tmpd_update_time = 0;\n\t\t} else if ((dash_profile>=GF_DASH_PROFILE_MAIN) && !use_url_template && !mpd_update_time) {\n\t\t\t/*use a default MPD update of dash_duration sec*/\n\t\t\tmpd_update_time = (Double) (dash_subduration ? dash_subduration : dash_duration);\n\t\t\tfprintf(stderr, \"Using default MPD refresh of %g seconds\\n\", mpd_update_time);\n\t\t}\n\n\t\tif (file && needSave) {\n\t\t\tgf_isom_close(file);\n\t\t\tfile = NULL;\n\t\t\tdel_file = GF_TRUE;\n\t\t}\n\n\t\t/*setup dash*/\n\t\tdasher = gf_dasher_new(szMPD, dash_profile, tmpdir, dash_scale, dash_ctx_file);\n\t\tif (!dasher) {\n\t\t\treturn mp4box_cleanup(1);\n\t\t}\n\t\te = gf_dasher_set_info(dasher, dash_title, cprt, dash_more_info, dash_source, NULL);\n\t\tif (e) {\n\t\t\tfprintf(stderr, \"DASH Error: %s\\n\", gf_error_to_string(e));\n\t\t\tgf_dasher_del(dasher);\n\t\t\treturn mp4box_cleanup(1);\n\t\t}\n\n\t\tgf_dasher_set_start_date(dasher, dash_start_date);\n\t\tgf_dasher_set_location(dasher, dash_source);\n\t\tfor (i=0; i < nb_mpd_base_urls; i++) {\n\t\t\te = gf_dasher_add_base_url(dasher, mpd_base_urls[i]);\n\t\t\tif (e) {\n\t\t\t\tfprintf(stderr, \"DASH Error: %s\\n\", gf_error_to_string(e));\n\t\t\t\tgf_dasher_del(dasher);\n\t\t\t\treturn mp4box_cleanup(1);\n\t\t\t}\n\t\t}\n\n\t\tif (segment_timeline && !use_url_template) {\n\t\t\tfprintf(stderr, \"DASH Warning: using -segment-timeline with no -url-template. Forcing URL template.\\n\");\n\t\t\tuse_url_template = GF_TRUE;\n\t\t}\n\n\t\te = gf_dasher_enable_url_template(dasher, (Bool) use_url_template, seg_name, seg_ext, init_seg_ext);\n\t\tif (!e) e = gf_dasher_enable_segment_timeline(dasher, segment_timeline);\n\t\tif (!e) e = gf_dasher_enable_single_segment(dasher, single_segment);\n\t\tif (!e) e = gf_dasher_enable_single_file(dasher, single_file);\n\t\tif (!e) e = gf_dasher_set_switch_mode(dasher, bitstream_switching_mode);\n\t\tif (!e) e = gf_dasher_set_durations(dasher, dash_duration, interleaving_time, dash_subduration);\n\t\tif (!e) e = gf_dasher_enable_rap_splitting(dasher, seg_at_rap, frag_at_rap);\n\t\tif (!e) e = gf_dasher_set_segment_marker(dasher, segment_marker);\n\t\tif (!e) e = gf_dasher_enable_sidx(dasher, (subsegs_per_sidx>=0) ? 1 : 0, (u32) subsegs_per_sidx, daisy_chain_sidx, use_ssix);\n\t\tif (!e) e = gf_dasher_set_dynamic_mode(dasher, dash_mode, mpd_update_time, time_shift_depth, mpd_live_duration);\n\t\tif (!e) e = gf_dasher_set_min_buffer(dasher, min_buffer);\n\t\tif (!e) e = gf_dasher_set_ast_offset(dasher, ast_offset_ms);\n\t\tif (!e) e = gf_dasher_enable_memory_fragmenting(dasher, memory_frags);\n\t\tif (!e) e = gf_dasher_set_initial_isobmf(dasher, initial_moof_sn, initial_tfdt);\n\t\tif (!e) e = gf_dasher_configure_isobmf_default(dasher, no_fragments_defaults, pssh_mode, samplegroups_in_traf, single_traf_per_moof, tfdt_per_traf, mvex_after_traks, sdtp_in_traf);\n\t\tif (!e) e = gf_dasher_enable_utc_ref(dasher, insert_utc);\n\t\tif (!e) e = gf_dasher_enable_real_time(dasher, frag_real_time);\n\t\tif (!e) e = gf_dasher_set_content_protection_location_mode(dasher, cp_location_mode);\n\t\tif (!e) e = gf_dasher_set_profile_extension(dasher, dash_profile_extension);\n\t\tif (!e) e = gf_dasher_enable_cached_inputs(dasher, no_cache);\n\t\tif (!e) e = gf_dasher_enable_loop_inputs(dasher, ! no_loop);\n\t\tif (!e) e = gf_dasher_set_split_mode(dasher, dash_split_mode);\n\t\tif (!e) e = gf_dasher_set_hls_clock(dasher, hls_clock);\n\t\tif (!e && dash_cues) e = gf_dasher_set_cues(dasher, dash_cues, strict_cues);\n\t\tif (!e && fs_dump_flags) e = gf_dasher_print_session_info(dasher, fs_dump_flags);\n\n\t\tfor (i=0; i < nb_dash_inputs; i++) {\n\t\t\tif (!e) e = gf_dasher_add_input(dasher, &dash_inputs[i]);\n\t\t}\n\t\tif (e) {\n\t\t\tfprintf(stderr, \"DASH Setup Error: %s\\n\", gf_error_to_string(e));\n\t\t\tgf_dasher_del(dasher);\n\t\t\treturn mp4box_cleanup(1);\n\t\t}\n\n\t\tdash_cumulated_time=0;\n\n\t\twhile (1) {\n\t\t\tif (run_for && (dash_cumulated_time >= run_for)) {\n\t\t\t\tfprintf(stderr, \"Done running, computing static MPD\\n\");\n\t\t\t\tdo_abort = 3;\n\t\t\t}\n\n\t\t\tdash_prev_time=gf_sys_clock();\n\t\t\tif (do_abort>=2) {\n\t\t\t\te = gf_dasher_set_dynamic_mode(dasher, GF_DASH_DYNAMIC_LAST, 0, time_shift_depth, mpd_live_duration);\n\t\t\t}\n\n\t\t\tif (!e) e = gf_dasher_process(dasher);\n\t\t\tif (!dash_live && (e==GF_EOS) ) {\n\t\t\t\tfprintf(stderr, \"Nothing to dash, too early ...\\n\");\n\t\t\t\te = GF_OK;\n\t\t\t}\n\n\t\t\tif (do_abort)\n\t\t\t\tbreak;\n\n\t\t\t//this happens when reading file while writing them (local playback of the live session ...)\n\t\t\tif (dash_live && (e==GF_IO_ERR) ) {\n\t\t\t\tfprintf(stderr, \"Error dashing file (%s) but continuing ...\\n\", gf_error_to_string(e) );\n\t\t\t\te = GF_OK;\n\t\t\t}\n\n\t\t\tif (e) break;\n\n\t\t\tif (dash_live) {\n\t\t\t\tu64 ms_in_session=0;\n\t\t\t\tu32 slept = gf_sys_clock();\n\t\t\t\tu32 sleep_for = gf_dasher_next_update_time(dasher, &ms_in_session);\n\t\t\t\tfprintf(stderr, \"Next generation scheduled in %u ms (DASH time \"LLU\" ms)\\r\", sleep_for, ms_in_session);\n\t\t\t\tif (run_for && (ms_in_session>=run_for)) {\n\t\t\t\t\tdash_cumulated_time = 1+run_for;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\twhile (1) {\n\t\t\t\t\tif (gf_prompt_has_input()) {\n\t\t\t\t\t\tchar c = (char) gf_prompt_get_char();\n\t\t\t\t\t\tif (c=='X') {\n\t\t\t\t\t\t\tdo_abort = 1;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (c=='q') {\n\t\t\t\t\t\t\tdo_abort = 2;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (c=='s') {\n\t\t\t\t\t\t\tdo_abort = 3;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (dash_mode == GF_DASH_DYNAMIC_DEBUG) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tif (!sleep_for) break;\n\n\t\t\t\t\tgf_sleep(sleep_for/10);\n\t\t\t\t\tsleep_for = gf_dasher_next_update_time(dasher, NULL);\n\t\t\t\t\tif (sleep_for<=1) {\n\t\t\t\t\t\tdash_now_time=gf_sys_clock();\n\t\t\t\t\t\tdash_cumulated_time+=(dash_now_time-dash_prev_time);\n\t\t\t\t\t\tfprintf(stderr, \"Slept for %d ms before generation, dash cumulated time %d\\n\", dash_now_time - slept, dash_cumulated_time);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tgf_dasher_del(dasher);\n\n\t\tif (!run_for && dash_ctx_file && (do_abort==3) && (dyn_state_file) && !gf_sys_is_test_mode() ) {\n\t\t\tchar szName[1024];\n\t\t\tfprintf(stderr, \"Enter file name to save dash context:\\n\");\n\t\t\tif (scanf(\"%1023s\", szName) == 1) {\n\t\t\t\tgf_file_move(dash_ctx_file, szName);\n\t\t\t}\n\t\t}\n\t\tif (e) fprintf(stderr, \"Error DASHing file: %s\\n\", gf_error_to_string(e));\n\t\tif (file) gf_isom_delete(file);\n\t\tif (del_file)\n\t\t\tgf_file_delete(inName);\n\n\t\tif (e) return mp4box_cleanup(1);\n\t\tgoto exit;\n\t}\n\n\telse if (!file && !do_hash\n#ifndef GPAC_DISABLE_MEDIA_EXPORT\n\t && !(track_dump_type & GF_EXPORT_AVI_NATIVE)\n#endif\n\t ) {\n\t\tFILE *st = gf_fopen(inName, \"rb\");\n\t\tBool file_exists = 0;\n\t\tGF_ISOOpenMode omode;\n\t\tif (st) {\n\t\t\tfile_exists = 1;\n\t\t\tgf_fclose(st);\n\t\t}\n\t\tswitch (get_file_type_by_ext(inName)) {\n\t\tcase 1:\n\t\t\tomode = (u8) (force_new ? GF_ISOM_WRITE_EDIT : (open_edit ? GF_ISOM_OPEN_EDIT : ( ((dump_isom>0) || print_info) ? GF_ISOM_OPEN_READ_DUMP : GF_ISOM_OPEN_READ) ) );\n\n\t\t\tif (crypt) {\n\t\t\t\t//keep fragment signaling in moov\n\t\t\t\tomode = GF_ISOM_OPEN_READ;\n\t\t\t\tif (use_init_seg)\n\t\t\t\t\tfile = gf_isom_open(use_init_seg, GF_ISOM_OPEN_READ, tmpdir);\n\t\t\t}\n\t\t\tif (!crypt && use_init_seg) {\n\t\t\t\tfile = gf_isom_open(use_init_seg, GF_ISOM_OPEN_READ_DUMP, tmpdir);\n\t\t\t\tif (file) {\n\t\t\t\t\te = gf_isom_open_segment(file, inName, 0, 0, 0);\n\t\t\t\t\tif (e) {\n\t\t\t\t\t\tfprintf(stderr, \"Error opening segment %s: %s\\n\", inName, gf_error_to_string(e) );\n\t\t\t\t\t\tgf_isom_delete(file);\n\t\t\t\t\t\tfile = NULL;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!file)\n\t\t\t\tfile = gf_isom_open(inName, omode, tmpdir);\n\n\t\t\tif (!file && (gf_isom_last_error(NULL) == GF_ISOM_INCOMPLETE_FILE) && !open_edit) {\n\t\t\t\tu64 missing_bytes;\n\t\t\t\te = gf_isom_open_progressive(inName, 0, 0, GF_FALSE, &file, &missing_bytes);\n\t\t\t\tfprintf(stderr, \"Truncated file - missing \"LLD\" bytes\\n\", missing_bytes);\n\t\t\t}\n\n\t\t\tif (!file) {\n\t\t\t\tif (open_edit && nb_meta_act) {\n\t\t\t\t\tfile = gf_isom_open(inName, GF_ISOM_WRITE_EDIT, tmpdir);\n\t\t\t\t\tif (!outName && file) outName = inName;\n\t\t\t\t}\n\n\t\t\t\tif (!file) {\n\t\t\t\t\tfprintf(stderr, \"Error opening file %s: %s\\n\", inName, gf_error_to_string(gf_isom_last_error(NULL)));\n\t\t\t\t\treturn mp4box_cleanup(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (freeze_box_order)\n\t\t\t\tgf_isom_freeze_order(file);\n\t\t\tbreak;\n\t\t/*allowed for bt<->xmt*/\n\t\tcase 2:\n\t\tcase 3:\n\t\t/*allowed for svg->lsr**/\n\t\tcase 4:\n\t\t/*allowed for swf->bt, swf->xmt, swf->svg*/\n\t\tcase 5:\n\t\t\tbreak;\n\t\t/*used for .saf / .lsr dump*/\n\t\tcase 6:\n#ifndef GPAC_DISABLE_SCENE_DUMP\n\t\t\tif ((dump_mode==GF_SM_DUMP_LASER) || (dump_mode==GF_SM_DUMP_SVG)) {\n\t\t\t\tbreak;\n\t\t\t}\n#endif\n\n\t\tdefault:\n\t\t\tif (!open_edit && file_exists && !gf_isom_probe_file(inName) && track_dump_type) {\n\t\t\t}\n#ifndef GPAC_DISABLE_ISOM_WRITE\n\t\t\telse if (!open_edit && file_exists /* && !gf_isom_probe_file(inName) */\n#ifndef GPAC_DISABLE_SCENE_DUMP\n\t\t\t && dump_mode == GF_SM_DUMP_NONE\n#endif //GPAC_DISABLE_SCENE_DUMP\n\t\t\t ) {\n\t\t\t\t/*************************************************************************************************/\n#ifndef GPAC_DISABLE_MEDIA_IMPORT\n\t\t\t\tif(dvbhdemux)\n\t\t\t\t{\n\t\t\t\t\tGF_MediaImporter import;\n\t\t\t\t\tfile = gf_isom_open(\"ttxt_convert\", GF_ISOM_OPEN_WRITE, NULL);\n\t\t\t\t\tmemset(&import, 0, sizeof(GF_MediaImporter));\n\t\t\t\t\timport.dest = file;\n\t\t\t\t\timport.in_name = inName;\n\t\t\t\t\timport.flags = GF_IMPORT_MPE_DEMUX;\n\t\t\t\t\te = gf_media_import(&import);\n\t\t\t\t\tif (e) {\n\t\t\t\t\t\tfprintf(stderr, \"Error importing %s: %s\\n\", inName, gf_error_to_string(e));\n\t\t\t\t\t\tgf_isom_delete(file);\n\t\t\t\t\t\tgf_file_delete(\"ttxt_convert\");\n\t\t\t\t\t\treturn mp4box_cleanup(1);\n\t\t\t\t\t}\n\t\t\t\t}\n#endif /*GPAC_DISABLE_MEDIA_IMPORT*/\n\n\t\t\t\tif (dump_m2ts) {\n#ifndef GPAC_DISABLE_MPEG2TS\n\t\t\t\t\tdump_mpeg2_ts(inName, pes_dump, program_number);\n#endif\n\t\t\t\t} else if (dump_timestamps) {\n#ifndef GPAC_DISABLE_MPEG2TS\n\t\t\t\t\tdump_mpeg2_ts(inName, pes_dump, program_number);\n#endif\n#ifndef GPAC_DISABLE_CORE_TOOLS\n\t\t\t\t} else if (do_bin_xml) {\n\t\t\t\t\txml_bs_to_bin(inName, outName, dump_std);\n#endif\n\t\t\t\t} else if (do_hash) {\n\t\t\t\t\thash_file(inName, dump_std);\n\t\t\t\t} else if (print_info) {\n#ifndef GPAC_DISABLE_MEDIA_IMPORT\n\t\t\t\t\tconvert_file_info(inName, info_track_id);\n#endif\n\t\t\t\t} else {\n\t\t\t\t\tfprintf(stderr, \"Input %s is not an MP4 file, operation not allowed\\n\", inName);\n\t\t\t\t\treturn mp4box_cleanup(1);\n\t\t\t\t}\n\t\t\t\tgoto exit;\n\t\t\t}\n#endif /*GPAC_DISABLE_ISOM_WRITE*/\n\t\t\telse if (open_edit) {\n\t\t\t\tfile = gf_isom_open(inName, GF_ISOM_WRITE_EDIT, tmpdir);\n\t\t\t\tif (!outName && file) outName = inName;\n\t\t\t} else if (!file_exists) {\n\t\t\t\tfprintf(stderr, \"Error creating file %s: %s\\n\", inName, gf_error_to_string(GF_URL_ERROR));\n\t\t\t\treturn mp4box_cleanup(1);\n\t\t\t} else {\n\t\t\t\tfprintf(stderr, \"Cannot open %s - extension not supported\\n\", inName);\n\t\t\t\treturn mp4box_cleanup(1);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (high_dynamc_range_filename) {\n\t\te = parse_high_dynamc_range_xml_desc(file, high_dynamc_range_filename);\n\t\tif (e) goto err_exit;\n\t}\n\n\tif (file && keep_utc && open_edit) {\n\t\tgf_isom_keep_utc_times(file, 1);\n\t}\n\n\tstrcpy(outfile, outName ? outName : inName);\n\t{\n\n\t\tchar *szExt = gf_file_ext_start(outfile);\n\n\t\tif (szExt)\n\t\t{\n\t\t\t/*turn on 3GP saving*/\n\t\t\tif (!stricmp(szExt, \".3gp\") || !stricmp(szExt, \".3gpp\") || !stricmp(szExt, \".3g2\"))\n\t\t\t\tconv_type = GF_ISOM_CONV_TYPE_3GPP;\n\t\t\telse if (!stricmp(szExt, \".m4a\") || !stricmp(szExt, \".m4v\"))\n\t\t\t\tconv_type = GF_ISOM_CONV_TYPE_IPOD;\n\t\t\telse if (!stricmp(szExt, \".psp\"))\n\t\t\t\tconv_type = GF_ISOM_CONV_TYPE_PSP;\n\t\t\telse if (!stricmp(szExt, \".mov\") || !stricmp(szExt, \".qt\"))\n\t\t\t\tconv_type = GF_ISOM_CONV_TYPE_MOV;\n\n\t\t\t//remove extension from outfile\n\t\t\t*szExt = 0;\n\t\t}\n\t}\n\n#ifndef GPAC_DISABLE_MEDIA_EXPORT\n\tif (track_dump_type & GF_EXPORT_AVI_NATIVE) {\n\t\tchar szFile[GF_MAX_PATH+24];\n\t\tGF_MediaExporter mdump;\n\t\tmemset(&mdump, 0, sizeof(mdump));\n\t\tmdump.in_name = inName;\n\t\tmdump.flags = GF_EXPORT_AVI_NATIVE;\n\t\tmdump.trackID = trackID;\n\t\tif (dump_std) {\n\t\t\tmdump.out_name = \"std\";\n\t\t} else if (outName) {\n\t\t\tmdump.out_name = outName;\n\t\t} else if (trackID>2) {\n\t\t\tsprintf(szFile, \"%s_audio%d\", outfile, trackID-1);\n\t\t\tmdump.out_name = szFile;\n\t\t} else {\n\t\t\tsprintf(szFile, \"%s_%s\", outfile, (trackID==1) ? \"video\" : \"audio\");\n\t\t\tmdump.out_name = szFile;\n\t\t}\n\n\t\tmdump.print_stats_graph = fs_dump_flags;\n\t\te = gf_media_export(&mdump);\n\t\tif (e) goto err_exit;\n\t\tgoto exit;\n\t}\n\tif (!open_edit && track_dump_type && !gf_isom_probe_file(inName)) {\n\t\tGF_MediaExporter mdump;\n\t\tchar szFile[GF_MAX_PATH+24];\n\t\tfor (i=0; iact_type != TRAC_ACTION_RAW_EXTRACT) continue;\n\t\t\tmemset(&mdump, 0, sizeof(mdump));\n\t\t\tmdump.in_name = inName;\n\t\t\tmdump.flags = tka->dump_type;\n\t\t\tmdump.trackID = tka->trackID;\n\t\t\tmdump.sample_num = tka->sample_num;\n\t\t\tif (outName) {\n\t\t\t\tmdump.out_name = outName;\n\t\t\t\tmdump.flags |= GF_EXPORT_MERGE;\n\t\t\t} else if (nb_track_act>1) {\n\t\t\t\tsprintf(szFile, \"%s_track%d\", outfile, mdump.trackID);\n\t\t\t\tmdump.out_name = szFile;\n\t\t\t} else {\n\t\t\t\tmdump.out_name = outfile;\n\t\t\t}\n\t\t\tmdump.print_stats_graph = fs_dump_flags;\n\t\t\te = gf_media_export(&mdump);\n\t\t\tif (e) goto err_exit;\n\t\t}\n\t\tgoto exit;\n\t}\n\n#endif /*GPAC_DISABLE_MEDIA_EXPORT*/\n\n#ifndef GPAC_DISABLE_SCENE_DUMP\n\tif (dump_mode != GF_SM_DUMP_NONE) {\n\t\te = dump_isom_scene(inName, dump_std ? NULL : (outName ? outName : outfile), outName ? GF_TRUE : GF_FALSE, dump_mode, do_scene_log, no_odf_conf);\n\t\tif (e) goto err_exit;\n\t}\n#endif\n\n#ifndef GPAC_DISABLE_SCENE_STATS\n\tif (stat_level) dump_isom_scene_stats(inName, dump_std ? NULL : (outName ? outName : outfile), outName ? GF_TRUE : GF_FALSE, stat_level);\n#endif\n\n#ifndef GPAC_DISABLE_ISOM_HINTING\n\tif (!HintIt && print_sdp) dump_isom_sdp(file, dump_std ? NULL : (outName ? outName : outfile), outName ? GF_TRUE : GF_FALSE);\n#endif\n\tif (get_nb_tracks) {\n\t\tfprintf(stdout, \"%d\\n\", gf_isom_get_track_count(file));\n\t}\n\tif (print_info) {\n\t\tif (!file) {\n\t\t\tfprintf(stderr, \"Cannot print info on a non ISOM file (%s)\\n\", inName);\n\t\t} else {\n\t\t\tif (info_track_id) DumpTrackInfo(file, info_track_id, 1, (print_info==2) ? GF_TRUE : GF_FALSE);\n\t\t\telse DumpMovieInfo(file);\n\t\t}\n\t}\n#ifndef GPAC_DISABLE_ISOM_DUMP\n\tif (dump_isom) {\n\t\te = dump_isom_xml(file, dump_std ? NULL : (outName ? outName : outfile), outName ? GF_TRUE : GF_FALSE, (dump_isom==2) ? GF_TRUE : GF_FALSE, merge_vtt_cues, use_init_seg ? GF_TRUE : GF_FALSE, (dump_isom==3) ? GF_TRUE : GF_FALSE);\n\t\tif (e) goto err_exit;\n\t}\n\tif (dump_cr) dump_isom_ismacryp(file, dump_std ? NULL : (outName ? outName : outfile), outName ? GF_TRUE : GF_FALSE);\n\tif ((dump_ttxt || dump_srt) && trackID) {\n\n\t\tif (trackID == (u32)-1) {\n\t\t\tfor (j=0; jact_type != TRAC_ACTION_RAW_EXTRACT) continue;\n\t\t\tmemset(&mdump, 0, sizeof(mdump));\n\t\t\tmdump.file = file;\n\t\t\tmdump.flags = tka->dump_type;\n\t\t\tmdump.trackID = tka->trackID;\n\t\t\tmdump.sample_num = tka->sample_num;\n\t\t\tif (tka->out_name) {\n\t\t\t\tmdump.out_name = tka->out_name;\n\t\t\t} else if (outName) {\n\t\t\t\tmdump.out_name = outName;\n\t\t\t\tmdump.flags |= GF_EXPORT_MERGE;\n\t\t\t\t/*don't infer extension on user-given filename*/\n\t\t\t\tmdump.flags |= GF_EXPORT_NO_FILE_EXT;\n\t\t\t} else if (mdump.trackID) {\n\t\t\t\tsprintf(szFile, \"%s_track%d\", outfile, mdump.trackID);\n\t\t\t\tmdump.out_name = szFile;\n\t\t\t} else {\n\t\t\t\tsprintf(szFile, \"%s_export\", outfile);\n\t\t\t\tmdump.out_name = szFile;\n\t\t\t}\n\t\t\tif (tka->trackID==(u32) -1) {\n\t\t\t\tfor (j=0; jtrackID) tk = gf_isom_get_track_by_id(file, meta->trackID);\n\n\t\tswitch (meta->act_type) {\n#ifndef GPAC_DISABLE_ISOM_WRITE\n\t\tcase META_ACTION_SET_TYPE:\n\t\t\t/*note: we don't handle file brand modification, this is an author stuff and cannot be guessed from meta type*/\n\t\t\te = gf_isom_set_meta_type(file, meta->root_meta, tk, meta->meta_4cc);\n\t\t\tgf_isom_modify_alternate_brand(file, GF_ISOM_BRAND_ISO2, GF_TRUE);\n\t\t\tneedSave = GF_TRUE;\n\t\t\tbreak;\n\t\tcase META_ACTION_ADD_ITEM:\n\t\t\tself_ref = !stricmp(meta->szPath, \"NULL\") || !stricmp(meta->szPath, \"this\") || !stricmp(meta->szPath, \"self\");\n\t\t\te = gf_isom_add_meta_item(file, meta->root_meta, tk, self_ref, self_ref ? NULL : meta->szPath,\n\t\t\t meta->szName,\n\t\t\t meta->item_id,\n\t\t\t\t\t\t\t\t\t meta->item_type,\n\t\t\t meta->mime_type,\n\t\t\t meta->enc_type,\n\t\t\t meta->use_dref ? meta->szPath : NULL, NULL,\n\t\t\t meta->image_props);\n\t\t\tif (meta->ref_type) {\n\t\t\t\te = gf_isom_meta_add_item_ref(file, meta->root_meta, tk, meta->item_id, meta->ref_item_id, meta->ref_type, NULL);\n\t\t\t}\n\t\t\tneedSave = GF_TRUE;\n\t\t\tbreak;\n\t\tcase META_ACTION_ADD_IMAGE_ITEM:\n\t\t{\n\t\t\tu32 old_tk_count = gf_isom_get_track_count(file);\n\t\t\tGF_Fraction _frac = {0,0};\n\t\t\te = import_file(file, meta->szPath, 0, _frac, 0, NULL, NULL, 0);\n\t\t\tif (e == GF_OK) {\n\t\t\t\tu32 meta_type = gf_isom_get_meta_type(file, meta->root_meta, tk);\n\t\t\t\tif (!meta_type) {\n\t\t\t\t\te = gf_isom_set_meta_type(file, meta->root_meta, tk, GF_META_ITEM_TYPE_PICT);\n\t\t\t\t} else {\n\t\t\t\t\tif (meta_type != GF_META_ITEM_TYPE_PICT) {\n\t\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"Warning: file already has a root 'meta' box of type %s\\n\", gf_4cc_to_str(meta_type)));\n\t\t\t\t\t\te = GF_BAD_PARAM;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (e == GF_OK) {\n\t\t\t\t\tif (!meta->item_id) {\n\t\t\t\t\t\te = gf_isom_meta_get_next_item_id(file, meta->root_meta, tk, &meta->item_id);\n\t\t\t\t\t}\n\t\t\t\t\tif (e == GF_OK) {\n\t\t\t\t\t\te = gf_isom_iff_create_image_item_from_track(file, meta->root_meta, tk, 1,\n\t\t\t\t\t\t\t\tmeta->szName,\n\t\t\t\t\t\t\t\tmeta->item_id,\n\t\t\t\t\t\t\t\tmeta->image_props, NULL);\n\t\t\t\t\t\tif (e == GF_OK && meta->primary) {\n\t\t\t\t\t\t\te = gf_isom_set_meta_primary_item(file, meta->root_meta, tk, meta->item_id);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (e == GF_OK && meta->ref_type) {\n\t\t\t\t\t\t\te = gf_isom_meta_add_item_ref(file, meta->root_meta, tk, meta->item_id, meta->ref_item_id, meta->ref_type, NULL);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tgf_isom_remove_track(file, old_tk_count+1);\n\t\t\tneedSave = GF_TRUE;\n\t\t}\n\t\t\tbreak;\n\t\tcase META_ACTION_REM_ITEM:\n\t\t\te = gf_isom_remove_meta_item(file, meta->root_meta, tk, meta->item_id);\n\t\t\tneedSave = GF_TRUE;\n\t\t\tbreak;\n\t\tcase META_ACTION_SET_PRIMARY_ITEM:\n\t\t\te = gf_isom_set_meta_primary_item(file, meta->root_meta, tk, meta->item_id);\n\t\t\tneedSave = GF_TRUE;\n\t\t\tbreak;\n\t\tcase META_ACTION_SET_XML:\n\t\tcase META_ACTION_SET_BINARY_XML:\n\t\t\te = gf_isom_set_meta_xml(file, meta->root_meta, tk, meta->szPath, NULL, 0, (meta->act_type==META_ACTION_SET_BINARY_XML) ? 1 : 0);\n\t\t\tneedSave = GF_TRUE;\n\t\t\tbreak;\n\t\tcase META_ACTION_REM_XML:\n\t\t\tif (gf_isom_get_meta_item_count(file, meta->root_meta, tk)) {\n\t\t\t\te = gf_isom_remove_meta_xml(file, meta->root_meta, tk);\n\t\t\t\tneedSave = GF_TRUE;\n\t\t\t} else {\n\t\t\t\tfprintf(stderr, \"No meta box in input file\\n\");\n\t\t\t}\n\t\t\tbreak;\n\t\tcase META_ACTION_DUMP_ITEM:\n\t\t\tif (gf_isom_get_meta_item_count(file, meta->root_meta, tk)) {\n\t\t\t\te = gf_isom_extract_meta_item(file, meta->root_meta, tk, meta->item_id, strlen(meta->szPath) ? meta->szPath : NULL);\n\t\t\t} else {\n\t\t\t\tfprintf(stderr, \"No meta box in input file\\n\");\n\t\t\t}\n\t\t\tbreak;\n#endif // GPAC_DISABLE_ISOM_WRITE\n\n\t\tcase META_ACTION_DUMP_XML:\n\t\t\tif (gf_isom_has_meta_xml(file, meta->root_meta, tk)) {\n\t\t\t\te = gf_isom_extract_meta_xml(file, meta->root_meta, tk, meta->szPath, NULL);\n\t\t\t} else {\n\t\t\t\tfprintf(stderr, \"No meta box in input file\\n\");\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t\tif (meta->image_props) {\n\t\t\tgf_free(meta->image_props);\n\t\t\tmeta->image_props = NULL;\n\t\t}\n\t\tif (e) goto err_exit;\n\t}\n\tif (!open_edit && !needSave) {\n\t\tif (file) gf_isom_delete(file);\n\t\tgoto exit;\n\t}\n\n\n#ifndef GPAC_DISABLE_ISOM_WRITE\n\tif (clean_groups) {\n\t\te = gf_isom_reset_switch_parameters(file);\n\t\tif (e) goto err_exit;\n\t\tneedSave = GF_TRUE;\n\t}\n\n\tfor (i=0; i0) {\n\t\t\t\t\t\t\t\tu32 tk, k;\n\t\t\t\t\t\t\t\tfor (k=0; k<(u32) count; k++) {\n\t\t\t\t\t\t\t\t\tgf_isom_get_reference(file, j+1, GF_ISOM_REF_CHAP, k+1, &tk);\n\t\t\t\t\t\t\t\t\tif (tk==i+1) {\n\t\t\t\t\t\t\t\t\t\tis_chap = 1;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (is_chap) break;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (is_chap) break;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t/*this is a subtitle track*/\n\t\t\t\t\t\tif (!is_chap)\n\t\t\t\t\t\t\tgf_isom_set_media_type(file, i+1, GF_ISOM_MEDIA_SUBT);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tgf_isom_set_brand_info(file, ipod_major_brand, 1);\n\t\t\tgf_isom_modify_alternate_brand(file, GF_ISOM_BRAND_MP42, GF_TRUE);\n\t\t\tneedSave = GF_TRUE;\n\t\t}\n\n\t} else if (outName) {\n\t\tstrcpy(outfile, outName);\n\t}\n\n\tfor (j=0; jtrackID ? gf_isom_get_track_by_id(file, tka->trackID) : 0;\n\n\t\ttimescale = gf_isom_get_timescale(file);\n\t\tswitch (tka->act_type) {\n\t\tcase TRAC_ACTION_REM_TRACK:\n\t\t\te = gf_isom_remove_track(file, track);\n\t\t\tif (e) {\n\t\t\t\tfprintf(stderr, \"Error Removing track ID %d: %s\\n\", tka->trackID, gf_error_to_string(e));\n\t\t\t} else {\n\t\t\t\tfprintf(stderr, \"Removing track ID %d\\n\", tka->trackID);\n\t\t\t}\n\t\t\tneedSave = GF_TRUE;\n\t\t\tbreak;\n\t\tcase TRAC_ACTION_SET_LANGUAGE:\n\t\t\tfor (i=0; ilang);\n\t\t\t\tif (e) goto err_exit;\n\t\t\t\tneedSave = GF_TRUE;\n\t\t\t}\n\t\t\tneedSave = GF_TRUE;\n\t\t\tbreak;\n\t\tcase TRAC_ACTION_SET_KIND:\n\t\t\tfor (i=0; ikind_scheme, tka->kind_value);\n\t\t\t\tif (e) goto err_exit;\n\t\t\t\tneedSave = GF_TRUE;\n\t\t\t}\n\t\t\tneedSave = GF_TRUE;\n\t\t\tbreak;\n\t\tcase TRAC_ACTION_REM_KIND:\n\t\t\tfor (i=0; ikind_scheme, tka->kind_value);\n\t\t\t\tif (e) goto err_exit;\n\t\t\t\tneedSave = GF_TRUE;\n\t\t\t}\n\t\t\tneedSave = GF_TRUE;\n\t\t\tbreak;\n\t\tcase TRAC_ACTION_SET_DELAY:\n\t\t\tif (tka->delay_ms) {\n\t\t\t\tu64 tk_dur;\n\n\t\t\t\tgf_isom_remove_edits(file, track);\n\t\t\t\ttk_dur = gf_isom_get_track_duration(file, track);\n\t\t\t\tif (gf_isom_get_edits_count(file, track))\n\t\t\t\t\tneedSave = GF_TRUE;\n\t\t\t\tif (tka->delay_ms>0) {\n\t\t\t\t\tgf_isom_append_edit(file, track, (timescale*tka->delay_ms)/1000, 0, GF_ISOM_EDIT_EMPTY);\n\t\t\t\t\tgf_isom_append_edit(file, track, tk_dur, 0, GF_ISOM_EDIT_NORMAL);\n\t\t\t\t\tneedSave = GF_TRUE;\n\t\t\t\t} else {\n\t\t\t\t\tu64 to_skip = (timescale*(-tka->delay_ms))/1000;\n\t\t\t\t\tif (to_skipdelay_ms)*gf_isom_get_media_timescale(file, track) / 1000;\n\t\t\t\t\t\tgf_isom_append_edit(file, track, tk_dur-to_skip, media_time, GF_ISOM_EDIT_NORMAL);\n\t\t\t\t\t\tneedSave = GF_TRUE;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfprintf(stderr, \"Warning: request negative delay longer than track duration - ignoring\\n\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (gf_isom_get_edits_count(file, track)) {\n\t\t\t\tgf_isom_remove_edits(file, track);\n\t\t\t\tneedSave = GF_TRUE;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase TRAC_ACTION_SET_KMS_URI:\n\t\t\tfor (i=0; ikms);\n\t\t\t\tif (e) goto err_exit;\n\t\t\t\tneedSave = GF_TRUE;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase TRAC_ACTION_SET_ID:\n\t\t\tif (!tka->trackID && (gf_isom_get_track_count(file) == 1)) {\n\t\t\t\tfprintf(stderr, \"Warning: track id is not specified, but file has only one track - assume that you want to change id for this track\\n\");\n\t\t\t\ttrack = 1;\n\t\t\t}\n\t\t\tif (track) {\n\t\t\t\tu32 newTrack;\n\t\t\t\tnewTrack = gf_isom_get_track_by_id(file, tka->newTrackID);\n\t\t\t\tif (newTrack != 0) {\n\t\t\t\t\tfprintf(stderr, \"Error: Cannot set track id with value %d because a track already exists - ignoring\", tka->newTrackID);\n\t\t\t\t} else {\n\t\t\t\t\te = gf_isom_set_track_id(file, track, tka->newTrackID);\n\t\t\t\t\tneedSave = GF_TRUE;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfprintf(stderr, \"Error: Cannot change id for track %d because it does not exist - ignoring\", tka->trackID);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase TRAC_ACTION_SWAP_ID:\n\t\t\tif (track) {\n\t\t\t\tu32 tk1, tk2;\n\t\t\t\ttk1 = gf_isom_get_track_by_id(file, tka->trackID);\n\t\t\t\ttk2 = gf_isom_get_track_by_id(file, tka->newTrackID);\n\t\t\t\tif (!tk1 || !tk2) {\n\t\t\t\t\tfprintf(stderr, \"Error: Cannot swap track IDs because not existing - ignoring\");\n\t\t\t\t} else {\n\t\t\t\t\te = gf_isom_set_track_id(file, tk2, 0);\n\t\t\t\t\tif (!e) e = gf_isom_set_track_id(file, tk1, tka->newTrackID);\n\t\t\t\t\tif (!e) e = gf_isom_set_track_id(file, tk2, tka->trackID);\n\t\t\t\t\tneedSave = GF_TRUE;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfprintf(stderr, \"Error: Cannot change id for track %d because it does not exist - ignoring\", tka->trackID);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase TRAC_ACTION_SET_PAR:\n\t\t\te = gf_media_change_par(file, track, tka->par_num, tka->par_den, tka->force_par, tka->rewrite_bs);\n\t\t\tneedSave = GF_TRUE;\n\t\t\tbreak;\n\t\tcase TRAC_ACTION_SET_CLAP:\n\t\t\te = gf_isom_set_clean_aperture(file, track, 1, tka->clap_wnum, tka->clap_wden, tka->clap_hnum, tka->clap_hden, tka->clap_honum, tka->clap_hoden, tka->clap_vonum, tka->clap_voden);\n\t\t\tneedSave = GF_TRUE;\n\t\t\tbreak;\n\t\tcase TRAC_ACTION_SET_MX:\n\t\t\te = gf_isom_set_track_matrix(file, track, tka->mx);\n\t\t\tneedSave = GF_TRUE;\n\t\t\tbreak;\n\t\tcase TRAC_ACTION_SET_HANDLER_NAME:\n\t\t\te = gf_isom_set_handler_name(file, track, tka->hdl_name);\n\t\t\tneedSave = GF_TRUE;\n\t\t\tbreak;\n\t\tcase TRAC_ACTION_ENABLE:\n\t\t\tif (!gf_isom_is_track_enabled(file, track)) {\n\t\t\t\te = gf_isom_set_track_enabled(file, track, GF_TRUE);\n\t\t\t\tneedSave = GF_TRUE;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase TRAC_ACTION_DISABLE:\n\t\t\tif (gf_isom_is_track_enabled(file, track)) {\n\t\t\t\te = gf_isom_set_track_enabled(file, track, GF_FALSE);\n\t\t\t\tneedSave = GF_TRUE;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase TRAC_ACTION_REFERENCE:\n\t\t\te = gf_isom_set_track_reference(file, track, GF_4CC(tka->lang[0], tka->lang[1], tka->lang[2], tka->lang[3]), (u32) tka->delay_ms);\n\t\t\tneedSave = GF_TRUE;\n\t\t\tbreak;\n\t\tcase TRAC_ACTION_REM_NON_RAP:\n\t\t\tfprintf(stderr, \"Removing non-rap samples from track %d\\n\", tka->trackID);\n\t\t\te = gf_media_remove_non_rap(file, track, GF_FALSE);\n\t\t\tneedSave = GF_TRUE;\n\t\t\tbreak;\n\t\tcase TRAC_ACTION_REM_NON_REFS:\n\t\t\tfprintf(stderr, \"Removing non-reference samples from track %d\\n\", tka->trackID);\n\t\t\te = gf_media_remove_non_rap(file, track, GF_TRUE);\n\t\t\tneedSave = GF_TRUE;\n\t\t\tbreak;\n\t\tcase TRAC_ACTION_SET_UDTA:\n\t\t\tfprintf(stderr, \"Assigning udta box\\n\");\n\t\t\te = set_file_udta(file, track, tka->udta_type, tka->src_name, tka->sample_num ? GF_TRUE : GF_FALSE);\n\t\t\tif (e) goto err_exit;\n\t\t\tneedSave = GF_TRUE;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t\tif (e) goto err_exit;\n\t}\n\n\tif (itunes_tags) {\n\t\tchar *tags = itunes_tags;\n\n\t\twhile (tags) {\n\t\t\tchar *val;\n\t\t\tchar *sep = gf_url_colon_suffix(tags);\n\t\t\tu32 tlen, itag = 0;\n\t\t\tif (sep) {\n\t\t\t\twhile (sep) {\n\t\t\t\t\tfor (itag=0; itag> 8;\n\t\t\t\t\t\t_t[5] = t;\n\t\t\t\t\t\t_t[4] = t >> 8;\n\t\t\t\t\t}\n\t\t\t\t\telse if (sscanf(val, \"%u\", &n) == 1) {\n\t\t\t\t\t\t_t[3] = n;\n\t\t\t\t\t\t_t[2] = n >> 8;\n\t\t\t\t\t}\n\t\t\t\t\telse tlen = 0;\n\t\t\t\t}\n\t\t\t\tif (!val || tlen) gf_isom_apple_set_tag(file, itag, val ? (u8 *)_t : NULL, tlen);\n\t\t\t}\n\t\t\tbreak;\n\t\t\tcase GF_ISOM_ITUNE_GAPLESS:\n\t\t\tcase GF_ISOM_ITUNE_COMPILATION:\n\t\t\t{\n\t\t\t\tu8 _t[1];\n\t\t\t\tif (val && !stricmp(val, \"yes\")) _t[0] = 1;\n\t\t\t\telse _t[0] = 0;\n\t\t\t\tgf_isom_apple_set_tag(file, itag, _t, 1);\n\t\t\t}\n\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tgf_isom_apple_set_tag(file, itag, (u8 *)val, tlen);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tneedSave = GF_TRUE;\n\n\t\t\tif (sep) {\n\t\t\t\tsep[0] = ':';\n\t\t\t\ttags = sep+1;\n\t\t\t} else {\n\t\t\t\ttags = NULL;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (movie_time) {\n\t\tgf_isom_set_creation_time(file, movie_time);\n\t\tfor (i=0; i \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'fixed #1565'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool Helper::getPartitionSizeInfo(const QString &partDevice, qint64 *used, qint64 *free, int *blockSize)\n{\n QProcess process;\n QStringList env_list = QProcess::systemEnvironment();\n\n env_list.append(\"LANG=C\");\n process.setEnvironment(env_list);\n\n if (Helper::isMounted(partDevice)) {\n process.start(QString(\"df -B1 -P %1\").arg(partDevice));\n process.waitForFinished();\n\n if (process.exitCode() != 0) {\n dCError(\"Call df failed: %s\", qPrintable(process.readAllStandardError()));\n\n return false;\n }\n\n QByteArray output = process.readAll();\n const QByteArrayList &lines = output.trimmed().split('\\n');\n\n if (lines.count() != 2)\n return false;\n\n output = lines.last().simplified();\n\n const QByteArrayList &values = output.split(' ');\n\n if (values.count() != 6)\n return false;\n\n bool ok = false;\n\n if (used)\n *used = values.at(2).toLongLong(&ok);\n\n if (!ok)\n return false;\n\n if (free)\n *free = values.at(3).toLongLong(&ok);\n\n if (!ok)\n return false;\n\n return true;\n } else {\n process.start(QString(\"%1 -s %2 -c -q -C -L /tmp/partclone.log\").arg(getPartcloneExecuter(DDevicePartInfo(partDevice))).arg(partDevice));\n process.setStandardOutputFile(\"/dev/null\");\n process.setReadChannel(QProcess::StandardError);\n process.waitForStarted();\n\n qint64 used_block = -1;\n qint64 free_block = -1;\n\n while (process.waitForReadyRead(5000)) {\n const QByteArray &data = process.readAll();\n\n for (QByteArray line : data.split('\\n')) {\n line = line.simplified();\n\n if (QString::fromLatin1(line).contains(QRegularExpression(\"\\\\berror\\\\b\"))) {\n dCError(\"Call \\\"%s %s\\\" failed: \\\"%s\\\"\", qPrintable(process.program()), qPrintable(process.arguments().join(' ')), line.constData());\n }\n\n if (line.startsWith(\"Space in use:\")) {\n bool ok = false;\n const QByteArray &value = line.split(' ').value(6, \"-1\");\n\n used_block = value.toLongLong(&ok);\n\n if (!ok) {\n dCError(\"String to LongLong failed, String: %s\", value.constData());\n\n return false;\n }\n } else if (line.startsWith(\"Free Space:\")) {\n bool ok = false;\n const QByteArray &value = line.split(' ').value(5, \"-1\");\n\n free_block = value.toLongLong(&ok);\n\n if (!ok) {\n dCError(\"String to LongLong failed, String: %s\", value.constData());\n\n return false;\n }\n } else if (line.startsWith(\"Block size:\")) {\n bool ok = false;\n const QByteArray &value = line.split(' ').value(2, \"-1\");\n\n int block_size = value.toInt(&ok);\n\n if (!ok) {\n dCError(\"String to Int failed, String: %s\", value.constData());\n\n return false;\n }\n\n if (used_block < 0 || free_block < 0 || block_size < 0)\n return false;\n\n if (used)\n *used = used_block * block_size;\n\n if (free)\n *free = free_block * block_size;\n\n if (blockSize)\n *blockSize = block_size;\n\n process.terminate();\n process.waitForFinished();\n\n return true;\n }\n }\n }\n }\n\n return false;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'fix: Do not use the \"/tmp\" directory\n\nhttps://github.com/linuxdeepin/deepin-clone/issues/16\nhttps://bugzilla.opensuse.org/show_bug.cgi?id=1130388'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int rtp_packetize_xiph_config( sout_stream_id_sys_t *id, const char *fmtp,\n int64_t i_pts )\n{\n if (fmtp == NULL)\n return VLC_EGENERIC;\n\n /* extract base64 configuration from fmtp */\n char *start = strstr(fmtp, \"configuration=\");\n assert(start != NULL);\n start += sizeof(\"configuration=\") - 1;\n char *end = strchr(start, ';');\n assert(end != NULL);\n size_t len = end - start;\n char b64[len + 1];\n memcpy(b64, start, len);\n b64[len] = '\\0';\n\n int i_max = rtp_mtu (id) - 6; /* payload max in one packet */\n\n uint8_t *p_orig, *p_data;\n int i_data;\n\n i_data = vlc_b64_decode_binary(&p_orig, b64);\n if (i_data <= 9)\n {\n free(p_orig);\n return VLC_EGENERIC;\n }\n p_data = p_orig + 9;\n i_data -= 9;\n\n int i_count = ( i_data + i_max - 1 ) / i_max;\n\n for( int i = 0; i < i_count; i++ )\n {\n int i_payload = __MIN( i_max, i_data );\n block_t *out = block_Alloc( 18 + i_payload );\n\n unsigned fragtype, numpkts;\n if (i_count == 1)\n {\n fragtype = 0;\n numpkts = 1;\n }\n else\n {\n numpkts = 0;\n if (i == 0)\n fragtype = 1;\n else if (i == i_count - 1)\n fragtype = 3;\n else\n fragtype = 2;\n }\n /* Ident:24, Fragment type:2, Vorbis/Theora Data Type:2, # of pkts:4 */\n uint32_t header = ((XIPH_IDENT & 0xffffff) << 8) |\n (fragtype << 6) | (1 << 4) | numpkts;\n\n /* rtp common header */\n rtp_packetize_common( id, out, 0, i_pts );\n\n SetDWBE( out->p_buffer + 12, header);\n SetWBE( out->p_buffer + 16, i_payload);\n memcpy( &out->p_buffer[18], p_data, i_payload );\n\n out->i_dts = i_pts;\n\n rtp_packetize_send( id, out );\n\n p_data += i_payload;\n i_data -= i_payload;\n }\n\n free(p_orig);\n\n return VLC_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'stream_out: rtp: don't use VLA for user controlled data\n\nIt should fix a possible invalid memory access\n\nWhen streaming ogg-files via rtp, an ogg-file can trigger an invalid\nwrite access using an overly long 'configuration' string.\n\nThe original code attemps to allocate space to hold the string on the stack\nand hence, cannot verify if allocation succeeds. Instead, we now allocate the\nbuffer on the heap and return if allocation fails.\n\nIn detail, rtp_packetize_xiph_config allocates a buffer on the stack at (1) where\nthe size depends on the local variable 'len'. The variable 'len' is\ncalculated at (0) to be the length of a string contained in a specially\ncrafted Ogg Vorbis file, and therefore, it is attacker-controlled.\n\nSigned-off-by: Jean-Baptiste Kempf '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: lldp_private_8021_print(netdissect_options *ndo,\n const u_char *tptr, u_int tlv_len)\n{\n int subtype, hexdump = FALSE;\n u_int sublen;\n u_int tval;\n uint8_t i;\n\n if (tlv_len < 4) {\n return hexdump;\n }\n subtype = *(tptr+3);\n\n ND_PRINT((ndo, \"\\n\\t %s Subtype (%u)\",\n tok2str(lldp_8021_subtype_values, \"unknown\", subtype),\n subtype));\n\n switch (subtype) {\n case LLDP_PRIVATE_8021_SUBTYPE_PORT_VLAN_ID:\n if (tlv_len < 6) {\n return hexdump;\n }\n ND_PRINT((ndo, \"\\n\\t port vlan id (PVID): %u\",\n EXTRACT_16BITS(tptr + 4)));\n break;\n case LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_VLAN_ID:\n if (tlv_len < 7) {\n return hexdump;\n }\n ND_PRINT((ndo, \"\\n\\t port and protocol vlan id (PPVID): %u, flags [%s] (0x%02x)\",\n EXTRACT_16BITS(tptr+5),\n\t bittok2str(lldp_8021_port_protocol_id_values, \"none\", *(tptr+4)),\n\t *(tptr + 4)));\n break;\n case LLDP_PRIVATE_8021_SUBTYPE_VLAN_NAME:\n if (tlv_len < 6) {\n return hexdump;\n }\n ND_PRINT((ndo, \"\\n\\t vlan id (VID): %u\", EXTRACT_16BITS(tptr + 4)));\n if (tlv_len < 7) {\n return hexdump;\n }\n sublen = *(tptr+6);\n if (tlv_len < 7+sublen) {\n return hexdump;\n }\n ND_PRINT((ndo, \"\\n\\t vlan name: \"));\n safeputs(ndo, tptr + 7, sublen);\n break;\n case LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_IDENTITY:\n if (tlv_len < 5) {\n return hexdump;\n }\n sublen = *(tptr+4);\n if (tlv_len < 5+sublen) {\n return hexdump;\n }\n ND_PRINT((ndo, \"\\n\\t protocol identity: \"));\n safeputs(ndo, tptr + 5, sublen);\n break;\n case LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION:\n if(tlv_len> i) & 0x01));\n tval=*(tptr+5);\n ND_PRINT((ndo, \"\\n\\t Pre-Priority Ready Indicator\"));\n ND_PRINT((ndo, \"\\n\\t Priority : 0 1 2 3 4 5 6 7\"));\n ND_PRINT((ndo, \"\\n\\t Value : \"));\n for(i=0;i> i) & 0x01));\n break;\n\n case LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION:\n if(tlv_len> 7, (tval >> 6) & 0x02, (tval >> 3) & 0x07, tval & 0x07));\n\n /*Print Priority Assignment Table*/\n print_ets_priority_assignment_table(ndo, tptr + 5);\n\n /*Print TC Bandwidth Table*/\n print_tc_bandwidth_table(ndo, tptr + 9);\n\n /* Print TSA Assignment Table */\n print_tsa_assignment_table(ndo, tptr + 17);\n\n break;\n\n case LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION:\n if(tlv_len> 7, (tval >> 6) & 0x01, (tval >> 4) & 0x03, (tval & 0x0f)));\n ND_PRINT((ndo, \"\\n\\t PFC Enable\"));\n tval=*(tptr+5);\n ND_PRINT((ndo, \"\\n\\t Priority : 0 1 2 3 4 5 6 7\"));\n ND_PRINT((ndo, \"\\n\\t Value : \"));\n for(i=0;i> i) & 0x01));\n break;\n\n case LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY:\n if(tlv_len> 5, (tval >> 3) & 0x03, (tval & 0x07)));\n \tND_PRINT((ndo, \"Protocol ID: %d\", EXTRACT_16BITS(tptr + i + 5)));\n \ti=i+3;\n }\n break;\n case LLDP_PRIVATE_8021_SUBTYPE_EVB:\n if(tlv_len> 3, (tval >> 2) & 0x01, (tval >> 1) & 0x01, tval & 0x01));\n ND_PRINT((ndo, \"\\n\\t EVB Station Status\"));\n tval=*(tptr+5);\n ND_PRINT((ndo, \"\\n\\t RES: %d, SGID: %d, RRREQ: %d,RRSTAT: %d\",\n \ttval >> 4, (tval >> 3) & 0x01, (tval >> 2) & 0x01, tval & 0x03));\n tval=*(tptr+6);\n ND_PRINT((ndo, \"\\n\\t R: %d, RTE: %d, \",tval >> 5, tval & 0x1f));\n tval=*(tptr+7);\n ND_PRINT((ndo, \"EVB Mode: %s [%d]\",\n \ttok2str(lldp_evb_mode_values, \"unknown\", tval >> 6), tval >> 6));\n ND_PRINT((ndo, \"\\n\\t ROL: %d, RWD: %d, \", (tval >> 5) & 0x01, tval & 0x1f));\n tval=*(tptr+8);\n ND_PRINT((ndo, \"RES: %d, ROL: %d, RKA: %d\", tval >> 6, (tval >> 5) & 0x01, tval & 0x1f));\n break;\n\n case LLDP_PRIVATE_8021_SUBTYPE_CDCP:\n if(tlv_len> 7, (tval >> 4) & 0x07, (tval >> 3) & 0x01));\n ND_PRINT((ndo, \"ChnCap: %d\", EXTRACT_16BITS(tptr + 6) & 0x0fff));\n sublen=tlv_len-8;\n if(sublen%3!=0) {\n \treturn hexdump;\n }\n i=0;\n while(i> 12, tval & 0x000fff));\n \ti=i+3;\n }\n break;\n\n default:\n hexdump = TRUE;\n break;\n }\n\n return hexdump;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399', 'CWE-835'], 'message': 'CVE-2017-12997/LLDP: Don't use an 8-bit loop counter.\n\nIf you have a\n\n\tfor (i = 0; i < N; i++)\n\nloop, you'd better make sure that i is big enough to hold N - not N-1,\nN.\n\nThe TLV length here is 9 bits long, not 8 bits long, so an 8-bit loop\ncounter will overflow and you can loop infinitely.\n\nThis fixes an infinite loop discovered by Forcepoint's security\nresearchers Otto Airamo & Antti Levom\u00e4ki.\n\nAdd tests using the capture files supplied by the reporter(s).\n\nClean up the output a bit while we're at it.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int __vcpu_run(struct kvm_vcpu *vcpu)\n{\n\tint r;\n\tstruct kvm *kvm = vcpu->kvm;\n\n\tvcpu->srcu_idx = srcu_read_lock(&kvm->srcu);\n\tr = vapic_enter(vcpu);\n\tif (r) {\n\t\tsrcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);\n\t\treturn r;\n\t}\n\n\tr = 1;\n\twhile (r > 0) {\n\t\tif (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&\n\t\t !vcpu->arch.apf.halted)\n\t\t\tr = vcpu_enter_guest(vcpu);\n\t\telse {\n\t\t\tsrcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);\n\t\t\tkvm_vcpu_block(vcpu);\n\t\t\tvcpu->srcu_idx = srcu_read_lock(&kvm->srcu);\n\t\t\tif (kvm_check_request(KVM_REQ_UNHALT, vcpu)) {\n\t\t\t\tkvm_apic_accept_events(vcpu);\n\t\t\t\tswitch(vcpu->arch.mp_state) {\n\t\t\t\tcase KVM_MP_STATE_HALTED:\n\t\t\t\t\tvcpu->arch.pv.pv_unhalted = false;\n\t\t\t\t\tvcpu->arch.mp_state =\n\t\t\t\t\t\tKVM_MP_STATE_RUNNABLE;\n\t\t\t\tcase KVM_MP_STATE_RUNNABLE:\n\t\t\t\t\tvcpu->arch.apf.halted = false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase KVM_MP_STATE_INIT_RECEIVED:\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tr = -EINTR;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (r <= 0)\n\t\t\tbreak;\n\n\t\tclear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);\n\t\tif (kvm_cpu_has_pending_timer(vcpu))\n\t\t\tkvm_inject_pending_timer_irqs(vcpu);\n\n\t\tif (dm_request_for_irq_injection(vcpu)) {\n\t\t\tr = -EINTR;\n\t\t\tvcpu->run->exit_reason = KVM_EXIT_INTR;\n\t\t\t++vcpu->stat.request_irq_exits;\n\t\t}\n\n\t\tkvm_check_async_pf_completion(vcpu);\n\n\t\tif (signal_pending(current)) {\n\t\t\tr = -EINTR;\n\t\t\tvcpu->run->exit_reason = KVM_EXIT_INTR;\n\t\t\t++vcpu->stat.signal_exits;\n\t\t}\n\t\tif (need_resched()) {\n\t\t\tsrcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);\n\t\t\tkvm_resched(vcpu);\n\t\t\tvcpu->srcu_idx = srcu_read_lock(&kvm->srcu);\n\t\t}\n\t}\n\n\tsrcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);\n\n\tvapic_exit(vcpu);\n\n\treturn r;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'KVM: x86: Convert vapic synchronization to _cached functions (CVE-2013-6368)\n\nIn kvm_lapic_sync_from_vapic and kvm_lapic_sync_to_vapic there is the\npotential to corrupt kernel memory if userspace provides an address that\nis at the end of a page. This patches concerts those functions to use\nkvm_write_guest_cached and kvm_read_guest_cached. It also checks the\nvapic_address specified by userspace during ioctl processing and returns\nan error to userspace if the address is not a valid GPA.\n\nThis is generally not guest triggerable, because the required write is\ndone by firmware that runs before the guest. Also, it only affects AMD\nprocessors and oldish Intel that do not have the FlexPriority feature\n(unless you disable FlexPriority, of course; then newer processors are\nalso affected).\n\nFixes: b93463aa59d6 ('KVM: Accelerated apic support')\n\nReported-by: Andrew Honig \nCc: stable@vger.kernel.org\nSigned-off-by: Andrew Honig \nSigned-off-by: Paolo Bonzini '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int wc_ecc_sign_hash_ex(const byte* in, word32 inlen, WC_RNG* rng,\n ecc_key* key, mp_int *r, mp_int *s)\n{\n int err;\n#ifndef WOLFSSL_SP_MATH\n mp_int* e;\n#if !defined(WOLFSSL_ASYNC_CRYPT) || !defined(HAVE_CAVIUM_V)\n mp_int e_lcl;\n#endif\n#endif /* !WOLFSSL_SP_MATH */\n\n DECLARE_CURVE_SPECS(1)\n\n if (in == NULL || r == NULL || s == NULL || key == NULL || rng == NULL)\n return ECC_BAD_ARG_E;\n\n /* is this a private key? */\n if (key->type != ECC_PRIVATEKEY && key->type != ECC_PRIVATEKEY_ONLY) {\n return ECC_BAD_ARG_E;\n }\n\n /* is the IDX valid ? */\n if (wc_ecc_is_valid_idx(key->idx) != 1) {\n return ECC_BAD_ARG_E;\n }\n\n#ifdef WOLFSSL_SP_MATH\n if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1)\n return sp_ecc_sign_256(in, inlen, rng, &key->k, r, s, key->heap);\n else\n return WC_KEY_SIZE_E;\n#else\n#ifdef WOLFSSL_HAVE_SP_ECC\n #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) && \\\n defined(WOLFSSL_ASYNC_CRYPT_TEST)\n if (key->asyncDev.marker != WOLFSSL_ASYNC_MARKER_ECC)\n #endif\n {\n#ifndef WOLFSSL_SP_NO_256\n if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1)\n return sp_ecc_sign_256(in, inlen, rng, &key->k, r, s, key->heap);\n#endif\n }\n#endif /* WOLFSSL_HAVE_SP_ECC */\n\n\n#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) && \\\n defined(WOLFSSL_ASYNC_CRYPT_TEST)\n if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) {\n if (wc_AsyncTestInit(&key->asyncDev, ASYNC_TEST_ECC_SIGN)) {\n WC_ASYNC_TEST* testDev = &key->asyncDev.test;\n testDev->eccSign.in = in;\n testDev->eccSign.inSz = inlen;\n testDev->eccSign.rng = rng;\n testDev->eccSign.key = key;\n testDev->eccSign.r = r;\n testDev->eccSign.s = s;\n return WC_PENDING_E;\n }\n }\n#endif\n\n#if defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_CAVIUM_V)\n err = wc_ecc_alloc_mpint(key, &key->e);\n if (err != 0)\n return err;\n e = key->e;\n#else\n e = &e_lcl;\n#endif\n\n /* get the hash and load it as a bignum into 'e' */\n /* init the bignums */\n if ((err = mp_init(e)) != MP_OKAY) {\n return err;\n }\n\n /* load curve info */\n err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ORDER);\n\n /* load digest into e */\n if (err == MP_OKAY) {\n /* we may need to truncate if hash is longer than key size */\n word32 orderBits = mp_count_bits(curve->order);\n\n /* truncate down to byte size, may be all that's needed */\n if ((WOLFSSL_BIT_SIZE * inlen) > orderBits)\n inlen = (orderBits + WOLFSSL_BIT_SIZE - 1) / WOLFSSL_BIT_SIZE;\n err = mp_read_unsigned_bin(e, (byte*)in, inlen);\n\n /* may still need bit truncation too */\n if (err == MP_OKAY && (WOLFSSL_BIT_SIZE * inlen) > orderBits)\n mp_rshb(e, WOLFSSL_BIT_SIZE - (orderBits & 0x7));\n }\n\n /* make up a key and export the public copy */\n if (err == MP_OKAY) {\n int loop_check = 0;\n ecc_key pubkey;\n\n #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)\n if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) {\n #if defined(HAVE_CAVIUM_V) || defined(HAVE_INTEL_QA)\n #ifdef HAVE_CAVIUM_V\n if (NitroxEccIsCurveSupported(key))\n #endif\n {\n word32 keySz = key->dp->size;\n mp_int* k;\n #ifdef HAVE_CAVIUM_V\n err = wc_ecc_alloc_mpint(key, &key->signK);\n if (err != 0)\n return err;\n k = key->signK;\n #else\n mp_int k_lcl;\n k = &k_lcl;\n #endif\n\n err = mp_init(k);\n\n /* make sure r and s are allocated */\n #ifdef HAVE_CAVIUM_V\n /* Nitrox V needs single buffer for R and S */\n if (err == MP_OKAY)\n err = wc_bigint_alloc(&key->r->raw, NitroxEccGetSize(key)*2);\n /* Nitrox V only needs Prime and Order */\n if (err == MP_OKAY)\n err = wc_ecc_curve_load(key->dp, &curve,\n (ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_ORDER));\n #else\n if (err == MP_OKAY)\n err = wc_bigint_alloc(&key->r->raw, key->dp->size);\n if (err == MP_OKAY)\n err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL);\n #endif\n if (err == MP_OKAY)\n err = wc_bigint_alloc(&key->s->raw, key->dp->size);\n\n /* load e and k */\n if (err == MP_OKAY)\n err = wc_mp_to_bigint_sz(e, &e->raw, keySz);\n if (err == MP_OKAY)\n err = wc_mp_to_bigint_sz(&key->k, &key->k.raw, keySz);\n if (err == MP_OKAY)\n err = wc_ecc_gen_k(rng, key->dp->size, k, curve->order);\n if (err == MP_OKAY)\n err = wc_mp_to_bigint_sz(k, &k->raw, keySz);\n\n #ifdef HAVE_CAVIUM_V\n if (err == MP_OKAY)\n err = NitroxEcdsaSign(key, &e->raw, &key->k.raw, &k->raw,\n &r->raw, &s->raw, &curve->prime->raw, &curve->order->raw);\n #else\n if (err == MP_OKAY)\n err = IntelQaEcdsaSign(&key->asyncDev, &e->raw, &key->k.raw,\n &k->raw, &r->raw, &s->raw, &curve->Af->raw, &curve->Bf->raw,\n &curve->prime->raw, &curve->order->raw, &curve->Gx->raw,\n &curve->Gy->raw);\n #endif\n\n #ifndef HAVE_CAVIUM_V\n mp_clear(e);\n mp_clear(k);\n #endif\n wc_ecc_curve_free(curve);\n\n return err;\n }\n #endif /* HAVE_CAVIUM_V || HAVE_INTEL_QA */\n }\n #endif /* WOLFSSL_ASYNC_CRYPT */\n\n /* don't use async for key, since we don't support async return here */\n if ((err = wc_ecc_init_ex(&pubkey, key->heap, INVALID_DEVID)) == MP_OKAY) {\n #ifdef WOLFSSL_CUSTOM_CURVES\n /* if custom curve, apply params to pubkey */\n if (key->idx == ECC_CUSTOM_IDX) {\n err = wc_ecc_set_custom_curve(&pubkey, key->dp);\n }\n #endif\n\n for (; err == MP_OKAY;) {\n if (++loop_check > 64) {\n err = RNG_FAILURE_E;\n break;\n }\n err = wc_ecc_make_key_ex(rng, key->dp->size, &pubkey,\n key->dp->id);\n if (err != MP_OKAY) break;\n\n /* find r = x1 mod n */\n err = mp_mod(pubkey.pubkey.x, curve->order, r);\n if (err != MP_OKAY) break;\n\n if (mp_iszero(r) == MP_YES) {\n #ifndef ALT_ECC_SIZE\n mp_clear(pubkey.pubkey.x);\n mp_clear(pubkey.pubkey.y);\n mp_clear(pubkey.pubkey.z);\n #endif\n mp_forcezero(&pubkey.k);\n }\n else {\n /* find s = (e + xr)/k */\n err = mp_invmod(&pubkey.k, curve->order, &pubkey.k);\n if (err != MP_OKAY) break;\n\n /* s = xr */\n err = mp_mulmod(&key->k, r, curve->order, s);\n if (err != MP_OKAY) break;\n\n /* s = e + xr */\n err = mp_add(e, s, s);\n if (err != MP_OKAY) break;\n\n /* s = e + xr */\n err = mp_mod(s, curve->order, s);\n if (err != MP_OKAY) break;\n\n /* s = (e + xr)/k */\n err = mp_mulmod(s, &pubkey.k, curve->order, s);\n\n if (mp_iszero(s) == MP_NO)\n break;\n }\n }\n wc_ecc_free(&pubkey);\n }\n }\n\n mp_clear(e);\n wc_ecc_curve_free(curve);\n#endif /* WOLFSSL_SP_MATH */\n\n return err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Change ECDSA signing to use blinding.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: pjmedia_avi_player_create_streams(pj_pool_t *pool,\n const char *filename,\n\t\t\t\t unsigned options,\n\t\t\t\t pjmedia_avi_streams **p_streams)\n{\n pjmedia_avi_hdr avi_hdr;\n struct avi_reader_port *fport[PJMEDIA_AVI_MAX_NUM_STREAMS];\n pj_off_t pos;\n unsigned i, nstr = 0;\n pj_status_t status = PJ_SUCCESS;\n\n /* Check arguments. */\n PJ_ASSERT_RETURN(pool && filename && p_streams, PJ_EINVAL);\n\n /* Check the file really exists. */\n if (!pj_file_exists(filename)) {\n\treturn PJ_ENOTFOUND;\n }\n\n /* Create fport instance. */\n fport[0] = create_avi_port(pool);\n if (!fport[0]) {\n\treturn PJ_ENOMEM;\n }\n\n /* Get the file size. */\n fport[0]->fsize = pj_file_size(filename);\n\n /* Size must be more than AVI header size */\n if (fport[0]->fsize <= sizeof(riff_hdr_t) + sizeof(avih_hdr_t) + \n sizeof(strl_hdr_t))\n {\n\treturn PJMEDIA_EINVALIMEDIATYPE;\n }\n\n /* Open file. */\n status = pj_file_open(pool, filename, PJ_O_RDONLY, &fport[0]->fd);\n if (status != PJ_SUCCESS)\n\treturn status;\n\n /* Read the RIFF + AVIH header. */\n status = file_read(fport[0]->fd, &avi_hdr,\n sizeof(riff_hdr_t) + sizeof(avih_hdr_t));\n if (status != PJ_SUCCESS)\n goto on_error;\n\n /* Validate AVI file. */\n if (!COMPARE_TAG(avi_hdr.riff_hdr.riff, PJMEDIA_AVI_RIFF_TAG) ||\n\t!COMPARE_TAG(avi_hdr.riff_hdr.avi, PJMEDIA_AVI_AVI_TAG) ||\n !COMPARE_TAG(avi_hdr.avih_hdr.list_tag, PJMEDIA_AVI_LIST_TAG) ||\n !COMPARE_TAG(avi_hdr.avih_hdr.hdrl_tag, PJMEDIA_AVI_HDRL_TAG) ||\n !COMPARE_TAG(avi_hdr.avih_hdr.avih, PJMEDIA_AVI_AVIH_TAG))\n {\n\tstatus = PJMEDIA_EINVALIMEDIATYPE;\n goto on_error;\n }\n\n PJ_LOG(5, (THIS_FILE, \"The AVI file has %d streams.\",\n avi_hdr.avih_hdr.num_streams));\n\n /* Unsupported AVI format. */\n if (avi_hdr.avih_hdr.num_streams > PJMEDIA_AVI_MAX_NUM_STREAMS) {\n status = PJMEDIA_EAVIUNSUPP;\n goto on_error;\n }\n\n /** \n * TODO: Possibly unsupported AVI format.\n * If you encounter this warning, verify whether the avi player\n * is working properly.\n */\n if (avi_hdr.avih_hdr.flags & AVIF_MUSTUSEINDEX ||\n avi_hdr.avih_hdr.pad > 1)\n {\n PJ_LOG(3, (THIS_FILE, \"Warning!!! Possibly unsupported AVI format: \"\n \"flags:%d, pad:%d\", avi_hdr.avih_hdr.flags, \n avi_hdr.avih_hdr.pad));\n }\n\n /* Read the headers of each stream. */\n for (i = 0; i < avi_hdr.avih_hdr.num_streams; i++) {\n pj_size_t elem = 0;\n pj_ssize_t size_to_read;\n\n /* Read strl header */\n status = file_read(fport[0]->fd, &avi_hdr.strl_hdr[i],\n sizeof(strl_hdr_t));\n if (status != PJ_SUCCESS)\n goto on_error;\n \n elem = COMPARE_TAG(avi_hdr.strl_hdr[i].data_type, \n PJMEDIA_AVI_VIDS_TAG) ? \n sizeof(strf_video_hdr_t) :\n COMPARE_TAG(avi_hdr.strl_hdr[i].data_type, \n PJMEDIA_AVI_AUDS_TAG) ?\n sizeof(strf_audio_hdr_t) : 0;\n\n /* Read strf header */\n status = file_read2(fport[0]->fd, &avi_hdr.strf_hdr[i],\n elem, 0);\n if (status != PJ_SUCCESS)\n goto on_error;\n\n /* Normalize the endian */\n if (elem == sizeof(strf_video_hdr_t))\n data_to_host2(&avi_hdr.strf_hdr[i],\n sizeof(strf_video_hdr_sizes)/\n sizeof(strf_video_hdr_sizes[0]),\n strf_video_hdr_sizes);\n else if (elem == sizeof(strf_audio_hdr_t))\n data_to_host2(&avi_hdr.strf_hdr[i],\n sizeof(strf_audio_hdr_sizes)/\n sizeof(strf_audio_hdr_sizes[0]),\n strf_audio_hdr_sizes);\n\n /* Skip the remainder of the header */\n size_to_read = avi_hdr.strl_hdr[i].list_sz - (sizeof(strl_hdr_t) -\n 8) - elem;\n\tstatus = pj_file_setpos(fport[0]->fd, size_to_read, PJ_SEEK_CUR);\n\tif (status != PJ_SUCCESS) {\n goto on_error;\n\t}\n }\n\n /* Finish reading the AVIH header */\n status = pj_file_setpos(fport[0]->fd, avi_hdr.avih_hdr.list_sz +\n sizeof(riff_hdr_t) + 8, PJ_SEEK_SET);\n if (status != PJ_SUCCESS) {\n goto on_error;\n }\n\n /* Skip any JUNK or LIST INFO until we get MOVI tag */\n do {\n pjmedia_avi_subchunk ch;\n int read = 0;\n\n status = file_read(fport[0]->fd, &ch, sizeof(pjmedia_avi_subchunk));\n if (status != PJ_SUCCESS) {\n goto on_error;\n }\n\n if (COMPARE_TAG(ch.id, PJMEDIA_AVI_LIST_TAG))\n {\n read = 4;\n status = file_read(fport[0]->fd, &ch, read);\n if (COMPARE_TAG(ch.id, PJMEDIA_AVI_MOVI_TAG))\n break;\n }\n\n status = pj_file_setpos(fport[0]->fd, ch.len-read, PJ_SEEK_CUR);\n if (status != PJ_SUCCESS) {\n goto on_error;\n }\n } while(1);\n\n status = pj_file_getpos(fport[0]->fd, &pos);\n if (status != PJ_SUCCESS)\n goto on_error;\n\n for (i = 0, nstr = 0; i < avi_hdr.avih_hdr.num_streams; i++) {\n\tpjmedia_format_id fmt_id;\n\n /* Skip non-audio, non-video, or disabled streams) */\n if ((!COMPARE_TAG(avi_hdr.strl_hdr[i].data_type, \n PJMEDIA_AVI_VIDS_TAG) &&\n !COMPARE_TAG(avi_hdr.strl_hdr[i].data_type, \n PJMEDIA_AVI_AUDS_TAG)) ||\n avi_hdr.strl_hdr[i].flags & AVISF_DISABLED)\n {\n continue;\n }\n\n if (COMPARE_TAG(avi_hdr.strl_hdr[i].data_type, \n PJMEDIA_AVI_VIDS_TAG))\n {\n int j;\n\n if (avi_hdr.strl_hdr[i].flags & AVISF_VIDEO_PALCHANGES) {\n PJ_LOG(4, (THIS_FILE, \"Unsupported video stream\"));\n continue;\n }\n\n fmt_id = avi_hdr.strl_hdr[i].codec;\n for (j = sizeof(avi_fmts)/sizeof(avi_fmts[0])-1; j >= 0; j--) {\n /* Check supported video formats here */\n if (fmt_id == avi_fmts[j].fmt_id) {\n if (avi_fmts[j].eff_fmt_id)\n fmt_id = avi_fmts[j].eff_fmt_id;\n break;\n }\n }\n \n if (j < 0) {\n PJ_LOG(4, (THIS_FILE, \"Unsupported video stream\"));\n continue;\n }\n } else {\n /* Check supported audio formats here */\n\t strf_audio_hdr_t *hdr = (strf_audio_hdr_t*)\n\t\t\t\t &avi_hdr.strf_hdr[i].strf_audio_hdr;\n if (hdr->fmt_tag == PJMEDIA_WAVE_FMT_TAG_PCM &&\n\t\thdr->bits_per_sample == 16)\n\t {\n\t\tfmt_id = PJMEDIA_FORMAT_PCM;\n\t }\n\t else if (hdr->fmt_tag == PJMEDIA_WAVE_FMT_TAG_ALAW)\n\t {\n\t\tfmt_id = PJMEDIA_FORMAT_PCMA;\n\t }\n\t else if (hdr->fmt_tag == PJMEDIA_WAVE_FMT_TAG_ULAW)\n\t {\n\t\tfmt_id = PJMEDIA_FORMAT_PCMU;\n\t }\n\t else\n {\n PJ_LOG(4, (THIS_FILE, \"Unsupported audio stream\"));\n continue;\n }\n }\n\n if (nstr > 0) {\n /* Create fport instance. */\n fport[nstr] = create_avi_port(pool);\n if (!fport[nstr]) {\n\t status = PJ_ENOMEM;\n goto on_error;\n }\n\n /* Open file. */\n status = pj_file_open(pool, filename, PJ_O_RDONLY,\n &fport[nstr]->fd);\n if (status != PJ_SUCCESS)\n goto on_error;\n\n /* Set the file position */\n status = pj_file_setpos(fport[nstr]->fd, pos, PJ_SEEK_SET);\n if (status != PJ_SUCCESS) {\n goto on_error;\n }\n }\n\n fport[nstr]->stream_id = i;\n fport[nstr]->fmt_id = fmt_id;\n\n nstr++;\n }\n\n if (nstr == 0) {\n status = PJMEDIA_EAVIUNSUPP;\n goto on_error;\n }\n\n for (i = 0; i < nstr; i++) {\n strl_hdr_t *strl_hdr = &avi_hdr.strl_hdr[fport[i]->stream_id];\n\n /* Initialize */\n fport[i]->options = options;\n fport[i]->fsize = fport[0]->fsize;\n /* Current file position now points to start of data */\n fport[i]->start_data = pos;\n \n if (COMPARE_TAG(strl_hdr->data_type, PJMEDIA_AVI_VIDS_TAG)) {\n strf_video_hdr_t *strf_hdr =\n &avi_hdr.strf_hdr[fport[i]->stream_id].strf_video_hdr;\n const pjmedia_video_format_info *vfi;\n\n vfi = pjmedia_get_video_format_info(\n pjmedia_video_format_mgr_instance(),\n strl_hdr->codec);\n\n fport[i]->bits_per_sample = (vfi ? vfi->bpp : 0);\n fport[i]->usec_per_frame = avi_hdr.avih_hdr.usec_per_frame;\n pjmedia_format_init_video(&fport[i]->base.info.fmt,\n fport[i]->fmt_id,\n strf_hdr->biWidth,\n strf_hdr->biHeight,\n strl_hdr->rate,\n strl_hdr->scale);\n#if 0\n /* The calculation below is wrong. strf_hdr->biSizeImage shows\n * uncompressed size. Looks like we need to go the ugly way to\n * get the bitrage:\n * http://www.virtualdub.org/blog/pivot/entry.php?id=159\n */\n bps = strf_hdr->biSizeImage * 8 * strl_hdr->rate / strl_hdr->scale;\n if (bps==0) {\n \t/* strf_hdr->biSizeImage may be zero for uncompressed RGB */\n \tbps = strf_hdr->biWidth * strf_hdr->biHeight *\n \t\tstrf_hdr->biBitCount *\n \t\tstrl_hdr->rate / strl_hdr->scale;\n }\n fport[i]->base.info.fmt.det.vid.avg_bps = bps;\n fport[i]->base.info.fmt.det.vid.max_bps = bps;\n#endif\n } else {\n strf_audio_hdr_t *strf_hdr =\n &avi_hdr.strf_hdr[fport[i]->stream_id].strf_audio_hdr;\n\n fport[i]->bits_per_sample = strf_hdr->bits_per_sample;\n fport[i]->usec_per_frame = avi_hdr.avih_hdr.usec_per_frame;\n pjmedia_format_init_audio(&fport[i]->base.info.fmt,\n fport[i]->fmt_id,\n strf_hdr->sample_rate,\n strf_hdr->nchannels,\n strf_hdr->bits_per_sample,\n 20000 /* fport[i]->usec_per_frame */,\n strf_hdr->bytes_per_sec * 8,\n strf_hdr->bytes_per_sec * 8);\n\n\t /* Set format to PCM (we will decode PCMA/U) */\n\t if (fport[i]->fmt_id == PJMEDIA_FORMAT_PCMA ||\n\t\tfport[i]->fmt_id == PJMEDIA_FORMAT_PCMU)\n\t {\n\t\tfport[i]->base.info.fmt.id = PJMEDIA_FORMAT_PCM;\n\t\tfport[i]->base.info.fmt.det.aud.bits_per_sample = 16;\n\t }\n\t}\n\n pj_strdup2(pool, &fport[i]->base.info.name, filename);\n }\n\n /* Done. */\n *p_streams = pj_pool_alloc(pool, sizeof(pjmedia_avi_streams));\n (*p_streams)->num_streams = nstr;\n (*p_streams)->streams = pj_pool_calloc(pool, (*p_streams)->num_streams,\n sizeof(pjmedia_port *));\n for (i = 0; i < nstr; i++)\n (*p_streams)->streams[i] = &fport[i]->base;\n\n PJ_LOG(4,(THIS_FILE, \n\t \"AVI file player '%.*s' created with \"\n\t \"%d media ports\",\n\t (int)fport[0]->base.info.name.slen,\n\t fport[0]->base.info.name.ptr,\n (*p_streams)->num_streams));\n\n return PJ_SUCCESS;\n\non_error:\n fport[0]->base.on_destroy(&fport[0]->base);\n for (i = 1; i < nstr; i++)\n fport[i]->base.on_destroy(&fport[i]->base);\n if (status == AVI_EOF)\n return PJMEDIA_EINVALIMEDIATYPE;\n return status;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-835'], 'message': 'Merge pull request from GHSA-rwgw-vwxg-q799\n\n* Prevent potential infinite loop when parsing WAV format file\n\n* Check if subchunk is negative.\n\n* Fix and add checks\n\n* Change data type from pj_ssize_t to long.\n\n* Modify check\n\n* Fix leak file descriptor and modify check on wav_playlist\n\n* Move overflow/underflow check to pj_file_setpos()\n\n* Use macro to simplify check\n\n* modification based on comments\n\n* Remove unnecessary casting\n\n* Modification based on comments'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void ComputeAsync(OpKernelContext* context, DoneCallback done) override {\n // The shape of 'image' is [batch_size, image_height, image_width,\n // channels].\n const Tensor& image = context->input(0);\n // The shape of 'boxes' is [num_boxes, 4].\n const Tensor& boxes = context->input(1);\n // The shape of 'box_index' is [num_boxes].\n const Tensor& box_index = context->input(2);\n // The shape of 'crop_size' is [2].\n const Tensor& crop_size = context->input(3);\n\n // Validate inputs dimensions.\n OP_REQUIRES_ASYNC(context, image.dims() == 4,\n errors::InvalidArgument(\"input image must be 4-D\",\n image.shape().DebugString()),\n done);\n const int batch_size = image.dim_size(0);\n const int image_height = image.dim_size(1);\n const int image_width = image.dim_size(2);\n const int depth = image.dim_size(3);\n OP_REQUIRES_ASYNC(\n context, image_height > 0 && image_width > 0,\n errors::InvalidArgument(\"image dimensions must be positive\"), done);\n int num_boxes = 0;\n OP_REQUIRES_OK_ASYNC(\n context, ParseAndCheckBoxSizes(boxes, box_index, &num_boxes), done);\n\n OP_REQUIRES_ASYNC(context, crop_size.dims() == 1,\n errors::InvalidArgument(\"crop_size must be 1-D\",\n crop_size.shape().DebugString()),\n done);\n OP_REQUIRES_ASYNC(\n context, crop_size.dim_size(0) == 2,\n errors::InvalidArgument(\"crop_size must have two elements\",\n crop_size.shape().DebugString()),\n done);\n\n // Copy and validate crop sizes.\n auto crop_size_vec = crop_size.vec();\n const int crop_height = internal::SubtleMustCopy(crop_size_vec(0));\n const int crop_width = internal::SubtleMustCopy(crop_size_vec(1));\n OP_REQUIRES_ASYNC(\n context, crop_height > 0 && crop_width > 0,\n errors::InvalidArgument(\"crop dimensions must be positive\"), done);\n\n // Allocate output tensor.\n Tensor* output = nullptr;\n OP_REQUIRES_OK_ASYNC(\n context,\n context->allocate_output(\n 0, TensorShape({num_boxes, crop_height, crop_width, depth}),\n &output),\n done);\n\n auto compute_callback = [this, context, output]() {\n const Tensor& image = context->input(0);\n const Tensor& boxes = context->input(1);\n const Tensor& box_index = context->input(2);\n const bool status = functor::CropAndResize()(\n context, image.tensor(), boxes.tensor(),\n box_index.tensor(), method_, extrapolation_value_,\n output->tensor());\n\n if (!status) {\n context->SetStatus(\n errors::Internal(\"Failed to launch CropAndResizeKernel.\"));\n }\n };\n\n RunIfBoxIndexIsValid(context, box_index.tensor(),\n batch_size, std::move(compute_callback),\n std::move(done));\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'PR #51732: Fix crash of tf.image.crop_and_resize when input is large number\n\nImported from GitHub PR https://github.com/tensorflow/tensorflow/pull/51732\n\nThis PR is part of the effort in #46890 where\ntf.image.crop_and_resize will crash if shape consists of large number.\n\nSigned-off-by: Yong Tang \nCopybara import of the project:\n\n--\nc8d87055a56d8740d27ad8bdc74a7459ede6900e by Yong Tang :\n\nFix crash of tf.image.crop_and_resize when input is large number\n\nThis PR is part of the effort in 46890 where\ntf.image.crop_and_resize will crash if shape consists of large number.\n\nSigned-off-by: Yong Tang \nCOPYBARA_INTEGRATE_REVIEW=https://github.com/tensorflow/tensorflow/pull/51732 from yongtang:46890-tf.image.crop_and_resize c8d87055a56d8740d27ad8bdc74a7459ede6900e\nPiperOrigin-RevId: 394109830\nChange-Id: If049dad0844df9353722029ee95bc76819eda1f4'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static table_row *row_from_string(cmark_syntax_extension *self,\n cmark_parser *parser, unsigned char *string,\n int len) {\n table_row *row = NULL;\n bufsize_t cell_matched = 1, pipe_matched = 1, offset;\n\n row = (table_row *)parser->mem->calloc(1, sizeof(table_row));\n row->n_columns = 0;\n row->cells = NULL;\n\n offset = scan_table_cell_end(string, len, 0);\n\n // Parse the cells of the row. Stop if we reach the end of the input, or if we\n // cannot detect any more cells.\n while (offset < len && (cell_matched || pipe_matched)) {\n cell_matched = scan_table_cell(string, len, offset);\n pipe_matched = scan_table_cell_end(string, len, offset + cell_matched);\n\n if (cell_matched || pipe_matched) {\n cmark_strbuf *cell_buf = unescape_pipes(parser->mem, string + offset,\n cell_matched);\n cmark_strbuf_trim(cell_buf);\n\n node_cell *cell = (node_cell *)parser->mem->calloc(1, sizeof(*cell));\n cell->buf = cell_buf;\n cell->start_offset = offset;\n cell->end_offset = offset + cell_matched - 1;\n while (cell->start_offset > 0 && string[cell->start_offset - 1] != '|') {\n --cell->start_offset;\n ++cell->internal_offset;\n }\n row->n_columns += 1;\n row->cells = cmark_llist_append(parser->mem, row->cells, cell);\n }\n\n offset += cell_matched + pipe_matched;\n\n if (!pipe_matched) {\n pipe_matched = scan_table_row_end(string, len, offset);\n offset += pipe_matched;\n }\n }\n\n if (offset != len || !row->n_columns) {\n free_table_row(parser->mem, row);\n row = NULL;\n }\n\n return row;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'prevent integer overflow in row_from_string\n\n* added explicit check for UINT16_MAX boundary on row->n_columns\n\n* added additional checks for row_from_string NULL returns to prevent NULL\ndereferences on error cases\n\n* added additional check to ensure n_columns between marker and header rows\nalways match prior to any alignment processing\n\n* allocate alignment array based on marker rows rather than header rows\n\n* prevent memory leak on dangling node when encountering row_from_string\nerror in try_opening_table_row\n\n* add explicit integer overflow error marker to not overload offset semantics\nin row_from_string with other implied error conditions'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void Compute(OpKernelContext* context) override {\n const Tensor* reverse_index_map_t;\n const Tensor* grad_values_t;\n OP_REQUIRES_OK(context,\n context->input(\"reverse_index_map\", &reverse_index_map_t));\n OP_REQUIRES_OK(context, context->input(\"grad_values\", &grad_values_t));\n\n const CPUDevice& d = context->eigen_device();\n\n OP_REQUIRES(\n context, TensorShapeUtils::IsVector(reverse_index_map_t->shape()),\n errors::InvalidArgument(\"reverse_index_map must be a vector, saw: \",\n reverse_index_map_t->shape().DebugString()));\n\n const auto reverse_index_map = reverse_index_map_t->vec();\n const auto grad_values = grad_values_t->vec();\n\n const int64 N = reverse_index_map_t->shape().dim_size(0);\n const int64 N_full = grad_values_t->shape().dim_size(0);\n\n Tensor* d_values_t;\n OP_REQUIRES_OK(context, context->allocate_output(\n \"d_values\", TensorShape({N}), &d_values_t));\n auto d_values = d_values_t->vec();\n Tensor* d_default_value_t;\n OP_REQUIRES_OK(context,\n context->allocate_output(\"d_default_value\", TensorShape({}),\n &d_default_value_t));\n T& d_default_value = d_default_value_t->scalar()();\n d_default_value = T();\n\n Tensor visited_t;\n OP_REQUIRES_OK(context, context->allocate_temp(\n DT_BOOL, TensorShape({N_full}), &visited_t));\n auto visited = visited_t.vec();\n visited.device(d) = visited.constant(false);\n\n for (int i = 0; i < N; ++i) {\n // Locate the index of the output of the forward prop associated\n // with this location in the input of the forward prop. Copy\n // the gradient into it. Mark it as visited.\n d_values(i) = grad_values(reverse_index_map(i));\n visited(reverse_index_map(i)) = true;\n }\n for (int j = 0; j < N_full; ++j) {\n // The default value gradient gets the accumulated remainder of\n // the backprop values (since the default value was used to fill\n // in these slots in the forward calculation).\n if (!visited(j)) {\n d_default_value += grad_values(j);\n }\n }\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617', 'CWE-703', 'CWE-787'], 'message': 'Fix heap buffer overflow in `tf.raw_ops.SparseFillEmptyRowsGrad`.\n\nAlso add tests as they were lacking\n\nPiperOrigin-RevId: 332566071\nChange-Id: I44277578e26ff5fb3fdb0dcbba6e91b2ec3e7859'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: kg_unseal_v1(context, minor_status, ctx, ptr, bodysize, message_buffer,\n conf_state, qop_state, toktype)\n krb5_context context;\n OM_uint32 *minor_status;\n krb5_gss_ctx_id_rec *ctx;\n unsigned char *ptr;\n int bodysize;\n gss_buffer_t message_buffer;\n int *conf_state;\n gss_qop_t *qop_state;\n int toktype;\n{\n krb5_error_code code;\n int conflen = 0;\n int signalg;\n int sealalg;\n gss_buffer_desc token;\n krb5_checksum cksum;\n krb5_checksum md5cksum;\n krb5_data plaind;\n char *data_ptr;\n unsigned char *plain;\n unsigned int cksum_len = 0;\n size_t plainlen;\n int direction;\n krb5_ui_4 seqnum;\n OM_uint32 retval;\n size_t sumlen;\n krb5_keyusage sign_usage = KG_USAGE_SIGN;\n\n if (toktype == KG_TOK_SEAL_MSG) {\n message_buffer->length = 0;\n message_buffer->value = NULL;\n }\n\n /* get the sign and seal algorithms */\n\n signalg = ptr[0] + (ptr[1]<<8);\n sealalg = ptr[2] + (ptr[3]<<8);\n\n /* Sanity checks */\n\n if ((ptr[4] != 0xff) || (ptr[5] != 0xff)) {\n *minor_status = 0;\n return GSS_S_DEFECTIVE_TOKEN;\n }\n\n if ((toktype != KG_TOK_SEAL_MSG) &&\n (sealalg != 0xffff)) {\n *minor_status = 0;\n return GSS_S_DEFECTIVE_TOKEN;\n }\n\n /* in the current spec, there is only one valid seal algorithm per\n key type, so a simple comparison is ok */\n\n if ((toktype == KG_TOK_SEAL_MSG) &&\n !((sealalg == 0xffff) ||\n (sealalg == ctx->sealalg))) {\n *minor_status = 0;\n return GSS_S_DEFECTIVE_TOKEN;\n }\n\n /* there are several mappings of seal algorithms to sign algorithms,\n but few enough that we can try them all. */\n\n if ((ctx->sealalg == SEAL_ALG_NONE && signalg > 1) ||\n (ctx->sealalg == SEAL_ALG_1 && signalg != SGN_ALG_3) ||\n (ctx->sealalg == SEAL_ALG_DES3KD &&\n signalg != SGN_ALG_HMAC_SHA1_DES3_KD)||\n (ctx->sealalg == SEAL_ALG_MICROSOFT_RC4 &&\n signalg != SGN_ALG_HMAC_MD5)) {\n *minor_status = 0;\n return GSS_S_DEFECTIVE_TOKEN;\n }\n\n switch (signalg) {\n case SGN_ALG_DES_MAC_MD5:\n case SGN_ALG_MD2_5:\n case SGN_ALG_HMAC_MD5:\n cksum_len = 8;\n if (toktype != KG_TOK_SEAL_MSG)\n sign_usage = 15;\n break;\n case SGN_ALG_3:\n cksum_len = 16;\n break;\n case SGN_ALG_HMAC_SHA1_DES3_KD:\n cksum_len = 20;\n break;\n default:\n *minor_status = 0;\n return GSS_S_DEFECTIVE_TOKEN;\n }\n\n /* get the token parameters */\n\n if ((code = kg_get_seq_num(context, ctx->seq, ptr+14, ptr+6, &direction,\n &seqnum))) {\n *minor_status = code;\n return(GSS_S_BAD_SIG);\n }\n\n /* decode the message, if SEAL */\n\n if (toktype == KG_TOK_SEAL_MSG) {\n size_t tmsglen = bodysize-(14+cksum_len);\n if (sealalg != 0xffff) {\n if ((plain = (unsigned char *) xmalloc(tmsglen)) == NULL) {\n *minor_status = ENOMEM;\n return(GSS_S_FAILURE);\n }\n if (ctx->sealalg == SEAL_ALG_MICROSOFT_RC4) {\n unsigned char bigend_seqnum[4];\n krb5_keyblock *enc_key;\n int i;\n store_32_be(seqnum, bigend_seqnum);\n code = krb5_k_key_keyblock(context, ctx->enc, &enc_key);\n if (code)\n {\n xfree(plain);\n *minor_status = code;\n return(GSS_S_FAILURE);\n }\n\n assert (enc_key->length == 16);\n for (i = 0; i <= 15; i++)\n ((char *) enc_key->contents)[i] ^=0xf0;\n code = kg_arcfour_docrypt (enc_key, 0,\n &bigend_seqnum[0], 4,\n ptr+14+cksum_len, tmsglen,\n plain);\n krb5_free_keyblock (context, enc_key);\n } else {\n code = kg_decrypt(context, ctx->enc, KG_USAGE_SEAL, NULL,\n ptr+14+cksum_len, plain, tmsglen);\n }\n if (code) {\n xfree(plain);\n *minor_status = code;\n return(GSS_S_FAILURE);\n }\n } else {\n plain = ptr+14+cksum_len;\n }\n\n plainlen = tmsglen;\n\n conflen = kg_confounder_size(context, ctx->enc->keyblock.enctype);\n token.length = tmsglen - conflen - plain[tmsglen-1];\n\n if (token.length) {\n if ((token.value = (void *) gssalloc_malloc(token.length)) == NULL) {\n if (sealalg != 0xffff)\n xfree(plain);\n *minor_status = ENOMEM;\n return(GSS_S_FAILURE);\n }\n memcpy(token.value, plain+conflen, token.length);\n } else {\n token.value = NULL;\n }\n } else if (toktype == KG_TOK_SIGN_MSG) {\n token = *message_buffer;\n plain = token.value;\n plainlen = token.length;\n } else {\n token.length = 0;\n token.value = NULL;\n plain = token.value;\n plainlen = token.length;\n }\n\n /* compute the checksum of the message */\n\n /* initialize the the cksum */\n switch (signalg) {\n case SGN_ALG_DES_MAC_MD5:\n case SGN_ALG_MD2_5:\n case SGN_ALG_DES_MAC:\n case SGN_ALG_3:\n md5cksum.checksum_type = CKSUMTYPE_RSA_MD5;\n break;\n case SGN_ALG_HMAC_MD5:\n md5cksum.checksum_type = CKSUMTYPE_HMAC_MD5_ARCFOUR;\n break;\n case SGN_ALG_HMAC_SHA1_DES3_KD:\n md5cksum.checksum_type = CKSUMTYPE_HMAC_SHA1_DES3;\n break;\n default:\n abort ();\n }\n\n code = krb5_c_checksum_length(context, md5cksum.checksum_type, &sumlen);\n if (code)\n return(code);\n md5cksum.length = sumlen;\n\n switch (signalg) {\n case SGN_ALG_DES_MAC_MD5:\n case SGN_ALG_3:\n /* compute the checksum of the message */\n\n /* 8 = bytes of token body to be checksummed according to spec */\n\n if (! (data_ptr = xmalloc(8 + plainlen))) {\n if (sealalg != 0xffff)\n xfree(plain);\n if (toktype == KG_TOK_SEAL_MSG)\n gssalloc_free(token.value);\n *minor_status = ENOMEM;\n return(GSS_S_FAILURE);\n }\n\n (void) memcpy(data_ptr, ptr-2, 8);\n\n (void) memcpy(data_ptr+8, plain, plainlen);\n\n plaind.length = 8 + plainlen;\n plaind.data = data_ptr;\n code = krb5_k_make_checksum(context, md5cksum.checksum_type,\n ctx->seq, sign_usage,\n &plaind, &md5cksum);\n xfree(data_ptr);\n\n if (code) {\n if (toktype == KG_TOK_SEAL_MSG)\n gssalloc_free(token.value);\n *minor_status = code;\n return(GSS_S_FAILURE);\n }\n\n code = kg_encrypt_inplace(context, ctx->seq, KG_USAGE_SEAL,\n (g_OID_equal(ctx->mech_used,\n gss_mech_krb5_old) ?\n ctx->seq->keyblock.contents : NULL),\n md5cksum.contents, 16);\n if (code) {\n krb5_free_checksum_contents(context, &md5cksum);\n if (toktype == KG_TOK_SEAL_MSG)\n gssalloc_free(token.value);\n *minor_status = code;\n return GSS_S_FAILURE;\n }\n\n if (signalg == 0)\n cksum.length = 8;\n else\n cksum.length = 16;\n cksum.contents = md5cksum.contents + 16 - cksum.length;\n\n code = k5_bcmp(cksum.contents, ptr + 14, cksum.length);\n break;\n\n case SGN_ALG_MD2_5:\n if (!ctx->seed_init &&\n (code = kg_make_seed(context, ctx->subkey, ctx->seed))) {\n krb5_free_checksum_contents(context, &md5cksum);\n if (sealalg != 0xffff)\n xfree(plain);\n if (toktype == KG_TOK_SEAL_MSG)\n gssalloc_free(token.value);\n *minor_status = code;\n return GSS_S_FAILURE;\n }\n\n if (! (data_ptr = xmalloc(sizeof(ctx->seed) + 8 + plainlen))) {\n krb5_free_checksum_contents(context, &md5cksum);\n if (sealalg == 0)\n xfree(plain);\n if (toktype == KG_TOK_SEAL_MSG)\n gssalloc_free(token.value);\n *minor_status = ENOMEM;\n return(GSS_S_FAILURE);\n }\n (void) memcpy(data_ptr, ptr-2, 8);\n (void) memcpy(data_ptr+8, ctx->seed, sizeof(ctx->seed));\n (void) memcpy(data_ptr+8+sizeof(ctx->seed), plain, plainlen);\n plaind.length = 8 + sizeof(ctx->seed) + plainlen;\n plaind.data = data_ptr;\n krb5_free_checksum_contents(context, &md5cksum);\n code = krb5_k_make_checksum(context, md5cksum.checksum_type,\n ctx->seq, sign_usage,\n &plaind, &md5cksum);\n xfree(data_ptr);\n\n if (code) {\n if (sealalg == 0)\n xfree(plain);\n if (toktype == KG_TOK_SEAL_MSG)\n gssalloc_free(token.value);\n *minor_status = code;\n return(GSS_S_FAILURE);\n }\n\n code = k5_bcmp(md5cksum.contents, ptr + 14, 8);\n /* Falls through to defective-token?? */\n\n default:\n *minor_status = 0;\n return(GSS_S_DEFECTIVE_TOKEN);\n\n case SGN_ALG_HMAC_SHA1_DES3_KD:\n case SGN_ALG_HMAC_MD5:\n /* compute the checksum of the message */\n\n /* 8 = bytes of token body to be checksummed according to spec */\n\n if (! (data_ptr = xmalloc(8 + plainlen))) {\n if (sealalg != 0xffff)\n xfree(plain);\n if (toktype == KG_TOK_SEAL_MSG)\n gssalloc_free(token.value);\n *minor_status = ENOMEM;\n return(GSS_S_FAILURE);\n }\n\n (void) memcpy(data_ptr, ptr-2, 8);\n\n (void) memcpy(data_ptr+8, plain, plainlen);\n\n plaind.length = 8 + plainlen;\n plaind.data = data_ptr;\n code = krb5_k_make_checksum(context, md5cksum.checksum_type,\n ctx->seq, sign_usage,\n &plaind, &md5cksum);\n xfree(data_ptr);\n\n if (code) {\n if (toktype == KG_TOK_SEAL_MSG)\n gssalloc_free(token.value);\n *minor_status = code;\n return(GSS_S_FAILURE);\n }\n\n code = k5_bcmp(md5cksum.contents, ptr + 14, cksum_len);\n break;\n }\n\n krb5_free_checksum_contents(context, &md5cksum);\n if (sealalg != 0xffff)\n xfree(plain);\n\n /* compare the computed checksum against the transmitted checksum */\n\n if (code) {\n if (toktype == KG_TOK_SEAL_MSG)\n gssalloc_free(token.value);\n *minor_status = 0;\n return(GSS_S_BAD_SIG);\n }\n\n\n /* it got through unscathed. Make sure the context is unexpired */\n\n if (toktype == KG_TOK_SEAL_MSG)\n *message_buffer = token;\n\n if (conf_state)\n *conf_state = (sealalg != 0xffff);\n\n if (qop_state)\n *qop_state = GSS_C_QOP_DEFAULT;\n\n /* do sequencing checks */\n\n if ((ctx->initiate && direction != 0xff) ||\n (!ctx->initiate && direction != 0)) {\n if (toktype == KG_TOK_SEAL_MSG) {\n gssalloc_free(token.value);\n message_buffer->value = NULL;\n message_buffer->length = 0;\n }\n *minor_status = (OM_uint32)G_BAD_DIRECTION;\n return(GSS_S_BAD_SIG);\n }\n\n retval = g_order_check(&(ctx->seqstate), (gssint_uint64)seqnum);\n\n /* success or ordering violation */\n\n *minor_status = 0;\n return(retval);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-125'], 'message': 'Handle invalid RFC 1964 tokens [CVE-2014-4341...]\n\nDetect the following cases which would otherwise cause invalid memory\naccesses and/or integer underflow:\n\n* An RFC 1964 token being processed by an RFC 4121-only context\n [CVE-2014-4342]\n\n* A header with fewer than 22 bytes after the token ID or an\n incomplete checksum [CVE-2014-4341 CVE-2014-4342]\n\n* A ciphertext shorter than the confounder [CVE-2014-4341]\n\n* A declared padding length longer than the plaintext [CVE-2014-4341]\n\nIf we detect a bad pad byte, continue on to compute the checksum to\navoid creating a padding oracle, but treat the checksum as invalid\neven if it compares equal.\n\nCVE-2014-4341:\n\nIn MIT krb5, an unauthenticated remote attacker with the ability to\ninject packets into a legitimately established GSSAPI application\nsession can cause a program crash due to invalid memory references\nwhen attempting to read beyond the end of a buffer.\n\n CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:P/E:POC/RL:OF/RC:C\n\nCVE-2014-4342:\n\nIn MIT krb5 releases krb5-1.7 and later, an unauthenticated remote\nattacker with the ability to inject packets into a legitimately\nestablished GSSAPI application session can cause a program crash due\nto invalid memory references when reading beyond the end of a buffer\nor by causing a null pointer dereference.\n\n CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:P/E:POC/RL:OF/RC:C\n\n[tlyu@mit.edu: CVE summaries, CVSS]\n\n(cherry picked from commit fb99962cbd063ac04c9a9d2cc7c75eab73f3533d)\n\nticket: 7949\nversion_fixed: 1.12.2\nstatus: resolved'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void jslTokenAsString(int token, char *str, size_t len) {\n // see JS_ERROR_TOKEN_BUF_SIZE\n if (token>32 && token<128) {\n assert(len>=4);\n str[0] = '\\'';\n str[1] = (char)token;\n str[2] = '\\'';\n str[3] = 0;\n return;\n }\n\n switch (token) {\n case LEX_EOF : strncpy(str, \"EOF\", len); return;\n case LEX_ID : strncpy(str, \"ID\", len); return;\n case LEX_INT : strncpy(str, \"INT\", len); return;\n case LEX_FLOAT : strncpy(str, \"FLOAT\", len); return;\n case LEX_STR : strncpy(str, \"STRING\", len); return;\n case LEX_UNFINISHED_STR : strncpy(str, \"UNFINISHED STRING\", len); return;\n case LEX_TEMPLATE_LITERAL : strncpy(str, \"TEMPLATE LITERAL\", len); return;\n case LEX_UNFINISHED_TEMPLATE_LITERAL : strncpy(str, \"UNFINISHED TEMPLATE LITERAL\", len); return;\n case LEX_REGEX : strncpy(str, \"REGEX\", len); return;\n case LEX_UNFINISHED_REGEX : strncpy(str, \"UNFINISHED REGEX\", len); return;\n case LEX_UNFINISHED_COMMENT : strncpy(str, \"UNFINISHED COMMENT\", len); return;\n }\n if (token>=_LEX_OPERATOR_START && token<_LEX_R_LIST_END) {\n const char tokenNames[] =\n /* LEX_EQUAL : */ \"==\\0\"\n /* LEX_TYPEEQUAL : */ \"===\\0\"\n /* LEX_NEQUAL : */ \"!=\\0\"\n /* LEX_NTYPEEQUAL : */ \"!==\\0\"\n /* LEX_LEQUAL : */ \"<=\\0\"\n /* LEX_LSHIFT : */ \"<<\\0\"\n /* LEX_LSHIFTEQUAL : */ \"<<=\\0\"\n /* LEX_GEQUAL : */ \">=\\0\"\n /* LEX_RSHIFT : */ \">>\\0\"\n /* LEX_RSHIFTUNSIGNED */ \">>>\\0\"\n /* LEX_RSHIFTEQUAL : */ \">>=\\0\"\n /* LEX_RSHIFTUNSIGNEDEQUAL */ \">>>=\\0\"\n /* LEX_PLUSEQUAL : */ \"+=\\0\"\n /* LEX_MINUSEQUAL : */ \"-=\\0\"\n /* LEX_PLUSPLUS : */ \"++\\0\"\n /* LEX_MINUSMINUS */ \"--\\0\"\n /* LEX_MULEQUAL : */ \"*=\\0\"\n /* LEX_DIVEQUAL : */ \"/=\\0\"\n /* LEX_MODEQUAL : */ \"%=\\0\"\n /* LEX_ANDEQUAL : */ \"&=\\0\"\n /* LEX_ANDAND : */ \"&&\\0\"\n /* LEX_OREQUAL : */ \"|=\\0\"\n /* LEX_OROR : */ \"||\\0\"\n /* LEX_XOREQUAL : */ \"^=\\0\"\n /* LEX_ARROW_FUNCTION */ \"=>\\0\"\n\n // reserved words\n /*LEX_R_IF : */ \"if\\0\"\n /*LEX_R_ELSE : */ \"else\\0\"\n /*LEX_R_DO : */ \"do\\0\"\n /*LEX_R_WHILE : */ \"while\\0\"\n /*LEX_R_FOR : */ \"for\\0\"\n /*LEX_R_BREAK : */ \"return\\0\"\n /*LEX_R_CONTINUE */ \"continue\\0\"\n /*LEX_R_FUNCTION */ \"function\\0\"\n /*LEX_R_RETURN */ \"return\\0\"\n /*LEX_R_VAR : */ \"var\\0\"\n /*LEX_R_LET : */ \"let\\0\"\n /*LEX_R_CONST : */ \"const\\0\"\n /*LEX_R_THIS : */ \"this\\0\"\n /*LEX_R_THROW : */ \"throw\\0\"\n /*LEX_R_TRY : */ \"try\\0\"\n /*LEX_R_CATCH : */ \"catch\\0\"\n /*LEX_R_FINALLY : */ \"finally\\0\"\n /*LEX_R_TRUE : */ \"true\\0\"\n /*LEX_R_FALSE : */ \"false\\0\"\n /*LEX_R_NULL : */ \"null\\0\"\n /*LEX_R_UNDEFINED */ \"undefined\\0\"\n /*LEX_R_NEW : */ \"new\\0\"\n /*LEX_R_IN : */ \"in\\0\"\n /*LEX_R_INSTANCEOF */ \"instanceof\\0\"\n /*LEX_R_SWITCH */ \"switch\\0\"\n /*LEX_R_CASE */ \"case\\0\"\n /*LEX_R_DEFAULT */ \"default\\0\"\n /*LEX_R_DELETE */ \"delete\\0\"\n /*LEX_R_TYPEOF : */ \"typeof\\0\"\n /*LEX_R_VOID : */ \"void\\0\"\n /*LEX_R_DEBUGGER : */ \"debugger\\0\"\n /*LEX_R_CLASS : */ \"class\\0\"\n /*LEX_R_EXTENDS : */ \"extends\\0\"\n /*LEX_R_SUPER : */ \"super\\0\"\n /*LEX_R_STATIC : */ \"static\\0\"\n ;\n unsigned int p = 0;\n int n = token-_LEX_OPERATOR_START;\n while (n>0 && p=10);\n strncpy(str, \"?[\",len);\n itostr(token, &str[2], 10);\n strncat(str, \"]\",len);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix strncat/cpy bounding issues (fix #1425)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int security_context_to_sid_core(const char *scontext, u32 scontext_len,\n\t\t\t\t\tu32 *sid, u32 def_sid, gfp_t gfp_flags,\n\t\t\t\t\tint force)\n{\n\tchar *scontext2, *str = NULL;\n\tstruct context context;\n\tint rc = 0;\n\n\tif (!ss_initialized) {\n\t\tint i;\n\n\t\tfor (i = 1; i < SECINITSID_NUM; i++) {\n\t\t\tif (!strcmp(initial_sid_to_string[i], scontext)) {\n\t\t\t\t*sid = i;\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t\t*sid = SECINITSID_KERNEL;\n\t\treturn 0;\n\t}\n\t*sid = SECSID_NULL;\n\n\t/* Copy the string so that we can modify the copy as we parse it. */\n\tscontext2 = kmalloc(scontext_len + 1, gfp_flags);\n\tif (!scontext2)\n\t\treturn -ENOMEM;\n\tmemcpy(scontext2, scontext, scontext_len);\n\tscontext2[scontext_len] = 0;\n\n\tif (force) {\n\t\t/* Save another copy for storing in uninterpreted form */\n\t\trc = -ENOMEM;\n\t\tstr = kstrdup(scontext2, gfp_flags);\n\t\tif (!str)\n\t\t\tgoto out;\n\t}\n\n\tread_lock(&policy_rwlock);\n\trc = string_to_context_struct(&policydb, &sidtab, scontext2,\n\t\t\t\t scontext_len, &context, def_sid);\n\tif (rc == -EINVAL && force) {\n\t\tcontext.str = str;\n\t\tcontext.len = scontext_len;\n\t\tstr = NULL;\n\t} else if (rc)\n\t\tgoto out_unlock;\n\trc = sidtab_context_to_sid(&sidtab, &context, sid);\n\tcontext_destroy(&context);\nout_unlock:\n\tread_unlock(&policy_rwlock);\nout:\n\tkfree(scontext2);\n\tkfree(str);\n\treturn rc;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'SELinux: Fix kernel BUG on empty security contexts.\n\nSetting an empty security context (length=0) on a file will\nlead to incorrectly dereferencing the type and other fields\nof the security context structure, yielding a kernel BUG.\nAs a zero-length security context is never valid, just reject\nall such security contexts whether coming from userspace\nvia setxattr or coming from the filesystem upon a getxattr\nrequest by SELinux.\n\nSetting a security context value (empty or otherwise) unknown to\nSELinux in the first place is only possible for a root process\n(CAP_MAC_ADMIN), and, if running SELinux in enforcing mode, only\nif the corresponding SELinux mac_admin permission is also granted\nto the domain by policy. In Fedora policies, this is only allowed for\nspecific domains such as livecd for setting down security contexts\nthat are not defined in the build host policy.\n\nReproducer:\nsu\nsetenforce 0\ntouch foo\nsetfattr -n security.selinux foo\n\nCaveat:\nRelabeling or removing foo after doing the above may not be possible\nwithout booting with SELinux disabled. Any subsequent access to foo\nafter doing the above will also trigger the BUG.\n\nBUG output from Matthew Thode:\n[ 473.893141] ------------[ cut here ]------------\n[ 473.962110] kernel BUG at security/selinux/ss/services.c:654!\n[ 473.995314] invalid opcode: 0000 [#6] SMP\n[ 474.027196] Modules linked in:\n[ 474.058118] CPU: 0 PID: 8138 Comm: ls Tainted: G D I\n3.13.0-grsec #1\n[ 474.116637] Hardware name: Supermicro X8ST3/X8ST3, BIOS 2.0\n07/29/10\n[ 474.149768] task: ffff8805f50cd010 ti: ffff8805f50cd488 task.ti:\nffff8805f50cd488\n[ 474.183707] RIP: 0010:[] []\ncontext_struct_compute_av+0xce/0x308\n[ 474.219954] RSP: 0018:ffff8805c0ac3c38 EFLAGS: 00010246\n[ 474.252253] RAX: 0000000000000000 RBX: ffff8805c0ac3d94 RCX:\n0000000000000100\n[ 474.287018] RDX: ffff8805e8aac000 RSI: 00000000ffffffff RDI:\nffff8805e8aaa000\n[ 474.321199] RBP: ffff8805c0ac3cb8 R08: 0000000000000010 R09:\n0000000000000006\n[ 474.357446] R10: 0000000000000000 R11: ffff8805c567a000 R12:\n0000000000000006\n[ 474.419191] R13: ffff8805c2b74e88 R14: 00000000000001da R15:\n0000000000000000\n[ 474.453816] FS: 00007f2e75220800(0000) GS:ffff88061fc00000(0000)\nknlGS:0000000000000000\n[ 474.489254] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033\n[ 474.522215] CR2: 00007f2e74716090 CR3: 00000005c085e000 CR4:\n00000000000207f0\n[ 474.556058] Stack:\n[ 474.584325] ffff8805c0ac3c98 ffffffff811b549b ffff8805c0ac3c98\nffff8805f1190a40\n[ 474.618913] ffff8805a6202f08 ffff8805c2b74e88 00068800d0464990\nffff8805e8aac860\n[ 474.653955] ffff8805c0ac3cb8 000700068113833a ffff880606c75060\nffff8805c0ac3d94\n[ 474.690461] Call Trace:\n[ 474.723779] [] ? lookup_fast+0x1cd/0x22a\n[ 474.778049] [] security_compute_av+0xf4/0x20b\n[ 474.811398] [] avc_compute_av+0x2a/0x179\n[ 474.843813] [] avc_has_perm+0x45/0xf4\n[ 474.875694] [] inode_has_perm+0x2a/0x31\n[ 474.907370] [] selinux_inode_getattr+0x3c/0x3e\n[ 474.938726] [] security_inode_getattr+0x1b/0x22\n[ 474.970036] [] vfs_getattr+0x19/0x2d\n[ 475.000618] [] vfs_fstatat+0x54/0x91\n[ 475.030402] [] vfs_lstat+0x19/0x1b\n[ 475.061097] [] SyS_newlstat+0x15/0x30\n[ 475.094595] [] ? __audit_syscall_entry+0xa1/0xc3\n[ 475.148405] [] system_call_fastpath+0x16/0x1b\n[ 475.179201] Code: 00 48 85 c0 48 89 45 b8 75 02 0f 0b 48 8b 45 a0 48\n8b 3d 45 d0 b6 00 8b 40 08 89 c6 ff ce e8 d1 b0 06 00 48 85 c0 49 89 c7\n75 02 <0f> 0b 48 8b 45 b8 4c 8b 28 eb 1e 49 8d 7d 08 be 80 01 00 00 e8\n[ 475.255884] RIP []\ncontext_struct_compute_av+0xce/0x308\n[ 475.296120] RSP \n[ 475.328734] ---[ end trace f076482e9d754adc ]---\n\nReported-by: Matthew Thode \nSigned-off-by: Stephen Smalley \nCc: stable@vger.kernel.org\nSigned-off-by: Paul Moore '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)\n{\n int64_t pos = avio_tell(pb);\n int version = 0;\n uint32_t tag = track->tag;\n\n if (track->mode == MODE_MOV) {\n if (track->timescale > UINT16_MAX) {\n if (mov_get_lpcm_flags(track->par->codec_id))\n tag = AV_RL32(\"lpcm\");\n version = 2;\n } else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) ||\n mov_pcm_be_gt16(track->par->codec_id) ||\n track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||\n track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||\n track->par->codec_id == AV_CODEC_ID_QDM2) {\n version = 1;\n }\n }\n\n avio_wb32(pb, 0); /* size */\n if (mov->encryption_scheme != MOV_ENC_NONE) {\n ffio_wfourcc(pb, \"enca\");\n } else {\n avio_wl32(pb, tag); // store it byteswapped\n }\n avio_wb32(pb, 0); /* Reserved */\n avio_wb16(pb, 0); /* Reserved */\n avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */\n\n /* SoundDescription */\n avio_wb16(pb, version); /* Version */\n avio_wb16(pb, 0); /* Revision level */\n avio_wb32(pb, 0); /* Reserved */\n\n if (version == 2) {\n avio_wb16(pb, 3);\n avio_wb16(pb, 16);\n avio_wb16(pb, 0xfffe);\n avio_wb16(pb, 0);\n avio_wb32(pb, 0x00010000);\n avio_wb32(pb, 72);\n avio_wb64(pb, av_double2int(track->par->sample_rate));\n avio_wb32(pb, track->par->channels);\n avio_wb32(pb, 0x7F000000);\n avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id));\n avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id));\n avio_wb32(pb, track->sample_size);\n avio_wb32(pb, get_samples_per_packet(track));\n } else {\n if (track->mode == MODE_MOV) {\n avio_wb16(pb, track->par->channels);\n if (track->par->codec_id == AV_CODEC_ID_PCM_U8 ||\n track->par->codec_id == AV_CODEC_ID_PCM_S8)\n avio_wb16(pb, 8); /* bits per sample */\n else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726)\n avio_wb16(pb, track->par->bits_per_coded_sample);\n else\n avio_wb16(pb, 16);\n avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */\n } else { /* reserved for mp4/3gp */\n if (track->par->codec_id == AV_CODEC_ID_FLAC ||\n track->par->codec_id == AV_CODEC_ID_OPUS) {\n avio_wb16(pb, track->par->channels);\n } else {\n avio_wb16(pb, 2);\n }\n if (track->par->codec_id == AV_CODEC_ID_FLAC) {\n avio_wb16(pb, track->par->bits_per_raw_sample);\n } else {\n avio_wb16(pb, 16);\n }\n avio_wb16(pb, 0);\n }\n\n avio_wb16(pb, 0); /* packet size (= 0) */\n if (track->par->codec_id == AV_CODEC_ID_OPUS)\n avio_wb16(pb, 48000);\n else\n avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ?\n track->par->sample_rate : 0);\n avio_wb16(pb, 0); /* Reserved */\n }\n\n if (version == 1) { /* SoundDescription V1 extended info */\n if (mov_pcm_le_gt16(track->par->codec_id) ||\n mov_pcm_be_gt16(track->par->codec_id))\n avio_wb32(pb, 1); /* must be 1 for uncompressed formats */\n else\n avio_wb32(pb, track->par->frame_size); /* Samples per packet */\n avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */\n avio_wb32(pb, track->sample_size); /* Bytes per frame */\n avio_wb32(pb, 2); /* Bytes per sample */\n }\n\n if (track->mode == MODE_MOV &&\n (track->par->codec_id == AV_CODEC_ID_AAC ||\n track->par->codec_id == AV_CODEC_ID_AC3 ||\n track->par->codec_id == AV_CODEC_ID_EAC3 ||\n track->par->codec_id == AV_CODEC_ID_AMR_NB ||\n track->par->codec_id == AV_CODEC_ID_ALAC ||\n track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||\n track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||\n track->par->codec_id == AV_CODEC_ID_QDM2 ||\n (mov_pcm_le_gt16(track->par->codec_id) && version==1) ||\n (mov_pcm_be_gt16(track->par->codec_id) && version==1)))\n mov_write_wave_tag(s, pb, track);\n else if (track->tag == MKTAG('m','p','4','a'))\n mov_write_esds_tag(pb, track);\n else if (track->par->codec_id == AV_CODEC_ID_AMR_NB)\n mov_write_amr_tag(pb, track);\n else if (track->par->codec_id == AV_CODEC_ID_AC3)\n mov_write_ac3_tag(pb, track);\n else if (track->par->codec_id == AV_CODEC_ID_EAC3)\n mov_write_eac3_tag(pb, track);\n else if (track->par->codec_id == AV_CODEC_ID_ALAC)\n mov_write_extradata_tag(pb, track);\n else if (track->par->codec_id == AV_CODEC_ID_WMAPRO)\n mov_write_wfex_tag(s, pb, track);\n else if (track->par->codec_id == AV_CODEC_ID_FLAC)\n mov_write_dfla_tag(pb, track);\n else if (track->par->codec_id == AV_CODEC_ID_OPUS)\n mov_write_dops_tag(pb, track);\n else if (track->vos_len > 0)\n mov_write_glbl_tag(pb, track);\n\n if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO)\n mov_write_chan_tag(s, pb, track);\n\n if (mov->encryption_scheme != MOV_ENC_NONE) {\n ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);\n }\n\n return update_size(pb, pos);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-369'], 'message': 'avformat/movenc: Write version 2 of audio atom if channels is not known\n\nThe version 1 needs the channel count and would divide by 0\nFixes: division by 0\nFixes: fpe_movenc.c_1108_1.ogg\nFixes: fpe_movenc.c_1108_2.ogg\nFixes: fpe_movenc.c_1108_3.wav\n\nFound-by: #CHEN HONGXU# \nSigned-off-by: Michael Niedermayer '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void put_prev_task(struct rq *rq, struct task_struct *prev)\n{\n\tif (prev->se.on_rq)\n\t\tupdate_rq_clock(rq);\n\trq->skip_clock_update = 0;\n\tprev->sched_class->put_prev_task(rq, prev);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-835'], 'message': 'Sched: fix skip_clock_update optimization\n\nidle_balance() drops/retakes rq->lock, leaving the previous task\nvulnerable to set_tsk_need_resched(). Clear it after we return\nfrom balancing instead, and in setup_thread_stack() as well, so\nno successfully descheduled or never scheduled task has it set.\n\nNeed resched confused the skip_clock_update logic, which assumes\nthat the next call to update_rq_clock() will come nearly immediately\nafter being set. Make the optimization robust against the waking\na sleeper before it sucessfully deschedules case by checking that\nthe current task has not been dequeued before setting the flag,\nsince it is that useless clock update we're trying to save, and\nclear unconditionally in schedule() proper instead of conditionally\nin put_prev_task().\n\nSigned-off-by: Mike Galbraith \nReported-by: Bjoern B. Brandenburg \nTested-by: Yong Zhang \nSigned-off-by: Peter Zijlstra \nCc: stable@kernel.org\nLKML-Reference: <1291802742.1417.9.camel@marge.simson.net>\nSigned-off-by: Ingo Molnar '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: \tswitch (yych) {\n\t\tcase 'a': goto yy51;\n\t\tdefault: goto yy48;\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Emit an error when repetition lower bound exceeds upper bound.\n\nHistorically this was allowed and re2c swapped the bounds. However, it\nmost likely indicates an error in user code and there is only a single\noccurrence in the tests (and the test in an artificial one), so although\nthe change is backwards incompatible there is low chance of breaking\nreal-world code.\n\nThis fixes second test case in the bug #394 \"Stack overflow due to\nrecursion in src/dfa/dead_rules.cc\" (the actual fix is to limit DFA size\nbut the test also has counted repetition with swapped bounds).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: \tswitch (yych) {\n\t\tcase 'a': goto yy20;\n\t\tdefault: goto yy21;\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Emit an error when repetition lower bound exceeds upper bound.\n\nHistorically this was allowed and re2c swapped the bounds. However, it\nmost likely indicates an error in user code and there is only a single\noccurrence in the tests (and the test in an artificial one), so although\nthe change is backwards incompatible there is low chance of breaking\nreal-world code.\n\nThis fixes second test case in the bug #394 \"Stack overflow due to\nrecursion in src/dfa/dead_rules.cc\" (the actual fix is to limit DFA size\nbut the test also has counted repetition with swapped bounds).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void Scanner::lex_c_comment()\n{\nloop:\n\n#line 3708 \"src/parse/lex.cc\"\n{\n\tunsigned char yych;\n\tif ((lim - cur) < 2) { if (!fill(2)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yych <= '\\f') {\n\t\tif (yych <= 0x00) goto yy554;\n\t\tif (yych == '\\n') goto yy558;\n\t\tgoto yy556;\n\t} else {\n\t\tif (yych <= '\\r') goto yy560;\n\t\tif (yych == '*') goto yy561;\n\t\tgoto yy556;\n\t}\nyy554:\n\t++cur;\n#line 722 \"../src/parse/lex.re\"\n\t{ fail_if_eof(); goto loop; }\n#line 3726 \"src/parse/lex.cc\"\nyy556:\n\t++cur;\nyy557:\n#line 723 \"../src/parse/lex.re\"\n\t{ goto loop; }\n#line 3732 \"src/parse/lex.cc\"\nyy558:\n\t++cur;\n#line 721 \"../src/parse/lex.re\"\n\t{ next_line(); goto loop; }\n#line 3737 \"src/parse/lex.cc\"\nyy560:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '\\n') goto yy558;\n\tgoto yy557;\nyy561:\n\tyych = (unsigned char)*++cur;\n\tif (yych != '/') goto yy557;\n\t++cur;\n#line 720 \"../src/parse/lex.re\"\n\t{ return; }\n#line 3748 \"src/parse/lex.cc\"\n}\n#line 724 \"../src/parse/lex.re\"\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Emit an error when repetition lower bound exceeds upper bound.\n\nHistorically this was allowed and re2c swapped the bounds. However, it\nmost likely indicates an error in user code and there is only a single\noccurrence in the tests (and the test in an artificial one), so although\nthe change is backwards incompatible there is low chance of breaking\nreal-world code.\n\nThis fixes second test case in the bug #394 \"Stack overflow due to\nrecursion in src/dfa/dead_rules.cc\" (the actual fix is to limit DFA size\nbut the test also has counted repetition with swapped bounds).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool Scanner::lex_namedef_context_flex()\n{\n\n#line 2739 \"src/parse/lex.cc\"\n{\n\tunsigned char yych;\n\tstatic const unsigned char yybm[] = {\n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 128, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t128, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t\t 0, 0, 0, 0, 0, 0, 0, 0, \n\t};\n\tif (lim <= cur) { if (!fill(1)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yych == '\\t') {\n\t\tyyt1 = cur;\n\t\tgoto yy416;\n\t}\n\tif (yych == ' ') {\n\t\tyyt1 = cur;\n\t\tgoto yy416;\n\t}\n#line 589 \"../src/parse/lex.re\"\n\t{ return false; }\n#line 2788 \"src/parse/lex.cc\"\nyy416:\n\t++cur;\n\tif (lim <= cur) { if (!fill(1)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yybm[0+yych] & 128) {\n\t\tgoto yy416;\n\t}\n\tif (yych <= '<') {\n\t\tif (yych == ':') goto yy419;\n\t} else {\n\t\tif (yych <= '=') goto yy419;\n\t\tif (yych == '{') goto yy419;\n\t}\n\tcur = yyt1;\n#line 588 \"../src/parse/lex.re\"\n\t{ return true; }\n#line 2805 \"src/parse/lex.cc\"\nyy419:\n\t++cur;\n\tcur = yyt1;\n#line 587 \"../src/parse/lex.re\"\n\t{ return false; }\n#line 2811 \"src/parse/lex.cc\"\n}\n#line 590 \"../src/parse/lex.re\"\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Emit an error when repetition lower bound exceeds upper bound.\n\nHistorically this was allowed and re2c swapped the bounds. However, it\nmost likely indicates an error in user code and there is only a single\noccurrence in the tests (and the test in an artificial one), so although\nthe change is backwards incompatible there is low chance of breaking\nreal-world code.\n\nThis fixes second test case in the bug #394 \"Stack overflow due to\nrecursion in src/dfa/dead_rules.cc\" (the actual fix is to limit DFA size\nbut the test also has counted repetition with swapped bounds).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: uint32_t Scanner::lex_cls_chr()\n{\n tok = cur;\n const loc_t &loc = cur_loc();\n #line 798 \"../src/parse/lex.re\"\n\n if (globopts->input_encoding == Enc::ASCII) {\n \n#line 3869 \"src/parse/lex.cc\"\n{\n\tunsigned char yych;\n\tunsigned int yyaccept = 0;\n\tif ((lim - cur) < 10) { if (!fill(10)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yych <= '\\f') {\n\t\tif (yych <= 0x00) goto yy587;\n\t\tif (yych == '\\n') goto yy591;\n\t\tgoto yy589;\n\t} else {\n\t\tif (yych <= '\\r') goto yy593;\n\t\tif (yych == '\\\\') goto yy594;\n\t\tgoto yy589;\n\t}\nyy587:\n\t++cur;\n#line 779 \"../src/parse/lex.re\"\n\t{ fail_if_eof(); return 0; }\n#line 3888 \"src/parse/lex.cc\"\nyy589:\n\t++cur;\nyy590:\n#line 781 \"../src/parse/lex.re\"\n\t{ return decode(tok); }\n#line 3894 \"src/parse/lex.cc\"\nyy591:\n\t++cur;\n#line 773 \"../src/parse/lex.re\"\n\t{ msg.error(loc, \"newline in character class\"); exit(1); }\n#line 3899 \"src/parse/lex.cc\"\nyy593:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '\\n') goto yy591;\n\tgoto yy590;\nyy594:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '\\\\') {\n\t\tif (yych <= '/') {\n\t\t\tif (yych <= '\\f') {\n\t\t\t\tif (yych <= 0x00) goto yy595;\n\t\t\t\tif (yych == '\\n') goto yy591;\n\t\t\t\tgoto yy596;\n\t\t\t} else {\n\t\t\t\tif (yych <= '\\r') goto yy598;\n\t\t\t\tif (yych == '-') goto yy599;\n\t\t\t\tgoto yy596;\n\t\t\t}\n\t\t} else {\n\t\t\tif (yych <= 'U') {\n\t\t\t\tif (yych <= '3') goto yy601;\n\t\t\t\tif (yych <= '7') goto yy603;\n\t\t\t\tif (yych <= 'T') goto yy596;\n\t\t\t\tgoto yy604;\n\t\t\t} else {\n\t\t\t\tif (yych == 'X') goto yy606;\n\t\t\t\tif (yych <= '[') goto yy596;\n\t\t\t\tgoto yy607;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif (yych <= 'n') {\n\t\t\tif (yych <= 'b') {\n\t\t\t\tif (yych <= ']') goto yy609;\n\t\t\t\tif (yych <= '`') goto yy596;\n\t\t\t\tif (yych <= 'a') goto yy611;\n\t\t\t\tgoto yy613;\n\t\t\t} else {\n\t\t\t\tif (yych == 'f') goto yy615;\n\t\t\t\tif (yych <= 'm') goto yy596;\n\t\t\t\tgoto yy617;\n\t\t\t}\n\t\t} else {\n\t\t\tif (yych <= 't') {\n\t\t\t\tif (yych == 'r') goto yy619;\n\t\t\t\tif (yych <= 's') goto yy596;\n\t\t\t\tgoto yy621;\n\t\t\t} else {\n\t\t\t\tif (yych <= 'v') {\n\t\t\t\t\tif (yych <= 'u') goto yy606;\n\t\t\t\t\tgoto yy623;\n\t\t\t\t} else {\n\t\t\t\t\tif (yych == 'x') goto yy625;\n\t\t\t\t\tgoto yy596;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\nyy595:\n#line 776 \"../src/parse/lex.re\"\n\t{ msg.error(loc, \"syntax error in escape sequence\"); exit(1); }\n#line 3960 \"src/parse/lex.cc\"\nyy596:\n\t++cur;\nyy597:\n#line 794 \"../src/parse/lex.re\"\n\t{\n msg.warn.useless_escape(loc, tok, cur);\n return decode(tok + 1);\n }\n#line 3969 \"src/parse/lex.cc\"\nyy598:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '\\n') goto yy591;\n\tgoto yy597;\nyy599:\n\t++cur;\n#line 792 \"../src/parse/lex.re\"\n\t{ return static_cast('-'); }\n#line 3978 \"src/parse/lex.cc\"\nyy601:\n\tyyaccept = 0;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych <= '/') goto yy602;\n\tif (yych <= '7') goto yy626;\nyy602:\n#line 775 \"../src/parse/lex.re\"\n\t{ msg.error(loc, \"syntax error in octal escape sequence\"); exit(1); }\n#line 3987 \"src/parse/lex.cc\"\nyy603:\n\t++cur;\n\tgoto yy602;\nyy604:\n\tyyaccept = 1;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy605;\n\t\tif (yych <= '9') goto yy628;\n\t} else {\n\t\tif (yych <= 'F') goto yy628;\n\t\tif (yych <= '`') goto yy605;\n\t\tif (yych <= 'f') goto yy628;\n\t}\nyy605:\n#line 774 \"../src/parse/lex.re\"\n\t{ msg.error(loc, \"syntax error in hexadecimal escape sequence\"); exit(1); }\n#line 4005 \"src/parse/lex.cc\"\nyy606:\n\tyyaccept = 1;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy605;\n\t\tif (yych <= '9') goto yy629;\n\t\tgoto yy605;\n\t} else {\n\t\tif (yych <= 'F') goto yy629;\n\t\tif (yych <= '`') goto yy605;\n\t\tif (yych <= 'f') goto yy629;\n\t\tgoto yy605;\n\t}\nyy607:\n\t++cur;\n#line 791 \"../src/parse/lex.re\"\n\t{ return static_cast('\\\\'); }\n#line 4023 \"src/parse/lex.cc\"\nyy609:\n\t++cur;\n#line 793 \"../src/parse/lex.re\"\n\t{ return static_cast(']'); }\n#line 4028 \"src/parse/lex.cc\"\nyy611:\n\t++cur;\n#line 784 \"../src/parse/lex.re\"\n\t{ return static_cast('\\a'); }\n#line 4033 \"src/parse/lex.cc\"\nyy613:\n\t++cur;\n#line 785 \"../src/parse/lex.re\"\n\t{ return static_cast('\\b'); }\n#line 4038 \"src/parse/lex.cc\"\nyy615:\n\t++cur;\n#line 786 \"../src/parse/lex.re\"\n\t{ return static_cast('\\f'); }\n#line 4043 \"src/parse/lex.cc\"\nyy617:\n\t++cur;\n#line 787 \"../src/parse/lex.re\"\n\t{ return static_cast('\\n'); }\n#line 4048 \"src/parse/lex.cc\"\nyy619:\n\t++cur;\n#line 788 \"../src/parse/lex.re\"\n\t{ return static_cast('\\r'); }\n#line 4053 \"src/parse/lex.cc\"\nyy621:\n\t++cur;\n#line 789 \"../src/parse/lex.re\"\n\t{ return static_cast('\\t'); }\n#line 4058 \"src/parse/lex.cc\"\nyy623:\n\t++cur;\n#line 790 \"../src/parse/lex.re\"\n\t{ return static_cast('\\v'); }\n#line 4063 \"src/parse/lex.cc\"\nyy625:\n\tyyaccept = 1;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy605;\n\t\tif (yych <= '9') goto yy630;\n\t\tgoto yy605;\n\t} else {\n\t\tif (yych <= 'F') goto yy630;\n\t\tif (yych <= '`') goto yy605;\n\t\tif (yych <= 'f') goto yy630;\n\t\tgoto yy605;\n\t}\nyy626:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '/') goto yy627;\n\tif (yych <= '7') goto yy631;\nyy627:\n\tcur = mar;\n\tif (yyaccept == 0) {\n\t\tgoto yy602;\n\t} else {\n\t\tgoto yy605;\n\t}\nyy628:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy627;\n\t\tif (yych <= '9') goto yy633;\n\t\tgoto yy627;\n\t} else {\n\t\tif (yych <= 'F') goto yy633;\n\t\tif (yych <= '`') goto yy627;\n\t\tif (yych <= 'f') goto yy633;\n\t\tgoto yy627;\n\t}\nyy629:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy627;\n\t\tif (yych <= '9') goto yy634;\n\t\tgoto yy627;\n\t} else {\n\t\tif (yych <= 'F') goto yy634;\n\t\tif (yych <= '`') goto yy627;\n\t\tif (yych <= 'f') goto yy634;\n\t\tgoto yy627;\n\t}\nyy630:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy627;\n\t\tif (yych <= '9') goto yy635;\n\t\tgoto yy627;\n\t} else {\n\t\tif (yych <= 'F') goto yy635;\n\t\tif (yych <= '`') goto yy627;\n\t\tif (yych <= 'f') goto yy635;\n\t\tgoto yy627;\n\t}\nyy631:\n\t++cur;\n#line 783 \"../src/parse/lex.re\"\n\t{ return unesc_oct(tok, cur); }\n#line 4128 \"src/parse/lex.cc\"\nyy633:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy627;\n\t\tif (yych <= '9') goto yy637;\n\t\tgoto yy627;\n\t} else {\n\t\tif (yych <= 'F') goto yy637;\n\t\tif (yych <= '`') goto yy627;\n\t\tif (yych <= 'f') goto yy637;\n\t\tgoto yy627;\n\t}\nyy634:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy627;\n\t\tif (yych <= '9') goto yy630;\n\t\tgoto yy627;\n\t} else {\n\t\tif (yych <= 'F') goto yy630;\n\t\tif (yych <= '`') goto yy627;\n\t\tif (yych <= 'f') goto yy630;\n\t\tgoto yy627;\n\t}\nyy635:\n\t++cur;\n#line 782 \"../src/parse/lex.re\"\n\t{ return unesc_hex(tok, cur); }\n#line 4157 \"src/parse/lex.cc\"\nyy637:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy627;\n\t\tif (yych >= ':') goto yy627;\n\t} else {\n\t\tif (yych <= 'F') goto yy638;\n\t\tif (yych <= '`') goto yy627;\n\t\tif (yych >= 'g') goto yy627;\n\t}\nyy638:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy627;\n\t\tif (yych <= '9') goto yy629;\n\t\tgoto yy627;\n\t} else {\n\t\tif (yych <= 'F') goto yy629;\n\t\tif (yych <= '`') goto yy627;\n\t\tif (yych <= 'f') goto yy629;\n\t\tgoto yy627;\n\t}\n}\n#line 800 \"../src/parse/lex.re\"\n\n }\n else {\n \n#line 4186 \"src/parse/lex.cc\"\n{\n\tunsigned char yych;\n\tunsigned int yyaccept = 0;\n\tif ((lim - cur) < 10) { if (!fill(10)) { error(\"unexpected end of input\"); exit(1); } }\n\tyych = (unsigned char)*cur;\n\tif (yych <= 0x7F) {\n\t\tif (yych <= '\\f') {\n\t\t\tif (yych <= 0x00) goto yy641;\n\t\t\tif (yych == '\\n') goto yy645;\n\t\t\tgoto yy643;\n\t\t} else {\n\t\t\tif (yych <= '\\r') goto yy647;\n\t\t\tif (yych == '\\\\') goto yy648;\n\t\t\tgoto yy643;\n\t\t}\n\t} else {\n\t\tif (yych <= 0xEF) {\n\t\t\tif (yych <= 0xC1) goto yy650;\n\t\t\tif (yych <= 0xDF) goto yy652;\n\t\t\tif (yych <= 0xE0) goto yy653;\n\t\t\tgoto yy654;\n\t\t} else {\n\t\t\tif (yych <= 0xF0) goto yy655;\n\t\t\tif (yych <= 0xF3) goto yy656;\n\t\t\tif (yych <= 0xF4) goto yy657;\n\t\t\tgoto yy650;\n\t\t}\n\t}\nyy641:\n\t++cur;\n#line 779 \"../src/parse/lex.re\"\n\t{ fail_if_eof(); return 0; }\n#line 4219 \"src/parse/lex.cc\"\nyy643:\n\t++cur;\nyy644:\n#line 781 \"../src/parse/lex.re\"\n\t{ return decode(tok); }\n#line 4225 \"src/parse/lex.cc\"\nyy645:\n\t++cur;\n#line 773 \"../src/parse/lex.re\"\n\t{ msg.error(loc, \"newline in character class\"); exit(1); }\n#line 4230 \"src/parse/lex.cc\"\nyy647:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '\\n') goto yy645;\n\tgoto yy644;\nyy648:\n\tyyaccept = 0;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych <= 'b') {\n\t\tif (yych <= '7') {\n\t\t\tif (yych <= '\\r') {\n\t\t\t\tif (yych <= '\\t') {\n\t\t\t\t\tif (yych >= 0x01) goto yy658;\n\t\t\t\t} else {\n\t\t\t\t\tif (yych <= '\\n') goto yy645;\n\t\t\t\t\tif (yych <= '\\f') goto yy658;\n\t\t\t\t\tgoto yy660;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (yych <= '-') {\n\t\t\t\t\tif (yych <= ',') goto yy658;\n\t\t\t\t\tgoto yy661;\n\t\t\t\t} else {\n\t\t\t\t\tif (yych <= '/') goto yy658;\n\t\t\t\t\tif (yych <= '3') goto yy663;\n\t\t\t\t\tgoto yy665;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif (yych <= '[') {\n\t\t\t\tif (yych <= 'U') {\n\t\t\t\t\tif (yych <= 'T') goto yy658;\n\t\t\t\t\tgoto yy666;\n\t\t\t\t} else {\n\t\t\t\t\tif (yych == 'X') goto yy668;\n\t\t\t\t\tgoto yy658;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (yych <= ']') {\n\t\t\t\t\tif (yych <= '\\\\') goto yy669;\n\t\t\t\t\tgoto yy671;\n\t\t\t\t} else {\n\t\t\t\t\tif (yych <= '`') goto yy658;\n\t\t\t\t\tif (yych <= 'a') goto yy673;\n\t\t\t\t\tgoto yy675;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif (yych <= 'v') {\n\t\t\tif (yych <= 'q') {\n\t\t\t\tif (yych <= 'f') {\n\t\t\t\t\tif (yych <= 'e') goto yy658;\n\t\t\t\t\tgoto yy677;\n\t\t\t\t} else {\n\t\t\t\t\tif (yych == 'n') goto yy679;\n\t\t\t\t\tgoto yy658;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (yych <= 's') {\n\t\t\t\t\tif (yych <= 'r') goto yy681;\n\t\t\t\t\tgoto yy658;\n\t\t\t\t} else {\n\t\t\t\t\tif (yych <= 't') goto yy683;\n\t\t\t\t\tif (yych <= 'u') goto yy668;\n\t\t\t\t\tgoto yy685;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif (yych <= 0xDF) {\n\t\t\t\tif (yych <= 'x') {\n\t\t\t\t\tif (yych <= 'w') goto yy658;\n\t\t\t\t\tgoto yy687;\n\t\t\t\t} else {\n\t\t\t\t\tif (yych <= 0x7F) goto yy658;\n\t\t\t\t\tif (yych >= 0xC2) goto yy688;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (yych <= 0xF0) {\n\t\t\t\t\tif (yych <= 0xE0) goto yy690;\n\t\t\t\t\tif (yych <= 0xEF) goto yy691;\n\t\t\t\t\tgoto yy692;\n\t\t\t\t} else {\n\t\t\t\t\tif (yych <= 0xF3) goto yy693;\n\t\t\t\t\tif (yych <= 0xF4) goto yy694;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\nyy649:\n#line 776 \"../src/parse/lex.re\"\n\t{ msg.error(loc, \"syntax error in escape sequence\"); exit(1); }\n#line 4322 \"src/parse/lex.cc\"\nyy650:\n\t++cur;\nyy651:\n#line 777 \"../src/parse/lex.re\"\n\t{ msg.error(loc, \"syntax error\"); exit(1); }\n#line 4328 \"src/parse/lex.cc\"\nyy652:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= 0x7F) goto yy651;\n\tif (yych <= 0xBF) goto yy643;\n\tgoto yy651;\nyy653:\n\tyyaccept = 1;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych <= 0x9F) goto yy651;\n\tif (yych <= 0xBF) goto yy695;\n\tgoto yy651;\nyy654:\n\tyyaccept = 1;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych <= 0x7F) goto yy651;\n\tif (yych <= 0xBF) goto yy695;\n\tgoto yy651;\nyy655:\n\tyyaccept = 1;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych <= 0x8F) goto yy651;\n\tif (yych <= 0xBF) goto yy696;\n\tgoto yy651;\nyy656:\n\tyyaccept = 1;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych <= 0x7F) goto yy651;\n\tif (yych <= 0xBF) goto yy696;\n\tgoto yy651;\nyy657:\n\tyyaccept = 1;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych <= 0x7F) goto yy651;\n\tif (yych <= 0x8F) goto yy696;\n\tgoto yy651;\nyy658:\n\t++cur;\nyy659:\n#line 794 \"../src/parse/lex.re\"\n\t{\n msg.warn.useless_escape(loc, tok, cur);\n return decode(tok + 1);\n }\n#line 4372 \"src/parse/lex.cc\"\nyy660:\n\tyych = (unsigned char)*++cur;\n\tif (yych == '\\n') goto yy645;\n\tgoto yy659;\nyy661:\n\t++cur;\n#line 792 \"../src/parse/lex.re\"\n\t{ return static_cast('-'); }\n#line 4381 \"src/parse/lex.cc\"\nyy663:\n\tyyaccept = 2;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych <= '/') goto yy664;\n\tif (yych <= '7') goto yy697;\nyy664:\n#line 775 \"../src/parse/lex.re\"\n\t{ msg.error(loc, \"syntax error in octal escape sequence\"); exit(1); }\n#line 4390 \"src/parse/lex.cc\"\nyy665:\n\t++cur;\n\tgoto yy664;\nyy666:\n\tyyaccept = 3;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy667;\n\t\tif (yych <= '9') goto yy698;\n\t} else {\n\t\tif (yych <= 'F') goto yy698;\n\t\tif (yych <= '`') goto yy667;\n\t\tif (yych <= 'f') goto yy698;\n\t}\nyy667:\n#line 774 \"../src/parse/lex.re\"\n\t{ msg.error(loc, \"syntax error in hexadecimal escape sequence\"); exit(1); }\n#line 4408 \"src/parse/lex.cc\"\nyy668:\n\tyyaccept = 3;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy667;\n\t\tif (yych <= '9') goto yy699;\n\t\tgoto yy667;\n\t} else {\n\t\tif (yych <= 'F') goto yy699;\n\t\tif (yych <= '`') goto yy667;\n\t\tif (yych <= 'f') goto yy699;\n\t\tgoto yy667;\n\t}\nyy669:\n\t++cur;\n#line 791 \"../src/parse/lex.re\"\n\t{ return static_cast('\\\\'); }\n#line 4426 \"src/parse/lex.cc\"\nyy671:\n\t++cur;\n#line 793 \"../src/parse/lex.re\"\n\t{ return static_cast(']'); }\n#line 4431 \"src/parse/lex.cc\"\nyy673:\n\t++cur;\n#line 784 \"../src/parse/lex.re\"\n\t{ return static_cast('\\a'); }\n#line 4436 \"src/parse/lex.cc\"\nyy675:\n\t++cur;\n#line 785 \"../src/parse/lex.re\"\n\t{ return static_cast('\\b'); }\n#line 4441 \"src/parse/lex.cc\"\nyy677:\n\t++cur;\n#line 786 \"../src/parse/lex.re\"\n\t{ return static_cast('\\f'); }\n#line 4446 \"src/parse/lex.cc\"\nyy679:\n\t++cur;\n#line 787 \"../src/parse/lex.re\"\n\t{ return static_cast('\\n'); }\n#line 4451 \"src/parse/lex.cc\"\nyy681:\n\t++cur;\n#line 788 \"../src/parse/lex.re\"\n\t{ return static_cast('\\r'); }\n#line 4456 \"src/parse/lex.cc\"\nyy683:\n\t++cur;\n#line 789 \"../src/parse/lex.re\"\n\t{ return static_cast('\\t'); }\n#line 4461 \"src/parse/lex.cc\"\nyy685:\n\t++cur;\n#line 790 \"../src/parse/lex.re\"\n\t{ return static_cast('\\v'); }\n#line 4466 \"src/parse/lex.cc\"\nyy687:\n\tyyaccept = 3;\n\tyych = (unsigned char)*(mar = ++cur);\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy667;\n\t\tif (yych <= '9') goto yy700;\n\t\tgoto yy667;\n\t} else {\n\t\tif (yych <= 'F') goto yy700;\n\t\tif (yych <= '`') goto yy667;\n\t\tif (yych <= 'f') goto yy700;\n\t\tgoto yy667;\n\t}\nyy688:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= 0x7F) goto yy689;\n\tif (yych <= 0xBF) goto yy658;\nyy689:\n\tcur = mar;\n\tif (yyaccept <= 1) {\n\t\tif (yyaccept == 0) {\n\t\t\tgoto yy649;\n\t\t} else {\n\t\t\tgoto yy651;\n\t\t}\n\t} else {\n\t\tif (yyaccept == 2) {\n\t\t\tgoto yy664;\n\t\t} else {\n\t\t\tgoto yy667;\n\t\t}\n\t}\nyy690:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= 0x9F) goto yy689;\n\tif (yych <= 0xBF) goto yy688;\n\tgoto yy689;\nyy691:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= 0x7F) goto yy689;\n\tif (yych <= 0xBF) goto yy688;\n\tgoto yy689;\nyy692:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= 0x8F) goto yy689;\n\tif (yych <= 0xBF) goto yy691;\n\tgoto yy689;\nyy693:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= 0x7F) goto yy689;\n\tif (yych <= 0xBF) goto yy691;\n\tgoto yy689;\nyy694:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= 0x7F) goto yy689;\n\tif (yych <= 0x8F) goto yy691;\n\tgoto yy689;\nyy695:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= 0x7F) goto yy689;\n\tif (yych <= 0xBF) goto yy643;\n\tgoto yy689;\nyy696:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= 0x7F) goto yy689;\n\tif (yych <= 0xBF) goto yy695;\n\tgoto yy689;\nyy697:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '/') goto yy689;\n\tif (yych <= '7') goto yy701;\n\tgoto yy689;\nyy698:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy689;\n\t\tif (yych <= '9') goto yy703;\n\t\tgoto yy689;\n\t} else {\n\t\tif (yych <= 'F') goto yy703;\n\t\tif (yych <= '`') goto yy689;\n\t\tif (yych <= 'f') goto yy703;\n\t\tgoto yy689;\n\t}\nyy699:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy689;\n\t\tif (yych <= '9') goto yy704;\n\t\tgoto yy689;\n\t} else {\n\t\tif (yych <= 'F') goto yy704;\n\t\tif (yych <= '`') goto yy689;\n\t\tif (yych <= 'f') goto yy704;\n\t\tgoto yy689;\n\t}\nyy700:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy689;\n\t\tif (yych <= '9') goto yy705;\n\t\tgoto yy689;\n\t} else {\n\t\tif (yych <= 'F') goto yy705;\n\t\tif (yych <= '`') goto yy689;\n\t\tif (yych <= 'f') goto yy705;\n\t\tgoto yy689;\n\t}\nyy701:\n\t++cur;\n#line 783 \"../src/parse/lex.re\"\n\t{ return unesc_oct(tok, cur); }\n#line 4579 \"src/parse/lex.cc\"\nyy703:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy689;\n\t\tif (yych <= '9') goto yy707;\n\t\tgoto yy689;\n\t} else {\n\t\tif (yych <= 'F') goto yy707;\n\t\tif (yych <= '`') goto yy689;\n\t\tif (yych <= 'f') goto yy707;\n\t\tgoto yy689;\n\t}\nyy704:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy689;\n\t\tif (yych <= '9') goto yy700;\n\t\tgoto yy689;\n\t} else {\n\t\tif (yych <= 'F') goto yy700;\n\t\tif (yych <= '`') goto yy689;\n\t\tif (yych <= 'f') goto yy700;\n\t\tgoto yy689;\n\t}\nyy705:\n\t++cur;\n#line 782 \"../src/parse/lex.re\"\n\t{ return unesc_hex(tok, cur); }\n#line 4608 \"src/parse/lex.cc\"\nyy707:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy689;\n\t\tif (yych >= ':') goto yy689;\n\t} else {\n\t\tif (yych <= 'F') goto yy708;\n\t\tif (yych <= '`') goto yy689;\n\t\tif (yych >= 'g') goto yy689;\n\t}\nyy708:\n\tyych = (unsigned char)*++cur;\n\tif (yych <= '@') {\n\t\tif (yych <= '/') goto yy689;\n\t\tif (yych <= '9') goto yy699;\n\t\tgoto yy689;\n\t} else {\n\t\tif (yych <= 'F') goto yy699;\n\t\tif (yych <= '`') goto yy689;\n\t\tif (yych <= 'f') goto yy699;\n\t\tgoto yy689;\n\t}\n}\n#line 803 \"../src/parse/lex.re\"\n\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Emit an error when repetition lower bound exceeds upper bound.\n\nHistorically this was allowed and re2c swapped the bounds. However, it\nmost likely indicates an error in user code and there is only a single\noccurrence in the tests (and the test in an artificial one), so although\nthe change is backwards incompatible there is low chance of breaking\nreal-world code.\n\nThis fixes second test case in the bug #394 \"Stack overflow due to\nrecursion in src/dfa/dead_rules.cc\" (the actual fix is to limit DFA size\nbut the test also has counted repetition with swapped bounds).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void initialize() override {\n setMaxRequestHeadersKb(60);\n setMaxRequestHeadersCount(100);\n envoy::config::route::v3::RetryPolicy retry_policy;\n\n auto pass_through = config_helper_.createVirtualHost(\"pass.through.internal.redirect\");\n config_helper_.addVirtualHost(pass_through);\n\n auto handle = config_helper_.createVirtualHost(\"handle.internal.redirect\");\n handle.mutable_routes(0)->set_name(\"redirect\");\n handle.mutable_routes(0)->mutable_route()->mutable_internal_redirect_policy();\n config_helper_.addVirtualHost(handle);\n\n auto handle_max_3_hop =\n config_helper_.createVirtualHost(\"handle.internal.redirect.max.three.hop\");\n handle_max_3_hop.mutable_routes(0)->set_name(\"max_three_hop\");\n handle_max_3_hop.mutable_routes(0)->mutable_route()->mutable_internal_redirect_policy();\n handle_max_3_hop.mutable_routes(0)\n ->mutable_route()\n ->mutable_internal_redirect_policy()\n ->mutable_max_internal_redirects()\n ->set_value(3);\n config_helper_.addVirtualHost(handle_max_3_hop);\n\n HttpProtocolIntegrationTest::initialize();\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': '[1.18] CVE-2022-21655\n\nCrash with direct_response\n\nSigned-off-by: Otto van der Schaaf '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: pim_print(netdissect_options *ndo,\n register const u_char *bp, register u_int len, const u_char *bp2)\n{\n\tregister const u_char *ep;\n\tregister const struct pim *pim = (const struct pim *)bp;\n\n\tep = (const u_char *)ndo->ndo_snapend;\n\tif (bp >= ep)\n\t\treturn;\n#ifdef notyet\t\t\t/* currently we see only version and type */\n\tND_TCHECK(pim->pim_rsv);\n#endif\n\n\tswitch (PIM_VER(pim->pim_typever)) {\n\tcase 2:\n\t\tif (!ndo->ndo_vflag) {\n\t\t\tND_PRINT((ndo, \"PIMv%u, %s, length %u\",\n\t\t\t PIM_VER(pim->pim_typever),\n\t\t\t tok2str(pimv2_type_values,\"Unknown Type\",PIM_TYPE(pim->pim_typever)),\n\t\t\t len));\n\t\t\treturn;\n\t\t} else {\n\t\t\tND_PRINT((ndo, \"PIMv%u, length %u\\n\\t%s\",\n\t\t\t PIM_VER(pim->pim_typever),\n\t\t\t len,\n\t\t\t tok2str(pimv2_type_values,\"Unknown Type\",PIM_TYPE(pim->pim_typever))));\n\t\t\tpimv2_print(ndo, bp, len, bp2);\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\tND_PRINT((ndo, \"PIMv%u, length %u\",\n\t\t PIM_VER(pim->pim_typever),\n\t\t len));\n\t\tbreak;\n\t}\n\treturn;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13030/PIM: Redo bounds checks and add length checks.\n\nUse ND_TCHECK macros to do bounds checking, and add length checks before\nthe bounds checks.\n\nAdd a bounds check that the review process found was missing.\n\nThis fixes a buffer over-read discovered by Bhargava Shastry,\nSecT/TU Berlin.\n\nAdd a test using the capture file supplied by the reporter(s), modified\nso the capture file won't be rejected as an invalid capture.\n\nUpdate one test output file to reflect the changes.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: CreateForeignServer(CreateForeignServerStmt *stmt)\n{\n\tRelation\trel;\n\tDatum\t\tsrvoptions;\n\tDatum\t\tvalues[Natts_pg_foreign_server];\n\tbool\t\tnulls[Natts_pg_foreign_server];\n\tHeapTuple\ttuple;\n\tOid\t\t\tsrvId;\n\tOid\t\t\townerId;\n\tAclResult\taclresult;\n\tObjectAddress myself;\n\tObjectAddress referenced;\n\tForeignDataWrapper *fdw;\n\n\trel = heap_open(ForeignServerRelationId, RowExclusiveLock);\n\n\t/* For now the owner cannot be specified on create. Use effective user ID. */\n\townerId = GetUserId();\n\n\t/*\n\t * Check that there is no other foreign server by this name. Do nothing if\n\t * IF NOT EXISTS was enforced.\n\t */\n\tif (GetForeignServerByName(stmt->servername, true) != NULL)\n\t{\n\t\tif (stmt->if_not_exists)\n\t\t{\n\t\t\tereport(NOTICE,\n\t\t\t\t\t(errcode(ERRCODE_DUPLICATE_OBJECT),\n\t\t\t\t\t errmsg(\"server \\\"%s\\\" already exists, skipping\",\n\t\t\t\t\t\t\tstmt->servername)));\n\t\t\theap_close(rel, RowExclusiveLock);\n\t\t\treturn InvalidObjectAddress;\n\t\t}\n\t\telse\n\t\t\tereport(ERROR,\n\t\t\t\t\t(errcode(ERRCODE_DUPLICATE_OBJECT),\n\t\t\t\t\t errmsg(\"server \\\"%s\\\" already exists\",\n\t\t\t\t\t\t\tstmt->servername)));\n\t}\n\n\t/*\n\t * Check that the FDW exists and that we have USAGE on it. Also get the\n\t * actual FDW for option validation etc.\n\t */\n\tfdw = GetForeignDataWrapperByName(stmt->fdwname, false);\n\n\taclresult = pg_foreign_data_wrapper_aclcheck(fdw->fdwid, ownerId, ACL_USAGE);\n\tif (aclresult != ACLCHECK_OK)\n\t\taclcheck_error(aclresult, OBJECT_FDW, fdw->fdwname);\n\n\t/*\n\t * Insert tuple into pg_foreign_server.\n\t */\n\tmemset(values, 0, sizeof(values));\n\tmemset(nulls, false, sizeof(nulls));\n\n\tvalues[Anum_pg_foreign_server_srvname - 1] =\n\t\tDirectFunctionCall1(namein, CStringGetDatum(stmt->servername));\n\tvalues[Anum_pg_foreign_server_srvowner - 1] = ObjectIdGetDatum(ownerId);\n\tvalues[Anum_pg_foreign_server_srvfdw - 1] = ObjectIdGetDatum(fdw->fdwid);\n\n\t/* Add server type if supplied */\n\tif (stmt->servertype)\n\t\tvalues[Anum_pg_foreign_server_srvtype - 1] =\n\t\t\tCStringGetTextDatum(stmt->servertype);\n\telse\n\t\tnulls[Anum_pg_foreign_server_srvtype - 1] = true;\n\n\t/* Add server version if supplied */\n\tif (stmt->version)\n\t\tvalues[Anum_pg_foreign_server_srvversion - 1] =\n\t\t\tCStringGetTextDatum(stmt->version);\n\telse\n\t\tnulls[Anum_pg_foreign_server_srvversion - 1] = true;\n\n\t/* Start with a blank acl */\n\tnulls[Anum_pg_foreign_server_srvacl - 1] = true;\n\n\t/* Add server options */\n\tsrvoptions = transformGenericOptions(ForeignServerRelationId,\n\t\t\t\t\t\t\t\t\t\t PointerGetDatum(NULL),\n\t\t\t\t\t\t\t\t\t\t stmt->options,\n\t\t\t\t\t\t\t\t\t\t fdw->fdwvalidator);\n\n\tif (PointerIsValid(DatumGetPointer(srvoptions)))\n\t\tvalues[Anum_pg_foreign_server_srvoptions - 1] = srvoptions;\n\telse\n\t\tnulls[Anum_pg_foreign_server_srvoptions - 1] = true;\n\n\ttuple = heap_form_tuple(rel->rd_att, values, nulls);\n\n\tsrvId = CatalogTupleInsert(rel, tuple);\n\n\theap_freetuple(tuple);\n\n\t/* record dependencies */\n\tmyself.classId = ForeignServerRelationId;\n\tmyself.objectId = srvId;\n\tmyself.objectSubId = 0;\n\n\treferenced.classId = ForeignDataWrapperRelationId;\n\treferenced.objectId = fdw->fdwid;\n\treferenced.objectSubId = 0;\n\trecordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);\n\n\trecordDependencyOnOwner(ForeignServerRelationId, srvId, ownerId);\n\n\t/* dependency on extension */\n\trecordDependencyOnCurrentExtension(&myself, false);\n\n\t/* Post creation hook for new foreign server */\n\tInvokeObjectPostCreateHook(ForeignServerRelationId, srvId, 0);\n\n\theap_close(rel, RowExclusiveLock);\n\n\treturn myself;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-94'], 'message': 'In extensions, don't replace objects not belonging to the extension.\n\nPreviously, if an extension script did CREATE OR REPLACE and there was\nan existing object not belonging to the extension, it would overwrite\nthe object and adopt it into the extension. This is problematic, first\nbecause the overwrite is probably unintentional, and second because we\ndidn't change the object's ownership. Thus a hostile user could create\nan object in advance of an expected CREATE EXTENSION command, and would\nthen have ownership rights on an extension object, which could be\nmodified for trojan-horse-type attacks.\n\nHence, forbid CREATE OR REPLACE of an existing object unless it already\nbelongs to the extension. (Note that we've always forbidden replacing\nan object that belongs to some other extension; only the behavior for\npreviously-free-standing objects changes here.)\n\nFor the same reason, also fail CREATE IF NOT EXISTS when there is\nan existing object that doesn't belong to the extension.\n\nOur thanks to Sven Klemm for reporting this problem.\n\nSecurity: CVE-2022-2625'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: GIOChannel *net_connect_ip_ssl(IPADDR *ip, int port, IPADDR *my_ip, const char *cert, const char *pkey, const char *cafile, const char *capath, gboolean verify)\n{\n\tg_warning(\"Connection failed: SSL support not enabled in this build.\");\n\terrno = ENOSYS;\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Check if an SSL certificate matches the hostname of the server we are connecting to\n\ngit-svn-id: http://svn.irssi.org/repos/irssi/trunk@5104 dbcabf3a-b0e7-0310-adc4-f8d773084564'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void Compute(OpKernelContext* const context) override {\n // node_id_range\n const Tensor* node_id_range_t;\n OP_REQUIRES_OK(context, context->input(\"node_id_range\", &node_id_range_t));\n const auto node_id_range = node_id_range_t->vec();\n OP_REQUIRES(\n context, node_id_range_t->dims() == 1,\n errors::InvalidArgument(\"node_id_range must be a rank 1 tensor, but \"\n \"given node_id_range has dims of \",\n node_id_range_t->dims()));\n OP_REQUIRES(context, node_id_range_t->dim_size(0) == 2,\n errors::InvalidArgument(\n \"node_id_range must be a rank 1 tensor with shape=[2], but \"\n \"given node_id_range has shape \",\n node_id_range_t->dim_size(0), \" on its first dim\"));\n const int32_t node_id_first = node_id_range(0); // Inclusive.\n const int32_t node_id_last = node_id_range(1); // Exclusive.\n\n // Get stats_summaries_list.\n OpInputList stats_summaries_list;\n OP_REQUIRES_OK(context, context->input_list(\"stats_summaries_list\",\n &stats_summaries_list));\n\n // Infer dimensions of a stats_summary.\n DCHECK_GT(stats_summaries_list.size(), 0);\n const int32_t feature_dims = stats_summaries_list[0].dim_size(1);\n // The last bucket is for default/missing value.\n const int32_t num_buckets = stats_summaries_list[0].dim_size(2) - 1;\n const int32_t logits_dim = logits_dim_;\n const int32_t hessian_dim =\n stats_summaries_list[0].dim_size(3) - logits_dim;\n DCHECK_GT(hessian_dim, 0);\n DCHECK_LE(hessian_dim, logits_dim * logits_dim);\n\n // Vector of stats_summaries; each element is stats for feature of shape\n // [max_splits, feature_dim, num_buckets, logits_dim + hessian_dim].\n std::vector::ConstTensor> stats_summaries;\n DCHECK_EQ(stats_summaries_list.size(), num_features_);\n stats_summaries.reserve(num_features_);\n for (const auto& tensor : stats_summaries_list) {\n stats_summaries.emplace_back(tensor.tensor());\n }\n\n // Split types.\n const Tensor* split_types_t;\n OP_REQUIRES_OK(context, context->input(\"split_types\", &split_types_t));\n const auto split_types = split_types_t->vec();\n DCHECK_EQ(split_types.size(), num_features_);\n // Validate.\n for (int i = 0; i < num_features_; ++i) {\n if (!(split_types(i) == kInequalitySplit ||\n split_types(i) == kEqualitySplit)) {\n OP_REQUIRES_OK(\n context,\n errors::Aborted(\n \"Operation received an exception: Incorrect split type\"));\n }\n }\n // Feature ids.\n const Tensor* candidate_feature_ids_t;\n OP_REQUIRES_OK(context, context->input(\"candidate_feature_ids\",\n &candidate_feature_ids_t));\n const auto candidate_feature_ids = candidate_feature_ids_t->vec();\n DCHECK_EQ(candidate_feature_ids.size(), num_features_);\n\n // L1, L2, tree_complexity, min_node_weight.\n const Tensor* l1_t;\n OP_REQUIRES_OK(context, context->input(\"l1\", &l1_t));\n const auto l1 = l1_t->scalar()();\n DCHECK_GE(l1, 0);\n if (logits_dim_ > 1) {\n // Multi-class L1 regularization not supported yet.\n DCHECK_EQ(l1, 0);\n }\n const Tensor* l2_t;\n OP_REQUIRES_OK(context, context->input(\"l2\", &l2_t));\n const auto l2 = l2_t->scalar()();\n DCHECK_GE(l2, 0);\n const Tensor* tree_complexity_t;\n OP_REQUIRES_OK(context,\n context->input(\"tree_complexity\", &tree_complexity_t));\n const auto tree_complexity = tree_complexity_t->scalar()();\n const Tensor* min_node_weight_t;\n OP_REQUIRES_OK(context,\n context->input(\"min_node_weight\", &min_node_weight_t));\n const auto min_node_weight = min_node_weight_t->scalar()();\n\n std::vector output_node_ids;\n std::vector output_gains;\n std::vector output_feature_ids;\n std::vector output_feature_dimensions;\n std::vector output_thresholds;\n std::vector output_left_node_contribs;\n std::vector output_right_node_contribs;\n std::vector output_split_types;\n\n // TODO(tanzheny) parallelize the computation.\n // Iterate each node and find the best gain per node.\n float parent_gain;\n for (int32_t node_id = node_id_first; node_id < node_id_last; ++node_id) {\n float best_gain = std::numeric_limits::lowest();\n int32_t best_bucket;\n int32_t best_f_id;\n int32_t best_f_dim;\n string best_split_type;\n Eigen::VectorXf best_contrib_for_left(logits_dim);\n Eigen::VectorXf best_contrib_for_right(logits_dim);\n\n // Sum of gradient and hessian. Compute parent gain using first feature.\n ConstMatrixMap stats_mat(&stats_summaries[0](node_id, 0, 0, 0),\n num_buckets + 1, // Including default bucket.\n logits_dim + hessian_dim);\n const Eigen::VectorXf total_grad =\n stats_mat.leftCols(logits_dim).colwise().sum();\n const Eigen::VectorXf total_hess =\n stats_mat.rightCols(hessian_dim).colwise().sum();\n if (total_hess.norm() < min_node_weight) {\n continue;\n }\n Eigen::VectorXf unused(logits_dim);\n CalculateWeightsAndGains(total_grad, total_hess, l1, l2, &unused,\n &parent_gain);\n for (int f_idx = 0; f_idx < num_features_; ++f_idx) {\n const string split_type = split_types(f_idx);\n TTypes::ConstTensor stats_summary = stats_summaries[f_idx];\n float f_best_gain = std::numeric_limits::lowest();\n int32_t f_best_bucket;\n int32_t f_best_f_dim;\n string f_best_split_type;\n Eigen::VectorXf f_best_contrib_for_left(logits_dim);\n Eigen::VectorXf f_best_contrib_for_right(logits_dim);\n\n if (split_type == kInequalitySplit) {\n CalculateBestInequalitySplit(\n stats_summary, node_id, feature_dims, logits_dim, hessian_dim,\n num_buckets, min_node_weight, l1, l2, &f_best_gain,\n &f_best_bucket, &f_best_f_dim, &f_best_split_type,\n &f_best_contrib_for_left, &f_best_contrib_for_right);\n } else {\n CalculateBestEqualitySplit(\n stats_summary, total_grad, total_hess, node_id, feature_dims,\n logits_dim, hessian_dim, num_buckets, l1, l2, &f_best_gain,\n &f_best_bucket, &f_best_f_dim, &f_best_split_type,\n &f_best_contrib_for_left, &f_best_contrib_for_right);\n }\n if (f_best_gain > best_gain) {\n best_gain = f_best_gain;\n best_f_id = candidate_feature_ids(f_idx);\n best_f_dim = f_best_f_dim;\n best_split_type = f_best_split_type;\n best_bucket = f_best_bucket;\n best_contrib_for_left = f_best_contrib_for_left;\n best_contrib_for_right = f_best_contrib_for_right;\n }\n } // For feature id.\n if (best_gain == std::numeric_limits::lowest()) {\n // Do not add the node if no split is found.\n continue;\n }\n output_node_ids.push_back(node_id);\n // Remove the parent gain for the parent node.\n output_gains.push_back(best_gain - parent_gain);\n output_feature_ids.push_back(best_f_id);\n output_feature_dimensions.push_back(best_f_dim);\n // Default direction is fixed for dense splits.\n // TODO(tanzheny) account for default values.\n output_split_types.push_back(best_split_type);\n output_thresholds.push_back(best_bucket);\n output_left_node_contribs.push_back(best_contrib_for_left);\n output_right_node_contribs.push_back(best_contrib_for_right);\n } // for node id.\n const int num_nodes = output_node_ids.size();\n // output_node_ids\n Tensor* output_node_ids_t = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(\"node_ids\", {num_nodes},\n &output_node_ids_t));\n auto output_node_ids_vec = output_node_ids_t->vec();\n\n // output_gains\n Tensor* output_gains_t;\n OP_REQUIRES_OK(context, context->allocate_output(\"gains\", {num_nodes},\n &output_gains_t));\n auto output_gains_vec = output_gains_t->vec();\n\n // output_feature_ids\n Tensor* output_features_ids_t;\n OP_REQUIRES_OK(context, context->allocate_output(\"feature_ids\", {num_nodes},\n &output_features_ids_t));\n auto output_features_vec = output_features_ids_t->vec();\n\n // output_feature_dimensions\n Tensor* output_feature_dimension_t;\n OP_REQUIRES_OK(context,\n context->allocate_output(\"feature_dimensions\", {num_nodes},\n &output_feature_dimension_t));\n auto output_feature_dimensions_vec =\n output_feature_dimension_t->vec();\n\n // output_thresholds\n Tensor* output_thresholds_t;\n OP_REQUIRES_OK(context, context->allocate_output(\"thresholds\", {num_nodes},\n &output_thresholds_t));\n auto output_thresholds_vec = output_thresholds_t->vec();\n\n // output_left_node_contribs\n Tensor* output_left_node_contribs_t;\n OP_REQUIRES_OK(context, context->allocate_output(\n \"left_node_contribs\", {num_nodes, logits_dim},\n &output_left_node_contribs_t));\n auto output_left_node_contribs_matrix =\n output_left_node_contribs_t->matrix();\n\n // output_right_node_contribs\n Tensor* output_right_node_contribs_t;\n OP_REQUIRES_OK(context, context->allocate_output(\n \"right_node_contribs\", {num_nodes, logits_dim},\n &output_right_node_contribs_t));\n auto output_right_node_contribs_matrix =\n output_right_node_contribs_t->matrix();\n\n // split type\n Tensor* output_split_types_t;\n OP_REQUIRES_OK(\n context, context->allocate_output(\"split_with_default_directions\",\n {num_nodes}, &output_split_types_t));\n auto output_split_types_vec = output_split_types_t->vec();\n\n // Sets output tensors from vectors.\n for (int i = 0; i < num_nodes; ++i) {\n output_node_ids_vec(i) = output_node_ids[i];\n output_features_vec(i) = output_feature_ids[i];\n // Adjust the gains to penalize by tree complexity.\n output_gains_vec(i) = output_gains[i] - tree_complexity;\n output_feature_dimensions_vec(i) = output_feature_dimensions[i];\n output_thresholds_vec(i) = output_thresholds[i];\n for (int j = 0; j < logits_dim; ++j) {\n output_left_node_contribs_matrix(i, j) =\n output_left_node_contribs[i][j];\n output_right_node_contribs_matrix(i, j) =\n output_right_node_contribs[i][j];\n }\n output_split_types_vec(i) = output_split_types[i];\n }\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-369'], 'message': 'Fixing security fixes in boosted trees ops\n\nPiperOrigin-RevId: 405669548\nChange-Id: Iae224d240d1779bcc02405c2fff99785644fbd0d'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bgp_size_t bgp_packet_attribute(struct bgp *bgp, struct peer *peer,\n\t\t\t\tstruct stream *s, struct attr *attr,\n\t\t\t\tstruct bpacket_attr_vec_arr *vecarr,\n\t\t\t\tstruct prefix *p, afi_t afi, safi_t safi,\n\t\t\t\tstruct peer *from, struct prefix_rd *prd,\n\t\t\t\tmpls_label_t *label, uint32_t num_labels,\n\t\t\t\tint addpath_encode, uint32_t addpath_tx_id)\n{\n\tsize_t cp;\n\tsize_t aspath_sizep;\n\tstruct aspath *aspath;\n\tint send_as4_path = 0;\n\tint send_as4_aggregator = 0;\n\tint use32bit = (CHECK_FLAG(peer->cap, PEER_CAP_AS4_RCV)) ? 1 : 0;\n\n\tif (!bgp)\n\t\tbgp = peer->bgp;\n\n\t/* Remember current pointer. */\n\tcp = stream_get_endp(s);\n\n\tif (p\n\t && !((afi == AFI_IP && safi == SAFI_UNICAST)\n\t\t && !peer_cap_enhe(peer, afi, safi))) {\n\t\tsize_t mpattrlen_pos = 0;\n\n\t\tmpattrlen_pos = bgp_packet_mpattr_start(s, peer, afi, safi,\n\t\t\t\t\t\t\tvecarr, attr);\n\t\tbgp_packet_mpattr_prefix(s, afi, safi, p, prd, label,\n\t\t\t\t\t num_labels, addpath_encode,\n\t\t\t\t\t addpath_tx_id, attr);\n\t\tbgp_packet_mpattr_end(s, mpattrlen_pos);\n\t}\n\n\t/* Origin attribute. */\n\tstream_putc(s, BGP_ATTR_FLAG_TRANS);\n\tstream_putc(s, BGP_ATTR_ORIGIN);\n\tstream_putc(s, 1);\n\tstream_putc(s, attr->origin);\n\n\t/* AS path attribute. */\n\n\t/* If remote-peer is EBGP */\n\tif (peer->sort == BGP_PEER_EBGP\n\t && (!CHECK_FLAG(peer->af_flags[afi][safi],\n\t\t\t PEER_FLAG_AS_PATH_UNCHANGED)\n\t\t|| attr->aspath->segments == NULL)\n\t && (!CHECK_FLAG(peer->af_flags[afi][safi],\n\t\t\t PEER_FLAG_RSERVER_CLIENT))) {\n\t\taspath = aspath_dup(attr->aspath);\n\n\t\t/* Even though we may not be configured for confederations we\n\t\t * may have\n\t\t * RXed an AS_PATH with AS_CONFED_SEQUENCE or AS_CONFED_SET */\n\t\taspath = aspath_delete_confed_seq(aspath);\n\n\t\tif (CHECK_FLAG(bgp->config, BGP_CONFIG_CONFEDERATION)) {\n\t\t\t/* Stuff our path CONFED_ID on the front */\n\t\t\taspath = aspath_add_seq(aspath, bgp->confed_id);\n\t\t} else {\n\t\t\tif (peer->change_local_as) {\n\t\t\t\t/* If replace-as is specified, we only use the\n\t\t\t\t change_local_as when\n\t\t\t\t advertising routes. */\n\t\t\t\tif (!CHECK_FLAG(\n\t\t\t\t\t peer->flags,\n\t\t\t\t\t PEER_FLAG_LOCAL_AS_REPLACE_AS)) {\n\t\t\t\t\taspath = aspath_add_seq(aspath,\n\t\t\t\t\t\t\t\tpeer->local_as);\n\t\t\t\t}\n\t\t\t\taspath = aspath_add_seq(aspath,\n\t\t\t\t\t\t\tpeer->change_local_as);\n\t\t\t} else {\n\t\t\t\taspath = aspath_add_seq(aspath, peer->local_as);\n\t\t\t}\n\t\t}\n\t} else if (peer->sort == BGP_PEER_CONFED) {\n\t\t/* A confed member, so we need to do the AS_CONFED_SEQUENCE\n\t\t * thing */\n\t\taspath = aspath_dup(attr->aspath);\n\t\taspath = aspath_add_confed_seq(aspath, peer->local_as);\n\t} else\n\t\taspath = attr->aspath;\n\n\t/* If peer is not AS4 capable, then:\n\t * - send the created AS_PATH out as AS4_PATH (optional, transitive),\n\t * but ensure that no AS_CONFED_SEQUENCE and AS_CONFED_SET path\n\t * segment\n\t * types are in it (i.e. exclude them if they are there)\n\t * AND do this only if there is at least one asnum > 65535 in the\n\t * path!\n\t * - send an AS_PATH out, but put 16Bit ASnums in it, not 32bit, and\n\t * change\n\t * all ASnums > 65535 to BGP_AS_TRANS\n\t */\n\n\tstream_putc(s, BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_EXTLEN);\n\tstream_putc(s, BGP_ATTR_AS_PATH);\n\taspath_sizep = stream_get_endp(s);\n\tstream_putw(s, 0);\n\tstream_putw_at(s, aspath_sizep, aspath_put(s, aspath, use32bit));\n\n\t/* OLD session may need NEW_AS_PATH sent, if there are 4-byte ASNs\n\t * in the path\n\t */\n\tif (!use32bit && aspath_has_as4(aspath))\n\t\tsend_as4_path =\n\t\t\t1; /* we'll do this later, at the correct place */\n\n\t/* Nexthop attribute. */\n\tif (afi == AFI_IP && safi == SAFI_UNICAST\n\t && !peer_cap_enhe(peer, afi, safi)) {\n\t\tif (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_NEXT_HOP)) {\n\t\t\tstream_putc(s, BGP_ATTR_FLAG_TRANS);\n\t\t\tstream_putc(s, BGP_ATTR_NEXT_HOP);\n\t\t\tbpacket_attr_vec_arr_set_vec(vecarr, BGP_ATTR_VEC_NH, s,\n\t\t\t\t\t\t attr);\n\t\t\tstream_putc(s, 4);\n\t\t\tstream_put_ipv4(s, attr->nexthop.s_addr);\n\t\t} else if (peer_cap_enhe(from, afi, safi)) {\n\t\t\t/*\n\t\t\t * Likely this is the case when an IPv4 prefix was\n\t\t\t * received with\n\t\t\t * Extended Next-hop capability and now being advertised\n\t\t\t * to\n\t\t\t * non-ENHE peers.\n\t\t\t * Setting the mandatory (ipv4) next-hop attribute here\n\t\t\t * to enable\n\t\t\t * implicit next-hop self with correct (ipv4 address\n\t\t\t * family).\n\t\t\t */\n\t\t\tstream_putc(s, BGP_ATTR_FLAG_TRANS);\n\t\t\tstream_putc(s, BGP_ATTR_NEXT_HOP);\n\t\t\tbpacket_attr_vec_arr_set_vec(vecarr, BGP_ATTR_VEC_NH, s,\n\t\t\t\t\t\t NULL);\n\t\t\tstream_putc(s, 4);\n\t\t\tstream_put_ipv4(s, 0);\n\t\t}\n\t}\n\n\t/* MED attribute. */\n\tif (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_MULTI_EXIT_DISC)\n\t || bgp->maxmed_active) {\n\t\tstream_putc(s, BGP_ATTR_FLAG_OPTIONAL);\n\t\tstream_putc(s, BGP_ATTR_MULTI_EXIT_DISC);\n\t\tstream_putc(s, 4);\n\t\tstream_putl(s, (bgp->maxmed_active ? bgp->maxmed_value\n\t\t\t\t\t\t : attr->med));\n\t}\n\n\t/* Local preference. */\n\tif (peer->sort == BGP_PEER_IBGP || peer->sort == BGP_PEER_CONFED) {\n\t\tstream_putc(s, BGP_ATTR_FLAG_TRANS);\n\t\tstream_putc(s, BGP_ATTR_LOCAL_PREF);\n\t\tstream_putc(s, 4);\n\t\tstream_putl(s, attr->local_pref);\n\t}\n\n\t/* Atomic aggregate. */\n\tif (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_ATOMIC_AGGREGATE)) {\n\t\tstream_putc(s, BGP_ATTR_FLAG_TRANS);\n\t\tstream_putc(s, BGP_ATTR_ATOMIC_AGGREGATE);\n\t\tstream_putc(s, 0);\n\t}\n\n\t/* Aggregator. */\n\tif (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_AGGREGATOR)) {\n\t\t/* Common to BGP_ATTR_AGGREGATOR, regardless of ASN size */\n\t\tstream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS);\n\t\tstream_putc(s, BGP_ATTR_AGGREGATOR);\n\n\t\tif (use32bit) {\n\t\t\t/* AS4 capable peer */\n\t\t\tstream_putc(s, 8);\n\t\t\tstream_putl(s, attr->aggregator_as);\n\t\t} else {\n\t\t\t/* 2-byte AS peer */\n\t\t\tstream_putc(s, 6);\n\n\t\t\t/* Is ASN representable in 2-bytes? Or must AS_TRANS be\n\t\t\t * used? */\n\t\t\tif (attr->aggregator_as > 65535) {\n\t\t\t\tstream_putw(s, BGP_AS_TRANS);\n\n\t\t\t\t/* we have to send AS4_AGGREGATOR, too.\n\t\t\t\t * we'll do that later in order to send\n\t\t\t\t * attributes in ascending\n\t\t\t\t * order.\n\t\t\t\t */\n\t\t\t\tsend_as4_aggregator = 1;\n\t\t\t} else\n\t\t\t\tstream_putw(s, (uint16_t)attr->aggregator_as);\n\t\t}\n\t\tstream_put_ipv4(s, attr->aggregator_addr.s_addr);\n\t}\n\n\t/* Community attribute. */\n\tif (CHECK_FLAG(peer->af_flags[afi][safi], PEER_FLAG_SEND_COMMUNITY)\n\t && (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_COMMUNITIES))) {\n\t\tif (attr->community->size * 4 > 255) {\n\t\t\tstream_putc(s,\n\t\t\t\t BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS\n\t\t\t\t\t | BGP_ATTR_FLAG_EXTLEN);\n\t\t\tstream_putc(s, BGP_ATTR_COMMUNITIES);\n\t\t\tstream_putw(s, attr->community->size * 4);\n\t\t} else {\n\t\t\tstream_putc(s,\n\t\t\t\t BGP_ATTR_FLAG_OPTIONAL\n\t\t\t\t\t | BGP_ATTR_FLAG_TRANS);\n\t\t\tstream_putc(s, BGP_ATTR_COMMUNITIES);\n\t\t\tstream_putc(s, attr->community->size * 4);\n\t\t}\n\t\tstream_put(s, attr->community->val, attr->community->size * 4);\n\t}\n\n\t/*\n\t * Large Community attribute.\n\t */\n\tif (CHECK_FLAG(peer->af_flags[afi][safi],\n\t\t PEER_FLAG_SEND_LARGE_COMMUNITY)\n\t && (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_LARGE_COMMUNITIES))) {\n\t\tif (lcom_length(attr->lcommunity) > 255) {\n\t\t\tstream_putc(s,\n\t\t\t\t BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS\n\t\t\t\t\t | BGP_ATTR_FLAG_EXTLEN);\n\t\t\tstream_putc(s, BGP_ATTR_LARGE_COMMUNITIES);\n\t\t\tstream_putw(s, lcom_length(attr->lcommunity));\n\t\t} else {\n\t\t\tstream_putc(s,\n\t\t\t\t BGP_ATTR_FLAG_OPTIONAL\n\t\t\t\t\t | BGP_ATTR_FLAG_TRANS);\n\t\t\tstream_putc(s, BGP_ATTR_LARGE_COMMUNITIES);\n\t\t\tstream_putc(s, lcom_length(attr->lcommunity));\n\t\t}\n\t\tstream_put(s, attr->lcommunity->val,\n\t\t\t lcom_length(attr->lcommunity));\n\t}\n\n\t/* Route Reflector. */\n\tif (peer->sort == BGP_PEER_IBGP && from\n\t && from->sort == BGP_PEER_IBGP) {\n\t\t/* Originator ID. */\n\t\tstream_putc(s, BGP_ATTR_FLAG_OPTIONAL);\n\t\tstream_putc(s, BGP_ATTR_ORIGINATOR_ID);\n\t\tstream_putc(s, 4);\n\n\t\tif (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_ORIGINATOR_ID))\n\t\t\tstream_put_in_addr(s, &attr->originator_id);\n\t\telse\n\t\t\tstream_put_in_addr(s, &from->remote_id);\n\n\t\t/* Cluster list. */\n\t\tstream_putc(s, BGP_ATTR_FLAG_OPTIONAL);\n\t\tstream_putc(s, BGP_ATTR_CLUSTER_LIST);\n\n\t\tif (attr->cluster) {\n\t\t\tstream_putc(s, attr->cluster->length + 4);\n\t\t\t/* If this peer configuration's parent BGP has\n\t\t\t * cluster_id. */\n\t\t\tif (bgp->config & BGP_CONFIG_CLUSTER_ID)\n\t\t\t\tstream_put_in_addr(s, &bgp->cluster_id);\n\t\t\telse\n\t\t\t\tstream_put_in_addr(s, &bgp->router_id);\n\t\t\tstream_put(s, attr->cluster->list,\n\t\t\t\t attr->cluster->length);\n\t\t} else {\n\t\t\tstream_putc(s, 4);\n\t\t\t/* If this peer configuration's parent BGP has\n\t\t\t * cluster_id. */\n\t\t\tif (bgp->config & BGP_CONFIG_CLUSTER_ID)\n\t\t\t\tstream_put_in_addr(s, &bgp->cluster_id);\n\t\t\telse\n\t\t\t\tstream_put_in_addr(s, &bgp->router_id);\n\t\t}\n\t}\n\n\t/* Extended Communities attribute. */\n\tif (CHECK_FLAG(peer->af_flags[afi][safi], PEER_FLAG_SEND_EXT_COMMUNITY)\n\t && (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_EXT_COMMUNITIES))) {\n\t\tif (peer->sort == BGP_PEER_IBGP\n\t\t || peer->sort == BGP_PEER_CONFED) {\n\t\t\tif (attr->ecommunity->size * 8 > 255) {\n\t\t\t\tstream_putc(s,\n\t\t\t\t\t BGP_ATTR_FLAG_OPTIONAL\n\t\t\t\t\t\t | BGP_ATTR_FLAG_TRANS\n\t\t\t\t\t\t | BGP_ATTR_FLAG_EXTLEN);\n\t\t\t\tstream_putc(s, BGP_ATTR_EXT_COMMUNITIES);\n\t\t\t\tstream_putw(s, attr->ecommunity->size * 8);\n\t\t\t} else {\n\t\t\t\tstream_putc(s,\n\t\t\t\t\t BGP_ATTR_FLAG_OPTIONAL\n\t\t\t\t\t\t | BGP_ATTR_FLAG_TRANS);\n\t\t\t\tstream_putc(s, BGP_ATTR_EXT_COMMUNITIES);\n\t\t\t\tstream_putc(s, attr->ecommunity->size * 8);\n\t\t\t}\n\t\t\tstream_put(s, attr->ecommunity->val,\n\t\t\t\t attr->ecommunity->size * 8);\n\t\t} else {\n\t\t\tuint8_t *pnt;\n\t\t\tint tbit;\n\t\t\tint ecom_tr_size = 0;\n\t\t\tint i;\n\n\t\t\tfor (i = 0; i < attr->ecommunity->size; i++) {\n\t\t\t\tpnt = attr->ecommunity->val + (i * 8);\n\t\t\t\ttbit = *pnt;\n\n\t\t\t\tif (CHECK_FLAG(tbit,\n\t\t\t\t\t ECOMMUNITY_FLAG_NON_TRANSITIVE))\n\t\t\t\t\tcontinue;\n\n\t\t\t\tecom_tr_size++;\n\t\t\t}\n\n\t\t\tif (ecom_tr_size) {\n\t\t\t\tif (ecom_tr_size * 8 > 255) {\n\t\t\t\t\tstream_putc(\n\t\t\t\t\t\ts,\n\t\t\t\t\t\tBGP_ATTR_FLAG_OPTIONAL\n\t\t\t\t\t\t\t| BGP_ATTR_FLAG_TRANS\n\t\t\t\t\t\t\t| BGP_ATTR_FLAG_EXTLEN);\n\t\t\t\t\tstream_putc(s,\n\t\t\t\t\t\t BGP_ATTR_EXT_COMMUNITIES);\n\t\t\t\t\tstream_putw(s, ecom_tr_size * 8);\n\t\t\t\t} else {\n\t\t\t\t\tstream_putc(\n\t\t\t\t\t\ts,\n\t\t\t\t\t\tBGP_ATTR_FLAG_OPTIONAL\n\t\t\t\t\t\t\t| BGP_ATTR_FLAG_TRANS);\n\t\t\t\t\tstream_putc(s,\n\t\t\t\t\t\t BGP_ATTR_EXT_COMMUNITIES);\n\t\t\t\t\tstream_putc(s, ecom_tr_size * 8);\n\t\t\t\t}\n\n\t\t\t\tfor (i = 0; i < attr->ecommunity->size; i++) {\n\t\t\t\t\tpnt = attr->ecommunity->val + (i * 8);\n\t\t\t\t\ttbit = *pnt;\n\n\t\t\t\t\tif (CHECK_FLAG(\n\t\t\t\t\t\t tbit,\n\t\t\t\t\t\t ECOMMUNITY_FLAG_NON_TRANSITIVE))\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tstream_put(s, pnt, 8);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/* Label index attribute. */\n\tif (safi == SAFI_LABELED_UNICAST) {\n\t\tif (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_PREFIX_SID)) {\n\t\t\tuint32_t label_index;\n\n\t\t\tlabel_index = attr->label_index;\n\n\t\t\tif (label_index != BGP_INVALID_LABEL_INDEX) {\n\t\t\t\tstream_putc(s,\n\t\t\t\t\t BGP_ATTR_FLAG_OPTIONAL\n\t\t\t\t\t\t | BGP_ATTR_FLAG_TRANS);\n\t\t\t\tstream_putc(s, BGP_ATTR_PREFIX_SID);\n\t\t\t\tstream_putc(s, 10);\n\t\t\t\tstream_putc(s, BGP_PREFIX_SID_LABEL_INDEX);\n\t\t\t\tstream_putw(s,\n\t\t\t\t\t BGP_PREFIX_SID_LABEL_INDEX_LENGTH);\n\t\t\t\tstream_putc(s, 0); // reserved\n\t\t\t\tstream_putw(s, 0); // flags\n\t\t\t\tstream_putl(s, label_index);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (send_as4_path) {\n\t\t/* If the peer is NOT As4 capable, AND */\n\t\t/* there are ASnums > 65535 in path THEN\n\t\t * give out AS4_PATH */\n\n\t\t/* Get rid of all AS_CONFED_SEQUENCE and AS_CONFED_SET\n\t\t * path segments!\n\t\t * Hm, I wonder... confederation things *should* only be at\n\t\t * the beginning of an aspath, right? Then we should use\n\t\t * aspath_delete_confed_seq for this, because it is already\n\t\t * there! (JK)\n\t\t * Folks, talk to me: what is reasonable here!?\n\t\t */\n\t\taspath = aspath_delete_confed_seq(aspath);\n\n\t\tstream_putc(s,\n\t\t\t BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_OPTIONAL\n\t\t\t\t | BGP_ATTR_FLAG_EXTLEN);\n\t\tstream_putc(s, BGP_ATTR_AS4_PATH);\n\t\taspath_sizep = stream_get_endp(s);\n\t\tstream_putw(s, 0);\n\t\tstream_putw_at(s, aspath_sizep, aspath_put(s, aspath, 1));\n\t}\n\n\tif (aspath != attr->aspath)\n\t\taspath_free(aspath);\n\n\tif (send_as4_aggregator) {\n\t\t/* send AS4_AGGREGATOR, at this place */\n\t\t/* this section of code moved here in order to ensure the\n\t\t * correct\n\t\t * *ascending* order of attributes\n\t\t */\n\t\tstream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS);\n\t\tstream_putc(s, BGP_ATTR_AS4_AGGREGATOR);\n\t\tstream_putc(s, 8);\n\t\tstream_putl(s, attr->aggregator_as);\n\t\tstream_put_ipv4(s, attr->aggregator_addr.s_addr);\n\t}\n\n\tif (((afi == AFI_IP || afi == AFI_IP6)\n\t && (safi == SAFI_ENCAP || safi == SAFI_MPLS_VPN))\n\t || (afi == AFI_L2VPN && safi == SAFI_EVPN)) {\n\t\t/* Tunnel Encap attribute */\n\t\tbgp_packet_mpattr_tea(bgp, peer, s, attr, BGP_ATTR_ENCAP);\n\n#if ENABLE_BGP_VNC\n\t\t/* VNC attribute */\n\t\tbgp_packet_mpattr_tea(bgp, peer, s, attr, BGP_ATTR_VNC);\n#endif\n\t}\n\n\t/* PMSI Tunnel */\n\tif (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_PMSI_TUNNEL)) {\n\t\tstream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS);\n\t\tstream_putc(s, BGP_ATTR_PMSI_TUNNEL);\n\t\tstream_putc(s, 9); // Length\n\t\tstream_putc(s, 0); // Flags\n\t\tstream_putc(s, PMSI_TNLTYPE_INGR_REPL); // IR (6)\n\t\tstream_put(s, &(attr->label),\n\t\t\t BGP_LABEL_BYTES); // MPLS Label / VXLAN VNI\n\t\tstream_put_ipv4(s, attr->nexthop.s_addr);\n\t\t// Unicast tunnel endpoint IP address\n\t}\n\n\t/* Unknown transit attribute. */\n\tif (attr->transit)\n\t\tstream_put(s, attr->transit->val, attr->transit->length);\n\n\t/* Return total size of attribute. */\n\treturn stream_get_endp(s) - cp;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-436'], 'message': 'bgpd: don't use BGP_ATTR_VNC(255) unless ENABLE_BGP_VNC_ATTR is defined\n\nSigned-off-by: Lou Berger '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: wrap_lines_smart(ASS_Renderer *render_priv, double max_text_width)\n{\n int i;\n GlyphInfo *cur, *s1, *e1, *s2, *s3;\n int last_space;\n int break_type;\n int exit;\n double pen_shift_x;\n double pen_shift_y;\n int cur_line;\n int run_offset;\n TextInfo *text_info = &render_priv->text_info;\n\n last_space = -1;\n text_info->n_lines = 1;\n break_type = 0;\n s1 = text_info->glyphs; // current line start\n for (i = 0; i < text_info->length; ++i) {\n int break_at = -1;\n double s_offset, len;\n cur = text_info->glyphs + i;\n s_offset = d6_to_double(s1->bbox.xMin + s1->pos.x);\n len = d6_to_double(cur->bbox.xMax + cur->pos.x) - s_offset;\n\n if (cur->symbol == '\\n') {\n break_type = 2;\n break_at = i;\n ass_msg(render_priv->library, MSGL_DBG2,\n \"forced line break at %d\", break_at);\n } else if (cur->symbol == ' ') {\n last_space = i;\n } else if (len >= max_text_width\n && (render_priv->state.wrap_style != 2)) {\n break_type = 1;\n break_at = last_space;\n if (break_at >= 0)\n ass_msg(render_priv->library, MSGL_DBG2, \"line break at %d\",\n break_at);\n }\n\n if (break_at != -1) {\n // need to use one more line\n // marking break_at+1 as start of a new line\n int lead = break_at + 1; // the first symbol of the new line\n if (text_info->n_lines >= text_info->max_lines) {\n // Raise maximum number of lines\n text_info->max_lines *= 2;\n text_info->lines = realloc(text_info->lines,\n sizeof(LineInfo) *\n text_info->max_lines);\n }\n if (lead < text_info->length) {\n text_info->glyphs[lead].linebreak = break_type;\n last_space = -1;\n s1 = text_info->glyphs + lead;\n text_info->n_lines++;\n }\n }\n }\n#define DIFF(x,y) (((x) < (y)) ? (y - x) : (x - y))\n exit = 0;\n while (!exit && render_priv->state.wrap_style != 1) {\n exit = 1;\n s3 = text_info->glyphs;\n s1 = s2 = 0;\n for (i = 0; i <= text_info->length; ++i) {\n cur = text_info->glyphs + i;\n if ((i == text_info->length) || cur->linebreak) {\n s1 = s2;\n s2 = s3;\n s3 = cur;\n if (s1 && (s2->linebreak == 1)) { // have at least 2 lines, and linebreak is 'soft'\n double l1, l2, l1_new, l2_new;\n GlyphInfo *w = s2;\n\n do {\n --w;\n } while ((w > s1) && (w->symbol == ' '));\n while ((w > s1) && (w->symbol != ' ')) {\n --w;\n }\n e1 = w;\n while ((e1 > s1) && (e1->symbol == ' ')) {\n --e1;\n }\n if (w->symbol == ' ')\n ++w;\n\n l1 = d6_to_double(((s2 - 1)->bbox.xMax + (s2 - 1)->pos.x) -\n (s1->bbox.xMin + s1->pos.x));\n l2 = d6_to_double(((s3 - 1)->bbox.xMax + (s3 - 1)->pos.x) -\n (s2->bbox.xMin + s2->pos.x));\n l1_new = d6_to_double(\n (e1->bbox.xMax + e1->pos.x) -\n (s1->bbox.xMin + s1->pos.x));\n l2_new = d6_to_double(\n ((s3 - 1)->bbox.xMax + (s3 - 1)->pos.x) -\n (w->bbox.xMin + w->pos.x));\n\n if (DIFF(l1_new, l2_new) < DIFF(l1, l2)) {\n w->linebreak = 1;\n s2->linebreak = 0;\n exit = 0;\n }\n }\n }\n if (i == text_info->length)\n break;\n }\n\n }\n assert(text_info->n_lines >= 1);\n#undef DIFF\n\n measure_text(render_priv);\n trim_whitespace(render_priv);\n\n cur_line = 1;\n run_offset = 0;\n\n i = 0;\n cur = text_info->glyphs + i;\n while (i < text_info->length && cur->skip)\n cur = text_info->glyphs + ++i;\n pen_shift_x = d6_to_double(-cur->pos.x);\n pen_shift_y = 0.;\n\n for (i = 0; i < text_info->length; ++i) {\n cur = text_info->glyphs + i;\n if (cur->linebreak) {\n while (i < text_info->length && cur->skip && cur->symbol != '\\n')\n cur = text_info->glyphs + ++i;\n double height =\n text_info->lines[cur_line - 1].desc +\n text_info->lines[cur_line].asc;\n text_info->lines[cur_line - 1].len = i -\n text_info->lines[cur_line - 1].offset;\n text_info->lines[cur_line].offset = i;\n cur_line++;\n run_offset++;\n pen_shift_x = d6_to_double(-cur->pos.x);\n pen_shift_y += height + render_priv->settings.line_spacing;\n }\n cur->pos.x += double_to_d6(pen_shift_x);\n cur->pos.y += double_to_d6(pen_shift_y);\n }\n text_info->lines[cur_line - 1].len =\n text_info->length - text_info->lines[cur_line - 1].offset;\n\n#if 0\n // print line info\n for (i = 0; i < text_info->n_lines; i++) {\n printf(\"line %d offset %d length %d\\n\", i, text_info->lines[i].offset,\n text_info->lines[i].len);\n }\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix line wrapping mode 0/3 bugs\n\nThis fixes two separate bugs:\n\na) Don't move a linebreak into the first symbol. This results in a empty\n line at the front, which does not help to equalize line lengths at all.\n Instead, merge line with the second one.\nb) When moving a linebreak into a symbol that already is a break, the\n number of lines must be decremented. Otherwise, uninitialized memory\n is possibly used for later layout operations.\n\nFound by fuzzer test case\nid:000085,sig:11,src:003377+003350,op:splice,rep:8.\n\nThis might also affect and hopefully fix libass#229.\n\nv2: change semantics according to review'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline ut8 r_read_ble8(const void *src) {\n\treturn *(ut8 *)src;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fix #6816 - null deref in r_read_*'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: NORET_TYPE void do_exit(long code)\n{\n\tstruct task_struct *tsk = current;\n\tint group_dead;\n\n\tprofile_task_exit(tsk);\n\n\tWARN_ON(atomic_read(&tsk->fs_excl));\n\n\tif (unlikely(in_interrupt()))\n\t\tpanic(\"Aiee, killing interrupt handler!\");\n\tif (unlikely(!tsk->pid))\n\t\tpanic(\"Attempted to kill the idle task!\");\n\n\ttracehook_report_exit(&code);\n\n\t/*\n\t * We're taking recursive faults here in do_exit. Safest is to just\n\t * leave this task alone and wait for reboot.\n\t */\n\tif (unlikely(tsk->flags & PF_EXITING)) {\n\t\tprintk(KERN_ALERT\n\t\t\t\"Fixing recursive fault but reboot is needed!\\n\");\n\t\t/*\n\t\t * We can do this unlocked here. The futex code uses\n\t\t * this flag just to verify whether the pi state\n\t\t * cleanup has been done or not. In the worst case it\n\t\t * loops once more. We pretend that the cleanup was\n\t\t * done as there is no way to return. Either the\n\t\t * OWNER_DIED bit is set by now or we push the blocked\n\t\t * task into the wait for ever nirwana as well.\n\t\t */\n\t\ttsk->flags |= PF_EXITPIDONE;\n\t\tif (tsk->io_context)\n\t\t\texit_io_context();\n\t\tset_current_state(TASK_UNINTERRUPTIBLE);\n\t\tschedule();\n\t}\n\n\texit_signals(tsk); /* sets PF_EXITING */\n\t/*\n\t * tsk->flags are checked in the futex code to protect against\n\t * an exiting task cleaning up the robust pi futexes.\n\t */\n\tsmp_mb();\n\tspin_unlock_wait(&tsk->pi_lock);\n\n\tif (unlikely(in_atomic()))\n\t\tprintk(KERN_INFO \"note: %s[%d] exited with preempt_count %d\\n\",\n\t\t\t\tcurrent->comm, task_pid_nr(current),\n\t\t\t\tpreempt_count());\n\n\tacct_update_integrals(tsk);\n\tif (tsk->mm) {\n\t\tupdate_hiwater_rss(tsk->mm);\n\t\tupdate_hiwater_vm(tsk->mm);\n\t}\n\tgroup_dead = atomic_dec_and_test(&tsk->signal->live);\n\tif (group_dead) {\n\t\thrtimer_cancel(&tsk->signal->real_timer);\n\t\texit_itimers(tsk->signal);\n\t}\n\tacct_collect(code, group_dead);\n#ifdef CONFIG_FUTEX\n\tif (unlikely(tsk->robust_list))\n\t\texit_robust_list(tsk);\n#ifdef CONFIG_COMPAT\n\tif (unlikely(tsk->compat_robust_list))\n\t\tcompat_exit_robust_list(tsk);\n#endif\n#endif\n\tif (group_dead)\n\t\ttty_audit_exit();\n\tif (unlikely(tsk->audit_context))\n\t\taudit_free(tsk);\n\n\ttsk->exit_code = code;\n\ttaskstats_exit(tsk, group_dead);\n\n\texit_mm(tsk);\n\n\tif (group_dead)\n\t\tacct_process();\n\ttrace_sched_process_exit(tsk);\n\n\texit_sem(tsk);\n\texit_files(tsk);\n\texit_fs(tsk);\n\tcheck_stack_usage();\n\texit_thread();\n\tcgroup_exit(tsk, 1);\n\texit_keys(tsk);\n\n\tif (group_dead && tsk->signal->leader)\n\t\tdisassociate_ctty(1);\n\n\tmodule_put(task_thread_info(tsk)->exec_domain->module);\n\tif (tsk->binfmt)\n\t\tmodule_put(tsk->binfmt->module);\n\n\tproc_exit_connector(tsk);\n\texit_notify(tsk, group_dead);\n#ifdef CONFIG_NUMA\n\tmpol_put(tsk->mempolicy);\n\ttsk->mempolicy = NULL;\n#endif\n#ifdef CONFIG_FUTEX\n\t/*\n\t * This must happen late, after the PID is not\n\t * hashed anymore:\n\t */\n\tif (unlikely(!list_empty(&tsk->pi_state_list)))\n\t\texit_pi_state_list(tsk);\n\tif (unlikely(current->pi_state_cache))\n\t\tkfree(current->pi_state_cache);\n#endif\n\t/*\n\t * Make sure we are holding no locks:\n\t */\n\tdebug_check_no_locks_held(tsk);\n\t/*\n\t * We can do this unlocked here. The futex code uses this flag\n\t * just to verify whether the pi state cleanup has been done\n\t * or not. In the worst case it loops once more.\n\t */\n\ttsk->flags |= PF_EXITPIDONE;\n\n\tif (tsk->io_context)\n\t\texit_io_context();\n\n\tif (tsk->splice_pipe)\n\t\t__free_pipe_info(tsk->splice_pipe);\n\n\tpreempt_disable();\n\t/* causes final put_task_struct in finish_task_switch(). */\n\ttsk->state = TASK_DEAD;\n\n\tschedule();\n\tBUG();\n\t/* Avoid \"noreturn function does return\". */\n\tfor (;;)\n\t\tcpu_relax();\t/* For when BUG is null */\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'Move \"exit_robust_list\" into mm_release()\n\nWe don't want to get rid of the futexes just at exit() time, we want to\ndrop them when doing an execve() too, since that gets rid of the\nprevious VM image too.\n\nDoing it at mm_release() time means that we automatically always do it\nwhen we disassociate a VM map from the task.\n\nReported-by: pageexec@freemail.hu\nCc: Andrew Morton \nCc: Nick Piggin \nCc: Hugh Dickins \nCc: Ingo Molnar \nCc: Thomas Gleixner \nCc: Brad Spengler \nCc: Alex Efros \nCc: Peter Zijlstra \nCc: Oleg Nesterov \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: RZ_API void rz_core_analysis_esil(RzCore *core, const char *str, const char *target) {\n\tbool cfg_analysis_strings = rz_config_get_i(core->config, \"analysis.strings\");\n\tbool emu_lazy = rz_config_get_i(core->config, \"emu.lazy\");\n\tbool gp_fixed = rz_config_get_i(core->config, \"analysis.gpfixed\");\n\tRzAnalysisEsil *ESIL = core->analysis->esil;\n\tut64 refptr = 0LL;\n\tconst char *pcname;\n\tRzAnalysisOp op = RZ_EMPTY;\n\tut8 *buf = NULL;\n\tbool end_address_set = false;\n\tint iend;\n\tint minopsize = 4; // XXX this depends on asm->mininstrsize\n\tbool archIsArm = false;\n\tut64 addr = core->offset;\n\tut64 start = addr;\n\tut64 end = 0LL;\n\tut64 cur;\n\n\tif (!strcmp(str, \"?\")) {\n\t\teprintf(\"Usage: aae[f] [len] [addr] - analyze refs in function, section or len bytes with esil\\n\");\n\t\teprintf(\" aae $SS @ $S - analyze the whole section\\n\");\n\t\teprintf(\" aae $SS str.Hello @ $S - find references for str.Hellow\\n\");\n\t\teprintf(\" aaef - analyze functions discovered with esil\\n\");\n\t\treturn;\n\t}\n#define CHECKREF(x) ((refptr && (x) == refptr) || !refptr)\n\tif (target) {\n\t\tconst char *expr = rz_str_trim_head_ro(target);\n\t\tif (*expr) {\n\t\t\trefptr = ntarget = rz_num_math(core->num, expr);\n\t\t\tif (!refptr) {\n\t\t\t\tntarget = refptr = addr;\n\t\t\t}\n\t\t} else {\n\t\t\tntarget = UT64_MAX;\n\t\t\trefptr = 0LL;\n\t\t}\n\t} else {\n\t\tntarget = UT64_MAX;\n\t\trefptr = 0LL;\n\t}\n\tRzAnalysisFunction *fcn = NULL;\n\tif (!strcmp(str, \"f\")) {\n\t\tfcn = rz_analysis_get_fcn_in(core->analysis, core->offset, 0);\n\t\tif (fcn) {\n\t\t\tstart = rz_analysis_function_min_addr(fcn);\n\t\t\taddr = fcn->addr;\n\t\t\tend = rz_analysis_function_max_addr(fcn);\n\t\t\tend_address_set = true;\n\t\t}\n\t}\n\n\tif (!end_address_set) {\n\t\tif (str[0] == ' ') {\n\t\t\tend = addr + rz_num_math(core->num, str + 1);\n\t\t} else {\n\t\t\tRzIOMap *map = rz_io_map_get(core->io, addr);\n\t\t\tif (map) {\n\t\t\t\tend = map->itv.addr + map->itv.size;\n\t\t\t} else {\n\t\t\t\tend = addr + core->blocksize;\n\t\t\t}\n\t\t}\n\t}\n\n\tiend = end - start;\n\tif (iend < 0) {\n\t\treturn;\n\t}\n\tif (iend > MAX_SCAN_SIZE) {\n\t\teprintf(\"Warning: Not going to analyze 0x%08\" PFMT64x \" bytes.\\n\", (ut64)iend);\n\t\treturn;\n\t}\n\tbuf = malloc((size_t)iend + 2);\n\tif (!buf) {\n\t\tperror(\"malloc\");\n\t\treturn;\n\t}\n\tesilbreak_last_read = UT64_MAX;\n\trz_io_read_at(core->io, start, buf, iend + 1);\n\tif (!ESIL) {\n\t\trz_core_analysis_esil_reinit(core);\n\t\tESIL = core->analysis->esil;\n\t\tif (!ESIL) {\n\t\t\teprintf(\"ESIL not initialized\\n\");\n\t\t\treturn;\n\t\t}\n\t\trz_core_analysis_esil_init_mem(core, NULL, UT64_MAX, UT32_MAX);\n\t}\n\tconst char *spname = rz_reg_get_name(core->analysis->reg, RZ_REG_NAME_SP);\n\tEsilBreakCtx ctx = {\n\t\t&op,\n\t\tfcn,\n\t\tspname,\n\t\trz_reg_getv(core->analysis->reg, spname)\n\t};\n\tESIL->cb.hook_reg_write = &esilbreak_reg_write;\n\t//this is necessary for the hook to read the id of analop\n\tESIL->user = &ctx;\n\tESIL->cb.hook_mem_read = &esilbreak_mem_read;\n\tESIL->cb.hook_mem_write = &esilbreak_mem_write;\n\n\tif (fcn && fcn->reg_save_area) {\n\t\trz_reg_setv(core->analysis->reg, ctx.spname, ctx.initial_sp - fcn->reg_save_area);\n\t}\n\t//eprintf (\"Analyzing ESIL refs from 0x%\"PFMT64x\" - 0x%\"PFMT64x\"\\n\", addr, end);\n\t// TODO: backup/restore register state before/after analysis\n\tpcname = rz_reg_get_name(core->analysis->reg, RZ_REG_NAME_PC);\n\tif (!pcname || !*pcname) {\n\t\teprintf(\"Cannot find program counter register in the current profile.\\n\");\n\t\treturn;\n\t}\n\tesil_analysis_stop = false;\n\trz_cons_break_push(cccb, core);\n\n\tint arch = -1;\n\tif (!strcmp(core->analysis->cur->arch, \"arm\")) {\n\t\tswitch (core->analysis->bits) {\n\t\tcase 64: arch = RZ_ARCH_ARM64; break;\n\t\tcase 32: arch = RZ_ARCH_ARM32; break;\n\t\tcase 16: arch = RZ_ARCH_THUMB; break;\n\t\t}\n\t\tarchIsArm = true;\n\t}\n\n\tut64 gp = rz_config_get_i(core->config, \"analysis.gp\");\n\tconst char *gp_reg = NULL;\n\tif (!strcmp(core->analysis->cur->arch, \"mips\")) {\n\t\tgp_reg = \"gp\";\n\t\tarch = RZ_ARCH_MIPS;\n\t}\n\n\tconst char *sn = rz_reg_get_name(core->analysis->reg, RZ_REG_NAME_SN);\n\tif (!sn) {\n\t\teprintf(\"Warning: No SN reg alias for current architecture.\\n\");\n\t}\n\trz_reg_arena_push(core->analysis->reg);\n\n\tIterCtx ictx = { start, end, fcn, NULL };\n\tsize_t i = addr - start;\n\tdo {\n\t\tif (esil_analysis_stop || rz_cons_is_breaked()) {\n\t\t\tbreak;\n\t\t}\n\t\tsize_t i_old = i;\n\t\tcur = start + i;\n\t\tif (!rz_io_is_valid_offset(core->io, cur, 0)) {\n\t\t\tbreak;\n\t\t}\n\t\t{\n\t\t\tRzPVector *list = rz_meta_get_all_in(core->analysis, cur, RZ_META_TYPE_ANY);\n\t\t\tvoid **it;\n\t\t\trz_pvector_foreach (list, it) {\n\t\t\t\tRzIntervalNode *node = *it;\n\t\t\t\tRzAnalysisMetaItem *meta = node->data;\n\t\t\t\tswitch (meta->type) {\n\t\t\t\tcase RZ_META_TYPE_DATA:\n\t\t\t\tcase RZ_META_TYPE_STRING:\n\t\t\t\tcase RZ_META_TYPE_FORMAT:\n\t\t\t\t\ti += 4;\n\t\t\t\t\trz_pvector_free(list);\n\t\t\t\t\tgoto repeat;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\trz_pvector_free(list);\n\t\t}\n\n\t\t/* realign address if needed */\n\t\trz_core_seek_arch_bits(core, cur);\n\t\tint opalign = core->analysis->pcalign;\n\t\tif (opalign > 0) {\n\t\t\tcur -= (cur % opalign);\n\t\t}\n\n\t\trz_analysis_op_fini(&op);\n\t\trz_asm_set_pc(core->rasm, cur);\n\t\tif (!rz_analysis_op(core->analysis, &op, cur, buf + i, iend - i, RZ_ANALYSIS_OP_MASK_ESIL | RZ_ANALYSIS_OP_MASK_VAL | RZ_ANALYSIS_OP_MASK_HINT)) {\n\t\t\ti += minopsize - 1; // XXX dupe in op.size below\n\t\t}\n\t\t// if (op.type & 0x80000000 || op.type == 0) {\n\t\tif (op.type == RZ_ANALYSIS_OP_TYPE_ILL || op.type == RZ_ANALYSIS_OP_TYPE_UNK) {\n\t\t\t// i += 2\n\t\t\trz_analysis_op_fini(&op);\n\t\t\tgoto repeat;\n\t\t}\n\t\t//we need to check again i because buf+i may goes beyond its boundaries\n\t\t//because of i+= minopsize - 1\n\t\tif (i > iend) {\n\t\t\tgoto repeat;\n\t\t}\n\t\tif (op.size < 1) {\n\t\t\ti += minopsize - 1;\n\t\t\tgoto repeat;\n\t\t}\n\t\tif (emu_lazy) {\n\t\t\tif (op.type & RZ_ANALYSIS_OP_TYPE_REP) {\n\t\t\t\ti += op.size - 1;\n\t\t\t\tgoto repeat;\n\t\t\t}\n\t\t\tswitch (op.type & RZ_ANALYSIS_OP_TYPE_MASK) {\n\t\t\tcase RZ_ANALYSIS_OP_TYPE_JMP:\n\t\t\tcase RZ_ANALYSIS_OP_TYPE_CJMP:\n\t\t\tcase RZ_ANALYSIS_OP_TYPE_CALL:\n\t\t\tcase RZ_ANALYSIS_OP_TYPE_RET:\n\t\t\tcase RZ_ANALYSIS_OP_TYPE_ILL:\n\t\t\tcase RZ_ANALYSIS_OP_TYPE_NOP:\n\t\t\tcase RZ_ANALYSIS_OP_TYPE_UJMP:\n\t\t\tcase RZ_ANALYSIS_OP_TYPE_IO:\n\t\t\tcase RZ_ANALYSIS_OP_TYPE_LEAVE:\n\t\t\tcase RZ_ANALYSIS_OP_TYPE_CRYPTO:\n\t\t\tcase RZ_ANALYSIS_OP_TYPE_CPL:\n\t\t\tcase RZ_ANALYSIS_OP_TYPE_SYNC:\n\t\t\tcase RZ_ANALYSIS_OP_TYPE_SWI:\n\t\t\tcase RZ_ANALYSIS_OP_TYPE_CMP:\n\t\t\tcase RZ_ANALYSIS_OP_TYPE_ACMP:\n\t\t\tcase RZ_ANALYSIS_OP_TYPE_NULL:\n\t\t\tcase RZ_ANALYSIS_OP_TYPE_CSWI:\n\t\t\tcase RZ_ANALYSIS_OP_TYPE_TRAP:\n\t\t\t\ti += op.size - 1;\n\t\t\t\tgoto repeat;\n\t\t\t// those require write support\n\t\t\tcase RZ_ANALYSIS_OP_TYPE_PUSH:\n\t\t\tcase RZ_ANALYSIS_OP_TYPE_POP:\n\t\t\t\ti += op.size - 1;\n\t\t\t\tgoto repeat;\n\t\t\t}\n\t\t}\n\t\tif (sn && op.type == RZ_ANALYSIS_OP_TYPE_SWI) {\n\t\t\trz_flag_space_set(core->flags, RZ_FLAGS_FS_SYSCALLS);\n\t\t\tint snv = (arch == RZ_ARCH_THUMB) ? op.val : (int)rz_reg_getv(core->analysis->reg, sn);\n\t\t\tRzSyscallItem *si = rz_syscall_get(core->analysis->syscall, snv, -1);\n\t\t\tif (si) {\n\t\t\t\t//\teprintf (\"0x%08\"PFMT64x\" SYSCALL %-4d %s\\n\", cur, snv, si->name);\n\t\t\t\trz_flag_set_next(core->flags, sdb_fmt(\"syscall.%s\", si->name), cur, 1);\n\t\t\t\trz_syscall_item_free(si);\n\t\t\t} else {\n\t\t\t\t//todo were doing less filtering up top because we can't match against 80 on all platforms\n\t\t\t\t// might get too many of this path now..\n\t\t\t\t//\teprintf (\"0x%08\"PFMT64x\" SYSCALL %d\\n\", cur, snv);\n\t\t\t\trz_flag_set_next(core->flags, sdb_fmt(\"syscall.%d\", snv), cur, 1);\n\t\t\t}\n\t\t\trz_flag_space_set(core->flags, NULL);\n\t\t}\n\t\tconst char *esilstr = RZ_STRBUF_SAFEGET(&op.esil);\n\t\ti += op.size - 1;\n\t\tif (!esilstr || !*esilstr) {\n\t\t\tgoto repeat;\n\t\t}\n\t\trz_analysis_esil_set_pc(ESIL, cur);\n\t\trz_reg_setv(core->analysis->reg, pcname, cur + op.size);\n\t\tif (gp_fixed && gp_reg) {\n\t\t\trz_reg_setv(core->analysis->reg, gp_reg, gp);\n\t\t}\n\t\t(void)rz_analysis_esil_parse(ESIL, esilstr);\n\t\t// looks like ^C is handled by esil_parse !!!!\n\t\t//rz_analysis_esil_dumpstack (ESIL);\n\t\t//rz_analysis_esil_stack_free (ESIL);\n\t\tswitch (op.type) {\n\t\tcase RZ_ANALYSIS_OP_TYPE_LEA:\n\t\t\t// arm64\n\t\t\tif (core->analysis->cur && arch == RZ_ARCH_ARM64) {\n\t\t\t\tif (CHECKREF(ESIL->cur)) {\n\t\t\t\t\trz_analysis_xrefs_set(core->analysis, cur, ESIL->cur, RZ_ANALYSIS_REF_TYPE_STRING);\n\t\t\t\t}\n\t\t\t} else if ((target && op.ptr == ntarget) || !target) {\n\t\t\t\tif (CHECKREF(ESIL->cur)) {\n\t\t\t\t\tif (op.ptr && rz_io_is_valid_offset(core->io, op.ptr, !core->analysis->opt.noncode)) {\n\t\t\t\t\t\trz_analysis_xrefs_set(core->analysis, cur, op.ptr, RZ_ANALYSIS_REF_TYPE_STRING);\n\t\t\t\t\t} else {\n\t\t\t\t\t\trz_analysis_xrefs_set(core->analysis, cur, ESIL->cur, RZ_ANALYSIS_REF_TYPE_STRING);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (cfg_analysis_strings) {\n\t\t\t\tadd_string_ref(core, op.addr, op.ptr);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase RZ_ANALYSIS_OP_TYPE_ADD:\n\t\t\t/* TODO: test if this is valid for other archs too */\n\t\t\tif (core->analysis->cur && archIsArm) {\n\t\t\t\t/* This code is known to work on Thumb, ARM and ARM64 */\n\t\t\t\tut64 dst = ESIL->cur;\n\t\t\t\tif ((target && dst == ntarget) || !target) {\n\t\t\t\t\tif (CHECKREF(dst)) {\n\t\t\t\t\t\trz_analysis_xrefs_set(core->analysis, cur, dst, RZ_ANALYSIS_REF_TYPE_DATA);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (cfg_analysis_strings) {\n\t\t\t\t\tadd_string_ref(core, op.addr, dst);\n\t\t\t\t}\n\t\t\t} else if ((core->analysis->bits == 32 && core->analysis->cur && arch == RZ_ARCH_MIPS)) {\n\t\t\t\tut64 dst = ESIL->cur;\n\t\t\t\tif (!op.src[0] || !op.src[0]->reg || !op.src[0]->reg->name) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (!strcmp(op.src[0]->reg->name, \"sp\")) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (!strcmp(op.src[0]->reg->name, \"zero\")) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif ((target && dst == ntarget) || !target) {\n\t\t\t\t\tif (dst > 0xffff && op.src[1] && (dst & 0xffff) == (op.src[1]->imm & 0xffff) && myvalid(core->io, dst)) {\n\t\t\t\t\t\tRzFlagItem *f;\n\t\t\t\t\t\tchar *str;\n\t\t\t\t\t\tif (CHECKREF(dst) || CHECKREF(cur)) {\n\t\t\t\t\t\t\trz_analysis_xrefs_set(core->analysis, cur, dst, RZ_ANALYSIS_REF_TYPE_DATA);\n\t\t\t\t\t\t\tif (cfg_analysis_strings) {\n\t\t\t\t\t\t\t\tadd_string_ref(core, op.addr, dst);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif ((f = rz_core_flag_get_by_spaces(core->flags, dst))) {\n\t\t\t\t\t\t\t\trz_meta_set_string(core->analysis, RZ_META_TYPE_COMMENT, cur, f->name);\n\t\t\t\t\t\t\t} else if ((str = is_string_at(core, dst, NULL))) {\n\t\t\t\t\t\t\t\tchar *str2 = sdb_fmt(\"esilref: '%s'\", str);\n\t\t\t\t\t\t\t\t// HACK avoid format string inside string used later as format\n\t\t\t\t\t\t\t\t// string crashes disasm inside agf under some conditions.\n\t\t\t\t\t\t\t\t// https://github.com/rizinorg/rizin/issues/6937\n\t\t\t\t\t\t\t\trz_str_replace_char(str2, '%', '&');\n\t\t\t\t\t\t\t\trz_meta_set_string(core->analysis, RZ_META_TYPE_COMMENT, cur, str2);\n\t\t\t\t\t\t\t\tfree(str);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase RZ_ANALYSIS_OP_TYPE_LOAD: {\n\t\t\tut64 dst = esilbreak_last_read;\n\t\t\tif (dst != UT64_MAX && CHECKREF(dst)) {\n\t\t\t\tif (myvalid(core->io, dst)) {\n\t\t\t\t\trz_analysis_xrefs_set(core->analysis, cur, dst, RZ_ANALYSIS_REF_TYPE_DATA);\n\t\t\t\t\tif (cfg_analysis_strings) {\n\t\t\t\t\t\tadd_string_ref(core, op.addr, dst);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tdst = esilbreak_last_data;\n\t\t\tif (dst != UT64_MAX && CHECKREF(dst)) {\n\t\t\t\tif (myvalid(core->io, dst)) {\n\t\t\t\t\trz_analysis_xrefs_set(core->analysis, cur, dst, RZ_ANALYSIS_REF_TYPE_DATA);\n\t\t\t\t\tif (cfg_analysis_strings) {\n\t\t\t\t\t\tadd_string_ref(core, op.addr, dst);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} break;\n\t\tcase RZ_ANALYSIS_OP_TYPE_JMP: {\n\t\t\tut64 dst = op.jump;\n\t\t\tif (CHECKREF(dst)) {\n\t\t\t\tif (myvalid(core->io, dst)) {\n\t\t\t\t\trz_analysis_xrefs_set(core->analysis, cur, dst, RZ_ANALYSIS_REF_TYPE_CODE);\n\t\t\t\t}\n\t\t\t}\n\t\t} break;\n\t\tcase RZ_ANALYSIS_OP_TYPE_CALL: {\n\t\t\tut64 dst = op.jump;\n\t\t\tif (CHECKREF(dst)) {\n\t\t\t\tif (myvalid(core->io, dst)) {\n\t\t\t\t\trz_analysis_xrefs_set(core->analysis, cur, dst, RZ_ANALYSIS_REF_TYPE_CALL);\n\t\t\t\t}\n\t\t\t\tESIL->old = cur + op.size;\n\t\t\t\tgetpcfromstack(core, ESIL);\n\t\t\t}\n\t\t} break;\n\t\tcase RZ_ANALYSIS_OP_TYPE_UJMP:\n\t\tcase RZ_ANALYSIS_OP_TYPE_RJMP:\n\t\tcase RZ_ANALYSIS_OP_TYPE_UCALL:\n\t\tcase RZ_ANALYSIS_OP_TYPE_ICALL:\n\t\tcase RZ_ANALYSIS_OP_TYPE_RCALL:\n\t\tcase RZ_ANALYSIS_OP_TYPE_IRCALL:\n\t\tcase RZ_ANALYSIS_OP_TYPE_MJMP: {\n\t\t\tut64 dst = core->analysis->esil->jump_target;\n\t\t\tif (dst == 0 || dst == UT64_MAX) {\n\t\t\t\tdst = rz_reg_getv(core->analysis->reg, pcname);\n\t\t\t}\n\t\t\tif (CHECKREF(dst)) {\n\t\t\t\tif (myvalid(core->io, dst)) {\n\t\t\t\t\tRzAnalysisXRefType ref =\n\t\t\t\t\t\t(op.type & RZ_ANALYSIS_OP_TYPE_MASK) == RZ_ANALYSIS_OP_TYPE_UCALL\n\t\t\t\t\t\t? RZ_ANALYSIS_REF_TYPE_CALL\n\t\t\t\t\t\t: RZ_ANALYSIS_REF_TYPE_CODE;\n\t\t\t\t\trz_analysis_xrefs_set(core->analysis, cur, dst, ref);\n\t\t\t\t\trz_core_analysis_fcn(core, dst, UT64_MAX, RZ_ANALYSIS_REF_TYPE_NULL, 1);\n// analyze function here\n#if 0\n\t\t\t\t\t\tif (op.type == RZ_ANALYSIS_OP_TYPE_UCALL || op.type == RZ_ANALYSIS_OP_TYPE_RCALL) {\n\t\t\t\t\t\t\teprintf (\"0x%08\"PFMT64x\" RCALL TO %llx\\n\", cur, dst);\n\t\t\t\t\t\t}\n#endif\n\t\t\t\t}\n\t\t\t}\n\t\t} break;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t\trz_analysis_esil_stack_free(ESIL);\n\trepeat:\n\t\tif (!rz_analysis_get_block_at(core->analysis, cur)) {\n\t\t\tfor (size_t bb_i = i_old + 1; bb_i <= i; bb_i++) {\n\t\t\t\tif (rz_analysis_get_block_at(core->analysis, start + bb_i)) {\n\t\t\t\t\ti = bb_i - 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (i > iend) {\n\t\t\tbreak;\n\t\t}\n\t} while (get_next_i(&ictx, &i));\n\tfree(buf);\n\tESIL->cb.hook_mem_read = NULL;\n\tESIL->cb.hook_mem_write = NULL;\n\tESIL->cb.hook_reg_write = NULL;\n\tESIL->user = NULL;\n\trz_analysis_op_fini(&op);\n\trz_cons_break_pop();\n\t// restore register\n\trz_reg_arena_pop(core->analysis->reg);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'Initialize retctx,ctx before freeing the inner elements\n\nIn rz_core_analysis_type_match retctx structure was initialized on the\nstack only after a \"goto out_function\", where a field of that structure\nwas freed. When the goto path is taken, the field is not properly\ninitialized and it cause cause a crash of Rizin or have other effects.\n\nFixes: CVE-2021-4022'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int pfkey_register(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)\n{\n\tstruct pfkey_sock *pfk = pfkey_sk(sk);\n\tstruct sk_buff *supp_skb;\n\n\tif (hdr->sadb_msg_satype > SADB_SATYPE_MAX)\n\t\treturn -EINVAL;\n\n\tif (hdr->sadb_msg_satype != SADB_SATYPE_UNSPEC) {\n\t\tif (pfk->registered&(1<sadb_msg_satype))\n\t\t\treturn -EEXIST;\n\t\tpfk->registered |= (1<sadb_msg_satype);\n\t}\n\n\txfrm_probe_algs();\n\n\tsupp_skb = compose_sadb_supported(hdr, GFP_KERNEL);\n\tif (!supp_skb) {\n\t\tif (hdr->sadb_msg_satype != SADB_SATYPE_UNSPEC)\n\t\t\tpfk->registered &= ~(1<sadb_msg_satype);\n\n\t\treturn -ENOBUFS;\n\t}\n\n\tpfkey_broadcast(supp_skb, GFP_KERNEL, BROADCAST_REGISTERED, sk,\n\t\t\tsock_net(sk));\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'af_key: add __GFP_ZERO flag for compose_sadb_supported in function pfkey_register\n\nAdd __GFP_ZERO flag for compose_sadb_supported in function pfkey_register\nto initialize the buffer of supp_skb to fix a kernel-info-leak issue.\n1) Function pfkey_register calls compose_sadb_supported to request\na sk_buff. 2) compose_sadb_supported calls alloc_sbk to allocate\na sk_buff, but it doesn't zero it. 3) If auth_len is greater 0, then\ncompose_sadb_supported treats the memory as a struct sadb_supported and\nbegins to initialize. But it just initializes the field sadb_supported_len\nand field sadb_supported_exttype without field sadb_supported_reserved.\n\nReported-by: TCS Robot \nSigned-off-by: Haimin Zhang \nSigned-off-by: Steffen Klassert '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: R_API RBinJavaAttrInfo *r_bin_java_line_number_table_attr_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {\n\tut32 i = 0;\n\tut64 curpos, offset = 0;\n\tRBinJavaLineNumberAttribute *lnattr;\n\tRBinJavaAttrInfo *attr = r_bin_java_default_attr_new (buffer, sz, buf_offset);\n\tif (!attr) {\n\t\treturn NULL;\n\t}\n\toffset += 6;\n\tattr->type = R_BIN_JAVA_ATTR_TYPE_LINE_NUMBER_TABLE_ATTR;\n\tattr->info.line_number_table_attr.line_number_table_length = R_BIN_JAVA_USHORT (buffer, offset);\n\toffset += 2;\n\tattr->info.line_number_table_attr.line_number_table = r_list_newf (free);\n\n\tut32 linenum_len = attr->info.line_number_table_attr.line_number_table_length;\n\tRList *linenum_list = attr->info.line_number_table_attr.line_number_table;\n\tif (linenum_len > sz) {\n\t\tfree (attr);\n\t\treturn NULL;\n\t}\n\tfor (i = 0; i < linenum_len; i++) {\n\t\tcurpos = buf_offset + offset;\n\t\t// printf (\"%llx %llx \\n\", curpos, sz);\n\t\t// XXX if (curpos + 8 >= sz) break;\n\t\tlnattr = R_NEW0 (RBinJavaLineNumberAttribute);\n\t\tif (!lnattr) {\n\t\t\tbreak;\n\t\t}\n\t\tlnattr->start_pc = R_BIN_JAVA_USHORT (buffer, offset);\n\t\toffset += 2;\n\t\tlnattr->line_number = R_BIN_JAVA_USHORT (buffer, offset);\n\t\toffset += 2;\n\t\tlnattr->file_offset = curpos;\n\t\tlnattr->size = 4;\n\t\tr_list_append (linenum_list, lnattr);\n\t}\n\tattr->size = offset;\n\treturn attr;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix #10498 - Fix crash in fuzzed java files (#10511)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void add_bytes_l2_c(uint8_t *dst, uint8_t *src1, uint8_t *src2, int w)\n{\n long i;\n for (i = 0; i <= w - sizeof(long); i += sizeof(long)) {\n long a = *(long *)(src1 + i);\n long b = *(long *)(src2 + i);\n *(long *)(dst + i) = ((a & pb_7f) + (b & pb_7f)) ^ ((a ^ b) & pb_80);\n }\n for (; i < w; i++)\n dst[i] = src1[i] + src2[i];\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'avcodec/pngdsp: fix (un)signed type in end comparission\n\nFixes out of array accesses\nFixes Ticket2919\n\nFound_by: ami_stuff\nSigned-off-by: Michael Niedermayer '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: tgs_make_reply(krb5_context context,\n\t krb5_kdc_configuration *config,\n\t KDC_REQ_BODY *b,\n\t krb5_const_principal tgt_name,\n\t const EncTicketPart *tgt,\n\t const krb5_keyblock *replykey,\n\t int rk_is_subkey,\n\t const EncryptionKey *serverkey,\n\t const krb5_keyblock *sessionkey,\n\t krb5_kvno kvno,\n\t AuthorizationData *auth_data,\n\t hdb_entry_ex *server,\n\t krb5_principal server_principal,\n\t const char *server_name,\n\t hdb_entry_ex *client,\n\t krb5_principal client_principal,\n\t hdb_entry_ex *krbtgt,\n\t krb5_enctype krbtgt_etype,\n\t krb5_principals spp,\n\t const krb5_data *rspac,\n\t const METHOD_DATA *enc_pa_data,\n\t const char **e_text,\n\t krb5_data *reply)\n{\n KDC_REP rep;\n EncKDCRepPart ek;\n EncTicketPart et;\n KDCOptions f = b->kdc_options;\n krb5_error_code ret;\n int is_weak = 0;\n\n memset(&rep, 0, sizeof(rep));\n memset(&et, 0, sizeof(et));\n memset(&ek, 0, sizeof(ek));\n\n rep.pvno = 5;\n rep.msg_type = krb_tgs_rep;\n\n et.authtime = tgt->authtime;\n _kdc_fix_time(&b->till);\n et.endtime = min(tgt->endtime, *b->till);\n ALLOC(et.starttime);\n *et.starttime = kdc_time;\n\n ret = check_tgs_flags(context, config, b, tgt, &et);\n if(ret)\n\tgoto out;\n\n /* We should check the transited encoding if:\n 1) the request doesn't ask not to be checked\n 2) globally enforcing a check\n 3) principal requires checking\n 4) we allow non-check per-principal, but principal isn't marked as allowing this\n 5) we don't globally allow this\n */\n\n#define GLOBAL_FORCE_TRANSITED_CHECK\t\t\\\n (config->trpolicy == TRPOLICY_ALWAYS_CHECK)\n#define GLOBAL_ALLOW_PER_PRINCIPAL\t\t\t\\\n (config->trpolicy == TRPOLICY_ALLOW_PER_PRINCIPAL)\n#define GLOBAL_ALLOW_DISABLE_TRANSITED_CHECK\t\t\t\\\n (config->trpolicy == TRPOLICY_ALWAYS_HONOUR_REQUEST)\n\n/* these will consult the database in future release */\n#define PRINCIPAL_FORCE_TRANSITED_CHECK(P)\t\t0\n#define PRINCIPAL_ALLOW_DISABLE_TRANSITED_CHECK(P)\t0\n\n ret = fix_transited_encoding(context, config,\n\t\t\t\t !f.disable_transited_check ||\n\t\t\t\t GLOBAL_FORCE_TRANSITED_CHECK ||\n\t\t\t\t PRINCIPAL_FORCE_TRANSITED_CHECK(server) ||\n\t\t\t\t !((GLOBAL_ALLOW_PER_PRINCIPAL &&\n\t\t\t\t PRINCIPAL_ALLOW_DISABLE_TRANSITED_CHECK(server)) ||\n\t\t\t\t GLOBAL_ALLOW_DISABLE_TRANSITED_CHECK),\n\t\t\t\t &tgt->transited, &et,\n\t\t\t\t krb5_principal_get_realm(context, client_principal),\n\t\t\t\t krb5_principal_get_realm(context, server->entry.principal),\n\t\t\t\t krb5_principal_get_realm(context, krbtgt->entry.principal));\n if(ret)\n\tgoto out;\n\n copy_Realm(&server_principal->realm, &rep.ticket.realm);\n _krb5_principal2principalname(&rep.ticket.sname, server_principal);\n copy_Realm(&tgt_name->realm, &rep.crealm);\n/*\n if (f.request_anonymous)\n\t_kdc_make_anonymous_principalname (&rep.cname);\n else */\n\n copy_PrincipalName(&tgt_name->name, &rep.cname);\n rep.ticket.tkt_vno = 5;\n\n ek.caddr = et.caddr;\n\n {\n\ttime_t life;\n\tlife = et.endtime - *et.starttime;\n\tif(client && client->entry.max_life)\n\t life = min(life, *client->entry.max_life);\n\tif(server->entry.max_life)\n\t life = min(life, *server->entry.max_life);\n\tet.endtime = *et.starttime + life;\n }\n if(f.renewable_ok && tgt->flags.renewable &&\n et.renew_till == NULL && et.endtime < *b->till &&\n tgt->renew_till != NULL)\n {\n\tet.flags.renewable = 1;\n\tALLOC(et.renew_till);\n\t*et.renew_till = *b->till;\n }\n if(et.renew_till){\n\ttime_t renew;\n\trenew = *et.renew_till - *et.starttime;\n\tif(client && client->entry.max_renew)\n\t renew = min(renew, *client->entry.max_renew);\n\tif(server->entry.max_renew)\n\t renew = min(renew, *server->entry.max_renew);\n\t*et.renew_till = *et.starttime + renew;\n }\n\n if(et.renew_till){\n\t*et.renew_till = min(*et.renew_till, *tgt->renew_till);\n\t*et.starttime = min(*et.starttime, *et.renew_till);\n\tet.endtime = min(et.endtime, *et.renew_till);\n }\n\n *et.starttime = min(*et.starttime, et.endtime);\n\n if(*et.starttime == et.endtime){\n\tret = KRB5KDC_ERR_NEVER_VALID;\n\tgoto out;\n }\n if(et.renew_till && et.endtime == *et.renew_till){\n\tfree(et.renew_till);\n\tet.renew_till = NULL;\n\tet.flags.renewable = 0;\n }\n\n et.flags.pre_authent = tgt->flags.pre_authent;\n et.flags.hw_authent = tgt->flags.hw_authent;\n et.flags.anonymous = tgt->flags.anonymous;\n et.flags.ok_as_delegate = server->entry.flags.ok_as_delegate;\n\n if(rspac->length) {\n\t/*\n\t * No not need to filter out the any PAC from the\n\t * auth_data since it's signed by the KDC.\n\t */\n\tret = _kdc_tkt_add_if_relevant_ad(context, &et,\n\t\t\t\t\t KRB5_AUTHDATA_WIN2K_PAC, rspac);\n\tif (ret)\n\t goto out;\n }\n\n if (auth_data) {\n\tunsigned int i = 0;\n\n\t/* XXX check authdata */\n\n\tif (et.authorization_data == NULL) {\n\t et.authorization_data = calloc(1, sizeof(*et.authorization_data));\n\t if (et.authorization_data == NULL) {\n\t\tret = ENOMEM;\n\t\tkrb5_set_error_message(context, ret, \"malloc: out of memory\");\n\t\tgoto out;\n\t }\n\t}\n\tfor(i = 0; i < auth_data->len ; i++) {\n\t ret = add_AuthorizationData(et.authorization_data, &auth_data->val[i]);\n\t if (ret) {\n\t\tkrb5_set_error_message(context, ret, \"malloc: out of memory\");\n\t\tgoto out;\n\t }\n\t}\n\n\t/* Filter out type KRB5SignedPath */\n\tret = find_KRB5SignedPath(context, et.authorization_data, NULL);\n\tif (ret == 0) {\n\t if (et.authorization_data->len == 1) {\n\t\tfree_AuthorizationData(et.authorization_data);\n\t\tfree(et.authorization_data);\n\t\tet.authorization_data = NULL;\n\t } else {\n\t\tAuthorizationData *ad = et.authorization_data;\n\t\tfree_AuthorizationDataElement(&ad->val[ad->len - 1]);\n\t\tad->len--;\n\t }\n\t}\n }\n\n ret = krb5_copy_keyblock_contents(context, sessionkey, &et.key);\n if (ret)\n\tgoto out;\n et.crealm = tgt_name->realm;\n et.cname = tgt_name->name;\n\n ek.key = et.key;\n /* MIT must have at least one last_req */\n ek.last_req.val = calloc(1, sizeof(*ek.last_req.val));\n if (ek.last_req.val == NULL) {\n\tret = ENOMEM;\n\tgoto out;\n }\n ek.last_req.len = 1; /* set after alloc to avoid null deref on cleanup */\n ek.nonce = b->nonce;\n ek.flags = et.flags;\n ek.authtime = et.authtime;\n ek.starttime = et.starttime;\n ek.endtime = et.endtime;\n ek.renew_till = et.renew_till;\n ek.srealm = rep.ticket.realm;\n ek.sname = rep.ticket.sname;\n\n _kdc_log_timestamp(context, config, \"TGS-REQ\", et.authtime, et.starttime,\n\t\t et.endtime, et.renew_till);\n\n /* Don't sign cross realm tickets, they can't be checked anyway */\n {\n\tchar *r = get_krbtgt_realm(&ek.sname);\n\n\tif (r == NULL || strcmp(r, ek.srealm) == 0) {\n\t ret = _kdc_add_KRB5SignedPath(context,\n\t\t\t\t\t config,\n\t\t\t\t\t krbtgt,\n\t\t\t\t\t krbtgt_etype,\n\t\t\t\t\t client_principal,\n\t\t\t\t\t NULL,\n\t\t\t\t\t spp,\n\t\t\t\t\t &et);\n\t if (ret)\n\t\tgoto out;\n\t}\n }\n\n if (enc_pa_data->len) {\n\trep.padata = calloc(1, sizeof(*rep.padata));\n\tif (rep.padata == NULL) {\n\t ret = ENOMEM;\n\t goto out;\n\t}\n\tret = copy_METHOD_DATA(enc_pa_data, rep.padata);\n\tif (ret)\n\t goto out;\n }\n\n if (krb5_enctype_valid(context, serverkey->keytype) != 0\n\t&& _kdc_is_weak_exception(server->entry.principal, serverkey->keytype))\n {\n\tkrb5_enctype_enable(context, serverkey->keytype);\n\tis_weak = 1;\n }\n\n\n /* It is somewhat unclear where the etype in the following\n encryption should come from. What we have is a session\n key in the passed tgt, and a list of preferred etypes\n *for the new ticket*. Should we pick the best possible\n etype, given the keytype in the tgt, or should we look\n at the etype list here as well? What if the tgt\n session key is DES3 and we want a ticket with a (say)\n CAST session key. Should the DES3 etype be added to the\n etype list, even if we don't want a session key with\n DES3? */\n ret = _kdc_encode_reply(context, config, NULL, 0,\n\t\t\t &rep, &et, &ek, serverkey->keytype,\n\t\t\t kvno,\n\t\t\t serverkey, 0, replykey, rk_is_subkey,\n\t\t\t e_text, reply);\n if (is_weak)\n\tkrb5_enctype_disable(context, serverkey->keytype);\n\nout:\n free_TGS_REP(&rep);\n free_TransitedEncoding(&et.transited);\n if(et.starttime)\n\tfree(et.starttime);\n if(et.renew_till)\n\tfree(et.renew_till);\n if(et.authorization_data) {\n\tfree_AuthorizationData(et.authorization_data);\n\tfree(et.authorization_data);\n }\n free_LastReq(&ek.last_req);\n memset(et.key.keyvalue.data, 0, et.key.keyvalue.length);\n free_EncryptionKey(&et.key);\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284', 'CWE-295'], 'message': 'Fix transit path validation CVE-2017-6594\n\nCommit f469fc6 (2010-10-02) inadvertently caused the previous hop realm\nto not be added to the transit path of issued tickets. This may, in\nsome cases, enable bypass of capath policy in Heimdal versions 1.5\nthrough 7.2.\n\nNote, this may break sites that rely on the bug. With the bug some\nincomplete [capaths] worked, that should not have. These may now break\nauthentication in some cross-realm configurations.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline int object_common2(UNSERIALIZE_PARAMETER, long elements)\n{\n\tzval *retval_ptr = NULL;\n\tzval fname;\n\n\tif (Z_TYPE_PP(rval) != IS_OBJECT) {\n\t\treturn 0;\n\t}\n\n\tif (!process_nested_data(UNSERIALIZE_PASSTHRU, Z_OBJPROP_PP(rval), elements, 1)) {\n\t /* We've got partially constructed object on our hands here. Wipe it. */\n\t if(Z_TYPE_PP(rval) == IS_OBJECT) {\n\t zend_hash_clean(Z_OBJPROP_PP(rval));\n\t }\n\t ZVAL_NULL(*rval);\n\t\treturn 0;\n\t}\n\n if (Z_TYPE_PP(rval) != IS_OBJECT) {\n return 0;\n }\n\n\tif (Z_OBJCE_PP(rval) != PHP_IC_ENTRY &&\n\t\tzend_hash_exists(&Z_OBJCE_PP(rval)->function_table, \"__wakeup\", sizeof(\"__wakeup\"))) {\n\t\tINIT_PZVAL(&fname);\n\t\tZVAL_STRINGL(&fname, \"__wakeup\", sizeof(\"__wakeup\") - 1, 0);\n\t\tBG(serialize_lock)++;\n\t\tcall_user_function_ex(CG(function_table), rval, &fname, &retval_ptr, 0, 0, 1, NULL TSRMLS_CC);\n\t\tBG(serialize_lock)--;\n\t}\n\n\tif (retval_ptr) {\n\t\tzval_ptr_dtor(&retval_ptr);\n\t}\n\n\tif (EG(exception)) {\n\t\treturn 0;\n\t}\n\n\treturn finish_nested_data(UNSERIALIZE_PASSTHRU);\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix bug #73052 - Memory Corruption in During Deserialized-object Destruction'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: friend bool operator==(const TensorKey& t1, const TensorKey& t2) {\n if (t1.dtype() != t2.dtype() || t1.shape() != t2.shape()) {\n return false;\n }\n if (DataTypeCanUseMemcpy(t1.dtype())) {\n return t1.tensor_data() == t2.tensor_data();\n }\n if (t1.dtype() == DT_STRING) {\n const auto s1 = t1.unaligned_flat();\n const auto s2 = t2.unaligned_flat();\n for (int64_t i = 0, n = t1.NumElements(); i < n; ++i) {\n if (TF_PREDICT_FALSE(s1(i) != s2(i))) {\n return false;\n }\n }\n return true;\n }\n return false;\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-122', 'CWE-787'], 'message': 'Fix TensorKey hash function.\n\nThe original hash function only used total estimated `AllocatedBytes()`, which (a) is an estimate per tensor, and (b) is a very poor hash function for constants (e.g. `int32_t`).\nIt also tried to access individual tensor bytes through `tensor.data()` of size `AllocatedBytes()`. This led to ASAN failures because the `AllocatedBytes()` is an estimate of total bytes allocated by a tensor, including any pointed-to constructs (e.g. strings), and does not refer to contiguous bytes in the `.data()` buffer. We couldn't use this byte vector anyways, since types like `tstring` include pointers, whereas we need to hash the string values themselves.\n\nModified the hash function to more closely mirror the `==` operator. This correctly handles `tstring` and any numeric types that do have contiguous storage. Other types are currently left as unimplemented.\n\nPiperOrigin-RevId: 446265413'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int hevc_frame_start(HEVCContext *s)\n{\n HEVCLocalContext *lc = &s->HEVClc;\n int ret;\n\n memset(s->horizontal_bs, 0, 2 * s->bs_width * (s->bs_height + 1));\n memset(s->vertical_bs, 0, 2 * s->bs_width * (s->bs_height + 1));\n memset(s->cbf_luma, 0, s->sps->min_tb_width * s->sps->min_tb_height);\n memset(s->is_pcm, 0, s->sps->min_pu_width * s->sps->min_pu_height);\n\n lc->start_of_tiles_x = 0;\n s->is_decoded = 0;\n\n if (s->pps->tiles_enabled_flag)\n lc->end_of_tiles_x = s->pps->column_width[0] << s->sps->log2_ctb_size;\n\n ret = ff_hevc_set_new_ref(s, s->sps->sao_enabled ? &s->sao_frame : &s->frame,\n s->poc);\n if (ret < 0)\n goto fail;\n\n ret = ff_hevc_frame_rps(s);\n if (ret < 0) {\n av_log(s->avctx, AV_LOG_ERROR, \"Error constructing the frame RPS.\\n\");\n goto fail;\n }\n\n ret = set_side_data(s);\n if (ret < 0)\n goto fail;\n\n av_frame_unref(s->output_frame);\n ret = ff_hevc_output_frame(s, s->output_frame, 0);\n if (ret < 0)\n goto fail;\n\n ff_thread_finish_setup(s->avctx);\n\n return 0;\n\nfail:\n if (s->ref)\n ff_thread_report_progress(&s->ref->tf, INT_MAX, 0);\n s->ref = NULL;\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'hevc: check that the VCL NAL types are the same for all slice segments of a frame\n\nFixes possible invalid memory access for mismatching skipped/non-skipped\nslice segments.\n\nFound-by: Mateusz \"j00ru\" Jurczyk and Gynvael Coldwind\nSample-Id: 00001533-google'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int lag_decode_frame(AVCodecContext *avctx,\n void *data, int *got_frame, AVPacket *avpkt)\n{\n const uint8_t *buf = avpkt->data;\n int buf_size = avpkt->size;\n LagarithContext *l = avctx->priv_data;\n ThreadFrame frame = { .f = data };\n AVFrame *const p = data;\n uint8_t frametype = 0;\n uint32_t offset_gu = 0, offset_bv = 0, offset_ry = 9;\n uint32_t offs[4];\n uint8_t *srcs[4], *dst;\n int i, j, planes = 3;\n\n p->key_frame = 1;\n\n frametype = buf[0];\n\n offset_gu = AV_RL32(buf + 1);\n offset_bv = AV_RL32(buf + 5);\n\n switch (frametype) {\n case FRAME_SOLID_RGBA:\n avctx->pix_fmt = AV_PIX_FMT_RGB32;\n\n if (ff_thread_get_buffer(avctx, &frame, 0) < 0) {\n av_log(avctx, AV_LOG_ERROR, \"get_buffer() failed\\n\");\n return -1;\n }\n\n dst = p->data[0];\n for (j = 0; j < avctx->height; j++) {\n for (i = 0; i < avctx->width; i++)\n AV_WN32(dst + i * 4, offset_gu);\n dst += p->linesize[0];\n }\n break;\n case FRAME_ARITH_RGBA:\n avctx->pix_fmt = AV_PIX_FMT_RGB32;\n planes = 4;\n offset_ry += 4;\n offs[3] = AV_RL32(buf + 9);\n case FRAME_ARITH_RGB24:\n case FRAME_U_RGB24:\n if (frametype == FRAME_ARITH_RGB24 || frametype == FRAME_U_RGB24)\n avctx->pix_fmt = AV_PIX_FMT_RGB24;\n\n if (ff_thread_get_buffer(avctx, &frame, 0) < 0) {\n av_log(avctx, AV_LOG_ERROR, \"get_buffer() failed\\n\");\n return -1;\n }\n\n offs[0] = offset_bv;\n offs[1] = offset_gu;\n offs[2] = offset_ry;\n\n if (!l->rgb_planes) {\n l->rgb_stride = FFALIGN(avctx->width, 16);\n l->rgb_planes = av_malloc(l->rgb_stride * avctx->height * planes + 1);\n if (!l->rgb_planes) {\n av_log(avctx, AV_LOG_ERROR, \"cannot allocate temporary buffer\\n\");\n return AVERROR(ENOMEM);\n }\n }\n for (i = 0; i < planes; i++)\n srcs[i] = l->rgb_planes + (i + 1) * l->rgb_stride * avctx->height - l->rgb_stride;\n if (offset_ry >= buf_size ||\n offset_gu >= buf_size ||\n offset_bv >= buf_size ||\n (planes == 4 && offs[3] >= buf_size)) {\n av_log(avctx, AV_LOG_ERROR,\n \"Invalid frame offsets\\n\");\n return AVERROR_INVALIDDATA;\n }\n for (i = 0; i < planes; i++)\n lag_decode_arith_plane(l, srcs[i],\n avctx->width, avctx->height,\n -l->rgb_stride, buf + offs[i],\n buf_size - offs[i]);\n dst = p->data[0];\n for (i = 0; i < planes; i++)\n srcs[i] = l->rgb_planes + i * l->rgb_stride * avctx->height;\n for (j = 0; j < avctx->height; j++) {\n for (i = 0; i < avctx->width; i++) {\n uint8_t r, g, b, a;\n r = srcs[0][i];\n g = srcs[1][i];\n b = srcs[2][i];\n r += g;\n b += g;\n if (frametype == FRAME_ARITH_RGBA) {\n a = srcs[3][i];\n AV_WN32(dst + i * 4, MKBETAG(a, r, g, b));\n } else {\n dst[i * 3 + 0] = r;\n dst[i * 3 + 1] = g;\n dst[i * 3 + 2] = b;\n }\n }\n dst += p->linesize[0];\n for (i = 0; i < planes; i++)\n srcs[i] += l->rgb_stride;\n }\n break;\n case FRAME_ARITH_YUY2:\n avctx->pix_fmt = AV_PIX_FMT_YUV422P;\n\n if (ff_thread_get_buffer(avctx, &frame, 0) < 0) {\n av_log(avctx, AV_LOG_ERROR, \"get_buffer() failed\\n\");\n return -1;\n }\n\n if (offset_ry >= buf_size ||\n offset_gu >= buf_size ||\n offset_bv >= buf_size) {\n av_log(avctx, AV_LOG_ERROR,\n \"Invalid frame offsets\\n\");\n return AVERROR_INVALIDDATA;\n }\n\n lag_decode_arith_plane(l, p->data[0], avctx->width, avctx->height,\n p->linesize[0], buf + offset_ry,\n buf_size - offset_ry);\n lag_decode_arith_plane(l, p->data[1], avctx->width / 2,\n avctx->height, p->linesize[1],\n buf + offset_gu, buf_size - offset_gu);\n lag_decode_arith_plane(l, p->data[2], avctx->width / 2,\n avctx->height, p->linesize[2],\n buf + offset_bv, buf_size - offset_bv);\n break;\n case FRAME_ARITH_YV12:\n avctx->pix_fmt = AV_PIX_FMT_YUV420P;\n\n if (ff_thread_get_buffer(avctx, &frame, 0) < 0) {\n av_log(avctx, AV_LOG_ERROR, \"get_buffer() failed\\n\");\n return -1;\n }\n\n if (offset_ry >= buf_size ||\n offset_gu >= buf_size ||\n offset_bv >= buf_size) {\n av_log(avctx, AV_LOG_ERROR,\n \"Invalid frame offsets\\n\");\n return AVERROR_INVALIDDATA;\n }\n\n lag_decode_arith_plane(l, p->data[0], avctx->width, avctx->height,\n p->linesize[0], buf + offset_ry,\n buf_size - offset_ry);\n lag_decode_arith_plane(l, p->data[2], avctx->width / 2,\n avctx->height / 2, p->linesize[2],\n buf + offset_gu, buf_size - offset_gu);\n lag_decode_arith_plane(l, p->data[1], avctx->width / 2,\n avctx->height / 2, p->linesize[1],\n buf + offset_bv, buf_size - offset_bv);\n break;\n default:\n av_log(avctx, AV_LOG_ERROR,\n \"Unsupported Lagarith frame type: %#x\\n\", frametype);\n return -1;\n }\n\n *got_frame = 1;\n\n return buf_size;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'lagarith: reallocate rgb_planes when needed\n\nFixes invalid writes on pixel format changes.\n\nFound-by: Mateusz \"j00ru\" Jurczyk and Gynvael Coldwind\nCC:libav-stable@libav.org'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void bpf_jit_compile(struct sk_filter *fp)\n{\n\tu8 temp[64];\n\tu8 *prog;\n\tunsigned int proglen, oldproglen = 0;\n\tint ilen, i;\n\tint t_offset, f_offset;\n\tu8 t_op, f_op, seen = 0, pass;\n\tu8 *image = NULL;\n\tu8 *func;\n\tint pc_ret0 = -1; /* bpf index of first RET #0 instruction (if any) */\n\tunsigned int cleanup_addr; /* epilogue code offset */\n\tunsigned int *addrs;\n\tconst struct sock_filter *filter = fp->insns;\n\tint flen = fp->len;\n\n\tif (!bpf_jit_enable)\n\t\treturn;\n\n\taddrs = kmalloc(flen * sizeof(*addrs), GFP_KERNEL);\n\tif (addrs == NULL)\n\t\treturn;\n\n\t/* Before first pass, make a rough estimation of addrs[]\n\t * each bpf instruction is translated to less than 64 bytes\n\t */\n\tfor (proglen = 0, i = 0; i < flen; i++) {\n\t\tproglen += 64;\n\t\taddrs[i] = proglen;\n\t}\n\tcleanup_addr = proglen; /* epilogue address */\n\n\tfor (pass = 0; pass < 10; pass++) {\n\t\t/* no prologue/epilogue for trivial filters (RET something) */\n\t\tproglen = 0;\n\t\tprog = temp;\n\n\t\tif (seen) {\n\t\t\tEMIT4(0x55, 0x48, 0x89, 0xe5); /* push %rbp; mov %rsp,%rbp */\n\t\t\tEMIT4(0x48, 0x83, 0xec, 96);\t/* subq $96,%rsp\t*/\n\t\t\t/* note : must save %rbx in case bpf_error is hit */\n\t\t\tif (seen & (SEEN_XREG | SEEN_DATAREF))\n\t\t\t\tEMIT4(0x48, 0x89, 0x5d, 0xf8); /* mov %rbx, -8(%rbp) */\n\t\t\tif (seen & SEEN_XREG)\n\t\t\t\tCLEAR_X(); /* make sure we dont leek kernel memory */\n\n\t\t\t/*\n\t\t\t * If this filter needs to access skb data,\n\t\t\t * loads r9 and r8 with :\n\t\t\t * r9 = skb->len - skb->data_len\n\t\t\t * r8 = skb->data\n\t\t\t */\n\t\t\tif (seen & SEEN_DATAREF) {\n\t\t\t\tif (offsetof(struct sk_buff, len) <= 127)\n\t\t\t\t\t/* mov off8(%rdi),%r9d */\n\t\t\t\t\tEMIT4(0x44, 0x8b, 0x4f, offsetof(struct sk_buff, len));\n\t\t\t\telse {\n\t\t\t\t\t/* mov off32(%rdi),%r9d */\n\t\t\t\t\tEMIT3(0x44, 0x8b, 0x8f);\n\t\t\t\t\tEMIT(offsetof(struct sk_buff, len), 4);\n\t\t\t\t}\n\t\t\t\tif (is_imm8(offsetof(struct sk_buff, data_len)))\n\t\t\t\t\t/* sub off8(%rdi),%r9d */\n\t\t\t\t\tEMIT4(0x44, 0x2b, 0x4f, offsetof(struct sk_buff, data_len));\n\t\t\t\telse {\n\t\t\t\t\tEMIT3(0x44, 0x2b, 0x8f);\n\t\t\t\t\tEMIT(offsetof(struct sk_buff, data_len), 4);\n\t\t\t\t}\n\n\t\t\t\tif (is_imm8(offsetof(struct sk_buff, data)))\n\t\t\t\t\t/* mov off8(%rdi),%r8 */\n\t\t\t\t\tEMIT4(0x4c, 0x8b, 0x47, offsetof(struct sk_buff, data));\n\t\t\t\telse {\n\t\t\t\t\t/* mov off32(%rdi),%r8 */\n\t\t\t\t\tEMIT3(0x4c, 0x8b, 0x87);\n\t\t\t\t\tEMIT(offsetof(struct sk_buff, data), 4);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tswitch (filter[0].code) {\n\t\tcase BPF_S_RET_K:\n\t\tcase BPF_S_LD_W_LEN:\n\t\tcase BPF_S_ANC_PROTOCOL:\n\t\tcase BPF_S_ANC_IFINDEX:\n\t\tcase BPF_S_ANC_MARK:\n\t\tcase BPF_S_ANC_RXHASH:\n\t\tcase BPF_S_ANC_CPU:\n\t\tcase BPF_S_ANC_QUEUE:\n\t\tcase BPF_S_LD_W_ABS:\n\t\tcase BPF_S_LD_H_ABS:\n\t\tcase BPF_S_LD_B_ABS:\n\t\t\t/* first instruction sets A register (or is RET 'constant') */\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t/* make sure we dont leak kernel information to user */\n\t\t\tCLEAR_A(); /* A = 0 */\n\t\t}\n\n\t\tfor (i = 0; i < flen; i++) {\n\t\t\tunsigned int K = filter[i].k;\n\n\t\t\tswitch (filter[i].code) {\n\t\t\tcase BPF_S_ALU_ADD_X: /* A += X; */\n\t\t\t\tseen |= SEEN_XREG;\n\t\t\t\tEMIT2(0x01, 0xd8);\t\t/* add %ebx,%eax */\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_ALU_ADD_K: /* A += K; */\n\t\t\t\tif (!K)\n\t\t\t\t\tbreak;\n\t\t\t\tif (is_imm8(K))\n\t\t\t\t\tEMIT3(0x83, 0xc0, K);\t/* add imm8,%eax */\n\t\t\t\telse\n\t\t\t\t\tEMIT1_off32(0x05, K);\t/* add imm32,%eax */\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_ALU_SUB_X: /* A -= X; */\n\t\t\t\tseen |= SEEN_XREG;\n\t\t\t\tEMIT2(0x29, 0xd8);\t\t/* sub %ebx,%eax */\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_ALU_SUB_K: /* A -= K */\n\t\t\t\tif (!K)\n\t\t\t\t\tbreak;\n\t\t\t\tif (is_imm8(K))\n\t\t\t\t\tEMIT3(0x83, 0xe8, K); /* sub imm8,%eax */\n\t\t\t\telse\n\t\t\t\t\tEMIT1_off32(0x2d, K); /* sub imm32,%eax */\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_ALU_MUL_X: /* A *= X; */\n\t\t\t\tseen |= SEEN_XREG;\n\t\t\t\tEMIT3(0x0f, 0xaf, 0xc3);\t/* imul %ebx,%eax */\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_ALU_MUL_K: /* A *= K */\n\t\t\t\tif (is_imm8(K))\n\t\t\t\t\tEMIT3(0x6b, 0xc0, K); /* imul imm8,%eax,%eax */\n\t\t\t\telse {\n\t\t\t\t\tEMIT2(0x69, 0xc0);\t\t/* imul imm32,%eax */\n\t\t\t\t\tEMIT(K, 4);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_ALU_DIV_X: /* A /= X; */\n\t\t\t\tseen |= SEEN_XREG;\n\t\t\t\tEMIT2(0x85, 0xdb);\t/* test %ebx,%ebx */\n\t\t\t\tif (pc_ret0 != -1)\n\t\t\t\t\tEMIT_COND_JMP(X86_JE, addrs[pc_ret0] - (addrs[i] - 4));\n\t\t\t\telse {\n\t\t\t\t\tEMIT_COND_JMP(X86_JNE, 2 + 5);\n\t\t\t\t\tCLEAR_A();\n\t\t\t\t\tEMIT1_off32(0xe9, cleanup_addr - (addrs[i] - 4)); /* jmp .+off32 */\n\t\t\t\t}\n\t\t\t\tEMIT4(0x31, 0xd2, 0xf7, 0xf3); /* xor %edx,%edx; div %ebx */\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_ALU_DIV_K: /* A = reciprocal_divide(A, K); */\n\t\t\t\tEMIT3(0x48, 0x69, 0xc0); /* imul imm32,%rax,%rax */\n\t\t\t\tEMIT(K, 4);\n\t\t\t\tEMIT4(0x48, 0xc1, 0xe8, 0x20); /* shr $0x20,%rax */\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_ALU_AND_X:\n\t\t\t\tseen |= SEEN_XREG;\n\t\t\t\tEMIT2(0x21, 0xd8);\t\t/* and %ebx,%eax */\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_ALU_AND_K:\n\t\t\t\tif (K >= 0xFFFFFF00) {\n\t\t\t\t\tEMIT2(0x24, K & 0xFF); /* and imm8,%al */\n\t\t\t\t} else if (K >= 0xFFFF0000) {\n\t\t\t\t\tEMIT2(0x66, 0x25);\t/* and imm16,%ax */\n\t\t\t\t\tEMIT2(K, 2);\n\t\t\t\t} else {\n\t\t\t\t\tEMIT1_off32(0x25, K);\t/* and imm32,%eax */\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_ALU_OR_X:\n\t\t\t\tseen |= SEEN_XREG;\n\t\t\t\tEMIT2(0x09, 0xd8);\t\t/* or %ebx,%eax */\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_ALU_OR_K:\n\t\t\t\tif (is_imm8(K))\n\t\t\t\t\tEMIT3(0x83, 0xc8, K); /* or imm8,%eax */\n\t\t\t\telse\n\t\t\t\t\tEMIT1_off32(0x0d, K);\t/* or imm32,%eax */\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_ALU_LSH_X: /* A <<= X; */\n\t\t\t\tseen |= SEEN_XREG;\n\t\t\t\tEMIT4(0x89, 0xd9, 0xd3, 0xe0);\t/* mov %ebx,%ecx; shl %cl,%eax */\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_ALU_LSH_K:\n\t\t\t\tif (K == 0)\n\t\t\t\t\tbreak;\n\t\t\t\telse if (K == 1)\n\t\t\t\t\tEMIT2(0xd1, 0xe0); /* shl %eax */\n\t\t\t\telse\n\t\t\t\t\tEMIT3(0xc1, 0xe0, K);\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_ALU_RSH_X: /* A >>= X; */\n\t\t\t\tseen |= SEEN_XREG;\n\t\t\t\tEMIT4(0x89, 0xd9, 0xd3, 0xe8);\t/* mov %ebx,%ecx; shr %cl,%eax */\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_ALU_RSH_K: /* A >>= K; */\n\t\t\t\tif (K == 0)\n\t\t\t\t\tbreak;\n\t\t\t\telse if (K == 1)\n\t\t\t\t\tEMIT2(0xd1, 0xe8); /* shr %eax */\n\t\t\t\telse\n\t\t\t\t\tEMIT3(0xc1, 0xe8, K);\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_ALU_NEG:\n\t\t\t\tEMIT2(0xf7, 0xd8);\t\t/* neg %eax */\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_RET_K:\n\t\t\t\tif (!K) {\n\t\t\t\t\tif (pc_ret0 == -1)\n\t\t\t\t\t\tpc_ret0 = i;\n\t\t\t\t\tCLEAR_A();\n\t\t\t\t} else {\n\t\t\t\t\tEMIT1_off32(0xb8, K);\t/* mov $imm32,%eax */\n\t\t\t\t}\n\t\t\t\t/* fallinto */\n\t\t\tcase BPF_S_RET_A:\n\t\t\t\tif (seen) {\n\t\t\t\t\tif (i != flen - 1) {\n\t\t\t\t\t\tEMIT_JMP(cleanup_addr - addrs[i]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tif (seen & SEEN_XREG)\n\t\t\t\t\t\tEMIT4(0x48, 0x8b, 0x5d, 0xf8); /* mov -8(%rbp),%rbx */\n\t\t\t\t\tEMIT1(0xc9);\t\t/* leaveq */\n\t\t\t\t}\n\t\t\t\tEMIT1(0xc3);\t\t/* ret */\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_MISC_TAX: /* X = A */\n\t\t\t\tseen |= SEEN_XREG;\n\t\t\t\tEMIT2(0x89, 0xc3);\t/* mov %eax,%ebx */\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_MISC_TXA: /* A = X */\n\t\t\t\tseen |= SEEN_XREG;\n\t\t\t\tEMIT2(0x89, 0xd8);\t/* mov %ebx,%eax */\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_LD_IMM: /* A = K */\n\t\t\t\tif (!K)\n\t\t\t\t\tCLEAR_A();\n\t\t\t\telse\n\t\t\t\t\tEMIT1_off32(0xb8, K); /* mov $imm32,%eax */\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_LDX_IMM: /* X = K */\n\t\t\t\tseen |= SEEN_XREG;\n\t\t\t\tif (!K)\n\t\t\t\t\tCLEAR_X();\n\t\t\t\telse\n\t\t\t\t\tEMIT1_off32(0xbb, K); /* mov $imm32,%ebx */\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_LD_MEM: /* A = mem[K] : mov off8(%rbp),%eax */\n\t\t\t\tseen |= SEEN_MEM;\n\t\t\t\tEMIT3(0x8b, 0x45, 0xf0 - K*4);\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_LDX_MEM: /* X = mem[K] : mov off8(%rbp),%ebx */\n\t\t\t\tseen |= SEEN_XREG | SEEN_MEM;\n\t\t\t\tEMIT3(0x8b, 0x5d, 0xf0 - K*4);\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_ST: /* mem[K] = A : mov %eax,off8(%rbp) */\n\t\t\t\tseen |= SEEN_MEM;\n\t\t\t\tEMIT3(0x89, 0x45, 0xf0 - K*4);\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_STX: /* mem[K] = X : mov %ebx,off8(%rbp) */\n\t\t\t\tseen |= SEEN_XREG | SEEN_MEM;\n\t\t\t\tEMIT3(0x89, 0x5d, 0xf0 - K*4);\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_LD_W_LEN: /*\tA = skb->len; */\n\t\t\t\tBUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, len) != 4);\n\t\t\t\tif (is_imm8(offsetof(struct sk_buff, len)))\n\t\t\t\t\t/* mov off8(%rdi),%eax */\n\t\t\t\t\tEMIT3(0x8b, 0x47, offsetof(struct sk_buff, len));\n\t\t\t\telse {\n\t\t\t\t\tEMIT2(0x8b, 0x87);\n\t\t\t\t\tEMIT(offsetof(struct sk_buff, len), 4);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_LDX_W_LEN: /* X = skb->len; */\n\t\t\t\tseen |= SEEN_XREG;\n\t\t\t\tif (is_imm8(offsetof(struct sk_buff, len)))\n\t\t\t\t\t/* mov off8(%rdi),%ebx */\n\t\t\t\t\tEMIT3(0x8b, 0x5f, offsetof(struct sk_buff, len));\n\t\t\t\telse {\n\t\t\t\t\tEMIT2(0x8b, 0x9f);\n\t\t\t\t\tEMIT(offsetof(struct sk_buff, len), 4);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_ANC_PROTOCOL: /* A = ntohs(skb->protocol); */\n\t\t\t\tBUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, protocol) != 2);\n\t\t\t\tif (is_imm8(offsetof(struct sk_buff, protocol))) {\n\t\t\t\t\t/* movzwl off8(%rdi),%eax */\n\t\t\t\t\tEMIT4(0x0f, 0xb7, 0x47, offsetof(struct sk_buff, protocol));\n\t\t\t\t} else {\n\t\t\t\t\tEMIT3(0x0f, 0xb7, 0x87); /* movzwl off32(%rdi),%eax */\n\t\t\t\t\tEMIT(offsetof(struct sk_buff, protocol), 4);\n\t\t\t\t}\n\t\t\t\tEMIT2(0x86, 0xc4); /* ntohs() : xchg %al,%ah */\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_ANC_IFINDEX:\n\t\t\t\tif (is_imm8(offsetof(struct sk_buff, dev))) {\n\t\t\t\t\t/* movq off8(%rdi),%rax */\n\t\t\t\t\tEMIT4(0x48, 0x8b, 0x47, offsetof(struct sk_buff, dev));\n\t\t\t\t} else {\n\t\t\t\t\tEMIT3(0x48, 0x8b, 0x87); /* movq off32(%rdi),%rax */\n\t\t\t\t\tEMIT(offsetof(struct sk_buff, dev), 4);\n\t\t\t\t}\n\t\t\t\tEMIT3(0x48, 0x85, 0xc0);\t/* test %rax,%rax */\n\t\t\t\tEMIT_COND_JMP(X86_JE, cleanup_addr - (addrs[i] - 6));\n\t\t\t\tBUILD_BUG_ON(FIELD_SIZEOF(struct net_device, ifindex) != 4);\n\t\t\t\tEMIT2(0x8b, 0x80);\t/* mov off32(%rax),%eax */\n\t\t\t\tEMIT(offsetof(struct net_device, ifindex), 4);\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_ANC_MARK:\n\t\t\t\tBUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, mark) != 4);\n\t\t\t\tif (is_imm8(offsetof(struct sk_buff, mark))) {\n\t\t\t\t\t/* mov off8(%rdi),%eax */\n\t\t\t\t\tEMIT3(0x8b, 0x47, offsetof(struct sk_buff, mark));\n\t\t\t\t} else {\n\t\t\t\t\tEMIT2(0x8b, 0x87);\n\t\t\t\t\tEMIT(offsetof(struct sk_buff, mark), 4);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_ANC_RXHASH:\n\t\t\t\tBUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, rxhash) != 4);\n\t\t\t\tif (is_imm8(offsetof(struct sk_buff, rxhash))) {\n\t\t\t\t\t/* mov off8(%rdi),%eax */\n\t\t\t\t\tEMIT3(0x8b, 0x47, offsetof(struct sk_buff, rxhash));\n\t\t\t\t} else {\n\t\t\t\t\tEMIT2(0x8b, 0x87);\n\t\t\t\t\tEMIT(offsetof(struct sk_buff, rxhash), 4);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_ANC_QUEUE:\n\t\t\t\tBUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, queue_mapping) != 2);\n\t\t\t\tif (is_imm8(offsetof(struct sk_buff, queue_mapping))) {\n\t\t\t\t\t/* movzwl off8(%rdi),%eax */\n\t\t\t\t\tEMIT4(0x0f, 0xb7, 0x47, offsetof(struct sk_buff, queue_mapping));\n\t\t\t\t} else {\n\t\t\t\t\tEMIT3(0x0f, 0xb7, 0x87); /* movzwl off32(%rdi),%eax */\n\t\t\t\t\tEMIT(offsetof(struct sk_buff, queue_mapping), 4);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_ANC_CPU:\n#ifdef CONFIG_SMP\n\t\t\t\tEMIT4(0x65, 0x8b, 0x04, 0x25); /* mov %gs:off32,%eax */\n\t\t\t\tEMIT((u32)(unsigned long)&cpu_number, 4); /* A = smp_processor_id(); */\n#else\n\t\t\t\tCLEAR_A();\n#endif\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_LD_W_ABS:\n\t\t\t\tfunc = sk_load_word;\ncommon_load:\t\t\tseen |= SEEN_DATAREF;\n\t\t\t\tif ((int)K < 0)\n\t\t\t\t\tgoto out;\n\t\t\t\tt_offset = func - (image + addrs[i]);\n\t\t\t\tEMIT1_off32(0xbe, K); /* mov imm32,%esi */\n\t\t\t\tEMIT1_off32(0xe8, t_offset); /* call */\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_LD_H_ABS:\n\t\t\t\tfunc = sk_load_half;\n\t\t\t\tgoto common_load;\n\t\t\tcase BPF_S_LD_B_ABS:\n\t\t\t\tfunc = sk_load_byte;\n\t\t\t\tgoto common_load;\n\t\t\tcase BPF_S_LDX_B_MSH:\n\t\t\t\tif ((int)K < 0) {\n\t\t\t\t\tif (pc_ret0 != -1) {\n\t\t\t\t\t\tEMIT_JMP(addrs[pc_ret0] - addrs[i]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tCLEAR_A();\n\t\t\t\t\tEMIT_JMP(cleanup_addr - addrs[i]);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tseen |= SEEN_DATAREF | SEEN_XREG;\n\t\t\t\tt_offset = sk_load_byte_msh - (image + addrs[i]);\n\t\t\t\tEMIT1_off32(0xbe, K);\t/* mov imm32,%esi */\n\t\t\t\tEMIT1_off32(0xe8, t_offset); /* call sk_load_byte_msh */\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_LD_W_IND:\n\t\t\t\tfunc = sk_load_word_ind;\ncommon_load_ind:\t\tseen |= SEEN_DATAREF | SEEN_XREG;\n\t\t\t\tt_offset = func - (image + addrs[i]);\n\t\t\t\tEMIT1_off32(0xbe, K);\t/* mov imm32,%esi */\n\t\t\t\tEMIT1_off32(0xe8, t_offset);\t/* call sk_load_xxx_ind */\n\t\t\t\tbreak;\n\t\t\tcase BPF_S_LD_H_IND:\n\t\t\t\tfunc = sk_load_half_ind;\n\t\t\t\tgoto common_load_ind;\n\t\t\tcase BPF_S_LD_B_IND:\n\t\t\t\tfunc = sk_load_byte_ind;\n\t\t\t\tgoto common_load_ind;\n\t\t\tcase BPF_S_JMP_JA:\n\t\t\t\tt_offset = addrs[i + K] - addrs[i];\n\t\t\t\tEMIT_JMP(t_offset);\n\t\t\t\tbreak;\n\t\t\tCOND_SEL(BPF_S_JMP_JGT_K, X86_JA, X86_JBE);\n\t\t\tCOND_SEL(BPF_S_JMP_JGE_K, X86_JAE, X86_JB);\n\t\t\tCOND_SEL(BPF_S_JMP_JEQ_K, X86_JE, X86_JNE);\n\t\t\tCOND_SEL(BPF_S_JMP_JSET_K,X86_JNE, X86_JE);\n\t\t\tCOND_SEL(BPF_S_JMP_JGT_X, X86_JA, X86_JBE);\n\t\t\tCOND_SEL(BPF_S_JMP_JGE_X, X86_JAE, X86_JB);\n\t\t\tCOND_SEL(BPF_S_JMP_JEQ_X, X86_JE, X86_JNE);\n\t\t\tCOND_SEL(BPF_S_JMP_JSET_X,X86_JNE, X86_JE);\n\ncond_branch:\t\t\tf_offset = addrs[i + filter[i].jf] - addrs[i];\n\t\t\t\tt_offset = addrs[i + filter[i].jt] - addrs[i];\n\n\t\t\t\t/* same targets, can avoid doing the test :) */\n\t\t\t\tif (filter[i].jt == filter[i].jf) {\n\t\t\t\t\tEMIT_JMP(t_offset);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tswitch (filter[i].code) {\n\t\t\t\tcase BPF_S_JMP_JGT_X:\n\t\t\t\tcase BPF_S_JMP_JGE_X:\n\t\t\t\tcase BPF_S_JMP_JEQ_X:\n\t\t\t\t\tseen |= SEEN_XREG;\n\t\t\t\t\tEMIT2(0x39, 0xd8); /* cmp %ebx,%eax */\n\t\t\t\t\tbreak;\n\t\t\t\tcase BPF_S_JMP_JSET_X:\n\t\t\t\t\tseen |= SEEN_XREG;\n\t\t\t\t\tEMIT2(0x85, 0xd8); /* test %ebx,%eax */\n\t\t\t\t\tbreak;\n\t\t\t\tcase BPF_S_JMP_JEQ_K:\n\t\t\t\t\tif (K == 0) {\n\t\t\t\t\t\tEMIT2(0x85, 0xc0); /* test %eax,%eax */\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\tcase BPF_S_JMP_JGT_K:\n\t\t\t\tcase BPF_S_JMP_JGE_K:\n\t\t\t\t\tif (K <= 127)\n\t\t\t\t\t\tEMIT3(0x83, 0xf8, K); /* cmp imm8,%eax */\n\t\t\t\t\telse\n\t\t\t\t\t\tEMIT1_off32(0x3d, K); /* cmp imm32,%eax */\n\t\t\t\t\tbreak;\n\t\t\t\tcase BPF_S_JMP_JSET_K:\n\t\t\t\t\tif (K <= 0xFF)\n\t\t\t\t\t\tEMIT2(0xa8, K); /* test imm8,%al */\n\t\t\t\t\telse if (!(K & 0xFFFF00FF))\n\t\t\t\t\t\tEMIT3(0xf6, 0xc4, K >> 8); /* test imm8,%ah */\n\t\t\t\t\telse if (K <= 0xFFFF) {\n\t\t\t\t\t\tEMIT2(0x66, 0xa9); /* test imm16,%ax */\n\t\t\t\t\t\tEMIT(K, 2);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tEMIT1_off32(0xa9, K); /* test imm32,%eax */\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (filter[i].jt != 0) {\n\t\t\t\t\tif (filter[i].jf)\n\t\t\t\t\t\tt_offset += is_near(f_offset) ? 2 : 6;\n\t\t\t\t\tEMIT_COND_JMP(t_op, t_offset);\n\t\t\t\t\tif (filter[i].jf)\n\t\t\t\t\t\tEMIT_JMP(f_offset);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tEMIT_COND_JMP(f_op, f_offset);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\t/* hmm, too complex filter, give up with jit compiler */\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tilen = prog - temp;\n\t\t\tif (image) {\n\t\t\t\tif (unlikely(proglen + ilen > oldproglen)) {\n\t\t\t\t\tpr_err(\"bpb_jit_compile fatal error\\n\");\n\t\t\t\t\tkfree(addrs);\n\t\t\t\t\tmodule_free(NULL, image);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tmemcpy(image + proglen, temp, ilen);\n\t\t\t}\n\t\t\tproglen += ilen;\n\t\t\taddrs[i] = proglen;\n\t\t\tprog = temp;\n\t\t}\n\t\t/* last bpf instruction is always a RET :\n\t\t * use it to give the cleanup instruction(s) addr\n\t\t */\n\t\tcleanup_addr = proglen - 1; /* ret */\n\t\tif (seen)\n\t\t\tcleanup_addr -= 1; /* leaveq */\n\t\tif (seen & SEEN_XREG)\n\t\t\tcleanup_addr -= 4; /* mov -8(%rbp),%rbx */\n\n\t\tif (image) {\n\t\t\tWARN_ON(proglen != oldproglen);\n\t\t\tbreak;\n\t\t}\n\t\tif (proglen == oldproglen) {\n\t\t\timage = module_alloc(max_t(unsigned int,\n\t\t\t\t\t\t proglen,\n\t\t\t\t\t\t sizeof(struct work_struct)));\n\t\t\tif (!image)\n\t\t\t\tgoto out;\n\t\t}\n\t\toldproglen = proglen;\n\t}\n\tif (bpf_jit_enable > 1)\n\t\tpr_err(\"flen=%d proglen=%u pass=%d image=%p\\n\",\n\t\t flen, proglen, pass, image);\n\n\tif (image) {\n\t\tif (bpf_jit_enable > 1)\n\t\t\tprint_hex_dump(KERN_ERR, \"JIT code: \", DUMP_PREFIX_ADDRESS,\n\t\t\t\t 16, 1, image, proglen, false);\n\n\t\tbpf_flush_icache(image, image + proglen);\n\n\t\tfp->bpf_func = (void *)image;\n\t}\nout:\n\tkfree(addrs);\n\treturn;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'net: bpf_jit: fix an off-one bug in x86_64 cond jump target\n\nx86 jump instruction size is 2 or 5 bytes (near/long jump), not 2 or 6\nbytes.\n\nIn case a conditional jump is followed by a long jump, conditional jump\ntarget is one byte past the start of target instruction.\n\nSigned-off-by: Markus K\u00f6tter \nSigned-off-by: Eric Dumazet \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus EvalGatherNd(TfLiteContext* context, const TfLiteTensor* params,\n const TfLiteTensor* indices, TfLiteTensor* output) {\n switch (params->type) {\n case kTfLiteFloat32:\n return GatherNd(params, indices, output);\n case kTfLiteUInt8:\n return GatherNd(params, indices, output);\n case kTfLiteInt8:\n return GatherNd(params, indices, output);\n case kTfLiteInt16:\n return GatherNd(params, indices, output);\n case kTfLiteInt32:\n return GatherNd(params, indices, output);\n case kTfLiteInt64:\n return GatherNd(params, indices, output);\n case kTfLiteString:\n return GatherNdString(params, indices, output);\n default:\n context->ReportError(context,\n \"Params type '%s' are not supported by gather_nd.\",\n TfLiteTypeGetName(params->type));\n return kTfLiteError;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Prevent heap OOB read in TFLite's `gather_nd.cc`.\n\nPassing negative indices is illegal but there was a missing check so that resulted in OOB accesses.\n\nPiperOrigin-RevId: 387208551\nChange-Id: I6b7a8a62d3e7c13a16d81619e5bc23ae2cdbc7fd'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int mincore_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end,\n\t\t\tstruct mm_walk *walk)\n{\n\tspinlock_t *ptl;\n\tstruct vm_area_struct *vma = walk->vma;\n\tpte_t *ptep;\n\tunsigned char *vec = walk->private;\n\tint nr = (end - addr) >> PAGE_SHIFT;\n\n\tptl = pmd_trans_huge_lock(pmd, vma);\n\tif (ptl) {\n\t\tmemset(vec, 1, nr);\n\t\tspin_unlock(ptl);\n\t\tgoto out;\n\t}\n\n\tif (pmd_trans_unstable(pmd)) {\n\t\t__mincore_unmapped_range(addr, end, vma, vec);\n\t\tgoto out;\n\t}\n\n\tptep = pte_offset_map_lock(walk->mm, pmd, addr, &ptl);\n\tfor (; addr != end; ptep++, addr += PAGE_SIZE) {\n\t\tpte_t pte = *ptep;\n\n\t\tif (pte_none(pte))\n\t\t\t__mincore_unmapped_range(addr, addr + PAGE_SIZE,\n\t\t\t\t\t\t vma, vec);\n\t\telse if (pte_present(pte))\n\t\t\t*vec = 1;\n\t\telse { /* pte is a swap entry */\n\t\t\tswp_entry_t entry = pte_to_swp_entry(pte);\n\n\t\t\tif (non_swap_entry(entry)) {\n\t\t\t\t/*\n\t\t\t\t * migration or hwpoison entries are always\n\t\t\t\t * uptodate\n\t\t\t\t */\n\t\t\t\t*vec = 1;\n\t\t\t} else {\n#ifdef CONFIG_SWAP\n\t\t\t\t*vec = mincore_page(swap_address_space(entry),\n\t\t\t\t\t\t swp_offset(entry));\n#else\n\t\t\t\tWARN_ON(1);\n\t\t\t\t*vec = 1;\n#endif\n\t\t\t}\n\t\t}\n\t\tvec++;\n\t}\n\tpte_unmap_unlock(ptep - 1, ptl);\nout:\n\twalk->private += nr;\n\tcond_resched();\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-319'], 'message': 'Change mincore() to count \"mapped\" pages rather than \"cached\" pages\n\nThe semantics of what \"in core\" means for the mincore() system call are\nsomewhat unclear, but Linux has always (since 2.3.52, which is when\nmincore() was initially done) treated it as \"page is available in page\ncache\" rather than \"page is mapped in the mapping\".\n\nThe problem with that traditional semantic is that it exposes a lot of\nsystem cache state that it really probably shouldn't, and that users\nshouldn't really even care about.\n\nSo let's try to avoid that information leak by simply changing the\nsemantics to be that mincore() counts actual mapped pages, not pages\nthat might be cheaply mapped if they were faulted (note the \"might be\"\npart of the old semantics: being in the cache doesn't actually guarantee\nthat you can access them without IO anyway, since things like network\nfilesystems may have to revalidate the cache before use).\n\nIn many ways the old semantics were somewhat insane even aside from the\ninformation leak issue. From the very beginning (and that beginning is\na long time ago: 2.3.52 was released in March 2000, I think), the code\nhad a comment saying\n\n Later we can get more picky about what \"in core\" means precisely.\n\nand this is that \"later\". Admittedly it is much later than is really\ncomfortable.\n\nNOTE! This is a real semantic change, and it is for example known to\nchange the output of \"fincore\", since that program literally does a\nmmmap without populating it, and then doing \"mincore()\" on that mapping\nthat doesn't actually have any pages in it.\n\nI'm hoping that nobody actually has any workflow that cares, and the\ninfo leak is real.\n\nWe may have to do something different if it turns out that people have\nvalid reasons to want the old semantics, and if we can limit the\ninformation leak sanely.\n\nCc: Kevin Easton \nCc: Jiri Kosina \nCc: Masatake YAMATO \nCc: Andrew Morton \nCc: Greg KH \nCc: Peter Zijlstra \nCc: Michal Hocko \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void pjsua_init_tpselector(pjsua_transport_id tp_id,\n\t\t\t pjsip_tpselector *sel)\n{\n pjsua_transport_data *tpdata;\n unsigned flag;\n\n pj_bzero(sel, sizeof(*sel));\n if (tp_id == PJSUA_INVALID_ID)\n\treturn;\n\n pj_assert(tp_id >= 0 && tp_id < (int)PJ_ARRAY_SIZE(pjsua_var.tpdata));\n tpdata = &pjsua_var.tpdata[tp_id];\n\n flag = pjsip_transport_get_flag_from_type(tpdata->type);\n\n if (flag & PJSIP_TRANSPORT_DATAGRAM) {\n\tsel->type = PJSIP_TPSELECTOR_TRANSPORT;\n\tsel->u.transport = tpdata->data.tp;\n } else {\n\tsel->type = PJSIP_TPSELECTOR_LISTENER;\n\tsel->u.listener = tpdata->data.factory;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'Use PJ_ASSERT_RETURN() on pjsip_auth_create_digest() and pjsua_init_tpselector() (#3009)\n\n* Use PJ_ASSERT_RETURN on pjsip_auth_create_digest\r\n\r\n* Use PJ_ASSERT_RETURN on pjsua_init_tpselector()\r\n\r\n* Fix incorrect check.\r\n\r\n* Add return value to pjsip_auth_create_digest() and pjsip_auth_create_digestSHA256()\r\n\r\n* Modification based on comments.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: rsa_oaep_sha256_decrypt(const struct rsa_private_key *key,\n\t size_t label_length, const uint8_t *label,\n\t size_t *length, uint8_t *message,\n\t const mpz_t gibberish)\n{\n mpz_t m;\n int res;\n struct sha256_ctx ctx;\n\n mpz_init(m);\n rsa_compute_root(key, m, gibberish);\n\n res = pkcs1_oaep_decrypt (key->size, m, SHA256_DIGEST_SIZE,\n &ctx, &nettle_sha256, (nettle_hash_init_func*)&sha256_init, (nettle_hash_update_func*)&sha256_update, (nettle_hash_digest_func*)&sha256_digest,\n label_length, label, length, message);\n mpz_clear(m);\n return res;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'Fix rsa oaep key length check before decryption'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: CotpConnection_readToTpktBuffer(CotpConnection* self)\n{\n uint8_t* buffer = self->readBuffer->buffer;\n int bufferSize = self->readBuffer->maxSize;\n int bufPos = self->readBuffer->size;\n\n assert (bufferSize > 4);\n\n int readBytes;\n\n if (bufPos < 4) {\n\n readBytes = readFromSocket(self, buffer + bufPos, 4 - bufPos);\n\n if (readBytes < 0)\n goto exit_closed;\n\n if (DEBUG_COTP) {\n if (readBytes > 0)\n printf(\"TPKT: read %i bytes from socket\\n\", readBytes);\n }\n\n bufPos += readBytes;\n\n if (bufPos == 4) {\n if ((buffer[0] == 3) && (buffer[1] == 0)) {\n self->packetSize = (buffer[2] * 0x100) + buffer[3];\n\n if (DEBUG_COTP)\n printf(\"TPKT: header complete (msg size = %i)\\n\", self->packetSize);\n\n if (self->packetSize > bufferSize) {\n if (DEBUG_COTP) printf(\"TPKT: packet too large\\n\");\n goto exit_error;\n }\n }\n else {\n if (DEBUG_COTP) printf(\"TPKT: failed to decode TPKT header.\\n\");\n goto exit_error;\n }\n }\n else\n goto exit_waiting;\n }\n\n readBytes = readFromSocket(self, buffer + bufPos, self->packetSize - bufPos);\n\n if (readBytes < 0)\n goto exit_closed;\n\n bufPos += readBytes;\n\n if (bufPos < self->packetSize)\n goto exit_waiting;\n\n if (DEBUG_COTP) printf(\"TPKT: message complete (size = %i)\\n\", self->packetSize);\n\n self->readBuffer->size = bufPos;\n return TPKT_PACKET_COMPLETE;\n\nexit_closed:\n if (DEBUG_COTP) printf(\"TPKT: socket closed or socket error\\n\");\n return TPKT_ERROR;\n\nexit_error:\n if (DEBUG_COTP) printf(\"TPKT: Error parsing message\\n\");\n return TPKT_ERROR;\n\nexit_waiting:\n\n if (DEBUG_COTP)\n if (bufPos != 0)\n printf(\"TPKT: waiting (read %i of %i)\\n\", bufPos, self->packetSize);\n\n self->readBuffer->size = bufPos;\n return TPKT_WAITING;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-122'], 'message': '- COTP: fixed possible heap buffer overflow when handling message with invalid (zero) value in length field (#250)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void GTextFieldSave(GTextField *gt,int utf8) {\n unichar_t *ret;\n char *cret;\n FILE *file;\n unichar_t *pt;\n\n if ( _ggadget_use_gettext ) {\n\tchar *temp = GWidgetOpenFile8(_(\"Save\"),NULL,\"*.{txt,py}\",NULL,NULL);\n\tret = utf82u_copy(temp);\n\tfree(temp);\n } else\n\tret = GWidgetSaveAsFile(GStringGetResource(_STR_Save,NULL),NULL,\n\t\ttxt,NULL,NULL);\n\n if ( ret==NULL )\nreturn;\n cret = u2def_copy(ret);\n free(ret);\n file = fopen(cret,\"w\");\n if ( file==NULL ) {\n\tif ( _ggadget_use_gettext )\n\t GWidgetError8(_(\"Could not open file\"), _(\"Could not open %.100s\"),cret);\n\telse\n\t GWidgetError(errort,error,cret);\n\tfree(cret);\nreturn;\n }\n free(cret);\n\n if ( utf8 ) {\n\tputc(0xef,file);\t\t/* Zero width something or other. Marks this as unicode, utf8 */\n\tputc(0xbb,file);\n\tputc(0xbf,file);\n\tfor ( pt = gt->text ; *pt; ++pt ) {\n\t if ( *pt<0x80 )\n\t\tputc(*pt,file);\n\t else if ( *pt<0x800 ) {\n\t\tputc(0xc0 | (*pt>>6), file);\n\t\tputc(0x80 | (*pt&0x3f), file);\n\t } else if ( *pt>=0xd800 && *pt<0xdc00 && pt[1]>=0xdc00 && pt[1]<0xe000 ) {\n\t\tint u = ((*pt>>6)&0xf)+1, y = ((*pt&3)<<4) | ((pt[1]>>6)&0xf);\n\t\tputc( 0xf0 | (u>>2),file );\n\t\tputc( 0x80 | ((u&3)<<4) | ((*pt>>2)&0xf),file );\n\t\tputc( 0x80 | y,file );\n\t\tputc( 0x80 | (pt[1]&0x3f),file );\n\t } else {\n\t\tputc( 0xe0 | (*pt>>12),file );\n\t\tputc( 0x80 | ((*pt>>6)&0x3f),file );\n\t\tputc( 0x80 | (*pt&0x3f),file );\n\t }\n\t}\n } else {\n\tputc(0xfeff>>8,file);\t\t/* Zero width something or other. Marks this as unicode */\n\tputc(0xfeff&0xff,file);\n\tfor ( pt = gt->text ; *pt; ++pt ) {\n\t putc(*pt>>8,file);\n\t putc(*pt&0xff,file);\n\t}\n }\n fclose(file);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Warn users before discarding their unsaved scripts (#3852)\n\n* Warn users before discarding their unsaved scripts\r\n\r\nThis closes #3846.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void operator()(OpKernelContext* ctx, bool use_cudnn, bool cudnn_use_autotune,\n const Tensor& input, const Tensor& filter, int row_dilation,\n int col_dilation, int row_stride, int col_stride,\n const Padding& padding,\n const std::vector& explicit_paddings, Tensor* output,\n TensorFormat data_format) {\n if (data_format != FORMAT_NHWC) {\n ctx->SetStatus(\n errors::Unimplemented(\"The Conv2D op currently only supports the \"\n \"NHWC tensor format for integer types. \"\n \"The op was given the format: \",\n ToString(data_format)));\n return;\n }\n const int64 in_depth = GetTensorDim(input, data_format, 'C');\n OP_REQUIRES(ctx, in_depth == filter.dim_size(2),\n errors::Unimplemented(\n \"The Conv2D op currently does not support grouped \"\n \"convolutions for integer types. A grouped convolution was \"\n \"attempted to be run because the input depth of \",\n in_depth, \" does not match the filter input depth of \",\n filter.dim_size(2)));\n\n for (int64 explicit_padding : explicit_paddings) {\n if (!FastBoundsCheck(explicit_padding, std::numeric_limits::max())) {\n ctx->SetStatus(errors::InvalidArgument(\"filter too large\"));\n return;\n }\n }\n LaunchGeneric()(\n ctx, input, filter, row_stride, col_stride, row_dilation, col_dilation,\n padding, explicit_paddings, output, data_format);\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-369'], 'message': 'Fix one more FPE.\n\nPiperOrigin-RevId: 369346568\nChange-Id: I840fd575962adc879713a4c9cc59e6da3331caa7'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static bool parseOperands(char* str, ArmOp *op) {\n\tchar *t = strdup (str);\n\tint operand = 0;\n\tchar *token = t;\n\tchar *x;\n\tint imm_count = 0;\n\tint mem_opt = 0;\n\tif (!token) {\n\t\treturn false;\n\t}\n\n\twhile (token) {\n\t\tchar *next = strchr (token, ',');\n\t\tif (next) {\n\t\t\t*next++ = 0;\n\t\t}\n\t\twhile (token[0] == ' ') {\n\t\t\ttoken++;\n\t\t}\n\t\tif (operand >= MAX_OPERANDS) {\n\t\t\teprintf (\"Too many operands\\n\");\n\t\t\treturn false;\n\t\t}\n\t\top->operands[operand].type = ARM_NOTYPE;\n\t\top->operands[operand].reg_type = ARM_UNDEFINED;\n\t\top->operands[operand].shift = ARM_NO_SHIFT;\n\n\t\twhile (token[0] == ' ' || token[0] == '[' || token[0] == ']') {\n\t\t\ttoken ++;\n\t\t}\n\n\t\tif (!strncmp (token, \"lsl\", 3)) {\n\t\t\top->operands[operand].shift = ARM_LSL;\n\t\t} else if (!strncmp (token, \"lsr\", 3)) {\n\t\t\top->operands[operand].shift = ARM_LSR;\n\t\t} else if (!strncmp (token, \"asr\", 3)) {\n\t\t\top->operands[operand].shift = ARM_ASR;\n\t\t}\n\t\tif (op->operands[operand].shift != ARM_NO_SHIFT) {\n\t\t\top->operands_count ++;\n\t\t\top->operands[operand].shift_amount = r_num_math (NULL, token + 4);\n\t\t\tif (op->operands[operand].shift_amount > 63) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\toperand ++;\n\t\t\ttoken = next;\n\t\t\tcontinue;\n\t\t}\n\n\t\tswitch (token[0]) {\n\t\tcase 'x':\n\t\t\tx = strchr (token, ',');\n\t\t\tif (x) {\n\t\t\t\tx[0] = '\\0';\n\t\t\t}\n\t\t\top->operands_count ++;\n\t\t\top->operands[operand].type = ARM_GPR;\n\t\t\top->operands[operand].reg_type = ARM_REG64;\n\t\t\top->operands[operand].reg = r_num_math (NULL, token + 1);\n\t\t\tif (op->operands[operand].reg > 31) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'w':\n\t\t\top->operands_count ++;\n\t\t\top->operands[operand].type = ARM_GPR;\n\t\t\top->operands[operand].reg_type = ARM_REG32;\n\t\t\top->operands[operand].reg = r_num_math (NULL, token + 1);\n\t\t\tif (op->operands[operand].reg > 31) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\top->operands_count ++;\n\t\t\top->operands[operand].type = ARM_FP;\n\t\t\top->operands[operand].reg = r_num_math (NULL, token + 1);\n\t\t\tbreak;\n\t\tcase 's':\n\t\tcase 'S':\n\t\t\tif (token[1] == 'P' || token [1] == 'p') {\n\t\t\t\tint i;\n\t\t\t\tfor (i = 0; msr_const[i].name; i++) {\n\t\t\t\t\tif (!r_str_ncasecmp (token, msr_const[i].name, strlen (msr_const[i].name))) {\n\t\t\t\t\t\top->operands[operand].sp_val = msr_const[i].val;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\top->operands_count ++;\n\t\t\t\top->operands[operand].type = ARM_GPR;\n\t\t\t\top->operands[operand].reg_type = ARM_SP | ARM_REG64;\n\t\t\t\top->operands[operand].reg = 31;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tmem_opt = get_mem_option (token);\n\t\t\tif (mem_opt != -1) {\n\t\t\t\top->operands_count ++;\n\t\t\t\top->operands[operand].type = ARM_MEM_OPT;\n\t\t\t\top->operands[operand].mem_option = mem_opt;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'L':\n\t\tcase 'l':\n\t\tcase 'I':\n\t\tcase 'i':\n\t\tcase 'N':\n\t\tcase 'n':\n\t\tcase 'O':\n\t\tcase 'o':\n\t\tcase 'p':\n\t\tcase 'P':\n\t\t\tmem_opt = get_mem_option (token);\n\t\t\tif (mem_opt != -1) {\n\t\t\t\top->operands_count ++;\n\t\t\t\top->operands[operand].type = ARM_MEM_OPT;\n\t\t\t\top->operands[operand].mem_option = mem_opt;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase '-':\n\t\t\top->operands[operand].sign = -1;\n\t\t\t// falthru\n\t\tdefault:\n\t\t\top->operands_count ++;\n\t\t\top->operands[operand].type = ARM_CONSTANT;\n\t\t\top->operands[operand].immediate = r_num_math (NULL, token);\n\t\t\timm_count++;\n\t\t\tbreak;\n\t\t}\n\t\ttoken = next;\n\n\t\toperand ++;\n\t\tif (operand > MAX_OPERANDS) {\n\t\t\tfree (t);\n\t\t\treturn false;\n\t\t}\n\t}\n\tfree (t);\n\treturn true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'Fix #12417/#12418 (arm assembler heap overflows)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void ff_jpeg2000_cleanup(Jpeg2000Component *comp, Jpeg2000CodingStyle *codsty)\n{\n int reslevelno, bandno, precno;\n for (reslevelno = 0;\n comp->reslevel && reslevelno < codsty->nreslevels;\n reslevelno++) {\n Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;\n\n for (bandno = 0; bandno < reslevel->nbands; bandno++) {\n Jpeg2000Band *band = reslevel->band + bandno;\n for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++) {\n Jpeg2000Prec *prec = band->prec + precno;\n av_freep(&prec->zerobits);\n av_freep(&prec->cblkincl);\n av_freep(&prec->cblk);\n }\n\n av_freep(&band->prec);\n }\n av_freep(&reslevel->band);\n }\n\n ff_dwt_destroy(&comp->dwt);\n av_freep(&comp->reslevel);\n av_freep(&comp->i_data);\n av_freep(&comp->f_data);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'jpeg2000: fix dereferencing invalid pointers\n\nFound-by: Laurent Butti \nSigned-off-by: Michael Niedermayer '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: next_state_val(CClassNode* cc, OnigCodePoint *vs, OnigCodePoint v,\n\t int* vs_israw, int v_israw,\n\t enum CCVALTYPE intype, enum CCVALTYPE* type,\n\t enum CCSTATE* state, ScanEnv* env)\n{\n int r;\n\n switch (*state) {\n case CCS_VALUE:\n if (*type == CCV_SB) {\n BITSET_SET_BIT(cc->bs, (int )(*vs));\n }\n else if (*type == CCV_CODE_POINT) {\n r = add_code_range(&(cc->mbuf), env, *vs, *vs);\n if (r < 0) return r;\n }\n break;\n\n case CCS_RANGE:\n if (intype == *type) {\n if (intype == CCV_SB) {\n if (*vs > 0xff || v > 0xff)\n return ONIGERR_INVALID_CODE_POINT_VALUE;\n\n if (*vs > v) {\n if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC))\n goto ccs_range_end;\n else\n return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS;\n }\n bitset_set_range(cc->bs, (int )*vs, (int )v);\n }\n else {\n r = add_code_range(&(cc->mbuf), env, *vs, v);\n if (r < 0) return r;\n }\n }\n else {\n#if 0\n if (intype == CCV_CODE_POINT && *type == CCV_SB) {\n#endif\n if (*vs > v) {\n if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC))\n goto ccs_range_end;\n else\n return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS;\n }\n bitset_set_range(cc->bs, (int )*vs, (int )(v < 0xff ? v : 0xff));\n r = add_code_range(&(cc->mbuf), env, (OnigCodePoint )*vs, v);\n if (r < 0) return r;\n#if 0\n }\n else\n return ONIGERR_MISMATCH_CODE_LENGTH_IN_CLASS_RANGE;\n#endif\n }\n ccs_range_end:\n *state = CCS_COMPLETE;\n break;\n\n case CCS_COMPLETE:\n case CCS_START:\n *state = CCS_VALUE;\n break;\n\n default:\n break;\n }\n\n *vs_israw = v_israw;\n *vs = v;\n *type = intype;\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'fix #55 : check too big code point value for single byte value in next_state_val()'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void rijndaelEncrypt(const u32 *rk, int nrounds, const u8 plaintext[16],\n u8 ciphertext[16])\n{\n u32 s0, s1, s2, s3, t0, t1, t2, t3;\n #ifndef FULL_UNROLL\n int r;\n #endif /* ?FULL_UNROLL */\n /*\n * map byte array block to cipher state\n * and add initial round key:\n */\n s0 = GETU32(plaintext ) ^ rk[0];\n s1 = GETU32(plaintext + 4) ^ rk[1];\n s2 = GETU32(plaintext + 8) ^ rk[2];\n s3 = GETU32(plaintext + 12) ^ rk[3];\n #ifdef FULL_UNROLL\n /* round 1: */\n t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[ 4];\n t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[ 5];\n t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[ 6];\n t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[ 7];\n /* round 2: */\n s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[ 8];\n s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[ 9];\n s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[10];\n s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[11];\n /* round 3: */\n t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[12];\n t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[13];\n t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[14];\n t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[15];\n /* round 4: */\n s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[16];\n s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[17];\n s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[18];\n s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[19];\n /* round 5: */\n t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[20];\n t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[21];\n t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[22];\n t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[23];\n /* round 6: */\n s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[24];\n s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[25];\n s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[26];\n s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[27];\n /* round 7: */\n t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[28];\n t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[29];\n t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[30];\n t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[31];\n /* round 8: */\n s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[32];\n s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[33];\n s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[34];\n s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[35];\n /* round 9: */\n t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[36];\n t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[37];\n t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[38];\n t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[39];\n if (nrounds > 10)\n {\n /* round 10: */\n s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[40];\n s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[41];\n s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[42];\n s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[43];\n /* round 11: */\n t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[44];\n t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[45];\n t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[46];\n t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[47];\n if (nrounds > 12)\n {\n /* round 12: */\n s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[48];\n s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[49];\n s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[50];\n s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[51];\n /* round 13: */\n t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[52];\n t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[53];\n t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[54];\n t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[55];\n }\n }\n rk += nrounds << 2;\n #else /* !FULL_UNROLL */\n /*\n * nrounds - 1 full rounds:\n */\n r = nrounds >> 1;\n for (;;)\n {\n t0 =\n Te0[(s0 >> 24) ] ^\n Te1[(s1 >> 16) & 0xff] ^\n Te2[(s2 >> 8) & 0xff] ^\n Te3[(s3 ) & 0xff] ^\n rk[4];\n t1 =\n Te0[(s1 >> 24) ] ^\n Te1[(s2 >> 16) & 0xff] ^\n Te2[(s3 >> 8) & 0xff] ^\n Te3[(s0 ) & 0xff] ^\n rk[5];\n t2 =\n Te0[(s2 >> 24) ] ^\n Te1[(s3 >> 16) & 0xff] ^\n Te2[(s0 >> 8) & 0xff] ^\n Te3[(s1 ) & 0xff] ^\n rk[6];\n t3 =\n Te0[(s3 >> 24) ] ^\n Te1[(s0 >> 16) & 0xff] ^\n Te2[(s1 >> 8) & 0xff] ^\n Te3[(s2 ) & 0xff] ^\n rk[7];\n rk += 8;\n if (--r == 0)\n break;\n s0 =\n Te0[(t0 >> 24) ] ^\n Te1[(t1 >> 16) & 0xff] ^\n Te2[(t2 >> 8) & 0xff] ^\n Te3[(t3 ) & 0xff] ^\n rk[0];\n s1 =\n Te0[(t1 >> 24) ] ^\n Te1[(t2 >> 16) & 0xff] ^\n Te2[(t3 >> 8) & 0xff] ^\n Te3[(t0 ) & 0xff] ^\n rk[1];\n s2 =\n Te0[(t2 >> 24) ] ^\n Te1[(t3 >> 16) & 0xff] ^\n Te2[(t0 >> 8) & 0xff] ^\n Te3[(t1 ) & 0xff] ^\n rk[2];\n s3 =\n Te0[(t3 >> 24) ] ^\n Te1[(t0 >> 16) & 0xff] ^\n Te2[(t1 >> 8) & 0xff] ^\n Te3[(t2 ) & 0xff] ^\n rk[3];\n }\n #endif /* ?FULL_UNROLL */\n /*\n * apply last round and\n * map cipher state to byte array block:\n */\n s0 =\n (Te4[(t0 >> 24) ] & 0xff000000) ^\n (Te4[(t1 >> 16) & 0xff] & 0x00ff0000) ^\n (Te4[(t2 >> 8) & 0xff] & 0x0000ff00) ^\n (Te4[(t3 ) & 0xff] & 0x000000ff) ^\n rk[0];\n PUTU32(ciphertext , s0);\n s1 =\n (Te4[(t1 >> 24) ] & 0xff000000) ^\n (Te4[(t2 >> 16) & 0xff] & 0x00ff0000) ^\n (Te4[(t3 >> 8) & 0xff] & 0x0000ff00) ^\n (Te4[(t0 ) & 0xff] & 0x000000ff) ^\n rk[1];\n PUTU32(ciphertext + 4, s1);\n s2 =\n (Te4[(t2 >> 24) ] & 0xff000000) ^\n (Te4[(t3 >> 16) & 0xff] & 0x00ff0000) ^\n (Te4[(t0 >> 8) & 0xff] & 0x0000ff00) ^\n (Te4[(t1 ) & 0xff] & 0x000000ff) ^\n rk[2];\n PUTU32(ciphertext + 8, s2);\n s3 =\n (Te4[(t3 >> 24) ] & 0xff000000) ^\n (Te4[(t0 >> 16) & 0xff] & 0x00ff0000) ^\n (Te4[(t1 >> 8) & 0xff] & 0x0000ff00) ^\n (Te4[(t2 ) & 0xff] & 0x000000ff) ^\n rk[3];\n PUTU32(ciphertext + 12, s3);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: JSON::encode_string(std::string const& str)\n{\n std::string result;\n size_t len = str.length();\n for (size_t i = 0; i < len; ++i)\n {\n unsigned char ch = static_cast(str.at(i));\n switch (ch)\n {\n case '\\\\':\n result += \"\\\\\\\\\";\n break;\n case '\\\"':\n result += \"\\\\\\\"\";\n break;\n case '\\b':\n result += \"\\\\b\";\n break;\n case '\\n':\n result += \"\\\\n\";\n break;\n case '\\r':\n result += \"\\\\r\";\n break;\n case '\\t':\n result += \"\\\\t\";\n break;\n default:\n if (ch < 32)\n {\n result += \"\\\\u\" + QUtil::int_to_string_base(ch, 16, 4);\n }\n else\n {\n result.append(1, ch);\n }\n }\n }\n return result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: QPDF_Stream::replaceFilterData(QPDFObjectHandle const& filter,\n\t\t\t QPDFObjectHandle const& decode_parms,\n\t\t\t size_t length)\n{\n this->stream_dict.replaceOrRemoveKey(\"/Filter\", filter);\n this->stream_dict.replaceOrRemoveKey(\"/DecodeParms\", decode_parms);\n if (length == 0)\n {\n QTC::TC(\"qpdf\", \"QPDF_Stream unknown stream length\");\n this->stream_dict.removeKey(\"/Length\");\n }\n else\n {\n this->stream_dict.replaceKey(\n \"/Length\", QPDFObjectHandle::newInteger(length));\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void do_under_overlay_for_page(\n QPDF& pdf,\n Options& o,\n UnderOverlay& uo,\n std::map >& pagenos,\n size_t page_idx,\n std::map& fo,\n std::vector& pages,\n QPDFPageObjectHelper& dest_page,\n bool before)\n{\n int pageno = 1 + page_idx;\n if (! pagenos.count(pageno))\n {\n return;\n }\n\n std::string content;\n int min_suffix = 1;\n QPDFObjectHandle resources = dest_page.getAttribute(\"/Resources\", true);\n for (std::vector::iterator iter = pagenos[pageno].begin();\n iter != pagenos[pageno].end(); ++iter)\n {\n int from_pageno = *iter;\n if (o.verbose)\n {\n std::cout << \" \" << uo.which << \" \" << from_pageno << std::endl;\n }\n if (0 == fo.count(from_pageno))\n {\n fo[from_pageno] =\n pdf.copyForeignObject(\n pages.at(from_pageno - 1).getFormXObjectForPage());\n }\n // If the same page is overlaid or underlaid multiple times,\n // we'll generate multiple names for it, but that's harmless\n // and also a pretty goofy case that's not worth coding\n // around.\n std::string name = resources.getUniqueResourceName(\"/Fx\", min_suffix);\n std::string new_content = dest_page.placeFormXObject(\n fo[from_pageno], name,\n dest_page.getTrimBox().getArrayAsRectangle());\n if (! new_content.empty())\n {\n resources.mergeResources(\n QPDFObjectHandle::parse(\"<< /XObject << >> >>\"));\n resources.getKey(\"/XObject\").replaceKey(name, fo[from_pageno]);\n ++min_suffix;\n content += new_content;\n }\n }\n if (! content.empty())\n {\n if (before)\n {\n dest_page.addPageContents(\n QPDFObjectHandle::newStream(&pdf, content), true);\n }\n else\n {\n dest_page.addPageContents(\n QPDFObjectHandle::newStream(&pdf, \"q\\n\"), true);\n dest_page.addPageContents(\n QPDFObjectHandle::newStream(&pdf, \"\\nQ\\n\" + content), false);\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: Pl_ASCIIHexDecoder::write(unsigned char* buf, size_t len)\n{\n if (this->eod)\n {\n\treturn;\n }\n for (size_t i = 0; i < len; ++i)\n {\n\tchar ch = toupper(buf[i]);\n\tswitch (ch)\n\t{\n\t case ' ':\n\t case '\\f':\n\t case '\\v':\n\t case '\\t':\n\t case '\\r':\n\t case '\\n':\n\t QTC::TC(\"libtests\", \"Pl_ASCIIHexDecoder ignore space\");\n\t // ignore whitespace\n\t break;\n\n\t case '>':\n\t this->eod = true;\n\t flush();\n\t break;\n\n\t default:\n\t if (((ch >= '0') && (ch <= '9')) ||\n\t\t((ch >= 'A') && (ch <= 'F')))\n\t {\n\t\tthis->inbuf[this->pos++] = ch;\n\t\tif (this->pos == 2)\n\t\t{\n\t\t flush();\n\t\t}\n\t }\n\t else\n\t {\n\t\tchar t[2];\n\t\tt[0] = ch;\n\t\tt[1] = 0;\n\t\tthrow std::runtime_error(\n\t\t std::string(\"character out of range\"\n\t\t\t\t\" during base Hex decode: \") + t);\n\t }\n\t break;\n\t}\n\tif (this->eod)\n\t{\n\t break;\n\t}\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: QPDF::checkHSharedObject(std::list& errors,\n\t\t\t std::list& warnings,\n\t\t\t std::vector const& pages,\n\t\t\t std::map& idx_to_obj)\n{\n // Implementation note 125 says shared object groups always\n // contain only one object. Implementation note 128 says that\n // Acrobat always nbits_nobjects to zero. Implementation note 130\n // says that Acrobat does not support more than one shared object\n // per group. These are all consistent.\n\n // Implementation note 129 states that MD5 signatures are not\n // implemented in Acrobat, so signature_present must always be\n // zero.\n\n // Implementation note 131 states that first_shared_obj and\n // first_shared_offset have meaningless values for single-page\n // files.\n\n // Empirically, Acrobat and pdlin generate incorrect values for\n // these whenever there are no shared objects not referenced by\n // the first page (i.e., nshared_total == nshared_first_page).\n\n HSharedObject& so = this->m->shared_object_hints;\n if (so.nshared_total < so.nshared_first_page)\n {\n\terrors.push_back(\"shared object hint table: ntotal < nfirst_page\");\n }\n else\n {\n\t// The first nshared_first_page objects are consecutive\n\t// objects starting with the first page object. The rest are\n\t// consecutive starting from the first_shared_obj object.\n\tint cur_object = pages.at(0).getObjectID();\n\tfor (int i = 0; i < so.nshared_total; ++i)\n\t{\n\t if (i == so.nshared_first_page)\n\t {\n\t\tQTC::TC(\"qpdf\", \"QPDF lin check shared past first page\");\n\t\tif (this->m->part8.empty())\n\t\t{\n\t\t errors.push_back(\n\t\t\t\"part 8 is empty but nshared_total > \"\n\t\t\t\"nshared_first_page\");\n\t\t}\n\t\telse\n\t\t{\n\t\t int obj = this->m->part8.at(0).getObjectID();\n\t\t if (obj != so.first_shared_obj)\n\t\t {\n\t\t\terrors.push_back(\n\t\t\t \"first shared object number mismatch: \"\n\t\t\t \"hint table = \" +\n\t\t\t QUtil::int_to_string(so.first_shared_obj) +\n\t\t\t \"; computed = \" +\n\t\t\t QUtil::int_to_string(obj));\n\t\t }\n\t\t}\n\n\t\tcur_object = so.first_shared_obj;\n\n\t\tQPDFObjGen og(cur_object, 0);\n\t\tif (this->m->xref_table.count(og) == 0)\n {\n stopOnError(\"unknown object in shared object hint table\");\n }\n\t\tint offset = getLinearizationOffset(og);\n\t\tint h_offset = adjusted_offset(so.first_shared_offset);\n\t\tif (offset != h_offset)\n\t\t{\n\t\t errors.push_back(\n\t\t\t\"first shared object offset mismatch: hint table = \" +\n\t\t\tQUtil::int_to_string(h_offset) + \"; computed = \" +\n\t\t\tQUtil::int_to_string(offset));\n\t\t}\n\t }\n\n\t idx_to_obj[i] = cur_object;\n\t HSharedObjectEntry& se = so.entries.at(i);\n\t int nobjects = se.nobjects_minus_one + 1;\n\t int length = lengthNextN(cur_object, nobjects, errors);\n\t int h_length = so.min_group_length + se.delta_group_length;\n\t if (length != h_length)\n\t {\n\t\terrors.push_back(\n\t\t \"shared object \" + QUtil::int_to_string(i) +\n\t\t \" length mismatch: hint table = \" +\n\t\t QUtil::int_to_string(h_length) + \"; computed = \" +\n\t\t QUtil::int_to_string(length));\n\t }\n\t cur_object += nobjects;\n\t}\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: write_vector_vector(BitWriter& w,\n\t\t int nitems1, std::vector& vec1, int T::*nitems2,\n\t\t int bits, std::vector T::*vec2)\n{\n // nitems1 times, write nitems2 (from the ith element of vec1) items\n // from the vec2 vector field of the ith item of vec1.\n for (int i1 = 0; i1 < nitems1; ++i1)\n {\n\tfor (int i2 = 0; i2 < vec1.at(i1).*nitems2; ++i2)\n\t{\n\t w.writeBits((vec1.at(i1).*vec2).at(i2), bits);\n\t}\n }\n w.flush();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: sph_enc16le(void *dst, unsigned val)\n{\n\t((unsigned char *)dst)[0] = val;\n\t((unsigned char *)dst)[1] = val >> 8;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: QUtil::hex_decode(std::string const& input)\n{\n std::string result;\n size_t pos = 0;\n for (std::string::const_iterator p = input.begin(); p != input.end(); ++p)\n {\n char ch = *p;\n bool skip = false;\n if ((*p >= 'A') && (*p <= 'F'))\n {\n ch -= 'A';\n ch += 10;\n }\n else if ((*p >= 'a') && (*p <= 'f'))\n {\n ch -= 'a';\n ch += 10;\n }\n else if ((*p >= '0') && (*p <= '9'))\n {\n ch -= '0';\n }\n else\n {\n skip = true;\n }\n if (! skip)\n {\n if (pos == 0)\n {\n result.push_back(ch << 4);\n pos = 1;\n }\n else\n {\n result[result.length()-1] += ch;\n pos = 0;\n }\n }\n }\n return result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void MD5::encodeString(char const* str)\n{\n unsigned int len = strlen(str);\n\n update(QUtil::unsigned_char_pointer(str), len);\n final();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void handle_page_specs(QPDF& pdf, Options& o)\n{\n // Parse all page specifications and translate them into lists of\n // actual pages.\n\n // Handle \".\" as a shortcut for the input file\n for (std::vector::iterator iter = o.page_specs.begin();\n iter != o.page_specs.end(); ++iter)\n {\n PageSpec& page_spec = *iter;\n if (page_spec.filename == \".\")\n {\n page_spec.filename = o.infilename;\n }\n }\n\n if (! o.keep_files_open_set)\n {\n // Count the number of distinct files to determine whether we\n // should keep files open or not. Rather than trying to code\n // some portable heuristic based on OS limits, just hard-code\n // this at a given number and allow users to override.\n std::set filenames;\n for (std::vector::iterator iter = o.page_specs.begin();\n iter != o.page_specs.end(); ++iter)\n {\n PageSpec& page_spec = *iter;\n filenames.insert(page_spec.filename);\n }\n if (filenames.size() > o.keep_files_open_threshold)\n {\n QTC::TC(\"qpdf\", \"qpdf disable keep files open\");\n if (o.verbose)\n {\n std::cout << whoami << \": selecting --keep-open-files=n\"\n << std::endl;\n }\n o.keep_files_open = false;\n }\n else\n {\n if (o.verbose)\n {\n std::cout << whoami << \": selecting --keep-open-files=y\"\n << std::endl;\n }\n o.keep_files_open = true;\n QTC::TC(\"qpdf\", \"qpdf don't disable keep files open\");\n }\n }\n\n // Create a QPDF object for each file that we may take pages from.\n std::vector > page_heap;\n std::map page_spec_qpdfs;\n std::map page_spec_cfis;\n page_spec_qpdfs[o.infilename] = &pdf;\n std::vector parsed_specs;\n std::map > copied_pages;\n for (std::vector::iterator iter = o.page_specs.begin();\n iter != o.page_specs.end(); ++iter)\n {\n PageSpec& page_spec = *iter;\n if (page_spec_qpdfs.count(page_spec.filename) == 0)\n {\n // Open the PDF file and store the QPDF object. Throw a\n // PointerHolder to the qpdf into a heap so that it\n // survives through copying to the output but gets cleaned up\n // automatically at the end. Do not canonicalize the file\n // name. Using two different paths to refer to the same\n // file is a document workaround for duplicating a page.\n // If you are using this an example of how to do this with\n // the API, you can just create two different QPDF objects\n // to the same underlying file with the same path to\n // achieve the same affect.\n char const* password = page_spec.password;\n if (o.encryption_file && (password == 0) &&\n (page_spec.filename == o.encryption_file))\n {\n QTC::TC(\"qpdf\", \"qpdf pages encryption password\");\n password = o.encryption_file_password;\n }\n if (o.verbose)\n {\n std::cout << whoami << \": processing \"\n << page_spec.filename << std::endl;\n }\n PointerHolder is;\n ClosedFileInputSource* cis = 0;\n if (! o.keep_files_open)\n {\n QTC::TC(\"qpdf\", \"qpdf keep files open n\");\n cis = new ClosedFileInputSource(page_spec.filename.c_str());\n is = cis;\n cis->stayOpen(true);\n }\n else\n {\n QTC::TC(\"qpdf\", \"qpdf keep files open y\");\n FileInputSource* fis = new FileInputSource();\n is = fis;\n fis->setFilename(page_spec.filename.c_str());\n }\n PointerHolder qpdf_ph = process_input_source(is, password, o);\n page_heap.push_back(qpdf_ph);\n page_spec_qpdfs[page_spec.filename] = qpdf_ph.getPointer();\n if (cis)\n {\n cis->stayOpen(false);\n page_spec_cfis[page_spec.filename] = cis;\n }\n }\n\n // Read original pages from the PDF, and parse the page range\n // associated with this occurrence of the file.\n parsed_specs.push_back(\n QPDFPageData(page_spec.filename,\n page_spec_qpdfs[page_spec.filename],\n page_spec.range));\n }\n\n if (! o.preserve_unreferenced_page_resources)\n {\n for (std::map::iterator iter =\n page_spec_qpdfs.begin();\n iter != page_spec_qpdfs.end(); ++iter)\n {\n std::string const& filename = (*iter).first;\n ClosedFileInputSource* cis = 0;\n if (page_spec_cfis.count(filename))\n {\n cis = page_spec_cfis[filename];\n cis->stayOpen(true);\n }\n QPDFPageDocumentHelper dh(*((*iter).second));\n dh.removeUnreferencedResources();\n if (cis)\n {\n cis->stayOpen(false);\n }\n }\n }\n\n // Clear all pages out of the primary QPDF's pages tree but leave\n // the objects in place in the file so they can be re-added\n // without changing their object numbers. This enables other\n // things in the original file, such as outlines, to continue to\n // work.\n if (o.verbose)\n {\n std::cout << whoami\n << \": removing unreferenced pages from primary input\"\n << std::endl;\n }\n QPDFPageDocumentHelper dh(pdf);\n std::vector orig_pages = dh.getAllPages();\n for (std::vector::iterator iter =\n orig_pages.begin();\n iter != orig_pages.end(); ++iter)\n {\n dh.removePage(*iter);\n }\n\n if (o.collate && (parsed_specs.size() > 1))\n {\n // Collate the pages by selecting one page from each spec in\n // order. When a spec runs out of pages, stop selecting from\n // it.\n std::vector new_parsed_specs;\n size_t nspecs = parsed_specs.size();\n size_t cur_page = 0;\n bool got_pages = true;\n while (got_pages)\n {\n got_pages = false;\n for (size_t i = 0; i < nspecs; ++i)\n {\n QPDFPageData& page_data = parsed_specs.at(i);\n if (cur_page < page_data.selected_pages.size())\n {\n got_pages = true;\n new_parsed_specs.push_back(\n QPDFPageData(\n page_data,\n page_data.selected_pages.at(cur_page)));\n }\n }\n ++cur_page;\n }\n parsed_specs = new_parsed_specs;\n }\n\n // Add all the pages from all the files in the order specified.\n // Keep track of any pages from the original file that we are\n // selecting.\n std::set selected_from_orig;\n std::vector new_labels;\n bool any_page_labels = false;\n int out_pageno = 0;\n for (std::vector::iterator iter =\n parsed_specs.begin();\n iter != parsed_specs.end(); ++iter)\n {\n QPDFPageData& page_data = *iter;\n ClosedFileInputSource* cis = 0;\n if (page_spec_cfis.count(page_data.filename))\n {\n cis = page_spec_cfis[page_data.filename];\n cis->stayOpen(true);\n }\n QPDFPageLabelDocumentHelper pldh(*page_data.qpdf);\n if (pldh.hasPageLabels())\n {\n any_page_labels = true;\n }\n if (o.verbose)\n {\n std::cout << whoami << \": adding pages from \"\n << page_data.filename << std::endl;\n }\n for (std::vector::iterator pageno_iter =\n page_data.selected_pages.begin();\n pageno_iter != page_data.selected_pages.end();\n ++pageno_iter, ++out_pageno)\n {\n // Pages are specified from 1 but numbered from 0 in the\n // vector\n int pageno = *pageno_iter - 1;\n pldh.getLabelsForPageRange(pageno, pageno, out_pageno,\n new_labels);\n QPDFPageObjectHelper to_copy = page_data.orig_pages.at(pageno);\n QPDFObjGen to_copy_og = to_copy.getObjectHandle().getObjGen();\n unsigned long long from_uuid = page_data.qpdf->getUniqueId();\n if (copied_pages[from_uuid].count(to_copy_og))\n {\n QTC::TC(\"qpdf\", \"qpdf copy same page more than once\",\n (page_data.qpdf == &pdf) ? 0 : 1);\n to_copy = to_copy.shallowCopyPage();\n }\n else\n {\n copied_pages[from_uuid].insert(to_copy_og);\n }\n dh.addPage(to_copy, false);\n if (page_data.qpdf == &pdf)\n {\n // This is a page from the original file. Keep track\n // of the fact that we are using it.\n selected_from_orig.insert(pageno);\n }\n }\n if (cis)\n {\n cis->stayOpen(false);\n }\n }\n if (any_page_labels)\n {\n QPDFObjectHandle page_labels =\n QPDFObjectHandle::newDictionary();\n page_labels.replaceKey(\n \"/Nums\", QPDFObjectHandle::newArray(new_labels));\n pdf.getRoot().replaceKey(\"/PageLabels\", page_labels);\n }\n\n // Delete page objects for unused page in primary. This prevents\n // those objects from being preserved by being referred to from\n // other places, such as the outlines dictionary.\n for (size_t pageno = 0; pageno < orig_pages.size(); ++pageno)\n {\n if (selected_from_orig.count(pageno) == 0)\n {\n pdf.replaceObject(\n orig_pages.at(pageno).getObjectHandle().getObjGen(),\n QPDFObjectHandle::newNull());\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: QPDFAcroFormDocumentHelper::traverseField(\n QPDFObjectHandle field, QPDFObjectHandle parent, int depth,\n std::set& visited)\n{\n if (depth > 100)\n {\n // Arbitrarily cut off recursion at a fixed depth to avoid\n // specially crafted files that could cause stack overflow.\n return;\n }\n if (! field.isIndirect())\n {\n QTC::TC(\"qpdf\", \"QPDFAcroFormDocumentHelper direct field\");\n field.warnIfPossible(\n \"encountered a direct object as a field or annotation while\"\n \" traversing /AcroForm; ignoring field or annotation\");\n return;\n }\n if (! field.isDictionary())\n {\n QTC::TC(\"qpdf\", \"QPDFAcroFormDocumentHelper non-dictionary field\");\n field.warnIfPossible(\n \"encountered a non-dictionary as a field or annotation while\"\n \" traversing /AcroForm; ignoring field or annotation\");\n return;\n }\n QPDFObjGen og(field.getObjGen());\n if (visited.count(og) != 0)\n {\n QTC::TC(\"qpdf\", \"QPDFAcroFormDocumentHelper loop\");\n field.warnIfPossible(\"loop detected while traversing /AcroForm\");\n return;\n }\n visited.insert(og);\n\n // A dictionary encountered while traversing the /AcroForm field\n // may be a form field, an annotation, or the merger of the two. A\n // field that has no fields below it is a terminal. If a terminal\n // field looks like an annotation, it is an annotation because\n // annotation dictionary fields can be merged with terminal field\n // dictionaries. Otherwise, the annotation fields might be there\n // to be inherited by annotations below it.\n\n bool is_annotation = false;\n bool is_field = (0 == depth);\n QPDFObjectHandle kids = field.getKey(\"/Kids\");\n if (kids.isArray())\n {\n is_field = true;\n size_t nkids = kids.getArrayNItems();\n for (size_t k = 0; k < nkids; ++k)\n {\n traverseField(kids.getArrayItem(k), field, 1 + depth, visited);\n }\n }\n else\n {\n if (field.hasKey(\"/Parent\"))\n {\n is_field = true;\n }\n if (field.hasKey(\"/Subtype\") ||\n field.hasKey(\"/Rect\") ||\n field.hasKey(\"/AP\"))\n {\n is_annotation = true;\n }\n }\n\n QTC::TC(\"qpdf\", \"QPDFAcroFormDocumentHelper field found\",\n (depth == 0) ? 0 : 1);\n QTC::TC(\"qpdf\", \"QPDFAcroFormDocumentHelper annotation found\",\n (is_field ? 0 : 1));\n\n if (is_annotation)\n {\n QPDFObjectHandle our_field = (is_field ? field : parent);\n this->m->field_to_annotations[our_field.getObjGen()].push_back(\n QPDFAnnotationObjectHelper(field));\n this->m->annotation_to_field[og] =\n QPDFFormFieldObjectHelper(our_field);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: QPDF::trim_user_password(std::string& user_password)\n{\n // Although unnecessary, this routine trims the padding string\n // from the end of a user password. Its only purpose is for\n // recovery of user passwords which is done in the test suite.\n char const* cstr = user_password.c_str();\n size_t len = user_password.length();\n if (len < key_bytes)\n {\n\treturn;\n }\n\n char const* p1 = cstr;\n char const* p2 = 0;\n while ((p2 = strchr(p1, '\\x28')) != 0)\n {\n\tif (memcmp(p2, padding_string, len - (p2 - cstr)) == 0)\n\t{\n\t user_password = user_password.substr(0, p2 - cstr);\n\t return;\n\t}\n else\n {\n QTC::TC(\"qpdf\", \"QPDF_encryption skip 0x28\");\n p1 = p2 + 1;\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: MD5::checkDataChecksum(char const* const checksum,\n\t\t char const* buf, int len)\n{\n std::string actual_checksum = getDataChecksum(buf, len);\n return (checksum == actual_checksum);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void run(char const* filename, char const* filter,\n bool encode, unsigned int columns,\n int bits_per_sample, int samples_per_pixel)\n{\n FILE* in = QUtil::safe_fopen(filename, \"rb\");\n FILE* o1 = QUtil::safe_fopen(\"out\", \"wb\");\n Pipeline* out = new Pl_StdioFile(\"out\", o1);\n Pipeline* pl = 0;\n if (strcmp(filter, \"png\") == 0)\n {\n pl = new Pl_PNGFilter(\n \"png\", out,\n encode ? Pl_PNGFilter::a_encode : Pl_PNGFilter::a_decode,\n columns, samples_per_pixel, bits_per_sample);\n }\n else if (strcmp(filter, \"tiff\") == 0)\n {\n pl = new Pl_TIFFPredictor(\n \"png\", out,\n encode ? Pl_TIFFPredictor::a_encode : Pl_TIFFPredictor::a_decode,\n columns, samples_per_pixel, bits_per_sample);\n }\n else\n {\n std::cerr << \"unknown filter \" << filter << std::endl;\n exit(2);\n }\n assert((2 * (columns + 1)) < 1024);\n unsigned char buf[1024];\n size_t len;\n while (true)\n {\n\tlen = fread(buf, 1, (2 * columns) + 1, in);\n\tif (len == 0)\n\t{\n\t break;\n\t}\n\tpl->write(buf, len);\n\tlen = fread(buf, 1, 1, in);\n\tif (len == 0)\n\t{\n\t break;\n\t}\n\tpl->write(buf, len);\n\tlen = fread(buf, 1, 1, in);\n\tif (len == 0)\n\t{\n\t break;\n\t}\n\tpl->write(buf, len);\n }\n\n pl->finish();\n delete pl;\n delete out;\n fclose(o1);\n fclose(in);\n\n std::cout << \"done\" << std::endl;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: QPDF::outputLengthNextN(\n int in_object, int n,\n std::map const& lengths,\n std::map const& obj_renumber)\n{\n // Figure out the length of a series of n consecutive objects in\n // the output file starting with whatever object in_object from\n // the input file mapped to.\n\n if (obj_renumber.count(in_object) == 0)\n {\n stopOnError(\"found object that is not renumbered while\"\n \" writing linearization data\");\n }\n int first = (*(obj_renumber.find(in_object))).second;\n int length = 0;\n for (int i = 0; i < n; ++i)\n {\n\tif (lengths.count(first + i) == 0)\n {\n stopOnError(\"found item with unknown length\"\n \" while writing linearization data\");\n }\n\tlength += (*(lengths.find(first + i))).second;\n }\n return length;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: QPDF::read_xrefTable(qpdf_offset_t xref_offset)\n{\n std::vector deleted_items;\n\n this->m->file->seek(xref_offset, SEEK_SET);\n bool done = false;\n while (! done)\n {\n char linebuf[51];\n memset(linebuf, 0, sizeof(linebuf));\n this->m->file->read(linebuf, sizeof(linebuf) - 1);\n\tstd::string line = linebuf;\n int obj = 0;\n int num = 0;\n int bytes = 0;\n if (! parse_xrefFirst(line, obj, num, bytes))\n\t{\n\t QTC::TC(\"qpdf\", \"QPDF invalid xref\");\n\t throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),\n\t\t\t \"xref table\", this->m->file->getLastOffset(),\n\t\t\t \"xref syntax invalid\");\n\t}\n this->m->file->seek(this->m->file->getLastOffset() + bytes, SEEK_SET);\n\tfor (qpdf_offset_t i = obj; i - num < obj; ++i)\n\t{\n\t if (i == 0)\n\t {\n\t\t// This is needed by checkLinearization()\n\t\tthis->m->first_xref_item_offset = this->m->file->tell();\n\t }\n\t std::string xref_entry = this->m->file->readLine(30);\n // For xref_table, these will always be small enough to be ints\n\t qpdf_offset_t f1 = 0;\n\t int f2 = 0;\n\t char type = '\\0';\n if (! parse_xrefEntry(xref_entry, f1, f2, type))\n\t {\n\t\tQTC::TC(\"qpdf\", \"QPDF invalid xref entry\");\n\t\tthrow QPDFExc(\n\t\t qpdf_e_damaged_pdf, this->m->file->getName(),\n\t\t \"xref table\", this->m->file->getLastOffset(),\n\t\t \"invalid xref entry (obj=\" +\n\t\t QUtil::int_to_string(i) + \")\");\n\t }\n\t if (type == 'f')\n\t {\n\t\t// Save deleted items until after we've checked the\n\t\t// XRefStm, if any.\n\t\tdeleted_items.push_back(QPDFObjGen(i, f2));\n\t }\n\t else\n\t {\n\t\tinsertXrefEntry(i, 1, f1, f2);\n\t }\n\t}\n\tqpdf_offset_t pos = this->m->file->tell();\n\tQPDFTokenizer::Token t = readToken(this->m->file);\n\tif (t == QPDFTokenizer::Token(QPDFTokenizer::tt_word, \"trailer\"))\n\t{\n\t done = true;\n\t}\n\telse\n\t{\n\t this->m->file->seek(pos, SEEK_SET);\n\t}\n }\n\n // Set offset to previous xref table if any\n QPDFObjectHandle cur_trailer =\n\treadObject(this->m->file, \"trailer\", 0, 0, false);\n if (! cur_trailer.isDictionary())\n {\n\tQTC::TC(\"qpdf\", \"QPDF missing trailer\");\n\tthrow QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),\n\t\t \"\", this->m->file->getLastOffset(),\n\t\t \"expected trailer dictionary\");\n }\n\n if (! this->m->trailer.isInitialized())\n {\n\tsetTrailer(cur_trailer);\n\n\tif (! this->m->trailer.hasKey(\"/Size\"))\n\t{\n\t QTC::TC(\"qpdf\", \"QPDF trailer lacks size\");\n\t throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),\n\t\t\t \"trailer\", this->m->file->getLastOffset(),\n\t\t\t \"trailer dictionary lacks /Size key\");\n\t}\n\tif (! this->m->trailer.getKey(\"/Size\").isInteger())\n\t{\n\t QTC::TC(\"qpdf\", \"QPDF trailer size not integer\");\n\t throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),\n\t\t\t \"trailer\", this->m->file->getLastOffset(),\n\t\t\t \"/Size key in trailer dictionary is not \"\n\t\t\t \"an integer\");\n\t}\n }\n\n if (cur_trailer.hasKey(\"/XRefStm\"))\n {\n\tif (this->m->ignore_xref_streams)\n\t{\n\t QTC::TC(\"qpdf\", \"QPDF ignoring XRefStm in trailer\");\n\t}\n\telse\n\t{\n\t if (cur_trailer.getKey(\"/XRefStm\").isInteger())\n\t {\n\t\t// Read the xref stream but disregard any return value\n\t\t// -- we'll use our trailer's /Prev key instead of the\n\t\t// xref stream's.\n\t\t(void) read_xrefStream(\n\t\t cur_trailer.getKey(\"/XRefStm\").getIntValue());\n\t }\n\t else\n\t {\n\t\tthrow QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),\n\t\t\t \"xref stream\", xref_offset,\n\t\t\t \"invalid /XRefStm\");\n\t }\n\t}\n }\n\n // Handle any deleted items now that we've read the /XRefStm.\n for (std::vector::iterator iter = deleted_items.begin();\n\t iter != deleted_items.end(); ++iter)\n {\n\tQPDFObjGen& og = *iter;\n\tinsertXrefEntry(og.getObj(), 0, 0, og.getGen());\n }\n\n if (cur_trailer.hasKey(\"/Prev\"))\n {\n\tif (! cur_trailer.getKey(\"/Prev\").isInteger())\n\t{\n\t QTC::TC(\"qpdf\", \"QPDF trailer prev not integer\");\n\t throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),\n\t\t\t \"trailer\", this->m->file->getLastOffset(),\n\t\t\t \"/Prev key in trailer dictionary is not \"\n\t\t\t \"an integer\");\n\t}\n\tQTC::TC(\"qpdf\", \"QPDF prev key in trailer dictionary\");\n\txref_offset = cur_trailer.getKey(\"/Prev\").getIntValue();\n }\n else\n {\n\txref_offset = 0;\n }\n\n return xref_offset;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: MD5::checkFileChecksum(char const* const checksum,\n\t\t char const* filename, int up_to_size)\n{\n bool result = false;\n try\n {\n\tstd::string actual_checksum = getFileChecksum(filename, up_to_size);\n\tresult = (checksum == actual_checksum);\n }\n catch (std::runtime_error const&)\n {\n\t// Ignore -- return false\n }\n return result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ImageOptimizer::makePipeline(std::string const& description, Pipeline* next)\n{\n PointerHolder result;\n QPDFObjectHandle dict = image.getDict();\n QPDFObjectHandle w_obj = dict.getKey(\"/Width\");\n QPDFObjectHandle h_obj = dict.getKey(\"/Height\");\n QPDFObjectHandle colorspace_obj = dict.getKey(\"/ColorSpace\");\n if (! (w_obj.isNumber() && h_obj.isNumber()))\n {\n if (o.verbose && (! description.empty()))\n {\n std::cout << whoami << \": \" << description\n << \": not optimizing because image dictionary\"\n << \" is missing required keys\" << std::endl;\n }\n return result;\n }\n QPDFObjectHandle components_obj = dict.getKey(\"/BitsPerComponent\");\n if (! (components_obj.isInteger() && (components_obj.getIntValue() == 8)))\n {\n QTC::TC(\"qpdf\", \"qpdf image optimize bits per component\");\n if (o.verbose && (! description.empty()))\n {\n std::cout << whoami << \": \" << description\n << \": not optimizing because image has other than\"\n << \" 8 bits per component\" << std::endl;\n }\n return result;\n }\n // Files have been seen in the wild whose width and height are\n // floating point, which is goofy, but we can deal with it.\n JDIMENSION w = static_cast(\n w_obj.isInteger() ? w_obj.getIntValue() : w_obj.getNumericValue());\n JDIMENSION h = static_cast(\n h_obj.isInteger() ? h_obj.getIntValue() : h_obj.getNumericValue());\n std::string colorspace = (colorspace_obj.isName() ?\n colorspace_obj.getName() :\n std::string());\n int components = 0;\n J_COLOR_SPACE cs = JCS_UNKNOWN;\n if (colorspace == \"/DeviceRGB\")\n {\n components = 3;\n cs = JCS_RGB;\n }\n else if (colorspace == \"/DeviceGray\")\n {\n components = 1;\n cs = JCS_GRAYSCALE;\n }\n else if (colorspace == \"/DeviceCMYK\")\n {\n components = 4;\n cs = JCS_CMYK;\n }\n else\n {\n QTC::TC(\"qpdf\", \"qpdf image optimize colorspace\");\n if (o.verbose && (! description.empty()))\n {\n std::cout << whoami << \": \" << description\n << \": not optimizing because qpdf can't optimize\"\n << \" images with this colorspace\" << std::endl;\n }\n return result;\n }\n if (((o.oi_min_width > 0) && (w <= o.oi_min_width)) ||\n ((o.oi_min_height > 0) && (h <= o.oi_min_height)) ||\n ((o.oi_min_area > 0) && ((w * h) <= o.oi_min_area)))\n {\n QTC::TC(\"qpdf\", \"qpdf image optimize too small\");\n if (o.verbose && (! description.empty()))\n {\n std::cout << whoami << \": \" << description\n << \": not optimizing because image\"\n << \" is smaller than requested minimum dimensions\"\n << std::endl;\n }\n return result;\n }\n\n result = new Pl_DCT(\"jpg\", next, w, h, components, cs);\n return result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: WindowsCryptProvider()\n {\n if (!CryptAcquireContext(&crypt_prov,\n \"Container\",\n NULL,\n PROV_RSA_FULL,\n 0))\n {\n#if ((defined(__GNUC__) && ((__GNUC__ * 100) + __GNUC_MINOR__) >= 406) || \\\n defined(__clang__))\n# pragma GCC diagnostic push\n# pragma GCC diagnostic ignored \"-Wold-style-cast\"\n# pragma GCC diagnostic ignored \"-Wsign-compare\"\n#endif\n if (GetLastError() == NTE_BAD_KEYSET)\n#if ((defined(__GNUC__) && ((__GNUC__ * 100) + __GNUC_MINOR__) >= 406) || \\\n defined(__clang__))\n# pragma GCC diagnostic pop\n#endif\n {\n if (! CryptAcquireContext(&crypt_prov,\n \"Container\",\n NULL,\n PROV_RSA_FULL,\n CRYPT_NEWKEYSET))\n {\n throw std::runtime_error(\n \"unable to acquire crypt context with new keyset\");\n }\n }\n else\n {\n throw std::runtime_error(\"unable to acquire crypt context\");\n }\n }\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: QUtil::toUTF16(unsigned long uval)\n{\n std::string result;\n if ((uval >= 0xd800) && (uval <= 0xdfff))\n {\n result = \"\\xff\\xfd\";\n }\n else if (uval <= 0xffff)\n {\n char out[2];\n out[0] = (uval & 0xff00) >> 8;\n out[1] = (uval & 0xff);\n result = std::string(out, 2);\n }\n else if (uval <= 0x10ffff)\n {\n char out[4];\n uval -= 0x10000;\n unsigned short high = ((uval & 0xffc00) >> 10) + 0xd800;\n unsigned short low = (uval & 0x3ff) + 0xdc00;\n out[0] = (high & 0xff00) >> 8;\n out[1] = (high & 0xff);\n out[2] = (low & 0xff00) >> 8;\n out[3] = (low & 0xff);\n result = std::string(out, 4);\n }\n else\n {\n result = \"\\xff\\xfd\";\n }\n\n return result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: QPDFWriter::doWriteSetup()\n{\n if (this->m->did_write_setup)\n {\n return;\n }\n this->m->did_write_setup = true;\n\n // Do preliminary setup\n\n if (this->m->linearized)\n {\n\tthis->m->qdf_mode = false;\n }\n\n if (this->m->pclm)\n {\n this->m->stream_decode_level = qpdf_dl_none;\n this->m->compress_streams = false;\n this->m->encrypted = false;\n }\n\n if (this->m->qdf_mode)\n {\n\tif (! this->m->normalize_content_set)\n\t{\n\t this->m->normalize_content = true;\n\t}\n\tif (! this->m->compress_streams_set)\n\t{\n\t this->m->compress_streams = false;\n\t}\n if (! this->m->stream_decode_level_set)\n {\n this->m->stream_decode_level = qpdf_dl_generalized;\n }\n }\n\n if (this->m->encrypted)\n {\n\t// Encryption has been explicitly set\n\tthis->m->preserve_encryption = false;\n }\n else if (this->m->normalize_content ||\n\t this->m->stream_decode_level ||\n this->m->pclm ||\n\t this->m->qdf_mode)\n {\n\t// Encryption makes looking at contents pretty useless. If\n\t// the user explicitly encrypted though, we still obey that.\n\tthis->m->preserve_encryption = false;\n }\n\n if (this->m->preserve_encryption)\n {\n\tcopyEncryptionParameters(this->m->pdf);\n }\n\n if (! this->m->forced_pdf_version.empty())\n {\n\tint major = 0;\n\tint minor = 0;\n\tparseVersion(this->m->forced_pdf_version, major, minor);\n\tdisableIncompatibleEncryption(major, minor,\n this->m->forced_extension_level);\n\tif (compareVersions(major, minor, 1, 5) < 0)\n\t{\n\t QTC::TC(\"qpdf\", \"QPDFWriter forcing object stream disable\");\n\t this->m->object_stream_mode = qpdf_o_disable;\n\t}\n }\n\n if (this->m->qdf_mode || this->m->normalize_content ||\n this->m->stream_decode_level)\n {\n\tinitializeSpecialStreams();\n }\n\n if (this->m->qdf_mode)\n {\n\t// Generate indirect stream lengths for qdf mode since fix-qdf\n\t// uses them for storing recomputed stream length data.\n\t// Certain streams such as object streams, xref streams, and\n\t// hint streams always get direct stream lengths.\n\tthis->m->direct_stream_lengths = false;\n }\n\n switch (this->m->object_stream_mode)\n {\n case qpdf_o_disable:\n\t// no action required\n\tbreak;\n\n case qpdf_o_preserve:\n\tpreserveObjectStreams();\n\tbreak;\n\n case qpdf_o_generate:\n\tgenerateObjectStreams();\n\tbreak;\n\n\t// no default so gcc will warn for missing case tag\n }\n\n if (this->m->linearized)\n {\n\t// Page dictionaries are not allowed to be compressed objects.\n\tstd::vector pages = this->m->pdf.getAllPages();\n\tfor (std::vector::iterator iter = pages.begin();\n\t iter != pages.end(); ++iter)\n\t{\n\t QPDFObjectHandle& page = *iter;\n\t QPDFObjGen og = page.getObjGen();\n\t if (this->m->object_to_object_stream.count(og))\n\t {\n\t\tQTC::TC(\"qpdf\", \"QPDFWriter uncompressing page dictionary\");\n\t\tthis->m->object_to_object_stream.erase(og);\n\t }\n\t}\n }\n\n if (this->m->linearized || this->m->encrypted)\n {\n \t// The document catalog is not allowed to be compressed in\n \t// linearized files either. It also appears that Adobe Reader\n \t// 8.0.0 has a bug that prevents it from being able to handle\n \t// encrypted files with compressed document catalogs, so we\n \t// disable them in that case as well.\n\tQPDFObjGen og = this->m->pdf.getRoot().getObjGen();\n\tif (this->m->object_to_object_stream.count(og))\n\t{\n\t QTC::TC(\"qpdf\", \"QPDFWriter uncompressing root\");\n\t this->m->object_to_object_stream.erase(og);\n\t}\n }\n\n // Generate reverse mapping from object stream to objects\n for (std::map::iterator iter =\n\t this->m->object_to_object_stream.begin();\n\t iter != this->m->object_to_object_stream.end(); ++iter)\n {\n\tQPDFObjGen obj = (*iter).first;\n\tint stream = (*iter).second;\n\tthis->m->object_stream_to_objects[stream].insert(obj);\n\tthis->m->max_ostream_index =\n\t std::max(this->m->max_ostream_index,\n\t\t static_cast(\n this->m->object_stream_to_objects[stream].size()) - 1);\n }\n\n if (! this->m->object_stream_to_objects.empty())\n {\n\tsetMinimumPDFVersion(\"1.5\");\n }\n\n setMinimumPDFVersion(this->m->pdf.getPDFVersion(),\n this->m->pdf.getExtensionLevel());\n this->m->final_pdf_version = this->m->min_pdf_version;\n this->m->final_extension_level = this->m->min_extension_level;\n if (! this->m->forced_pdf_version.empty())\n {\n\tQTC::TC(\"qpdf\", \"QPDFWriter using forced PDF version\");\n\tthis->m->final_pdf_version = this->m->forced_pdf_version;\n this->m->final_extension_level = this->m->forced_extension_level;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: BitStream::getBitsSigned(int nbits)\n{\n unsigned long long bits = read_bits(this->p, this->bit_offset,\n this->bits_available, nbits);\n long long result = 0;\n if (static_cast(bits) > 1 << (nbits - 1))\n {\n result = static_cast(bits - (1 << nbits));\n }\n else\n {\n result = static_cast(bits);\n }\n return result;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: QPDF_Stream::understandDecodeParams(\n std::string const& filter, QPDFObjectHandle decode_obj,\n int& predictor, int& columns,\n int& colors, int& bits_per_component,\n bool& early_code_change)\n{\n bool filterable = true;\n std::set keys = decode_obj.getKeys();\n for (std::set::iterator iter = keys.begin();\n iter != keys.end(); ++iter)\n {\n std::string const& key = *iter;\n if (((filter == \"/FlateDecode\") || (filter == \"/LZWDecode\")) &&\n (key == \"/Predictor\"))\n {\n QPDFObjectHandle predictor_obj = decode_obj.getKey(key);\n if (predictor_obj.isInteger())\n {\n predictor = predictor_obj.getIntValue();\n if (! ((predictor == 1) || (predictor == 2) ||\n ((predictor >= 10) && (predictor <= 15))))\n {\n filterable = false;\n }\n }\n else\n {\n filterable = false;\n }\n }\n else if ((filter == \"/LZWDecode\") && (key == \"/EarlyChange\"))\n {\n QPDFObjectHandle earlychange_obj = decode_obj.getKey(key);\n if (earlychange_obj.isInteger())\n {\n int earlychange = earlychange_obj.getIntValue();\n early_code_change = (earlychange == 1);\n if (! ((earlychange == 0) || (earlychange == 1)))\n {\n filterable = false;\n }\n }\n else\n {\n filterable = false;\n }\n }\n else if ((key == \"/Columns\") ||\n (key == \"/Colors\") ||\n (key == \"/BitsPerComponent\"))\n {\n QPDFObjectHandle param_obj = decode_obj.getKey(key);\n if (param_obj.isInteger())\n {\n int val = param_obj.getIntValue();\n if (key == \"/Columns\")\n {\n columns = val;\n }\n else if (key == \"/Colors\")\n {\n colors = val;\n }\n else if (key == \"/BitsPerComponent\")\n {\n bits_per_component = val;\n }\n }\n else\n {\n filterable = false;\n }\n }\n else if ((filter == \"/Crypt\") &&\n (((key == \"/Type\") || (key == \"/Name\")) &&\n (decode_obj.getKey(\"/Type\").isNull() ||\n (decode_obj.getKey(\"/Type\").isName() &&\n (decode_obj.getKey(\"/Type\").getName() ==\n \"/CryptFilterDecodeParms\")))))\n {\n // we handle this in decryptStream\n }\n else\n {\n filterable = false;\n }\n }\n\n return filterable;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Fix sign and conversion warnings (major)\n\nThis makes all integer type conversions that have potential data loss\nexplicit with calls that do range checks and raise an exception. After\nthis commit, qpdf builds with no warnings when -Wsign-conversion\n-Wconversion is used with gcc or clang or when -W3 -Wd4800 is used\nwith MSVC. This significantly reduces the likelihood of potential\ncrashes from bogus integer values.\n\nThere are some parts of the code that take int when they should take\nsize_t or an offset. Such places would make qpdf not support files\nwith more than 2^31 of something that usually wouldn't be so large. In\nthe event that such a file shows up and is valid, at least qpdf would\nraise an error in the right spot so the issue could be legitimately\naddressed rather than failing in some weird way because of a silent\noverflow condition.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static const ut8 *r_bin_dwarf_parse_comp_unit(Sdb *s, const ut8 *obuf,\n\t\tRBinDwarfCompUnit *cu, const RBinDwarfDebugAbbrev *da,\n\t\tsize_t offset, const ut8 *debug_str, size_t debug_str_len) {\n\tconst ut8 *buf = obuf, *buf_end = obuf + (cu->hdr.length - 7);\n\tut64 abbr_code;\n\tsize_t i;\n\t\n\tif (cu->hdr.length > debug_str_len) {\n\t\t//avoid oob read\n\t\treturn NULL;\n\t}\n\twhile (buf && buf < buf_end && buf >= obuf) {\n\t\tif (cu->length && cu->capacity == cu->length) {\n\t\t\tr_bin_dwarf_expand_cu (cu);\n\t\t}\n\t\tbuf = r_uleb128 (buf, buf_end - buf, &abbr_code);\n\t\tif (abbr_code > da->length || !buf) {\n\t\t\treturn NULL;\n\t\t}\n\n\t\tr_bin_dwarf_init_die (&cu->dies[cu->length]);\n\t\tif (!abbr_code) {\n\t\t\tcu->dies[cu->length].abbrev_code = 0;\n\t\t\tcu->length++;\n\t\t\tbuf++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tcu->dies[cu->length].abbrev_code = abbr_code;\n\t\tcu->dies[cu->length].tag = da->decls[abbr_code - 1].tag;\n\t\tabbr_code += offset;\n\n\t\tif (da->capacity < abbr_code) {\n\t\t\treturn NULL;\n\t\t}\n\n\t\tfor (i = 0; i < da->decls[abbr_code - 1].length; i++) {\n\t\t\tif (cu->dies[cu->length].length == cu->dies[cu->length].capacity) {\n\t\t\t\tr_bin_dwarf_expand_die (&cu->dies[cu->length]);\n\t\t\t}\n\t\t\tif (i >= cu->dies[cu->length].capacity || i >= da->decls[abbr_code - 1].capacity) {\n\t\t\t\teprintf (\"Warning: malformed dwarf attribute capacity doesn't match length\\n\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tmemset (&cu->dies[cu->length].attr_values[i], 0, sizeof\n\t\t\t\t\t(cu->dies[cu->length].attr_values[i]));\n\t\t\tbuf = r_bin_dwarf_parse_attr_value (buf, buf_end - buf,\n\t\t\t\t\t&da->decls[abbr_code - 1].specs[i],\n\t\t\t\t\t&cu->dies[cu->length].attr_values[i],\n\t\t\t\t\t&cu->hdr, debug_str, debug_str_len);\n\t\t\tif (cu->dies[cu->length].attr_values[i].name == DW_AT_comp_dir) {\n\t\t\t\tconst char *name = cu->dies[cu->length].attr_values[i].encoding.str_struct.string;\n\t\t\t\tsdb_set (s, \"DW_AT_comp_dir\", name, 0);\n\t\t\t}\n\t\t\tcu->dies[cu->length].length++;\n\t\t}\n\t\tcu->length++;\n\t}\n\treturn buf;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'Fix #8813 - segfault in dwarf parser'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: proc_lambda(mrb_state *mrb, mrb_value self)\n{\n mrb_value blk;\n struct RProc *p;\n\n mrb_get_args(mrb, \"&\", &blk);\n if (mrb_nil_p(blk)) {\n mrb_raise(mrb, E_ARGUMENT_ERROR, \"tried to create Proc object without a block\");\n }\n if (!mrb_proc_p(blk)) {\n mrb_raise(mrb, E_ARGUMENT_ERROR, \"not a proc\");\n }\n p = mrb_proc_ptr(blk);\n if (!MRB_PROC_STRICT_P(p)) {\n struct RProc *p2 = MRB_OBJ_ALLOC(mrb, MRB_TT_PROC, p->c);\n mrb_proc_copy(p2, p);\n p2->flags |= MRB_PROC_STRICT;\n return mrb_obj_value(p2);\n }\n return blk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476', 'CWE-190'], 'message': 'proc.c: add `mrb_state` argument to `mrb_proc_copy()`.\n\nThe function may invoke the garbage collection and it requires\n`mrb_state` to run.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus Subgraph::AllocateTensors() {\n TFLITE_SCOPED_TAGGED_DEFAULT_PROFILE(profiler_.get(), \"AllocateTensors\");\n if (!consistent_) {\n ReportError(\"AllocateTensors() called on inconsistent model.\");\n return kTfLiteError;\n }\n\n // Restore delegation state if applicable.\n TF_LITE_ENSURE_STATUS(RedoAllDelegates());\n\n // Explicit (re)allocation is necessary if nodes have been changed or tensors\n // have been resized. For inputs marked as dynamic, we can't short-circuit the\n // allocation as the client may have done the resize manually.\n if (state_ != kStateUninvokable &&\n !HasDynamicTensorImpl(context_, inputs())) {\n if (memory_planner_ && !memory_planner_->HasNonPersistentMemory()) {\n // If the only change was the release of non-persistent memory via\n // ReleaseNonPersistentMemory(), just re-allocate it. For any other type\n // of memory-planning change (for eg, ResizeInputTensor), the state would\n // be kStateUninvokable.\n memory_planner_->AcquireNonPersistentMemory();\n }\n return kTfLiteOk;\n }\n\n next_execution_plan_index_to_prepare_ = 0;\n next_execution_plan_index_to_plan_allocation_ = 0;\n next_original_execution_plan_index_to_prepare_ = 0;\n if (memory_planner_) {\n TF_LITE_ENSURE_STATUS(memory_planner_->ResetAllocations());\n }\n\n TF_LITE_ENSURE_STATUS(PrepareOpsAndTensors());\n\n state_ = kStateInvokable;\n\n // Reset the variable tensors to zero after (re)allocating the tensors.\n // Developers shouldn't rely on the side effect of this function to reset\n // variable tensors. They should call `ResetVariableTensors` directly\n // instead.\n ResetVariableTensors();\n\n return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-835'], 'message': 'TFLite: Error out when the graph has a recurion.\n\nRecursion is currently unsupported.\n\nPiperOrigin-RevId: 371708957\nChange-Id: I8dfad0d85cbfe08e39ae8ea7bad21254ddee5003'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static bool extractFileTo(zip* zip, const std::string &file, std::string& to,\n char* buf, size_t len) {\n auto sep = file.rfind('/');\n if (sep != std::string::npos) {\n auto path = to + file.substr(0, sep);\n if (!HHVM_FN(is_dir)(path) && !HHVM_FN(mkdir)(path, 0777, true)) {\n return false;\n }\n\n if (sep == file.length() - 1) {\n return true;\n }\n }\n\n to.append(file);\n struct zip_stat zipStat;\n if (zip_stat(zip, file.c_str(), 0, &zipStat) != 0) {\n return false;\n }\n\n auto zipFile = zip_fopen_index(zip, zipStat.index, 0);\n FAIL_IF_INVALID_PTR(zipFile);\n\n auto outFile = fopen(to.c_str(), \"wb\");\n if (outFile == nullptr) {\n zip_fclose(zipFile);\n return false;\n }\n\n for (auto n = zip_fread(zipFile, buf, len); n != 0;\n n = zip_fread(zipFile, buf, len)) {\n if (n < 0 || fwrite(buf, sizeof(char), n, outFile) != n) {\n zip_fclose(zipFile);\n fclose(outFile);\n remove(to.c_str());\n return false;\n }\n }\n\n zip_fclose(zipFile);\n if (fclose(outFile) != 0) {\n return false;\n }\n\n return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-22'], 'message': 'ZipArchive::extractTo bug 70350\n\nSummary:Don't allow upward directory traversal when extracting zip archive files.\n\nFiles in zip files with `..` or starting at main root `/` should be normalized\nto something where the file being extracted winds up within the directory or\na subdirectory where the actual extraction is taking place.\n\nhttp://git.php.net/?p=php-src.git;a=commit;h=f9c2bf73adb2ede0a486b0db466c264f2b27e0bb\n\nReviewed By: FBNeal\n\nDifferential Revision: D2798452\n\nfb-gh-sync-id: 844549c93e011d1e991bb322bf85822246b04e30\nshipit-source-id: 844549c93e011d1e991bb322bf85822246b04e30'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool CModules::GetModPathInfo(CModInfo& ModInfo, const CString& sModule,\n const CString& sModPath, CString& sRetMsg) {\n ModInfo.SetName(sModule);\n ModInfo.SetPath(sModPath);\n\n ModHandle p = OpenModule(sModule, sModPath, ModInfo, sRetMsg);\n if (!p) return false;\n\n dlclose(p);\n\n return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20', 'CWE-264'], 'message': 'Fix remote code execution and privilege escalation vulnerability.\n\nTo trigger this, need to have a user already.\n\nThanks for Jeriko One for finding and reporting this.\n\nCVE-2019-12816'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int try_read_command(conn *c) {\n assert(c != NULL);\n assert(c->rcurr <= (c->rbuf + c->rsize));\n assert(c->rbytes > 0);\n\n if (c->protocol == negotiating_prot || c->transport == udp_transport) {\n if ((unsigned char)c->rbuf[0] == (unsigned char)PROTOCOL_BINARY_REQ) {\n c->protocol = binary_prot;\n } else {\n c->protocol = ascii_prot;\n }\n\n if (settings.verbose > 1) {\n fprintf(stderr, \"%d: Client using the %s protocol\\n\", c->sfd,\n prot_text(c->protocol));\n }\n }\n\n if (c->protocol == binary_prot) {\n /* Do we have the complete packet header? */\n if (c->rbytes < sizeof(c->binary_header)) {\n /* need more data! */\n return 0;\n } else {\n#ifdef NEED_ALIGN\n if (((long)(c->rcurr)) % 8 != 0) {\n /* must realign input buffer */\n memmove(c->rbuf, c->rcurr, c->rbytes);\n c->rcurr = c->rbuf;\n if (settings.verbose > 1) {\n fprintf(stderr, \"%d: Realign input buffer\\n\", c->sfd);\n }\n }\n#endif\n protocol_binary_request_header* req;\n req = (protocol_binary_request_header*)c->rcurr;\n\n if (settings.verbose > 1) {\n /* Dump the packet before we convert it to host order */\n int ii;\n fprintf(stderr, \"<%d Read binary protocol data:\", c->sfd);\n for (ii = 0; ii < sizeof(req->bytes); ++ii) {\n if (ii % 4 == 0) {\n fprintf(stderr, \"\\n<%d \", c->sfd);\n }\n fprintf(stderr, \" 0x%02x\", req->bytes[ii]);\n }\n fprintf(stderr, \"\\n\");\n }\n\n c->binary_header = *req;\n c->binary_header.request.keylen = ntohs(req->request.keylen);\n c->binary_header.request.bodylen = ntohl(req->request.bodylen);\n c->binary_header.request.cas = ntohll(req->request.cas);\n\n if (c->binary_header.request.magic != PROTOCOL_BINARY_REQ) {\n if (settings.verbose) {\n fprintf(stderr, \"Invalid magic: %x\\n\",\n c->binary_header.request.magic);\n }\n conn_set_state(c, conn_closing);\n return -1;\n }\n\n c->msgcurr = 0;\n c->msgused = 0;\n c->iovused = 0;\n if (add_msghdr(c) != 0) {\n out_string(c, \"SERVER_ERROR out of memory\");\n return 0;\n }\n\n c->cmd = c->binary_header.request.opcode;\n c->keylen = c->binary_header.request.keylen;\n c->opaque = c->binary_header.request.opaque;\n /* clear the returned cas value */\n c->cas = 0;\n\n dispatch_bin_command(c);\n\n c->rbytes -= sizeof(c->binary_header);\n c->rcurr += sizeof(c->binary_header);\n }\n } else {\n char *el, *cont;\n\n if (c->rbytes == 0)\n return 0;\n\n el = memchr(c->rcurr, '\\n', c->rbytes);\n if (!el) {\n if (c->rbytes > 1024) {\n /*\n * We didn't have a '\\n' in the first k. This _has_ to be a\n * large multiget, if not we should just nuke the connection.\n */\n char *ptr = c->rcurr;\n while (*ptr == ' ') { /* ignore leading whitespaces */\n ++ptr;\n }\n\n if (strcmp(ptr, \"get \") && strcmp(ptr, \"gets \")) {\n conn_set_state(c, conn_closing);\n return 1;\n }\n }\n\n return 0;\n }\n cont = el + 1;\n if ((el - c->rcurr) > 1 && *(el - 1) == '\\r') {\n el--;\n }\n *el = '\\0';\n\n assert(cont <= (c->rcurr + c->rbytes));\n\n process_command(c, c->rcurr);\n\n c->rbytes -= (cont - c->rcurr);\n c->rcurr = cont;\n\n assert(c->rcurr <= (c->rbuf + c->rsize));\n }\n\n return 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Use strncmp when checking for large ascii multigets.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ZSTD_buildCTable(void* dst, size_t dstCapacity,\n FSE_CTable* nextCTable, U32 FSELog, symbolEncodingType_e type,\n U32* count, U32 max,\n const BYTE* codeTable, size_t nbSeq,\n const S16* defaultNorm, U32 defaultNormLog, U32 defaultMax,\n const FSE_CTable* prevCTable, size_t prevCTableSize,\n void* workspace, size_t workspaceSize)\n{\n BYTE* op = (BYTE*)dst;\n const BYTE* const oend = op + dstCapacity;\n\n switch (type) {\n case set_rle:\n *op = codeTable[0];\n CHECK_F(FSE_buildCTable_rle(nextCTable, (BYTE)max));\n return 1;\n case set_repeat:\n memcpy(nextCTable, prevCTable, prevCTableSize);\n return 0;\n case set_basic:\n CHECK_F(FSE_buildCTable_wksp(nextCTable, defaultNorm, defaultMax, defaultNormLog, workspace, workspaceSize)); /* note : could be pre-calculated */\n return 0;\n case set_compressed: {\n S16 norm[MaxSeq + 1];\n size_t nbSeq_1 = nbSeq;\n const U32 tableLog = FSE_optimalTableLog(FSELog, nbSeq, max);\n if (count[codeTable[nbSeq-1]] > 1) {\n count[codeTable[nbSeq-1]]--;\n nbSeq_1--;\n }\n assert(nbSeq_1 > 1);\n CHECK_F(FSE_normalizeCount(norm, tableLog, count, nbSeq_1, max));\n { size_t const NCountSize = FSE_writeNCount(op, oend - op, norm, max, tableLog); /* overflow protected */\n if (FSE_isError(NCountSize)) return NCountSize;\n CHECK_F(FSE_buildCTable_wksp(nextCTable, norm, max, tableLog, workspace, workspaceSize));\n return NCountSize;\n }\n }\n default: return assert(0), ERROR(GENERIC);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'fixed T36302429'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: QStringList JlCompress::extractDir(QuaZip &zip, const QString &dir)\n{\n if(!zip.open(QuaZip::mdUnzip)) {\n return QStringList();\n }\n\n QDir directory(dir);\n QStringList extracted;\n if (!zip.goToFirstFile()) {\n return QStringList();\n }\n do {\n QString name = zip.getCurrentFileName();\n QString absFilePath = directory.absoluteFilePath(name);\n if (!extractFile(&zip, \"\", absFilePath)) {\n removeFile(extracted);\n return QStringList();\n }\n extracted.append(absFilePath);\n } while (zip.goToNextFile());\n\n // Chiudo il file zip\n zip.close();\n if(zip.getZipError()!=0) {\n removeFile(extracted);\n return QStringList();\n }\n\n return extracted;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-22'], 'message': 'Fixed the Zip Slip vulnerability in JlCompress\n\nWhen extracting a file with a dangerous path like \"../evil.exe\"\nfrom a ZIP archive with JlCompress::extractDir(), the target\nfile would be created outside of the target directory, potentially\neven overwriting an existing file there.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: Status SparseCountSparseOutputShapeFn(InferenceContext *c) {\n auto rank = c->Dim(c->input(0), 1);\n auto nvals = c->UnknownDim();\n c->set_output(0, c->Matrix(nvals, rank)); // out.indices\n c->set_output(1, c->Vector(nvals)); // out.values\n c->set_output(2, c->Vector(rank)); // out.dense_shape\n return Status::OK();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix heap out of bounds error in tf.raw_ops.SparseCountSparseOutput shape inference when it is called with invalid inputs, and add a test for it.\n\nPiperOrigin-RevId: 405766415\nChange-Id: I77d244ef35f351ef7b6f821efd959cac2c66db24'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void Compute(OpKernelContext* ctx) final {\n // Extract inputs and validate shapes and types.\n const CSRSparseMatrix* input_matrix;\n OP_REQUIRES_OK(ctx, ExtractVariantFromInput(ctx, 0, &input_matrix));\n const Tensor& input_permutation_indices = ctx->input(1);\n\n int64 num_rows;\n int batch_size;\n ValidateInputs(ctx, *input_matrix, input_permutation_indices, &batch_size,\n &num_rows);\n\n // Allocate batch pointers.\n Tensor batch_ptr(cpu_allocator(), DT_INT32, TensorShape({batch_size + 1}));\n auto batch_ptr_vec = batch_ptr.vec();\n batch_ptr_vec(0) = 0;\n\n // Temporary vector of Eigen SparseMatrices to store the Sparse Cholesky\n // factors.\n // Note: we use column-compressed (CSC) SparseMatrix because SimplicialLLT\n // returns the factors in column major format. Since our input should be\n // symmetric, column major and row major is identical in storage. We just\n // have to switch to reading the upper triangular part of the input, which\n // corresponds to the lower triangular part in row major format.\n std::vector sparse_cholesky_factors(batch_size);\n\n // TODO(anudhyan): Tune the cost per unit based on benchmarks.\n const double nnz_per_row =\n (input_matrix->total_nnz() / batch_size) / num_rows;\n const int64 sparse_cholesky_cost_per_batch =\n nnz_per_row * nnz_per_row * num_rows;\n // Perform sparse Cholesky factorization of each batch in parallel.\n auto worker_threads = *(ctx->device()->tensorflow_cpu_worker_threads());\n std::atomic invalid_input_index(-1);\n Shard(worker_threads.num_threads, worker_threads.workers, batch_size,\n sparse_cholesky_cost_per_batch,\n [&](int64 batch_begin, int64 batch_end) {\n for (int64 batch_index = batch_begin; batch_index < batch_end;\n ++batch_index) {\n // Define an Eigen SparseMatrix Map to operate on the\n // CSRSparseMatrix component without copying the data.\n Eigen::Map sparse_matrix(\n num_rows, num_rows, input_matrix->nnz(batch_index),\n input_matrix->row_pointers_vec(batch_index).data(),\n input_matrix->col_indices_vec(batch_index).data(),\n input_matrix->values_vec(batch_index).data());\n\n Eigen::SimplicialLLT>\n solver;\n auto permutation_indices_flat =\n input_permutation_indices.flat().data();\n\n // Invert the fill-in reducing ordering and apply it to the input\n // sparse matrix.\n Eigen::Map<\n Eigen::PermutationMatrix>\n permutation(permutation_indices_flat + batch_index * num_rows,\n num_rows);\n auto permutation_inverse = permutation.inverse();\n\n SparseMatrix permuted_sparse_matrix;\n permuted_sparse_matrix.template selfadjointView() =\n sparse_matrix.template selfadjointView()\n .twistedBy(permutation_inverse);\n\n // Compute the Cholesky decomposition.\n solver.compute(permuted_sparse_matrix);\n if (solver.info() != Eigen::Success) {\n invalid_input_index = batch_index;\n return;\n }\n\n // Get the upper triangular factor, which would end up in the\n // lower triangular part of the output CSRSparseMatrix when\n // interpreted in row major format.\n sparse_cholesky_factors[batch_index] =\n std::move(solver.matrixU());\n // For now, batch_ptr contains the number of nonzeros in each\n // batch.\n batch_ptr_vec(batch_index + 1) =\n sparse_cholesky_factors[batch_index].nonZeros();\n }\n });\n\n // Check for invalid input.\n OP_REQUIRES(\n ctx, invalid_input_index == -1,\n errors::InvalidArgument(\n \"Sparse Cholesky factorization failed for batch index \",\n invalid_input_index.load(), \". The input might not be valid.\"));\n\n // Compute a cumulative sum to obtain the batch pointers.\n std::partial_sum(batch_ptr_vec.data(),\n batch_ptr_vec.data() + batch_size + 1,\n batch_ptr_vec.data());\n\n // Allocate output Tensors.\n const int64 total_nnz = batch_ptr_vec(batch_size);\n Tensor output_row_ptr(cpu_allocator(), DT_INT32,\n TensorShape({(num_rows + 1) * batch_size}));\n Tensor output_col_ind(cpu_allocator(), DT_INT32, TensorShape({total_nnz}));\n Tensor output_values(cpu_allocator(), DataTypeToEnum::value,\n TensorShape({total_nnz}));\n auto output_row_ptr_ptr = output_row_ptr.flat().data();\n auto output_col_ind_ptr = output_col_ind.flat().data();\n auto output_values_ptr = output_values.flat().data();\n\n // Copy the output matrices from each batch into the CSRSparseMatrix\n // Tensors.\n // TODO(b/129906419): Factor out the copy from Eigen SparseMatrix to\n // CSRSparseMatrix into common utils. This is also used in\n // SparseMatrixSparseMatMul.\n Shard(worker_threads.num_threads, worker_threads.workers, batch_size,\n (3 * total_nnz) / batch_size /* cost per unit */,\n [&](int64 batch_begin, int64 batch_end) {\n for (int64 batch_index = batch_begin; batch_index < batch_end;\n ++batch_index) {\n const SparseMatrix& cholesky_factor =\n sparse_cholesky_factors[batch_index];\n const int64 nnz = cholesky_factor.nonZeros();\n\n std::copy(cholesky_factor.outerIndexPtr(),\n cholesky_factor.outerIndexPtr() + num_rows + 1,\n output_row_ptr_ptr + batch_index * (num_rows + 1));\n std::copy(cholesky_factor.innerIndexPtr(),\n cholesky_factor.innerIndexPtr() + nnz,\n output_col_ind_ptr + batch_ptr_vec(batch_index));\n std::copy(cholesky_factor.valuePtr(),\n cholesky_factor.valuePtr() + nnz,\n output_values_ptr + batch_ptr_vec(batch_index));\n }\n });\n\n // Create the CSRSparseMatrix instance from its component Tensors and\n // prepare the Variant output Tensor.\n CSRSparseMatrix output_csr_matrix;\n OP_REQUIRES_OK(\n ctx,\n CSRSparseMatrix::CreateCSRSparseMatrix(\n DataTypeToEnum::value, input_matrix->dense_shape(), batch_ptr,\n output_row_ptr, output_col_ind, output_values, &output_csr_matrix));\n Tensor* output_csr_matrix_tensor;\n AllocatorAttributes cpu_alloc;\n cpu_alloc.set_on_host(true);\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(0, TensorShape({}), &output_csr_matrix_tensor,\n cpu_alloc));\n output_csr_matrix_tensor->scalar()() =\n std::move(output_csr_matrix);\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Remove `OP_REQUIRES` call from helper function.\n\nSince `OP_REQUIRES` macro expands to a `return;` (among other), calling it in a helper function only ends the helper function's execution earlier, but the kernel will still run from start to end. Thus, all the expected validations are actually broken/useless as the code ploughs through the next crash anyway.\n\nPiperOrigin-RevId: 369524386\nChange-Id: I54f6cf9328445675ccc392e661b04336b229c9da'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void __detach_mounts(struct dentry *dentry)\n{\n\tstruct mountpoint *mp;\n\tstruct mount *mnt;\n\n\tnamespace_lock();\n\tmp = lookup_mountpoint(dentry);\n\tif (!mp)\n\t\tgoto out_unlock;\n\n\tlock_mount_hash();\n\twhile (!hlist_empty(&mp->m_list)) {\n\t\tmnt = hlist_entry(mp->m_list.first, struct mount, mnt_mp_list);\n\t\tumount_tree(mnt, 0);\n\t}\n\tunlock_mount_hash();\n\tput_mountpoint(mp);\nout_unlock:\n\tnamespace_unlock();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284'], 'message': 'mnt: Honor MNT_LOCKED when detaching mounts\n\nModify umount(MNT_DETACH) to keep mounts in the hash table that are\nlocked to their parent mounts, when the parent is lazily unmounted.\n\nIn mntput_no_expire detach the children from the hash table, depending\non mnt_pin_kill in cleanup_mnt to decrement the mnt_count of the children.\n\nIn __detach_mounts if there are any mounts that have been unmounted\nbut still are on the list of mounts of a mountpoint, remove their\nchildren from the mount hash table and those children to the unmounted\nlist so they won't linger potentially indefinitely waiting for their\nfinal mntput, now that the mounts serve no purpose.\n\nCc: stable@vger.kernel.org\nSigned-off-by: \"Eric W. Biederman\" '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline int ip6_ufo_append_data(struct sock *sk,\n\t\t\tint getfrag(void *from, char *to, int offset, int len,\n\t\t\tint odd, struct sk_buff *skb),\n\t\t\tvoid *from, int length, int hh_len, int fragheaderlen,\n\t\t\tint transhdrlen, int mtu,unsigned int flags)\n\n{\n\tstruct sk_buff *skb;\n\tint err;\n\n\t/* There is support for UDP large send offload by network\n\t * device, so create one single skb packet containing complete\n\t * udp datagram\n\t */\n\tif ((skb = skb_peek_tail(&sk->sk_write_queue)) == NULL) {\n\t\tskb = sock_alloc_send_skb(sk,\n\t\t\thh_len + fragheaderlen + transhdrlen + 20,\n\t\t\t(flags & MSG_DONTWAIT), &err);\n\t\tif (skb == NULL)\n\t\t\treturn -ENOMEM;\n\n\t\t/* reserve space for Hardware header */\n\t\tskb_reserve(skb, hh_len);\n\n\t\t/* create space for UDP/IP header */\n\t\tskb_put(skb,fragheaderlen + transhdrlen);\n\n\t\t/* initialize network header pointer */\n\t\tskb_reset_network_header(skb);\n\n\t\t/* initialize protocol header pointer */\n\t\tskb->transport_header = skb->network_header + fragheaderlen;\n\n\t\tskb->ip_summed = CHECKSUM_PARTIAL;\n\t\tskb->csum = 0;\n\t}\n\n\terr = skb_append_datato_frags(sk,skb, getfrag, from,\n\t\t\t\t (length - transhdrlen));\n\tif (!err) {\n\t\tstruct frag_hdr fhdr;\n\n\t\t/* Specify the length of each IPv6 datagram fragment.\n\t\t * It has to be a multiple of 8.\n\t\t */\n\t\tskb_shinfo(skb)->gso_size = (mtu - fragheaderlen -\n\t\t\t\t\t sizeof(struct frag_hdr)) & ~7;\n\t\tskb_shinfo(skb)->gso_type = SKB_GSO_UDP;\n\t\tipv6_select_ident(&fhdr);\n\t\tskb_shinfo(skb)->ip6_frag_id = fhdr.identification;\n\t\t__skb_queue_tail(&sk->sk_write_queue, skb);\n\n\t\treturn 0;\n\t}\n\t/* There is not enough support do UPD LSO,\n\t * so follow normal path\n\t */\n\tkfree_skb(skb);\n\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'ipv6: make fragment identifications less predictable\n\nIPv6 fragment identification generation is way beyond what we use for\nIPv4 : It uses a single generator. Its not scalable and allows DOS\nattacks.\n\nNow inetpeer is IPv6 aware, we can use it to provide a more secure and\nscalable frag ident generator (per destination, instead of system wide)\n\nThis patch :\n1) defines a new secure_ipv6_id() helper\n2) extends inet_getid() to provide 32bit results\n3) extends ipv6_select_ident() with a new dest parameter\n\nReported-by: Fernando Gont \nSigned-off-by: Eric Dumazet \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int stellaris_enet_load(QEMUFile *f, void *opaque, int version_id)\n{\n stellaris_enet_state *s = (stellaris_enet_state *)opaque;\n int i;\n\n if (version_id != 1)\n return -EINVAL;\n\n s->ris = qemu_get_be32(f);\n s->im = qemu_get_be32(f);\n s->rctl = qemu_get_be32(f);\n s->tctl = qemu_get_be32(f);\n s->thr = qemu_get_be32(f);\n s->mctl = qemu_get_be32(f);\n s->mdv = qemu_get_be32(f);\n s->mtxd = qemu_get_be32(f);\n s->mrxd = qemu_get_be32(f);\n s->np = qemu_get_be32(f);\n s->tx_fifo_len = qemu_get_be32(f);\n qemu_get_buffer(f, s->tx_fifo, sizeof(s->tx_fifo));\n for (i = 0; i < 31; i++) {\n s->rx[i].len = qemu_get_be32(f);\n qemu_get_buffer(f, s->rx[i].data, sizeof(s->rx[i].data));\n\n }\n s->next_packet = qemu_get_be32(f);\n s->rx_fifo_offset = qemu_get_be32(f);\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'hw/net/stellaris_enet: Convert to vmstate\n\nConvert this device to use vmstate for its save/load, including\nproviding a post_load function that sanitizes inbound data to\navoid possible buffer overflows if it is malicious.\n\nThe sanitizing fixes CVE-2013-4532 (though nobody should be\nrelying on the security properties of most of the unmaintained\nARM board models anyway, and migration doesn't actually\nwork on this board due to issues in other device models).\n\nSigned-off-by: Peter Maydell \nReviewed-by: Dr. David Alan Gilbert \nReviewed-by: Michael S. Tsirkin '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: CreateSchemaCommand(CreateSchemaStmt *stmt, const char *queryString,\n\t\t\t\t\tint stmt_location, int stmt_len)\n{\n\tconst char *schemaName = stmt->schemaname;\n\tOid\t\t\tnamespaceId;\n\tOverrideSearchPath *overridePath;\n\tList\t *parsetree_list;\n\tListCell *parsetree_item;\n\tOid\t\t\towner_uid;\n\tOid\t\t\tsaved_uid;\n\tint\t\t\tsave_sec_context;\n\tAclResult\taclresult;\n\tObjectAddress address;\n\n\tGetUserIdAndSecContext(&saved_uid, &save_sec_context);\n\n\t/*\n\t * Who is supposed to own the new schema?\n\t */\n\tif (stmt->authrole)\n\t\towner_uid = get_rolespec_oid(stmt->authrole, false);\n\telse\n\t\towner_uid = saved_uid;\n\n\t/* fill schema name with the user name if not specified */\n\tif (!schemaName)\n\t{\n\t\tHeapTuple\ttuple;\n\n\t\ttuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(owner_uid));\n\t\tif (!HeapTupleIsValid(tuple))\n\t\t\telog(ERROR, \"cache lookup failed for role %u\", owner_uid);\n\t\tschemaName =\n\t\t\tpstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));\n\t\tReleaseSysCache(tuple);\n\t}\n\n\t/*\n\t * To create a schema, must have schema-create privilege on the current\n\t * database and must be able to become the target role (this does not\n\t * imply that the target role itself must have create-schema privilege).\n\t * The latter provision guards against \"giveaway\" attacks. Note that a\n\t * superuser will always have both of these privileges a fortiori.\n\t */\n\taclresult = pg_database_aclcheck(MyDatabaseId, saved_uid, ACL_CREATE);\n\tif (aclresult != ACLCHECK_OK)\n\t\taclcheck_error(aclresult, ACL_KIND_DATABASE,\n\t\t\t\t\t get_database_name(MyDatabaseId));\n\n\tcheck_is_member_of_role(saved_uid, owner_uid);\n\n\t/* Additional check to protect reserved schema names */\n\tif (!allowSystemTableMods && IsReservedName(schemaName))\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_RESERVED_NAME),\n\t\t\t\t errmsg(\"unacceptable schema name \\\"%s\\\"\", schemaName),\n\t\t\t\t errdetail(\"The prefix \\\"pg_\\\" is reserved for system schemas.\")));\n\n\t/*\n\t * If if_not_exists was given and the schema already exists, bail out.\n\t * (Note: we needn't check this when not if_not_exists, because\n\t * NamespaceCreate will complain anyway.) We could do this before making\n\t * the permissions checks, but since CREATE TABLE IF NOT EXISTS makes its\n\t * creation-permission check first, we do likewise.\n\t */\n\tif (stmt->if_not_exists &&\n\t\tSearchSysCacheExists1(NAMESPACENAME, PointerGetDatum(schemaName)))\n\t{\n\t\tereport(NOTICE,\n\t\t\t\t(errcode(ERRCODE_DUPLICATE_SCHEMA),\n\t\t\t\t errmsg(\"schema \\\"%s\\\" already exists, skipping\",\n\t\t\t\t\t\tschemaName)));\n\t\treturn InvalidOid;\n\t}\n\n\t/*\n\t * If the requested authorization is different from the current user,\n\t * temporarily set the current user so that the object(s) will be created\n\t * with the correct ownership.\n\t *\n\t * (The setting will be restored at the end of this routine, or in case of\n\t * error, transaction abort will clean things up.)\n\t */\n\tif (saved_uid != owner_uid)\n\t\tSetUserIdAndSecContext(owner_uid,\n\t\t\t\t\t\t\t save_sec_context | SECURITY_LOCAL_USERID_CHANGE);\n\n\t/* Create the schema's namespace */\n\tnamespaceId = NamespaceCreate(schemaName, owner_uid, false);\n\n\t/* Advance cmd counter to make the namespace visible */\n\tCommandCounterIncrement();\n\n\t/*\n\t * Temporarily make the new namespace be the front of the search path, as\n\t * well as the default creation target namespace. This will be undone at\n\t * the end of this routine, or upon error.\n\t */\n\toverridePath = GetOverrideSearchPath(CurrentMemoryContext);\n\toverridePath->schemas = lcons_oid(namespaceId, overridePath->schemas);\n\t/* XXX should we clear overridePath->useTemp? */\n\tPushOverrideSearchPath(overridePath);\n\n\t/*\n\t * Report the new schema to possibly interested event triggers. Note we\n\t * must do this here and not in ProcessUtilitySlow because otherwise the\n\t * objects created below are reported before the schema, which would be\n\t * wrong.\n\t */\n\tObjectAddressSet(address, NamespaceRelationId, namespaceId);\n\tEventTriggerCollectSimpleCommand(address, InvalidObjectAddress,\n\t\t\t\t\t\t\t\t\t (Node *) stmt);\n\n\t/*\n\t * Examine the list of commands embedded in the CREATE SCHEMA command, and\n\t * reorganize them into a sequentially executable order with no forward\n\t * references. Note that the result is still a list of raw parsetrees ---\n\t * we cannot, in general, run parse analysis on one statement until we\n\t * have actually executed the prior ones.\n\t */\n\tparsetree_list = transformCreateSchemaStmt(stmt);\n\n\t/*\n\t * Execute each command contained in the CREATE SCHEMA. Since the grammar\n\t * allows only utility commands in CREATE SCHEMA, there is no need to pass\n\t * them through parse_analyze() or the rewriter; we can just hand them\n\t * straight to ProcessUtility.\n\t */\n\tforeach(parsetree_item, parsetree_list)\n\t{\n\t\tNode\t *stmt = (Node *) lfirst(parsetree_item);\n\t\tPlannedStmt *wrapper;\n\n\t\t/* need to make a wrapper PlannedStmt */\n\t\twrapper = makeNode(PlannedStmt);\n\t\twrapper->commandType = CMD_UTILITY;\n\t\twrapper->canSetTag = false;\n\t\twrapper->utilityStmt = stmt;\n\t\twrapper->stmt_location = stmt_location;\n\t\twrapper->stmt_len = stmt_len;\n\n\t\t/* do this step */\n\t\tProcessUtility(wrapper,\n\t\t\t\t\t queryString,\n\t\t\t\t\t PROCESS_UTILITY_SUBCOMMAND,\n\t\t\t\t\t NULL,\n\t\t\t\t\t NULL,\n\t\t\t\t\t None_Receiver,\n\t\t\t\t\t NULL);\n\n\t\t/* make sure later steps can see the object created here */\n\t\tCommandCounterIncrement();\n\t}\n\n\t/* Reset search path to normal state */\n\tPopOverrideSearchPath();\n\n\t/* Reset current user and security context */\n\tSetUserIdAndSecContext(saved_uid, save_sec_context);\n\n\treturn namespaceId;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-94'], 'message': 'In extensions, don't replace objects not belonging to the extension.\n\nPreviously, if an extension script did CREATE OR REPLACE and there was\nan existing object not belonging to the extension, it would overwrite\nthe object and adopt it into the extension. This is problematic, first\nbecause the overwrite is probably unintentional, and second because we\ndidn't change the object's ownership. Thus a hostile user could create\nan object in advance of an expected CREATE EXTENSION command, and would\nthen have ownership rights on an extension object, which could be\nmodified for trojan-horse-type attacks.\n\nHence, forbid CREATE OR REPLACE of an existing object unless it already\nbelongs to the extension. (Note that we've always forbidden replacing\nan object that belongs to some other extension; only the behavior for\npreviously-free-standing objects changes here.)\n\nFor the same reason, also fail CREATE IF NOT EXISTS when there is\nan existing object that doesn't belong to the extension.\n\nOur thanks to Sven Klemm for reporting this problem.\n\nSecurity: CVE-2022-2625'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int dxtory_decode_v1_410(AVCodecContext *avctx, AVFrame *pic,\n const uint8_t *src, int src_size)\n{\n int h, w;\n uint8_t *Y1, *Y2, *Y3, *Y4, *U, *V;\n int ret;\n\n if (src_size < avctx->width * avctx->height * 18 / 16) {\n av_log(avctx, AV_LOG_ERROR, \"packet too small\\n\");\n return AVERROR_INVALIDDATA;\n }\n\n avctx->pix_fmt = AV_PIX_FMT_YUV410P;\n if ((ret = ff_get_buffer(avctx, pic, 0)) < 0)\n return ret;\n\n Y1 = pic->data[0];\n Y2 = pic->data[0] + pic->linesize[0];\n Y3 = pic->data[0] + pic->linesize[0] * 2;\n Y4 = pic->data[0] + pic->linesize[0] * 3;\n U = pic->data[1];\n V = pic->data[2];\n for (h = 0; h < avctx->height; h += 4) {\n for (w = 0; w < avctx->width; w += 4) {\n AV_COPY32(Y1 + w, src);\n AV_COPY32(Y2 + w, src + 4);\n AV_COPY32(Y3 + w, src + 8);\n AV_COPY32(Y4 + w, src + 12);\n U[w >> 2] = src[16] + 0x80;\n V[w >> 2] = src[17] + 0x80;\n src += 18;\n }\n Y1 += pic->linesize[0] << 2;\n Y2 += pic->linesize[0] << 2;\n Y3 += pic->linesize[0] << 2;\n Y4 += pic->linesize[0] << 2;\n U += pic->linesize[1];\n V += pic->linesize[2];\n }\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'avcodec/dxtory: fix src size checks\n\nFixes integer overflow\nFixes out of array read\nFixes: d104661bb59b202df7671fb19a00ca6c-asan_heap-oob_d6429d_5066_cov_1729501105_dxtory_mic.avi\nFound-by: Mateusz \"j00ru\" Jurczyk and Gynvael Coldwind\nSigned-off-by: Michael Niedermayer '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int descriptor_modify(struct ldb_module *module, struct ldb_request *req)\n{\n\tstruct ldb_context *ldb = ldb_module_get_ctx(module);\n\tstruct ldb_request *mod_req;\n\tstruct ldb_message *msg;\n\tstruct ldb_result *current_res, *parent_res;\n\tconst struct ldb_val *old_sd = NULL;\n\tconst struct ldb_val *parent_sd = NULL;\n\tconst struct ldb_val *user_sd;\n\tstruct ldb_dn *dn = req->op.mod.message->dn;\n\tstruct ldb_dn *parent_dn;\n\tstruct ldb_message_element *objectclass_element, *sd_element;\n\tint ret;\n\tuint32_t instanceType;\n\tbool explicit_sd_flags = false;\n\tuint32_t sd_flags = dsdb_request_sd_flags(req, &explicit_sd_flags);\n\tconst struct dsdb_schema *schema;\n\tDATA_BLOB *sd;\n\tconst struct dsdb_class *objectclass;\n\tstatic const char * const parent_attrs[] = { \"nTSecurityDescriptor\", NULL };\n\tstatic const char * const current_attrs[] = { \"nTSecurityDescriptor\",\n\t\t\t\t\t\t \"instanceType\",\n\t\t\t\t\t\t \"objectClass\", NULL };\n\tstruct GUID parent_guid = { .time_low = 0 };\n\tstruct ldb_control *sd_propagation_control;\n\tint cmp_ret = -1;\n\n\t/* do not manipulate our control entries */\n\tif (ldb_dn_is_special(dn)) {\n\t\treturn ldb_next_request(module, req);\n\t}\n\n\tsd_propagation_control = ldb_request_get_control(req,\n\t\t\t\t\tDSDB_CONTROL_SEC_DESC_PROPAGATION_OID);\n\tif (sd_propagation_control != NULL) {\n\t\tif (sd_propagation_control->data != module) {\n\t\t\treturn ldb_operr(ldb);\n\t\t}\n\t\tif (req->op.mod.message->num_elements != 0) {\n\t\t\treturn ldb_operr(ldb);\n\t\t}\n\t\tif (explicit_sd_flags) {\n\t\t\treturn ldb_operr(ldb);\n\t\t}\n\t\tif (sd_flags != 0xF) {\n\t\t\treturn ldb_operr(ldb);\n\t\t}\n\t\tif (sd_propagation_control->critical == 0) {\n\t\t\treturn ldb_operr(ldb);\n\t\t}\n\n\t\tsd_propagation_control->critical = 0;\n\t}\n\n\tsd_element = ldb_msg_find_element(req->op.mod.message, \"nTSecurityDescriptor\");\n\tif (sd_propagation_control == NULL && sd_element == NULL) {\n\t\treturn ldb_next_request(module, req);\n\t}\n\n\t/*\n\t * nTSecurityDescriptor with DELETE is not supported yet.\n\t * TODO: handle this correctly.\n\t */\n\tif (sd_propagation_control == NULL &&\n\t LDB_FLAG_MOD_TYPE(sd_element->flags) == LDB_FLAG_MOD_DELETE)\n\t{\n\t\treturn ldb_module_error(module,\n\t\t\t\t\tLDB_ERR_UNWILLING_TO_PERFORM,\n\t\t\t\t\t\"MOD_DELETE for nTSecurityDescriptor \"\n\t\t\t\t\t\"not supported yet\");\n\t}\n\n\tuser_sd = ldb_msg_find_ldb_val(req->op.mod.message, \"nTSecurityDescriptor\");\n\t/* nTSecurityDescriptor without a value is an error, letting through so it is handled */\n\tif (sd_propagation_control == NULL && user_sd == NULL) {\n\t\treturn ldb_next_request(module, req);\n\t}\n\n\tldb_debug(ldb, LDB_DEBUG_TRACE,\"descriptor_modify: %s\\n\", ldb_dn_get_linearized(dn));\n\n\tret = dsdb_module_search_dn(module, req, ¤t_res, dn,\n\t\t\t\t current_attrs,\n\t\t\t\t DSDB_FLAG_NEXT_MODULE |\n\t\t\t\t DSDB_FLAG_AS_SYSTEM |\n\t\t\t\t DSDB_SEARCH_SHOW_RECYCLED |\n\t\t\t\t DSDB_SEARCH_SHOW_EXTENDED_DN,\n\t\t\t\t req);\n\tif (ret != LDB_SUCCESS) {\n\t\tldb_debug(ldb, LDB_DEBUG_ERROR,\"descriptor_modify: Could not find %s\\n\",\n\t\t\t ldb_dn_get_linearized(dn));\n\t\treturn ret;\n\t}\n\n\tinstanceType = ldb_msg_find_attr_as_uint(current_res->msgs[0],\n\t\t\t\t\t\t \"instanceType\", 0);\n\t/* if the object has a parent, retrieve its SD to\n\t * use for calculation */\n\tif (!ldb_dn_is_null(current_res->msgs[0]->dn) &&\n\t !(instanceType & INSTANCE_TYPE_IS_NC_HEAD)) {\n\t\tNTSTATUS status;\n\n\t\tparent_dn = ldb_dn_get_parent(req, dn);\n\t\tif (parent_dn == NULL) {\n\t\t\treturn ldb_oom(ldb);\n\t\t}\n\t\tret = dsdb_module_search_dn(module, req, &parent_res, parent_dn,\n\t\t\t\t\t parent_attrs,\n\t\t\t\t\t DSDB_FLAG_NEXT_MODULE |\n\t\t\t\t\t DSDB_FLAG_AS_SYSTEM |\n\t\t\t\t\t DSDB_SEARCH_SHOW_RECYCLED |\n\t\t\t\t\t DSDB_SEARCH_SHOW_EXTENDED_DN,\n\t\t\t\t\t req);\n\t\tif (ret != LDB_SUCCESS) {\n\t\t\tldb_debug(ldb, LDB_DEBUG_ERROR, \"descriptor_modify: Could not find SD for %s\\n\",\n\t\t\t\t ldb_dn_get_linearized(parent_dn));\n\t\t\treturn ret;\n\t\t}\n\t\tif (parent_res->count != 1) {\n\t\t\treturn ldb_operr(ldb);\n\t\t}\n\t\tparent_sd = ldb_msg_find_ldb_val(parent_res->msgs[0], \"nTSecurityDescriptor\");\n\n\t\tstatus = dsdb_get_extended_dn_guid(parent_res->msgs[0]->dn,\n\t\t\t\t\t\t &parent_guid,\n\t\t\t\t\t\t \"GUID\");\n\t\tif (!NT_STATUS_IS_OK(status)) {\n\t\t\treturn ldb_operr(ldb);\n\t\t}\n\t}\n\n\tschema = dsdb_get_schema(ldb, req);\n\n\tobjectclass_element = ldb_msg_find_element(current_res->msgs[0], \"objectClass\");\n\tif (objectclass_element == NULL) {\n\t\treturn ldb_operr(ldb);\n\t}\n\n\tobjectclass = dsdb_get_last_structural_class(schema,\n\t\t\t\t\t\t objectclass_element);\n\tif (objectclass == NULL) {\n\t\treturn ldb_operr(ldb);\n\t}\n\n\told_sd = ldb_msg_find_ldb_val(current_res->msgs[0], \"nTSecurityDescriptor\");\n\tif (old_sd == NULL) {\n\t\treturn ldb_operr(ldb);\n\t}\n\n\tif (sd_propagation_control != NULL) {\n\t\t/*\n\t\t * This just triggers a recalculation of the\n\t\t * inherited aces.\n\t\t */\n\t\tuser_sd = old_sd;\n\t}\n\n\tsd = get_new_descriptor(module, current_res->msgs[0]->dn, req,\n\t\t\t\tobjectclass, parent_sd,\n\t\t\t\tuser_sd, old_sd, sd_flags);\n\tif (sd == NULL) {\n\t\treturn ldb_operr(ldb);\n\t}\n\tmsg = ldb_msg_copy_shallow(req, req->op.mod.message);\n\tif (msg == NULL) {\n\t\treturn ldb_oom(ldb);\n\t}\n\tcmp_ret = data_blob_cmp(old_sd, sd);\n\tif (sd_propagation_control != NULL) {\n\t\tif (cmp_ret == 0) {\n\t\t\t/*\n\t\t\t * The nTSecurityDescriptor is unchanged,\n\t\t\t * which means we can stop the processing.\n\t\t\t *\n\t\t\t * We mark the control as critical again,\n\t\t\t * as we have not processed it, so the caller\n\t\t\t * can tell that the descriptor was unchanged.\n\t\t\t */\n\t\t\tsd_propagation_control->critical = 1;\n\t\t\treturn ldb_module_done(req, NULL, NULL, LDB_SUCCESS);\n\t\t}\n\n\t\tret = ldb_msg_add_empty(msg, \"nTSecurityDescriptor\",\n\t\t\t\t\tLDB_FLAG_MOD_REPLACE,\n\t\t\t\t\t&sd_element);\n\t\tif (ret != LDB_SUCCESS) {\n\t\t\treturn ldb_oom(ldb);\n\t\t}\n\t\tret = ldb_msg_add_value(msg, \"nTSecurityDescriptor\",\n\t\t\t\t\tsd, NULL);\n\t\tif (ret != LDB_SUCCESS) {\n\t\t\treturn ldb_oom(ldb);\n\t\t}\n\t} else if (cmp_ret != 0) {\n\t\tstruct GUID guid;\n\t\tstruct ldb_dn *nc_root;\n\t\tNTSTATUS status;\n\n\t\tret = dsdb_find_nc_root(ldb,\n\t\t\t\t\tmsg,\n\t\t\t\t\tcurrent_res->msgs[0]->dn,\n\t\t\t\t\t&nc_root);\n\t\tif (ret != LDB_SUCCESS) {\n\t\t\treturn ldb_oom(ldb);\n\t\t}\n\n\t\tstatus = dsdb_get_extended_dn_guid(current_res->msgs[0]->dn,\n\t\t\t\t\t\t &guid,\n\t\t\t\t\t\t \"GUID\");\n\t\tif (!NT_STATUS_IS_OK(status)) {\n\t\t\treturn ldb_operr(ldb);\n\t\t}\n\n\t\t/*\n\t\t * Force SD propagation on children of this record\n\t\t */\n\t\tret = dsdb_module_schedule_sd_propagation(module,\n\t\t\t\t\t\t\t nc_root,\n\t\t\t\t\t\t\t guid,\n\t\t\t\t\t\t\t parent_guid,\n\t\t\t\t\t\t\t false);\n\t\tif (ret != LDB_SUCCESS) {\n\t\t\treturn ldb_operr(ldb);\n\t\t}\n\t\tsd_element->values[0] = *sd;\n\t} else {\n\t\tsd_element->values[0] = *sd;\n\t}\n\n\tret = ldb_build_mod_req(&mod_req, ldb, req,\n\t\t\t\tmsg,\n\t\t\t\treq->controls,\n\t\t\t\treq,\n\t\t\t\tdsdb_next_callback,\n\t\t\t\treq);\n\tLDB_REQ_SET_LOCATION(mod_req);\n\tif (ret != LDB_SUCCESS) {\n\t\treturn ret;\n\t}\n\n\treturn ldb_next_request(module, mod_req);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'CVE-2022-32746 ldb: Make use of functions for appending to an ldb_message\n\nThis aims to minimise usage of the error-prone pattern of searching for\na just-added message element in order to make modifications to it (and\npotentially finding the wrong element).\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=15009\n\nSigned-off-by: Joseph Sutton '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int samldb_user_account_control_change(struct samldb_ctx *ac)\n{\n\tstruct ldb_context *ldb = ldb_module_get_ctx(ac->module);\n\tuint32_t old_uac;\n\tuint32_t new_uac;\n\tuint32_t raw_uac;\n\tuint32_t old_ufa;\n\tuint32_t new_ufa;\n\tuint32_t old_uac_computed;\n\tuint32_t clear_uac;\n\tuint32_t old_atype;\n\tuint32_t new_atype;\n\tuint32_t old_pgrid;\n\tuint32_t new_pgrid;\n\tNTTIME old_lockoutTime;\n\tstruct ldb_message_element *el;\n\tstruct ldb_val *val;\n\tstruct ldb_val computer_val;\n\tstruct ldb_message *tmp_msg;\n\tstruct dom_sid *sid;\n\tint ret;\n\tstruct ldb_result *res;\n\tconst char * const attrs[] = {\n\t\t\"objectClass\",\n\t\t\"isCriticalSystemObject\",\n\t\t\"userAccountControl\",\n\t\t\"msDS-User-Account-Control-Computed\",\n\t\t\"lockoutTime\",\n\t\t\"objectSid\",\n\t\tNULL\n\t};\n\tbool is_computer_objectclass = false;\n\tbool old_is_critical = false;\n\tbool new_is_critical = false;\n\n\tret = dsdb_get_expected_new_values(ac,\n\t\t\t\t\t ac->msg,\n\t\t\t\t\t \"userAccountControl\",\n\t\t\t\t\t &el,\n\t\t\t\t\t ac->req->operation);\n\tif (ret != LDB_SUCCESS) {\n\t\treturn ret;\n\t}\n\n\tif (el == NULL || el->num_values == 0) {\n\t\tldb_asprintf_errstring(ldb,\n\t\t\t\"%08X: samldb: 'userAccountControl' can't be deleted!\",\n\t\t\tW_ERROR_V(WERR_DS_ILLEGAL_MOD_OPERATION));\n\t\treturn LDB_ERR_UNWILLING_TO_PERFORM;\n\t}\n\n\t/* Create a temporary message for fetching the \"userAccountControl\" */\n\ttmp_msg = ldb_msg_new(ac->msg);\n\tif (tmp_msg == NULL) {\n\t\treturn ldb_module_oom(ac->module);\n\t}\n\tret = ldb_msg_add(tmp_msg, el, 0);\n\tif (ret != LDB_SUCCESS) {\n\t\treturn ret;\n\t}\n\traw_uac = ldb_msg_find_attr_as_uint(tmp_msg,\n\t\t\t\t\t \"userAccountControl\",\n\t\t\t\t\t 0);\n\ttalloc_free(tmp_msg);\n\t/*\n\t * UF_LOCKOUT, UF_PASSWD_CANT_CHANGE and UF_PASSWORD_EXPIRED\n\t * are only generated and not stored. We ignore them almost\n\t * completely, along with unknown bits and UF_SCRIPT.\n\t *\n\t * The only exception is ACB_AUTOLOCK, which features in\n\t * clear_acb when the bit is cleared in this modify operation.\n\t *\n\t * MS-SAMR 2.2.1.13 UF_FLAG Codes states that some bits are\n\t * ignored by clients and servers\n\t */\n\tnew_uac = raw_uac & UF_SETTABLE_BITS;\n\n\t/* Fetch the old \"userAccountControl\" and \"objectClass\" */\n\tret = dsdb_module_search_dn(ac->module, ac, &res, ac->msg->dn, attrs,\n\t\t\t\t DSDB_FLAG_NEXT_MODULE, ac->req);\n\tif (ret != LDB_SUCCESS) {\n\t\treturn ret;\n\t}\n\told_uac = ldb_msg_find_attr_as_uint(res->msgs[0], \"userAccountControl\", 0);\n\tif (old_uac == 0) {\n\t\treturn ldb_operr(ldb);\n\t}\n\told_uac_computed = ldb_msg_find_attr_as_uint(res->msgs[0],\n\t\t\t\t\t\t \"msDS-User-Account-Control-Computed\", 0);\n\told_lockoutTime = ldb_msg_find_attr_as_int64(res->msgs[0],\n\t\t\t\t\t\t \"lockoutTime\", 0);\n\told_is_critical = ldb_msg_find_attr_as_bool(res->msgs[0],\n\t\t\t\t\t\t \"isCriticalSystemObject\", 0);\n\t/*\n\t * When we do not have objectclass \"computer\" we cannot\n\t * switch to a workstation or (RO)DC\n\t */\n\tel = ldb_msg_find_element(res->msgs[0], \"objectClass\");\n\tif (el == NULL) {\n\t\treturn ldb_operr(ldb);\n\t}\n\tcomputer_val = data_blob_string_const(\"computer\");\n\tval = ldb_msg_find_val(el, &computer_val);\n\tif (val != NULL) {\n\t\tis_computer_objectclass = true;\n\t}\n\n\told_ufa = old_uac & UF_ACCOUNT_TYPE_MASK;\n\told_atype = ds_uf2atype(old_ufa);\n\told_pgrid = ds_uf2prim_group_rid(old_uac);\n\n\tnew_ufa = new_uac & UF_ACCOUNT_TYPE_MASK;\n\tif (new_ufa == 0) {\n\t\t/*\n\t\t * \"userAccountControl\" = 0 or missing one of the\n\t\t * types means \"UF_NORMAL_ACCOUNT\". See MS-SAMR\n\t\t * 3.1.1.8.10 point 8\n\t\t */\n\t\tnew_ufa = UF_NORMAL_ACCOUNT;\n\t\tnew_uac |= new_ufa;\n\t}\n\tsid = samdb_result_dom_sid(res, res->msgs[0], \"objectSid\");\n\tif (sid == NULL) {\n\t\treturn ldb_module_operr(ac->module);\n\t}\n\n\tret = samldb_check_user_account_control_rules(ac, sid,\n\t\t\t\t\t\t raw_uac,\n\t\t\t\t\t\t new_uac,\n\t\t\t\t\t\t old_uac,\n\t\t\t\t\t\t is_computer_objectclass);\n\tif (ret != LDB_SUCCESS) {\n\t\treturn ret;\n\t}\n\n\tnew_atype = ds_uf2atype(new_ufa);\n\tnew_pgrid = ds_uf2prim_group_rid(new_uac);\n\n\tclear_uac = (old_uac | old_uac_computed) & ~raw_uac;\n\n\tswitch (new_ufa) {\n\tcase UF_NORMAL_ACCOUNT:\n\t\tnew_is_critical = old_is_critical;\n\t\tbreak;\n\n\tcase UF_INTERDOMAIN_TRUST_ACCOUNT:\n\t\tnew_is_critical = true;\n\t\tbreak;\n\n\tcase UF_WORKSTATION_TRUST_ACCOUNT:\n\t\tnew_is_critical = false;\n\t\tif (new_uac & UF_PARTIAL_SECRETS_ACCOUNT) {\n\t\t\tnew_is_critical = true;\n\t\t}\n\t\tbreak;\n\n\tcase UF_SERVER_TRUST_ACCOUNT:\n\t\tnew_is_critical = true;\n\t\tbreak;\n\n\tdefault:\n\t\tldb_asprintf_errstring(ldb,\n\t\t\t\"%08X: samldb: invalid userAccountControl[0x%08X]\",\n\t\t\tW_ERROR_V(WERR_INVALID_PARAMETER), raw_uac);\n\t\treturn LDB_ERR_OTHER;\n\t}\n\n\tif (old_atype != new_atype) {\n\t\tret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,\n\t\t\t\t\t \"sAMAccountType\", new_atype);\n\t\tif (ret != LDB_SUCCESS) {\n\t\t\treturn ret;\n\t\t}\n\t\tel = ldb_msg_find_element(ac->msg, \"sAMAccountType\");\n\t\tel->flags = LDB_FLAG_MOD_REPLACE;\n\t}\n\n\t/* As per MS-SAMR 3.1.1.8.10 these flags have not to be set */\n\tif ((clear_uac & UF_LOCKOUT) && (old_lockoutTime != 0)) {\n\t\t/* \"lockoutTime\" reset as per MS-SAMR 3.1.1.8.10 */\n\t\tldb_msg_remove_attr(ac->msg, \"lockoutTime\");\n\t\tret = samdb_msg_add_uint64(ldb, ac->msg, ac->msg, \"lockoutTime\",\n\t\t\t\t\t (NTTIME)0);\n\t\tif (ret != LDB_SUCCESS) {\n\t\t\treturn ret;\n\t\t}\n\t\tel = ldb_msg_find_element(ac->msg, \"lockoutTime\");\n\t\tel->flags = LDB_FLAG_MOD_REPLACE;\n\t}\n\n\t/*\n\t * \"isCriticalSystemObject\" might be set/changed\n\t *\n\t * Even a change from UF_NORMAL_ACCOUNT (implicitly FALSE) to\n\t * UF_WORKSTATION_TRUST_ACCOUNT (actually FALSE) triggers\n\t * creating the attribute.\n\t */\n\tif (old_is_critical != new_is_critical || old_atype != new_atype) {\n\t\tret = ldb_msg_add_string(ac->msg, \"isCriticalSystemObject\",\n\t\t\t\t\t new_is_critical ? \"TRUE\": \"FALSE\");\n\t\tif (ret != LDB_SUCCESS) {\n\t\t\treturn ret;\n\t\t}\n\t\tel = ldb_msg_find_element(ac->msg,\n\t\t\t\t\t \"isCriticalSystemObject\");\n\t\tel->flags = LDB_FLAG_MOD_REPLACE;\n\t}\n\n\tif (!ldb_msg_find_element(ac->msg, \"primaryGroupID\") &&\n\t (old_pgrid != new_pgrid)) {\n\t\t/* Older AD deployments don't know about the RODC group */\n\t\tif (new_pgrid == DOMAIN_RID_READONLY_DCS) {\n\t\t\tret = samldb_prim_group_tester(ac, new_pgrid);\n\t\t\tif (ret != LDB_SUCCESS) {\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t}\n\n\t\tret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,\n\t\t\t\t\t \"primaryGroupID\", new_pgrid);\n\t\tif (ret != LDB_SUCCESS) {\n\t\t\treturn ret;\n\t\t}\n\t\tel = ldb_msg_find_element(ac->msg,\n\t\t\t\t\t \"primaryGroupID\");\n\t\tel->flags = LDB_FLAG_MOD_REPLACE;\n\t}\n\n\t/* Propagate eventual \"userAccountControl\" attribute changes */\n\tif (old_uac != new_uac) {\n\t\tchar *tempstr = talloc_asprintf(ac->msg, \"%d\",\n\t\t\t\t\t\tnew_uac);\n\t\tif (tempstr == NULL) {\n\t\t\treturn ldb_module_oom(ac->module);\n\t\t}\n\n\t\tret = ldb_msg_add_empty(ac->msg,\n\t\t\t\t\t\"userAccountControl\",\n\t\t\t\t\tLDB_FLAG_MOD_REPLACE,\n\t\t\t\t\t&el);\n\t\tel->values = talloc(ac->msg, struct ldb_val);\n\t\tel->num_values = 1;\n\t\tel->values[0].data = (uint8_t *) tempstr;\n\t\tel->values[0].length = strlen(tempstr);\n\t} else {\n\t\tldb_msg_remove_attr(ac->msg, \"userAccountControl\");\n\t}\n\n\treturn LDB_SUCCESS;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'CVE-2022-32746 ldb: Make use of functions for appending to an ldb_message\n\nThis aims to minimise usage of the error-prone pattern of searching for\na just-added message element in order to make modifications to it (and\npotentially finding the wrong element).\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=15009\n\nSigned-off-by: Joseph Sutton '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int samldb_rodc_add(struct samldb_ctx *ac)\n{\n\tstruct ldb_context *ldb = ldb_module_get_ctx(ac->module);\n\tuint32_t krbtgt_number, i_start, i;\n\tint ret;\n\tstruct ldb_val newpass_utf16;\n\n\t/* find a unused msDS-SecondaryKrbTgtNumber */\n\ti_start = generate_random() & 0xFFFF;\n\tif (i_start == 0) {\n\t\ti_start = 1;\n\t}\n\n\tfor (i=i_start; i<=0xFFFF; i++) {\n\t\tif (samldb_krbtgtnumber_available(ac, i)) {\n\t\t\tkrbtgt_number = i;\n\t\t\tgoto found;\n\t\t}\n\t}\n\tfor (i=1; imsg, \"msDS-SecondaryKrbTgtNumber\",\n\t\t\t\tLDB_FLAG_INTERNAL_DISABLE_VALIDATION, NULL);\n\tif (ret != LDB_SUCCESS) {\n\t\treturn ldb_operr(ldb);\n\t}\n\n\tret = samdb_msg_add_uint(ldb, ac->msg, ac->msg,\n\t\t\t\t \"msDS-SecondaryKrbTgtNumber\", krbtgt_number);\n\tif (ret != LDB_SUCCESS) {\n\t\treturn ldb_operr(ldb);\n\t}\n\n\tret = ldb_msg_add_fmt(ac->msg, \"sAMAccountName\", \"krbtgt_%u\",\n\t\t\t krbtgt_number);\n\tif (ret != LDB_SUCCESS) {\n\t\treturn ldb_operr(ldb);\n\t}\n\n\tnewpass_utf16 = data_blob_talloc_zero(ac->module, 256);\n\tif (newpass_utf16.data == NULL) {\n\t\treturn ldb_oom(ldb);\n\t}\n\t/*\n\t * Note that the password_hash module will ignore\n\t * this value and use it's own generate_secret_buffer()\n\t * that's why we can just use generate_random_buffer()\n\t * here.\n\t */\n\tgenerate_random_buffer(newpass_utf16.data, newpass_utf16.length);\n\tret = ldb_msg_add_steal_value(ac->msg, \"clearTextPassword\", &newpass_utf16);\n\tif (ret != LDB_SUCCESS) {\n\t\treturn ldb_operr(ldb);\n\t}\n\n\treturn samldb_next_step(ac);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'CVE-2022-32746 ldb: Make use of functions for appending to an ldb_message\n\nThis aims to minimise usage of the error-prone pattern of searching for\na just-added message element in order to make modifications to it (and\npotentially finding the wrong element).\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=15009\n\nSigned-off-by: Joseph Sutton '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)\n{\n int i;\n uint16_t limit;\n VncDisplay *vd = vs->vd;\n\n if (data[0] > 3) {\n update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);\n }\n\n switch (data[0]) {\n case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:\n if (len == 1)\n return 20;\n\n set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),\n read_u8(data, 6), read_u8(data, 7),\n read_u16(data, 8), read_u16(data, 10),\n read_u16(data, 12), read_u8(data, 14),\n read_u8(data, 15), read_u8(data, 16));\n break;\n case VNC_MSG_CLIENT_SET_ENCODINGS:\n if (len == 1)\n return 4;\n\n if (len == 4) {\n limit = read_u16(data, 2);\n if (limit > 0)\n return 4 + (limit * 4);\n } else\n limit = read_u16(data, 2);\n\n for (i = 0; i < limit; i++) {\n int32_t val = read_s32(data, 4 + (i * 4));\n memcpy(data + 4 + (i * 4), &val, sizeof(val));\n }\n\n set_encodings(vs, (int32_t *)(data + 4), limit);\n break;\n case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:\n if (len == 1)\n return 10;\n\n framebuffer_update_request(vs,\n read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),\n read_u16(data, 6), read_u16(data, 8));\n break;\n case VNC_MSG_CLIENT_KEY_EVENT:\n if (len == 1)\n return 8;\n\n key_event(vs, read_u8(data, 1), read_u32(data, 4));\n break;\n case VNC_MSG_CLIENT_POINTER_EVENT:\n if (len == 1)\n return 6;\n\n pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));\n break;\n case VNC_MSG_CLIENT_CUT_TEXT:\n if (len == 1)\n return 8;\n\n if (len == 8) {\n uint32_t dlen = read_u32(data, 4);\n if (dlen > 0)\n return 8 + dlen;\n }\n\n client_cut_text(vs, read_u32(data, 4), data + 8);\n break;\n case VNC_MSG_CLIENT_QEMU:\n if (len == 1)\n return 2;\n\n switch (read_u8(data, 1)) {\n case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:\n if (len == 2)\n return 12;\n\n ext_key_event(vs, read_u16(data, 2),\n read_u32(data, 4), read_u32(data, 8));\n break;\n case VNC_MSG_CLIENT_QEMU_AUDIO:\n if (len == 2)\n return 4;\n\n switch (read_u16 (data, 2)) {\n case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:\n audio_add(vs);\n break;\n case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:\n audio_del(vs);\n break;\n case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:\n if (len == 4)\n return 10;\n switch (read_u8(data, 4)) {\n case 0: vs->as.fmt = AUD_FMT_U8; break;\n case 1: vs->as.fmt = AUD_FMT_S8; break;\n case 2: vs->as.fmt = AUD_FMT_U16; break;\n case 3: vs->as.fmt = AUD_FMT_S16; break;\n case 4: vs->as.fmt = AUD_FMT_U32; break;\n case 5: vs->as.fmt = AUD_FMT_S32; break;\n default:\n printf(\"Invalid audio format %d\\n\", read_u8(data, 4));\n vnc_client_error(vs);\n break;\n }\n vs->as.nchannels = read_u8(data, 5);\n if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {\n printf(\"Invalid audio channel coount %d\\n\",\n read_u8(data, 5));\n vnc_client_error(vs);\n break;\n }\n vs->as.freq = read_u32(data, 6);\n break;\n default:\n printf (\"Invalid audio message %d\\n\", read_u8(data, 4));\n vnc_client_error(vs);\n break;\n }\n break;\n\n default:\n printf(\"Msg: %d\\n\", read_u16(data, 0));\n vnc_client_error(vs);\n break;\n }\n break;\n default:\n printf(\"Msg: %d\\n\", data[0]);\n vnc_client_error(vs);\n break;\n }\n\n vnc_read_when(vs, protocol_client_msg, 1);\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703', 'CWE-835'], 'message': 'ui/vnc: limit client_cut_text msg payload size\n\ncurrently a malicious client could define a payload\nsize of 2^32 - 1 bytes and send up to that size of\ndata to the vnc server. The server would allocated\nthat amount of memory which could easily create an\nout of memory condition.\n\nThis patch limits the payload size to 1MB max.\n\nPlease note that client_cut_text messages are currently\nsilently ignored.\n\nSigned-off-by: Peter Lieven \nSigned-off-by: Gerd Hoffmann '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static zval **spl_array_get_dimension_ptr_ptr(int check_inherited, zval *object, zval *offset, int type TSRMLS_DC) /* {{{ */\n{\n\tspl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);\n\tzval **retval;\n\tchar *key;\n\tuint len;\n\tlong index;\n\tHashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);\n\n\tif (!offset) {\n\t\treturn &EG(uninitialized_zval_ptr);\n\t}\n\n\tif ((type == BP_VAR_W || type == BP_VAR_RW) && (ht->nApplyCount > 0)) {\n\t\tzend_error(E_WARNING, \"Modification of ArrayObject during sorting is prohibited\");\n\t\treturn &EG(error_zval_ptr);;\n\t}\n\n\tswitch (Z_TYPE_P(offset)) {\n\tcase IS_STRING:\n\t\tkey = Z_STRVAL_P(offset);\n\t\tlen = Z_STRLEN_P(offset) + 1;\nstring_offest:\n\t\tif (zend_symtable_find(ht, key, len, (void **) &retval) == FAILURE) {\n\t\t\tswitch (type) {\n\t\t\t\tcase BP_VAR_R:\n\t\t\t\t\tzend_error(E_NOTICE, \"Undefined index: %s\", key);\n\t\t\t\tcase BP_VAR_UNSET:\n\t\t\t\tcase BP_VAR_IS:\n\t\t\t\t\tretval = &EG(uninitialized_zval_ptr);\n\t\t\t\t\tbreak;\n\t\t\t\tcase BP_VAR_RW:\n\t\t\t\t\tzend_error(E_NOTICE,\"Undefined index: %s\", key);\n\t\t\t\tcase BP_VAR_W: {\n\t\t\t\t zval *value;\n\t\t\t\t ALLOC_INIT_ZVAL(value);\n\t\t\t\t zend_symtable_update(ht, key, len, (void**)&value, sizeof(void*), (void **)&retval);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn retval;\n\tcase IS_NULL:\n\t\tkey = \"\";\n\t\tlen = 1;\n\t\tgoto string_offest;\n\tcase IS_RESOURCE:\n\t\tzend_error(E_STRICT, \"Resource ID#%ld used as offset, casting to integer (%ld)\", Z_LVAL_P(offset), Z_LVAL_P(offset));\n\tcase IS_DOUBLE:\n\tcase IS_BOOL:\n\tcase IS_LONG:\n\t\tif (offset->type == IS_DOUBLE) {\n\t\t\tindex = (long)Z_DVAL_P(offset);\n\t\t} else {\n\t\t\tindex = Z_LVAL_P(offset);\n\t\t}\n\t\tif (zend_hash_index_find(ht, index, (void **) &retval) == FAILURE) {\n\t\t\tswitch (type) {\n\t\t\t\tcase BP_VAR_R:\n\t\t\t\t\tzend_error(E_NOTICE, \"Undefined offset: %ld\", index);\n\t\t\t\tcase BP_VAR_UNSET:\n\t\t\t\tcase BP_VAR_IS:\n\t\t\t\t\tretval = &EG(uninitialized_zval_ptr);\n\t\t\t\t\tbreak;\n\t\t\t\tcase BP_VAR_RW:\n\t\t\t\t\tzend_error(E_NOTICE, \"Undefined offset: %ld\", index);\n\t\t\t\tcase BP_VAR_W: {\n\t\t\t\t zval *value;\n\t\t\t\t ALLOC_INIT_ZVAL(value);\n\t\t\t\t\tzend_hash_index_update(ht, index, (void**)&value, sizeof(void*), (void **)&retval);\n\t\t\t }\n\t\t\t}\n\t\t}\n\t\treturn retval;\n\tdefault:\n\t\tzend_error(E_WARNING, \"Illegal offset type\");\n\t\treturn (type == BP_VAR_W || type == BP_VAR_RW) ?\n\t\t\t&EG(error_zval_ptr) : &EG(uninitialized_zval_ptr);\n\t}\n} /* }}} */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #73029 - Missing type check when unserializing SplArray'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: GF_Err gf_hinter_finalize(GF_ISOFile *file, GF_SDP_IODProfile IOD_Profile, u32 bandwidth)\n{\n\tu32 i, sceneT, odT, descIndex, size, size64;\n\tGF_InitialObjectDescriptor *iod;\n\tGF_SLConfig slc;\n\tGF_ISOSample *samp;\n\tBool remove_ocr;\n\tu8 *buffer;\n\tchar buf64[5000], sdpLine[5100];\n\n\n\tgf_isom_sdp_clean(file);\n\n\tif (bandwidth) {\n\t\tsprintf(buf64, \"b=AS:%d\", bandwidth);\n\t\tgf_isom_sdp_add_line(file, buf64);\n\t}\n //xtended attribute for copyright\n if (gf_sys_is_test_mode()) {\n sprintf(buf64, \"a=x-copyright: %s\", \"MP4/3GP File hinted with GPAC - (c) Telecom ParisTech (http://gpac.io)\");\n } else {\n sprintf(buf64, \"a=x-copyright: MP4/3GP File hinted with GPAC %s - %s\", gf_gpac_version(), gf_gpac_copyright() );\n }\n\tgf_isom_sdp_add_line(file, buf64);\n\n\tif (IOD_Profile == GF_SDP_IOD_NONE) return GF_OK;\n\n\todT = sceneT = 0;\n\tfor (i=0; iESDescriptors)) {\n\t\t\tesd = (GF_ESD*)gf_list_get(iod->ESDescriptors, 0);\n\t\t\tgf_odf_desc_del((GF_Descriptor *) esd);\n\t\t\tgf_list_rem(iod->ESDescriptors, 0);\n\t\t}\n\n\n\t\t/*get OD esd, and embbed stream data if possible*/\n\t\tif (odT) {\n\t\t\tesd = gf_isom_get_esd(file, odT, 1);\n\t\t\tif (gf_isom_get_sample_count(file, odT)==1) {\n\t\t\t\tsamp = gf_isom_get_sample(file, odT, 1, &descIndex);\n\t\t\t\tif (samp && gf_hinter_can_embbed_data(samp->data, samp->dataLength, GF_STREAM_OD)) {\n\t\t\t\t\tInitSL_NULL(&slc);\n\t\t\t\t\tslc.predefined = 0;\n\t\t\t\t\tslc.hasRandomAccessUnitsOnlyFlag = 1;\n\t\t\t\t\tslc.timeScale = slc.timestampResolution = gf_isom_get_media_timescale(file, odT);\n\t\t\t\t\tslc.OCRResolution = 1000;\n\t\t\t\t\tslc.startCTS = samp->DTS+samp->CTS_Offset;\n\t\t\t\t\tslc.startDTS = samp->DTS;\n\t\t\t\t\t//set the SL for future extraction\n\t\t\t\t\tgf_isom_set_extraction_slc(file, odT, 1, &slc);\n\n\t\t\t\t\tsize64 = gf_base64_encode(samp->data, samp->dataLength, buf64, 2000);\n\t\t\t\t\tbuf64[size64] = 0;\n\t\t\t\t\tsprintf(sdpLine, \"data:application/mpeg4-od-au;base64,%s\", buf64);\n\n\t\t\t\t\tesd->decoderConfig->avgBitrate = 0;\n\t\t\t\t\tesd->decoderConfig->bufferSizeDB = samp->dataLength;\n\t\t\t\t\tesd->decoderConfig->maxBitrate = 0;\n\t\t\t\t\tsize64 = (u32) strlen(sdpLine)+1;\n\t\t\t\t\tesd->URLString = (char*)gf_malloc(sizeof(char) * size64);\n\t\t\t\t\tstrcpy(esd->URLString, sdpLine);\n\t\t\t\t} else {\n\t\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_RTP, (\"[rtp hinter] OD sample too large to be embedded in IOD - ISMA disabled\\n\"));\n\t\t\t\t\tis_ok = 0;\n\t\t\t\t}\n\t\t\t\tgf_isom_sample_del(&samp);\n\t\t\t}\n\t\t\tif (remove_ocr) esd->OCRESID = 0;\n\t\t\telse if (esd->OCRESID == esd->ESID) esd->OCRESID = 0;\n\n\t\t\t//OK, add this to our IOD\n\t\t\tgf_list_add(iod->ESDescriptors, esd);\n\t\t}\n\n\t\tesd = gf_isom_get_esd(file, sceneT, 1);\n\t\tif (gf_isom_get_sample_count(file, sceneT)==1) {\n\t\t\tsamp = gf_isom_get_sample(file, sceneT, 1, &descIndex);\n\t\t\tif (gf_hinter_can_embbed_data(samp->data, samp->dataLength, GF_STREAM_SCENE)) {\n\n\t\t\t\tslc.timeScale = slc.timestampResolution = gf_isom_get_media_timescale(file, sceneT);\n\t\t\t\tslc.OCRResolution = 1000;\n\t\t\t\tslc.startCTS = samp->DTS+samp->CTS_Offset;\n\t\t\t\tslc.startDTS = samp->DTS;\n\t\t\t\t//set the SL for future extraction\n\t\t\t\tgf_isom_set_extraction_slc(file, sceneT, 1, &slc);\n\t\t\t\t//encode in Base64 the sample\n\t\t\t\tsize64 = gf_base64_encode(samp->data, samp->dataLength, buf64, 2000);\n\t\t\t\tbuf64[size64] = 0;\n\t\t\t\tsprintf(sdpLine, \"data:application/mpeg4-bifs-au;base64,%s\", buf64);\n\n\t\t\t\tesd->decoderConfig->avgBitrate = 0;\n\t\t\t\tesd->decoderConfig->bufferSizeDB = samp->dataLength;\n\t\t\t\tesd->decoderConfig->maxBitrate = 0;\n\t\t\t\tesd->URLString = (char*)gf_malloc(sizeof(char) * (strlen(sdpLine)+1));\n\t\t\t\tstrcpy(esd->URLString, sdpLine);\n\t\t\t} else {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_RTP, (\"[rtp hinter] Scene description sample too large to be embedded in IOD - ISMA disabled\\n\"));\n\t\t\t\tis_ok = 0;\n\t\t\t}\n\t\t\tgf_isom_sample_del(&samp);\n\t\t}\n\t\tif (remove_ocr) esd->OCRESID = 0;\n\t\telse if (esd->OCRESID == esd->ESID) esd->OCRESID = 0;\n\n\t\tgf_list_add(iod->ESDescriptors, esd);\n\n\t\tif (is_ok) {\n\t\t\tu32 has_a, has_v, has_i_a, has_i_v;\n\t\t\thas_a = has_v = has_i_a = has_i_v = 0;\n\t\t\tfor (i=0; idecoderConfig->streamType==GF_STREAM_VISUAL) {\n\t\t\t\t\tif (esd->decoderConfig->objectTypeIndication==GF_CODECID_MPEG4_PART2) has_i_v ++;\n\t\t\t\t\telse has_v++;\n\t\t\t\t} else if (esd->decoderConfig->streamType==GF_STREAM_AUDIO) {\n\t\t\t\t\tif (esd->decoderConfig->objectTypeIndication==GF_CODECID_AAC_MPEG4) has_i_a ++;\n\t\t\t\t\telse has_a++;\n\t\t\t\t}\n\t\t\t\tgf_odf_desc_del((GF_Descriptor *)esd);\n\t\t\t}\n\t\t\t/*only 1 MPEG-4 visual max and 1 MPEG-4 audio max for ISMA compliancy*/\n\t\t\tif (!has_v && !has_a && (has_i_v<=1) && (has_i_a<=1)) {\n\t\t\t\tsprintf(sdpLine, \"a=isma-compliance:1,1.0,1\");\n\t\t\t\tgf_isom_sdp_add_line(file, sdpLine);\n\t\t\t}\n\t\t}\n\t}\n\n\t//encode the IOD\n\tbuffer = NULL;\n\tsize = 0;\n\tgf_odf_desc_write((GF_Descriptor *) iod, &buffer, &size);\n\tgf_odf_desc_del((GF_Descriptor *)iod);\n\n\t//encode in Base64 the iod\n\tsize64 = gf_base64_encode(buffer, size, buf64, 2000);\n\tbuf64[size64] = 0;\n\tgf_free(buffer);\n\n\tsprintf(sdpLine, \"a=mpeg4-iod:\\\"data:application/mpeg4-iod;base64,%s\\\"\", buf64);\n\tgf_isom_sdp_add_line(file, sdpLine);\n\n\treturn GF_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'fixed #1770 (fuzz)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool CClient::OnTextMessage(CTextMessage& Message) {\n CString sTargets = Message.GetTarget();\n\n VCString vTargets;\n sTargets.Split(\",\", vTargets, false);\n\n for (CString& sTarget : vTargets) {\n Message.SetTarget(sTarget);\n if (m_pNetwork) {\n // May be nullptr.\n Message.SetChan(m_pNetwork->FindChan(sTarget));\n }\n\n if (sTarget.TrimPrefix(m_pUser->GetStatusPrefix())) {\n if (sTarget.Equals(\"status\")) {\n CString sMsg = Message.GetText();\n UserCommand(sMsg);\n } else {\n CALLMOD(sTarget, this, m_pUser, m_pNetwork,\n OnModCommand(Message.GetText()));\n }\n continue;\n }\n\n bool bContinue = false;\n NETWORKMODULECALL(OnUserTextMessage(Message), m_pUser, m_pNetwork, this,\n &bContinue);\n if (bContinue) continue;\n\n if (!GetIRCSock()) {\n // Some lagmeters do a PRIVMSG to their own nick, ignore those.\n if (!sTarget.Equals(m_sNick))\n PutStatus(\n t_f(\"Your message to {1} got lost, you are not connected \"\n \"to IRC!\")(Message.GetTarget()));\n continue;\n }\n\n if (m_pNetwork) {\n AddBuffer(Message);\n EchoMessage(Message);\n PutIRC(Message.ToString(CMessage::ExcludePrefix |\n CMessage::ExcludeTags));\n }\n }\n\n return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Fix echo-message for *status\n\nClose #1705'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: AP_CORE_DECLARE_NONSTD(const char *) ap_limit_section(cmd_parms *cmd,\n void *dummy,\n const char *arg)\n{\n const char *endp = ap_strrchr_c(arg, '>');\n const char *limited_methods;\n void *tog = cmd->cmd->cmd_data;\n apr_int64_t limited = 0;\n apr_int64_t old_limited = cmd->limited;\n const char *errmsg;\n\n if (endp == NULL) {\n return unclosed_directive(cmd);\n }\n\n limited_methods = apr_pstrmemdup(cmd->temp_pool, arg, endp - arg);\n\n if (!limited_methods[0]) {\n return missing_container_arg(cmd);\n }\n\n while (limited_methods[0]) {\n char *method = ap_getword_conf(cmd->temp_pool, &limited_methods);\n int methnum;\n\n /* check for builtin or module registered method number */\n methnum = ap_method_number_of(method);\n\n if (methnum == M_TRACE && !tog) {\n return \"TRACE cannot be controlled by , see TraceEnable\";\n }\n else if (methnum == M_INVALID) {\n /* method has not been registered yet, but resource restriction\n * is always checked before method handling, so register it.\n */\n methnum = ap_method_register(cmd->pool,\n apr_pstrdup(cmd->pool, method));\n }\n\n limited |= (AP_METHOD_BIT << methnum);\n }\n\n /* Killing two features with one function,\n * if (tog == NULL) , else \n */\n limited = tog ? ~limited : limited;\n\n if (!(old_limited & limited)) {\n return apr_pstrcat(cmd->pool, cmd->cmd->name,\n \"> directive excludes all methods\", NULL);\n }\n else if ((old_limited & limited) == old_limited) {\n return apr_pstrcat(cmd->pool, cmd->cmd->name,\n \"> directive specifies methods already excluded\",\n NULL);\n }\n\n cmd->limited &= limited;\n\n errmsg = ap_walk_config(cmd->directive->first_child, cmd, cmd->context);\n\n cmd->limited = old_limited;\n\n return errmsg;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-284'], 'message': 'core: Disallow Methods' registration at run time (.htaccess), they may be\nused only if registered at init time (httpd.conf).\n\nCalling ap_method_register() in children processes is not the right scope\nsince it won't be shared for all requests.\n\n\ngit-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1807655 13f79535-47bb-0310-9956-ffa450edef68'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: cJSON *cJSON_GetObjectItem( cJSON *object, const char *string )\n{\n\tcJSON *c = object->child;\n\twhile ( c && cJSON_strcasecmp( c->string, string ) )\n\t\tc = c->next;\n\treturn c;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120', 'CWE-119', 'CWE-787'], 'message': 'Fix a buffer overflow / heap corruption issue that could occur if a\nmalformed JSON string was passed on the control channel. This issue,\npresent in the cJSON library, was already fixed upstream, so was\naddressed here in iperf3 by importing a newer version of cJSON (plus\nlocal ESnet modifications).\n\nDiscovered and reported by Dave McDaniel, Cisco Talos.\n\nBased on a patch by @dopheide-esnet, with input from @DaveGamble.\n\nCross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,\nCVE-2016-4303\n\n(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)\nSigned-off-by: Bruce A. Mah '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static const char *parse_number( cJSON *item, const char *num )\n{\n\tint64_t i = 0;\n\tdouble f = 0;\n\tint isint = 1;\n\tint sign = 1, scale = 0, subscale = 0, signsubscale = 1;\n\n\t/* Could use sscanf for this? */\n\tif ( *num == '-' ) {\n\t\t/* Has sign. */\n\t\tsign = -1;\n\t\t++num;\n\t}\n\tif ( *num == '0' )\n\t\t/* Is zero. */\n\t\t++num;\n\tif ( *num >= '1' && *num<='9' ) {\n\t\t/* Number. */\n\t\tdo {\n\t\t\ti = ( i * 10 ) + ( *num - '0' );\n\t\t\tf = ( f * 10.0 ) + ( *num - '0' );\n\t\t\t++num;\n\t\t} while ( *num >= '0' && *num <= '9' );\n\t}\n\tif ( *num == '.' && num[1] >= '0' && num[1] <= '9' ) {\n\t\t/* Fractional part. */\n\t\tisint = 0;\n\t\t++num;\n\t\tdo {\n\t\t\tf = ( f * 10.0 ) + ( *num++ - '0' );\n\t\t\tscale--;\n\t\t} while ( *num >= '0' && *num <= '9' );\n\t}\n\tif ( *num == 'e' || *num == 'E' ) {\n\t\t/* Exponent. */\n\t\tisint = 0;\n\t\t++num;\n\t\tif ( *num == '+' )\n\t\t\t++num;\n\t\telse if ( *num == '-' ) {\n\t\t\t/* With sign. */\n\t\t\tsignsubscale = -1;\n\t\t\t++num;\n\t\t}\n\t\twhile ( *num >= '0' && *num <= '9' )\n\t\t\tsubscale = ( subscale * 10 ) + ( *num++ - '0' );\n\t}\n\n\t/* Put it together. */\n\tif ( isint ) {\n\t\t/* Int: number = +/- number */\n\t\ti = sign * i;\n\t\titem->valueint = i;\n\t\titem->valuefloat = i;\n\t} else {\n\t\t/* Float: number = +/- number.fraction * 10^+/- exponent */\n\t\tf = sign * f * ipow( 10.0, scale + subscale * signsubscale );\n\t\titem->valueint = f;\n\t\titem->valuefloat = f;\n\t}\n\n\titem->type = cJSON_Number;\n\treturn num;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120', 'CWE-119', 'CWE-787'], 'message': 'Fix a buffer overflow / heap corruption issue that could occur if a\nmalformed JSON string was passed on the control channel. This issue,\npresent in the cJSON library, was already fixed upstream, so was\naddressed here in iperf3 by importing a newer version of cJSON (plus\nlocal ESnet modifications).\n\nDiscovered and reported by Dave McDaniel, Cisco Talos.\n\nBased on a patch by @dopheide-esnet, with input from @DaveGamble.\n\nCross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,\nCVE-2016-4303\n\n(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)\nSigned-off-by: Bruce A. Mah '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static char* cJSON_strdup( const char* str )\n{\n\tsize_t len;\n\tchar* copy;\n\n\tlen = strlen( str ) + 1;\n\tif ( ! ( copy = (char*) cJSON_malloc( len ) ) )\n\t\treturn 0;\n\tmemcpy( copy, str, len );\n\treturn copy;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120', 'CWE-119', 'CWE-787'], 'message': 'Fix a buffer overflow / heap corruption issue that could occur if a\nmalformed JSON string was passed on the control channel. This issue,\npresent in the cJSON library, was already fixed upstream, so was\naddressed here in iperf3 by importing a newer version of cJSON (plus\nlocal ESnet modifications).\n\nDiscovered and reported by Dave McDaniel, Cisco Talos.\n\nBased on a patch by @dopheide-esnet, with input from @DaveGamble.\n\nCross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,\nCVE-2016-4303\n\n(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)\nSigned-off-by: Bruce A. Mah '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void cJSON_InitHooks(cJSON_Hooks* hooks)\n{\n\tif ( ! hooks ) {\n\t\t/* Reset hooks. */\n\t\tcJSON_malloc = malloc;\n\t\tcJSON_free = free;\n\t\treturn;\n\t}\n\tcJSON_malloc = (hooks->malloc_fn) ? hooks->malloc_fn : malloc;\n\tcJSON_free = (hooks->free_fn) ? hooks->free_fn : free;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120', 'CWE-119', 'CWE-787'], 'message': 'Fix a buffer overflow / heap corruption issue that could occur if a\nmalformed JSON string was passed on the control channel. This issue,\npresent in the cJSON library, was already fixed upstream, so was\naddressed here in iperf3 by importing a newer version of cJSON (plus\nlocal ESnet modifications).\n\nDiscovered and reported by Dave McDaniel, Cisco Talos.\n\nBased on a patch by @dopheide-esnet, with input from @DaveGamble.\n\nCross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,\nCVE-2016-4303\n\n(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)\nSigned-off-by: Bruce A. Mah '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: cJSON *cJSON_CreateNull( void )\n{\n\tcJSON *item = cJSON_New_Item();\n\tif ( item )\n\t\titem->type = cJSON_NULL;\n\treturn item;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120', 'CWE-119', 'CWE-787'], 'message': 'Fix a buffer overflow / heap corruption issue that could occur if a\nmalformed JSON string was passed on the control channel. This issue,\npresent in the cJSON library, was already fixed upstream, so was\naddressed here in iperf3 by importing a newer version of cJSON (plus\nlocal ESnet modifications).\n\nDiscovered and reported by Dave McDaniel, Cisco Talos.\n\nBased on a patch by @dopheide-esnet, with input from @DaveGamble.\n\nCross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,\nCVE-2016-4303\n\n(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)\nSigned-off-by: Bruce A. Mah '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline void switch_to_bitmap(unsigned long tifp)\n{\n\t/*\n\t * Invalidate I/O bitmap if the previous task used it. This prevents\n\t * any possible leakage of an active I/O bitmap.\n\t *\n\t * If the next task has an I/O bitmap it will handle it on exit to\n\t * user mode.\n\t */\n\tif (tifp & _TIF_IO_BITMAP)\n\t\ttss_invalidate_io_bitmap(this_cpu_ptr(&cpu_tss_rw));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-276'], 'message': 'x86/ioperm: Fix io bitmap invalidation on Xen PV\n\ntss_invalidate_io_bitmap() wasn't wired up properly through the pvop\nmachinery, so the TSS and Xen's io bitmap would get out of sync\nwhenever disabling a valid io bitmap.\n\nAdd a new pvop for tss_invalidate_io_bitmap() to fix it.\n\nThis is XSA-329.\n\nFixes: 22fe5b0439dd (\"x86/ioperm: Move TSS bitmap update to exit to user work\")\nSigned-off-by: Andy Lutomirski \nSigned-off-by: Thomas Gleixner \nReviewed-by: Juergen Gross \nReviewed-by: Thomas Gleixner \nCc: stable@vger.kernel.org\nLink: https://lkml.kernel.org/r/d53075590e1f91c19f8af705059d3ff99424c020.1595030016.git.luto@kernel.org'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: PackLinuxElf64::PackLinuxElf64help1(InputFile *f)\n{\n e_type = get_te16(&ehdri.e_type);\n e_phnum = get_te16(&ehdri.e_phnum);\n e_shnum = get_te16(&ehdri.e_shnum);\n unsigned const e_phentsize = get_te16(&ehdri.e_phentsize);\n if (ehdri.e_ident[Elf64_Ehdr::EI_CLASS]!=Elf64_Ehdr::ELFCLASS64\n || sizeof(Elf64_Phdr) != e_phentsize\n || (Elf64_Ehdr::ELFDATA2MSB == ehdri.e_ident[Elf64_Ehdr::EI_DATA]\n && &N_BELE_RTP::be_policy != bele)\n || (Elf64_Ehdr::ELFDATA2LSB == ehdri.e_ident[Elf64_Ehdr::EI_DATA]\n && &N_BELE_RTP::le_policy != bele)) {\n e_phoff = 0;\n e_shoff = 0;\n sz_phdrs = 0;\n return;\n }\n if (0==e_phnum) throwCantUnpack(\"0==e_phnum\");\n e_phoff = get_te64(&ehdri.e_phoff);\n upx_uint64_t const last_Phdr = e_phoff + e_phnum * sizeof(Elf64_Phdr);\n if (last_Phdr < e_phoff || (unsigned long)file_size < last_Phdr) {\n throwCantUnpack(\"bad e_phoff\");\n }\n e_shoff = get_te64(&ehdri.e_shoff);\n upx_uint64_t const last_Shdr = e_shoff + e_shnum * sizeof(Elf64_Shdr);\n if (last_Shdr < e_shoff || (unsigned long)file_size < last_Shdr) {\n if (opt->cmd == CMD_COMPRESS) {\n throwCantUnpack(\"bad e_shoff\");\n }\n }\n sz_phdrs = e_phnum * e_phentsize;\n\n if (f && Elf64_Ehdr::ET_DYN!=e_type) {\n unsigned const len = sz_phdrs + e_phoff;\n alloc_file_image(file_image, len);\n f->seek(0, SEEK_SET);\n f->readx(file_image, len);\n phdri= (Elf64_Phdr *)(e_phoff + file_image); // do not free() !!\n }\n if (f && Elf64_Ehdr::ET_DYN==e_type) {\n // The DT_SYMTAB has no designated length. Read the whole file.\n alloc_file_image(file_image, file_size);\n f->seek(0, SEEK_SET);\n f->readx(file_image, file_size);\n phdri= (Elf64_Phdr *)(e_phoff + file_image); // do not free() !!\n shdri= (Elf64_Shdr *)(e_shoff + file_image); // do not free() !!\n if (opt->cmd != CMD_COMPRESS) {\n shdri = NULL;\n }\n sec_dynsym = elf_find_section_type(Elf64_Shdr::SHT_DYNSYM);\n if (sec_dynsym) {\n unsigned t = get_te32(&sec_dynsym->sh_link);\n if (e_shnum <= t)\n throwCantPack(\"bad dynsym->sh_link\");\n sec_dynstr = &shdri[t];\n }\n\n Elf64_Phdr const *phdr= phdri;\n for (int j = e_phnum; --j>=0; ++phdr)\n if (Elf64_Phdr::PT_DYNAMIC==get_te64(&phdr->p_type)) {\n dynseg= (Elf64_Dyn const *)(check_pt_dynamic(phdr) + file_image);\n invert_pt_dynamic(dynseg);\n }\n else if (PT_LOAD64==get_te32(&phdr->p_type)) {\n check_pt_load(phdr);\n }\n // elf_find_dynamic() returns 0 if 0==dynseg.\n dynstr = (char const *)elf_find_dynamic(Elf64_Dyn::DT_STRTAB);\n dynsym = (Elf64_Sym const *)elf_find_dynamic(Elf64_Dyn::DT_SYMTAB);\n gashtab = (unsigned const *)elf_find_dynamic(Elf64_Dyn::DT_GNU_HASH);\n hashtab = (unsigned const *)elf_find_dynamic(Elf64_Dyn::DT_HASH);\n if (3& ((uintptr_t)dynsym | (uintptr_t)gashtab | (uintptr_t)hashtab)) {\n throwCantPack(\"unaligned DT_SYMTAB, DT_GNU_HASH, or DT_HASH/n\");\n }\n jni_onload_sym = elf_lookup(\"JNI_OnLoad\");\n if (jni_onload_sym) {\n jni_onload_va = get_te64(&jni_onload_sym->st_value);\n jni_onload_va = 0; // FIXME not understood; need example\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Defend against bad PT_DYNAMIC\n\nhttps://github.com/upx/upx/issues/391\n\tmodified: p_lx_elf.cpp\n\tmodified: p_lx_elf.h'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: hcom_client_init\r\n(\r\n\t\tOUT\tp_hsm_com_client_hdl_t\t*p_hdl,\r\n\tIN\t\tchar\t\t\t\t\t*server_path,\r\n\tIN\t\tchar\t\t\t\t\t*client_path,\r\n\tIN\t\tint\t\t\t\t\t\tmax_data_len\r\n)\r\n{\r\n\thsm_com_client_hdl_t\t*hdl = NULL;\r\n\thsm_com_errno_t\t\t\tres = HSM_COM_OK;\r\n\t\r\n\r\n\tif((strlen(server_path) > (HSM_COM_SVR_MAX_PATH - 1)) ||\r\n\t (strlen(server_path) == 0)){\r\n\t\tres = HSM_COM_PATH_ERR;\r\n\t\tgoto cleanup;\r\n\t}\r\n\r\n\tif((strlen(client_path) > (HSM_COM_SVR_MAX_PATH - 1)) ||\r\n\t (strlen(client_path) == 0)){\r\n\t\tres = HSM_COM_PATH_ERR;\r\n\t\tgoto cleanup;\r\n\t}\r\n\r\n\r\n\tif((hdl = calloc(1,sizeof(hsm_com_client_hdl_t))) == NULL)\r\n\t{\r\n\t\tres = HSM_COM_NO_MEM;\r\n\t\tgoto cleanup;\r\n\t}\r\n\r\n\tif((hdl->scr.scratch = malloc(max_data_len)) == NULL) \r\n\t{\r\n\t\tres = HSM_COM_NO_MEM;\r\n\t\tgoto cleanup;\r\n\t}\r\n\r\n\tif((hdl->recv_buf = malloc(max_data_len)) == NULL) \r\n\t{\r\n\t\tres = HSM_COM_NO_MEM;\r\n\t\tgoto cleanup;\r\n\t}\r\n\r\n\tif((hdl->send_buf = malloc(max_data_len)) == NULL) \r\n\t{\r\n\t\tres = HSM_COM_NO_MEM;\r\n\t\tgoto cleanup;\r\n\t}\r\n\r\n\thdl->scr.scratch_fill = 0;\r\n\thdl->scr.scratch_len = max_data_len;\r\n\thdl->buf_len = max_data_len;\r\n\thdl->trans_id = 1;\r\n\r\n\r\n\tstrcpy(hdl->s_path,server_path);\r\n\tstrcpy(hdl->c_path,client_path);\r\n\r\n\r\n\thdl->client_state = HSM_COM_C_STATE_IN;\r\n\r\n\t*p_hdl = hdl;\r\n\r\n\treturn res;\r\n\r\ncleanup:\r\n\tif(hdl)\r\n\t{\r\n\t\tif (hdl->scr.scratch) {\r\n\t\t\tfree(hdl->scr.scratch);\r\n\t\t}\r\n\t\tif (hdl->recv_buf) {\r\n\t\t\tfree(hdl->recv_buf);\r\n\t\t}\r\n\t\tfree(hdl);\r\n\t}\r\n\r\n\treturn res;\r\n\r\n}\r ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'Fix scripts and code that use well-known tmp files.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int parse_sequence_header(davs2_mgr_t *mgr, davs2_seq_t *seq, davs2_bs_t *bs)\n{\n static const float FRAME_RATE[8] = {\n 24000.0f / 1001.0f, 24.0f, 25.0f, 30000.0f / 1001.0f, 30.0f, 50.0f, 60000.0f / 1001.0f, 60.0f\n };\n rps_t *p_rps = NULL;\n\n int i, j;\n int num_of_rps;\n\n bs->i_bit_pos += 32; /* skip start code */\n\n memset(seq, 0, sizeof(davs2_seq_t)); // reset all value\n\n seq->head.profile_id = u_v(bs, 8, \"profile_id\");\n seq->head.level_id = u_v(bs, 8, \"level_id\");\n seq->head.progressive = u_v(bs, 1, \"progressive_sequence\");\n seq->b_field_coding = u_flag(bs, \"field_coded_sequence\");\n\n seq->head.width = u_v(bs, 14, \"horizontal_size\");\n seq->head.height = u_v(bs, 14, \"vertical_size\");\n\n if (seq->head.width < 16 || seq->head.height < 16) {\n return -1;\n }\n\n seq->head.chroma_format = u_v(bs, 2, \"chroma_format\");\n\n if (seq->head.chroma_format != CHROMA_420 && seq->head.chroma_format != CHROMA_400) {\n return -1;\n }\n if (seq->head.chroma_format == CHROMA_400) {\n davs2_log(mgr, DAVS2_LOG_WARNING, \"Un-supported Chroma Format YUV400 as 0 for GB/T.\\n\");\n }\n\n /* sample bit depth */\n if (seq->head.profile_id == MAIN10_PROFILE) {\n seq->sample_precision = u_v(bs, 3, \"sample_precision\");\n seq->encoding_precision = u_v(bs, 3, \"encoding_precision\");\n } else {\n seq->sample_precision = u_v(bs, 3, \"sample_precision\");\n seq->encoding_precision = 1;\n }\n if (seq->sample_precision < 1 || seq->sample_precision > 3 ||\n seq->encoding_precision < 1 || seq->encoding_precision > 3) {\n return -1;\n }\n\n seq->head.internal_bit_depth = 6 + (seq->encoding_precision << 1);\n seq->head.output_bit_depth = 6 + (seq->encoding_precision << 1);\n seq->head.bytes_per_sample = seq->head.output_bit_depth > 8 ? 2 : 1;\n\n /* */\n seq->head.aspect_ratio = u_v(bs, 4, \"aspect_ratio_information\");\n seq->head.frame_rate_id = u_v(bs, 4, \"frame_rate_id\");\n seq->bit_rate_lower = u_v(bs, 18, \"bit_rate_lower\");\n u_v(bs, 1, \"marker bit\");\n seq->bit_rate_upper = u_v(bs, 12, \"bit_rate_upper\");\n seq->head.low_delay = u_v(bs, 1, \"low_delay\");\n u_v(bs, 1, \"marker bit\");\n seq->b_temporal_id_exist = u_flag(bs, \"temporal_id exist flag\"); // get Extension Flag\n u_v(bs, 18, \"bbv buffer size\");\n\n seq->log2_lcu_size = u_v(bs, 3, \"Largest Coding Block Size\");\n\n if (seq->log2_lcu_size < 4 || seq->log2_lcu_size > 6) {\n davs2_log(mgr, DAVS2_LOG_ERROR, \"Invalid LCU size: %d\\n\", seq->log2_lcu_size);\n return -1;\n }\n\n seq->enable_weighted_quant = u_flag(bs, \"enable_weighted_quant\");\n\n if (seq->enable_weighted_quant) {\n int load_seq_wquant_data_flag;\n int x, y, sizeId, uiWqMSize;\n const int *Seq_WQM;\n\n load_seq_wquant_data_flag = u_flag(bs, \"load_seq_weight_quant_data_flag\");\n\n for (sizeId = 0; sizeId < 2; sizeId++) {\n uiWqMSize = DAVS2_MIN(1 << (sizeId + 2), 8);\n if (load_seq_wquant_data_flag == 1) {\n for (y = 0; y < uiWqMSize; y++) {\n for (x = 0; x < uiWqMSize; x++) {\n seq->seq_wq_matrix[sizeId][y * uiWqMSize + x] = (int16_t)ue_v(bs, \"weight_quant_coeff\");\n }\n }\n } else if (load_seq_wquant_data_flag == 0) {\n Seq_WQM = wq_get_default_matrix(sizeId);\n for (i = 0; i < (uiWqMSize * uiWqMSize); i++) {\n seq->seq_wq_matrix[sizeId][i] = (int16_t)Seq_WQM[i];\n }\n }\n }\n }\n\n seq->enable_background_picture = u_flag(bs, \"background_picture_disable\") ^ 0x01;\n seq->enable_mhp_skip = u_flag(bs, \"mhpskip enabled\");\n seq->enable_dhp = u_flag(bs, \"dhp enabled\");\n seq->enable_wsm = u_flag(bs, \"wsm enabled\");\n seq->enable_amp = u_flag(bs, \"Asymmetric Motion Partitions\");\n seq->enable_nsqt = u_flag(bs, \"use NSQT\");\n seq->enable_sdip = u_flag(bs, \"use NSIP\");\n seq->enable_2nd_transform = u_flag(bs, \"secT enabled\");\n seq->enable_sao = u_flag(bs, \"SAO Enable Flag\");\n seq->enable_alf = u_flag(bs, \"ALF Enable Flag\");\n seq->enable_pmvr = u_flag(bs, \"pmvr enabled\");\n\n if (1 != u_v(bs, 1, \"marker bit\")) {\n davs2_log(mgr, DAVS2_LOG_ERROR, \"expected marker_bit 1 while received 0, FILE %s, Row %d\\n\", __FILE__, __LINE__);\n }\n\n num_of_rps = u_v(bs, 6, \"num_of_RPS\");\n if (num_of_rps > AVS2_GOP_NUM) {\n return -1;\n }\n\n seq->num_of_rps = num_of_rps;\n\n for (i = 0; i < num_of_rps; i++) {\n p_rps = &seq->seq_rps[i];\n\n p_rps->refered_by_others = u_v(bs, 1, \"refered by others\");\n p_rps->num_of_ref = u_v(bs, 3, \"num of reference picture\");\n\n for (j = 0; j < p_rps->num_of_ref; j++) {\n p_rps->ref_pic[j] = u_v(bs, 6, \"delta COI of ref pic\");\n }\n\n p_rps->num_to_remove = u_v(bs, 3, \"num of removed picture\");\n\n for (j = 0; j < p_rps->num_to_remove; j++) {\n p_rps->remove_pic[j] = u_v(bs, 6, \"delta COI of removed pic\");\n }\n\n if (1 != u_v(bs, 1, \"marker bit\")) {\n davs2_log(mgr, DAVS2_LOG_ERROR, \"expected marker_bit 1 while received 0, FILE %s, Row %d\\n\", __FILE__, __LINE__);\n }\n }\n\n if (seq->head.low_delay == 0) {\n seq->picture_reorder_delay = u_v(bs, 5, \"picture_reorder_delay\");\n }\n\n seq->cross_loop_filter_flag = u_flag(bs, \"Cross Loop Filter Flag\");\n u_v(bs, 2, \"reserved bits\");\n\n bs_align(bs); /* align position */\n\n seq->head.bitrate = ((seq->bit_rate_upper << 18) + seq->bit_rate_lower) * 400;\n seq->head.frame_rate = FRAME_RATE[seq->head.frame_rate_id - 1];\n\n seq->i_enc_width = ((seq->head.width + MIN_CU_SIZE - 1) >> MIN_CU_SIZE_IN_BIT) << MIN_CU_SIZE_IN_BIT;\n seq->i_enc_height = ((seq->head.height + MIN_CU_SIZE - 1) >> MIN_CU_SIZE_IN_BIT) << MIN_CU_SIZE_IN_BIT;\n seq->valid_flag = 1;\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Add checking for `frame_rate_code`.\n\nSigned-off-by: luofl '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void follow_dotdot(struct nameidata *nd)\n{\n\tif (!nd->root.mnt)\n\t\tset_root(nd);\n\n\twhile(1) {\n\t\tstruct dentry *old = nd->path.dentry;\n\n\t\tif (nd->path.dentry == nd->root.dentry &&\n\t\t nd->path.mnt == nd->root.mnt) {\n\t\t\tbreak;\n\t\t}\n\t\tif (nd->path.dentry != nd->path.mnt->mnt_root) {\n\t\t\t/* rare case of legitimate dget_parent()... */\n\t\t\tnd->path.dentry = dget_parent(nd->path.dentry);\n\t\t\tdput(old);\n\t\t\tbreak;\n\t\t}\n\t\tif (!follow_up(&nd->path))\n\t\t\tbreak;\n\t}\n\tfollow_mount(&nd->path);\n\tnd->inode = nd->path.dentry->d_inode;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-254'], 'message': 'vfs: Test for and handle paths that are unreachable from their mnt_root\n\nIn rare cases a directory can be renamed out from under a bind mount.\nIn those cases without special handling it becomes possible to walk up\nthe directory tree to the root dentry of the filesystem and down\nfrom the root dentry to every other file or directory on the filesystem.\n\nLike division by zero .. from an unconnected path can not be given\na useful semantic as there is no predicting at which path component\nthe code will realize it is unconnected. We certainly can not match\nthe current behavior as the current behavior is a security hole.\n\nTherefore when encounting .. when following an unconnected path\nreturn -ENOENT.\n\n- Add a function path_connected to verify path->dentry is reachable\n from path->mnt.mnt_root. AKA to validate that rename did not do\n something nasty to the bind mount.\n\n To avoid races path_connected must be called after following a path\n component to it's next path component.\n\nSigned-off-by: \"Eric W. Biederman\" \nSigned-off-by: Al Viro '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: GF_Err hdlr_dump(GF_Box *a, FILE * trace)\n{\n\tGF_HandlerBox *p = (GF_HandlerBox *)a;\n\tgf_isom_box_dump_start(a, \"HandlerBox\", trace);\n\tif (p->nameUTF8 && (u32) p->nameUTF8[0] == strlen(p->nameUTF8+1)) {\n\t\tfprintf(trace, \"hdlrType=\\\"%s\\\" Name=\\\"%s\\\" \", gf_4cc_to_str(p->handlerType), p->nameUTF8+1);\n\t} else {\n\t\tfprintf(trace, \"hdlrType=\\\"%s\\\" Name=\\\"%s\\\" \", gf_4cc_to_str(p->handlerType), p->nameUTF8);\n\t}\n\tfprintf(trace, \"reserved1=\\\"%d\\\" reserved2=\\\"\", p->reserved1);\n\tdump_data(trace, (char *) p->reserved2, 12);\n\tfprintf(trace, \"\\\"\");\n\n\tfprintf(trace, \">\\n\");\n\tgf_isom_box_dump_done(\"HandlerBox\", a, trace);\n\treturn GF_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'fixed 2 possible heap overflows (inc. #1088)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int dnxhd_find_frame_end(DNXHDParserContext *dctx,\n const uint8_t *buf, int buf_size)\n{\n ParseContext *pc = &dctx->pc;\n uint64_t state = pc->state64;\n int pic_found = pc->frame_start_found;\n int i = 0;\n\n if (!pic_found) {\n for (i = 0; i < buf_size; i++) {\n state = (state << 8) | buf[i];\n if (ff_dnxhd_check_header_prefix(state & 0xffffffffff00LL) != 0) {\n i++;\n pic_found = 1;\n dctx->cur_byte = 0;\n dctx->remaining = 0;\n break;\n }\n }\n }\n\n if (pic_found && !dctx->remaining) {\n if (!buf_size) /* EOF considered as end of frame */\n return 0;\n for (; i < buf_size; i++) {\n dctx->cur_byte++;\n state = (state << 8) | buf[i];\n\n if (dctx->cur_byte == 24) {\n dctx->h = (state >> 32) & 0xFFFF;\n } else if (dctx->cur_byte == 26) {\n dctx->w = (state >> 32) & 0xFFFF;\n } else if (dctx->cur_byte == 42) {\n int cid = (state >> 32) & 0xFFFFFFFF;\n\n if (cid <= 0)\n continue;\n\n dctx->remaining = avpriv_dnxhd_get_frame_size(cid);\n if (dctx->remaining <= 0) {\n dctx->remaining = dnxhd_get_hr_frame_size(cid, dctx->w, dctx->h);\n if (dctx->remaining <= 0)\n return dctx->remaining;\n }\n if (buf_size - i + 47 >= dctx->remaining) {\n int remaining = dctx->remaining;\n\n pc->frame_start_found = 0;\n pc->state64 = -1;\n dctx->cur_byte = 0;\n dctx->remaining = 0;\n return remaining;\n } else {\n dctx->remaining -= buf_size;\n }\n }\n }\n } else if (pic_found) {\n if (dctx->remaining > buf_size) {\n dctx->remaining -= buf_size;\n } else {\n int remaining = dctx->remaining;\n\n pc->frame_start_found = 0;\n pc->state64 = -1;\n dctx->cur_byte = 0;\n dctx->remaining = 0;\n return remaining;\n }\n }\n pc->frame_start_found = pic_found;\n pc->state64 = state;\n return END_NOT_FOUND;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'avcodec/dnxhd_parser: Do not return invalid value from dnxhd_find_frame_end() on error\n\nFixes: Null pointer dereference\n\nFixes: CVE-2017-9608\nFound-by: Yihan Lian\nSigned-off-by: Michael Niedermayer \n(cherry picked from commit 611b35627488a8d0763e75c25ee0875c5b7987dd)\nSigned-off-by: Michael Niedermayer '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,\n int parse_extradata)\n{\n AVCodecContext *const avctx = h->avctx;\n H264Context *hx; ///< thread context\n int buf_index;\n int context_count;\n int next_avc;\n int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);\n int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts\n int nal_index;\n int ret = 0;\n\n h->max_contexts = h->slice_context_count;\n if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {\n h->current_slice = 0;\n if (!h->first_field)\n h->cur_pic_ptr = NULL;\n ff_h264_reset_sei(h);\n }\n\n for (; pass <= 1; pass++) {\n buf_index = 0;\n context_count = 0;\n next_avc = h->is_avc ? 0 : buf_size;\n nal_index = 0;\n for (;;) {\n int consumed;\n int dst_length;\n int bit_length;\n const uint8_t *ptr;\n int i, nalsize = 0;\n int err;\n\n if (buf_index >= next_avc) {\n if (buf_index >= buf_size - h->nal_length_size)\n break;\n nalsize = 0;\n for (i = 0; i < h->nal_length_size; i++)\n nalsize = (nalsize << 8) | buf[buf_index++];\n if (nalsize <= 0 || nalsize > buf_size - buf_index) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"AVC: nal size %d\\n\", nalsize);\n break;\n }\n next_avc = buf_index + nalsize;\n } else {\n // start code prefix search\n for (; buf_index + 3 < next_avc; buf_index++)\n // This should always succeed in the first iteration.\n if (buf[buf_index] == 0 &&\n buf[buf_index + 1] == 0 &&\n buf[buf_index + 2] == 1)\n break;\n\n if (buf_index + 3 >= buf_size) {\n buf_index = buf_size;\n break;\n }\n\n buf_index += 3;\n if (buf_index >= next_avc)\n continue;\n }\n\n hx = h->thread_context[context_count];\n\n ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,\n &consumed, next_avc - buf_index);\n if (ptr == NULL || dst_length < 0) {\n ret = -1;\n goto end;\n }\n i = buf_index + consumed;\n if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&\n buf[i] == 0x00 && buf[i + 1] == 0x00 &&\n buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)\n h->workaround_bugs |= FF_BUG_TRUNCATED;\n\n if (!(h->workaround_bugs & FF_BUG_TRUNCATED))\n while (dst_length > 0 && ptr[dst_length - 1] == 0)\n dst_length--;\n bit_length = !dst_length ? 0\n : (8 * dst_length -\n decode_rbsp_trailing(h, ptr + dst_length - 1));\n\n if (h->avctx->debug & FF_DEBUG_STARTCODE)\n av_log(h->avctx, AV_LOG_DEBUG,\n \"NAL %d at %d/%d length %d\\n\",\n hx->nal_unit_type, buf_index, buf_size, dst_length);\n\n if (h->is_avc && (nalsize != consumed) && nalsize)\n av_log(h->avctx, AV_LOG_DEBUG,\n \"AVC: Consumed only %d bytes instead of %d\\n\",\n consumed, nalsize);\n\n buf_index += consumed;\n nal_index++;\n\n if (pass == 0) {\n /* packets can sometimes contain multiple PPS/SPS,\n * e.g. two PAFF field pictures in one packet, or a demuxer\n * which splits NALs strangely if so, when frame threading we\n * can't start the next thread until we've read all of them */\n switch (hx->nal_unit_type) {\n case NAL_SPS:\n case NAL_PPS:\n nals_needed = nal_index;\n break;\n case NAL_DPA:\n case NAL_IDR_SLICE:\n case NAL_SLICE:\n init_get_bits(&hx->gb, ptr, bit_length);\n if (!get_ue_golomb(&hx->gb))\n nals_needed = nal_index;\n }\n continue;\n }\n\n if (avctx->skip_frame >= AVDISCARD_NONREF &&\n h->nal_ref_idc == 0 &&\n h->nal_unit_type != NAL_SEI)\n continue;\n\nagain:\n /* Ignore every NAL unit type except PPS and SPS during extradata\n * parsing. Decoding slices is not possible in codec init\n * with frame-mt */\n if (parse_extradata && HAVE_THREADS &&\n (h->avctx->active_thread_type & FF_THREAD_FRAME) &&\n (hx->nal_unit_type != NAL_PPS &&\n hx->nal_unit_type != NAL_SPS)) {\n if (hx->nal_unit_type < NAL_AUD ||\n hx->nal_unit_type > NAL_AUXILIARY_SLICE)\n av_log(avctx, AV_LOG_INFO,\n \"Ignoring NAL unit %d during extradata parsing\\n\",\n hx->nal_unit_type);\n hx->nal_unit_type = NAL_FF_IGNORE;\n }\n err = 0;\n switch (hx->nal_unit_type) {\n case NAL_IDR_SLICE:\n if (h->nal_unit_type != NAL_IDR_SLICE) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"Invalid mix of idr and non-idr slices\\n\");\n ret = -1;\n goto end;\n }\n idr(h); // FIXME ensure we don't lose some frames if there is reordering\n case NAL_SLICE:\n init_get_bits(&hx->gb, ptr, bit_length);\n hx->intra_gb_ptr =\n hx->inter_gb_ptr = &hx->gb;\n hx->data_partitioning = 0;\n\n if ((err = decode_slice_header(hx, h)))\n break;\n\n if (h->sei_recovery_frame_cnt >= 0 && h->recovery_frame < 0) {\n h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &\n ((1 << h->sps.log2_max_frame_num) - 1);\n }\n\n h->cur_pic_ptr->f.key_frame |=\n (hx->nal_unit_type == NAL_IDR_SLICE) ||\n (h->sei_recovery_frame_cnt >= 0);\n\n if (hx->nal_unit_type == NAL_IDR_SLICE ||\n h->recovery_frame == h->frame_num) {\n h->recovery_frame = -1;\n h->cur_pic_ptr->recovered = 1;\n }\n // If we have an IDR, all frames after it in decoded order are\n // \"recovered\".\n if (hx->nal_unit_type == NAL_IDR_SLICE)\n h->frame_recovered |= FRAME_RECOVERED_IDR;\n h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);\n\n if (h->current_slice == 1) {\n if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))\n decode_postinit(h, nal_index >= nals_needed);\n\n if (h->avctx->hwaccel &&\n (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)\n return ret;\n }\n\n if (hx->redundant_pic_count == 0 &&\n (avctx->skip_frame < AVDISCARD_NONREF ||\n hx->nal_ref_idc) &&\n (avctx->skip_frame < AVDISCARD_BIDIR ||\n hx->slice_type_nos != AV_PICTURE_TYPE_B) &&\n (avctx->skip_frame < AVDISCARD_NONKEY ||\n hx->slice_type_nos == AV_PICTURE_TYPE_I) &&\n avctx->skip_frame < AVDISCARD_ALL) {\n if (avctx->hwaccel) {\n ret = avctx->hwaccel->decode_slice(avctx,\n &buf[buf_index - consumed],\n consumed);\n if (ret < 0)\n return ret;\n } else\n context_count++;\n }\n break;\n case NAL_DPA:\n init_get_bits(&hx->gb, ptr, bit_length);\n hx->intra_gb_ptr =\n hx->inter_gb_ptr = NULL;\n\n if ((err = decode_slice_header(hx, h)) < 0) {\n /* make sure data_partitioning is cleared if it was set\n * before, so we don't try decoding a slice without a valid\n * slice header later */\n h->data_partitioning = 0;\n break;\n }\n\n hx->data_partitioning = 1;\n break;\n case NAL_DPB:\n init_get_bits(&hx->intra_gb, ptr, bit_length);\n hx->intra_gb_ptr = &hx->intra_gb;\n break;\n case NAL_DPC:\n init_get_bits(&hx->inter_gb, ptr, bit_length);\n hx->inter_gb_ptr = &hx->inter_gb;\n\n if (hx->redundant_pic_count == 0 &&\n hx->intra_gb_ptr &&\n hx->data_partitioning &&\n h->cur_pic_ptr && h->context_initialized &&\n (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&\n (avctx->skip_frame < AVDISCARD_BIDIR ||\n hx->slice_type_nos != AV_PICTURE_TYPE_B) &&\n (avctx->skip_frame < AVDISCARD_NONKEY ||\n hx->slice_type_nos == AV_PICTURE_TYPE_I) &&\n avctx->skip_frame < AVDISCARD_ALL)\n context_count++;\n break;\n case NAL_SEI:\n init_get_bits(&h->gb, ptr, bit_length);\n ff_h264_decode_sei(h);\n break;\n case NAL_SPS:\n init_get_bits(&h->gb, ptr, bit_length);\n ret = ff_h264_decode_seq_parameter_set(h);\n if (ret < 0 && h->is_avc && (nalsize != consumed) && nalsize) {\n av_log(h->avctx, AV_LOG_DEBUG,\n \"SPS decoding failure, trying again with the complete NAL\\n\");\n init_get_bits(&h->gb, buf + buf_index + 1 - consumed,\n 8 * (nalsize - 1));\n ff_h264_decode_seq_parameter_set(h);\n }\n\n ret = h264_set_parameter_from_sps(h);\n if (ret < 0)\n goto end;\n\n break;\n case NAL_PPS:\n init_get_bits(&h->gb, ptr, bit_length);\n ff_h264_decode_picture_parameter_set(h, bit_length);\n break;\n case NAL_AUD:\n case NAL_END_SEQUENCE:\n case NAL_END_STREAM:\n case NAL_FILLER_DATA:\n case NAL_SPS_EXT:\n case NAL_AUXILIARY_SLICE:\n break;\n case NAL_FF_IGNORE:\n break;\n default:\n av_log(avctx, AV_LOG_DEBUG, \"Unknown NAL code: %d (%d bits)\\n\",\n hx->nal_unit_type, bit_length);\n }\n\n if (context_count == h->max_contexts) {\n execute_decode_slices(h, context_count);\n context_count = 0;\n }\n\n if (err < 0) {\n av_log(h->avctx, AV_LOG_ERROR, \"decode_slice_header error\\n\");\n h->ref_count[0] = h->ref_count[1] = h->list_count = 0;\n } else if (err == 1) {\n /* Slice could not be decoded in parallel mode, copy down\n * NAL unit stuff to context 0 and restart. Note that\n * rbsp_buffer is not transferred, but since we no longer\n * run in parallel mode this should not be an issue. */\n h->nal_unit_type = hx->nal_unit_type;\n h->nal_ref_idc = hx->nal_ref_idc;\n hx = h;\n goto again;\n }\n }\n }\n if (context_count)\n execute_decode_slices(h, context_count);\n\nend:\n /* clean up */\n if (h->cur_pic_ptr && !h->droppable) {\n ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,\n h->picture_structure == PICT_BOTTOM_FIELD);\n }\n\n return (ret < 0) ? ret : buf_index;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'h264: reset data partitioning at the beginning of each decode call\n\nPrevents using GetBitContexts with data from previous calls.\n\nFixes access to freed memory.\n\nFound-by: Mateusz \"j00ru\" Jurczyk and Gynvael Coldwind\nCC:libav-stable@libav.org'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void Compute(OpKernelContext* context) override {\n const Tensor& logits_in = context->input(0);\n const Tensor& labels_in = context->input(1);\n\n TensorShape shape_in = logits_in.shape();\n\n BCast bcast(BCast::FromShape(logits_in.shape()),\n BCast::FromShape(labels_in.shape()));\n if (!logits_in.IsSameSize(labels_in)) {\n OP_REQUIRES(context, bcast.IsValid(),\n errors::InvalidArgument(\n \"logits and labels must be broadcastable: logits_size=\",\n logits_in.shape().DebugString(),\n \" labels_size=\", labels_in.shape().DebugString()));\n shape_in = BCast::ToShape(bcast.output_shape());\n }\n OP_REQUIRES(context, TensorShapeUtils::IsMatrix(shape_in),\n errors::InvalidArgument(\"logits and labels must be either \"\n \"2-dimensional, or broadcasted to be \"\n \"2-dimensional\"));\n\n if (std::is_same::value) {\n OP_REQUIRES(context, !OpDeterminismRequired(),\n errors::Unimplemented(\n \"The GPU implementation of SoftmaxCrossEntropyWithLogits\"\n \" that would have been executed is not deterministic.\"\n \" Note that the Python API uses an alternative,\"\n \" deterministic, GPU-accelerated path when determinism is\"\n \" enabled.\"));\n }\n\n // loss is 1-D (one per example), and size is batch_size.\n\n Tensor scratch;\n OP_REQUIRES_OK(\n context, context->allocate_temp(DataTypeToEnum::value,\n TensorShape({shape_in.dim_size(0), 1}),\n &scratch));\n\n Tensor* loss_out = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(\n 0, TensorShape({shape_in.dim_size(0)}), &loss_out));\n Tensor* back_out = nullptr;\n // Try to reuse the logits_in buffer for the backprop output.\n OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(\n {0}, 1, shape_in, &back_out));\n if (shape_in.dim_size(0) > 0) {\n functor::XentFunctor functor;\n if (logits_in.IsSameSize(labels_in)) {\n functor(context->eigen_device(), shape_in.AsEigenDSizes<2>(),\n Eigen::array{1, 1},\n Eigen::array{1, 1}, logits_in.matrix(),\n labels_in.matrix(), scratch.matrix(), loss_out->vec(),\n back_out->matrix());\n } else {\n functor(context->eigen_device(), shape_in.AsEigenDSizes<2>(),\n BCast::ToIndexArray<2>(bcast.x_bcast()),\n BCast::ToIndexArray<2>(bcast.y_bcast()),\n logits_in.template shaped(bcast.x_reshape()),\n labels_in.template shaped(bcast.y_reshape()),\n scratch.matrix(), loss_out->vec(), back_out->matrix());\n }\n }\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-354'], 'message': 'Fix crash in softmax-xent when some input dimensions are 1.\n\nBefore, tf.nn.softmax_cross_entropy_with_logits would fail a CHECK if one input tensor had shape (1, 1) and the other did not.\n\nIn particular, the call to ToIndexArray<2> here https://github.com/tensorflow/tensorflow/blob/1f3da84a89702d3b4f234ee83762d738caffe098/tensorflow/core/kernels/xent_op.cc#L99 would fail, since the call assumed the array had two dimensions. If both dimensions were 1, BCast would merge the two dimensions into a single dimension. Passing fewer_dims_optimization=false stops this optimization\n\nPiperOrigin-RevId: 384844496\nChange-Id: Ifb02dc74964132c3ed3f3bc98b0858dbe4e258b7'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int sdp_parse_fmtp_config_h264(AVFormatContext *s,\n AVStream *stream,\n PayloadContext *h264_data,\n const char *attr, const char *value)\n{\n AVCodecParameters *par = stream->codecpar;\n\n if (!strcmp(attr, \"packetization-mode\")) {\n av_log(s, AV_LOG_DEBUG, \"RTP Packetization Mode: %d\\n\", atoi(value));\n h264_data->packetization_mode = atoi(value);\n /*\n * Packetization Mode:\n * 0 or not present: Single NAL mode (Only nals from 1-23 are allowed)\n * 1: Non-interleaved Mode: 1-23, 24 (STAP-A), 28 (FU-A) are allowed.\n * 2: Interleaved Mode: 25 (STAP-B), 26 (MTAP16), 27 (MTAP24), 28 (FU-A),\n * and 29 (FU-B) are allowed.\n */\n if (h264_data->packetization_mode > 1)\n av_log(s, AV_LOG_ERROR,\n \"Interleaved RTP mode is not supported yet.\\n\");\n } else if (!strcmp(attr, \"profile-level-id\")) {\n if (strlen(value) == 6)\n parse_profile_level_id(s, h264_data, value);\n } else if (!strcmp(attr, \"sprop-parameter-sets\")) {\n int ret;\n if (value[strlen(value) - 1] == ',') {\n av_log(s, AV_LOG_WARNING, \"Missing PPS in sprop-parameter-sets, ignoring\\n\");\n return 0;\n }\n par->extradata_size = 0;\n av_freep(&par->extradata);\n ret = ff_h264_parse_sprop_parameter_sets(s, &par->extradata,\n &par->extradata_size, value);\n av_log(s, AV_LOG_DEBUG, \"Extradata set to %p (size: %d)\\n\",\n par->extradata, par->extradata_size);\n return ret;\n }\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'avformat/rtpdec_h264: Fix heap-buffer-overflow\n\nFixes: rtp_sdp/poc.sdp\n\nFound-by: Bingchang \nSigned-off-by: Michael Niedermayer '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus ResizeOutput(TfLiteContext* context, const TfLiteTensor* input,\n const TfLiteTensor* axis, TfLiteTensor* output) {\n int axis_value;\n // Retrive all 8 bytes when axis type is kTfLiteInt64 to avoid data loss.\n if (axis->type == kTfLiteInt64) {\n axis_value = static_cast(*GetTensorData(axis));\n } else {\n axis_value = *GetTensorData(axis);\n }\n if (axis_value < 0) {\n axis_value += NumDimensions(input);\n }\n\n // Copy the input dimensions to output except the axis dimension.\n TfLiteIntArray* output_dims = TfLiteIntArrayCreate(NumDimensions(input) - 1);\n int j = 0;\n for (int i = 0; i < NumDimensions(input); ++i) {\n if (i != axis_value) {\n output_dims->data[j] = SizeOfDimension(input, i);\n ++j;\n }\n }\n return context->ResizeTensor(context, output, output_dims);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Prevent array write out-of-bounds.\n\nIf user passes an invalid axis, then we copy one too many dimensions to the output in the loop below these checks. Even if we didn't do that, there will be further issues with an invalid axis, so we check for that right now.\n\nPiperOrigin-RevId: 371023299\nChange-Id: I9eca37ffc2b29e8e48710f500701270ef0790224'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: folly::Optional PlaintextReadRecordLayer::read(\n folly::IOBufQueue& buf) {\n while (true) {\n folly::io::Cursor cursor(buf.front());\n\n if (buf.empty() || !cursor.canAdvance(kPlaintextHeaderSize)) {\n return folly::none;\n }\n\n TLSMessage msg;\n msg.type = static_cast(cursor.readBE());\n\n if (skipEncryptedRecords_) {\n if (msg.type == ContentType::application_data) {\n cursor.skip(sizeof(ProtocolVersion));\n auto length = cursor.readBE();\n if (buf.chainLength() < (cursor - buf.front()) + length) {\n return folly::none;\n }\n length +=\n sizeof(ContentType) + sizeof(ProtocolVersion) + sizeof(uint16_t);\n buf.trimStart(length);\n continue;\n } else if (msg.type != ContentType::change_cipher_spec) {\n skipEncryptedRecords_ = false;\n }\n }\n\n switch (msg.type) {\n case ContentType::handshake:\n case ContentType::alert:\n break;\n case ContentType::change_cipher_spec:\n break;\n default:\n throw std::runtime_error(folly::to(\n \"received plaintext content type \",\n static_cast(msg.type),\n \", header: \",\n folly::hexlify(buf.splitAtMost(10)->coalesce())));\n }\n\n receivedRecordVersion_ =\n static_cast(cursor.readBE());\n\n auto length = cursor.readBE();\n if (length > kMaxPlaintextRecordSize) {\n throw std::runtime_error(\"received too long plaintext record\");\n }\n if (length == 0) {\n throw std::runtime_error(\"received empty plaintext record\");\n }\n if (buf.chainLength() < (cursor - buf.front()) + length) {\n return folly::none;\n }\n\n cursor.clone(msg.fragment, length);\n\n buf.trimStart(cursor - buf.front());\n\n if (msg.type == ContentType::change_cipher_spec) {\n msg.fragment->coalesce();\n if (msg.fragment->length() == 1 && *msg.fragment->data() == 0x01) {\n continue;\n } else {\n throw FizzException(\n \"received ccs\", AlertDescription::illegal_parameter);\n }\n }\n\n return std::move(msg);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-835', 'CWE-787'], 'message': 'Avoid arithmetic operation on uint16 read from the wire.\n\nSummary:\nThis could overflow previously.\n\nCVE-2019-3560\n\nReviewed By: yfeldblum\n\nDifferential Revision: D14152362\n\nfbshipit-source-id: c0ebb3fc59b49c7c23e6bcb90458c19cd891be65'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int DefragTrackerReuseTest(void)\n{\n int ret = 0;\n int id = 1;\n Packet *p1 = NULL;\n DefragTracker *tracker1 = NULL, *tracker2 = NULL;\n\n DefragInit();\n\n /* Build a packet, its not a fragment but shouldn't matter for\n * this test. */\n p1 = BuildTestPacket(id, 0, 0, 'A', 8);\n if (p1 == NULL) {\n goto end;\n }\n\n /* Get a tracker. It shouldn't look like its already in use. */\n tracker1 = DefragGetTracker(NULL, NULL, p1);\n if (tracker1 == NULL) {\n goto end;\n }\n if (tracker1->seen_last) {\n goto end;\n }\n if (tracker1->remove) {\n goto end;\n }\n DefragTrackerRelease(tracker1);\n\n /* Get a tracker again, it should be the same one. */\n tracker2 = DefragGetTracker(NULL, NULL, p1);\n if (tracker2 == NULL) {\n goto end;\n }\n if (tracker2 != tracker1) {\n goto end;\n }\n DefragTrackerRelease(tracker1);\n\n /* Now mark the tracker for removal. It should not be returned\n * when we get a tracker for a packet that may have the same\n * attributes. */\n tracker1->remove = 1;\n\n tracker2 = DefragGetTracker(NULL, NULL, p1);\n if (tracker2 == NULL) {\n goto end;\n }\n if (tracker2 == tracker1) {\n goto end;\n }\n if (tracker2->remove) {\n goto end;\n }\n\n ret = 1;\nend:\n if (p1 != NULL) {\n SCFree(p1);\n }\n DefragDestroy();\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-358'], 'message': 'defrag - take protocol into account during re-assembly\n\nThe IP protocol was not being used to match fragments with\ntheir packets allowing a carefully constructed packet\nwith a different protocol to be matched, allowing re-assembly\nto complete, creating a packet that would not be re-assembled\nby the destination host.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int DefragMfIpv6Test(void)\n{\n int retval = 0;\n int ip_id = 9;\n Packet *p = NULL;\n\n DefragInit();\n\n Packet *p1 = IPV6BuildTestPacket(ip_id, 2, 1, 'C', 8);\n Packet *p2 = IPV6BuildTestPacket(ip_id, 0, 1, 'A', 8);\n Packet *p3 = IPV6BuildTestPacket(ip_id, 1, 0, 'B', 8);\n if (p1 == NULL || p2 == NULL || p3 == NULL) {\n goto end;\n }\n\n p = Defrag(NULL, NULL, p1, NULL);\n if (p != NULL) {\n goto end;\n }\n\n p = Defrag(NULL, NULL, p2, NULL);\n if (p != NULL) {\n goto end;\n }\n\n /* This should return a packet as MF=0. */\n p = Defrag(NULL, NULL, p3, NULL);\n if (p == NULL) {\n goto end;\n }\n\n /* For IPv6 the expected length is just the length of the payload\n * of 2 fragments, so 16. */\n if (IPV6_GET_PLEN(p) != 16) {\n goto end;\n }\n\n retval = 1;\nend:\n if (p1 != NULL) {\n SCFree(p1);\n }\n if (p2 != NULL) {\n SCFree(p2);\n }\n if (p3 != NULL) {\n SCFree(p3);\n }\n if (p != NULL) {\n SCFree(p);\n }\n DefragDestroy();\n return retval;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-358'], 'message': 'defrag - take protocol into account during re-assembly\n\nThe IP protocol was not being used to match fragments with\ntheir packets allowing a carefully constructed packet\nwith a different protocol to be matched, allowing re-assembly\nto complete, creating a packet that would not be re-assembled\nby the destination host.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: auto ReferenceHandle::Get(Local key_handle, MaybeLocal maybe_options) -> Local {\n\treturn ThreePhaseTask::Run(*isolate, *this, key_handle, maybe_options, inherit);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-913'], 'message': 'Don't invoke accessors or proxies via Reference functions'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int truemotion1_decode_header(TrueMotion1Context *s)\n{\n int i, ret;\n int width_shift = 0;\n int new_pix_fmt;\n struct frame_header header;\n uint8_t header_buffer[128] = { 0 }; /* logical maximum size of the header */\n const uint8_t *sel_vector_table;\n\n header.header_size = ((s->buf[0] >> 5) | (s->buf[0] << 3)) & 0x7f;\n if (s->buf[0] < 0x10)\n {\n av_log(s->avctx, AV_LOG_ERROR, \"invalid header size (%d)\\n\", s->buf[0]);\n return AVERROR_INVALIDDATA;\n }\n\n /* unscramble the header bytes with a XOR operation */\n for (i = 1; i < header.header_size; i++)\n header_buffer[i - 1] = s->buf[i] ^ s->buf[i + 1];\n\n header.compression = header_buffer[0];\n header.deltaset = header_buffer[1];\n header.vectable = header_buffer[2];\n header.ysize = AV_RL16(&header_buffer[3]);\n header.xsize = AV_RL16(&header_buffer[5]);\n header.checksum = AV_RL16(&header_buffer[7]);\n header.version = header_buffer[9];\n header.header_type = header_buffer[10];\n header.flags = header_buffer[11];\n header.control = header_buffer[12];\n\n /* Version 2 */\n if (header.version >= 2)\n {\n if (header.header_type > 3)\n {\n av_log(s->avctx, AV_LOG_ERROR, \"invalid header type (%d)\\n\", header.header_type);\n return AVERROR_INVALIDDATA;\n } else if ((header.header_type == 2) || (header.header_type == 3)) {\n s->flags = header.flags;\n if (!(s->flags & FLAG_INTERFRAME))\n s->flags |= FLAG_KEYFRAME;\n } else\n s->flags = FLAG_KEYFRAME;\n } else /* Version 1 */\n s->flags = FLAG_KEYFRAME;\n\n if (s->flags & FLAG_SPRITE) {\n avpriv_request_sample(s->avctx, \"Frame with sprite\");\n /* FIXME header.width, height, xoffset and yoffset aren't initialized */\n return AVERROR_PATCHWELCOME;\n } else {\n s->w = header.xsize;\n s->h = header.ysize;\n if (header.header_type < 2) {\n if ((s->w < 213) && (s->h >= 176))\n {\n s->flags |= FLAG_INTERPOLATED;\n avpriv_request_sample(s->avctx, \"Interpolated frame\");\n }\n }\n }\n\n if (header.compression >= 17) {\n av_log(s->avctx, AV_LOG_ERROR, \"invalid compression type (%d)\\n\", header.compression);\n return AVERROR_INVALIDDATA;\n }\n\n if ((header.deltaset != s->last_deltaset) ||\n (header.vectable != s->last_vectable))\n select_delta_tables(s, header.deltaset);\n\n if ((header.compression & 1) && header.header_type)\n sel_vector_table = pc_tbl2;\n else {\n if (header.vectable > 0 && header.vectable < 4)\n sel_vector_table = tables[header.vectable - 1];\n else {\n av_log(s->avctx, AV_LOG_ERROR, \"invalid vector table id (%d)\\n\", header.vectable);\n return AVERROR_INVALIDDATA;\n }\n }\n\n if (compression_types[header.compression].algorithm == ALGO_RGB24H) {\n new_pix_fmt = AV_PIX_FMT_RGB32;\n width_shift = 1;\n } else\n new_pix_fmt = AV_PIX_FMT_RGB555; // RGB565 is supported as well\n\n s->w >>= width_shift;\n\n if (s->w != s->avctx->width || s->h != s->avctx->height ||\n new_pix_fmt != s->avctx->pix_fmt) {\n av_frame_unref(s->frame);\n s->avctx->sample_aspect_ratio = (AVRational){ 1 << width_shift, 1 };\n s->avctx->pix_fmt = new_pix_fmt;\n\n if ((ret = ff_set_dimensions(s->avctx, s->w, s->h)) < 0)\n return ret;\n\n av_fast_malloc(&s->vert_pred, &s->vert_pred_size, s->avctx->width * sizeof(unsigned int));\n }\n\n /* There is 1 change bit per 4 pixels, so each change byte represents\n * 32 pixels; divide width by 4 to obtain the number of change bits and\n * then round up to the nearest byte. */\n s->mb_change_bits_row_size = ((s->avctx->width >> (2 - width_shift)) + 7) >> 3;\n\n if ((header.deltaset != s->last_deltaset) || (header.vectable != s->last_vectable))\n {\n if (compression_types[header.compression].algorithm == ALGO_RGB24H)\n gen_vector_table24(s, sel_vector_table);\n else\n if (s->avctx->pix_fmt == AV_PIX_FMT_RGB555)\n gen_vector_table15(s, sel_vector_table);\n else\n gen_vector_table16(s, sel_vector_table);\n }\n\n /* set up pointers to the other key data chunks */\n s->mb_change_bits = s->buf + header.header_size;\n if (s->flags & FLAG_KEYFRAME) {\n /* no change bits specified for a keyframe; only index bytes */\n s->index_stream = s->mb_change_bits;\n } else {\n /* one change bit per 4x4 block */\n s->index_stream = s->mb_change_bits +\n (s->mb_change_bits_row_size * (s->avctx->height >> 2));\n }\n s->index_stream_size = s->size - (s->index_stream - s->buf);\n\n s->last_deltaset = header.deltaset;\n s->last_vectable = header.vectable;\n s->compression = header.compression;\n s->block_width = compression_types[header.compression].block_width;\n s->block_height = compression_types[header.compression].block_height;\n s->block_type = compression_types[header.compression].block_type;\n\n if (s->avctx->debug & FF_DEBUG_PICT_INFO)\n av_log(s->avctx, AV_LOG_INFO, \"tables: %d / %d c:%d %dx%d t:%d %s%s%s%s\\n\",\n s->last_deltaset, s->last_vectable, s->compression, s->block_width,\n s->block_height, s->block_type,\n s->flags & FLAG_KEYFRAME ? \" KEY\" : \"\",\n s->flags & FLAG_INTERFRAME ? \" INTER\" : \"\",\n s->flags & FLAG_SPRITE ? \" SPRITE\" : \"\",\n s->flags & FLAG_INTERPOLATED ? \" INTERPOL\" : \"\");\n\n return header.header_size;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'truemotion1: check the header size\n\nFixes invalid reads.\n\nFound-by: Mateusz \"j00ru\" Jurczyk and Gynvael Coldwind\nCC:libav-stable@libav.org'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: Status check_index_ordering(const Tensor& indices) {\n auto findices = indices.flat();\n\n for (std::size_t i = 0; i < findices.dimension(0) - 1; ++i) {\n if (findices(i) < findices(i + 1)) {\n continue;\n }\n\n return Status(\n errors::InvalidArgument(\"Indices are not strictly ordered\"));\n }\n\n return Status::OK();\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-824'], 'message': 'Prevent nullptr deref in validation of indexes in map ops.\n\nPiperOrigin-RevId: 387738023\nChange-Id: I83d18d36a7b82ffd2a40b5124a4e5b4c72238f27'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool has_capacity() const TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) {\n return capacity_ > 0;\n } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-824'], 'message': 'Prevent nullptr deref in validation of indexes in map ops.\n\nPiperOrigin-RevId: 387738023\nChange-Id: I83d18d36a7b82ffd2a40b5124a4e5b4c72238f27'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: DSA_Verification_Operation(const DSA_PublicKey& dsa,\n const std::string& emsa) :\n PK_Ops::Verification_with_EMSA(emsa),\n m_group(dsa.get_group()),\n m_y(dsa.get_y()),\n m_mod_q(dsa.group_q())\n {} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Address DSA/ECDSA side channel'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int filter_frame(AVFilterLink *inlink, AVFrame *in)\n{\n PadContext *s = inlink->dst->priv;\n AVFrame *out;\n int needs_copy = frame_needs_copy(s, in);\n\n if (needs_copy) {\n av_log(inlink->dst, AV_LOG_DEBUG, \"Direct padding impossible allocating new frame\\n\");\n out = ff_get_video_buffer(inlink->dst->outputs[0],\n FFMAX(inlink->w, s->w),\n FFMAX(inlink->h, s->h));\n if (!out) {\n av_frame_free(&in);\n return AVERROR(ENOMEM);\n }\n\n av_frame_copy_props(out, in);\n } else {\n int i;\n\n out = in;\n for (i = 0; i < 4 && out->data[i]; i++) {\n int hsub = s->draw.hsub[i];\n int vsub = s->draw.vsub[i];\n out->data[i] -= (s->x >> hsub) * s->draw.pixelstep[i] +\n (s->y >> vsub) * out->linesize[i];\n }\n }\n\n /* top bar */\n if (s->y) {\n ff_fill_rectangle(&s->draw, &s->color,\n out->data, out->linesize,\n 0, 0, s->w, s->y);\n }\n\n /* bottom bar */\n if (s->h > s->y + s->in_h) {\n ff_fill_rectangle(&s->draw, &s->color,\n out->data, out->linesize,\n 0, s->y + s->in_h, s->w, s->h - s->y - s->in_h);\n }\n\n /* left border */\n ff_fill_rectangle(&s->draw, &s->color, out->data, out->linesize,\n 0, s->y, s->x, in->height);\n\n if (needs_copy) {\n ff_copy_rectangle2(&s->draw,\n out->data, out->linesize, in->data, in->linesize,\n s->x, s->y, 0, 0, in->width, in->height);\n }\n\n /* right border */\n ff_fill_rectangle(&s->draw, &s->color, out->data, out->linesize,\n s->x + s->in_w, s->y, s->w - s->x - s->in_w,\n in->height);\n\n out->width = s->w;\n out->height = s->h;\n\n if (in != out)\n av_frame_free(&in);\n return ff_filter_frame(inlink->dst->outputs[0], out);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'avfilter: fix plane validity checks\n\nFixes out of array accesses\n\nSigned-off-by: Michael Niedermayer '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int java_switch_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {\n\tut8 op_byte = data[0];\n\tut64 offset = addr - java_get_method_start ();\n\tut8 pos = (offset+1)%4 ? 1 + 4 - (offset+1)%4 : 1;\n\n\tif (op_byte == 0xaa) {\n\t\t// handle a table switch condition\n\t\tif (pos + 8 > len) {\n\t\t\treturn op->size;\n\t\t}\n\t\tint min_val = (ut32)(UINT (data, pos + 4)),\n\t\t\tmax_val = (ut32)(UINT (data, pos + 8));\n\n\t\tut32 default_loc = (ut32) (UINT (data, pos)), cur_case = 0;\n\t\top->switch_op = r_anal_switch_op_new (addr, min_val, default_loc);\n\t\tRAnalCaseOp *caseop = NULL;\n\t\tpos += 12;\n\t\tif (max_val > min_val && ((max_val - min_val)<(UT16_MAX/4))) {\n\t\t\t//caseop = r_anal_switch_op_add_case(op->switch_op, addr+default_loc, -1, addr+offset);\n\t\t\tfor (cur_case = 0; cur_case <= max_val - min_val; pos += 4, cur_case++) {\n\t\t\t\t//ut32 value = (ut32)(UINT (data, pos));\n\t\t\t\tif (pos + 4 >= len) {\n\t\t\t\t\t// switch is too big cant read further\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tint offset = (int)(ut32)(R_BIN_JAVA_UINT (data, pos));\n\t\t\t\tcaseop = r_anal_switch_op_add_case (op->switch_op,\n\t\t\t\t\taddr + pos, cur_case + min_val, addr + offset);\n\t\t\t\tif (caseop) {\n\t\t\t\t\tcaseop->bb_ref_to = addr+offset;\n\t\t\t\t\tcaseop->bb_ref_from = addr; // TODO figure this one out\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\teprintf (\"Invalid switch boundaries at 0x%\"PFMT64x\"\\n\", addr);\n\t\t}\n\t}\n\top->size = pos;\n\treturn op->size;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix #10296 - Heap out of bounds read in java_switch_op()'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void do_iccprofile_item(deark *c, lctx *d, i64 pos, i64 len)\n{\n\ti64 selector;\n\ti64 data_len;\n\n\tif(len<4) return;\n\tselector = de_getu32be(pos);\n\tdata_len = len-4;\n\tde_dbg(c, \"ICC profile segment, selector=%d, data len=%d\", (int)selector,\n\t\t(int)data_len);\n\n\tif(selector!=1) {\n\t\t// If this is not a Continuation segment, close any current file.\n\t\tdbuf_close(d->iccprofile_file);\n\t\td->iccprofile_file = NULL;\n\t}\n\n\tif(selector==0) { // Beginning segment\n\t\td->iccprofile_file = dbuf_create_output_file(c, \"icc\", NULL, DE_CREATEFLAG_IS_AUX);\n\t}\n\n\tif(selector==0 || selector==1) {\n\t\t// Beginning and Continuation segments normally have profile data.\n\t\t// End segments (selector==2) are not allowed to include data.\n\t\tdbuf_copy(c->infile, pos+4, data_len, d->iccprofile_file);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'pict: Fixed a bug with ICC profile extraction\n\nCould cause a NULL pointer dereference.\n\nFound by F. \u00c7elik.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: parserep(netdissect_options *ndo,\n register const struct sunrpc_msg *rp, register u_int length)\n{\n\tregister const uint32_t *dp;\n\tu_int len;\n\tenum sunrpc_accept_stat astat;\n\n\t/*\n\t * Portability note:\n\t * Here we find the address of the ar_verf credentials.\n\t * Originally, this calculation was\n\t *\tdp = (uint32_t *)&rp->rm_reply.rp_acpt.ar_verf\n\t * On the wire, the rp_acpt field starts immediately after\n\t * the (32 bit) rp_stat field. However, rp_acpt (which is a\n\t * \"struct accepted_reply\") contains a \"struct opaque_auth\",\n\t * whose internal representation contains a pointer, so on a\n\t * 64-bit machine the compiler inserts 32 bits of padding\n\t * before rp->rm_reply.rp_acpt.ar_verf. So, we cannot use\n\t * the internal representation to parse the on-the-wire\n\t * representation. Instead, we skip past the rp_stat field,\n\t * which is an \"enum\" and so occupies one 32-bit word.\n\t */\n\tdp = ((const uint32_t *)&rp->rm_reply) + 1;\n\tND_TCHECK(dp[1]);\n\tlen = EXTRACT_32BITS(&dp[1]);\n\tif (len >= length)\n\t\treturn (NULL);\n\t/*\n\t * skip past the ar_verf credentials.\n\t */\n\tdp += (len + (2*sizeof(uint32_t) + 3)) / sizeof(uint32_t);\n\tND_TCHECK2(dp[0], 0);\n\n\t/*\n\t * now we can check the ar_stat field\n\t */\n\tastat = (enum sunrpc_accept_stat) EXTRACT_32BITS(dp);\n\tif (astat != SUNRPC_SUCCESS) {\n\t\tND_PRINT((ndo, \" %s\", tok2str(sunrpc_str, \"ar_stat %d\", astat)));\n\t\tnfserr = 1;\t\t/* suppress trunc string */\n\t\treturn (NULL);\n\t}\n\t/* successful return */\n\tND_TCHECK2(*dp, sizeof(astat));\n\treturn ((const uint32_t *) (sizeof(astat) + ((const char *)dp)));\ntrunc:\n\treturn (0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-12898/NFS: Fix bounds checking.\n\nFix the bounds checking for the NFSv3 WRITE procedure to check whether the\nlength of the opaque data being written is present in the captured data,\nnot just whether the byte count is present in the captured data.\nfurthest forward in the packet, not the item before it. (This also lets\nus eliminate the check for the \"stable\" argument being present in the\ncaptured data; rewrite the code to print that to make it a bit clearer.)\n\nCheck that the entire ar_stat field is present in the capture.\n\nNote that parse_wcc_attr() is called after we've already checked whether\nthe wcc_data is present.\n\nCheck before fetching the \"access\" part of the NFSv3 ACCESS results.\nThis fixes a buffer over-read discovered by Kamil Frankowicz.\n\nInclude a test for the \"check before fetching the \"access\" part...\" fix,\nusing the capture supplied by the reporter(s).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int interpret_errors(void)\n{\n\tchar bad;\n\n\tif (inr != 7) {\n\t\tDPRINT(\"-- FDC reply error\\n\");\n\t\tfdc_state[current_fdc].reset = 1;\n\t\treturn 1;\n\t}\n\n\t/* check IC to find cause of interrupt */\n\tswitch (reply_buffer[ST0] & ST0_INTR) {\n\tcase 0x40:\t\t/* error occurred during command execution */\n\t\tif (reply_buffer[ST1] & ST1_EOC)\n\t\t\treturn 0;\t/* occurs with pseudo-DMA */\n\t\tbad = 1;\n\t\tif (reply_buffer[ST1] & ST1_WP) {\n\t\t\tDPRINT(\"Drive is write protected\\n\");\n\t\t\tclear_bit(FD_DISK_WRITABLE_BIT,\n\t\t\t\t &drive_state[current_drive].flags);\n\t\t\tcont->done(0);\n\t\t\tbad = 2;\n\t\t} else if (reply_buffer[ST1] & ST1_ND) {\n\t\t\tset_bit(FD_NEED_TWADDLE_BIT,\n\t\t\t\t&drive_state[current_drive].flags);\n\t\t} else if (reply_buffer[ST1] & ST1_OR) {\n\t\t\tif (drive_params[current_drive].flags & FTD_MSG)\n\t\t\t\tDPRINT(\"Over/Underrun - retrying\\n\");\n\t\t\tbad = 0;\n\t\t} else if (*errors >= drive_params[current_drive].max_errors.reporting) {\n\t\t\tprint_errors();\n\t\t}\n\t\tif (reply_buffer[ST2] & ST2_WC || reply_buffer[ST2] & ST2_BC)\n\t\t\t/* wrong cylinder => recal */\n\t\t\tdrive_state[current_drive].track = NEED_2_RECAL;\n\t\treturn bad;\n\tcase 0x80:\t\t/* invalid command given */\n\t\tDPRINT(\"Invalid FDC command given!\\n\");\n\t\tcont->done(0);\n\t\treturn 2;\n\tcase 0xc0:\n\t\tDPRINT(\"Abnormal termination caused by polling\\n\");\n\t\tcont->error();\n\t\treturn 2;\n\tdefault:\t\t/* (0) Normal command termination */\n\t\treturn 0;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'floppy: use a statically allocated error counter\n\nInterrupt handler bad_flp_intr() may cause a UAF on the recently freed\nrequest just to increment the error count. There's no point keeping\nthat one in the request anyway, and since the interrupt handler uses a\nstatic pointer to the error which cannot be kept in sync with the\npending request, better make it use a static error counter that's reset\nfor each new request. This reset now happens when entering\nredo_fd_request() for a new request via set_next_request().\n\nOne initial concern about a single error counter was that errors on one\nfloppy drive could be reported on another one, but this problem is not\nreal given that the driver uses a single drive at a time, as that\nPC-compatible controllers also have this limitation by using shared\nsignals. As such the error count is always for the \"current\" drive.\n\nReported-by: Minh Yuan \nSuggested-by: Linus Torvalds \nTested-by: Denis Efremov \nSigned-off-by: Willy Tarreau \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: fst_get_iface(struct fst_card_info *card, struct fst_port_info *port,\n\t struct ifreq *ifr)\n{\n\tsync_serial_settings sync;\n\tint i;\n\n\t/* First check what line type is set, we'll default to reporting X.21\n\t * if nothing is set as IF_IFACE_SYNC_SERIAL implies it can't be\n\t * changed\n\t */\n\tswitch (port->hwif) {\n\tcase E1:\n\t\tifr->ifr_settings.type = IF_IFACE_E1;\n\t\tbreak;\n\tcase T1:\n\t\tifr->ifr_settings.type = IF_IFACE_T1;\n\t\tbreak;\n\tcase V35:\n\t\tifr->ifr_settings.type = IF_IFACE_V35;\n\t\tbreak;\n\tcase V24:\n\t\tifr->ifr_settings.type = IF_IFACE_V24;\n\t\tbreak;\n\tcase X21D:\n\t\tifr->ifr_settings.type = IF_IFACE_X21D;\n\t\tbreak;\n\tcase X21:\n\tdefault:\n\t\tifr->ifr_settings.type = IF_IFACE_X21;\n\t\tbreak;\n\t}\n\tif (ifr->ifr_settings.size == 0) {\n\t\treturn 0;\t/* only type requested */\n\t}\n\tif (ifr->ifr_settings.size < sizeof (sync)) {\n\t\treturn -ENOMEM;\n\t}\n\n\ti = port->index;\n\tsync.clock_rate = FST_RDL(card, portConfig[i].lineSpeed);\n\t/* Lucky card and linux use same encoding here */\n\tsync.clock_type = FST_RDB(card, portConfig[i].internalClock) ==\n\t INTCLK ? CLOCK_INT : CLOCK_EXT;\n\tsync.loopback = 0;\n\n\tif (copy_to_user(ifr->ifr_settings.ifs_ifsu.sync, &sync, sizeof (sync))) {\n\t\treturn -EFAULT;\n\t}\n\n\tifr->ifr_settings.size = sizeof (sync);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'farsync: fix info leak in ioctl\n\nThe fst_get_iface() code fails to initialize the two padding bytes of\nstruct sync_serial_settings after the ->loopback member. Add an explicit\nmemset(0) before filling the structure to avoid the info leak.\n\nSigned-off-by: Dan Carpenter \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: mrb_vm_exec(mrb_state *mrb, const struct RProc *proc, const mrb_code *pc)\n{\n /* mrb_assert(MRB_PROC_CFUNC_P(proc)) */\n const mrb_irep *irep = proc->body.irep;\n const mrb_pool_value *pool = irep->pool;\n const mrb_sym *syms = irep->syms;\n mrb_code insn;\n int ai = mrb_gc_arena_save(mrb);\n struct mrb_jmpbuf *prev_jmp = mrb->jmp;\n struct mrb_jmpbuf c_jmp;\n uint32_t a;\n uint16_t b;\n uint16_t c;\n mrb_sym mid;\n const struct mrb_irep_catch_handler *ch;\n\n#ifdef DIRECT_THREADED\n static const void * const optable[] = {\n#define OPCODE(x,_) &&L_OP_ ## x,\n#include \"mruby/ops.h\"\n#undef OPCODE\n };\n#endif\n\n mrb_bool exc_catched = FALSE;\nRETRY_TRY_BLOCK:\n\n MRB_TRY(&c_jmp) {\n\n if (exc_catched) {\n exc_catched = FALSE;\n mrb_gc_arena_restore(mrb, ai);\n if (mrb->exc && mrb->exc->tt == MRB_TT_BREAK)\n goto L_BREAK;\n goto L_RAISE;\n }\n mrb->jmp = &c_jmp;\n mrb_vm_ci_proc_set(mrb->c->ci, proc);\n\n#define regs (mrb->c->ci->stack)\n INIT_DISPATCH {\n CASE(OP_NOP, Z) {\n /* do nothing */\n NEXT;\n }\n\n CASE(OP_MOVE, BB) {\n regs[a] = regs[b];\n NEXT;\n }\n\n CASE(OP_LOADL, BB) {\n switch (pool[b].tt) { /* number */\n case IREP_TT_INT32:\n regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i32);\n break;\n case IREP_TT_INT64:\n#if defined(MRB_INT64)\n regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i64);\n break;\n#else\n#if defined(MRB_64BIT)\n if (INT32_MIN <= pool[b].u.i64 && pool[b].u.i64 <= INT32_MAX) {\n regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i64);\n break;\n }\n#endif\n goto L_INT_OVERFLOW;\n#endif\n case IREP_TT_BIGINT:\n goto L_INT_OVERFLOW;\n#ifndef MRB_NO_FLOAT\n case IREP_TT_FLOAT:\n regs[a] = mrb_float_value(mrb, pool[b].u.f);\n break;\n#endif\n default:\n /* should not happen (tt:string) */\n regs[a] = mrb_nil_value();\n break;\n }\n NEXT;\n }\n\n CASE(OP_LOADI, BB) {\n SET_FIXNUM_VALUE(regs[a], b);\n NEXT;\n }\n\n CASE(OP_LOADINEG, BB) {\n SET_FIXNUM_VALUE(regs[a], -b);\n NEXT;\n }\n\n CASE(OP_LOADI__1,B) goto L_LOADI;\n CASE(OP_LOADI_0,B) goto L_LOADI;\n CASE(OP_LOADI_1,B) goto L_LOADI;\n CASE(OP_LOADI_2,B) goto L_LOADI;\n CASE(OP_LOADI_3,B) goto L_LOADI;\n CASE(OP_LOADI_4,B) goto L_LOADI;\n CASE(OP_LOADI_5,B) goto L_LOADI;\n CASE(OP_LOADI_6,B) goto L_LOADI;\n CASE(OP_LOADI_7, B) {\n L_LOADI:\n SET_FIXNUM_VALUE(regs[a], (mrb_int)insn - (mrb_int)OP_LOADI_0);\n NEXT;\n }\n\n CASE(OP_LOADI16, BS) {\n SET_FIXNUM_VALUE(regs[a], (mrb_int)(int16_t)b);\n NEXT;\n }\n\n CASE(OP_LOADI32, BSS) {\n SET_INT_VALUE(mrb, regs[a], (int32_t)(((uint32_t)b<<16)+c));\n NEXT;\n }\n\n CASE(OP_LOADSYM, BB) {\n SET_SYM_VALUE(regs[a], syms[b]);\n NEXT;\n }\n\n CASE(OP_LOADNIL, B) {\n SET_NIL_VALUE(regs[a]);\n NEXT;\n }\n\n CASE(OP_LOADSELF, B) {\n regs[a] = regs[0];\n NEXT;\n }\n\n CASE(OP_LOADT, B) {\n SET_TRUE_VALUE(regs[a]);\n NEXT;\n }\n\n CASE(OP_LOADF, B) {\n SET_FALSE_VALUE(regs[a]);\n NEXT;\n }\n\n CASE(OP_GETGV, BB) {\n mrb_value val = mrb_gv_get(mrb, syms[b]);\n regs[a] = val;\n NEXT;\n }\n\n CASE(OP_SETGV, BB) {\n mrb_gv_set(mrb, syms[b], regs[a]);\n NEXT;\n }\n\n CASE(OP_GETSV, BB) {\n mrb_value val = mrb_vm_special_get(mrb, syms[b]);\n regs[a] = val;\n NEXT;\n }\n\n CASE(OP_SETSV, BB) {\n mrb_vm_special_set(mrb, syms[b], regs[a]);\n NEXT;\n }\n\n CASE(OP_GETIV, BB) {\n regs[a] = mrb_iv_get(mrb, regs[0], syms[b]);\n NEXT;\n }\n\n CASE(OP_SETIV, BB) {\n mrb_iv_set(mrb, regs[0], syms[b], regs[a]);\n NEXT;\n }\n\n CASE(OP_GETCV, BB) {\n mrb_value val;\n val = mrb_vm_cv_get(mrb, syms[b]);\n regs[a] = val;\n NEXT;\n }\n\n CASE(OP_SETCV, BB) {\n mrb_vm_cv_set(mrb, syms[b], regs[a]);\n NEXT;\n }\n\n CASE(OP_GETIDX, B) {\n mrb_value va = regs[a], vb = regs[a+1];\n switch (mrb_type(va)) {\n case MRB_TT_ARRAY:\n if (!mrb_integer_p(vb)) goto getidx_fallback;\n regs[a] = mrb_ary_entry(va, mrb_integer(vb));\n break;\n case MRB_TT_HASH:\n va = mrb_hash_get(mrb, va, vb);\n regs[a] = va;\n break;\n case MRB_TT_STRING:\n switch (mrb_type(vb)) {\n case MRB_TT_INTEGER:\n case MRB_TT_STRING:\n case MRB_TT_RANGE:\n va = mrb_str_aref(mrb, va, vb, mrb_undef_value());\n regs[a] = va;\n break;\n default:\n goto getidx_fallback;\n }\n break;\n default:\n getidx_fallback:\n mid = MRB_OPSYM(aref);\n goto L_SEND_SYM;\n }\n NEXT;\n }\n\n CASE(OP_SETIDX, B) {\n c = 2;\n mid = MRB_OPSYM(aset);\n SET_NIL_VALUE(regs[a+3]);\n goto L_SENDB_SYM;\n }\n\n CASE(OP_GETCONST, BB) {\n mrb_value v = mrb_vm_const_get(mrb, syms[b]);\n regs[a] = v;\n NEXT;\n }\n\n CASE(OP_SETCONST, BB) {\n mrb_vm_const_set(mrb, syms[b], regs[a]);\n NEXT;\n }\n\n CASE(OP_GETMCNST, BB) {\n mrb_value v = mrb_const_get(mrb, regs[a], syms[b]);\n regs[a] = v;\n NEXT;\n }\n\n CASE(OP_SETMCNST, BB) {\n mrb_const_set(mrb, regs[a+1], syms[b], regs[a]);\n NEXT;\n }\n\n CASE(OP_GETUPVAR, BBB) {\n mrb_value *regs_a = regs + a;\n struct REnv *e = uvenv(mrb, c);\n\n if (e && b < MRB_ENV_LEN(e)) {\n *regs_a = e->stack[b];\n }\n else {\n *regs_a = mrb_nil_value();\n }\n NEXT;\n }\n\n CASE(OP_SETUPVAR, BBB) {\n struct REnv *e = uvenv(mrb, c);\n\n if (e) {\n mrb_value *regs_a = regs + a;\n\n if (b < MRB_ENV_LEN(e)) {\n e->stack[b] = *regs_a;\n mrb_write_barrier(mrb, (struct RBasic*)e);\n }\n }\n NEXT;\n }\n\n CASE(OP_JMP, S) {\n pc += (int16_t)a;\n JUMP;\n }\n CASE(OP_JMPIF, BS) {\n if (mrb_test(regs[a])) {\n pc += (int16_t)b;\n JUMP;\n }\n NEXT;\n }\n CASE(OP_JMPNOT, BS) {\n if (!mrb_test(regs[a])) {\n pc += (int16_t)b;\n JUMP;\n }\n NEXT;\n }\n CASE(OP_JMPNIL, BS) {\n if (mrb_nil_p(regs[a])) {\n pc += (int16_t)b;\n JUMP;\n }\n NEXT;\n }\n\n CASE(OP_JMPUW, S) {\n a = (uint32_t)((pc - irep->iseq) + (int16_t)a);\n CHECKPOINT_RESTORE(RBREAK_TAG_JUMP) {\n struct RBreak *brk = (struct RBreak*)mrb->exc;\n mrb_value target = mrb_break_value_get(brk);\n mrb_assert(mrb_integer_p(target));\n a = (uint32_t)mrb_integer(target);\n mrb_assert(a >= 0 && a < irep->ilen);\n }\n CHECKPOINT_MAIN(RBREAK_TAG_JUMP) {\n ch = catch_handler_find(mrb, mrb->c->ci, pc, MRB_CATCH_FILTER_ENSURE);\n if (ch) {\n /* avoiding a jump from a catch handler into the same handler */\n if (a < mrb_irep_catch_handler_unpack(ch->begin) || a >= mrb_irep_catch_handler_unpack(ch->end)) {\n THROW_TAGGED_BREAK(mrb, RBREAK_TAG_JUMP, proc, mrb_fixnum_value(a));\n }\n }\n }\n CHECKPOINT_END(RBREAK_TAG_JUMP);\n\n mrb->exc = NULL; /* clear break object */\n pc = irep->iseq + a;\n JUMP;\n }\n\n CASE(OP_EXCEPT, B) {\n mrb_value exc;\n\n if (mrb->exc == NULL) {\n exc = mrb_nil_value();\n }\n else {\n switch (mrb->exc->tt) {\n case MRB_TT_BREAK:\n case MRB_TT_EXCEPTION:\n exc = mrb_obj_value(mrb->exc);\n break;\n default:\n mrb_assert(!\"bad mrb_type\");\n exc = mrb_nil_value();\n break;\n }\n mrb->exc = NULL;\n }\n regs[a] = exc;\n NEXT;\n }\n CASE(OP_RESCUE, BB) {\n mrb_value exc = regs[a]; /* exc on stack */\n mrb_value e = regs[b];\n struct RClass *ec;\n\n switch (mrb_type(e)) {\n case MRB_TT_CLASS:\n case MRB_TT_MODULE:\n break;\n default:\n {\n mrb_value exc;\n\n exc = mrb_exc_new_lit(mrb, E_TYPE_ERROR,\n \"class or module required for rescue clause\");\n mrb_exc_set(mrb, exc);\n goto L_RAISE;\n }\n }\n ec = mrb_class_ptr(e);\n regs[b] = mrb_bool_value(mrb_obj_is_kind_of(mrb, exc, ec));\n NEXT;\n }\n\n CASE(OP_RAISEIF, B) {\n mrb_value exc = regs[a];\n if (mrb_break_p(exc)) {\n mrb->exc = mrb_obj_ptr(exc);\n goto L_BREAK;\n }\n mrb_exc_set(mrb, exc);\n if (mrb->exc) {\n goto L_RAISE;\n }\n NEXT;\n }\n\n CASE(OP_SSEND, BBB) {\n regs[a] = regs[0];\n insn = OP_SEND;\n }\n goto L_SENDB;\n\n CASE(OP_SSENDB, BBB) {\n regs[a] = regs[0];\n }\n goto L_SENDB;\n\n CASE(OP_SEND, BBB)\n goto L_SENDB;\n\n L_SEND_SYM:\n c = 1;\n /* push nil after arguments */\n SET_NIL_VALUE(regs[a+2]);\n goto L_SENDB_SYM;\n\n CASE(OP_SENDB, BBB)\n L_SENDB:\n mid = syms[b];\n L_SENDB_SYM:\n {\n mrb_callinfo *ci = mrb->c->ci;\n mrb_method_t m;\n struct RClass *cls;\n mrb_value recv, blk;\n\n ARGUMENT_NORMALIZE(a, &c, insn);\n\n recv = regs[a];\n cls = mrb_class(mrb, recv);\n m = mrb_method_search_vm(mrb, &cls, mid);\n if (MRB_METHOD_UNDEF_P(m)) {\n m = prepare_missing(mrb, recv, mid, &cls, a, &c, blk, 0);\n mid = MRB_SYM(method_missing);\n }\n\n /* push callinfo */\n ci = cipush(mrb, a, 0, cls, NULL, mid, c);\n\n if (MRB_METHOD_CFUNC_P(m)) {\n if (MRB_METHOD_PROC_P(m)) {\n struct RProc *p = MRB_METHOD_PROC(m);\n\n mrb_vm_ci_proc_set(ci, p);\n recv = p->body.func(mrb, recv);\n }\n else {\n if (MRB_METHOD_NOARG_P(m)) {\n check_method_noarg(mrb, ci);\n }\n recv = MRB_METHOD_FUNC(m)(mrb, recv);\n }\n mrb_gc_arena_shrink(mrb, ai);\n if (mrb->exc) goto L_RAISE;\n ci = mrb->c->ci;\n if (mrb_proc_p(blk)) {\n struct RProc *p = mrb_proc_ptr(blk);\n if (p && !MRB_PROC_STRICT_P(p) && MRB_PROC_ENV(p) == mrb_vm_ci_env(&ci[-1])) {\n p->flags |= MRB_PROC_ORPHAN;\n }\n }\n if (!ci->u.target_class) { /* return from context modifying method (resume/yield) */\n if (ci->cci == CINFO_RESUMED) {\n mrb->jmp = prev_jmp;\n return recv;\n }\n else {\n mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc));\n proc = ci[-1].proc;\n irep = proc->body.irep;\n pool = irep->pool;\n syms = irep->syms;\n }\n }\n ci->stack[0] = recv;\n /* pop stackpos */\n ci = cipop(mrb);\n pc = ci->pc;\n }\n else {\n /* setup environment for calling method */\n mrb_vm_ci_proc_set(ci, (proc = MRB_METHOD_PROC(m)));\n irep = proc->body.irep;\n pool = irep->pool;\n syms = irep->syms;\n mrb_stack_extend(mrb, (irep->nregs < 4) ? 4 : irep->nregs);\n pc = irep->iseq;\n }\n }\n JUMP;\n\n CASE(OP_CALL, Z) {\n mrb_callinfo *ci = mrb->c->ci;\n mrb_value recv = ci->stack[0];\n struct RProc *m = mrb_proc_ptr(recv);\n\n /* replace callinfo */\n ci->u.target_class = MRB_PROC_TARGET_CLASS(m);\n mrb_vm_ci_proc_set(ci, m);\n if (MRB_PROC_ENV_P(m)) {\n ci->mid = MRB_PROC_ENV(m)->mid;\n }\n\n /* prepare stack */\n if (MRB_PROC_CFUNC_P(m)) {\n recv = MRB_PROC_CFUNC(m)(mrb, recv);\n mrb_gc_arena_shrink(mrb, ai);\n if (mrb->exc) goto L_RAISE;\n /* pop stackpos */\n ci = cipop(mrb);\n pc = ci->pc;\n ci[1].stack[0] = recv;\n irep = mrb->c->ci->proc->body.irep;\n }\n else {\n /* setup environment for calling method */\n proc = m;\n irep = m->body.irep;\n if (!irep) {\n mrb->c->ci->stack[0] = mrb_nil_value();\n a = 0;\n c = OP_R_NORMAL;\n goto L_OP_RETURN_BODY;\n }\n mrb_int nargs = mrb_ci_bidx(ci)+1;\n if (nargs < irep->nregs) {\n mrb_stack_extend(mrb, irep->nregs);\n stack_clear(regs+nargs, irep->nregs-nargs);\n }\n if (MRB_PROC_ENV_P(m)) {\n regs[0] = MRB_PROC_ENV(m)->stack[0];\n }\n pc = irep->iseq;\n }\n pool = irep->pool;\n syms = irep->syms;\n JUMP;\n }\n\n CASE(OP_SUPER, BB) {\n mrb_method_t m;\n struct RClass *cls;\n mrb_callinfo *ci = mrb->c->ci;\n mrb_value recv, blk;\n const struct RProc *p = ci->proc;\n mrb_sym mid = ci->mid;\n struct RClass* target_class = MRB_PROC_TARGET_CLASS(p);\n\n if (MRB_PROC_ENV_P(p) && p->e.env->mid && p->e.env->mid != mid) { /* alias support */\n mid = p->e.env->mid; /* restore old mid */\n }\n\n if (mid == 0 || !target_class) {\n mrb_value exc = mrb_exc_new_lit(mrb, E_NOMETHOD_ERROR, \"super called outside of method\");\n mrb_exc_set(mrb, exc);\n goto L_RAISE;\n }\n if (target_class->flags & MRB_FL_CLASS_IS_PREPENDED) {\n target_class = mrb_vm_ci_target_class(ci);\n }\n else if (target_class->tt == MRB_TT_MODULE) {\n target_class = mrb_vm_ci_target_class(ci);\n if (!target_class || target_class->tt != MRB_TT_ICLASS) {\n goto super_typeerror;\n }\n }\n recv = regs[0];\n if (!mrb_obj_is_kind_of(mrb, recv, target_class)) {\n super_typeerror: ;\n mrb_value exc = mrb_exc_new_lit(mrb, E_TYPE_ERROR,\n \"self has wrong type to call super in this context\");\n mrb_exc_set(mrb, exc);\n goto L_RAISE;\n }\n\n ARGUMENT_NORMALIZE(a, &b, OP_SUPER);\n\n cls = target_class->super;\n m = mrb_method_search_vm(mrb, &cls, mid);\n if (MRB_METHOD_UNDEF_P(m)) {\n m = prepare_missing(mrb, recv, mid, &cls, a, &b, blk, 1);\n mid = MRB_SYM(method_missing);\n }\n\n /* push callinfo */\n ci = cipush(mrb, a, 0, cls, NULL, mid, b);\n\n /* prepare stack */\n ci->stack[0] = recv;\n\n if (MRB_METHOD_CFUNC_P(m)) {\n mrb_value v;\n\n if (MRB_METHOD_PROC_P(m)) {\n mrb_vm_ci_proc_set(ci, MRB_METHOD_PROC(m));\n }\n v = MRB_METHOD_CFUNC(m)(mrb, recv);\n mrb_gc_arena_restore(mrb, ai);\n if (mrb->exc) goto L_RAISE;\n ci = mrb->c->ci;\n mrb_assert(!mrb_break_p(v));\n if (!mrb_vm_ci_target_class(ci)) { /* return from context modifying method (resume/yield) */\n if (ci->cci == CINFO_RESUMED) {\n mrb->jmp = prev_jmp;\n return v;\n }\n else {\n mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc));\n proc = ci[-1].proc;\n irep = proc->body.irep;\n pool = irep->pool;\n syms = irep->syms;\n }\n }\n mrb->c->ci->stack[0] = v;\n ci = cipop(mrb);\n pc = ci->pc;\n }\n else {\n /* setup environment for calling method */\n mrb_vm_ci_proc_set(ci, (proc = MRB_METHOD_PROC(m)));\n irep = proc->body.irep;\n pool = irep->pool;\n syms = irep->syms;\n mrb_stack_extend(mrb, (irep->nregs < 4) ? 4 : irep->nregs);\n pc = irep->iseq;\n }\n JUMP;\n }\n\n CASE(OP_ARGARY, BS) {\n mrb_int m1 = (b>>11)&0x3f;\n mrb_int r = (b>>10)&0x1;\n mrb_int m2 = (b>>5)&0x1f;\n mrb_int kd = (b>>4)&0x1;\n mrb_int lv = (b>>0)&0xf;\n mrb_value *stack;\n\n if (mrb->c->ci->mid == 0 || mrb_vm_ci_target_class(mrb->c->ci) == NULL) {\n mrb_value exc;\n\n L_NOSUPER:\n exc = mrb_exc_new_lit(mrb, E_NOMETHOD_ERROR, \"super called outside of method\");\n mrb_exc_set(mrb, exc);\n goto L_RAISE;\n }\n if (lv == 0) stack = regs + 1;\n else {\n struct REnv *e = uvenv(mrb, lv-1);\n if (!e) goto L_NOSUPER;\n if (MRB_ENV_LEN(e) <= m1+r+m2+1)\n goto L_NOSUPER;\n stack = e->stack + 1;\n }\n if (r == 0) {\n regs[a] = mrb_ary_new_from_values(mrb, m1+m2, stack);\n }\n else {\n mrb_value *pp = NULL;\n struct RArray *rest;\n mrb_int len = 0;\n\n if (mrb_array_p(stack[m1])) {\n struct RArray *ary = mrb_ary_ptr(stack[m1]);\n\n pp = ARY_PTR(ary);\n len = ARY_LEN(ary);\n }\n regs[a] = mrb_ary_new_capa(mrb, m1+len+m2);\n rest = mrb_ary_ptr(regs[a]);\n if (m1 > 0) {\n stack_copy(ARY_PTR(rest), stack, m1);\n }\n if (len > 0) {\n stack_copy(ARY_PTR(rest)+m1, pp, len);\n }\n if (m2 > 0) {\n stack_copy(ARY_PTR(rest)+m1+len, stack+m1+1, m2);\n }\n ARY_SET_LEN(rest, m1+len+m2);\n }\n if (kd) {\n regs[a+1] = stack[m1+r+m2];\n regs[a+2] = stack[m1+r+m2+1];\n }\n else {\n regs[a+1] = stack[m1+r+m2];\n }\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_ENTER, W) {\n mrb_int m1 = MRB_ASPEC_REQ(a);\n mrb_int o = MRB_ASPEC_OPT(a);\n mrb_int r = MRB_ASPEC_REST(a);\n mrb_int m2 = MRB_ASPEC_POST(a);\n mrb_int kd = (MRB_ASPEC_KEY(a) > 0 || MRB_ASPEC_KDICT(a))? 1 : 0;\n /* unused\n int b = MRB_ASPEC_BLOCK(a);\n */\n mrb_int const len = m1 + o + r + m2;\n\n mrb_callinfo *ci = mrb->c->ci;\n mrb_int argc = ci->n;\n mrb_value *argv = regs+1;\n mrb_value * const argv0 = argv;\n mrb_int const kw_pos = len + kd; /* where kwhash should be */\n mrb_int const blk_pos = kw_pos + 1; /* where block should be */\n mrb_value blk = regs[mrb_ci_bidx(ci)];\n mrb_value kdict = mrb_nil_value();\n\n /* keyword arguments */\n if (ci->nk > 0) {\n mrb_int kidx = mrb_ci_kidx(ci);\n kdict = regs[kidx];\n if (!mrb_hash_p(kdict) || mrb_hash_size(mrb, kdict) == 0) {\n kdict = mrb_nil_value();\n ci->nk = 0;\n }\n }\n if (!kd && !mrb_nil_p(kdict)) {\n if (argc < 14) {\n ci->n++;\n argc++; /* include kdict in normal arguments */\n }\n else if (argc == 14) {\n /* pack arguments and kdict */\n regs[1] = mrb_ary_new_from_values(mrb, argc+1, ®s[1]);\n argc = ci->n = 15;\n }\n else {/* argc == 15 */\n /* push kdict to packed arguments */\n mrb_ary_push(mrb, regs[1], regs[2]);\n }\n ci->nk = 0;\n }\n if (kd && MRB_ASPEC_KEY(a) > 0 && mrb_hash_p(kdict)) {\n kdict = mrb_hash_dup(mrb, kdict);\n }\n\n /* arguments is passed with Array */\n if (argc == 15) {\n struct RArray *ary = mrb_ary_ptr(regs[1]);\n argv = ARY_PTR(ary);\n argc = (int)ARY_LEN(ary);\n mrb_gc_protect(mrb, regs[1]);\n }\n\n /* strict argument check */\n if (ci->proc && MRB_PROC_STRICT_P(ci->proc)) {\n if (argc < m1 + m2 || (r == 0 && argc > len)) {\n argnum_error(mrb, m1+m2);\n goto L_RAISE;\n }\n }\n /* extract first argument array to arguments */\n else if (len > 1 && argc == 1 && mrb_array_p(argv[0])) {\n mrb_gc_protect(mrb, argv[0]);\n argc = (int)RARRAY_LEN(argv[0]);\n argv = RARRAY_PTR(argv[0]);\n }\n\n /* rest arguments */\n mrb_value rest = mrb_nil_value();\n if (argc < len) {\n mrb_int mlen = m2;\n if (argc < m1+m2) {\n mlen = m1 < argc ? argc - m1 : 0;\n }\n\n /* copy mandatory and optional arguments */\n if (argv0 != argv && argv) {\n value_move(®s[1], argv, argc-mlen); /* m1 + o */\n }\n if (argc < m1) {\n stack_clear(®s[argc+1], m1-argc);\n }\n /* copy post mandatory arguments */\n if (mlen) {\n value_move(®s[len-m2+1], &argv[argc-mlen], mlen);\n }\n if (mlen < m2) {\n stack_clear(®s[len-m2+mlen+1], m2-mlen);\n }\n /* initialize rest arguments with empty Array */\n if (r) {\n rest = mrb_ary_new_capa(mrb, 0);\n regs[m1+o+1] = rest;\n }\n /* skip initializer of passed arguments */\n if (o > 0 && argc > m1+m2)\n pc += (argc - m1 - m2)*3;\n }\n else {\n mrb_int rnum = 0;\n if (argv0 != argv) {\n value_move(®s[1], argv, m1+o);\n }\n if (r) {\n rnum = argc-m1-o-m2;\n rest = mrb_ary_new_from_values(mrb, rnum, argv+m1+o);\n regs[m1+o+1] = rest;\n }\n if (m2 > 0 && argc-m2 > m1) {\n value_move(®s[m1+o+r+1], &argv[m1+o+rnum], m2);\n }\n pc += o*3;\n }\n\n /* need to be update blk first to protect blk from GC */\n regs[blk_pos] = blk; /* move block */\n if (kd) {\n if (mrb_nil_p(kdict))\n kdict = mrb_hash_new_capa(mrb, 0);\n regs[kw_pos] = kdict; /* set kwhash */\n }\n\n /* format arguments for generated code */\n mrb->c->ci->n = len;\n\n /* clear local (but non-argument) variables */\n if (irep->nlocals-blk_pos-1 > 0) {\n stack_clear(®s[blk_pos+1], irep->nlocals-blk_pos-1);\n }\n JUMP;\n }\n\n CASE(OP_KARG, BB) {\n mrb_value k = mrb_symbol_value(syms[b]);\n mrb_int kidx = mrb_ci_kidx(mrb->c->ci);\n mrb_value kdict, v;\n\n if (kidx < 0 || !mrb_hash_p(kdict=regs[kidx]) || !mrb_hash_key_p(mrb, kdict, k)) {\n mrb_value str = mrb_format(mrb, \"missing keyword: %v\", k);\n mrb_exc_set(mrb, mrb_exc_new_str(mrb, E_ARGUMENT_ERROR, str));\n goto L_RAISE;\n }\n v = mrb_hash_get(mrb, kdict, k);\n regs[a] = v;\n mrb_hash_delete_key(mrb, kdict, k);\n NEXT;\n }\n\n CASE(OP_KEY_P, BB) {\n mrb_value k = mrb_symbol_value(syms[b]);\n mrb_int kidx = mrb_ci_kidx(mrb->c->ci);\n mrb_value kdict;\n mrb_bool key_p = FALSE;\n\n if (kidx >= 0 && mrb_hash_p(kdict=regs[kidx])) {\n key_p = mrb_hash_key_p(mrb, kdict, k);\n }\n regs[a] = mrb_bool_value(key_p);\n NEXT;\n }\n\n CASE(OP_KEYEND, Z) {\n mrb_int kidx = mrb_ci_kidx(mrb->c->ci);\n mrb_value kdict;\n\n if (kidx >= 0 && mrb_hash_p(kdict=regs[kidx]) && !mrb_hash_empty_p(mrb, kdict)) {\n mrb_value keys = mrb_hash_keys(mrb, kdict);\n mrb_value key1 = RARRAY_PTR(keys)[0];\n mrb_value str = mrb_format(mrb, \"unknown keyword: %v\", key1);\n mrb_exc_set(mrb, mrb_exc_new_str(mrb, E_ARGUMENT_ERROR, str));\n goto L_RAISE;\n }\n NEXT;\n }\n\n CASE(OP_BREAK, B) {\n c = OP_R_BREAK;\n goto L_RETURN;\n }\n CASE(OP_RETURN_BLK, B) {\n c = OP_R_RETURN;\n goto L_RETURN;\n }\n CASE(OP_RETURN, B)\n c = OP_R_NORMAL;\n L_RETURN:\n {\n mrb_callinfo *ci;\n\n ci = mrb->c->ci;\n if (ci->mid) {\n mrb_value blk = regs[mrb_ci_bidx(ci)];\n\n if (mrb_proc_p(blk)) {\n struct RProc *p = mrb_proc_ptr(blk);\n\n if (!MRB_PROC_STRICT_P(p) &&\n ci > mrb->c->cibase && MRB_PROC_ENV(p) == mrb_vm_ci_env(&ci[-1])) {\n p->flags |= MRB_PROC_ORPHAN;\n }\n }\n }\n\n if (mrb->exc) {\n L_RAISE:\n ci = mrb->c->ci;\n if (ci == mrb->c->cibase) {\n ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL);\n if (ch == NULL) goto L_FTOP;\n goto L_CATCH;\n }\n while ((ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL)) == NULL) {\n ci = cipop(mrb);\n if (ci[1].cci == CINFO_SKIP && prev_jmp) {\n mrb->jmp = prev_jmp;\n MRB_THROW(prev_jmp);\n }\n pc = ci[0].pc;\n if (ci == mrb->c->cibase) {\n ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL);\n if (ch == NULL) {\n L_FTOP: /* fiber top */\n if (mrb->c == mrb->root_c) {\n mrb->c->ci->stack = mrb->c->stbase;\n goto L_STOP;\n }\n else {\n struct mrb_context *c = mrb->c;\n\n c->status = MRB_FIBER_TERMINATED;\n mrb->c = c->prev;\n c->prev = NULL;\n goto L_RAISE;\n }\n }\n break;\n }\n }\n L_CATCH:\n if (ch == NULL) goto L_STOP;\n if (FALSE) {\n L_CATCH_TAGGED_BREAK: /* from THROW_TAGGED_BREAK() or UNWIND_ENSURE() */\n ci = mrb->c->ci;\n }\n proc = ci->proc;\n irep = proc->body.irep;\n pool = irep->pool;\n syms = irep->syms;\n mrb_stack_extend(mrb, irep->nregs);\n pc = irep->iseq + mrb_irep_catch_handler_unpack(ch->target);\n }\n else {\n mrb_int acc;\n mrb_value v;\n\n ci = mrb->c->ci;\n v = regs[a];\n mrb_gc_protect(mrb, v);\n switch (c) {\n case OP_R_RETURN:\n /* Fall through to OP_R_NORMAL otherwise */\n if (ci->cci == CINFO_NONE && MRB_PROC_ENV_P(proc) && !MRB_PROC_STRICT_P(proc)) {\n const struct RProc *dst;\n mrb_callinfo *cibase;\n cibase = mrb->c->cibase;\n dst = top_proc(mrb, proc);\n\n if (MRB_PROC_ENV_P(dst)) {\n struct REnv *e = MRB_PROC_ENV(dst);\n\n if (!MRB_ENV_ONSTACK_P(e) || (e->cxt && e->cxt != mrb->c)) {\n localjump_error(mrb, LOCALJUMP_ERROR_RETURN);\n goto L_RAISE;\n }\n }\n /* check jump destination */\n while (cibase <= ci && ci->proc != dst) {\n if (ci->cci > CINFO_NONE) { /* jump cross C boundary */\n localjump_error(mrb, LOCALJUMP_ERROR_RETURN);\n goto L_RAISE;\n }\n ci--;\n }\n if (ci <= cibase) { /* no jump destination */\n localjump_error(mrb, LOCALJUMP_ERROR_RETURN);\n goto L_RAISE;\n }\n ci = mrb->c->ci;\n while (cibase <= ci && ci->proc != dst) {\n CHECKPOINT_RESTORE(RBREAK_TAG_RETURN_BLOCK) {\n cibase = mrb->c->cibase;\n dst = top_proc(mrb, proc);\n }\n CHECKPOINT_MAIN(RBREAK_TAG_RETURN_BLOCK) {\n UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN_BLOCK, proc, v);\n }\n CHECKPOINT_END(RBREAK_TAG_RETURN_BLOCK);\n ci = cipop(mrb);\n pc = ci->pc;\n }\n proc = ci->proc;\n mrb->exc = NULL; /* clear break object */\n break;\n }\n /* fallthrough */\n case OP_R_NORMAL:\n NORMAL_RETURN:\n if (ci == mrb->c->cibase) {\n struct mrb_context *c;\n c = mrb->c;\n\n if (!c->prev) { /* toplevel return */\n regs[irep->nlocals] = v;\n goto CHECKPOINT_LABEL_MAKE(RBREAK_TAG_STOP);\n }\n if (!c->vmexec && c->prev->ci == c->prev->cibase) {\n mrb_value exc = mrb_exc_new_lit(mrb, E_FIBER_ERROR, \"double resume\");\n mrb_exc_set(mrb, exc);\n goto L_RAISE;\n }\n CHECKPOINT_RESTORE(RBREAK_TAG_RETURN_TOPLEVEL) {\n c = mrb->c;\n }\n CHECKPOINT_MAIN(RBREAK_TAG_RETURN_TOPLEVEL) {\n UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN_TOPLEVEL, proc, v);\n }\n CHECKPOINT_END(RBREAK_TAG_RETURN_TOPLEVEL);\n /* automatic yield at the end */\n c->status = MRB_FIBER_TERMINATED;\n mrb->c = c->prev;\n mrb->c->status = MRB_FIBER_RUNNING;\n c->prev = NULL;\n if (c->vmexec) {\n mrb_gc_arena_restore(mrb, ai);\n c->vmexec = FALSE;\n mrb->jmp = prev_jmp;\n return v;\n }\n ci = mrb->c->ci;\n }\n CHECKPOINT_RESTORE(RBREAK_TAG_RETURN) {\n /* do nothing */\n }\n CHECKPOINT_MAIN(RBREAK_TAG_RETURN) {\n UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN, proc, v);\n }\n CHECKPOINT_END(RBREAK_TAG_RETURN);\n mrb->exc = NULL; /* clear break object */\n break;\n case OP_R_BREAK:\n if (MRB_PROC_STRICT_P(proc)) goto NORMAL_RETURN;\n if (MRB_PROC_ORPHAN_P(proc)) {\n mrb_value exc;\n\n L_BREAK_ERROR:\n exc = mrb_exc_new_lit(mrb, E_LOCALJUMP_ERROR,\n \"break from proc-closure\");\n mrb_exc_set(mrb, exc);\n goto L_RAISE;\n }\n if (!MRB_PROC_ENV_P(proc) || !MRB_ENV_ONSTACK_P(MRB_PROC_ENV(proc))) {\n goto L_BREAK_ERROR;\n }\n else {\n struct REnv *e = MRB_PROC_ENV(proc);\n\n if (e->cxt != mrb->c) {\n goto L_BREAK_ERROR;\n }\n }\n CHECKPOINT_RESTORE(RBREAK_TAG_BREAK) {\n /* do nothing */\n }\n CHECKPOINT_MAIN(RBREAK_TAG_BREAK) {\n UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK, proc, v);\n }\n CHECKPOINT_END(RBREAK_TAG_BREAK);\n /* break from fiber block */\n if (ci == mrb->c->cibase && ci->pc) {\n struct mrb_context *c = mrb->c;\n\n mrb->c = c->prev;\n c->prev = NULL;\n ci = mrb->c->ci;\n }\n if (ci->cci > CINFO_NONE) {\n ci = cipop(mrb);\n mrb_gc_arena_restore(mrb, ai);\n mrb->c->vmexec = FALSE;\n mrb->exc = (struct RObject*)break_new(mrb, RBREAK_TAG_BREAK, proc, v);\n mrb->jmp = prev_jmp;\n MRB_THROW(prev_jmp);\n }\n if (FALSE) {\n struct RBreak *brk;\n\n L_BREAK:\n brk = (struct RBreak*)mrb->exc;\n proc = mrb_break_proc_get(brk);\n v = mrb_break_value_get(brk);\n ci = mrb->c->ci;\n\n switch (mrb_break_tag_get(brk)) {\n#define DISPATCH_CHECKPOINTS(n, i) case n: goto CHECKPOINT_LABEL_MAKE(n);\n RBREAK_TAG_FOREACH(DISPATCH_CHECKPOINTS)\n#undef DISPATCH_CHECKPOINTS\n default:\n mrb_assert(!\"wrong break tag\");\n }\n }\n while (mrb->c->cibase < ci && ci[-1].proc != proc->upper) {\n if (ci[-1].cci == CINFO_SKIP) {\n goto L_BREAK_ERROR;\n }\n CHECKPOINT_RESTORE(RBREAK_TAG_BREAK_UPPER) {\n /* do nothing */\n }\n CHECKPOINT_MAIN(RBREAK_TAG_BREAK_UPPER) {\n UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK_UPPER, proc, v);\n }\n CHECKPOINT_END(RBREAK_TAG_BREAK_UPPER);\n ci = cipop(mrb);\n pc = ci->pc;\n }\n CHECKPOINT_RESTORE(RBREAK_TAG_BREAK_INTARGET) {\n /* do nothing */\n }\n CHECKPOINT_MAIN(RBREAK_TAG_BREAK_INTARGET) {\n UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK_INTARGET, proc, v);\n }\n CHECKPOINT_END(RBREAK_TAG_BREAK_INTARGET);\n if (ci == mrb->c->cibase) {\n goto L_BREAK_ERROR;\n }\n mrb->exc = NULL; /* clear break object */\n break;\n default:\n /* cannot happen */\n break;\n }\n mrb_assert(ci == mrb->c->ci);\n mrb_assert(mrb->exc == NULL);\n\n if (mrb->c->vmexec && !mrb_vm_ci_target_class(ci)) {\n mrb_gc_arena_restore(mrb, ai);\n mrb->c->vmexec = FALSE;\n mrb->jmp = prev_jmp;\n return v;\n }\n acc = ci->cci;\n ci = cipop(mrb);\n if (acc == CINFO_SKIP || acc == CINFO_DIRECT) {\n mrb_gc_arena_restore(mrb, ai);\n mrb->jmp = prev_jmp;\n return v;\n }\n pc = ci->pc;\n DEBUG(fprintf(stderr, \"from :%s\\n\", mrb_sym_name(mrb, ci->mid)));\n proc = ci->proc;\n irep = proc->body.irep;\n pool = irep->pool;\n syms = irep->syms;\n\n ci[1].stack[0] = v;\n mrb_gc_arena_restore(mrb, ai);\n }\n JUMP;\n }\n\n CASE(OP_BLKPUSH, BS) {\n int m1 = (b>>11)&0x3f;\n int r = (b>>10)&0x1;\n int m2 = (b>>5)&0x1f;\n int kd = (b>>4)&0x1;\n int lv = (b>>0)&0xf;\n mrb_value *stack;\n\n if (lv == 0) stack = regs + 1;\n else {\n struct REnv *e = uvenv(mrb, lv-1);\n if (!e || (!MRB_ENV_ONSTACK_P(e) && e->mid == 0) ||\n MRB_ENV_LEN(e) <= m1+r+m2+1) {\n localjump_error(mrb, LOCALJUMP_ERROR_YIELD);\n goto L_RAISE;\n }\n stack = e->stack + 1;\n }\n if (mrb_nil_p(stack[m1+r+m2+kd])) {\n localjump_error(mrb, LOCALJUMP_ERROR_YIELD);\n goto L_RAISE;\n }\n regs[a] = stack[m1+r+m2+kd];\n NEXT;\n }\n\n L_INT_OVERFLOW:\n {\n mrb_value exc = mrb_exc_new_lit(mrb, E_RANGE_ERROR, \"integer overflow\");\n mrb_exc_set(mrb, exc);\n }\n goto L_RAISE;\n\n#define TYPES2(a,b) ((((uint16_t)(a))<<8)|(((uint16_t)(b))&0xff))\n#define OP_MATH(op_name) \\\n /* need to check if op is overridden */ \\\n switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) { \\\n OP_MATH_CASE_INTEGER(op_name); \\\n OP_MATH_CASE_FLOAT(op_name, integer, float); \\\n OP_MATH_CASE_FLOAT(op_name, float, integer); \\\n OP_MATH_CASE_FLOAT(op_name, float, float); \\\n OP_MATH_CASE_STRING_##op_name(); \\\n default: \\\n mid = MRB_OPSYM(op_name); \\\n goto L_SEND_SYM; \\\n } \\\n NEXT;\n#define OP_MATH_CASE_INTEGER(op_name) \\\n case TYPES2(MRB_TT_INTEGER, MRB_TT_INTEGER): \\\n { \\\n mrb_int x = mrb_integer(regs[a]), y = mrb_integer(regs[a+1]), z; \\\n if (mrb_int_##op_name##_overflow(x, y, &z)) \\\n OP_MATH_OVERFLOW_INT(); \\\n else \\\n SET_INT_VALUE(mrb,regs[a], z); \\\n } \\\n break\n#ifdef MRB_NO_FLOAT\n#define OP_MATH_CASE_FLOAT(op_name, t1, t2) (void)0\n#else\n#define OP_MATH_CASE_FLOAT(op_name, t1, t2) \\\n case TYPES2(OP_MATH_TT_##t1, OP_MATH_TT_##t2): \\\n { \\\n mrb_float z = mrb_##t1(regs[a]) OP_MATH_OP_##op_name mrb_##t2(regs[a+1]); \\\n SET_FLOAT_VALUE(mrb, regs[a], z); \\\n } \\\n break\n#endif\n#define OP_MATH_OVERFLOW_INT() goto L_INT_OVERFLOW\n#define OP_MATH_CASE_STRING_add() \\\n case TYPES2(MRB_TT_STRING, MRB_TT_STRING): \\\n regs[a] = mrb_str_plus(mrb, regs[a], regs[a+1]); \\\n mrb_gc_arena_restore(mrb, ai); \\\n break\n#define OP_MATH_CASE_STRING_sub() (void)0\n#define OP_MATH_CASE_STRING_mul() (void)0\n#define OP_MATH_OP_add +\n#define OP_MATH_OP_sub -\n#define OP_MATH_OP_mul *\n#define OP_MATH_TT_integer MRB_TT_INTEGER\n#define OP_MATH_TT_float MRB_TT_FLOAT\n\n CASE(OP_ADD, B) {\n OP_MATH(add);\n }\n\n CASE(OP_SUB, B) {\n OP_MATH(sub);\n }\n\n CASE(OP_MUL, B) {\n OP_MATH(mul);\n }\n\n CASE(OP_DIV, B) {\n#ifndef MRB_NO_FLOAT\n mrb_float x, y, f;\n#endif\n\n /* need to check if op is overridden */\n switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\n case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\n {\n mrb_int x = mrb_integer(regs[a]);\n mrb_int y = mrb_integer(regs[a+1]);\n mrb_int div = mrb_div_int(mrb, x, y);\n SET_INT_VALUE(mrb, regs[a], div);\n }\n NEXT;\n#ifndef MRB_NO_FLOAT\n case TYPES2(MRB_TT_INTEGER,MRB_TT_FLOAT):\n x = (mrb_float)mrb_integer(regs[a]);\n y = mrb_float(regs[a+1]);\n break;\n case TYPES2(MRB_TT_FLOAT,MRB_TT_INTEGER):\n x = mrb_float(regs[a]);\n y = (mrb_float)mrb_integer(regs[a+1]);\n break;\n case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\n x = mrb_float(regs[a]);\n y = mrb_float(regs[a+1]);\n break;\n#endif\n default:\n mid = MRB_OPSYM(div);\n goto L_SEND_SYM;\n }\n\n#ifndef MRB_NO_FLOAT\n f = mrb_div_float(x, y);\n SET_FLOAT_VALUE(mrb, regs[a], f);\n#endif\n NEXT;\n }\n\n#define OP_MATHI(op_name) \\\n /* need to check if op is overridden */ \\\n switch (mrb_type(regs[a])) { \\\n OP_MATHI_CASE_INTEGER(op_name); \\\n OP_MATHI_CASE_FLOAT(op_name); \\\n default: \\\n SET_INT_VALUE(mrb,regs[a+1], b); \\\n mid = MRB_OPSYM(op_name); \\\n goto L_SEND_SYM; \\\n } \\\n NEXT;\n#define OP_MATHI_CASE_INTEGER(op_name) \\\n case MRB_TT_INTEGER: \\\n { \\\n mrb_int x = mrb_integer(regs[a]), y = (mrb_int)b, z; \\\n if (mrb_int_##op_name##_overflow(x, y, &z)) \\\n OP_MATH_OVERFLOW_INT(); \\\n else \\\n SET_INT_VALUE(mrb,regs[a], z); \\\n } \\\n break\n#ifdef MRB_NO_FLOAT\n#define OP_MATHI_CASE_FLOAT(op_name) (void)0\n#else\n#define OP_MATHI_CASE_FLOAT(op_name) \\\n case MRB_TT_FLOAT: \\\n { \\\n mrb_float z = mrb_float(regs[a]) OP_MATH_OP_##op_name b; \\\n SET_FLOAT_VALUE(mrb, regs[a], z); \\\n } \\\n break\n#endif\n\n CASE(OP_ADDI, BB) {\n OP_MATHI(add);\n }\n\n CASE(OP_SUBI, BB) {\n OP_MATHI(sub);\n }\n\n#define OP_CMP_BODY(op,v1,v2) (v1(regs[a]) op v2(regs[a+1]))\n\n#ifdef MRB_NO_FLOAT\n#define OP_CMP(op,sym) do {\\\n int result;\\\n /* need to check if - is overridden */\\\n switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\\\n case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\\\n result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\\\n break;\\\n default:\\\n mid = MRB_OPSYM(sym);\\\n goto L_SEND_SYM;\\\n }\\\n if (result) {\\\n SET_TRUE_VALUE(regs[a]);\\\n }\\\n else {\\\n SET_FALSE_VALUE(regs[a]);\\\n }\\\n} while(0)\n#else\n#define OP_CMP(op, sym) do {\\\n int result;\\\n /* need to check if - is overridden */\\\n switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\\\n case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\\\n result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\\\n break;\\\n case TYPES2(MRB_TT_INTEGER,MRB_TT_FLOAT):\\\n result = OP_CMP_BODY(op,mrb_fixnum,mrb_float);\\\n break;\\\n case TYPES2(MRB_TT_FLOAT,MRB_TT_INTEGER):\\\n result = OP_CMP_BODY(op,mrb_float,mrb_fixnum);\\\n break;\\\n case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\\\n result = OP_CMP_BODY(op,mrb_float,mrb_float);\\\n break;\\\n default:\\\n mid = MRB_OPSYM(sym);\\\n goto L_SEND_SYM;\\\n }\\\n if (result) {\\\n SET_TRUE_VALUE(regs[a]);\\\n }\\\n else {\\\n SET_FALSE_VALUE(regs[a]);\\\n }\\\n} while(0)\n#endif\n\n CASE(OP_EQ, B) {\n if (mrb_obj_eq(mrb, regs[a], regs[a+1])) {\n SET_TRUE_VALUE(regs[a]);\n }\n else {\n OP_CMP(==,eq);\n }\n NEXT;\n }\n\n CASE(OP_LT, B) {\n OP_CMP(<,lt);\n NEXT;\n }\n\n CASE(OP_LE, B) {\n OP_CMP(<=,le);\n NEXT;\n }\n\n CASE(OP_GT, B) {\n OP_CMP(>,gt);\n NEXT;\n }\n\n CASE(OP_GE, B) {\n OP_CMP(>=,ge);\n NEXT;\n }\n\n CASE(OP_ARRAY, BB) {\n regs[a] = mrb_ary_new_from_values(mrb, b, ®s[a]);\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n CASE(OP_ARRAY2, BBB) {\n regs[a] = mrb_ary_new_from_values(mrb, c, ®s[b]);\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_ARYCAT, B) {\n mrb_value splat = mrb_ary_splat(mrb, regs[a+1]);\n if (mrb_nil_p(regs[a])) {\n regs[a] = splat;\n }\n else {\n mrb_assert(mrb_array_p(regs[a]));\n mrb_ary_concat(mrb, regs[a], splat);\n }\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_ARYPUSH, BB) {\n mrb_assert(mrb_array_p(regs[a]));\n for (mrb_int i=0; i pre + post) {\n v = mrb_ary_new_from_values(mrb, len - pre - post, ARY_PTR(ary)+pre);\n regs[a++] = v;\n while (post--) {\n regs[a++] = ARY_PTR(ary)[len-post-1];\n }\n }\n else {\n v = mrb_ary_new_capa(mrb, 0);\n regs[a++] = v;\n for (idx=0; idx+pre> 2;\n if (pool[b].tt & IREP_TT_SFLAG) {\n sym = mrb_intern_static(mrb, pool[b].u.str, len);\n }\n else {\n sym = mrb_intern(mrb, pool[b].u.str, len);\n }\n regs[a] = mrb_symbol_value(sym);\n NEXT;\n }\n\n CASE(OP_STRING, BB) {\n mrb_int len;\n\n mrb_assert((pool[b].tt&IREP_TT_NFLAG)==0);\n len = pool[b].tt >> 2;\n if (pool[b].tt & IREP_TT_SFLAG) {\n regs[a] = mrb_str_new_static(mrb, pool[b].u.str, len);\n }\n else {\n regs[a] = mrb_str_new(mrb, pool[b].u.str, len);\n }\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_STRCAT, B) {\n mrb_assert(mrb_string_p(regs[a]));\n mrb_str_concat(mrb, regs[a], regs[a+1]);\n NEXT;\n }\n\n CASE(OP_HASH, BB) {\n mrb_value hash = mrb_hash_new_capa(mrb, b);\n int i;\n int lim = a+b*2;\n\n for (i=a; ireps[b];\n\n if (c & OP_L_CAPTURE) {\n p = mrb_closure_new(mrb, nirep);\n }\n else {\n p = mrb_proc_new(mrb, nirep);\n p->flags |= MRB_PROC_SCOPE;\n }\n if (c & OP_L_STRICT) p->flags |= MRB_PROC_STRICT;\n regs[a] = mrb_obj_value(p);\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n CASE(OP_BLOCK, BB) {\n c = OP_L_BLOCK;\n goto L_MAKE_LAMBDA;\n }\n CASE(OP_METHOD, BB) {\n c = OP_L_METHOD;\n goto L_MAKE_LAMBDA;\n }\n\n CASE(OP_RANGE_INC, B) {\n mrb_value v = mrb_range_new(mrb, regs[a], regs[a+1], FALSE);\n regs[a] = v;\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_RANGE_EXC, B) {\n mrb_value v = mrb_range_new(mrb, regs[a], regs[a+1], TRUE);\n regs[a] = v;\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_OCLASS, B) {\n regs[a] = mrb_obj_value(mrb->object_class);\n NEXT;\n }\n\n CASE(OP_CLASS, BB) {\n struct RClass *c = 0, *baseclass;\n mrb_value base, super;\n mrb_sym id = syms[b];\n\n base = regs[a];\n super = regs[a+1];\n if (mrb_nil_p(base)) {\n baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc);\n if (!baseclass) baseclass = mrb->object_class;\n base = mrb_obj_value(baseclass);\n }\n c = mrb_vm_define_class(mrb, base, super, id);\n regs[a] = mrb_obj_value(c);\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_MODULE, BB) {\n struct RClass *cls = 0, *baseclass;\n mrb_value base;\n mrb_sym id = syms[b];\n\n base = regs[a];\n if (mrb_nil_p(base)) {\n baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc);\n if (!baseclass) baseclass = mrb->object_class;\n base = mrb_obj_value(baseclass);\n }\n cls = mrb_vm_define_module(mrb, base, id);\n regs[a] = mrb_obj_value(cls);\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_EXEC, BB)\n {\n mrb_value recv = regs[a];\n struct RProc *p;\n const mrb_irep *nirep = irep->reps[b];\n\n /* prepare closure */\n p = mrb_proc_new(mrb, nirep);\n p->c = NULL;\n mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)proc);\n MRB_PROC_SET_TARGET_CLASS(p, mrb_class_ptr(recv));\n p->flags |= MRB_PROC_SCOPE;\n\n /* prepare call stack */\n cipush(mrb, a, 0, mrb_class_ptr(recv), p, 0, 0);\n\n irep = p->body.irep;\n pool = irep->pool;\n syms = irep->syms;\n mrb_stack_extend(mrb, irep->nregs);\n stack_clear(regs+1, irep->nregs-1);\n pc = irep->iseq;\n JUMP;\n }\n\n CASE(OP_DEF, BB) {\n struct RClass *target = mrb_class_ptr(regs[a]);\n struct RProc *p = mrb_proc_ptr(regs[a+1]);\n mrb_method_t m;\n mrb_sym mid = syms[b];\n\n MRB_METHOD_FROM_PROC(m, p);\n mrb_define_method_raw(mrb, target, mid, m);\n mrb_method_added(mrb, target, mid);\n mrb_gc_arena_restore(mrb, ai);\n regs[a] = mrb_symbol_value(mid);\n NEXT;\n }\n\n CASE(OP_SCLASS, B) {\n regs[a] = mrb_singleton_class(mrb, regs[a]);\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_TCLASS, B) {\n struct RClass *target = check_target_class(mrb);\n if (!target) goto L_RAISE;\n regs[a] = mrb_obj_value(target);\n NEXT;\n }\n\n CASE(OP_ALIAS, BB) {\n struct RClass *target = check_target_class(mrb);\n\n if (!target) goto L_RAISE;\n mrb_alias_method(mrb, target, syms[a], syms[b]);\n mrb_method_added(mrb, target, syms[a]);\n NEXT;\n }\n CASE(OP_UNDEF, B) {\n struct RClass *target = check_target_class(mrb);\n\n if (!target) goto L_RAISE;\n mrb_undef_method_id(mrb, target, syms[a]);\n NEXT;\n }\n\n CASE(OP_DEBUG, Z) {\n FETCH_BBB();\n#ifdef MRB_USE_DEBUG_HOOK\n mrb->debug_op_hook(mrb, irep, pc, regs);\n#else\n#ifndef MRB_NO_STDIO\n printf(\"OP_DEBUG %d %d %d\\n\", a, b, c);\n#else\n abort();\n#endif\n#endif\n NEXT;\n }\n\n CASE(OP_ERR, B) {\n size_t len = pool[a].tt >> 2;\n mrb_value exc;\n\n mrb_assert((pool[a].tt&IREP_TT_NFLAG)==0);\n exc = mrb_exc_new(mrb, E_LOCALJUMP_ERROR, pool[a].u.str, len);\n mrb_exc_set(mrb, exc);\n goto L_RAISE;\n }\n\n CASE(OP_EXT1, Z) {\n insn = READ_B();\n switch (insn) {\n#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _1(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;\n#include \"mruby/ops.h\"\n#undef OPCODE\n }\n pc--;\n NEXT;\n }\n CASE(OP_EXT2, Z) {\n insn = READ_B();\n switch (insn) {\n#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _2(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;\n#include \"mruby/ops.h\"\n#undef OPCODE\n }\n pc--;\n NEXT;\n }\n CASE(OP_EXT3, Z) {\n uint8_t insn = READ_B();\n switch (insn) {\n#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _3(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;\n#include \"mruby/ops.h\"\n#undef OPCODE\n }\n pc--;\n NEXT;\n }\n\n CASE(OP_STOP, Z) {\n /* stop VM */\n CHECKPOINT_RESTORE(RBREAK_TAG_STOP) {\n /* do nothing */\n }\n CHECKPOINT_MAIN(RBREAK_TAG_STOP) {\n UNWIND_ENSURE(mrb, mrb->c->ci, pc, RBREAK_TAG_STOP, proc, mrb_nil_value());\n }\n CHECKPOINT_END(RBREAK_TAG_STOP);\n L_STOP:\n mrb->jmp = prev_jmp;\n if (mrb->exc) {\n mrb_assert(mrb->exc->tt == MRB_TT_EXCEPTION);\n return mrb_obj_value(mrb->exc);\n }\n return regs[irep->nlocals];\n }\n }\n END_DISPATCH;\n#undef regs\n }\n MRB_CATCH(&c_jmp) {\n mrb_callinfo *ci = mrb->c->ci;\n while (ci > mrb->c->cibase && ci->cci == CINFO_DIRECT) {\n ci = cipop(mrb);\n }\n exc_catched = TRUE;\n pc = ci->pc;\n goto RETRY_TRY_BLOCK;\n }\n MRB_END_EXC(&c_jmp);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-288'], 'message': 'vm.c: create break object before clearing GC arena.\n\nOtherwise it possibly cause use-after-free.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: PrimitiveStatus TrustedPrimitives::UntrustedCall(uint64_t untrusted_selector,\n MessageWriter *input,\n MessageReader *output) {\n int ret;\n\n UntrustedCacheMalloc *untrusted_cache = UntrustedCacheMalloc::Instance();\n\n SgxParams *const sgx_params =\n reinterpret_cast(untrusted_cache->Malloc(sizeof(SgxParams)));\n Cleanup clean_up(\n [sgx_params, untrusted_cache] { untrusted_cache->Free(sgx_params); });\n sgx_params->input_size = 0;\n sgx_params->input = nullptr;\n if (input) {\n sgx_params->input_size = input->MessageSize();\n if (sgx_params->input_size > 0) {\n // Allocate and copy data to |input_buffer|.\n sgx_params->input = untrusted_cache->Malloc(sgx_params->input_size);\n input->Serialize(const_cast(sgx_params->input));\n }\n }\n sgx_params->output_size = 0;\n sgx_params->output = nullptr;\n CHECK_OCALL(\n ocall_dispatch_untrusted_call(&ret, untrusted_selector, sgx_params));\n if (sgx_params->input) {\n untrusted_cache->Free(const_cast(sgx_params->input));\n }\n if (sgx_params->output) {\n // For the results obtained in |output_buffer|, copy them to |output|\n // before freeing the buffer.\n output->Deserialize(sgx_params->output, sgx_params->output_size);\n TrustedPrimitives::UntrustedLocalFree(sgx_params->output);\n }\n return PrimitiveStatus::OkStatus();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Verify UntrustedCall output is outside enclave\n\nPiperOrigin-RevId: 333781703\nChange-Id: I9df55c04dc8b04f4bf0bda8e68cc32bca81b933a'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int DecodeTunnel(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p,\n uint8_t *pkt, uint32_t len, PacketQueue *pq, enum DecodeTunnelProto proto)\n{\n switch (proto) {\n case DECODE_TUNNEL_PPP:\n return DecodePPP(tv, dtv, p, pkt, len, pq);\n case DECODE_TUNNEL_IPV4:\n return DecodeIPV4(tv, dtv, p, pkt, len, pq);\n case DECODE_TUNNEL_IPV6:\n return DecodeIPV6(tv, dtv, p, pkt, len, pq);\n case DECODE_TUNNEL_VLAN:\n return DecodeVLAN(tv, dtv, p, pkt, len, pq);\n case DECODE_TUNNEL_ETHERNET:\n return DecodeEthernet(tv, dtv, p, pkt, len, pq);\n case DECODE_TUNNEL_ERSPAN:\n return DecodeERSPAN(tv, dtv, p, pkt, len, pq);\n default:\n SCLogInfo(\"FIXME: DecodeTunnel: protocol %\" PRIu32 \" not supported.\", proto);\n break;\n }\n return TM_ECODE_OK;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'teredo: be stricter on what to consider valid teredo\n\nInvalid Teredo can lead to valid DNS traffic (or other UDP traffic)\nbeing misdetected as Teredo. This leads to false negatives in the\nUDP payload inspection.\n\nMake the teredo code only consider a packet teredo if the encapsulated\ndata was decoded without any 'invalid' events being set.\n\nBug #2736.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void CConnectionTransportUDPBase::Received_Data( const uint8 *pPkt, int cbPkt, SteamNetworkingMicroseconds usecNow )\n{\n\n\tif ( cbPkt < sizeof(UDPDataMsgHdr) )\n\t{\n\t\tReportBadUDPPacketFromConnectionPeer( \"DataPacket\", \"Packet of size %d is too small.\", cbPkt );\n\t\treturn;\n\t}\n\n\t// Check cookie\n\tconst UDPDataMsgHdr *hdr = (const UDPDataMsgHdr *)pPkt;\n\tif ( LittleDWord( hdr->m_unToConnectionID ) != ConnectionIDLocal() )\n\t{\n\n\t\t// Wrong session. It could be an old session, or it could be spoofed.\n\t\tReportBadUDPPacketFromConnectionPeer( \"DataPacket\", \"Incorrect connection ID\" );\n\t\tif ( BCheckGlobalSpamReplyRateLimit( usecNow ) )\n\t\t{\n\t\t\tSendNoConnection( LittleDWord( hdr->m_unToConnectionID ), 0 );\n\t\t}\n\t\treturn;\n\t}\n\tuint16 nWirePktNumber = LittleWord( hdr->m_unSeqNum );\n\n\t// Check state\n\tswitch ( ConnectionState() )\n\t{\n\t\tcase k_ESteamNetworkingConnectionState_Dead:\n\t\tcase k_ESteamNetworkingConnectionState_None:\n\t\tdefault:\n\t\t\tAssert( false );\n\t\t\treturn;\n\n\t\tcase k_ESteamNetworkingConnectionState_ClosedByPeer:\n\t\tcase k_ESteamNetworkingConnectionState_FinWait:\n\t\tcase k_ESteamNetworkingConnectionState_ProblemDetectedLocally:\n\t\t\tSendConnectionClosedOrNoConnection();\n\t\t\treturn;\n\n\t\tcase k_ESteamNetworkingConnectionState_Connecting:\n\t\t\t// Ignore it. We don't have the SteamID of whoever is on the other end yet,\n\t\t\t// their encryption keys, etc. The most likely cause is that a server sent\n\t\t\t// a ConnectOK, which dropped. So they think we're connected but we don't\n\t\t\t// have everything yet.\n\t\t\treturn;\n\n\t\tcase k_ESteamNetworkingConnectionState_Linger:\n\t\tcase k_ESteamNetworkingConnectionState_Connected:\n\t\tcase k_ESteamNetworkingConnectionState_FindingRoute: // not used for raw UDP, but might be used for derived class\n\n\t\t\t// We'll process the chunk\n\t\t\tbreak;\n\t}\n\n\tconst uint8 *pIn = pPkt + sizeof(*hdr);\n\tconst uint8 *pPktEnd = pPkt + cbPkt;\n\n\t// Inline stats?\n\tstatic CMsgSteamSockets_UDP_Stats msgStats;\n\tCMsgSteamSockets_UDP_Stats *pMsgStatsIn = nullptr;\n\tuint32 cbStatsMsgIn = 0;\n\tif ( hdr->m_unMsgFlags & hdr->kFlag_ProtobufBlob )\n\t{\n\t\t//Msg_Verbose( \"Received inline stats from %s\", server.m_szName );\n\n\t\tpIn = DeserializeVarInt( pIn, pPktEnd, cbStatsMsgIn );\n\t\tif ( pIn == NULL )\n\t\t{\n\t\t\tReportBadUDPPacketFromConnectionPeer( \"DataPacket\", \"Failed to varint decode size of stats blob\" );\n\t\t\treturn;\n\t\t}\n\t\tif ( pIn + cbStatsMsgIn > pPktEnd )\n\t\t{\n\t\t\tReportBadUDPPacketFromConnectionPeer( \"DataPacket\", \"stats message size doesn't make sense. Stats message size %d, packet size %d\", cbStatsMsgIn, cbPkt );\n\t\t\treturn;\n\t\t}\n\n\t\tif ( !msgStats.ParseFromArray( pIn, cbStatsMsgIn ) )\n\t\t{\n\t\t\tReportBadUDPPacketFromConnectionPeer( \"DataPacket\", \"protobuf failed to parse inline stats message\" );\n\t\t\treturn;\n\t\t}\n\n\t\t// Shove sequence number so we know what acks to pend, etc\n\t\tpMsgStatsIn = &msgStats;\n\n\t\t// Advance pointer\n\t\tpIn += cbStatsMsgIn;\n\t}\n\n\tconst void *pChunk = pIn;\n\tint cbChunk = pPktEnd - pIn;\n\n\t// Decrypt it, and check packet number\n\tUDPRecvPacketContext_t ctx;\n\tctx.m_usecNow = usecNow;\n\tctx.m_pTransport = this;\n\tctx.m_pStatsIn = pMsgStatsIn;\n\tif ( !m_connection.DecryptDataChunk( nWirePktNumber, cbPkt, pChunk, cbChunk, ctx ) )\n\t\treturn;\n\n\t// This is a valid packet. P2P connections might want to make a note of this\n\tRecvValidUDPDataPacket( ctx );\n\n\t// Process plaintext\n\tint usecTimeSinceLast = 0; // FIXME - should we plumb this through so we can measure jitter?\n\tif ( !m_connection.ProcessPlainTextDataChunk( usecTimeSinceLast, ctx ) )\n\t\treturn;\n\n\t// Process the stats, if any\n\tif ( pMsgStatsIn )\n\t\tRecvStats( *pMsgStatsIn, usecNow );\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'Tweak pointer math to avoid possible integer overflow'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int main() {\n CU_pSuite pSuite = NULL;\n unsigned int num_tests_failed;\n\n nghttp2_enable_strict_preface = 0;\n\n /* initialize the CUnit test registry */\n if (CUE_SUCCESS != CU_initialize_registry())\n return (int)CU_get_error();\n\n /* add a suite to the registry */\n pSuite = CU_add_suite(\"libnghttp2_TestSuite\", init_suite1, clean_suite1);\n if (NULL == pSuite) {\n CU_cleanup_registry();\n return (int)CU_get_error();\n }\n\n /* add the tests to the suite */\n if (!CU_add_test(pSuite, \"pq\", test_nghttp2_pq) ||\n !CU_add_test(pSuite, \"pq_update\", test_nghttp2_pq_update) ||\n !CU_add_test(pSuite, \"pq_remove\", test_nghttp2_pq_remove) ||\n !CU_add_test(pSuite, \"map\", test_nghttp2_map) ||\n !CU_add_test(pSuite, \"map_functional\", test_nghttp2_map_functional) ||\n !CU_add_test(pSuite, \"map_each_free\", test_nghttp2_map_each_free) ||\n !CU_add_test(pSuite, \"queue\", test_nghttp2_queue) ||\n !CU_add_test(pSuite, \"npn\", test_nghttp2_npn) ||\n !CU_add_test(pSuite, \"session_recv\", test_nghttp2_session_recv) ||\n !CU_add_test(pSuite, \"session_recv_invalid_stream_id\",\n test_nghttp2_session_recv_invalid_stream_id) ||\n !CU_add_test(pSuite, \"session_recv_invalid_frame\",\n test_nghttp2_session_recv_invalid_frame) ||\n !CU_add_test(pSuite, \"session_recv_eof\", test_nghttp2_session_recv_eof) ||\n !CU_add_test(pSuite, \"session_recv_data\",\n test_nghttp2_session_recv_data) ||\n !CU_add_test(pSuite, \"session_recv_data_no_auto_flow_control\",\n test_nghttp2_session_recv_data_no_auto_flow_control) ||\n !CU_add_test(pSuite, \"session_recv_continuation\",\n test_nghttp2_session_recv_continuation) ||\n !CU_add_test(pSuite, \"session_recv_headers_with_priority\",\n test_nghttp2_session_recv_headers_with_priority) ||\n !CU_add_test(pSuite, \"session_recv_headers_with_padding\",\n test_nghttp2_session_recv_headers_with_padding) ||\n !CU_add_test(pSuite, \"session_recv_headers_early_response\",\n test_nghttp2_session_recv_headers_early_response) ||\n !CU_add_test(pSuite, \"session_recv_headers_for_closed_stream\",\n test_nghttp2_session_recv_headers_for_closed_stream) ||\n !CU_add_test(pSuite, \"session_server_recv_push_response\",\n test_nghttp2_session_server_recv_push_response) ||\n !CU_add_test(pSuite, \"session_recv_premature_headers\",\n test_nghttp2_session_recv_premature_headers) ||\n !CU_add_test(pSuite, \"session_recv_unknown_frame\",\n test_nghttp2_session_recv_unknown_frame) ||\n !CU_add_test(pSuite, \"session_recv_unexpected_continuation\",\n test_nghttp2_session_recv_unexpected_continuation) ||\n !CU_add_test(pSuite, \"session_recv_settings_header_table_size\",\n test_nghttp2_session_recv_settings_header_table_size) ||\n !CU_add_test(pSuite, \"session_recv_too_large_frame_length\",\n test_nghttp2_session_recv_too_large_frame_length) ||\n !CU_add_test(pSuite, \"session_recv_extension\",\n test_nghttp2_session_recv_extension) ||\n !CU_add_test(pSuite, \"session_recv_altsvc\",\n test_nghttp2_session_recv_altsvc) ||\n !CU_add_test(pSuite, \"session_recv_origin\",\n test_nghttp2_session_recv_origin) ||\n !CU_add_test(pSuite, \"session_continue\", test_nghttp2_session_continue) ||\n !CU_add_test(pSuite, \"session_add_frame\",\n test_nghttp2_session_add_frame) ||\n !CU_add_test(pSuite, \"session_on_request_headers_received\",\n test_nghttp2_session_on_request_headers_received) ||\n !CU_add_test(pSuite, \"session_on_response_headers_received\",\n test_nghttp2_session_on_response_headers_received) ||\n !CU_add_test(pSuite, \"session_on_headers_received\",\n test_nghttp2_session_on_headers_received) ||\n !CU_add_test(pSuite, \"session_on_push_response_headers_received\",\n test_nghttp2_session_on_push_response_headers_received) ||\n !CU_add_test(pSuite, \"session_on_priority_received\",\n test_nghttp2_session_on_priority_received) ||\n !CU_add_test(pSuite, \"session_on_rst_stream_received\",\n test_nghttp2_session_on_rst_stream_received) ||\n !CU_add_test(pSuite, \"session_on_settings_received\",\n test_nghttp2_session_on_settings_received) ||\n !CU_add_test(pSuite, \"session_on_push_promise_received\",\n test_nghttp2_session_on_push_promise_received) ||\n !CU_add_test(pSuite, \"session_on_ping_received\",\n test_nghttp2_session_on_ping_received) ||\n !CU_add_test(pSuite, \"session_on_goaway_received\",\n test_nghttp2_session_on_goaway_received) ||\n !CU_add_test(pSuite, \"session_on_window_update_received\",\n test_nghttp2_session_on_window_update_received) ||\n !CU_add_test(pSuite, \"session_on_data_received\",\n test_nghttp2_session_on_data_received) ||\n !CU_add_test(pSuite, \"session_on_data_received_fail_fast\",\n test_nghttp2_session_on_data_received_fail_fast) ||\n !CU_add_test(pSuite, \"session_on_altsvc_received\",\n test_nghttp2_session_on_altsvc_received) ||\n !CU_add_test(pSuite, \"session_send_headers_start_stream\",\n test_nghttp2_session_send_headers_start_stream) ||\n !CU_add_test(pSuite, \"session_send_headers_reply\",\n test_nghttp2_session_send_headers_reply) ||\n !CU_add_test(pSuite, \"session_send_headers_frame_size_error\",\n test_nghttp2_session_send_headers_frame_size_error) ||\n !CU_add_test(pSuite, \"session_send_headers_push_reply\",\n test_nghttp2_session_send_headers_push_reply) ||\n !CU_add_test(pSuite, \"session_send_rst_stream\",\n test_nghttp2_session_send_rst_stream) ||\n !CU_add_test(pSuite, \"session_send_push_promise\",\n test_nghttp2_session_send_push_promise) ||\n !CU_add_test(pSuite, \"session_is_my_stream_id\",\n test_nghttp2_session_is_my_stream_id) ||\n !CU_add_test(pSuite, \"session_upgrade2\", test_nghttp2_session_upgrade2) ||\n !CU_add_test(pSuite, \"session_reprioritize_stream\",\n test_nghttp2_session_reprioritize_stream) ||\n !CU_add_test(\n pSuite, \"session_reprioritize_stream_with_idle_stream_dep\",\n test_nghttp2_session_reprioritize_stream_with_idle_stream_dep) ||\n !CU_add_test(pSuite, \"submit_data\", test_nghttp2_submit_data) ||\n !CU_add_test(pSuite, \"submit_data_read_length_too_large\",\n test_nghttp2_submit_data_read_length_too_large) ||\n !CU_add_test(pSuite, \"submit_data_read_length_smallest\",\n test_nghttp2_submit_data_read_length_smallest) ||\n !CU_add_test(pSuite, \"submit_data_twice\",\n test_nghttp2_submit_data_twice) ||\n !CU_add_test(pSuite, \"submit_request_with_data\",\n test_nghttp2_submit_request_with_data) ||\n !CU_add_test(pSuite, \"submit_request_without_data\",\n test_nghttp2_submit_request_without_data) ||\n !CU_add_test(pSuite, \"submit_response_with_data\",\n test_nghttp2_submit_response_with_data) ||\n !CU_add_test(pSuite, \"submit_response_without_data\",\n test_nghttp2_submit_response_without_data) ||\n !CU_add_test(pSuite, \"Submit_response_push_response\",\n test_nghttp2_submit_response_push_response) ||\n !CU_add_test(pSuite, \"submit_trailer\", test_nghttp2_submit_trailer) ||\n !CU_add_test(pSuite, \"submit_headers_start_stream\",\n test_nghttp2_submit_headers_start_stream) ||\n !CU_add_test(pSuite, \"submit_headers_reply\",\n test_nghttp2_submit_headers_reply) ||\n !CU_add_test(pSuite, \"submit_headers_push_reply\",\n test_nghttp2_submit_headers_push_reply) ||\n !CU_add_test(pSuite, \"submit_headers\", test_nghttp2_submit_headers) ||\n !CU_add_test(pSuite, \"submit_headers_continuation\",\n test_nghttp2_submit_headers_continuation) ||\n !CU_add_test(pSuite, \"submit_headers_continuation_extra_large\",\n test_nghttp2_submit_headers_continuation_extra_large) ||\n !CU_add_test(pSuite, \"submit_priority\", test_nghttp2_submit_priority) ||\n !CU_add_test(pSuite, \"session_submit_settings\",\n test_nghttp2_submit_settings) ||\n !CU_add_test(pSuite, \"session_submit_settings_update_local_window_size\",\n test_nghttp2_submit_settings_update_local_window_size) ||\n !CU_add_test(pSuite, \"session_submit_settings_multiple_times\",\n test_nghttp2_submit_settings_multiple_times) ||\n !CU_add_test(pSuite, \"session_submit_push_promise\",\n test_nghttp2_submit_push_promise) ||\n !CU_add_test(pSuite, \"submit_window_update\",\n test_nghttp2_submit_window_update) ||\n !CU_add_test(pSuite, \"submit_window_update_local_window_size\",\n test_nghttp2_submit_window_update_local_window_size) ||\n !CU_add_test(pSuite, \"submit_shutdown_notice\",\n test_nghttp2_submit_shutdown_notice) ||\n !CU_add_test(pSuite, \"submit_invalid_nv\",\n test_nghttp2_submit_invalid_nv) ||\n !CU_add_test(pSuite, \"submit_extension\", test_nghttp2_submit_extension) ||\n !CU_add_test(pSuite, \"submit_altsvc\", test_nghttp2_submit_altsvc) ||\n !CU_add_test(pSuite, \"submit_origin\", test_nghttp2_submit_origin) ||\n !CU_add_test(pSuite, \"session_open_stream\",\n test_nghttp2_session_open_stream) ||\n !CU_add_test(pSuite, \"session_open_stream_with_idle_stream_dep\",\n test_nghttp2_session_open_stream_with_idle_stream_dep) ||\n !CU_add_test(pSuite, \"session_get_next_ob_item\",\n test_nghttp2_session_get_next_ob_item) ||\n !CU_add_test(pSuite, \"session_pop_next_ob_item\",\n test_nghttp2_session_pop_next_ob_item) ||\n !CU_add_test(pSuite, \"session_reply_fail\",\n test_nghttp2_session_reply_fail) ||\n !CU_add_test(pSuite, \"session_max_concurrent_streams\",\n test_nghttp2_session_max_concurrent_streams) ||\n !CU_add_test(pSuite, \"session_stop_data_with_rst_stream\",\n test_nghttp2_session_stop_data_with_rst_stream) ||\n !CU_add_test(pSuite, \"session_defer_data\",\n test_nghttp2_session_defer_data) ||\n !CU_add_test(pSuite, \"session_flow_control\",\n test_nghttp2_session_flow_control) ||\n !CU_add_test(pSuite, \"session_flow_control_data_recv\",\n test_nghttp2_session_flow_control_data_recv) ||\n !CU_add_test(pSuite, \"session_flow_control_data_with_padding_recv\",\n test_nghttp2_session_flow_control_data_with_padding_recv) ||\n !CU_add_test(pSuite, \"session_data_read_temporal_failure\",\n test_nghttp2_session_data_read_temporal_failure) ||\n !CU_add_test(pSuite, \"session_on_stream_close\",\n test_nghttp2_session_on_stream_close) ||\n !CU_add_test(pSuite, \"session_on_ctrl_not_send\",\n test_nghttp2_session_on_ctrl_not_send) ||\n !CU_add_test(pSuite, \"session_get_outbound_queue_size\",\n test_nghttp2_session_get_outbound_queue_size) ||\n !CU_add_test(pSuite, \"session_get_effective_local_window_size\",\n test_nghttp2_session_get_effective_local_window_size) ||\n !CU_add_test(pSuite, \"session_set_option\",\n test_nghttp2_session_set_option) ||\n !CU_add_test(pSuite, \"session_data_backoff_by_high_pri_frame\",\n test_nghttp2_session_data_backoff_by_high_pri_frame) ||\n !CU_add_test(pSuite, \"session_pack_data_with_padding\",\n test_nghttp2_session_pack_data_with_padding) ||\n !CU_add_test(pSuite, \"session_pack_headers_with_padding\",\n test_nghttp2_session_pack_headers_with_padding) ||\n !CU_add_test(pSuite, \"pack_settings_payload\",\n test_nghttp2_pack_settings_payload) ||\n !CU_add_test(pSuite, \"session_stream_dep_add\",\n test_nghttp2_session_stream_dep_add) ||\n !CU_add_test(pSuite, \"session_stream_dep_remove\",\n test_nghttp2_session_stream_dep_remove) ||\n !CU_add_test(pSuite, \"session_stream_dep_add_subtree\",\n test_nghttp2_session_stream_dep_add_subtree) ||\n !CU_add_test(pSuite, \"session_stream_dep_remove_subtree\",\n test_nghttp2_session_stream_dep_remove_subtree) ||\n !CU_add_test(\n pSuite, \"session_stream_dep_all_your_stream_are_belong_to_us\",\n test_nghttp2_session_stream_dep_all_your_stream_are_belong_to_us) ||\n !CU_add_test(pSuite, \"session_stream_attach_item\",\n test_nghttp2_session_stream_attach_item) ||\n !CU_add_test(pSuite, \"session_stream_attach_item_subtree\",\n test_nghttp2_session_stream_attach_item_subtree) ||\n !CU_add_test(pSuite, \"session_stream_get_state\",\n test_nghttp2_session_stream_get_state) ||\n !CU_add_test(pSuite, \"session_stream_get_something\",\n test_nghttp2_session_stream_get_something) ||\n !CU_add_test(pSuite, \"session_find_stream\",\n test_nghttp2_session_find_stream) ||\n !CU_add_test(pSuite, \"session_keep_closed_stream\",\n test_nghttp2_session_keep_closed_stream) ||\n !CU_add_test(pSuite, \"session_keep_idle_stream\",\n test_nghttp2_session_keep_idle_stream) ||\n !CU_add_test(pSuite, \"session_detach_idle_stream\",\n test_nghttp2_session_detach_idle_stream) ||\n !CU_add_test(pSuite, \"session_large_dep_tree\",\n test_nghttp2_session_large_dep_tree) ||\n !CU_add_test(pSuite, \"session_graceful_shutdown\",\n test_nghttp2_session_graceful_shutdown) ||\n !CU_add_test(pSuite, \"session_on_header_temporal_failure\",\n test_nghttp2_session_on_header_temporal_failure) ||\n !CU_add_test(pSuite, \"session_recv_client_magic\",\n test_nghttp2_session_recv_client_magic) ||\n !CU_add_test(pSuite, \"session_delete_data_item\",\n test_nghttp2_session_delete_data_item) ||\n !CU_add_test(pSuite, \"session_open_idle_stream\",\n test_nghttp2_session_open_idle_stream) ||\n !CU_add_test(pSuite, \"session_cancel_reserved_remote\",\n test_nghttp2_session_cancel_reserved_remote) ||\n !CU_add_test(pSuite, \"session_reset_pending_headers\",\n test_nghttp2_session_reset_pending_headers) ||\n !CU_add_test(pSuite, \"session_send_data_callback\",\n test_nghttp2_session_send_data_callback) ||\n !CU_add_test(pSuite, \"session_on_begin_headers_temporal_failure\",\n test_nghttp2_session_on_begin_headers_temporal_failure) ||\n !CU_add_test(pSuite, \"session_defer_then_close\",\n test_nghttp2_session_defer_then_close) ||\n !CU_add_test(pSuite, \"session_detach_item_from_closed_stream\",\n test_nghttp2_session_detach_item_from_closed_stream) ||\n !CU_add_test(pSuite, \"session_flooding\", test_nghttp2_session_flooding) ||\n !CU_add_test(pSuite, \"session_change_stream_priority\",\n test_nghttp2_session_change_stream_priority) ||\n !CU_add_test(pSuite, \"session_create_idle_stream\",\n test_nghttp2_session_create_idle_stream) ||\n !CU_add_test(pSuite, \"session_repeated_priority_change\",\n test_nghttp2_session_repeated_priority_change) ||\n !CU_add_test(pSuite, \"session_repeated_priority_submission\",\n test_nghttp2_session_repeated_priority_submission) ||\n !CU_add_test(pSuite, \"session_set_local_window_size\",\n test_nghttp2_session_set_local_window_size) ||\n !CU_add_test(pSuite, \"session_cancel_from_before_frame_send\",\n test_nghttp2_session_cancel_from_before_frame_send) ||\n !CU_add_test(pSuite, \"session_removed_closed_stream\",\n test_nghttp2_session_removed_closed_stream) ||\n !CU_add_test(pSuite, \"session_pause_data\",\n test_nghttp2_session_pause_data) ||\n !CU_add_test(pSuite, \"session_no_closed_streams\",\n test_nghttp2_session_no_closed_streams) ||\n !CU_add_test(pSuite, \"session_set_stream_user_data\",\n test_nghttp2_session_set_stream_user_data) ||\n !CU_add_test(pSuite, \"http_mandatory_headers\",\n test_nghttp2_http_mandatory_headers) ||\n !CU_add_test(pSuite, \"http_content_length\",\n test_nghttp2_http_content_length) ||\n !CU_add_test(pSuite, \"http_content_length_mismatch\",\n test_nghttp2_http_content_length_mismatch) ||\n !CU_add_test(pSuite, \"http_non_final_response\",\n test_nghttp2_http_non_final_response) ||\n !CU_add_test(pSuite, \"http_trailer_headers\",\n test_nghttp2_http_trailer_headers) ||\n !CU_add_test(pSuite, \"http_ignore_regular_header\",\n test_nghttp2_http_ignore_regular_header) ||\n !CU_add_test(pSuite, \"http_ignore_content_length\",\n test_nghttp2_http_ignore_content_length) ||\n !CU_add_test(pSuite, \"http_record_request_method\",\n test_nghttp2_http_record_request_method) ||\n !CU_add_test(pSuite, \"http_push_promise\",\n test_nghttp2_http_push_promise) ||\n !CU_add_test(pSuite, \"http_head_method_upgrade_workaround\",\n test_nghttp2_http_head_method_upgrade_workaround) ||\n !CU_add_test(pSuite, \"frame_pack_headers\",\n test_nghttp2_frame_pack_headers) ||\n !CU_add_test(pSuite, \"frame_pack_headers_frame_too_large\",\n test_nghttp2_frame_pack_headers_frame_too_large) ||\n !CU_add_test(pSuite, \"frame_pack_priority\",\n test_nghttp2_frame_pack_priority) ||\n !CU_add_test(pSuite, \"frame_pack_rst_stream\",\n test_nghttp2_frame_pack_rst_stream) ||\n !CU_add_test(pSuite, \"frame_pack_settings\",\n test_nghttp2_frame_pack_settings) ||\n !CU_add_test(pSuite, \"frame_pack_push_promise\",\n test_nghttp2_frame_pack_push_promise) ||\n !CU_add_test(pSuite, \"frame_pack_ping\", test_nghttp2_frame_pack_ping) ||\n !CU_add_test(pSuite, \"frame_pack_goaway\",\n test_nghttp2_frame_pack_goaway) ||\n !CU_add_test(pSuite, \"frame_pack_window_update\",\n test_nghttp2_frame_pack_window_update) ||\n !CU_add_test(pSuite, \"frame_pack_altsvc\",\n test_nghttp2_frame_pack_altsvc) ||\n !CU_add_test(pSuite, \"frame_pack_origin\",\n test_nghttp2_frame_pack_origin) ||\n !CU_add_test(pSuite, \"nv_array_copy\", test_nghttp2_nv_array_copy) ||\n !CU_add_test(pSuite, \"iv_check\", test_nghttp2_iv_check) ||\n !CU_add_test(pSuite, \"hd_deflate\", test_nghttp2_hd_deflate) ||\n !CU_add_test(pSuite, \"hd_deflate_same_indexed_repr\",\n test_nghttp2_hd_deflate_same_indexed_repr) ||\n !CU_add_test(pSuite, \"hd_inflate_indexed\",\n test_nghttp2_hd_inflate_indexed) ||\n !CU_add_test(pSuite, \"hd_inflate_indname_noinc\",\n test_nghttp2_hd_inflate_indname_noinc) ||\n !CU_add_test(pSuite, \"hd_inflate_indname_inc\",\n test_nghttp2_hd_inflate_indname_inc) ||\n !CU_add_test(pSuite, \"hd_inflate_indname_inc_eviction\",\n test_nghttp2_hd_inflate_indname_inc_eviction) ||\n !CU_add_test(pSuite, \"hd_inflate_newname_noinc\",\n test_nghttp2_hd_inflate_newname_noinc) ||\n !CU_add_test(pSuite, \"hd_inflate_newname_inc\",\n test_nghttp2_hd_inflate_newname_inc) ||\n !CU_add_test(pSuite, \"hd_inflate_clearall_inc\",\n test_nghttp2_hd_inflate_clearall_inc) ||\n !CU_add_test(pSuite, \"hd_inflate_zero_length_huffman\",\n test_nghttp2_hd_inflate_zero_length_huffman) ||\n !CU_add_test(pSuite, \"hd_inflate_expect_table_size_update\",\n test_nghttp2_hd_inflate_expect_table_size_update) ||\n !CU_add_test(pSuite, \"hd_inflate_unexpected_table_size_update\",\n test_nghttp2_hd_inflate_unexpected_table_size_update) ||\n !CU_add_test(pSuite, \"hd_ringbuf_reserve\",\n test_nghttp2_hd_ringbuf_reserve) ||\n !CU_add_test(pSuite, \"hd_change_table_size\",\n test_nghttp2_hd_change_table_size) ||\n !CU_add_test(pSuite, \"hd_deflate_inflate\",\n test_nghttp2_hd_deflate_inflate) ||\n !CU_add_test(pSuite, \"hd_no_index\", test_nghttp2_hd_no_index) ||\n !CU_add_test(pSuite, \"hd_deflate_bound\", test_nghttp2_hd_deflate_bound) ||\n !CU_add_test(pSuite, \"hd_public_api\", test_nghttp2_hd_public_api) ||\n !CU_add_test(pSuite, \"hd_deflate_hd_vec\",\n test_nghttp2_hd_deflate_hd_vec) ||\n !CU_add_test(pSuite, \"hd_decode_length\", test_nghttp2_hd_decode_length) ||\n !CU_add_test(pSuite, \"hd_huff_encode\", test_nghttp2_hd_huff_encode) ||\n !CU_add_test(pSuite, \"hd_huff_decode\", test_nghttp2_hd_huff_decode) ||\n !CU_add_test(pSuite, \"adjust_local_window_size\",\n test_nghttp2_adjust_local_window_size) ||\n !CU_add_test(pSuite, \"check_header_name\",\n test_nghttp2_check_header_name) ||\n !CU_add_test(pSuite, \"check_header_value\",\n test_nghttp2_check_header_value) ||\n !CU_add_test(pSuite, \"bufs_add\", test_nghttp2_bufs_add) ||\n !CU_add_test(pSuite, \"bufs_add_stack_buffer_overflow_bug\",\n test_nghttp2_bufs_add_stack_buffer_overflow_bug) ||\n !CU_add_test(pSuite, \"bufs_addb\", test_nghttp2_bufs_addb) ||\n !CU_add_test(pSuite, \"bufs_orb\", test_nghttp2_bufs_orb) ||\n !CU_add_test(pSuite, \"bufs_remove\", test_nghttp2_bufs_remove) ||\n !CU_add_test(pSuite, \"bufs_reset\", test_nghttp2_bufs_reset) ||\n !CU_add_test(pSuite, \"bufs_advance\", test_nghttp2_bufs_advance) ||\n !CU_add_test(pSuite, \"bufs_next_present\",\n test_nghttp2_bufs_next_present) ||\n !CU_add_test(pSuite, \"bufs_realloc\", test_nghttp2_bufs_realloc)) {\n CU_cleanup_registry();\n return (int)CU_get_error();\n }\n\n /* Run all tests using the CUnit Basic interface */\n CU_basic_set_mode(CU_BRM_VERBOSE);\n CU_basic_run_tests();\n num_tests_failed = CU_get_number_of_tests_failed();\n CU_cleanup_registry();\n if (CU_get_error() == CUE_SUCCESS) {\n return (int)num_tests_failed;\n } else {\n printf(\"CUnit Error: %s\\n\", CU_get_error_msg());\n return (int)CU_get_error();\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-707'], 'message': 'Implement max settings option'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: mrb_vm_exec(mrb_state *mrb, const struct RProc *proc, const mrb_code *pc)\n{\n /* mrb_assert(MRB_PROC_CFUNC_P(proc)) */\n const mrb_irep *irep = proc->body.irep;\n const mrb_pool_value *pool = irep->pool;\n const mrb_sym *syms = irep->syms;\n mrb_code insn;\n int ai = mrb_gc_arena_save(mrb);\n struct mrb_jmpbuf *prev_jmp = mrb->jmp;\n struct mrb_jmpbuf c_jmp;\n uint32_t a;\n uint16_t b;\n uint16_t c;\n mrb_sym mid;\n const struct mrb_irep_catch_handler *ch;\n\n#ifdef DIRECT_THREADED\n static const void * const optable[] = {\n#define OPCODE(x,_) &&L_OP_ ## x,\n#include \"mruby/ops.h\"\n#undef OPCODE\n };\n#endif\n\n mrb_bool exc_catched = FALSE;\nRETRY_TRY_BLOCK:\n\n MRB_TRY(&c_jmp) {\n\n if (exc_catched) {\n exc_catched = FALSE;\n mrb_gc_arena_restore(mrb, ai);\n if (mrb->exc && mrb->exc->tt == MRB_TT_BREAK)\n goto L_BREAK;\n goto L_RAISE;\n }\n mrb->jmp = &c_jmp;\n mrb_vm_ci_proc_set(mrb->c->ci, proc);\n\n#define regs (mrb->c->ci->stack)\n INIT_DISPATCH {\n CASE(OP_NOP, Z) {\n /* do nothing */\n NEXT;\n }\n\n CASE(OP_MOVE, BB) {\n regs[a] = regs[b];\n NEXT;\n }\n\n CASE(OP_LOADL, BB) {\n switch (pool[b].tt) { /* number */\n case IREP_TT_INT32:\n regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i32);\n break;\n case IREP_TT_INT64:\n#if defined(MRB_INT64)\n regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i64);\n break;\n#else\n#if defined(MRB_64BIT)\n if (INT32_MIN <= pool[b].u.i64 && pool[b].u.i64 <= INT32_MAX) {\n regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i64);\n break;\n }\n#endif\n goto L_INT_OVERFLOW;\n#endif\n case IREP_TT_BIGINT:\n goto L_INT_OVERFLOW;\n#ifndef MRB_NO_FLOAT\n case IREP_TT_FLOAT:\n regs[a] = mrb_float_value(mrb, pool[b].u.f);\n break;\n#endif\n default:\n /* should not happen (tt:string) */\n regs[a] = mrb_nil_value();\n break;\n }\n NEXT;\n }\n\n CASE(OP_LOADI, BB) {\n SET_FIXNUM_VALUE(regs[a], b);\n NEXT;\n }\n\n CASE(OP_LOADINEG, BB) {\n SET_FIXNUM_VALUE(regs[a], -b);\n NEXT;\n }\n\n CASE(OP_LOADI__1,B) goto L_LOADI;\n CASE(OP_LOADI_0,B) goto L_LOADI;\n CASE(OP_LOADI_1,B) goto L_LOADI;\n CASE(OP_LOADI_2,B) goto L_LOADI;\n CASE(OP_LOADI_3,B) goto L_LOADI;\n CASE(OP_LOADI_4,B) goto L_LOADI;\n CASE(OP_LOADI_5,B) goto L_LOADI;\n CASE(OP_LOADI_6,B) goto L_LOADI;\n CASE(OP_LOADI_7, B) {\n L_LOADI:\n SET_FIXNUM_VALUE(regs[a], (mrb_int)insn - (mrb_int)OP_LOADI_0);\n NEXT;\n }\n\n CASE(OP_LOADI16, BS) {\n SET_FIXNUM_VALUE(regs[a], (mrb_int)(int16_t)b);\n NEXT;\n }\n\n CASE(OP_LOADI32, BSS) {\n SET_INT_VALUE(mrb, regs[a], (int32_t)(((uint32_t)b<<16)+c));\n NEXT;\n }\n\n CASE(OP_LOADSYM, BB) {\n SET_SYM_VALUE(regs[a], syms[b]);\n NEXT;\n }\n\n CASE(OP_LOADNIL, B) {\n SET_NIL_VALUE(regs[a]);\n NEXT;\n }\n\n CASE(OP_LOADSELF, B) {\n regs[a] = regs[0];\n NEXT;\n }\n\n CASE(OP_LOADT, B) {\n SET_TRUE_VALUE(regs[a]);\n NEXT;\n }\n\n CASE(OP_LOADF, B) {\n SET_FALSE_VALUE(regs[a]);\n NEXT;\n }\n\n CASE(OP_GETGV, BB) {\n mrb_value val = mrb_gv_get(mrb, syms[b]);\n regs[a] = val;\n NEXT;\n }\n\n CASE(OP_SETGV, BB) {\n mrb_gv_set(mrb, syms[b], regs[a]);\n NEXT;\n }\n\n CASE(OP_GETSV, BB) {\n mrb_value val = mrb_vm_special_get(mrb, syms[b]);\n regs[a] = val;\n NEXT;\n }\n\n CASE(OP_SETSV, BB) {\n mrb_vm_special_set(mrb, syms[b], regs[a]);\n NEXT;\n }\n\n CASE(OP_GETIV, BB) {\n regs[a] = mrb_iv_get(mrb, regs[0], syms[b]);\n NEXT;\n }\n\n CASE(OP_SETIV, BB) {\n mrb_iv_set(mrb, regs[0], syms[b], regs[a]);\n NEXT;\n }\n\n CASE(OP_GETCV, BB) {\n mrb_value val;\n val = mrb_vm_cv_get(mrb, syms[b]);\n regs[a] = val;\n NEXT;\n }\n\n CASE(OP_SETCV, BB) {\n mrb_vm_cv_set(mrb, syms[b], regs[a]);\n NEXT;\n }\n\n CASE(OP_GETIDX, B) {\n mrb_value va = regs[a], vb = regs[a+1];\n switch (mrb_type(va)) {\n case MRB_TT_ARRAY:\n if (!mrb_integer_p(vb)) goto getidx_fallback;\n regs[a] = mrb_ary_entry(va, mrb_integer(vb));\n break;\n case MRB_TT_HASH:\n va = mrb_hash_get(mrb, va, vb);\n regs[a] = va;\n break;\n case MRB_TT_STRING:\n switch (mrb_type(vb)) {\n case MRB_TT_INTEGER:\n case MRB_TT_STRING:\n case MRB_TT_RANGE:\n va = mrb_str_aref(mrb, va, vb, mrb_undef_value());\n regs[a] = va;\n break;\n default:\n goto getidx_fallback;\n }\n break;\n default:\n getidx_fallback:\n mid = MRB_OPSYM(aref);\n goto L_SEND_SYM;\n }\n NEXT;\n }\n\n CASE(OP_SETIDX, B) {\n c = 2;\n mid = MRB_OPSYM(aset);\n SET_NIL_VALUE(regs[a+3]);\n goto L_SENDB_SYM;\n }\n\n CASE(OP_GETCONST, BB) {\n mrb_value v = mrb_vm_const_get(mrb, syms[b]);\n regs[a] = v;\n NEXT;\n }\n\n CASE(OP_SETCONST, BB) {\n mrb_vm_const_set(mrb, syms[b], regs[a]);\n NEXT;\n }\n\n CASE(OP_GETMCNST, BB) {\n mrb_value v = mrb_const_get(mrb, regs[a], syms[b]);\n regs[a] = v;\n NEXT;\n }\n\n CASE(OP_SETMCNST, BB) {\n mrb_const_set(mrb, regs[a+1], syms[b], regs[a]);\n NEXT;\n }\n\n CASE(OP_GETUPVAR, BBB) {\n mrb_value *regs_a = regs + a;\n struct REnv *e = uvenv(mrb, c);\n\n if (e && b < MRB_ENV_LEN(e)) {\n *regs_a = e->stack[b];\n }\n else {\n *regs_a = mrb_nil_value();\n }\n NEXT;\n }\n\n CASE(OP_SETUPVAR, BBB) {\n struct REnv *e = uvenv(mrb, c);\n\n if (e) {\n mrb_value *regs_a = regs + a;\n\n if (b < MRB_ENV_LEN(e)) {\n e->stack[b] = *regs_a;\n mrb_write_barrier(mrb, (struct RBasic*)e);\n }\n }\n NEXT;\n }\n\n CASE(OP_JMP, S) {\n pc += (int16_t)a;\n JUMP;\n }\n CASE(OP_JMPIF, BS) {\n if (mrb_test(regs[a])) {\n pc += (int16_t)b;\n JUMP;\n }\n NEXT;\n }\n CASE(OP_JMPNOT, BS) {\n if (!mrb_test(regs[a])) {\n pc += (int16_t)b;\n JUMP;\n }\n NEXT;\n }\n CASE(OP_JMPNIL, BS) {\n if (mrb_nil_p(regs[a])) {\n pc += (int16_t)b;\n JUMP;\n }\n NEXT;\n }\n\n CASE(OP_JMPUW, S) {\n a = (uint32_t)((pc - irep->iseq) + (int16_t)a);\n CHECKPOINT_RESTORE(RBREAK_TAG_JUMP) {\n struct RBreak *brk = (struct RBreak*)mrb->exc;\n mrb_value target = mrb_break_value_get(brk);\n mrb_assert(mrb_integer_p(target));\n a = (uint32_t)mrb_integer(target);\n mrb_assert(a >= 0 && a < irep->ilen);\n }\n CHECKPOINT_MAIN(RBREAK_TAG_JUMP) {\n ch = catch_handler_find(mrb, mrb->c->ci, pc, MRB_CATCH_FILTER_ENSURE);\n if (ch) {\n /* avoiding a jump from a catch handler into the same handler */\n if (a < mrb_irep_catch_handler_unpack(ch->begin) || a >= mrb_irep_catch_handler_unpack(ch->end)) {\n THROW_TAGGED_BREAK(mrb, RBREAK_TAG_JUMP, proc, mrb_fixnum_value(a));\n }\n }\n }\n CHECKPOINT_END(RBREAK_TAG_JUMP);\n\n mrb->exc = NULL; /* clear break object */\n pc = irep->iseq + a;\n JUMP;\n }\n\n CASE(OP_EXCEPT, B) {\n mrb_value exc;\n\n if (mrb->exc == NULL) {\n exc = mrb_nil_value();\n }\n else {\n switch (mrb->exc->tt) {\n case MRB_TT_BREAK:\n case MRB_TT_EXCEPTION:\n exc = mrb_obj_value(mrb->exc);\n break;\n default:\n mrb_assert(!\"bad mrb_type\");\n exc = mrb_nil_value();\n break;\n }\n mrb->exc = NULL;\n }\n regs[a] = exc;\n NEXT;\n }\n CASE(OP_RESCUE, BB) {\n mrb_value exc = regs[a]; /* exc on stack */\n mrb_value e = regs[b];\n struct RClass *ec;\n\n switch (mrb_type(e)) {\n case MRB_TT_CLASS:\n case MRB_TT_MODULE:\n break;\n default:\n {\n mrb_value exc;\n\n exc = mrb_exc_new_lit(mrb, E_TYPE_ERROR,\n \"class or module required for rescue clause\");\n mrb_exc_set(mrb, exc);\n goto L_RAISE;\n }\n }\n ec = mrb_class_ptr(e);\n regs[b] = mrb_bool_value(mrb_obj_is_kind_of(mrb, exc, ec));\n NEXT;\n }\n\n CASE(OP_RAISEIF, B) {\n mrb_value exc = regs[a];\n if (mrb_break_p(exc)) {\n mrb->exc = mrb_obj_ptr(exc);\n goto L_BREAK;\n }\n mrb_exc_set(mrb, exc);\n if (mrb->exc) {\n goto L_RAISE;\n }\n NEXT;\n }\n\n CASE(OP_SSEND, BBB) {\n regs[a] = regs[0];\n insn = OP_SEND;\n }\n goto L_SENDB;\n\n CASE(OP_SSENDB, BBB) {\n regs[a] = regs[0];\n }\n goto L_SENDB;\n\n CASE(OP_SEND, BBB)\n goto L_SENDB;\n\n L_SEND_SYM:\n c = 1;\n /* push nil after arguments */\n SET_NIL_VALUE(regs[a+2]);\n goto L_SENDB_SYM;\n\n CASE(OP_SENDB, BBB)\n L_SENDB:\n mid = syms[b];\n L_SENDB_SYM:\n {\n mrb_callinfo *ci = mrb->c->ci;\n mrb_method_t m;\n struct RClass *cls;\n mrb_value recv, blk;\n\n ARGUMENT_NORMALIZE(a, &c, insn);\n\n recv = regs[a];\n cls = mrb_class(mrb, recv);\n m = mrb_method_search_vm(mrb, &cls, mid);\n if (MRB_METHOD_UNDEF_P(m)) {\n m = prepare_missing(mrb, recv, mid, &cls, a, &c, blk, 0);\n mid = MRB_SYM(method_missing);\n }\n\n /* push callinfo */\n ci = cipush(mrb, a, 0, cls, NULL, mid, c);\n\n if (MRB_METHOD_CFUNC_P(m)) {\n if (MRB_METHOD_PROC_P(m)) {\n struct RProc *p = MRB_METHOD_PROC(m);\n\n mrb_vm_ci_proc_set(ci, p);\n recv = p->body.func(mrb, recv);\n }\n else {\n if (MRB_METHOD_NOARG_P(m)) {\n check_method_noarg(mrb, ci);\n }\n recv = MRB_METHOD_FUNC(m)(mrb, recv);\n }\n mrb_gc_arena_shrink(mrb, ai);\n if (mrb->exc) goto L_RAISE;\n ci = mrb->c->ci;\n if (mrb_proc_p(blk)) {\n struct RProc *p = mrb_proc_ptr(blk);\n if (p && !MRB_PROC_STRICT_P(p) && MRB_PROC_ENV(p) == mrb_vm_ci_env(&ci[-1])) {\n p->flags |= MRB_PROC_ORPHAN;\n }\n }\n if (!ci->u.target_class) { /* return from context modifying method (resume/yield) */\n if (ci->cci == CINFO_RESUMED) {\n mrb->jmp = prev_jmp;\n return recv;\n }\n else {\n mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc));\n proc = ci[-1].proc;\n irep = proc->body.irep;\n pool = irep->pool;\n syms = irep->syms;\n }\n }\n ci->stack[0] = recv;\n /* pop stackpos */\n ci = cipop(mrb);\n pc = ci->pc;\n }\n else {\n /* setup environment for calling method */\n mrb_vm_ci_proc_set(ci, (proc = MRB_METHOD_PROC(m)));\n irep = proc->body.irep;\n pool = irep->pool;\n syms = irep->syms;\n mrb_stack_extend(mrb, (irep->nregs < 4) ? 4 : irep->nregs);\n pc = irep->iseq;\n }\n }\n JUMP;\n\n CASE(OP_CALL, Z) {\n mrb_callinfo *ci = mrb->c->ci;\n mrb_value recv = ci->stack[0];\n struct RProc *m = mrb_proc_ptr(recv);\n\n /* replace callinfo */\n ci->u.target_class = MRB_PROC_TARGET_CLASS(m);\n mrb_vm_ci_proc_set(ci, m);\n if (MRB_PROC_ENV_P(m)) {\n ci->mid = MRB_PROC_ENV(m)->mid;\n }\n\n /* prepare stack */\n if (MRB_PROC_CFUNC_P(m)) {\n recv = MRB_PROC_CFUNC(m)(mrb, recv);\n mrb_gc_arena_shrink(mrb, ai);\n if (mrb->exc) goto L_RAISE;\n /* pop stackpos */\n ci = cipop(mrb);\n pc = ci->pc;\n ci[1].stack[0] = recv;\n irep = mrb->c->ci->proc->body.irep;\n }\n else {\n /* setup environment for calling method */\n proc = m;\n irep = m->body.irep;\n if (!irep) {\n mrb->c->ci->stack[0] = mrb_nil_value();\n a = 0;\n c = OP_R_NORMAL;\n goto L_OP_RETURN_BODY;\n }\n mrb_int nargs = mrb_ci_bidx(ci)+1;\n if (nargs < irep->nregs) {\n mrb_stack_extend(mrb, irep->nregs);\n stack_clear(regs+nargs, irep->nregs-nargs);\n }\n if (MRB_PROC_ENV_P(m)) {\n regs[0] = MRB_PROC_ENV(m)->stack[0];\n }\n pc = irep->iseq;\n }\n pool = irep->pool;\n syms = irep->syms;\n JUMP;\n }\n\n CASE(OP_SUPER, BB) {\n mrb_method_t m;\n struct RClass *cls;\n mrb_callinfo *ci = mrb->c->ci;\n mrb_value recv, blk;\n const struct RProc *p = ci->proc;\n mrb_sym mid = ci->mid;\n struct RClass* target_class = MRB_PROC_TARGET_CLASS(p);\n\n if (MRB_PROC_ENV_P(p) && p->e.env->mid && p->e.env->mid != mid) { /* alias support */\n mid = p->e.env->mid; /* restore old mid */\n }\n\n if (mid == 0 || !target_class) {\n mrb_value exc = mrb_exc_new_lit(mrb, E_NOMETHOD_ERROR, \"super called outside of method\");\n mrb_exc_set(mrb, exc);\n goto L_RAISE;\n }\n if (target_class->flags & MRB_FL_CLASS_IS_PREPENDED) {\n target_class = mrb_vm_ci_target_class(ci);\n }\n else if (target_class->tt == MRB_TT_MODULE) {\n target_class = mrb_vm_ci_target_class(ci);\n if (target_class->tt != MRB_TT_ICLASS) {\n goto super_typeerror;\n }\n }\n recv = regs[0];\n if (!mrb_obj_is_kind_of(mrb, recv, target_class)) {\n super_typeerror: ;\n mrb_value exc = mrb_exc_new_lit(mrb, E_TYPE_ERROR,\n \"self has wrong type to call super in this context\");\n mrb_exc_set(mrb, exc);\n goto L_RAISE;\n }\n\n ARGUMENT_NORMALIZE(a, &b, OP_SUPER);\n\n cls = target_class->super;\n m = mrb_method_search_vm(mrb, &cls, mid);\n if (MRB_METHOD_UNDEF_P(m)) {\n m = prepare_missing(mrb, recv, mid, &cls, a, &b, blk, 1);\n mid = MRB_SYM(method_missing);\n }\n\n /* push callinfo */\n ci = cipush(mrb, a, 0, cls, NULL, mid, b);\n\n /* prepare stack */\n ci->stack[0] = recv;\n\n if (MRB_METHOD_CFUNC_P(m)) {\n mrb_value v;\n\n if (MRB_METHOD_PROC_P(m)) {\n mrb_vm_ci_proc_set(ci, MRB_METHOD_PROC(m));\n }\n v = MRB_METHOD_CFUNC(m)(mrb, recv);\n mrb_gc_arena_restore(mrb, ai);\n if (mrb->exc) goto L_RAISE;\n ci = mrb->c->ci;\n mrb_assert(!mrb_break_p(v));\n if (!mrb_vm_ci_target_class(ci)) { /* return from context modifying method (resume/yield) */\n if (ci->cci == CINFO_RESUMED) {\n mrb->jmp = prev_jmp;\n return v;\n }\n else {\n mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc));\n proc = ci[-1].proc;\n irep = proc->body.irep;\n pool = irep->pool;\n syms = irep->syms;\n }\n }\n mrb->c->ci->stack[0] = v;\n ci = cipop(mrb);\n pc = ci->pc;\n }\n else {\n /* setup environment for calling method */\n mrb_vm_ci_proc_set(ci, (proc = MRB_METHOD_PROC(m)));\n irep = proc->body.irep;\n pool = irep->pool;\n syms = irep->syms;\n mrb_stack_extend(mrb, (irep->nregs < 4) ? 4 : irep->nregs);\n pc = irep->iseq;\n }\n JUMP;\n }\n\n CASE(OP_ARGARY, BS) {\n mrb_int m1 = (b>>11)&0x3f;\n mrb_int r = (b>>10)&0x1;\n mrb_int m2 = (b>>5)&0x1f;\n mrb_int kd = (b>>4)&0x1;\n mrb_int lv = (b>>0)&0xf;\n mrb_value *stack;\n\n if (mrb->c->ci->mid == 0 || mrb_vm_ci_target_class(mrb->c->ci) == NULL) {\n mrb_value exc;\n\n L_NOSUPER:\n exc = mrb_exc_new_lit(mrb, E_NOMETHOD_ERROR, \"super called outside of method\");\n mrb_exc_set(mrb, exc);\n goto L_RAISE;\n }\n if (lv == 0) stack = regs + 1;\n else {\n struct REnv *e = uvenv(mrb, lv-1);\n if (!e) goto L_NOSUPER;\n if (MRB_ENV_LEN(e) <= m1+r+m2+1)\n goto L_NOSUPER;\n stack = e->stack + 1;\n }\n if (r == 0) {\n regs[a] = mrb_ary_new_from_values(mrb, m1+m2, stack);\n }\n else {\n mrb_value *pp = NULL;\n struct RArray *rest;\n mrb_int len = 0;\n\n if (mrb_array_p(stack[m1])) {\n struct RArray *ary = mrb_ary_ptr(stack[m1]);\n\n pp = ARY_PTR(ary);\n len = ARY_LEN(ary);\n }\n regs[a] = mrb_ary_new_capa(mrb, m1+len+m2);\n rest = mrb_ary_ptr(regs[a]);\n if (m1 > 0) {\n stack_copy(ARY_PTR(rest), stack, m1);\n }\n if (len > 0) {\n stack_copy(ARY_PTR(rest)+m1, pp, len);\n }\n if (m2 > 0) {\n stack_copy(ARY_PTR(rest)+m1+len, stack+m1+1, m2);\n }\n ARY_SET_LEN(rest, m1+len+m2);\n }\n if (kd) {\n regs[a+1] = stack[m1+r+m2];\n regs[a+2] = stack[m1+r+m2+1];\n }\n else {\n regs[a+1] = stack[m1+r+m2];\n }\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_ENTER, W) {\n mrb_int m1 = MRB_ASPEC_REQ(a);\n mrb_int o = MRB_ASPEC_OPT(a);\n mrb_int r = MRB_ASPEC_REST(a);\n mrb_int m2 = MRB_ASPEC_POST(a);\n mrb_int kd = (MRB_ASPEC_KEY(a) > 0 || MRB_ASPEC_KDICT(a))? 1 : 0;\n /* unused\n int b = MRB_ASPEC_BLOCK(a);\n */\n mrb_int const len = m1 + o + r + m2;\n\n mrb_callinfo *ci = mrb->c->ci;\n mrb_int argc = ci->n;\n mrb_value *argv = regs+1;\n mrb_value * const argv0 = argv;\n mrb_int const kw_pos = len + kd; /* where kwhash should be */\n mrb_int const blk_pos = kw_pos + 1; /* where block should be */\n mrb_value blk = regs[mrb_ci_bidx(ci)];\n mrb_value kdict = mrb_nil_value();\n\n /* keyword arguments */\n if (ci->nk > 0) {\n mrb_int kidx = mrb_ci_kidx(ci);\n kdict = regs[kidx];\n if (!mrb_hash_p(kdict) || mrb_hash_size(mrb, kdict) == 0) {\n kdict = mrb_nil_value();\n ci->nk = 0;\n }\n }\n if (!kd && !mrb_nil_p(kdict)) {\n if (argc < 14) {\n ci->n++;\n argc++; /* include kdict in normal arguments */\n }\n else if (argc == 14) {\n /* pack arguments and kdict */\n regs[1] = mrb_ary_new_from_values(mrb, argc+1, ®s[1]);\n argc = ci->n = 15;\n }\n else {/* argc == 15 */\n /* push kdict to packed arguments */\n mrb_ary_push(mrb, regs[1], regs[2]);\n }\n ci->nk = 0;\n }\n if (kd && MRB_ASPEC_KEY(a) > 0 && mrb_hash_p(kdict)) {\n kdict = mrb_hash_dup(mrb, kdict);\n }\n\n /* arguments is passed with Array */\n if (argc == 15) {\n struct RArray *ary = mrb_ary_ptr(regs[1]);\n argv = ARY_PTR(ary);\n argc = (int)ARY_LEN(ary);\n mrb_gc_protect(mrb, regs[1]);\n }\n\n /* strict argument check */\n if (ci->proc && MRB_PROC_STRICT_P(ci->proc)) {\n if (argc < m1 + m2 || (r == 0 && argc > len)) {\n argnum_error(mrb, m1+m2);\n goto L_RAISE;\n }\n }\n /* extract first argument array to arguments */\n else if (len > 1 && argc == 1 && mrb_array_p(argv[0])) {\n mrb_gc_protect(mrb, argv[0]);\n argc = (int)RARRAY_LEN(argv[0]);\n argv = RARRAY_PTR(argv[0]);\n }\n\n /* rest arguments */\n mrb_value rest = mrb_nil_value();\n if (argc < len) {\n mrb_int mlen = m2;\n if (argc < m1+m2) {\n mlen = m1 < argc ? argc - m1 : 0;\n }\n\n /* copy mandatory and optional arguments */\n if (argv0 != argv && argv) {\n value_move(®s[1], argv, argc-mlen); /* m1 + o */\n }\n if (argc < m1) {\n stack_clear(®s[argc+1], m1-argc);\n }\n /* copy post mandatory arguments */\n if (mlen) {\n value_move(®s[len-m2+1], &argv[argc-mlen], mlen);\n }\n if (mlen < m2) {\n stack_clear(®s[len-m2+mlen+1], m2-mlen);\n }\n /* initialize rest arguments with empty Array */\n if (r) {\n rest = mrb_ary_new_capa(mrb, 0);\n regs[m1+o+1] = rest;\n }\n /* skip initializer of passed arguments */\n if (o > 0 && argc > m1+m2)\n pc += (argc - m1 - m2)*3;\n }\n else {\n mrb_int rnum = 0;\n if (argv0 != argv) {\n value_move(®s[1], argv, m1+o);\n }\n if (r) {\n rnum = argc-m1-o-m2;\n rest = mrb_ary_new_from_values(mrb, rnum, argv+m1+o);\n regs[m1+o+1] = rest;\n }\n if (m2 > 0 && argc-m2 > m1) {\n value_move(®s[m1+o+r+1], &argv[m1+o+rnum], m2);\n }\n pc += o*3;\n }\n\n /* need to be update blk first to protect blk from GC */\n regs[blk_pos] = blk; /* move block */\n if (kd) {\n if (mrb_nil_p(kdict))\n kdict = mrb_hash_new_capa(mrb, 0);\n regs[kw_pos] = kdict; /* set kwhash */\n }\n\n /* format arguments for generated code */\n mrb->c->ci->n = len;\n\n /* clear local (but non-argument) variables */\n if (irep->nlocals-blk_pos-1 > 0) {\n stack_clear(®s[blk_pos+1], irep->nlocals-blk_pos-1);\n }\n JUMP;\n }\n\n CASE(OP_KARG, BB) {\n mrb_value k = mrb_symbol_value(syms[b]);\n mrb_int kidx = mrb_ci_kidx(mrb->c->ci);\n mrb_value kdict, v;\n\n if (kidx < 0 || !mrb_hash_p(kdict=regs[kidx]) || !mrb_hash_key_p(mrb, kdict, k)) {\n mrb_value str = mrb_format(mrb, \"missing keyword: %v\", k);\n mrb_exc_set(mrb, mrb_exc_new_str(mrb, E_ARGUMENT_ERROR, str));\n goto L_RAISE;\n }\n v = mrb_hash_get(mrb, kdict, k);\n regs[a] = v;\n mrb_hash_delete_key(mrb, kdict, k);\n NEXT;\n }\n\n CASE(OP_KEY_P, BB) {\n mrb_value k = mrb_symbol_value(syms[b]);\n mrb_int kidx = mrb_ci_kidx(mrb->c->ci);\n mrb_value kdict;\n mrb_bool key_p = FALSE;\n\n if (kidx >= 0 && mrb_hash_p(kdict=regs[kidx])) {\n key_p = mrb_hash_key_p(mrb, kdict, k);\n }\n regs[a] = mrb_bool_value(key_p);\n NEXT;\n }\n\n CASE(OP_KEYEND, Z) {\n mrb_int kidx = mrb_ci_kidx(mrb->c->ci);\n mrb_value kdict;\n\n if (kidx >= 0 && mrb_hash_p(kdict=regs[kidx]) && !mrb_hash_empty_p(mrb, kdict)) {\n mrb_value keys = mrb_hash_keys(mrb, kdict);\n mrb_value key1 = RARRAY_PTR(keys)[0];\n mrb_value str = mrb_format(mrb, \"unknown keyword: %v\", key1);\n mrb_exc_set(mrb, mrb_exc_new_str(mrb, E_ARGUMENT_ERROR, str));\n goto L_RAISE;\n }\n NEXT;\n }\n\n CASE(OP_BREAK, B) {\n c = OP_R_BREAK;\n goto L_RETURN;\n }\n CASE(OP_RETURN_BLK, B) {\n c = OP_R_RETURN;\n goto L_RETURN;\n }\n CASE(OP_RETURN, B)\n c = OP_R_NORMAL;\n L_RETURN:\n {\n mrb_callinfo *ci;\n\n ci = mrb->c->ci;\n if (ci->mid) {\n mrb_value blk = regs[mrb_ci_bidx(ci)];\n\n if (mrb_proc_p(blk)) {\n struct RProc *p = mrb_proc_ptr(blk);\n\n if (!MRB_PROC_STRICT_P(p) &&\n ci > mrb->c->cibase && MRB_PROC_ENV(p) == mrb_vm_ci_env(&ci[-1])) {\n p->flags |= MRB_PROC_ORPHAN;\n }\n }\n }\n\n if (mrb->exc) {\n L_RAISE:\n ci = mrb->c->ci;\n if (ci == mrb->c->cibase) {\n ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL);\n if (ch == NULL) goto L_FTOP;\n goto L_CATCH;\n }\n while ((ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL)) == NULL) {\n ci = cipop(mrb);\n if (ci[1].cci == CINFO_SKIP && prev_jmp) {\n mrb->jmp = prev_jmp;\n MRB_THROW(prev_jmp);\n }\n pc = ci[0].pc;\n if (ci == mrb->c->cibase) {\n ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL);\n if (ch == NULL) {\n L_FTOP: /* fiber top */\n if (mrb->c == mrb->root_c) {\n mrb->c->ci->stack = mrb->c->stbase;\n goto L_STOP;\n }\n else {\n struct mrb_context *c = mrb->c;\n\n c->status = MRB_FIBER_TERMINATED;\n mrb->c = c->prev;\n c->prev = NULL;\n goto L_RAISE;\n }\n }\n break;\n }\n }\n L_CATCH:\n if (ch == NULL) goto L_STOP;\n if (FALSE) {\n L_CATCH_TAGGED_BREAK: /* from THROW_TAGGED_BREAK() or UNWIND_ENSURE() */\n ci = mrb->c->ci;\n }\n proc = ci->proc;\n irep = proc->body.irep;\n pool = irep->pool;\n syms = irep->syms;\n mrb_stack_extend(mrb, irep->nregs);\n pc = irep->iseq + mrb_irep_catch_handler_unpack(ch->target);\n }\n else {\n mrb_int acc;\n mrb_value v;\n\n ci = mrb->c->ci;\n v = regs[a];\n mrb_gc_protect(mrb, v);\n switch (c) {\n case OP_R_RETURN:\n /* Fall through to OP_R_NORMAL otherwise */\n if (ci->cci == CINFO_NONE && MRB_PROC_ENV_P(proc) && !MRB_PROC_STRICT_P(proc)) {\n const struct RProc *dst;\n mrb_callinfo *cibase;\n cibase = mrb->c->cibase;\n dst = top_proc(mrb, proc);\n\n if (MRB_PROC_ENV_P(dst)) {\n struct REnv *e = MRB_PROC_ENV(dst);\n\n if (!MRB_ENV_ONSTACK_P(e) || (e->cxt && e->cxt != mrb->c)) {\n localjump_error(mrb, LOCALJUMP_ERROR_RETURN);\n goto L_RAISE;\n }\n }\n /* check jump destination */\n while (cibase <= ci && ci->proc != dst) {\n if (ci->cci > CINFO_NONE) { /* jump cross C boundary */\n localjump_error(mrb, LOCALJUMP_ERROR_RETURN);\n goto L_RAISE;\n }\n ci--;\n }\n if (ci <= cibase) { /* no jump destination */\n localjump_error(mrb, LOCALJUMP_ERROR_RETURN);\n goto L_RAISE;\n }\n ci = mrb->c->ci;\n while (cibase <= ci && ci->proc != dst) {\n CHECKPOINT_RESTORE(RBREAK_TAG_RETURN_BLOCK) {\n cibase = mrb->c->cibase;\n dst = top_proc(mrb, proc);\n }\n CHECKPOINT_MAIN(RBREAK_TAG_RETURN_BLOCK) {\n UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN_BLOCK, proc, v);\n }\n CHECKPOINT_END(RBREAK_TAG_RETURN_BLOCK);\n ci = cipop(mrb);\n pc = ci->pc;\n }\n proc = ci->proc;\n mrb->exc = NULL; /* clear break object */\n break;\n }\n /* fallthrough */\n case OP_R_NORMAL:\n NORMAL_RETURN:\n if (ci == mrb->c->cibase) {\n struct mrb_context *c;\n c = mrb->c;\n\n if (!c->prev) { /* toplevel return */\n regs[irep->nlocals] = v;\n goto CHECKPOINT_LABEL_MAKE(RBREAK_TAG_STOP);\n }\n if (!c->vmexec && c->prev->ci == c->prev->cibase) {\n mrb_value exc = mrb_exc_new_lit(mrb, E_FIBER_ERROR, \"double resume\");\n mrb_exc_set(mrb, exc);\n goto L_RAISE;\n }\n CHECKPOINT_RESTORE(RBREAK_TAG_RETURN_TOPLEVEL) {\n c = mrb->c;\n }\n CHECKPOINT_MAIN(RBREAK_TAG_RETURN_TOPLEVEL) {\n UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN_TOPLEVEL, proc, v);\n }\n CHECKPOINT_END(RBREAK_TAG_RETURN_TOPLEVEL);\n /* automatic yield at the end */\n c->status = MRB_FIBER_TERMINATED;\n mrb->c = c->prev;\n mrb->c->status = MRB_FIBER_RUNNING;\n c->prev = NULL;\n if (c->vmexec) {\n mrb_gc_arena_restore(mrb, ai);\n c->vmexec = FALSE;\n mrb->jmp = prev_jmp;\n return v;\n }\n ci = mrb->c->ci;\n }\n CHECKPOINT_RESTORE(RBREAK_TAG_RETURN) {\n /* do nothing */\n }\n CHECKPOINT_MAIN(RBREAK_TAG_RETURN) {\n UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN, proc, v);\n }\n CHECKPOINT_END(RBREAK_TAG_RETURN);\n mrb->exc = NULL; /* clear break object */\n break;\n case OP_R_BREAK:\n if (MRB_PROC_STRICT_P(proc)) goto NORMAL_RETURN;\n if (MRB_PROC_ORPHAN_P(proc)) {\n mrb_value exc;\n\n L_BREAK_ERROR:\n exc = mrb_exc_new_lit(mrb, E_LOCALJUMP_ERROR,\n \"break from proc-closure\");\n mrb_exc_set(mrb, exc);\n goto L_RAISE;\n }\n if (!MRB_PROC_ENV_P(proc) || !MRB_ENV_ONSTACK_P(MRB_PROC_ENV(proc))) {\n goto L_BREAK_ERROR;\n }\n else {\n struct REnv *e = MRB_PROC_ENV(proc);\n\n if (e->cxt != mrb->c) {\n goto L_BREAK_ERROR;\n }\n }\n CHECKPOINT_RESTORE(RBREAK_TAG_BREAK) {\n /* do nothing */\n }\n CHECKPOINT_MAIN(RBREAK_TAG_BREAK) {\n UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK, proc, v);\n }\n CHECKPOINT_END(RBREAK_TAG_BREAK);\n /* break from fiber block */\n if (ci == mrb->c->cibase && ci->pc) {\n struct mrb_context *c = mrb->c;\n\n mrb->c = c->prev;\n c->prev = NULL;\n ci = mrb->c->ci;\n }\n if (ci->cci > CINFO_NONE) {\n ci = cipop(mrb);\n mrb_gc_arena_restore(mrb, ai);\n mrb->c->vmexec = FALSE;\n mrb->exc = (struct RObject*)break_new(mrb, RBREAK_TAG_BREAK, proc, v);\n mrb->jmp = prev_jmp;\n MRB_THROW(prev_jmp);\n }\n if (FALSE) {\n struct RBreak *brk;\n\n L_BREAK:\n brk = (struct RBreak*)mrb->exc;\n proc = mrb_break_proc_get(brk);\n v = mrb_break_value_get(brk);\n ci = mrb->c->ci;\n\n switch (mrb_break_tag_get(brk)) {\n#define DISPATCH_CHECKPOINTS(n, i) case n: goto CHECKPOINT_LABEL_MAKE(n);\n RBREAK_TAG_FOREACH(DISPATCH_CHECKPOINTS)\n#undef DISPATCH_CHECKPOINTS\n default:\n mrb_assert(!\"wrong break tag\");\n }\n }\n while (mrb->c->cibase < ci && ci[-1].proc != proc->upper) {\n if (ci[-1].cci == CINFO_SKIP) {\n goto L_BREAK_ERROR;\n }\n CHECKPOINT_RESTORE(RBREAK_TAG_BREAK_UPPER) {\n /* do nothing */\n }\n CHECKPOINT_MAIN(RBREAK_TAG_BREAK_UPPER) {\n UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK_UPPER, proc, v);\n }\n CHECKPOINT_END(RBREAK_TAG_BREAK_UPPER);\n ci = cipop(mrb);\n pc = ci->pc;\n }\n CHECKPOINT_RESTORE(RBREAK_TAG_BREAK_INTARGET) {\n /* do nothing */\n }\n CHECKPOINT_MAIN(RBREAK_TAG_BREAK_INTARGET) {\n UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK_INTARGET, proc, v);\n }\n CHECKPOINT_END(RBREAK_TAG_BREAK_INTARGET);\n if (ci == mrb->c->cibase) {\n goto L_BREAK_ERROR;\n }\n mrb->exc = NULL; /* clear break object */\n break;\n default:\n /* cannot happen */\n break;\n }\n mrb_assert(ci == mrb->c->ci);\n mrb_assert(mrb->exc == NULL);\n\n if (mrb->c->vmexec && !mrb_vm_ci_target_class(ci)) {\n mrb_gc_arena_restore(mrb, ai);\n mrb->c->vmexec = FALSE;\n mrb->jmp = prev_jmp;\n return v;\n }\n acc = ci->cci;\n ci = cipop(mrb);\n if (acc == CINFO_SKIP || acc == CINFO_DIRECT) {\n mrb_gc_arena_restore(mrb, ai);\n mrb->jmp = prev_jmp;\n return v;\n }\n pc = ci->pc;\n DEBUG(fprintf(stderr, \"from :%s\\n\", mrb_sym_name(mrb, ci->mid)));\n proc = ci->proc;\n irep = proc->body.irep;\n pool = irep->pool;\n syms = irep->syms;\n\n ci[1].stack[0] = v;\n mrb_gc_arena_restore(mrb, ai);\n }\n JUMP;\n }\n\n CASE(OP_BLKPUSH, BS) {\n int m1 = (b>>11)&0x3f;\n int r = (b>>10)&0x1;\n int m2 = (b>>5)&0x1f;\n int kd = (b>>4)&0x1;\n int lv = (b>>0)&0xf;\n mrb_value *stack;\n\n if (lv == 0) stack = regs + 1;\n else {\n struct REnv *e = uvenv(mrb, lv-1);\n if (!e || (!MRB_ENV_ONSTACK_P(e) && e->mid == 0) ||\n MRB_ENV_LEN(e) <= m1+r+m2+1) {\n localjump_error(mrb, LOCALJUMP_ERROR_YIELD);\n goto L_RAISE;\n }\n stack = e->stack + 1;\n }\n if (mrb_nil_p(stack[m1+r+m2+kd])) {\n localjump_error(mrb, LOCALJUMP_ERROR_YIELD);\n goto L_RAISE;\n }\n regs[a] = stack[m1+r+m2+kd];\n NEXT;\n }\n\n L_INT_OVERFLOW:\n {\n mrb_value exc = mrb_exc_new_lit(mrb, E_RANGE_ERROR, \"integer overflow\");\n mrb_exc_set(mrb, exc);\n }\n goto L_RAISE;\n\n#define TYPES2(a,b) ((((uint16_t)(a))<<8)|(((uint16_t)(b))&0xff))\n#define OP_MATH(op_name) \\\n /* need to check if op is overridden */ \\\n switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) { \\\n OP_MATH_CASE_INTEGER(op_name); \\\n OP_MATH_CASE_FLOAT(op_name, integer, float); \\\n OP_MATH_CASE_FLOAT(op_name, float, integer); \\\n OP_MATH_CASE_FLOAT(op_name, float, float); \\\n OP_MATH_CASE_STRING_##op_name(); \\\n default: \\\n mid = MRB_OPSYM(op_name); \\\n goto L_SEND_SYM; \\\n } \\\n NEXT;\n#define OP_MATH_CASE_INTEGER(op_name) \\\n case TYPES2(MRB_TT_INTEGER, MRB_TT_INTEGER): \\\n { \\\n mrb_int x = mrb_integer(regs[a]), y = mrb_integer(regs[a+1]), z; \\\n if (mrb_int_##op_name##_overflow(x, y, &z)) \\\n OP_MATH_OVERFLOW_INT(); \\\n else \\\n SET_INT_VALUE(mrb,regs[a], z); \\\n } \\\n break\n#ifdef MRB_NO_FLOAT\n#define OP_MATH_CASE_FLOAT(op_name, t1, t2) (void)0\n#else\n#define OP_MATH_CASE_FLOAT(op_name, t1, t2) \\\n case TYPES2(OP_MATH_TT_##t1, OP_MATH_TT_##t2): \\\n { \\\n mrb_float z = mrb_##t1(regs[a]) OP_MATH_OP_##op_name mrb_##t2(regs[a+1]); \\\n SET_FLOAT_VALUE(mrb, regs[a], z); \\\n } \\\n break\n#endif\n#define OP_MATH_OVERFLOW_INT() goto L_INT_OVERFLOW\n#define OP_MATH_CASE_STRING_add() \\\n case TYPES2(MRB_TT_STRING, MRB_TT_STRING): \\\n regs[a] = mrb_str_plus(mrb, regs[a], regs[a+1]); \\\n mrb_gc_arena_restore(mrb, ai); \\\n break\n#define OP_MATH_CASE_STRING_sub() (void)0\n#define OP_MATH_CASE_STRING_mul() (void)0\n#define OP_MATH_OP_add +\n#define OP_MATH_OP_sub -\n#define OP_MATH_OP_mul *\n#define OP_MATH_TT_integer MRB_TT_INTEGER\n#define OP_MATH_TT_float MRB_TT_FLOAT\n\n CASE(OP_ADD, B) {\n OP_MATH(add);\n }\n\n CASE(OP_SUB, B) {\n OP_MATH(sub);\n }\n\n CASE(OP_MUL, B) {\n OP_MATH(mul);\n }\n\n CASE(OP_DIV, B) {\n#ifndef MRB_NO_FLOAT\n mrb_float x, y, f;\n#endif\n\n /* need to check if op is overridden */\n switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\n case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\n {\n mrb_int x = mrb_integer(regs[a]);\n mrb_int y = mrb_integer(regs[a+1]);\n mrb_int div = mrb_div_int(mrb, x, y);\n SET_INT_VALUE(mrb, regs[a], div);\n }\n NEXT;\n#ifndef MRB_NO_FLOAT\n case TYPES2(MRB_TT_INTEGER,MRB_TT_FLOAT):\n x = (mrb_float)mrb_integer(regs[a]);\n y = mrb_float(regs[a+1]);\n break;\n case TYPES2(MRB_TT_FLOAT,MRB_TT_INTEGER):\n x = mrb_float(regs[a]);\n y = (mrb_float)mrb_integer(regs[a+1]);\n break;\n case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\n x = mrb_float(regs[a]);\n y = mrb_float(regs[a+1]);\n break;\n#endif\n default:\n mid = MRB_OPSYM(div);\n goto L_SEND_SYM;\n }\n\n#ifndef MRB_NO_FLOAT\n f = mrb_div_float(x, y);\n SET_FLOAT_VALUE(mrb, regs[a], f);\n#endif\n NEXT;\n }\n\n#define OP_MATHI(op_name) \\\n /* need to check if op is overridden */ \\\n switch (mrb_type(regs[a])) { \\\n OP_MATHI_CASE_INTEGER(op_name); \\\n OP_MATHI_CASE_FLOAT(op_name); \\\n default: \\\n SET_INT_VALUE(mrb,regs[a+1], b); \\\n mid = MRB_OPSYM(op_name); \\\n goto L_SEND_SYM; \\\n } \\\n NEXT;\n#define OP_MATHI_CASE_INTEGER(op_name) \\\n case MRB_TT_INTEGER: \\\n { \\\n mrb_int x = mrb_integer(regs[a]), y = (mrb_int)b, z; \\\n if (mrb_int_##op_name##_overflow(x, y, &z)) \\\n OP_MATH_OVERFLOW_INT(); \\\n else \\\n SET_INT_VALUE(mrb,regs[a], z); \\\n } \\\n break\n#ifdef MRB_NO_FLOAT\n#define OP_MATHI_CASE_FLOAT(op_name) (void)0\n#else\n#define OP_MATHI_CASE_FLOAT(op_name) \\\n case MRB_TT_FLOAT: \\\n { \\\n mrb_float z = mrb_float(regs[a]) OP_MATH_OP_##op_name b; \\\n SET_FLOAT_VALUE(mrb, regs[a], z); \\\n } \\\n break\n#endif\n\n CASE(OP_ADDI, BB) {\n OP_MATHI(add);\n }\n\n CASE(OP_SUBI, BB) {\n OP_MATHI(sub);\n }\n\n#define OP_CMP_BODY(op,v1,v2) (v1(regs[a]) op v2(regs[a+1]))\n\n#ifdef MRB_NO_FLOAT\n#define OP_CMP(op,sym) do {\\\n int result;\\\n /* need to check if - is overridden */\\\n switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\\\n case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\\\n result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\\\n break;\\\n default:\\\n mid = MRB_OPSYM(sym);\\\n goto L_SEND_SYM;\\\n }\\\n if (result) {\\\n SET_TRUE_VALUE(regs[a]);\\\n }\\\n else {\\\n SET_FALSE_VALUE(regs[a]);\\\n }\\\n} while(0)\n#else\n#define OP_CMP(op, sym) do {\\\n int result;\\\n /* need to check if - is overridden */\\\n switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\\\n case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\\\n result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\\\n break;\\\n case TYPES2(MRB_TT_INTEGER,MRB_TT_FLOAT):\\\n result = OP_CMP_BODY(op,mrb_fixnum,mrb_float);\\\n break;\\\n case TYPES2(MRB_TT_FLOAT,MRB_TT_INTEGER):\\\n result = OP_CMP_BODY(op,mrb_float,mrb_fixnum);\\\n break;\\\n case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\\\n result = OP_CMP_BODY(op,mrb_float,mrb_float);\\\n break;\\\n default:\\\n mid = MRB_OPSYM(sym);\\\n goto L_SEND_SYM;\\\n }\\\n if (result) {\\\n SET_TRUE_VALUE(regs[a]);\\\n }\\\n else {\\\n SET_FALSE_VALUE(regs[a]);\\\n }\\\n} while(0)\n#endif\n\n CASE(OP_EQ, B) {\n if (mrb_obj_eq(mrb, regs[a], regs[a+1])) {\n SET_TRUE_VALUE(regs[a]);\n }\n else {\n OP_CMP(==,eq);\n }\n NEXT;\n }\n\n CASE(OP_LT, B) {\n OP_CMP(<,lt);\n NEXT;\n }\n\n CASE(OP_LE, B) {\n OP_CMP(<=,le);\n NEXT;\n }\n\n CASE(OP_GT, B) {\n OP_CMP(>,gt);\n NEXT;\n }\n\n CASE(OP_GE, B) {\n OP_CMP(>=,ge);\n NEXT;\n }\n\n CASE(OP_ARRAY, BB) {\n regs[a] = mrb_ary_new_from_values(mrb, b, ®s[a]);\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n CASE(OP_ARRAY2, BBB) {\n regs[a] = mrb_ary_new_from_values(mrb, c, ®s[b]);\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_ARYCAT, B) {\n mrb_value splat = mrb_ary_splat(mrb, regs[a+1]);\n if (mrb_nil_p(regs[a])) {\n regs[a] = splat;\n }\n else {\n mrb_assert(mrb_array_p(regs[a]));\n mrb_ary_concat(mrb, regs[a], splat);\n }\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_ARYPUSH, BB) {\n mrb_assert(mrb_array_p(regs[a]));\n for (mrb_int i=0; i pre + post) {\n v = mrb_ary_new_from_values(mrb, len - pre - post, ARY_PTR(ary)+pre);\n regs[a++] = v;\n while (post--) {\n regs[a++] = ARY_PTR(ary)[len-post-1];\n }\n }\n else {\n v = mrb_ary_new_capa(mrb, 0);\n regs[a++] = v;\n for (idx=0; idx+pre> 2;\n if (pool[b].tt & IREP_TT_SFLAG) {\n sym = mrb_intern_static(mrb, pool[b].u.str, len);\n }\n else {\n sym = mrb_intern(mrb, pool[b].u.str, len);\n }\n regs[a] = mrb_symbol_value(sym);\n NEXT;\n }\n\n CASE(OP_STRING, BB) {\n mrb_int len;\n\n mrb_assert((pool[b].tt&IREP_TT_NFLAG)==0);\n len = pool[b].tt >> 2;\n if (pool[b].tt & IREP_TT_SFLAG) {\n regs[a] = mrb_str_new_static(mrb, pool[b].u.str, len);\n }\n else {\n regs[a] = mrb_str_new(mrb, pool[b].u.str, len);\n }\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_STRCAT, B) {\n mrb_assert(mrb_string_p(regs[a]));\n mrb_str_concat(mrb, regs[a], regs[a+1]);\n NEXT;\n }\n\n CASE(OP_HASH, BB) {\n mrb_value hash = mrb_hash_new_capa(mrb, b);\n int i;\n int lim = a+b*2;\n\n for (i=a; ireps[b];\n\n if (c & OP_L_CAPTURE) {\n p = mrb_closure_new(mrb, nirep);\n }\n else {\n p = mrb_proc_new(mrb, nirep);\n p->flags |= MRB_PROC_SCOPE;\n }\n if (c & OP_L_STRICT) p->flags |= MRB_PROC_STRICT;\n regs[a] = mrb_obj_value(p);\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n CASE(OP_BLOCK, BB) {\n c = OP_L_BLOCK;\n goto L_MAKE_LAMBDA;\n }\n CASE(OP_METHOD, BB) {\n c = OP_L_METHOD;\n goto L_MAKE_LAMBDA;\n }\n\n CASE(OP_RANGE_INC, B) {\n mrb_value v = mrb_range_new(mrb, regs[a], regs[a+1], FALSE);\n regs[a] = v;\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_RANGE_EXC, B) {\n mrb_value v = mrb_range_new(mrb, regs[a], regs[a+1], TRUE);\n regs[a] = v;\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_OCLASS, B) {\n regs[a] = mrb_obj_value(mrb->object_class);\n NEXT;\n }\n\n CASE(OP_CLASS, BB) {\n struct RClass *c = 0, *baseclass;\n mrb_value base, super;\n mrb_sym id = syms[b];\n\n base = regs[a];\n super = regs[a+1];\n if (mrb_nil_p(base)) {\n baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc);\n if (!baseclass) baseclass = mrb->object_class;\n base = mrb_obj_value(baseclass);\n }\n c = mrb_vm_define_class(mrb, base, super, id);\n regs[a] = mrb_obj_value(c);\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_MODULE, BB) {\n struct RClass *cls = 0, *baseclass;\n mrb_value base;\n mrb_sym id = syms[b];\n\n base = regs[a];\n if (mrb_nil_p(base)) {\n baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc);\n if (!baseclass) baseclass = mrb->object_class;\n base = mrb_obj_value(baseclass);\n }\n cls = mrb_vm_define_module(mrb, base, id);\n regs[a] = mrb_obj_value(cls);\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_EXEC, BB)\n {\n mrb_value recv = regs[a];\n struct RProc *p;\n const mrb_irep *nirep = irep->reps[b];\n\n /* prepare closure */\n p = mrb_proc_new(mrb, nirep);\n p->c = NULL;\n mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)proc);\n MRB_PROC_SET_TARGET_CLASS(p, mrb_class_ptr(recv));\n p->flags |= MRB_PROC_SCOPE;\n\n /* prepare call stack */\n cipush(mrb, a, 0, mrb_class_ptr(recv), p, 0, 0);\n\n irep = p->body.irep;\n pool = irep->pool;\n syms = irep->syms;\n mrb_stack_extend(mrb, irep->nregs);\n stack_clear(regs+1, irep->nregs-1);\n pc = irep->iseq;\n JUMP;\n }\n\n CASE(OP_DEF, BB) {\n struct RClass *target = mrb_class_ptr(regs[a]);\n struct RProc *p = mrb_proc_ptr(regs[a+1]);\n mrb_method_t m;\n mrb_sym mid = syms[b];\n\n MRB_METHOD_FROM_PROC(m, p);\n mrb_define_method_raw(mrb, target, mid, m);\n mrb_method_added(mrb, target, mid);\n mrb_gc_arena_restore(mrb, ai);\n regs[a] = mrb_symbol_value(mid);\n NEXT;\n }\n\n CASE(OP_SCLASS, B) {\n regs[a] = mrb_singleton_class(mrb, regs[a]);\n mrb_gc_arena_restore(mrb, ai);\n NEXT;\n }\n\n CASE(OP_TCLASS, B) {\n struct RClass *target = check_target_class(mrb);\n if (!target) goto L_RAISE;\n regs[a] = mrb_obj_value(target);\n NEXT;\n }\n\n CASE(OP_ALIAS, BB) {\n struct RClass *target = check_target_class(mrb);\n\n if (!target) goto L_RAISE;\n mrb_alias_method(mrb, target, syms[a], syms[b]);\n mrb_method_added(mrb, target, syms[a]);\n NEXT;\n }\n CASE(OP_UNDEF, B) {\n struct RClass *target = check_target_class(mrb);\n\n if (!target) goto L_RAISE;\n mrb_undef_method_id(mrb, target, syms[a]);\n NEXT;\n }\n\n CASE(OP_DEBUG, Z) {\n FETCH_BBB();\n#ifdef MRB_USE_DEBUG_HOOK\n mrb->debug_op_hook(mrb, irep, pc, regs);\n#else\n#ifndef MRB_NO_STDIO\n printf(\"OP_DEBUG %d %d %d\\n\", a, b, c);\n#else\n abort();\n#endif\n#endif\n NEXT;\n }\n\n CASE(OP_ERR, B) {\n size_t len = pool[a].tt >> 2;\n mrb_value exc;\n\n mrb_assert((pool[a].tt&IREP_TT_NFLAG)==0);\n exc = mrb_exc_new(mrb, E_LOCALJUMP_ERROR, pool[a].u.str, len);\n mrb_exc_set(mrb, exc);\n goto L_RAISE;\n }\n\n CASE(OP_EXT1, Z) {\n insn = READ_B();\n switch (insn) {\n#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _1(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;\n#include \"mruby/ops.h\"\n#undef OPCODE\n }\n pc--;\n NEXT;\n }\n CASE(OP_EXT2, Z) {\n insn = READ_B();\n switch (insn) {\n#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _2(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;\n#include \"mruby/ops.h\"\n#undef OPCODE\n }\n pc--;\n NEXT;\n }\n CASE(OP_EXT3, Z) {\n uint8_t insn = READ_B();\n switch (insn) {\n#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _3(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;\n#include \"mruby/ops.h\"\n#undef OPCODE\n }\n pc--;\n NEXT;\n }\n\n CASE(OP_STOP, Z) {\n /* stop VM */\n CHECKPOINT_RESTORE(RBREAK_TAG_STOP) {\n /* do nothing */\n }\n CHECKPOINT_MAIN(RBREAK_TAG_STOP) {\n UNWIND_ENSURE(mrb, mrb->c->ci, pc, RBREAK_TAG_STOP, proc, mrb_nil_value());\n }\n CHECKPOINT_END(RBREAK_TAG_STOP);\n L_STOP:\n mrb->jmp = prev_jmp;\n if (mrb->exc) {\n mrb_assert(mrb->exc->tt == MRB_TT_EXCEPTION);\n return mrb_obj_value(mrb->exc);\n }\n return regs[irep->nlocals];\n }\n }\n END_DISPATCH;\n#undef regs\n }\n MRB_CATCH(&c_jmp) {\n mrb_callinfo *ci = mrb->c->ci;\n while (ci > mrb->c->cibase && ci->cci == CINFO_DIRECT) {\n ci = cipop(mrb);\n }\n exc_catched = TRUE;\n pc = ci->pc;\n goto RETRY_TRY_BLOCK;\n }\n MRB_END_EXC(&c_jmp);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'vm.c: target class may be NULL.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static TEE_Result tee_svc_cipher_update_helper(unsigned long state,\n\t\t\tbool last_block, const void *src, size_t src_len,\n\t\t\tvoid *dst, uint64_t *dst_len)\n{\n\tTEE_Result res;\n\tstruct tee_cryp_state *cs;\n\tstruct tee_ta_session *sess;\n\tsize_t dlen = 0;\n\n\tres = tee_ta_get_current_session(&sess);\n\tif (res != TEE_SUCCESS)\n\t\treturn res;\n\n\tres = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);\n\tif (res != TEE_SUCCESS)\n\t\treturn res;\n\n\tres = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),\n\t\t\t\t\t TEE_MEMORY_ACCESS_READ |\n\t\t\t\t\t TEE_MEMORY_ACCESS_ANY_OWNER,\n\t\t\t\t\t (uaddr_t)src, src_len);\n\tif (res != TEE_SUCCESS)\n\t\treturn res;\n\n\tif (!dst_len) {\n\t\tdlen = 0;\n\t} else {\n\t\tres = get_user_u64_as_size_t(&dlen, dst_len);\n\t\tif (res != TEE_SUCCESS)\n\t\t\treturn res;\n\n\t\tres = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),\n\t\t\t\t\t\t TEE_MEMORY_ACCESS_READ |\n\t\t\t\t\t\t TEE_MEMORY_ACCESS_WRITE |\n\t\t\t\t\t\t TEE_MEMORY_ACCESS_ANY_OWNER,\n\t\t\t\t\t\t (uaddr_t)dst, dlen);\n\t\tif (res != TEE_SUCCESS)\n\t\t\treturn res;\n\t}\n\n\tif (dlen < src_len) {\n\t\tres = TEE_ERROR_SHORT_BUFFER;\n\t\tgoto out;\n\t}\n\n\tif (src_len > 0) {\n\t\t/* Permit src_len == 0 to finalize the operation */\n\t\tres = tee_do_cipher_update(cs->ctx, cs->algo, cs->mode,\n\t\t\t\t\t last_block, src, src_len, dst);\n\t}\n\n\tif (last_block && cs->ctx_finalize != NULL) {\n\t\tcs->ctx_finalize(cs->ctx, cs->algo);\n\t\tcs->ctx_finalize = NULL;\n\t}\n\nout:\n\tif ((res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) &&\n\t dst_len != NULL) {\n\t\tTEE_Result res2;\n\n\t\tres2 = put_user_u64(dst_len, src_len);\n\t\tif (res2 != TEE_SUCCESS)\n\t\t\tres = res2;\n\t}\n\n\treturn res;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-327'], 'message': 'cryp: prevent direct calls to update and final functions\n\nWith inconsistent or malformed data it has been possible to call\n\"update\" and \"final\" crypto functions directly. Using a fuzzer tool [1]\nwe have seen that this results in asserts, i.e., a crash that\npotentially could leak sensitive information.\n\nBy setting the state (initialized) in the crypto context (i.e., the\ntee_cryp_state) at the end of all syscall_*_init functions and then add\na check of the state at the beginning of all update and final functions,\n we prevent direct entrance to the \"update\" and \"final\" functions.\n\n[1] https://github.com/MartijnB/optee_fuzzer\n\nFixes: OP-TEE-2019-0021\n\nSigned-off-by: Joakim Bech \nReported-by: Martijn Bogaard \nAcked-by: Jerome Forissier \nReviewed-by: Jens Wiklander '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TEST_F(OAuth2Test, OAuthTestFullFlowPostWithParameters) {\n // First construct the initial request to the oauth filter with URI parameters.\n Http::TestRequestHeaderMapImpl first_request_headers{\n {Http::Headers::get().Path.get(), \"/test?name=admin&level=trace\"},\n {Http::Headers::get().Host.get(), \"traffic.example.com\"},\n {Http::Headers::get().Method.get(), Http::Headers::get().MethodValues.Post},\n {Http::Headers::get().Scheme.get(), \"https\"},\n };\n\n // This is the immediate response - a redirect to the auth cluster.\n Http::TestResponseHeaderMapImpl first_response_headers{\n {Http::Headers::get().Status.get(), \"302\"},\n {Http::Headers::get().Location.get(),\n \"https://auth.example.com/oauth/\"\n \"authorize/?client_id=\" +\n TEST_CLIENT_ID + \"&scope=\" + TEST_ENCODED_AUTH_SCOPES +\n \"&response_type=code&\"\n \"redirect_uri=https%3A%2F%2Ftraffic.example.com%2F\"\n \"_oauth&state=https%3A%2F%2Ftraffic.example.com%2Ftest%\"\n \"3Fname%3Dadmin%26level%3Dtrace\"\n \"&resource=oauth2-resource&resource=http%3A%2F%2Fexample.com\"\n \"&resource=https%3A%2F%2Fexample.com\"},\n };\n\n // Fail the validation to trigger the OAuth flow.\n EXPECT_CALL(*validator_, setParams(_, _));\n EXPECT_CALL(*validator_, isValid()).WillOnce(Return(false));\n\n // Check that the redirect includes the escaped parameter characters, '?', '&' and '='.\n EXPECT_CALL(decoder_callbacks_, encodeHeaders_(HeaderMapEqualRef(&first_response_headers), true));\n\n // This represents the beginning of the OAuth filter.\n EXPECT_EQ(Http::FilterHeadersStatus::StopIteration,\n filter_->decodeHeaders(first_request_headers, false));\n\n // This represents the callback request from the authorization server.\n Http::TestRequestHeaderMapImpl second_request_headers{\n {Http::Headers::get().Path.get(), \"/_oauth?code=123&state=https%3A%2F%2Ftraffic.example.com%\"\n \"2Ftest%3Fname%3Dadmin%26level%3Dtrace\"},\n {Http::Headers::get().Host.get(), \"traffic.example.com\"},\n {Http::Headers::get().Method.get(), Http::Headers::get().MethodValues.Get},\n {Http::Headers::get().Scheme.get(), \"https\"},\n };\n\n // Deliberately fail the HMAC validation check.\n EXPECT_CALL(*validator_, setParams(_, _));\n EXPECT_CALL(*validator_, isValid()).WillOnce(Return(false));\n\n EXPECT_CALL(*oauth_client_, asyncGetAccessToken(\"123\", TEST_CLIENT_ID, \"asdf_client_secret_fdsa\",\n \"https://traffic.example.com\" + TEST_CALLBACK));\n\n // Invoke the callback logic. As a side effect, state_ will be populated.\n EXPECT_EQ(Http::FilterHeadersStatus::StopAllIterationAndBuffer,\n filter_->decodeHeaders(second_request_headers, false));\n\n EXPECT_EQ(1, config_->stats().oauth_unauthorized_rq_.value());\n EXPECT_EQ(config_->clusterName(), \"auth.example.com\");\n\n // Expected response after the callback & validation is complete - verifying we kept the\n // state and method of the original request, including the query string parameters.\n Http::TestRequestHeaderMapImpl second_response_headers{\n {Http::Headers::get().Status.get(), \"302\"},\n {Http::Headers::get().SetCookie.get(),\n \"OauthHMAC=\"\n \"NWUzNzE5MWQwYTg0ZjA2NjIyMjVjMzk3MzY3MzMyZmE0NjZmMWI2MjI1NWFhNDhkYjQ4NDFlZmRiMTVmMTk0MQ==;\"\n \"version=1;path=/;Max-Age=;secure;HttpOnly\"},\n {Http::Headers::get().SetCookie.get(),\n \"OauthExpires=;version=1;path=/;Max-Age=;secure;HttpOnly\"},\n {Http::Headers::get().SetCookie.get(), \"BearerToken=;version=1;path=/;Max-Age=;secure\"},\n {Http::Headers::get().Location.get(),\n \"https://traffic.example.com/test?name=admin&level=trace\"},\n };\n\n EXPECT_CALL(decoder_callbacks_,\n encodeHeaders_(HeaderMapEqualRef(&second_response_headers), true));\n EXPECT_CALL(decoder_callbacks_, continueDecoding());\n\n filter_->finishFlow();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'oauth2: do not blindly accept requests with a token in the Authorization headera (781)\n\nThe logic was broken because it assumed an additional call would be\nperformed to the auth server, which isn't the case. Per the filter\ndocumentation, a request is only considered subsequently authenticated\nif there's valid cookie that was set after the access token was received\nfrom the auth server:\n\nhttps://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_filters/oauth2_filter\n\nMore info about how to validate an access token (which we don't do, per\nabove):\n\nhttps://www.oauth.com/oauth2-servers/token-introspection-endpoint/\nhttps://datatracker.ietf.org/doc/html/rfc7662\n\nAlso fix the fact that ee shouldn't be calling continueDecoding() after\ndecoder_callbacks_->encodeHeaders().\n\nSigned-off-by: Raul Gutierrez Segales \nSigned-off-by: Matt Klein \nSigned-off-by: Pradeep Rao '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int pop_sync_mailbox(struct Context *ctx, int *index_hint)\n{\n int i, j, ret = 0;\n char buf[LONG_STRING];\n struct PopData *pop_data = (struct PopData *) ctx->data;\n struct Progress progress;\n#ifdef USE_HCACHE\n header_cache_t *hc = NULL;\n#endif\n\n pop_data->check_time = 0;\n\n while (true)\n {\n if (pop_reconnect(ctx) < 0)\n return -1;\n\n mutt_progress_init(&progress, _(\"Marking messages deleted...\"),\n MUTT_PROGRESS_MSG, WriteInc, ctx->deleted);\n\n#ifdef USE_HCACHE\n hc = pop_hcache_open(pop_data, ctx->path);\n#endif\n\n for (i = 0, j = 0, ret = 0; ret == 0 && i < ctx->msgcount; i++)\n {\n if (ctx->hdrs[i]->deleted && ctx->hdrs[i]->refno != -1)\n {\n j++;\n if (!ctx->quiet)\n mutt_progress_update(&progress, j, -1);\n snprintf(buf, sizeof(buf), \"DELE %d\\r\\n\", ctx->hdrs[i]->refno);\n ret = pop_query(pop_data, buf, sizeof(buf));\n if (ret == 0)\n {\n mutt_bcache_del(pop_data->bcache, ctx->hdrs[i]->data);\n#ifdef USE_HCACHE\n mutt_hcache_delete(hc, ctx->hdrs[i]->data, strlen(ctx->hdrs[i]->data));\n#endif\n }\n }\n\n#ifdef USE_HCACHE\n if (ctx->hdrs[i]->changed)\n {\n mutt_hcache_store(hc, ctx->hdrs[i]->data, strlen(ctx->hdrs[i]->data),\n ctx->hdrs[i], 0);\n }\n#endif\n }\n\n#ifdef USE_HCACHE\n mutt_hcache_close(hc);\n#endif\n\n if (ret == 0)\n {\n mutt_str_strfcpy(buf, \"QUIT\\r\\n\", sizeof(buf));\n ret = pop_query(pop_data, buf, sizeof(buf));\n }\n\n if (ret == 0)\n {\n pop_data->clear_cache = true;\n pop_clear_cache(pop_data);\n pop_data->status = POP_DISCONNECTED;\n return 0;\n }\n\n if (ret == -2)\n {\n mutt_error(\"%s\", pop_data->err_msg);\n return -1;\n }\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-241', 'CWE-119', 'CWE-22'], 'message': 'sanitise cache paths\n\nCo-authored-by: JerikoOne '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static zend_bool add_post_var(zval *arr, post_var_data_t *var, zend_bool eof TSRMLS_DC)\n{\n\tchar *ksep, *vsep, *val;\n\tsize_t klen, vlen;\n\t/* FIXME: string-size_t */\n\tunsigned int new_vlen;\n\n\tif (var->ptr >= var->end) {\n\t\treturn 0;\n\t}\n\n\tvsep = memchr(var->ptr, '&', var->end - var->ptr);\n\tif (!vsep) {\n\t\tif (!eof) {\n\t\t\treturn 0;\n\t\t} else {\n\t\t\tvsep = var->end;\n\t\t}\n\t}\n\n\tksep = memchr(var->ptr, '=', vsep - var->ptr);\n\tif (ksep) {\n\t\t*ksep = '\\0';\n\t\t/* \"foo=bar&\" or \"foo=&\" */\n\t\tklen = ksep - var->ptr;\n\t\tvlen = vsep - ++ksep;\n\t} else {\n\t\tksep = \"\";\n\t\t/* \"foo&\" */\n\t\tklen = vsep - var->ptr;\n\t\tvlen = 0;\n\t}\n\n\tphp_url_decode(var->ptr, klen);\n\n\tval = estrndup(ksep, vlen);\n\tif (vlen) {\n\t\tvlen = php_url_decode(val, vlen);\n\t}\n\n\tif (sapi_module.input_filter(PARSE_POST, var->ptr, &val, vlen, &new_vlen TSRMLS_CC)) {\n\t\tphp_register_variable_safe(var->ptr, val, new_vlen, arr TSRMLS_CC);\n\t}\n\tefree(val);\n\n\tvar->ptr = vsep + (vsep != var->end);\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Fix bug #73807'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int nfs_lookup_reply(uchar *pkt, unsigned len)\n{\n\tstruct rpc_t rpc_pkt;\n\n\tdebug(\"%s\\n\", __func__);\n\n\tmemcpy(&rpc_pkt.u.data[0], pkt, len);\n\n\tif (ntohl(rpc_pkt.u.reply.id) > rpc_id)\n\t\treturn -NFS_RPC_ERR;\n\telse if (ntohl(rpc_pkt.u.reply.id) < rpc_id)\n\t\treturn -NFS_RPC_DROP;\n\n\tif (rpc_pkt.u.reply.rstatus ||\n\t rpc_pkt.u.reply.verifier ||\n\t rpc_pkt.u.reply.astatus ||\n\t rpc_pkt.u.reply.data[0]) {\n\t\tswitch (ntohl(rpc_pkt.u.reply.astatus)) {\n\t\tcase NFS_RPC_SUCCESS: /* Not an error */\n\t\t\tbreak;\n\t\tcase NFS_RPC_PROG_MISMATCH:\n\t\t\t/* Remote can't support NFS version */\n\t\t\tswitch (ntohl(rpc_pkt.u.reply.data[0])) {\n\t\t\t/* Minimal supported NFS version */\n\t\t\tcase 3:\n\t\t\t\tdebug(\"*** Warning: NFS version not supported: Requested: V%d, accepted: min V%d - max V%d\\n\",\n\t\t\t\t (supported_nfs_versions & NFSV2_FLAG) ?\n\t\t\t\t\t\t2 : 3,\n\t\t\t\t ntohl(rpc_pkt.u.reply.data[0]),\n\t\t\t\t ntohl(rpc_pkt.u.reply.data[1]));\n\t\t\t\tdebug(\"Will retry with NFSv3\\n\");\n\t\t\t\t/* Clear NFSV2_FLAG from supported versions */\n\t\t\t\tsupported_nfs_versions &= ~NFSV2_FLAG;\n\t\t\t\treturn -NFS_RPC_PROG_MISMATCH;\n\t\t\tcase 4:\n\t\t\tdefault:\n\t\t\t\tputs(\"*** ERROR: NFS version not supported\");\n\t\t\t\tdebug(\": Requested: V%d, accepted: min V%d - max V%d\\n\",\n\t\t\t\t (supported_nfs_versions & NFSV2_FLAG) ?\n\t\t\t\t\t\t2 : 3,\n\t\t\t\t ntohl(rpc_pkt.u.reply.data[0]),\n\t\t\t\t ntohl(rpc_pkt.u.reply.data[1]));\n\t\t\t\tputs(\"\\n\");\n\t\t\t}\n\t\t\tbreak;\n\t\tcase NFS_RPC_PROG_UNAVAIL:\n\t\tcase NFS_RPC_PROC_UNAVAIL:\n\t\tcase NFS_RPC_GARBAGE_ARGS:\n\t\tcase NFS_RPC_SYSTEM_ERR:\n\t\tdefault: /* Unknown error on 'accept state' flag */\n\t\t\tdebug(\"*** ERROR: accept state error (%d)\\n\",\n\t\t\t ntohl(rpc_pkt.u.reply.astatus));\n\t\t\tbreak;\n\t\t}\n\t\treturn -1;\n\t}\n\n\tif (supported_nfs_versions & NFSV2_FLAG) {\n\t\tmemcpy(filefh, rpc_pkt.u.reply.data + 1, NFS_FHSIZE);\n\t} else { /* NFSV3_FLAG */\n\t\tfilefh3_length = ntohl(rpc_pkt.u.reply.data[1]);\n\t\tif (filefh3_length > NFS3_FHSIZE)\n\t\t\tfilefh3_length = NFS3_FHSIZE;\n\t\tmemcpy(filefh, rpc_pkt.u.reply.data + 2, filefh3_length);\n\t}\n\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120', 'CWE-703'], 'message': 'CVE-2019-14196: nfs: fix unbounded memcpy with a failed length check at nfs_lookup_reply\n\nThis patch adds a check to rpc_pkt.u.reply.data at nfs_lookup_reply.\n\nSigned-off-by: Cheng Liu \nReported-by: Ferm\u00edn Serna \nAcked-by: Joe Hershberger '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TfLiteStatus EvalSimple(TfLiteContext* context, TfLiteNode* node,\n const TfLiteTensor* lookup, const TfLiteTensor* value,\n TfLiteTensor* output) {\n const int row_size = SizeOfDimension(value, 0);\n const int row_bytes = value->bytes / row_size;\n\n char* output_raw = GetTensorData(output);\n const char* value_raw = GetTensorData(value);\n const int32_t* lookup_data = GetTensorData(lookup);\n for (int i = 0; i < SizeOfDimension(lookup, 0); i++) {\n int idx = lookup_data[i];\n if (idx >= row_size || idx < 0) {\n context->ReportError(context,\n \"Embedding Lookup: index out of bounds. \"\n \"Got %d, and bounds are [0, %d]\",\n idx, row_size - 1);\n return kTfLiteError;\n } else {\n std::memcpy(output_raw + i * row_bytes, value_raw + idx * row_bytes,\n row_bytes);\n }\n }\n\n return kTfLiteOk;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-369'], 'message': 'Prevent division by 0\n\nPiperOrigin-RevId: 370966645\nChange-Id: I831bfd96c7eb77b02d7ebb744335f59f6e5728cb'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: unsigned int get_random_int(void)\n{\n\tstruct keydata *keyptr;\n\t__u32 *hash = get_cpu_var(get_random_int_hash);\n\tint ret;\n\n\tkeyptr = get_keyptr();\n\thash[0] += current->pid + jiffies + get_cycles();\n\n\tret = half_md4_transform(hash, keyptr->secret);\n\tput_cpu_var(get_random_int_hash);\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'net: Compute protocol sequence numbers and fragment IDs using MD5.\n\nComputers have become a lot faster since we compromised on the\npartial MD4 hash which we use currently for performance reasons.\n\nMD5 is a much safer choice, and is inline with both RFC1948 and\nother ISS generators (OpenBSD, Solaris, etc.)\n\nFurthermore, only having 24-bits of the sequence number be truly\nunpredictable is a very serious limitation. So the periodic\nregeneration and 8-bit counter have been removed. We compute and\nuse a full 32-bit sequence number.\n\nFor ipv6, DCCP was found to use a 32-bit truncated initial sequence\nnumber (it needs 43-bits) and that is fixed here as well.\n\nReported-by: Dan Kaminsky \nTested-by: Willy Tarreau \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool DependencyOptimizer::SafeToRemoveIdentity(const NodeDef& node) const {\n if (!IsIdentity(node) && !IsIdentityN(node)) {\n return true;\n }\n\n if (nodes_to_preserve_.find(node.name()) != nodes_to_preserve_.end()) {\n return false;\n }\n if (!fetch_nodes_known_) {\n // The output values of this node may be needed.\n return false;\n }\n const NodeDef* input = node_map_->GetNode(NodeName(node.input(0)));\n CHECK(input != nullptr) << \"node = \" << node.name()\n << \" input = \" << node.input(0);\n // Don't remove Identity nodes corresponding to Variable reads or following\n // Recv.\n if (IsVariable(*input) || IsRecv(*input)) {\n return false;\n }\n for (const auto& consumer : node_map_->GetOutputs(node.name())) {\n if (node.input_size() > 1 && (IsRetval(*consumer) || IsMerge(*consumer))) {\n return false;\n }\n if (IsSwitch(*input)) {\n for (const string& consumer_input : consumer->input()) {\n if (consumer_input == AsControlDependency(node.name())) {\n return false;\n }\n }\n }\n }\n return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'Handle a special grappler case resulting in crash.\n\nIt might happen that a malformed input could be used to trick Grappler into trying to optimize a node with no inputs. This, in turn, would produce a null pointer dereference and a segfault.\n\nPiperOrigin-RevId: 369242852\nChange-Id: I2e5cbe7aec243d34a6d60220ac8ac9b16f136f6b'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: parse_elements(netdissect_options *ndo,\n struct mgmt_body_t *pbody, const u_char *p, int offset,\n u_int length)\n{\n\tu_int elementlen;\n\tstruct ssid_t ssid;\n\tstruct challenge_t challenge;\n\tstruct rates_t rates;\n\tstruct ds_t ds;\n\tstruct cf_t cf;\n\tstruct tim_t tim;\n\n\t/*\n\t * We haven't seen any elements yet.\n\t */\n\tpbody->challenge_present = 0;\n\tpbody->ssid_present = 0;\n\tpbody->rates_present = 0;\n\tpbody->ds_present = 0;\n\tpbody->cf_present = 0;\n\tpbody->tim_present = 0;\n\n\twhile (length != 0) {\n\t\t/* Make sure we at least have the element ID and length. */\n\t\tif (!ND_TTEST2(*(p + offset), 2))\n\t\t\treturn 0;\n\t\tif (length < 2)\n\t\t\treturn 0;\n\t\telementlen = *(p + offset + 1);\n\n\t\t/* Make sure we have the entire element. */\n\t\tif (!ND_TTEST2(*(p + offset + 2), elementlen))\n\t\t\treturn 0;\n\t\tif (length < elementlen + 2)\n\t\t\treturn 0;\n\n\t\tswitch (*(p + offset)) {\n\t\tcase E_SSID:\n\t\t\tmemcpy(&ssid, p + offset, 2);\n\t\t\toffset += 2;\n\t\t\tlength -= 2;\n\t\t\tif (ssid.length != 0) {\n\t\t\t\tif (ssid.length > sizeof(ssid.ssid) - 1)\n\t\t\t\t\treturn 0;\n\t\t\t\tif (!ND_TTEST2(*(p + offset), ssid.length))\n\t\t\t\t\treturn 0;\n\t\t\t\tif (length < ssid.length)\n\t\t\t\t\treturn 0;\n\t\t\t\tmemcpy(&ssid.ssid, p + offset, ssid.length);\n\t\t\t\toffset += ssid.length;\n\t\t\t\tlength -= ssid.length;\n\t\t\t}\n\t\t\tssid.ssid[ssid.length] = '\\0';\n\t\t\t/*\n\t\t\t * Present and not truncated.\n\t\t\t *\n\t\t\t * If we haven't already seen an SSID IE,\n\t\t\t * copy this one, otherwise ignore this one,\n\t\t\t * so we later report the first one we saw.\n\t\t\t */\n\t\t\tif (!pbody->ssid_present) {\n\t\t\t\tpbody->ssid = ssid;\n\t\t\t\tpbody->ssid_present = 1;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase E_CHALLENGE:\n\t\t\tmemcpy(&challenge, p + offset, 2);\n\t\t\toffset += 2;\n\t\t\tlength -= 2;\n\t\t\tif (challenge.length != 0) {\n\t\t\t\tif (challenge.length >\n\t\t\t\t sizeof(challenge.text) - 1)\n\t\t\t\t\treturn 0;\n\t\t\t\tif (!ND_TTEST2(*(p + offset), challenge.length))\n\t\t\t\t\treturn 0;\n\t\t\t\tif (length < challenge.length)\n\t\t\t\t\treturn 0;\n\t\t\t\tmemcpy(&challenge.text, p + offset,\n\t\t\t\t challenge.length);\n\t\t\t\toffset += challenge.length;\n\t\t\t\tlength -= challenge.length;\n\t\t\t}\n\t\t\tchallenge.text[challenge.length] = '\\0';\n\t\t\t/*\n\t\t\t * Present and not truncated.\n\t\t\t *\n\t\t\t * If we haven't already seen a challenge IE,\n\t\t\t * copy this one, otherwise ignore this one,\n\t\t\t * so we later report the first one we saw.\n\t\t\t */\n\t\t\tif (!pbody->challenge_present) {\n\t\t\t\tpbody->challenge = challenge;\n\t\t\t\tpbody->challenge_present = 1;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase E_RATES:\n\t\t\tmemcpy(&rates, p + offset, 2);\n\t\t\toffset += 2;\n\t\t\tlength -= 2;\n\t\t\tif (rates.length != 0) {\n\t\t\t\tif (rates.length > sizeof rates.rate)\n\t\t\t\t\treturn 0;\n\t\t\t\tif (!ND_TTEST2(*(p + offset), rates.length))\n\t\t\t\t\treturn 0;\n\t\t\t\tif (length < rates.length)\n\t\t\t\t\treturn 0;\n\t\t\t\tmemcpy(&rates.rate, p + offset, rates.length);\n\t\t\t\toffset += rates.length;\n\t\t\t\tlength -= rates.length;\n\t\t\t}\n\t\t\t/*\n\t\t\t * Present and not truncated.\n\t\t\t *\n\t\t\t * If we haven't already seen a rates IE,\n\t\t\t * copy this one if it's not zero-length,\n\t\t\t * otherwise ignore this one, so we later\n\t\t\t * report the first one we saw.\n\t\t\t *\n\t\t\t * We ignore zero-length rates IEs as some\n\t\t\t * devices seem to put a zero-length rates\n\t\t\t * IE, followed by an SSID IE, followed by\n\t\t\t * a non-zero-length rates IE into frames,\n\t\t\t * even though IEEE Std 802.11-2007 doesn't\n\t\t\t * seem to indicate that a zero-length rates\n\t\t\t * IE is valid.\n\t\t\t */\n\t\t\tif (!pbody->rates_present && rates.length != 0) {\n\t\t\t\tpbody->rates = rates;\n\t\t\t\tpbody->rates_present = 1;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase E_DS:\n\t\t\tmemcpy(&ds, p + offset, 2);\n\t\t\toffset += 2;\n\t\t\tlength -= 2;\n\t\t\tif (ds.length != 1) {\n\t\t\t\toffset += ds.length;\n\t\t\t\tlength -= ds.length;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tds.channel = *(p + offset);\n\t\t\toffset += 1;\n\t\t\tlength -= 1;\n\t\t\t/*\n\t\t\t * Present and not truncated.\n\t\t\t *\n\t\t\t * If we haven't already seen a DS IE,\n\t\t\t * copy this one, otherwise ignore this one,\n\t\t\t * so we later report the first one we saw.\n\t\t\t */\n\t\t\tif (!pbody->ds_present) {\n\t\t\t\tpbody->ds = ds;\n\t\t\t\tpbody->ds_present = 1;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase E_CF:\n\t\t\tmemcpy(&cf, p + offset, 2);\n\t\t\toffset += 2;\n\t\t\tlength -= 2;\n\t\t\tif (cf.length != 6) {\n\t\t\t\toffset += cf.length;\n\t\t\t\tlength -= cf.length;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tmemcpy(&cf.count, p + offset, 6);\n\t\t\toffset += 6;\n\t\t\tlength -= 6;\n\t\t\t/*\n\t\t\t * Present and not truncated.\n\t\t\t *\n\t\t\t * If we haven't already seen a CF IE,\n\t\t\t * copy this one, otherwise ignore this one,\n\t\t\t * so we later report the first one we saw.\n\t\t\t */\n\t\t\tif (!pbody->cf_present) {\n\t\t\t\tpbody->cf = cf;\n\t\t\t\tpbody->cf_present = 1;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase E_TIM:\n\t\t\tmemcpy(&tim, p + offset, 2);\n\t\t\toffset += 2;\n\t\t\tlength -= 2;\n\t\t\tif (tim.length <= 3) {\n\t\t\t\toffset += tim.length;\n\t\t\t\tlength -= tim.length;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (tim.length - 3 > (int)sizeof tim.bitmap)\n\t\t\t\treturn 0;\n\t\t\tmemcpy(&tim.count, p + offset, 3);\n\t\t\toffset += 3;\n\t\t\tlength -= 3;\n\n\t\t\tmemcpy(tim.bitmap, p + (tim.length - 3),\n\t\t\t (tim.length - 3));\n\t\t\toffset += tim.length - 3;\n\t\t\tlength -= tim.length - 3;\n\t\t\t/*\n\t\t\t * Present and not truncated.\n\t\t\t *\n\t\t\t * If we haven't already seen a TIM IE,\n\t\t\t * copy this one, otherwise ignore this one,\n\t\t\t * so we later report the first one we saw.\n\t\t\t */\n\t\t\tif (!pbody->tim_present) {\n\t\t\t\tpbody->tim = tim;\n\t\t\t\tpbody->tim_present = 1;\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n#if 0\n\t\t\tND_PRINT((ndo, \"(1) unhandled element_id (%d) \",\n\t\t\t *(p + offset)));\n#endif\n\t\t\toffset += 2 + elementlen;\n\t\t\tlength -= 2 + elementlen;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t/* No problems found. */\n\treturn 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'CVE-2017-12987/IEEE 802.11: Fix processing of TIM IE.\n\nThe arguments to memcpy() were completely wrong.\n\nThis fixes a buffer over-read discovered by Kamil Frankowicz.\n\nAdd a test using the capture file supplied by Brian 'geeknik' Carpenter.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: chdlc_print(netdissect_options *ndo, register const u_char *p, u_int length)\n{\n\tu_int proto;\n\n\tproto = EXTRACT_16BITS(&p[2]);\n\tif (ndo->ndo_eflag) {\n ND_PRINT((ndo, \"%s, ethertype %s (0x%04x), length %u: \",\n tok2str(chdlc_cast_values, \"0x%02x\", p[0]),\n tok2str(ethertype_values, \"Unknown\", proto),\n proto,\n length));\n\t}\n\n\tlength -= CHDLC_HDRLEN;\n\tp += CHDLC_HDRLEN;\n\n\tswitch (proto) {\n\tcase ETHERTYPE_IP:\n\t\tip_print(ndo, p, length);\n\t\tbreak;\n\tcase ETHERTYPE_IPV6:\n\t\tip6_print(ndo, p, length);\n\t\tbreak;\n\tcase CHDLC_TYPE_SLARP:\n\t\tchdlc_slarp_print(ndo, p, length);\n\t\tbreak;\n#if 0\n\tcase CHDLC_TYPE_CDP:\n\t\tchdlc_cdp_print(p, length);\n\t\tbreak;\n#endif\n case ETHERTYPE_MPLS:\n case ETHERTYPE_MPLS_MULTI:\n mpls_print(ndo, p, length);\n\t\tbreak;\n case ETHERTYPE_ISO:\n /* is the fudge byte set ? lets verify by spotting ISO headers */\n if (*(p+1) == 0x81 ||\n *(p+1) == 0x82 ||\n *(p+1) == 0x83)\n isoclns_print(ndo, p + 1, length - 1, ndo->ndo_snapend - p - 1);\n else\n isoclns_print(ndo, p, length, ndo->ndo_snapend - p);\n break;\n\tdefault:\n if (!ndo->ndo_eflag)\n ND_PRINT((ndo, \"unknown CHDLC protocol (0x%04x)\", proto));\n break;\n\t}\n\n\treturn (CHDLC_HDRLEN);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'CVE-2017-13687/CHDLC: Improve bounds and length checks.\n\nPrevent a possible buffer overread in chdlc_print() and replace the\ncustom check in chdlc_if_print() with a standard check in chdlc_print()\nso that the latter certainly does not over-read even when reached via\njuniper_chdlc_print(). Add length checks.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: vtp_print (netdissect_options *ndo,\n const u_char *pptr, u_int length)\n{\n int type, len, tlv_len, tlv_value, mgmtd_len;\n const u_char *tptr;\n const struct vtp_vlan_ *vtp_vlan;\n\n if (length < VTP_HEADER_LEN)\n goto trunc;\n\n tptr = pptr;\n\n ND_TCHECK2(*tptr, VTP_HEADER_LEN);\n\n type = *(tptr+1);\n ND_PRINT((ndo, \"VTPv%u, Message %s (0x%02x), length %u\",\n\t *tptr,\n\t tok2str(vtp_message_type_values,\"Unknown message type\", type),\n\t type,\n\t length));\n\n /* In non-verbose mode, just print version and message type */\n if (ndo->ndo_vflag < 1) {\n return;\n }\n\n /* verbose mode print all fields */\n ND_PRINT((ndo, \"\\n\\tDomain name: \"));\n mgmtd_len = *(tptr + 3);\n if (mgmtd_len < 1 || mgmtd_len > 32) {\n\tND_PRINT((ndo, \" [invalid MgmtD Len %d]\", mgmtd_len));\n\treturn;\n }\n fn_printzp(ndo, tptr + 4, mgmtd_len, NULL);\n ND_PRINT((ndo, \", %s: %u\",\n\t tok2str(vtp_header_values, \"Unknown\", type),\n\t *(tptr+2)));\n\n tptr += VTP_HEADER_LEN;\n\n switch (type) {\n\n case VTP_SUMMARY_ADV:\n\n\t/*\n\t * SUMMARY ADVERTISEMENT\n\t *\n\t * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n\t * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t * | Version | Code | Followers | MgmtD Len |\n\t * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t * | Management Domain Name (zero-padded to 32 bytes) |\n\t * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t * | Configuration revision number |\n\t * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t * | Updater Identity IP address |\n\t * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t * | Update Timestamp (12 bytes) |\n\t * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t * | MD5 digest (16 bytes) |\n\t * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t *\n\t */\n\n\tND_TCHECK2(*tptr, 8);\n\tND_PRINT((ndo, \"\\n\\t Config Rev %x, Updater %s\",\n\t EXTRACT_32BITS(tptr),\n\t ipaddr_string(ndo, tptr+4)));\n\ttptr += 8;\n\tND_TCHECK2(*tptr, VTP_UPDATE_TIMESTAMP_LEN);\n\tND_PRINT((ndo, \", Timestamp 0x%08x 0x%08x 0x%08x\",\n\t EXTRACT_32BITS(tptr),\n\t EXTRACT_32BITS(tptr + 4),\n\t EXTRACT_32BITS(tptr + 8)));\n\ttptr += VTP_UPDATE_TIMESTAMP_LEN;\n\tND_TCHECK2(*tptr, VTP_MD5_DIGEST_LEN);\n\tND_PRINT((ndo, \", MD5 digest: %08x%08x%08x%08x\",\n\t EXTRACT_32BITS(tptr),\n\t EXTRACT_32BITS(tptr + 4),\n\t EXTRACT_32BITS(tptr + 8),\n\t EXTRACT_32BITS(tptr + 12)));\n\ttptr += VTP_MD5_DIGEST_LEN;\n\tbreak;\n\n case VTP_SUBSET_ADV:\n\n\t/*\n\t * SUBSET ADVERTISEMENT\n\t *\n\t * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n\t * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t * | Version | Code | Seq number | MgmtD Len |\n\t * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t * | Management Domain Name (zero-padded to 32 bytes) |\n\t * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t * | Configuration revision number |\n\t * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t * | VLAN info field 1 |\n\t * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t * | ................ |\n\t * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t * | VLAN info field N |\n\t * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t *\n\t */\n\n\tND_TCHECK_32BITS(tptr);\n\tND_PRINT((ndo, \", Config Rev %x\", EXTRACT_32BITS(tptr)));\n\n\t/*\n\t * VLAN INFORMATION\n\t * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n\t * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t * | V info len | Status | VLAN type | VLAN name len |\n\t * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t * | ISL vlan id | MTU size |\n\t * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t * | 802.10 index (SAID) |\n\t * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t * | VLAN name |\n\t * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t *\n\t */\n\n\ttptr += 4;\n\twhile (tptr < (pptr+length)) {\n\n\t ND_TCHECK_8BITS(tptr);\n\t len = *tptr;\n\t if (len == 0)\n\t\tbreak;\n\n\t ND_TCHECK2(*tptr, len);\n\n\t vtp_vlan = (const struct vtp_vlan_*)tptr;\n\t ND_TCHECK(*vtp_vlan);\n\t ND_PRINT((ndo, \"\\n\\tVLAN info status %s, type %s, VLAN-id %u, MTU %u, SAID 0x%08x, Name \",\n\t\t tok2str(vtp_vlan_status,\"Unknown\",vtp_vlan->status),\n\t\t tok2str(vtp_vlan_type_values,\"Unknown\",vtp_vlan->type),\n\t\t EXTRACT_16BITS(&vtp_vlan->vlanid),\n\t\t EXTRACT_16BITS(&vtp_vlan->mtu),\n\t\t EXTRACT_32BITS(&vtp_vlan->index)));\n\t fn_printzp(ndo, tptr + VTP_VLAN_INFO_OFFSET, vtp_vlan->name_len, NULL);\n\n /*\n * Vlan names are aligned to 32-bit boundaries.\n */\n len -= VTP_VLAN_INFO_OFFSET + 4*((vtp_vlan->name_len + 3)/4);\n tptr += VTP_VLAN_INFO_OFFSET + 4*((vtp_vlan->name_len + 3)/4);\n\n /* TLV information follows */\n\n while (len > 0) {\n\n /*\n * Cisco specs says 2 bytes for type + 2 bytes for length, take only 1\n * See: http://www.cisco.com/univercd/cc/td/doc/product/lan/trsrb/frames.htm\n */\n type = *tptr;\n tlv_len = *(tptr+1);\n\n ND_PRINT((ndo, \"\\n\\t\\t%s (0x%04x) TLV\",\n tok2str(vtp_vlan_tlv_values, \"Unknown\", type),\n type));\n\n /*\n * infinite loop check\n */\n if (type == 0 || tlv_len == 0) {\n return;\n }\n\n ND_TCHECK2(*tptr, tlv_len * 2 +2);\n\n tlv_value = EXTRACT_16BITS(tptr+2);\n\n switch (type) {\n case VTP_VLAN_STE_HOP_COUNT:\n ND_PRINT((ndo, \", %u\", tlv_value));\n break;\n\n case VTP_VLAN_PRUNING:\n ND_PRINT((ndo, \", %s (%u)\",\n tlv_value == 1 ? \"Enabled\" : \"Disabled\",\n tlv_value));\n break;\n\n case VTP_VLAN_STP_TYPE:\n ND_PRINT((ndo, \", %s (%u)\",\n tok2str(vtp_stp_type_values, \"Unknown\", tlv_value),\n tlv_value));\n break;\n\n case VTP_VLAN_BRIDGE_TYPE:\n ND_PRINT((ndo, \", %s (%u)\",\n tlv_value == 1 ? \"SRB\" : \"SRT\",\n tlv_value));\n break;\n\n case VTP_VLAN_BACKUP_CRF_MODE:\n ND_PRINT((ndo, \", %s (%u)\",\n tlv_value == 1 ? \"Backup\" : \"Not backup\",\n tlv_value));\n break;\n\n /*\n * FIXME those are the defined TLVs that lack a decoder\n * you are welcome to contribute code ;-)\n */\n\n case VTP_VLAN_SOURCE_ROUTING_RING_NUMBER:\n case VTP_VLAN_SOURCE_ROUTING_BRIDGE_NUMBER:\n case VTP_VLAN_PARENT_VLAN:\n case VTP_VLAN_TRANS_BRIDGED_VLAN:\n case VTP_VLAN_ARP_HOP_COUNT:\n default:\n\t\t print_unknown_data(ndo, tptr, \"\\n\\t\\t \", 2 + tlv_len*2);\n break;\n }\n len -= 2 + tlv_len*2;\n tptr += 2 + tlv_len*2;\n }\n\t}\n\tbreak;\n\n case VTP_ADV_REQUEST:\n\n\t/*\n\t * ADVERTISEMENT REQUEST\n\t *\n\t * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n\t * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t * | Version | Code | Reserved | MgmtD Len |\n\t * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t * | Management Domain Name (zero-padded to 32 bytes) |\n\t * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t * | Start value |\n\t * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t *\n\t */\n\n\tND_TCHECK2(*tptr, 4);\n\tND_PRINT((ndo, \"\\n\\tStart value: %u\", EXTRACT_32BITS(tptr)));\n\tbreak;\n\n case VTP_JOIN_MESSAGE:\n\n\t/* FIXME - Could not find message format */\n\tbreak;\n\n default:\n\tbreak;\n }\n\n return;\n\n trunc:\n ND_PRINT((ndo, \"[|vtp]\"));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13033/VTP: Add more bound and length checks.\n\nThis fixes a buffer over-read discovered by Bhargava Shastry.\n\nAdd a test using the capture file supplied by the reporter(s), modified\nso the capture file won't be rejected as an invalid capture.\n\nUpdate another VTP test's .out file for this change.\n\nDon't treate a TLV type or length of 0 as invalid; a type of 0 should\njust be reported as illegal if that type isn't used, and the length is\nthe length of the *value*, not the length of the entire TLV, so if it's\nzero there won't be an infinite loop. (It's still not *legal*, as the\nvalues of all the TLVs we handle are 1 16-bit word long; we added a\ncheck for that.)\n\nUpdate some comments while we're at it, to give a new URL for one Cisco\npage and a non-Cisco URL for another former Cisco page (Cisco's UniverCD\npages don't seem to be available any more, and Cisco's robots.txt file\ndidn't allow the Wayback Machine to archive it).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void tipc_mon_rcv(struct net *net, void *data, u16 dlen, u32 addr,\n\t\t struct tipc_mon_state *state, int bearer_id)\n{\n\tstruct tipc_monitor *mon = tipc_monitor(net, bearer_id);\n\tstruct tipc_mon_domain *arrv_dom = data;\n\tstruct tipc_mon_domain dom_bef;\n\tstruct tipc_mon_domain *dom;\n\tstruct tipc_peer *peer;\n\tu16 new_member_cnt = mon_le16_to_cpu(arrv_dom->member_cnt);\n\tint new_dlen = dom_rec_len(arrv_dom, new_member_cnt);\n\tu16 new_gen = mon_le16_to_cpu(arrv_dom->gen);\n\tu16 acked_gen = mon_le16_to_cpu(arrv_dom->ack_gen);\n\tu16 arrv_dlen = mon_le16_to_cpu(arrv_dom->len);\n\tbool probing = state->probing;\n\tint i, applied_bef;\n\n\tstate->probing = false;\n\n\t/* Sanity check received domain record */\n\tif (dlen < dom_rec_len(arrv_dom, 0))\n\t\treturn;\n\tif (dlen != dom_rec_len(arrv_dom, new_member_cnt))\n\t\treturn;\n\tif (dlen < new_dlen || arrv_dlen != new_dlen)\n\t\treturn;\n\n\t/* Synch generation numbers with peer if link just came up */\n\tif (!state->synched) {\n\t\tstate->peer_gen = new_gen - 1;\n\t\tstate->acked_gen = acked_gen;\n\t\tstate->synched = true;\n\t}\n\n\tif (more(acked_gen, state->acked_gen))\n\t\tstate->acked_gen = acked_gen;\n\n\t/* Drop duplicate unless we are waiting for a probe response */\n\tif (!more(new_gen, state->peer_gen) && !probing)\n\t\treturn;\n\n\twrite_lock_bh(&mon->lock);\n\tpeer = get_peer(mon, addr);\n\tif (!peer || !peer->is_up)\n\t\tgoto exit;\n\n\t/* Peer is confirmed, stop any ongoing probing */\n\tpeer->down_cnt = 0;\n\n\t/* Task is done for duplicate record */\n\tif (!more(new_gen, state->peer_gen))\n\t\tgoto exit;\n\n\tstate->peer_gen = new_gen;\n\n\t/* Cache current domain record for later use */\n\tdom_bef.member_cnt = 0;\n\tdom = peer->domain;\n\tif (dom)\n\t\tmemcpy(&dom_bef, dom, dom->len);\n\n\t/* Transform and store received domain record */\n\tif (!dom || (dom->len < new_dlen)) {\n\t\tkfree(dom);\n\t\tdom = kmalloc(new_dlen, GFP_ATOMIC);\n\t\tpeer->domain = dom;\n\t\tif (!dom)\n\t\t\tgoto exit;\n\t}\n\tdom->len = new_dlen;\n\tdom->gen = new_gen;\n\tdom->member_cnt = new_member_cnt;\n\tdom->up_map = mon_le64_to_cpu(arrv_dom->up_map);\n\tfor (i = 0; i < new_member_cnt; i++)\n\t\tdom->members[i] = mon_le32_to_cpu(arrv_dom->members[i]);\n\n\t/* Update peers affected by this domain record */\n\tapplied_bef = peer->applied;\n\tmon_apply_domain(mon, peer);\n\tmon_identify_lost_members(peer, &dom_bef, applied_bef);\n\tmon_assign_roles(mon, peer_head(peer));\nexit:\n\twrite_unlock_bh(&mon->lock);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'tipc: improve size validations for received domain records\n\nThe function tipc_mon_rcv() allows a node to receive and process\ndomain_record structs from peer nodes to track their views of the\nnetwork topology.\n\nThis patch verifies that the number of members in a received domain\nrecord does not exceed the limit defined by MAX_MON_DOMAIN, something\nthat may otherwise lead to a stack overflow.\n\ntipc_mon_rcv() is called from the function tipc_link_proto_rcv(), where\nwe are reading a 32 bit message data length field into a uint16. To\navert any risk of bit overflow, we add an extra sanity check for this in\nthat function. We cannot see that happen with the current code, but\nfuture designers being unaware of this risk, may introduce it by\nallowing delivery of very large (> 64k) sk buffers from the bearer\nlayer. This potential problem was identified by Eric Dumazet.\n\nThis fixes CVE-2022-0435\n\nReported-by: Samuel Page \nReported-by: Eric Dumazet \nFixes: 35c55c9877f8 (\"tipc: add neighbor monitoring framework\")\nSigned-off-by: Jon Maloy \nReviewed-by: Xin Long \nReviewed-by: Samuel Page \nReviewed-by: Eric Dumazet \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: pci_get_cfgdata8(struct pci_vdev *dev, int offset)\n{\n\tassert(offset <= PCI_REGMAX);\n\treturn (*(uint8_t *)(dev->cfgdata + offset));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617', 'CWE-703'], 'message': 'dm: pci: clean up assert() in pci core\n\nTracked-On: #3252\nSigned-off-by: Shuo A Liu \nReviewed-by: Yonghua Huang '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: pci_emul_alloc_resource(uint64_t *baseptr, uint64_t limit, uint64_t size,\n\t\t\tuint64_t *addr)\n{\n\tuint64_t base;\n\n\tassert((size & (size - 1)) == 0);\t/* must be a power of 2 */\n\n\tbase = roundup2(*baseptr, size);\n\n\tif (base + size <= limit) {\n\t\t*addr = base;\n\t\t*baseptr = base + size;\n\t\treturn 0;\n\t} else\n\t\treturn -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617', 'CWE-703'], 'message': 'dm: pci: clean up assert() in pci core\n\nTracked-On: #3252\nSigned-off-by: Shuo A Liu \nReviewed-by: Yonghua Huang '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: pci_emul_capwrite(struct pci_vdev *dev, int offset, int bytes, uint32_t val)\n{\n\tint capid;\n\tuint8_t capoff, nextoff;\n\n\t/* Do not allow un-aligned writes */\n\tif ((offset & (bytes - 1)) != 0)\n\t\treturn;\n\n\t/* Find the capability that we want to update */\n\tcapoff = CAP_START_OFFSET;\n\twhile (1) {\n\t\tnextoff = pci_get_cfgdata8(dev, capoff + 1);\n\t\tif (nextoff == 0)\n\t\t\tbreak;\n\t\tif (offset >= capoff && offset < nextoff)\n\t\t\tbreak;\n\n\t\tcapoff = nextoff;\n\t}\n\tassert(offset >= capoff);\n\n\t/*\n\t * Capability ID and Next Capability Pointer are readonly.\n\t * However, some o/s's do 4-byte writes that include these.\n\t * For this case, trim the write back to 2 bytes and adjust\n\t * the data.\n\t */\n\tif (offset == capoff || offset == capoff + 1) {\n\t\tif (offset == capoff && bytes == 4) {\n\t\t\tbytes = 2;\n\t\t\toffset += 2;\n\t\t\tval >>= 16;\n\t\t} else\n\t\t\treturn;\n\t}\n\n\tcapid = pci_get_cfgdata8(dev, capoff);\n\tswitch (capid) {\n\tcase PCIY_MSI:\n\t\tmsicap_cfgwrite(dev, capoff, offset, bytes, val);\n\t\tbreak;\n\tcase PCIY_MSIX:\n\t\tmsixcap_cfgwrite(dev, capoff, offset, bytes, val);\n\t\tbreak;\n\tcase PCIY_EXPRESS:\n\t\tpciecap_cfgwrite(dev, capoff, offset, bytes, val);\n\t\tbreak;\n\tdefault:\n\t\tCFGWRITE(dev, offset, val, bytes);\n\t\tbreak;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-617', 'CWE-703'], 'message': 'dm: pci: clean up assert() in pci core\n\nTracked-On: #3252\nSigned-off-by: Shuo A Liu \nReviewed-by: Yonghua Huang '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static uint8_t last_seg(uint8_t len)\n{\n\tif (len <= START_PAYLOAD_MAX) {\n\t\treturn 0;\n\t}\n\n\tlen -= START_PAYLOAD_MAX;\n\n\treturn 1 + (len / CONT_PAYLOAD_MAX);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'Bluetooth: Mesh: Check SegN when receiving Transaction Start PDU\n\nWhen receiving Transaction Start PDU, assure that number of segments\nneeded to send a Provisioning PDU with TotalLength size is equal to SegN\nvalue provided in the Transaction Start PDU.\n\nSigned-off-by: Pavel Vasilyev \n(cherry picked from commit a63c51567991ded3939bbda4f82bcb8c44228331)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TPM2B_IV_Marshal(TPM2B_IV *source, BYTE **buffer, INT32 *size)\n{\n UINT16 written = 0;\n written += TPM2B_Marshal(&source->b, buffer, size);\n return written;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Add maxSize parameter to TPM2B_Marshal for sanity checks\n\nAdd maxSize parameter to TPM2B_Marshal and assert on it checking\nthe size of the data intended to be marshaled versus the maximum\nbuffer size.\n\nSigned-off-by: Stefan Berger '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TPM2B_DATA_Marshal(TPM2B_DATA *source, BYTE **buffer, INT32 *size)\n{\nUINT16 written = 0;\nwritten += TPM2B_Marshal(&source->b, buffer, size);\nreturn written;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Add maxSize parameter to TPM2B_Marshal for sanity checks\n\nAdd maxSize parameter to TPM2B_Marshal and assert on it checking\nthe size of the data intended to be marshaled versus the maximum\nbuffer size.\n\nSigned-off-by: Stefan Berger '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int store_icy(URLContext *h, int size)\n{\n HTTPContext *s = h->priv_data;\n /* until next metadata packet */\n int remaining = s->icy_metaint - s->icy_data_read;\n\n if (remaining < 0)\n return AVERROR_INVALIDDATA;\n\n if (!remaining) {\n /* The metadata packet is variable sized. It has a 1 byte header\n * which sets the length of the packet (divided by 16). If it's 0,\n * the metadata doesn't change. After the packet, icy_metaint bytes\n * of normal data follows. */\n uint8_t ch;\n int len = http_read_stream_all(h, &ch, 1);\n if (len < 0)\n return len;\n if (ch > 0) {\n char data[255 * 16 + 1];\n int ret;\n len = ch * 16;\n ret = http_read_stream_all(h, data, len);\n if (ret < 0)\n return ret;\n data[len + 1] = 0;\n if ((ret = av_opt_set(s, \"icy_metadata_packet\", data, 0)) < 0)\n return ret;\n update_metadata(s, data);\n }\n s->icy_data_read = 0;\n remaining = s->icy_metaint;\n }\n\n return FFMIN(size, remaining);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'http: make length/offset-related variables unsigned.\n\nFixes #5992, reported and found by Paul Cher .'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void chase_port(struct edgeport_port *port, unsigned long timeout,\n\t\t\t\t\t\t\t\tint flush)\n{\n\tint baud_rate;\n\tstruct tty_struct *tty = tty_port_tty_get(&port->port->port);\n\tstruct usb_serial *serial = port->port->serial;\n\twait_queue_t wait;\n\tunsigned long flags;\n\n\tif (!timeout)\n\t\ttimeout = (HZ * EDGE_CLOSING_WAIT)/100;\n\n\t/* wait for data to drain from the buffer */\n\tspin_lock_irqsave(&port->ep_lock, flags);\n\tinit_waitqueue_entry(&wait, current);\n\tadd_wait_queue(&tty->write_wait, &wait);\n\tfor (;;) {\n\t\tset_current_state(TASK_INTERRUPTIBLE);\n\t\tif (kfifo_len(&port->write_fifo) == 0\n\t\t|| timeout == 0 || signal_pending(current)\n\t\t|| serial->disconnected)\n\t\t\t/* disconnect */\n\t\t\tbreak;\n\t\tspin_unlock_irqrestore(&port->ep_lock, flags);\n\t\ttimeout = schedule_timeout(timeout);\n\t\tspin_lock_irqsave(&port->ep_lock, flags);\n\t}\n\tset_current_state(TASK_RUNNING);\n\tremove_wait_queue(&tty->write_wait, &wait);\n\tif (flush)\n\t\tkfifo_reset_out(&port->write_fifo);\n\tspin_unlock_irqrestore(&port->ep_lock, flags);\n\ttty_kref_put(tty);\n\n\t/* wait for data to drain from the device */\n\ttimeout += jiffies;\n\twhile ((long)(jiffies - timeout) < 0 && !signal_pending(current)\n\t\t\t\t\t\t&& !serial->disconnected) {\n\t\t/* not disconnected */\n\t\tif (!tx_active(port))\n\t\t\tbreak;\n\t\tmsleep(10);\n\t}\n\n\t/* disconnected */\n\tif (serial->disconnected)\n\t\treturn;\n\n\t/* wait one more character time, based on baud rate */\n\t/* (tx_active doesn't seem to wait for the last byte) */\n\tbaud_rate = port->baud_rate;\n\tif (baud_rate == 0)\n\t\tbaud_rate = 50;\n\tmsleep(max(1, DIV_ROUND_UP(10000, baud_rate)));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'USB: io_ti: Fix NULL dereference in chase_port()\n\nThe tty is NULL when the port is hanging up.\nchase_port() needs to check for this.\n\nThis patch is intended for stable series.\nThe behavior was observed and tested in Linux 3.2 and 3.7.1.\n\nJohan Hovold submitted a more elaborate patch for the mainline kernel.\n\n[ 56.277883] usb 1-1: edge_bulk_in_callback - nonzero read bulk status received: -84\n[ 56.278811] usb 1-1: USB disconnect, device number 3\n[ 56.278856] usb 1-1: edge_bulk_in_callback - stopping read!\n[ 56.279562] BUG: unable to handle kernel NULL pointer dereference at 00000000000001c8\n[ 56.280536] IP: [] _raw_spin_lock_irqsave+0x19/0x35\n[ 56.281212] PGD 1dc1b067 PUD 1e0f7067 PMD 0\n[ 56.282085] Oops: 0002 [#1] SMP\n[ 56.282744] Modules linked in:\n[ 56.283512] CPU 1\n[ 56.283512] Pid: 25, comm: khubd Not tainted 3.7.1 #1 innotek GmbH VirtualBox/VirtualBox\n[ 56.283512] RIP: 0010:[] [] _raw_spin_lock_irqsave+0x19/0x35\n[ 56.283512] RSP: 0018:ffff88001fa99ab0 EFLAGS: 00010046\n[ 56.283512] RAX: 0000000000000046 RBX: 00000000000001c8 RCX: 0000000000640064\n[ 56.283512] RDX: 0000000000010000 RSI: ffff88001fa99b20 RDI: 00000000000001c8\n[ 56.283512] RBP: ffff88001fa99b20 R08: 0000000000000000 R09: 0000000000000000\n[ 56.283512] R10: 0000000000000000 R11: ffffffff812fcb4c R12: ffff88001ddf53c0\n[ 56.283512] R13: 0000000000000000 R14: 00000000000001c8 R15: ffff88001e19b9f4\n[ 56.283512] FS: 0000000000000000(0000) GS:ffff88001fd00000(0000) knlGS:0000000000000000\n[ 56.283512] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b\n[ 56.283512] CR2: 00000000000001c8 CR3: 000000001dc51000 CR4: 00000000000006e0\n[ 56.283512] DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000\n[ 56.283512] DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400\n[ 56.283512] Process khubd (pid: 25, threadinfo ffff88001fa98000, task ffff88001fa94f80)\n[ 56.283512] Stack:\n[ 56.283512] 0000000000000046 00000000000001c8 ffffffff810578ec ffffffff812fcb4c\n[ 56.283512] ffff88001e19b980 0000000000002710 ffffffff812ffe81 0000000000000001\n[ 56.283512] ffff88001fa94f80 0000000000000202 ffffffff00000001 0000000000000296\n[ 56.283512] Call Trace:\n[ 56.283512] [] ? add_wait_queue+0x12/0x3c\n[ 56.283512] [] ? usb_serial_port_work+0x28/0x28\n[ 56.283512] [] ? chase_port+0x84/0x2d6\n[ 56.283512] [] ? try_to_wake_up+0x199/0x199\n[ 56.283512] [] ? tty_ldisc_hangup+0x222/0x298\n[ 56.283512] [] ? edge_close+0x64/0x129\n[ 56.283512] [] ? __wake_up+0x35/0x46\n[ 56.283512] [] ? should_resched+0x5/0x23\n[ 56.283512] [] ? tty_port_shutdown+0x39/0x44\n[ 56.283512] [] ? usb_serial_port_work+0x28/0x28\n[ 56.283512] [] ? __tty_hangup+0x307/0x351\n[ 56.283512] [] ? usb_hcd_flush_endpoint+0xde/0xed\n[ 56.283512] [] ? _raw_spin_lock_irqsave+0x14/0x35\n[ 56.283512] [] ? usb_serial_disconnect+0x57/0xc2\n[ 56.283512] [] ? usb_unbind_interface+0x5c/0x131\n[ 56.283512] [] ? __device_release_driver+0x7f/0xd5\n[ 56.283512] [] ? device_release_driver+0x1a/0x25\n[ 56.283512] [] ? bus_remove_device+0xd2/0xe7\n[ 56.283512] [] ? device_del+0x119/0x167\n[ 56.283512] [] ? usb_disable_device+0x6a/0x180\n[ 56.283512] [] ? usb_disconnect+0x81/0xe6\n[ 56.283512] [] ? hub_thread+0x577/0xe82\n[ 56.283512] [] ? __schedule+0x490/0x4be\n[ 56.283512] [] ? abort_exclusive_wait+0x79/0x79\n[ 56.283512] [] ? usb_remote_wakeup+0x2f/0x2f\n[ 56.283512] [] ? usb_remote_wakeup+0x2f/0x2f\n[ 56.283512] [] ? kthread+0x81/0x89\n[ 56.283512] [] ? __kthread_parkme+0x5c/0x5c\n[ 56.283512] [] ? ret_from_fork+0x7c/0xb0\n[ 56.283512] [] ? __kthread_parkme+0x5c/0x5c\n[ 56.283512] Code: 8b 7c 24 08 e8 17 0b c3 ff 48 8b 04 24 48 83 c4 10 c3 53 48 89 fb 41 50 e8 e0 0a c3 ff 48 89 04 24 e8 e7 0a c3 ff ba 00 00 01 00\n 0f c1 13 48 8b 04 24 89 d1 c1 ea 10 66 39 d1 74 07 f3 90 66\n[ 56.283512] RIP [] _raw_spin_lock_irqsave+0x19/0x35\n[ 56.283512] RSP \n[ 56.283512] CR2: 00000000000001c8\n[ 56.283512] ---[ end trace 49714df27e1679ce ]---\n\nSigned-off-by: Wolfgang Frisch \nCc: Johan Hovold \nCc: stable \nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int ssl3_get_record(SSL *s)\n\t{\n\tint ssl_major,ssl_minor,al;\n\tint enc_err,n,i,ret= -1;\n\tSSL3_RECORD *rr;\n\tSSL_SESSION *sess;\n\tunsigned char *p;\n\tunsigned char md[EVP_MAX_MD_SIZE];\n\tshort version;\n\tunsigned int mac_size;\n\tint clear=0;\n\tsize_t extra;\n\tint decryption_failed_or_bad_record_mac = 0;\n\tunsigned char *mac = NULL;\n\n\trr= &(s->s3->rrec);\n\tsess=s->session;\n\n\tif (s->options & SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER)\n\t\textra=SSL3_RT_MAX_EXTRA;\n\telse\n\t\textra=0;\n\tif (extra != s->s3->rbuf.len - SSL3_RT_MAX_PACKET_SIZE)\n\t\t{\n\t\t/* actually likely an application error: SLS_OP_MICROSOFT_BIG_SSLV3_BUFFER\n\t\t * set after ssl3_setup_buffers() was done */\n\t\tSSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);\n\t\treturn -1;\n\t\t}\n\nagain:\n\t/* check if we have the header */\n\tif (\t(s->rstate != SSL_ST_READ_BODY) ||\n\t\t(s->packet_length < SSL3_RT_HEADER_LENGTH)) \n\t\t{\n\t\tn=ssl3_read_n(s, SSL3_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);\n\t\tif (n <= 0) return(n); /* error or non-blocking */\n\t\ts->rstate=SSL_ST_READ_BODY;\n\n\t\tp=s->packet;\n\n\t\t/* Pull apart the header into the SSL3_RECORD */\n\t\trr->type= *(p++);\n\t\tssl_major= *(p++);\n\t\tssl_minor= *(p++);\n\t\tversion=(ssl_major<<8)|ssl_minor;\n\t\tn2s(p,rr->length);\n\n\t\t/* Lets check version */\n\t\tif (!s->first_packet)\n\t\t\t{\n\t\t\tif (version != s->version)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_WRONG_VERSION_NUMBER);\n if ((s->version & 0xFF00) == (version & 0xFF00))\n \t/* Send back error using their minor version number :-) */\n\t\t\t\t\ts->version = (unsigned short)version;\n\t\t\t\tal=SSL_AD_PROTOCOL_VERSION;\n\t\t\t\tgoto f_err;\n\t\t\t\t}\n\t\t\t}\n\n\t\tif ((version>>8) != SSL3_VERSION_MAJOR)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_WRONG_VERSION_NUMBER);\n\t\t\tgoto err;\n\t\t\t}\n\n\t\tif (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH+extra)\n\t\t\t{\n\t\t\tal=SSL_AD_RECORD_OVERFLOW;\n\t\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_PACKET_LENGTH_TOO_LONG);\n\t\t\tgoto f_err;\n\t\t\t}\n\n\t\t/* now s->rstate == SSL_ST_READ_BODY */\n\t\t}\n\n\t/* s->rstate == SSL_ST_READ_BODY, get and decode the data */\n\n\tif (rr->length > s->packet_length-SSL3_RT_HEADER_LENGTH)\n\t\t{\n\t\t/* now s->packet_length == SSL3_RT_HEADER_LENGTH */\n\t\ti=rr->length;\n\t\tn=ssl3_read_n(s,i,i,1);\n\t\tif (n <= 0) return(n); /* error or non-blocking io */\n\t\t/* now n == rr->length,\n\t\t * and s->packet_length == SSL3_RT_HEADER_LENGTH + rr->length */\n\t\t}\n\n\ts->rstate=SSL_ST_READ_HEADER; /* set state for later operations */\n\n\t/* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,\n\t * and we have that many bytes in s->packet\n\t */\n\trr->input= &(s->packet[SSL3_RT_HEADER_LENGTH]);\n\n\t/* ok, we can now read from 's->packet' data into 'rr'\n\t * rr->input points at rr->length bytes, which\n\t * need to be copied into rr->data by either\n\t * the decryption or by the decompression\n\t * When the data is 'copied' into the rr->data buffer,\n\t * rr->input will be pointed at the new buffer */ \n\n\t/* We now have - encrypted [ MAC [ compressed [ plain ] ] ]\n\t * rr->length bytes of encrypted compressed stuff. */\n\n\t/* check is not needed I believe */\n\tif (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH+extra)\n\t\t{\n\t\tal=SSL_AD_RECORD_OVERFLOW;\n\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_ENCRYPTED_LENGTH_TOO_LONG);\n\t\tgoto f_err;\n\t\t}\n\n\t/* decrypt in place in 'rr->input' */\n\trr->data=rr->input;\n\n\tenc_err = s->method->ssl3_enc->enc(s,0);\n\tif (enc_err <= 0)\n\t\t{\n\t\tif (enc_err == 0)\n\t\t\t/* SSLerr() and ssl3_send_alert() have been called */\n\t\t\tgoto err;\n\n\t\t/* Otherwise enc_err == -1, which indicates bad padding\n\t\t * (rec->length has not been changed in this case).\n\t\t * To minimize information leaked via timing, we will perform\n\t\t * the MAC computation anyway. */\n\t\tdecryption_failed_or_bad_record_mac = 1;\n\t\t}\n\n#ifdef TLS_DEBUG\nprintf(\"dec %d\\n\",rr->length);\n{ unsigned int z; for (z=0; zlength; z++) printf(\"%02X%c\",rr->data[z],((z+1)%16)?' ':'\\n'); }\nprintf(\"\\n\");\n#endif\n\n\t/* r->length is now the compressed data plus mac */\n\tif (\t(sess == NULL) ||\n\t\t(s->enc_read_ctx == NULL) ||\n\t\t(s->read_hash == NULL))\n\t\tclear=1;\n\n\tif (!clear)\n\t\t{\n\t\tmac_size=EVP_MD_size(s->read_hash);\n\n\t\tif (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+extra+mac_size)\n\t\t\t{\n#if 0 /* OK only for stream ciphers (then rr->length is visible from ciphertext anyway) */\n\t\t\tal=SSL_AD_RECORD_OVERFLOW;\n\t\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_PRE_MAC_LENGTH_TOO_LONG);\n\t\t\tgoto f_err;\n#else\n\t\t\tdecryption_failed_or_bad_record_mac = 1;\n#endif\t\t\t\n\t\t\t}\n\t\t/* check the MAC for rr->input (it's in mac_size bytes at the tail) */\n\t\tif (rr->length >= mac_size)\n\t\t\t{\n\t\t\trr->length -= mac_size;\n\t\t\tmac = &rr->data[rr->length];\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\t/* record (minus padding) is too short to contain a MAC */\n#if 0 /* OK only for stream ciphers */\n\t\t\tal=SSL_AD_DECODE_ERROR;\n\t\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_LENGTH_TOO_SHORT);\n\t\t\tgoto f_err;\n#else\n\t\t\tdecryption_failed_or_bad_record_mac = 1;\n\t\t\trr->length = 0;\n#endif\n\t\t\t}\n\t\ti=s->method->ssl3_enc->mac(s,md,0);\n\t\tif (i < 0 || mac == NULL || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)\n\t\t\t{\n\t\t\tdecryption_failed_or_bad_record_mac = 1;\n\t\t\t}\n\t\t}\n\n\tif (decryption_failed_or_bad_record_mac)\n\t\t{\n\t\t/* A separate 'decryption_failed' alert was introduced with TLS 1.0,\n\t\t * SSL 3.0 only has 'bad_record_mac'. But unless a decryption\n\t\t * failure is directly visible from the ciphertext anyway,\n\t\t * we should not reveal which kind of error occured -- this\n\t\t * might become visible to an attacker (e.g. via a logfile) */\n\t\tal=SSL_AD_BAD_RECORD_MAC;\n\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);\n\t\tgoto f_err;\n\t\t}\n\n\t/* r->length is now just compressed */\n\tif (s->expand != NULL)\n\t\t{\n\t\tif (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+extra)\n\t\t\t{\n\t\t\tal=SSL_AD_RECORD_OVERFLOW;\n\t\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\tif (!ssl3_do_uncompress(s))\n\t\t\t{\n\t\t\tal=SSL_AD_DECOMPRESSION_FAILURE;\n\t\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_BAD_DECOMPRESSION);\n\t\t\tgoto f_err;\n\t\t\t}\n\t\t}\n\n\tif (rr->length > SSL3_RT_MAX_PLAIN_LENGTH+extra)\n\t\t{\n\t\tal=SSL_AD_RECORD_OVERFLOW;\n\t\tSSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_DATA_LENGTH_TOO_LONG);\n\t\tgoto f_err;\n\t\t}\n\n\trr->off=0;\n\t/* So at this point the following is true\n\t * ssl->s3->rrec.type \tis the type of record\n\t * ssl->s3->rrec.length\t== number of bytes in record\n\t * ssl->s3->rrec.off\t== offset to first valid byte\n\t * ssl->s3->rrec.data\t== where to take bytes from, increment\n\t *\t\t\t after use :-).\n\t */\n\n\t/* we have pulled in a full packet so zero things */\n\ts->packet_length=0;\n\n\t/* just read a 0 length packet */\n\tif (rr->length == 0) goto again;\n\n\treturn(1);\n\nf_err:\n\tssl3_send_alert(s,SSL3_AL_FATAL,al);\nerr:\n\treturn(ret);\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Make CBC decoding constant time.\n\nThis patch makes the decoding of SSLv3 and TLS CBC records constant\ntime. Without this, a timing side-channel can be used to build a padding\noracle and mount Vaudenay's attack.\n\nThis patch also disables the stitched AESNI+SHA mode pending a similar\nfix to that code.\n\nIn order to be easy to backport, this change is implemented in ssl/,\nrather than as a generic AEAD mode. In the future this should be changed\naround so that HMAC isn't in ssl/, but crypto/ as FIPS expects.\n(cherry picked from commit e130841bccfc0bb9da254dc84e23bc6a1c78a64e)\n\nConflicts:\n\tcrypto/evp/c_allc.c\n\tssl/ssl_algs.c\n\tssl/ssl_locl.h\n\tssl/t1_enc.c\n(cherry picked from commit 3622239826698a0e534dcf0473204c724bb9b4b4)\n\nConflicts:\n\tssl/d1_enc.c\n\tssl/s3_enc.c\n\tssl/s3_pkt.c\n\tssl/ssl3.h\n\tssl/ssl_algs.c\n\tssl/t1_enc.c'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int dtls1_enc(SSL *s, int send)\n\t{\n\tSSL3_RECORD *rec;\n\tEVP_CIPHER_CTX *ds;\n\tunsigned long l;\n\tint bs,i,j,k,mac_size=0;\n\tconst EVP_CIPHER *enc;\n\n\tif (send)\n\t\t{\n\t\tif (EVP_MD_CTX_md(s->write_hash))\n\t\t\t{\n\t\t\tmac_size=EVP_MD_CTX_size(s->write_hash);\n\t\t\tif (mac_size < 0)\n\t\t\t\treturn -1;\n\t\t\t}\n\t\tds=s->enc_write_ctx;\n\t\trec= &(s->s3->wrec);\n\t\tif (s->enc_write_ctx == NULL)\n\t\t\tenc=NULL;\n\t\telse\n\t\t\t{\n\t\t\tenc=EVP_CIPHER_CTX_cipher(s->enc_write_ctx);\n\t\t\tif ( rec->data != rec->input)\n\t\t\t\t/* we can't write into the input stream */\n\t\t\t\tfprintf(stderr, \"%s:%d: rec->data != rec->input\\n\",\n\t\t\t\t\t__FILE__, __LINE__);\n\t\t\telse if ( EVP_CIPHER_block_size(ds->cipher) > 1)\n\t\t\t\t{\n\t\t\t\tif (RAND_bytes(rec->input, EVP_CIPHER_block_size(ds->cipher)) <= 0)\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\telse\n\t\t{\n\t\tif (EVP_MD_CTX_md(s->read_hash))\n\t\t\t{\n\t\t\tmac_size=EVP_MD_CTX_size(s->read_hash);\n\t\t\tif (mac_size < 0)\n\t\t\t\treturn -1;\n\t\t\t}\n\t\tds=s->enc_read_ctx;\n\t\trec= &(s->s3->rrec);\n\t\tif (s->enc_read_ctx == NULL)\n\t\t\tenc=NULL;\n\t\telse\n\t\t\tenc=EVP_CIPHER_CTX_cipher(s->enc_read_ctx);\n\t\t}\n\n#ifdef KSSL_DEBUG\n\tprintf(\"dtls1_enc(%d)\\n\", send);\n#endif /* KSSL_DEBUG */\n\n\tif ((s->session == NULL) || (ds == NULL) ||\n\t\t(enc == NULL))\n\t\t{\n\t\tmemmove(rec->data,rec->input,rec->length);\n\t\trec->input=rec->data;\n\t\t}\n\telse\n\t\t{\n\t\tl=rec->length;\n\t\tbs=EVP_CIPHER_block_size(ds->cipher);\n\n\t\tif ((bs != 1) && send)\n\t\t\t{\n\t\t\ti=bs-((int)l%bs);\n\n\t\t\t/* Add weird padding of upto 256 bytes */\n\n\t\t\t/* we need to add 'i' padding bytes of value j */\n\t\t\tj=i-1;\n\t\t\tif (s->options & SSL_OP_TLS_BLOCK_PADDING_BUG)\n\t\t\t\t{\n\t\t\t\tif (s->s3->flags & TLS1_FLAGS_TLS_PADDING_BUG)\n\t\t\t\t\tj++;\n\t\t\t\t}\n\t\t\tfor (k=(int)l; k<(int)(l+i); k++)\n\t\t\t\trec->input[k]=j;\n\t\t\tl+=i;\n\t\t\trec->length+=i;\n\t\t\t}\n\n#ifdef KSSL_DEBUG\n\t\t{\n unsigned long ui;\n\t\tprintf(\"EVP_Cipher(ds=%p,rec->data=%p,rec->input=%p,l=%ld) ==>\\n\",\n (void *)ds,rec->data,rec->input,l);\n\t\tprintf(\"\\tEVP_CIPHER_CTX: %d buf_len, %d key_len [%ld %ld], %d iv_len\\n\",\n ds->buf_len, ds->cipher->key_len,\n (unsigned long)DES_KEY_SZ,\n\t\t\t(unsigned long)DES_SCHEDULE_SZ,\n ds->cipher->iv_len);\n\t\tprintf(\"\\t\\tIV: \");\n\t\tfor (i=0; icipher->iv_len; i++) printf(\"%02X\", ds->iv[i]);\n\t\tprintf(\"\\n\");\n\t\tprintf(\"\\trec->input=\");\n\t\tfor (ui=0; uiinput[ui]);\n\t\tprintf(\"\\n\");\n\t\t}\n#endif\t/* KSSL_DEBUG */\n\n\t\tif (!send)\n\t\t\t{\n\t\t\tif (l == 0 || l%bs != 0)\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\n\t\tEVP_Cipher(ds,rec->data,rec->input,l);\n\n#ifdef KSSL_DEBUG\n\t\t{\n unsigned long ki;\n printf(\"\\trec->data=\");\n\t\tfor (ki=0; kidata[ki]); printf(\"\\n\");\n }\n#endif\t/* KSSL_DEBUG */\n\n\t\trec->orig_len = rec->length;\n\t\tif ((bs != 1) && !send)\n\t\t\treturn tls1_cbc_remove_padding(s, rec, bs, mac_size);\n\t\t}\n\treturn(1);\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Fixups.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ssl3_enc(SSL *s, int send)\n\t{\n\tSSL3_RECORD *rec;\n\tEVP_CIPHER_CTX *ds;\n\tunsigned long l;\n\tint bs,i,mac_size=0;\n\tconst EVP_CIPHER *enc;\n\n\tif (send)\n\t\t{\n\t\tds=s->enc_write_ctx;\n\t\trec= &(s->s3->wrec);\n\t\tif (s->enc_write_ctx == NULL)\n\t\t\tenc=NULL;\n\t\telse\n\t\t\tenc=EVP_CIPHER_CTX_cipher(s->enc_write_ctx);\n\t\t}\n\telse\n\t\t{\n\t\tds=s->enc_read_ctx;\n\t\trec= &(s->s3->rrec);\n\t\tif (s->enc_read_ctx == NULL)\n\t\t\tenc=NULL;\n\t\telse\n\t\t\tenc=EVP_CIPHER_CTX_cipher(s->enc_read_ctx);\n\t\t}\n\n\tif ((s->session == NULL) || (ds == NULL) ||\n\t\t(enc == NULL))\n\t\t{\n\t\tmemmove(rec->data,rec->input,rec->length);\n\t\trec->input=rec->data;\n\t\t}\n\telse\n\t\t{\n\t\tl=rec->length;\n\t\tbs=EVP_CIPHER_block_size(ds->cipher);\n\n\t\t/* COMPRESS */\n\n\t\tif ((bs != 1) && send)\n\t\t\t{\n\t\t\ti=bs-((int)l%bs);\n\n\t\t\t/* we need to add 'i-1' padding bytes */\n\t\t\tl+=i;\n\t\t\t/* the last of these zero bytes will be overwritten\n\t\t\t * with the padding length. */\n\t\t\tmemset(&rec->input[rec->length], 0, i);\n\t\t\trec->length+=i;\n\t\t\trec->input[l-1]=(i-1);\n\t\t\t}\n\t\t\n\t\tif (!send)\n\t\t\t{\n\t\t\tif (l == 0 || l%bs != 0)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_ENC,SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);\n\t\t\t\tssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECRYPTION_FAILED);\n\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t/* otherwise, rec->length >= bs */\n\t\t\t}\n\t\t\n\t\tEVP_Cipher(ds,rec->data,rec->input,l);\n\n\t\trec->orig_len = rec->length;\n\n\t\tif (s->read_hash != NULL)\n\t\t\tmac_size = EVP_MD_size(s->read_hash);\n\t\tif ((bs != 1) && !send)\n\t\t\treturn ssl3_cbc_remove_padding(s, rec, bs, mac_size);\n\t\t}\n\treturn(1);\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Don't crash when processing a zero-length, TLS >= 1.1 record.\n\nThe previous CBC patch was bugged in that there was a path through enc()\nin s3_pkt.c/d1_pkt.c which didn't set orig_len. orig_len would be left\nat the previous value which could suggest that the packet was a\nsufficient length when it wasn't.\n(cherry picked from commit 6cb19b7681f600b2f165e4adc57547b097b475fd)\n(cherry picked from commit 2c948c1bb218f4ae126e14fd3453d42c62b93235)\n\nConflicts:\n\tssl/s3_enc.c'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: char ssl3_cbc_record_digest_supported(const EVP_MD *digest)\n\t{\n#ifdef OPENSSL_FIPS\n\tif (FIPS_mode())\n\t\treturn 0;\n#endif\n\tswitch (digest->type)\n\t\t{\n\t\tcase NID_md5:\n\t\tcase NID_sha1:\n\t\tcase NID_sha224:\n\t\tcase NID_sha256:\n\t\tcase NID_sha384:\n\t\tcase NID_sha512:\n\t\t\treturn 1;\n\t\tdefault:\n\t\t\treturn 0;\n\t\t}\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Don't access EVP_MD internals directly.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int ssl2_read_internal(SSL *s, void *buf, int len, int peek)\n\t{\n\tint n;\n\tunsigned char mac[MAX_MAC_SIZE];\n\tunsigned char *p;\n\tint i;\n\tint mac_size;\n\n ssl2_read_again:\n\tif (SSL_in_init(s) && !s->in_handshake)\n\t\t{\n\t\tn=s->handshake_func(s);\n\t\tif (n < 0) return(n);\n\t\tif (n == 0)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL2_READ_INTERNAL,SSL_R_SSL_HANDSHAKE_FAILURE);\n\t\t\treturn(-1);\n\t\t\t}\n\t\t}\n\n\tclear_sys_error();\n\ts->rwstate=SSL_NOTHING;\n\tif (len <= 0) return(len);\n\n\tif (s->s2->ract_data_length != 0) /* read from buffer */\n\t\t{\n\t\tif (len > s->s2->ract_data_length)\n\t\t\tn=s->s2->ract_data_length;\n\t\telse\n\t\t\tn=len;\n\n\t\tmemcpy(buf,s->s2->ract_data,(unsigned int)n);\n\t\tif (!peek)\n\t\t\t{\n\t\t\ts->s2->ract_data_length-=n;\n\t\t\ts->s2->ract_data+=n;\n\t\t\tif (s->s2->ract_data_length == 0)\n\t\t\t\ts->rstate=SSL_ST_READ_HEADER;\n\t\t\t}\n\n\t\treturn(n);\n\t\t}\n\n\t/* s->s2->ract_data_length == 0\n\t * \n\t * Fill the buffer, then goto ssl2_read_again.\n\t */\n\n\tif (s->rstate == SSL_ST_READ_HEADER)\n\t\t{\n\t\tif (s->first_packet)\n\t\t\t{\n\t\t\tn=read_n(s,5,SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER+2,0);\n\t\t\tif (n <= 0) return(n); /* error or non-blocking */\n\t\t\ts->first_packet=0;\n\t\t\tp=s->packet;\n\t\t\tif (!((p[0] & 0x80) && (\n\t\t\t\t(p[2] == SSL2_MT_CLIENT_HELLO) ||\n\t\t\t\t(p[2] == SSL2_MT_SERVER_HELLO))))\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL2_READ_INTERNAL,SSL_R_NON_SSLV2_INITIAL_PACKET);\n\t\t\t\treturn(-1);\n\t\t\t\t}\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tn=read_n(s,2,SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER+2,0);\n\t\t\tif (n <= 0) return(n); /* error or non-blocking */\n\t\t\t}\n\t\t/* part read stuff */\n\n\t\ts->rstate=SSL_ST_READ_BODY;\n\t\tp=s->packet;\n\t\t/* Do header */\n\t\t/*s->s2->padding=0;*/\n\t\ts->s2->escape=0;\n\t\ts->s2->rlength=(((unsigned int)p[0])<<8)|((unsigned int)p[1]);\n\t\tif ((p[0] & TWO_BYTE_BIT))\t\t/* Two byte header? */\n\t\t\t{\n\t\t\ts->s2->three_byte_header=0;\n\t\t\ts->s2->rlength&=TWO_BYTE_MASK;\t\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\ts->s2->three_byte_header=1;\n\t\t\ts->s2->rlength&=THREE_BYTE_MASK;\n\n\t\t\t/* security >s2->escape */\n\t\t\ts->s2->escape=((p[0] & SEC_ESC_BIT))?1:0;\n\t\t\t}\n\t\t}\n\n\tif (s->rstate == SSL_ST_READ_BODY)\n\t\t{\n\t\tn=s->s2->rlength+2+s->s2->three_byte_header;\n\t\tif (n > (int)s->packet_length)\n\t\t\t{\n\t\t\tn-=s->packet_length;\n\t\t\ti=read_n(s,(unsigned int)n,(unsigned int)n,1);\n\t\t\tif (i <= 0) return(i); /* ERROR */\n\t\t\t}\n\n\t\tp= &(s->packet[2]);\n\t\ts->rstate=SSL_ST_READ_HEADER;\n\t\tif (s->s2->three_byte_header)\n\t\t\ts->s2->padding= *(p++);\n\t\telse\ts->s2->padding=0;\n\n\t\t/* Data portion */\n\t\tif (s->s2->clear_text)\n\t\t\t{\n\t\t\tmac_size = 0;\n\t\t\ts->s2->mac_data=p;\n\t\t\ts->s2->ract_data=p;\n\t\t\tif (s->s2->padding)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL2_READ_INTERNAL,SSL_R_ILLEGAL_PADDING);\n\t\t\t\treturn(-1);\n\t\t\t\t}\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tmac_size=EVP_MD_CTX_size(s->read_hash);\n\t\t\tif (mac_size < 0)\n\t\t\t\treturn -1;\n\t\t\tOPENSSL_assert(mac_size <= MAX_MAC_SIZE);\n\t\t\ts->s2->mac_data=p;\n\t\t\ts->s2->ract_data= &p[mac_size];\n\t\t\tif (s->s2->padding + mac_size > s->s2->rlength)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL2_READ_INTERNAL,SSL_R_ILLEGAL_PADDING);\n\t\t\t\treturn(-1);\n\t\t\t\t}\n\t\t\t}\n\n\t\ts->s2->ract_data_length=s->s2->rlength;\n\t\t/* added a check for length > max_size in case\n\t\t * encryption was not turned on yet due to an error */\n\t\tif ((!s->s2->clear_text) &&\n\t\t\t(s->s2->rlength >= (unsigned int)mac_size))\n\t\t\t{\n\t\t\tssl2_enc(s,0);\n\t\t\ts->s2->ract_data_length-=mac_size;\n\t\t\tssl2_mac(s,mac,0);\n\t\t\ts->s2->ract_data_length-=s->s2->padding;\n\t\t\tif (\t(memcmp(mac,s->s2->mac_data,\n\t\t\t\t(unsigned int)mac_size) != 0) ||\n\t\t\t\t(s->s2->rlength%EVP_CIPHER_CTX_block_size(s->enc_read_ctx) != 0))\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL2_READ_INTERNAL,SSL_R_BAD_MAC_DECODE);\n\t\t\t\treturn(-1);\n\t\t\t\t}\n\t\t\t}\n\t\tINC32(s->s2->read_sequence); /* expect next number */\n\t\t/* s->s2->ract_data is now available for processing */\n\n\t\t/* Possibly the packet that we just read had 0 actual data bytes.\n\t\t * (SSLeay/OpenSSL itself never sends such packets; see ssl2_write.)\n\t\t * In this case, returning 0 would be interpreted by the caller\n\t\t * as indicating EOF, so it's not a good idea. Instead, we just\n\t\t * continue reading; thus ssl2_read_internal may have to process\n\t\t * multiple packets before it can return.\n\t\t *\n\t\t * [Note that using select() for blocking sockets *never* guarantees\n\t\t * that the next SSL_read will not block -- the available\n\t\t * data may contain incomplete packets, and except for SSL 2,\n\t\t * renegotiation can confuse things even more.] */\n\n\t\tgoto ssl2_read_again; /* This should really be\n\t\t * \"return ssl2_read(s,buf,len)\",\n\t\t * but that would allow for\n\t\t * denial-of-service attacks if a\n\t\t * C compiler is used that does not\n\t\t * recognize end-recursion. */\n\t\t}\n\telse\n\t\t{\n\t\tSSLerr(SSL_F_SSL2_READ_INTERNAL,SSL_R_BAD_STATE);\n\t\t\treturn(-1);\n\t\t}\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Add and use a constant-time memcmp.\n\nThis change adds CRYPTO_memcmp, which compares two vectors of bytes in\nan amount of time that's independent of their contents. It also changes\nseveral MAC compares in the code to use this over the standard memcmp,\nwhich may leak information about the size of a matching prefix.\n(cherry picked from commit 2ee798880a246d648ecddadc5b91367bee4a5d98)\n\nConflicts:\n\tcrypto/crypto.h\n\tssl/t1_lib.c'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int tls1_enc(SSL *s, int send)\n\t{\n\tSSL3_RECORD *rec;\n\tEVP_CIPHER_CTX *ds;\n\tunsigned long l;\n\tint bs,i,j,k,pad=0,ret,mac_size=0;\n\tconst EVP_CIPHER *enc;\n\n\tif (send)\n\t\t{\n\t\tif (EVP_MD_CTX_md(s->write_hash))\n\t\t\t{\n\t\t\tn=EVP_MD_CTX_size(s->write_hash);\n\t\t\tOPENSSL_assert(n >= 0);\n\t\t\t}\n\t\tds=s->enc_write_ctx;\n\t\trec= &(s->s3->wrec);\n\t\tif (s->enc_write_ctx == NULL)\n\t\t\tenc=NULL;\n\t\telse\n\t\t\tenc=EVP_CIPHER_CTX_cipher(s->enc_write_ctx);\n\t\t}\n\telse\n\t\t{\n\t\tif (EVP_MD_CTX_md(s->read_hash))\n\t\t\t{\n\t\t\tn=EVP_MD_CTX_size(s->read_hash);\n\t\t\tOPENSSL_assert(n >= 0);\n\t\t\t}\n\t\tds=s->enc_read_ctx;\n\t\trec= &(s->s3->rrec);\n\t\tif (s->enc_read_ctx == NULL)\n\t\t\tenc=NULL;\n\t\telse\n\t\t\tenc=EVP_CIPHER_CTX_cipher(s->enc_read_ctx);\n\t\t}\n\n#ifdef KSSL_DEBUG\n\tprintf(\"tls1_enc(%d)\\n\", send);\n#endif /* KSSL_DEBUG */\n\n\tif ((s->session == NULL) || (ds == NULL) || (enc == NULL))\n\t\t{\n\t\tmemmove(rec->data,rec->input,rec->length);\n\t\trec->input=rec->data;\n\t\tret = 1;\n\t\t}\n\telse\n\t\t{\n\t\tl=rec->length;\n\t\tbs=EVP_CIPHER_block_size(ds->cipher);\n\n\t\tif ((bs != 1) && send)\n\t\t\t{\n\t\t\ti=bs-((int)l%bs);\n\n\t\t\t/* Add weird padding of upto 256 bytes */\n\n\t\t\t/* we need to add 'i' padding bytes of value j */\n\t\t\tj=i-1;\n\t\t\tif (s->options & SSL_OP_TLS_BLOCK_PADDING_BUG)\n\t\t\t\t{\n\t\t\t\tif (s->s3->flags & TLS1_FLAGS_TLS_PADDING_BUG)\n\t\t\t\t\tj++;\n\t\t\t\t}\n\t\t\tfor (k=(int)l; k<(int)(l+i); k++)\n\t\t\t\trec->input[k]=j;\n\t\t\tl+=i;\n\t\t\trec->length+=i;\n\t\t\t}\n\n#ifdef KSSL_DEBUG\n\t\t{\n\t\tunsigned long ui;\n\t\tprintf(\"EVP_Cipher(ds=%p,rec->data=%p,rec->input=%p,l=%ld) ==>\\n\",\n\t\t\tds,rec->data,rec->input,l);\n\t\tprintf(\"\\tEVP_CIPHER_CTX: %d buf_len, %d key_len [%d %d], %d iv_len\\n\",\n\t\t\tds->buf_len, ds->cipher->key_len,\n\t\t\tDES_KEY_SZ, DES_SCHEDULE_SZ,\n\t\t\tds->cipher->iv_len);\n\t\tprintf(\"\\t\\tIV: \");\n\t\tfor (i=0; icipher->iv_len; i++) printf(\"%02X\", ds->iv[i]);\n\t\tprintf(\"\\n\");\n\t\tprintf(\"\\trec->input=\");\n\t\tfor (ui=0; uiinput[ui]);\n\t\tprintf(\"\\n\");\n\t\t}\n#endif\t/* KSSL_DEBUG */\n\n\t\tif (!send)\n\t\t\t{\n\t\t\tif (l == 0 || l%bs != 0)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_TLS1_ENC,SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);\n\t\t\t\tssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECRYPTION_FAILED);\n\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\n\t\tEVP_Cipher(ds,rec->data,rec->input,l);\n\n#ifdef KSSL_DEBUG\n\t\t{\n\t\tunsigned long i;\n\t\tprintf(\"\\trec->data=\");\n\t\tfor (i=0; idata[i]); printf(\"\\n\");\n\t\t}\n#endif\t/* KSSL_DEBUG */\n\n\t\trec->orig_len = rec->length;\n\n\t\tret = 1;\n\t\tif (EVP_MD_CTX_md(s->read_hash) != NULL)\n\t\t\tmac_size = EVP_MD_CTX_size(s->read_hash);\n\t\tif ((bs != 1) && !send)\n\t\t\tret = tls1_cbc_remove_padding(s, rec, bs, mac_size);\n\t\tif (pad && !send)\n\t\t\trec->length -= pad;\n\t\t}\n\treturn ret;\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Fixups from previous commit.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void ssl3_cbc_digest_record(\n\tconst EVP_MD_CTX *ctx,\n\tunsigned char* md_out,\n\tsize_t* md_out_size,\n\tconst unsigned char header[13],\n\tconst unsigned char *data,\n\tsize_t data_plus_mac_size,\n\tsize_t data_plus_mac_plus_padding_size,\n\tconst unsigned char *mac_secret,\n\tunsigned mac_secret_length,\n\tchar is_sslv3)\n\t{\n\tunsigned char md_state[sizeof(SHA512_CTX)];\n\tvoid (*md_final_raw)(void *ctx, unsigned char *md_out);\n\tvoid (*md_transform)(void *ctx, const unsigned char *block);\n\tunsigned md_size, md_block_size = 64;\n\tunsigned sslv3_pad_length = 40, header_length, variance_blocks,\n\t\t len, max_mac_bytes, num_blocks,\n\t\t num_starting_blocks, k, mac_end_offset, c, index_a, index_b;\n\tunsigned int bits;\t/* at most 18 bits */\n\tunsigned char length_bytes[MAX_HASH_BIT_COUNT_BYTES];\n\t/* hmac_pad is the masked HMAC key. */\n\tunsigned char hmac_pad[MAX_HASH_BLOCK_SIZE];\n\tunsigned char first_block[MAX_HASH_BLOCK_SIZE];\n\tunsigned char mac_out[EVP_MAX_MD_SIZE];\n\tunsigned i, j, md_out_size_u;\n\tEVP_MD_CTX md_ctx;\n\t/* mdLengthSize is the number of bytes in the length field that terminates\n\t* the hash. */\n\tunsigned md_length_size = 8;\n\n\t/* This is a, hopefully redundant, check that allows us to forget about\n\t * many possible overflows later in this function. */\n\tOPENSSL_assert(data_plus_mac_plus_padding_size < 1024*1024);\n\n\tswitch (ctx->digest->type)\n\t\t{\n\t\tcase NID_md5:\n\t\t\tMD5_Init((MD5_CTX*)md_state);\n\t\t\tmd_final_raw = tls1_md5_final_raw;\n\t\t\tmd_transform = (void(*)(void *ctx, const unsigned char *block)) MD5_Transform;\n\t\t\tmd_size = 16;\n\t\t\tsslv3_pad_length = 48;\n\t\t\tbreak;\n\t\tcase NID_sha1:\n\t\t\tSHA1_Init((SHA_CTX*)md_state);\n\t\t\tmd_final_raw = tls1_sha1_final_raw;\n\t\t\tmd_transform = (void(*)(void *ctx, const unsigned char *block)) SHA1_Transform;\n\t\t\tmd_size = 20;\n\t\t\tbreak;\n\t\tcase NID_sha224:\n\t\t\tSHA224_Init((SHA256_CTX*)md_state);\n\t\t\tmd_final_raw = tls1_sha256_final_raw;\n\t\t\tmd_transform = (void(*)(void *ctx, const unsigned char *block)) SHA256_Transform;\n\t\t\tmd_size = 224/8;\n\t\t\tbreak;\n\t\tcase NID_sha256:\n\t\t\tSHA256_Init((SHA256_CTX*)md_state);\n\t\t\tmd_final_raw = tls1_sha256_final_raw;\n\t\t\tmd_transform = (void(*)(void *ctx, const unsigned char *block)) SHA256_Transform;\n\t\t\tmd_size = 32;\n\t\t\tbreak;\n\t\tcase NID_sha384:\n\t\t\tSHA384_Init((SHA512_CTX*)md_state);\n\t\t\tmd_final_raw = tls1_sha512_final_raw;\n\t\t\tmd_transform = (void(*)(void *ctx, const unsigned char *block)) SHA512_Transform;\n\t\t\tmd_size = 384/8;\n\t\t\tmd_block_size = 128;\n\t\t\tmd_length_size = 16;\n\t\t\tbreak;\n\t\tcase NID_sha512:\n\t\t\tSHA512_Init((SHA512_CTX*)md_state);\n\t\t\tmd_final_raw = tls1_sha512_final_raw;\n\t\t\tmd_transform = (void(*)(void *ctx, const unsigned char *block)) SHA512_Transform;\n\t\t\tmd_size = 64;\n\t\t\tmd_block_size = 128;\n\t\t\tmd_length_size = 16;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t/* ssl3_cbc_record_digest_supported should have been\n\t\t\t * called first to check that the hash function is\n\t\t\t * supported. */\n\t\t\tOPENSSL_assert(0);\n\t\t\tif (md_out_size)\n\t\t\t\t*md_out_size = -1;\n\t\t\treturn;\n\t\t}\n\n\tOPENSSL_assert(md_length_size <= MAX_HASH_BIT_COUNT_BYTES);\n\tOPENSSL_assert(md_block_size <= MAX_HASH_BLOCK_SIZE);\n\tOPENSSL_assert(md_size <= EVP_MAX_MD_SIZE);\n\n\theader_length = 13;\n\tif (is_sslv3)\n\t\t{\n\t\theader_length =\n\t\t\tmac_secret_length +\n\t\t\tsslv3_pad_length +\n\t\t\t8 /* sequence number */ +\n\t\t\t1 /* record type */ +\n\t\t\t2 /* record length */;\n\t\t}\n\n\t/* variance_blocks is the number of blocks of the hash that we have to\n\t * calculate in constant time because they could be altered by the\n\t * padding value.\n\t *\n\t * In SSLv3, the padding must be minimal so the end of the plaintext\n\t * varies by, at most, 15+20 = 35 bytes. (We conservatively assume that\n\t * the MAC size varies from 0..20 bytes.) In case the 9 bytes of hash\n\t * termination (0x80 + 64-bit length) don't fit in the final block, we\n\t * say that the final two blocks can vary based on the padding.\n\t *\n\t * TLSv1 has MACs up to 48 bytes long (SHA-384) and the padding is not\n\t * required to be minimal. Therefore we say that the final six blocks\n\t * can vary based on the padding.\n\t *\n\t * Later in the function, if the message is short and there obviously\n\t * cannot be this many blocks then variance_blocks can be reduced. */\n\tvariance_blocks = is_sslv3 ? 2 : 6;\n\t/* From now on we're dealing with the MAC, which conceptually has 13\n\t * bytes of `header' before the start of the data (TLS) or 71/75 bytes\n\t * (SSLv3) */\n\tlen = data_plus_mac_plus_padding_size + header_length;\n\t/* max_mac_bytes contains the maximum bytes of bytes in the MAC, including\n\t* |header|, assuming that there's no padding. */\n\tmax_mac_bytes = len - md_size - 1;\n\t/* num_blocks is the maximum number of hash blocks. */\n\tnum_blocks = (max_mac_bytes + 1 + md_length_size + md_block_size - 1) / md_block_size;\n\t/* In order to calculate the MAC in constant time we have to handle\n\t * the final blocks specially because the padding value could cause the\n\t * end to appear somewhere in the final |variance_blocks| blocks and we\n\t * can't leak where. However, |num_starting_blocks| worth of data can\n\t * be hashed right away because no padding value can affect whether\n\t * they are plaintext. */\n\tnum_starting_blocks = 0;\n\t/* k is the starting byte offset into the conceptual header||data where\n\t * we start processing. */\n\tk = 0;\n\t/* mac_end_offset is the index just past the end of the data to be\n\t * MACed. */\n\tmac_end_offset = data_plus_mac_size + header_length - md_size;\n\t/* c is the index of the 0x80 byte in the final hash block that\n\t * contains application data. */\n\tc = mac_end_offset % md_block_size;\n\t/* index_a is the hash block number that contains the 0x80 terminating\n\t * value. */\n\tindex_a = mac_end_offset / md_block_size;\n\t/* index_b is the hash block number that contains the 64-bit hash\n\t * length, in bits. */\n\tindex_b = (mac_end_offset + md_length_size) / md_block_size;\n\t/* bits is the hash-length in bits. It includes the additional hash\n\t * block for the masked HMAC key, or whole of |header| in the case of\n\t * SSLv3. */\n\n\t/* For SSLv3, if we're going to have any starting blocks then we need\n\t * at least two because the header is larger than a single block. */\n\tif (num_blocks > variance_blocks + (is_sslv3 ? 1 : 0))\n\t\t{\n\t\tnum_starting_blocks = num_blocks - variance_blocks;\n\t\tk = md_block_size*num_starting_blocks;\n\t\t}\n\n\tbits = 8*mac_end_offset;\n\tif (!is_sslv3)\n\t\t{\n\t\t/* Compute the initial HMAC block. For SSLv3, the padding and\n\t\t * secret bytes are included in |header| because they take more\n\t\t * than a single block. */\n\t\tbits += 8*md_block_size;\n\t\tmemset(hmac_pad, 0, md_block_size);\n\t\tOPENSSL_assert(mac_secret_length <= sizeof(hmac_pad));\n\t\tmemcpy(hmac_pad, mac_secret, mac_secret_length);\n\t\tfor (i = 0; i < md_block_size; i++)\n\t\t\thmac_pad[i] ^= 0x36;\n\n\t\tmd_transform(md_state, hmac_pad);\n\t\t}\n\n\tmemset(length_bytes,0,md_length_size-4);\n\tlength_bytes[md_length_size-4] = (unsigned char)(bits>>24);\n\tlength_bytes[md_length_size-3] = (unsigned char)(bits>>16);\n\tlength_bytes[md_length_size-2] = (unsigned char)(bits>>8);\n\tlength_bytes[md_length_size-1] = (unsigned char)bits;\n\n\tif (k > 0)\n\t\t{\n\t\tif (is_sslv3)\n\t\t\t{\n\t\t\t/* The SSLv3 header is larger than a single block.\n\t\t\t * overhang is the number of bytes beyond a single\n\t\t\t * block that the header consumes: either 7 bytes\n\t\t\t * (SHA1) or 11 bytes (MD5). */\n\t\t\tunsigned overhang = header_length-md_block_size;\n\t\t\tmd_transform(md_state, header);\n\t\t\tmemcpy(first_block, header + md_block_size, overhang);\n\t\t\tmemcpy(first_block + overhang, data, md_block_size-overhang);\n\t\t\tmd_transform(md_state, first_block);\n\t\t\tfor (i = 1; i < k/md_block_size - 1; i++)\n\t\t\t\tmd_transform(md_state, data + md_block_size*i - overhang);\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\t/* k is a multiple of md_block_size. */\n\t\t\tmemcpy(first_block, header, 13);\n\t\t\tmemcpy(first_block+13, data, md_block_size-13);\n\t\t\tmd_transform(md_state, first_block);\n\t\t\tfor (i = 1; i < k/md_block_size; i++)\n\t\t\t\tmd_transform(md_state, data + md_block_size*i - 13);\n\t\t\t}\n\t\t}\n\n\tmemset(mac_out, 0, sizeof(mac_out));\n\n\t/* We now process the final hash blocks. For each block, we construct\n\t * it in constant time. If the |i==index_a| then we'll include the 0x80\n\t * bytes and zero pad etc. For each block we selectively copy it, in\n\t * constant time, to |mac_out|. */\n\tfor (i = num_starting_blocks; i <= num_starting_blocks+variance_blocks; i++)\n\t\t{\n\t\tunsigned char block[MAX_HASH_BLOCK_SIZE];\n\t\tunsigned char is_block_a = constant_time_eq_8(i, index_a);\n\t\tunsigned char is_block_b = constant_time_eq_8(i, index_b);\n\t\tfor (j = 0; j < md_block_size; j++)\n\t\t\t{\n\t\t\tunsigned char b = 0, is_past_c, is_past_cp1;\n\t\t\tif (k < header_length)\n\t\t\t\tb = header[k];\n\t\t\telse if (k < data_plus_mac_plus_padding_size + header_length)\n\t\t\t\tb = data[k-header_length];\n\t\t\tk++;\n\n\t\t\tis_past_c = is_block_a & constant_time_ge(j, c);\n\t\t\tis_past_cp1 = is_block_a & constant_time_ge(j, c+1);\n\t\t\t/* If this is the block containing the end of the\n\t\t\t * application data, and we are at the offset for the\n\t\t\t * 0x80 value, then overwrite b with 0x80. */\n\t\t\tb = (b&~is_past_c) | (0x80&is_past_c);\n\t\t\t/* If this the the block containing the end of the\n\t\t\t * application data and we're past the 0x80 value then\n\t\t\t * just write zero. */\n\t\t\tb = b&~is_past_cp1;\n\t\t\t/* If this is index_b (the final block), but not\n\t\t\t * index_a (the end of the data), then the 64-bit\n\t\t\t * length didn't fit into index_a and we're having to\n\t\t\t * add an extra block of zeros. */\n\t\t\tb &= ~is_block_b | is_block_a;\n\n\t\t\t/* The final bytes of one of the blocks contains the\n\t\t\t * length. */\n\t\t\tif (j >= md_block_size - md_length_size)\n\t\t\t\t{\n\t\t\t\t/* If this is index_b, write a length byte. */\n\t\t\t\tb = (b&~is_block_b) | (is_block_b&length_bytes[j-(md_block_size-md_length_size)]);\n\t\t\t\t}\n\t\t\tblock[j] = b;\n\t\t\t}\n\n\t\tmd_transform(md_state, block);\n\t\tmd_final_raw(md_state, block);\n\t\t/* If this is index_b, copy the hash value to |mac_out|. */\n\t\tfor (j = 0; j < md_size; j++)\n\t\t\tmac_out[j] |= block[j]&is_block_b;\n\t\t}\n\n\tEVP_MD_CTX_init(&md_ctx);\n\tEVP_DigestInit_ex(&md_ctx, ctx->digest, NULL /* engine */);\n\tif (is_sslv3)\n\t\t{\n\t\t/* We repurpose |hmac_pad| to contain the SSLv3 pad2 block. */\n\t\tmemset(hmac_pad, 0x5c, sslv3_pad_length);\n\n\t\tEVP_DigestUpdate(&md_ctx, mac_secret, mac_secret_length);\n\t\tEVP_DigestUpdate(&md_ctx, hmac_pad, sslv3_pad_length);\n\t\tEVP_DigestUpdate(&md_ctx, mac_out, md_size);\n\t\t}\n\telse\n\t\t{\n\t\t/* Complete the HMAC in the standard manner. */\n\t\tfor (i = 0; i < md_block_size; i++)\n\t\t\thmac_pad[i] ^= 0x6a;\n\n\t\tEVP_DigestUpdate(&md_ctx, hmac_pad, md_block_size);\n\t\tEVP_DigestUpdate(&md_ctx, mac_out, md_size);\n\t\t}\n\tEVP_DigestFinal(&md_ctx, md_out, &md_out_size_u);\n\tif (md_out_size)\n\t\t*md_out_size = md_out_size_u;\n\tEVP_MD_CTX_cleanup(&md_ctx);\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'ssl/s3_cbc.c: md_state alignment portability fix.\n\nRISCs are picky and alignment granted by compiler for md_state can be\ninsufficient for SHA512.\n(cherry picked from commit 36260233e7e3396feed884d3f501283e0453c04f)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int SSL_library_init(void)\n\t{\n\n#ifndef OPENSSL_NO_DES\n\tEVP_add_cipher(EVP_des_cbc());\n\tEVP_add_cipher(EVP_des_ede3_cbc());\n#endif\n#ifndef OPENSSL_NO_IDEA\n\tEVP_add_cipher(EVP_idea_cbc());\n#endif\n#ifndef OPENSSL_NO_RC4\n\tEVP_add_cipher(EVP_rc4());\n#if !defined(OPENSSL_NO_MD5) && (defined(__x86_64) || defined(__x86_64__))\n\tEVP_add_cipher(EVP_rc4_hmac_md5());\n#endif\n#endif \n#ifndef OPENSSL_NO_RC2\n\tEVP_add_cipher(EVP_rc2_cbc());\n\t/* Not actually used for SSL/TLS but this makes PKCS#12 work\n\t * if an application only calls SSL_library_init().\n\t */\n\tEVP_add_cipher(EVP_rc2_40_cbc());\n#endif\n#ifndef OPENSSL_NO_AES\n\tEVP_add_cipher(EVP_aes_128_cbc());\n\tEVP_add_cipher(EVP_aes_192_cbc());\n\tEVP_add_cipher(EVP_aes_256_cbc());\n\tEVP_add_cipher(EVP_aes_128_gcm());\n\tEVP_add_cipher(EVP_aes_256_gcm());\n#if 0 /* Disabled because of timing side-channel leaks. */\n#if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_SHA1)\n\tEVP_add_cipher(EVP_aes_128_cbc_hmac_sha1());\n\tEVP_add_cipher(EVP_aes_256_cbc_hmac_sha1());\n#endif\n#endif\n\n#endif\n#ifndef OPENSSL_NO_CAMELLIA\n\tEVP_add_cipher(EVP_camellia_128_cbc());\n\tEVP_add_cipher(EVP_camellia_256_cbc());\n#endif\n\n#ifndef OPENSSL_NO_SEED\n\tEVP_add_cipher(EVP_seed_cbc());\n#endif\n \n#ifndef OPENSSL_NO_MD5\n\tEVP_add_digest(EVP_md5());\n\tEVP_add_digest_alias(SN_md5,\"ssl2-md5\");\n\tEVP_add_digest_alias(SN_md5,\"ssl3-md5\");\n#endif\n#ifndef OPENSSL_NO_SHA\n\tEVP_add_digest(EVP_sha1()); /* RSA with sha1 */\n\tEVP_add_digest_alias(SN_sha1,\"ssl3-sha1\");\n\tEVP_add_digest_alias(SN_sha1WithRSAEncryption,SN_sha1WithRSA);\n#endif\n#ifndef OPENSSL_NO_SHA256\n\tEVP_add_digest(EVP_sha224());\n\tEVP_add_digest(EVP_sha256());\n#endif\n#ifndef OPENSSL_NO_SHA512\n\tEVP_add_digest(EVP_sha384());\n\tEVP_add_digest(EVP_sha512());\n#endif\n#if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_DSA)\n\tEVP_add_digest(EVP_dss1()); /* DSA with sha1 */\n\tEVP_add_digest_alias(SN_dsaWithSHA1,SN_dsaWithSHA1_2);\n\tEVP_add_digest_alias(SN_dsaWithSHA1,\"DSS1\");\n\tEVP_add_digest_alias(SN_dsaWithSHA1,\"dss1\");\n#endif\n#ifndef OPENSSL_NO_ECDSA\n\tEVP_add_digest(EVP_ecdsa());\n#endif\n\t/* If you want support for phased out ciphers, add the following */\n#if 0\n\tEVP_add_digest(EVP_sha());\n\tEVP_add_digest(EVP_dss());\n#endif\n#ifndef OPENSSL_NO_COMP\n\t/* This will initialise the built-in compression algorithms.\n\t The value returned is a STACK_OF(SSL_COMP), but that can\n\t be discarded safely */\n\t(void)SSL_COMP_get_compression_methods();\n#endif\n\t/* initialize cipher/digest methods table */\n\tssl_load_ciphers();\n\treturn(1);\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'e_aes_cbc_hmac_sha1.c: address the CBC decrypt timing issues.\n\nAddress CBC decrypt timing issues and reenable the AESNI+SHA1 stitch.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: _rsvg_handle_allow_load (RsvgHandle *handle,\n const char *uri,\n GError **error)\n{\n RsvgLoadPolicy policy = handle->priv->load_policy;\n\n if (policy == RSVG_LOAD_POLICY_ALL_PERMISSIVE)\n return TRUE;\n\n return TRUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'io: Implement strict load policy\n\nAllow any file to load from data:, and any resource to load from other\nresources. Only allow file: to load other file: URIs from below the path\nof the base file. Any other loads are denied.\n\nBug #691708.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ssl3_connect(SSL *s)\n\t{\n\tBUF_MEM *buf=NULL;\n\tunsigned long Time=(unsigned long)time(NULL);\n\tvoid (*cb)(const SSL *ssl,int type,int val)=NULL;\n\tint ret= -1;\n\tint new_state,state,skip=0;\n\n\tRAND_add(&Time,sizeof(Time),0);\n\tERR_clear_error();\n\tclear_sys_error();\n\n\tif (s->info_callback != NULL)\n\t\tcb=s->info_callback;\n\telse if (s->ctx->info_callback != NULL)\n\t\tcb=s->ctx->info_callback;\n\t\n\ts->in_handshake++;\n\tif (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); \n\n\tfor (;;)\n\t\t{\n\t\tstate=s->state;\n\n\t\tswitch(s->state)\n\t\t\t{\n\t\tcase SSL_ST_RENEGOTIATE:\n\t\t\ts->new_session=1;\n\t\t\ts->state=SSL_ST_CONNECT;\n\t\t\ts->ctx->stats.sess_connect_renegotiate++;\n\t\t\t/* break */\n\t\tcase SSL_ST_BEFORE:\n\t\tcase SSL_ST_CONNECT:\n\t\tcase SSL_ST_BEFORE|SSL_ST_CONNECT:\n\t\tcase SSL_ST_OK|SSL_ST_CONNECT:\n\n\t\t\ts->server=0;\n\t\t\tif (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);\n\n\t\t\tif ((s->version & 0xff00 ) != 0x0300)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_CONNECT, ERR_R_INTERNAL_ERROR);\n\t\t\t\tret = -1;\n\t\t\t\tgoto end;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t/* s->version=SSL3_VERSION; */\n\t\t\ts->type=SSL_ST_CONNECT;\n\n\t\t\tif (s->init_buf == NULL)\n\t\t\t\t{\n\t\t\t\tif ((buf=BUF_MEM_new()) == NULL)\n\t\t\t\t\t{\n\t\t\t\t\tret= -1;\n\t\t\t\t\tgoto end;\n\t\t\t\t\t}\n\t\t\t\tif (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))\n\t\t\t\t\t{\n\t\t\t\t\tret= -1;\n\t\t\t\t\tgoto end;\n\t\t\t\t\t}\n\t\t\t\ts->init_buf=buf;\n\t\t\t\tbuf=NULL;\n\t\t\t\t}\n\n\t\t\tif (!ssl3_setup_buffers(s)) { ret= -1; goto end; }\n\n\t\t\t/* setup buffing BIO */\n\t\t\tif (!ssl_init_wbio_buffer(s,0)) { ret= -1; goto end; }\n\n\t\t\t/* don't push the buffering BIO quite yet */\n\n\t\t\tssl3_init_finished_mac(s);\n\n\t\t\ts->state=SSL3_ST_CW_CLNT_HELLO_A;\n\t\t\ts->ctx->stats.sess_connect++;\n\t\t\ts->init_num=0;\n\t\t\tbreak;\n\n\t\tcase SSL3_ST_CW_CLNT_HELLO_A:\n\t\tcase SSL3_ST_CW_CLNT_HELLO_B:\n\n\t\t\ts->shutdown=0;\n\t\t\tret=ssl3_client_hello(s);\n\t\t\tif (ret <= 0) goto end;\n\t\t\ts->state=SSL3_ST_CR_SRVR_HELLO_A;\n\t\t\ts->init_num=0;\n\n\t\t\t/* turn on buffering for the next lot of output */\n\t\t\tif (s->bbio != s->wbio)\n\t\t\t\ts->wbio=BIO_push(s->bbio,s->wbio);\n\n\t\t\tbreak;\n\n\t\tcase SSL3_ST_CR_SRVR_HELLO_A:\n\t\tcase SSL3_ST_CR_SRVR_HELLO_B:\n\t\t\tret=ssl3_get_server_hello(s);\n\t\t\tif (ret <= 0) goto end;\n\t\t\tif (s->hit)\n\t\t\t\t{\n\t\t\t\ts->state=SSL3_ST_CR_FINISHED_A;\n#ifndef OPENSSL_NO_TLSEXT\n\t\t\t\tif (s->tlsext_ticket_expected)\n\t\t\t\t\t{\n\t\t\t\t\t/* receive renewed session ticket */\n\t\t\t\t\ts->state=SSL3_ST_CR_SESSION_TICKET_A;\n\t\t\t\t\t}\n#endif\n\t\t\t\t}\n\t\t\telse\n\t\t\t\ts->state=SSL3_ST_CR_CERT_A;\n\t\t\ts->init_num=0;\n\t\t\tbreak;\n\n\t\tcase SSL3_ST_CR_CERT_A:\n\t\tcase SSL3_ST_CR_CERT_B:\n#ifndef OPENSSL_NO_TLSEXT\n\t\t\tret=ssl3_check_finished(s);\n\t\t\tif (ret <= 0) goto end;\n\t\t\tif (ret == 2)\n\t\t\t\t{\n\t\t\t\ts->hit = 1;\n\t\t\t\tif (s->tlsext_ticket_expected)\n\t\t\t\t\ts->state=SSL3_ST_CR_SESSION_TICKET_A;\n\t\t\t\telse\n\t\t\t\t\ts->state=SSL3_ST_CR_FINISHED_A;\n\t\t\t\ts->init_num=0;\n\t\t\t\tbreak;\n\t\t\t\t}\n#endif\n\t\t\t/* Check if it is anon DH/ECDH */\n\t\t\tif (!(s->s3->tmp.new_cipher->algorithms & SSL_aNULL))\n\t\t\t\t{\n\t\t\t\tret=ssl3_get_server_certificate(s);\n\t\t\t\tif (ret <= 0) goto end;\n#ifndef OPENSSL_NO_TLSEXT\n\t\t\t\tif (s->tlsext_status_expected)\n\t\t\t\t\ts->state=SSL3_ST_CR_CERT_STATUS_A;\n\t\t\t\telse\n\t\t\t\t\ts->state=SSL3_ST_CR_KEY_EXCH_A;\n\t\t\t\t}\n\t\t\telse\n\t\t\t\t{\n\t\t\t\tskip = 1;\n\t\t\t\ts->state=SSL3_ST_CR_KEY_EXCH_A;\n\t\t\t\t}\n#else\n\t\t\t\t}\n\t\t\telse\n\t\t\t\tskip=1;\n\n\t\t\ts->state=SSL3_ST_CR_KEY_EXCH_A;\n#endif\n\t\t\ts->init_num=0;\n\t\t\tbreak;\n\n\t\tcase SSL3_ST_CR_KEY_EXCH_A:\n\t\tcase SSL3_ST_CR_KEY_EXCH_B:\n\t\t\tret=ssl3_get_key_exchange(s);\n\t\t\tif (ret <= 0) goto end;\n\t\t\ts->state=SSL3_ST_CR_CERT_REQ_A;\n\t\t\ts->init_num=0;\n\n\t\t\t/* at this point we check that we have the\n\t\t\t * required stuff from the server */\n\t\t\tif (!ssl3_check_cert_and_algorithm(s))\n\t\t\t\t{\n\t\t\t\tret= -1;\n\t\t\t\tgoto end;\n\t\t\t\t}\n\t\t\tbreak;\n\n\t\tcase SSL3_ST_CR_CERT_REQ_A:\n\t\tcase SSL3_ST_CR_CERT_REQ_B:\n\t\t\tret=ssl3_get_certificate_request(s);\n\t\t\tif (ret <= 0) goto end;\n\t\t\ts->state=SSL3_ST_CR_SRVR_DONE_A;\n\t\t\ts->init_num=0;\n\t\t\tbreak;\n\n\t\tcase SSL3_ST_CR_SRVR_DONE_A:\n\t\tcase SSL3_ST_CR_SRVR_DONE_B:\n\t\t\tret=ssl3_get_server_done(s);\n\t\t\tif (ret <= 0) goto end;\n\t\t\tif (s->s3->tmp.cert_req)\n\t\t\t\ts->state=SSL3_ST_CW_CERT_A;\n\t\t\telse\n\t\t\t\ts->state=SSL3_ST_CW_KEY_EXCH_A;\n\t\t\ts->init_num=0;\n\n\t\t\tbreak;\n\n\t\tcase SSL3_ST_CW_CERT_A:\n\t\tcase SSL3_ST_CW_CERT_B:\n\t\tcase SSL3_ST_CW_CERT_C:\n\t\tcase SSL3_ST_CW_CERT_D:\n\t\t\tret=ssl3_send_client_certificate(s);\n\t\t\tif (ret <= 0) goto end;\n\t\t\ts->state=SSL3_ST_CW_KEY_EXCH_A;\n\t\t\ts->init_num=0;\n\t\t\tbreak;\n\n\t\tcase SSL3_ST_CW_KEY_EXCH_A:\n\t\tcase SSL3_ST_CW_KEY_EXCH_B:\n\t\t\tret=ssl3_send_client_key_exchange(s);\n\t\t\tif (ret <= 0) goto end;\n\t\t\t/* EAY EAY EAY need to check for DH fix cert\n\t\t\t * sent back */\n\t\t\t/* For TLS, cert_req is set to 2, so a cert chain\n\t\t\t * of nothing is sent, but no verify packet is sent */\n\t\t\t/* XXX: For now, we do not support client \n\t\t\t * authentication in ECDH cipher suites with\n\t\t\t * ECDH (rather than ECDSA) certificates.\n\t\t\t * We need to skip the certificate verify \n\t\t\t * message when client's ECDH public key is sent \n\t\t\t * inside the client certificate.\n\t\t\t */\n\t\t\tif (s->s3->tmp.cert_req == 1)\n\t\t\t\t{\n\t\t\t\ts->state=SSL3_ST_CW_CERT_VRFY_A;\n\t\t\t\t}\n\t\t\telse\n\t\t\t\t{\n\t\t\t\ts->state=SSL3_ST_CW_CHANGE_A;\n\t\t\t\ts->s3->change_cipher_spec=0;\n\t\t\t\t}\n\n\t\t\ts->init_num=0;\n\t\t\tbreak;\n\n\t\tcase SSL3_ST_CW_CERT_VRFY_A:\n\t\tcase SSL3_ST_CW_CERT_VRFY_B:\n\t\t\tret=ssl3_send_client_verify(s);\n\t\t\tif (ret <= 0) goto end;\n\t\t\ts->state=SSL3_ST_CW_CHANGE_A;\n\t\t\ts->init_num=0;\n\t\t\ts->s3->change_cipher_spec=0;\n\t\t\tbreak;\n\n\t\tcase SSL3_ST_CW_CHANGE_A:\n\t\tcase SSL3_ST_CW_CHANGE_B:\n\t\t\tret=ssl3_send_change_cipher_spec(s,\n\t\t\t\tSSL3_ST_CW_CHANGE_A,SSL3_ST_CW_CHANGE_B);\n\t\t\tif (ret <= 0) goto end;\n\t\t\ts->state=SSL3_ST_CW_FINISHED_A;\n\t\t\ts->init_num=0;\n\n\t\t\ts->session->cipher=s->s3->tmp.new_cipher;\n#ifdef OPENSSL_NO_COMP\n\t\t\ts->session->compress_meth=0;\n#else\n\t\t\tif (s->s3->tmp.new_compression == NULL)\n\t\t\t\ts->session->compress_meth=0;\n\t\t\telse\n\t\t\t\ts->session->compress_meth=\n\t\t\t\t\ts->s3->tmp.new_compression->id;\n#endif\n\t\t\tif (!s->method->ssl3_enc->setup_key_block(s))\n\t\t\t\t{\n\t\t\t\tret= -1;\n\t\t\t\tgoto end;\n\t\t\t\t}\n\n\t\t\tif (!s->method->ssl3_enc->change_cipher_state(s,\n\t\t\t\tSSL3_CHANGE_CIPHER_CLIENT_WRITE))\n\t\t\t\t{\n\t\t\t\tret= -1;\n\t\t\t\tgoto end;\n\t\t\t\t}\n\n\t\t\tbreak;\n\n\t\tcase SSL3_ST_CW_FINISHED_A:\n\t\tcase SSL3_ST_CW_FINISHED_B:\n\t\t\tret=ssl3_send_finished(s,\n\t\t\t\tSSL3_ST_CW_FINISHED_A,SSL3_ST_CW_FINISHED_B,\n\t\t\t\ts->method->ssl3_enc->client_finished_label,\n\t\t\t\ts->method->ssl3_enc->client_finished_label_len);\n\t\t\tif (ret <= 0) goto end;\n\t\t\ts->state=SSL3_ST_CW_FLUSH;\n\n\t\t\t/* clear flags */\n\t\t\ts->s3->flags&= ~SSL3_FLAGS_POP_BUFFER;\n\t\t\tif (s->hit)\n\t\t\t\t{\n\t\t\t\ts->s3->tmp.next_state=SSL_ST_OK;\n\t\t\t\tif (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED)\n\t\t\t\t\t{\n\t\t\t\t\ts->state=SSL_ST_OK;\n\t\t\t\t\ts->s3->flags|=SSL3_FLAGS_POP_BUFFER;\n\t\t\t\t\ts->s3->delay_buf_pop_ret=0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\telse\n\t\t\t\t{\n#ifndef OPENSSL_NO_TLSEXT\n\t\t\t\t/* Allow NewSessionTicket if ticket expected */\n\t\t\t\tif (s->tlsext_ticket_expected)\n\t\t\t\t\ts->s3->tmp.next_state=SSL3_ST_CR_SESSION_TICKET_A;\n\t\t\t\telse\n#endif\n\t\t\t\t\n\t\t\t\ts->s3->tmp.next_state=SSL3_ST_CR_FINISHED_A;\n\t\t\t\t}\n\t\t\ts->init_num=0;\n\t\t\tbreak;\n\n#ifndef OPENSSL_NO_TLSEXT\n\t\tcase SSL3_ST_CR_SESSION_TICKET_A:\n\t\tcase SSL3_ST_CR_SESSION_TICKET_B:\n\t\t\tret=ssl3_get_new_session_ticket(s);\n\t\t\tif (ret <= 0) goto end;\n\t\t\ts->state=SSL3_ST_CR_FINISHED_A;\n\t\t\ts->init_num=0;\n\t\tbreak;\n\n\t\tcase SSL3_ST_CR_CERT_STATUS_A:\n\t\tcase SSL3_ST_CR_CERT_STATUS_B:\n\t\t\tret=ssl3_get_cert_status(s);\n\t\t\tif (ret <= 0) goto end;\n\t\t\ts->state=SSL3_ST_CR_KEY_EXCH_A;\n\t\t\ts->init_num=0;\n\t\tbreak;\n#endif\n\n\t\tcase SSL3_ST_CR_FINISHED_A:\n\t\tcase SSL3_ST_CR_FINISHED_B:\n\n\t\t\tret=ssl3_get_finished(s,SSL3_ST_CR_FINISHED_A,\n\t\t\t\tSSL3_ST_CR_FINISHED_B);\n\t\t\tif (ret <= 0) goto end;\n\n\t\t\tif (s->hit)\n\t\t\t\ts->state=SSL3_ST_CW_CHANGE_A;\n\t\t\telse\n\t\t\t\ts->state=SSL_ST_OK;\n\t\t\ts->init_num=0;\n\t\t\tbreak;\n\n\t\tcase SSL3_ST_CW_FLUSH:\n\t\t\ts->rwstate=SSL_WRITING;\n\t\t\tif (BIO_flush(s->wbio) <= 0)\n\t\t\t\t{\n\t\t\t\tret= -1;\n\t\t\t\tgoto end;\n\t\t\t\t}\n\t\t\ts->rwstate=SSL_NOTHING;\n\t\t\ts->state=s->s3->tmp.next_state;\n\t\t\tbreak;\n\n\t\tcase SSL_ST_OK:\n\t\t\t/* clean a few things up */\n\t\t\tssl3_cleanup_key_block(s);\n\n\t\t\tif (s->init_buf != NULL)\n\t\t\t\t{\n\t\t\t\tBUF_MEM_free(s->init_buf);\n\t\t\t\ts->init_buf=NULL;\n\t\t\t\t}\n\n\t\t\t/* If we are not 'joining' the last two packets,\n\t\t\t * remove the buffering now */\n\t\t\tif (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER))\n\t\t\t\tssl_free_wbio_buffer(s);\n\t\t\t/* else do it later in ssl3_write */\n\n\t\t\ts->init_num=0;\n\t\t\ts->new_session=0;\n\n\t\t\tssl_update_cache(s,SSL_SESS_CACHE_CLIENT);\n\t\t\tif (s->hit) s->ctx->stats.sess_hit++;\n\n\t\t\tret=1;\n\t\t\t/* s->server=0; */\n\t\t\ts->handshake_func=ssl3_connect;\n\t\t\ts->ctx->stats.sess_connect_good++;\n\n\t\t\tif (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);\n\n\t\t\tgoto end;\n\t\t\t/* break; */\n\t\t\t\n\t\tdefault:\n\t\t\tSSLerr(SSL_F_SSL3_CONNECT,SSL_R_UNKNOWN_STATE);\n\t\t\tret= -1;\n\t\t\tgoto end;\n\t\t\t/* break; */\n\t\t\t}\n\n\t\t/* did we do anything */\n\t\tif (!s->s3->tmp.reuse_message && !skip)\n\t\t\t{\n\t\t\tif (s->debug)\n\t\t\t\t{\n\t\t\t\tif ((ret=BIO_flush(s->wbio)) <= 0)\n\t\t\t\t\tgoto end;\n\t\t\t\t}\n\n\t\t\tif ((cb != NULL) && (s->state != state))\n\t\t\t\t{\n\t\t\t\tnew_state=s->state;\n\t\t\t\ts->state=state;\n\t\t\t\tcb(s,SSL_CB_CONNECT_LOOP,1);\n\t\t\t\ts->state=new_state;\n\t\t\t\t}\n\t\t\t}\n\t\tskip=0;\n\t\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-326'], 'message': 'Fix for CVE-2014-0224\n\nOnly accept change cipher spec when it is expected instead of at any\ntime. This prevents premature setting of session keys before the master\nsecret is determined which an attacker could use as a MITM attack.\n\nThanks to KIKUCHI Masashi (Lepidum Co. Ltd.) for reporting this issue\nand providing the initial fix this patch is based on.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static BIGNUM *srp_Calc_k(BIGNUM *N, BIGNUM *g)\n\t{\n\t/* k = SHA1(N | PAD(g)) -- tls-srp draft 8 */\n\n\tunsigned char digest[SHA_DIGEST_LENGTH];\n\tunsigned char *tmp;\n\tEVP_MD_CTX ctxt;\n\tint longg ;\n\tint longN = BN_num_bytes(N);\n\n\tif ((tmp = OPENSSL_malloc(longN)) == NULL)\n\t\treturn NULL;\n\tBN_bn2bin(N,tmp) ;\n\n\tEVP_MD_CTX_init(&ctxt);\n\tEVP_DigestInit_ex(&ctxt, EVP_sha1(), NULL);\n\tEVP_DigestUpdate(&ctxt, tmp, longN);\n\n\tmemset(tmp, 0, longN);\n\tlongg = BN_bn2bin(g,tmp) ;\n /* use the zeros behind to pad on left */\n\tEVP_DigestUpdate(&ctxt, tmp + longg, longN-longg);\n\tEVP_DigestUpdate(&ctxt, tmp, longg);\n\tOPENSSL_free(tmp);\n\n\tEVP_DigestFinal_ex(&ctxt, digest, NULL);\n\tEVP_MD_CTX_cleanup(&ctxt);\n\treturn BN_bin2bn(digest, sizeof(digest), NULL);\t\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix SRP buffer overrun vulnerability.\n\nInvalid parameters passed to the SRP code can be overrun an internal\nbuffer. Add sanity check that g, A, B < N to SRP code.\n\nThanks to Sean Devlin and Watson Ladd of Cryptography Services, NCC\nGroup for reporting this issue.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ssl2_put_cipher_by_char(const SSL_CIPHER *c, unsigned char *p)\n\t{\n\tlong l;\n\n\tif (p != NULL)\n\t\t{\n\t\tl=c->id;\n\t\tif ((l & 0xff000000) != 0x02000000) return(0);\n\t\tp[0]=((unsigned char)(l>>16L))&0xFF;\n\t\tp[1]=((unsigned char)(l>> 8L))&0xFF;\n\t\tp[2]=((unsigned char)(l ))&0xFF;\n\t\t}\n\treturn(3);\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Support TLS_FALLBACK_SCSV.\n\nReviewed-by: Stephen Henson '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ssl_cipher_list_to_bytes(SSL *s,STACK_OF(SSL_CIPHER) *sk,unsigned char *p,\n\t\t\t int (*put_cb)(const SSL_CIPHER *, unsigned char *))\n\t{\n\tint i,j=0;\n\tSSL_CIPHER *c;\n\tunsigned char *q;\n\tint no_scsv = s->renegotiate;\n\t/* Set disabled masks for this session */\n\tssl_set_client_disabled(s);\n\n\tif (sk == NULL) return(0);\n\tq=p;\n\n\tfor (i=0; iid == SSL3_CK_SCSV)\n\t\t\t{\n\t\t\tif (no_scsv)\n\t\t\t\tcontinue;\n\t\t\telse\n\t\t\t\tno_scsv = 1;\n\t\t\t}\n#endif\n\t\tj = put_cb ? put_cb(c,p) : ssl_put_cipher_by_char(s,c,p);\n\t\tp+=j;\n\t\t}\n\t/* If p == q, no ciphers and caller indicates an error. Otherwise\n\t * add SCSV if not renegotiating.\n\t */\n\tif (p != q && !no_scsv)\n\t\t{\n\t\tstatic SSL_CIPHER scsv =\n\t\t\t{\n\t\t\t0, NULL, SSL3_CK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0\n\t\t\t};\n\t\tj = put_cb ? put_cb(&scsv,p) : ssl_put_cipher_by_char(s,&scsv,p);\n\t\tp+=j;\n#ifdef OPENSSL_RI_DEBUG\n\t\tfprintf(stderr, \"SCSV sent by client\\n\");\n#endif\n\t\t}\n\n\treturn(p-q);\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Support TLS_FALLBACK_SCSV.\n\nReviewed-by: Stephen Henson '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int MAIN(int argc, char **argv)\n\t{\n\tint off=0, clr = 0;\n\tSSL *con=NULL,*con2=NULL;\n\tX509_STORE *store = NULL;\n\tint s,k,width,state=0;\n\tchar *cbuf=NULL,*sbuf=NULL,*mbuf=NULL;\n\tint cbuf_len,cbuf_off;\n\tint sbuf_len,sbuf_off;\n\tfd_set readfds,writefds;\n\tshort port=PORT;\n\tint full_log=1;\n\tchar *host=SSL_HOST_NAME;\n\tchar *cert_file=NULL,*key_file=NULL;\n\tint cert_format = FORMAT_PEM, key_format = FORMAT_PEM;\n\tchar *passarg = NULL, *pass = NULL;\n\tX509 *cert = NULL;\n\tEVP_PKEY *key = NULL;\n\tchar *CApath=NULL,*CAfile=NULL,*cipher=NULL;\n\tint reconnect=0,badop=0,verify=SSL_VERIFY_NONE,bugs=0;\n\tint crlf=0;\n\tint write_tty,read_tty,write_ssl,read_ssl,tty_on,ssl_pending;\n\tSSL_CTX *ctx=NULL;\n\tint ret=1,in_init=1,i,nbio_test=0;\n\tint starttls_proto = PROTO_OFF;\n\tint prexit = 0, vflags = 0;\n\tSSL_METHOD *meth=NULL;\n#ifdef sock_type\n#undef sock_type\n#endif\n\tint sock_type=SOCK_STREAM;\n\tBIO *sbio;\n\tchar *inrand=NULL;\n\tint mbuf_len=0;\n\tstruct timeval timeout, *timeoutp;\n#ifndef OPENSSL_NO_ENGINE\n\tchar *engine_id=NULL;\n\tchar *ssl_client_engine_id=NULL;\n\tENGINE *ssl_client_engine=NULL;\n#endif\n\tENGINE *e=NULL;\n#if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_NETWARE)\n\tstruct timeval tv;\n#endif\n\n#ifndef OPENSSL_NO_TLSEXT\n\tchar *servername = NULL; \n tlsextctx tlsextcbp = \n {NULL,0};\n#endif\n\tchar *sess_in = NULL;\n\tchar *sess_out = NULL;\n\tstruct sockaddr peer;\n\tint peerlen = sizeof(peer);\n\tint enable_timeouts = 0 ;\n\tlong socket_mtu = 0;\n#ifndef OPENSSL_NO_JPAKE\n\tchar *jpake_secret = NULL;\n#endif\n\n\tmeth=SSLv23_client_method();\n\n\tapps_startup();\n\tc_Pause=0;\n\tc_quiet=0;\n\tc_ign_eof=0;\n\tc_debug=0;\n\tc_msg=0;\n\tc_showcerts=0;\n\n\tif (bio_err == NULL)\n\t\tbio_err=BIO_new_fp(stderr,BIO_NOCLOSE);\n\n\tif (!load_config(bio_err, NULL))\n\t\tgoto end;\n\n\tif (\t((cbuf=OPENSSL_malloc(BUFSIZZ)) == NULL) ||\n\t\t((sbuf=OPENSSL_malloc(BUFSIZZ)) == NULL) ||\n\t\t((mbuf=OPENSSL_malloc(BUFSIZZ)) == NULL))\n\t\t{\n\t\tBIO_printf(bio_err,\"out of memory\\n\");\n\t\tgoto end;\n\t\t}\n\n\tverify_depth=0;\n\tverify_error=X509_V_OK;\n#ifdef FIONBIO\n\tc_nbio=0;\n#endif\n\n\targc--;\n\targv++;\n\twhile (argc >= 1)\n\t\t{\n\t\tif\t(strcmp(*argv,\"-host\") == 0)\n\t\t\t{\n\t\t\tif (--argc < 1) goto bad;\n\t\t\thost= *(++argv);\n\t\t\t}\n\t\telse if\t(strcmp(*argv,\"-port\") == 0)\n\t\t\t{\n\t\t\tif (--argc < 1) goto bad;\n\t\t\tport=atoi(*(++argv));\n\t\t\tif (port == 0) goto bad;\n\t\t\t}\n\t\telse if (strcmp(*argv,\"-connect\") == 0)\n\t\t\t{\n\t\t\tif (--argc < 1) goto bad;\n\t\t\tif (!extract_host_port(*(++argv),&host,NULL,&port))\n\t\t\t\tgoto bad;\n\t\t\t}\n\t\telse if\t(strcmp(*argv,\"-verify\") == 0)\n\t\t\t{\n\t\t\tverify=SSL_VERIFY_PEER;\n\t\t\tif (--argc < 1) goto bad;\n\t\t\tverify_depth=atoi(*(++argv));\n\t\t\tBIO_printf(bio_err,\"verify depth is %d\\n\",verify_depth);\n\t\t\t}\n\t\telse if\t(strcmp(*argv,\"-cert\") == 0)\n\t\t\t{\n\t\t\tif (--argc < 1) goto bad;\n\t\t\tcert_file= *(++argv);\n\t\t\t}\n\t\telse if\t(strcmp(*argv,\"-sess_out\") == 0)\n\t\t\t{\n\t\t\tif (--argc < 1) goto bad;\n\t\t\tsess_out = *(++argv);\n\t\t\t}\n\t\telse if\t(strcmp(*argv,\"-sess_in\") == 0)\n\t\t\t{\n\t\t\tif (--argc < 1) goto bad;\n\t\t\tsess_in = *(++argv);\n\t\t\t}\n\t\telse if\t(strcmp(*argv,\"-certform\") == 0)\n\t\t\t{\n\t\t\tif (--argc < 1) goto bad;\n\t\t\tcert_format = str2fmt(*(++argv));\n\t\t\t}\n\t\telse if\t(strcmp(*argv,\"-crl_check\") == 0)\n\t\t\tvflags |= X509_V_FLAG_CRL_CHECK;\n\t\telse if\t(strcmp(*argv,\"-crl_check_all\") == 0)\n\t\t\tvflags |= X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL;\n\t\telse if\t(strcmp(*argv,\"-prexit\") == 0)\n\t\t\tprexit=1;\n\t\telse if\t(strcmp(*argv,\"-crlf\") == 0)\n\t\t\tcrlf=1;\n\t\telse if\t(strcmp(*argv,\"-quiet\") == 0)\n\t\t\t{\n\t\t\tc_quiet=1;\n\t\t\tc_ign_eof=1;\n\t\t\t}\n\t\telse if\t(strcmp(*argv,\"-ign_eof\") == 0)\n\t\t\tc_ign_eof=1;\n\t\telse if\t(strcmp(*argv,\"-no_ign_eof\") == 0)\n\t\t\tc_ign_eof=0;\n\t\telse if\t(strcmp(*argv,\"-pause\") == 0)\n\t\t\tc_Pause=1;\n\t\telse if\t(strcmp(*argv,\"-debug\") == 0)\n\t\t\tc_debug=1;\n#ifndef OPENSSL_NO_TLSEXT\n\t\telse if\t(strcmp(*argv,\"-tlsextdebug\") == 0)\n\t\t\tc_tlsextdebug=1;\n\t\telse if\t(strcmp(*argv,\"-status\") == 0)\n\t\t\tc_status_req=1;\n#endif\n#ifdef WATT32\n\t\telse if (strcmp(*argv,\"-wdebug\") == 0)\n\t\t\tdbug_init();\n#endif\n\t\telse if\t(strcmp(*argv,\"-msg\") == 0)\n\t\t\tc_msg=1;\n\t\telse if\t(strcmp(*argv,\"-showcerts\") == 0)\n\t\t\tc_showcerts=1;\n\t\telse if\t(strcmp(*argv,\"-nbio_test\") == 0)\n\t\t\tnbio_test=1;\n\t\telse if\t(strcmp(*argv,\"-state\") == 0)\n\t\t\tstate=1;\n#ifndef OPENSSL_NO_SSL2\n\t\telse if\t(strcmp(*argv,\"-ssl2\") == 0)\n\t\t\tmeth=SSLv2_client_method();\n#endif\n#ifndef OPENSSL_NO_SSL3\n\t\telse if\t(strcmp(*argv,\"-ssl3\") == 0)\n\t\t\tmeth=SSLv3_client_method();\n#endif\n#ifndef OPENSSL_NO_TLS1\n\t\telse if\t(strcmp(*argv,\"-tls1\") == 0)\n\t\t\tmeth=TLSv1_client_method();\n#endif\n#ifndef OPENSSL_NO_DTLS1\n\t\telse if\t(strcmp(*argv,\"-dtls1\") == 0)\n\t\t\t{\n\t\t\tmeth=DTLSv1_client_method();\n\t\t\tsock_type=SOCK_DGRAM;\n\t\t\t}\n\t\telse if (strcmp(*argv,\"-timeout\") == 0)\n\t\t\tenable_timeouts=1;\n\t\telse if (strcmp(*argv,\"-mtu\") == 0)\n\t\t\t{\n\t\t\tif (--argc < 1) goto bad;\n\t\t\tsocket_mtu = atol(*(++argv));\n\t\t\t}\n#endif\n\t\telse if (strcmp(*argv,\"-bugs\") == 0)\n\t\t\tbugs=1;\n\t\telse if\t(strcmp(*argv,\"-keyform\") == 0)\n\t\t\t{\n\t\t\tif (--argc < 1) goto bad;\n\t\t\tkey_format = str2fmt(*(++argv));\n\t\t\t}\n\t\telse if\t(strcmp(*argv,\"-pass\") == 0)\n\t\t\t{\n\t\t\tif (--argc < 1) goto bad;\n\t\t\tpassarg = *(++argv);\n\t\t\t}\n\t\telse if\t(strcmp(*argv,\"-key\") == 0)\n\t\t\t{\n\t\t\tif (--argc < 1) goto bad;\n\t\t\tkey_file= *(++argv);\n\t\t\t}\n\t\telse if\t(strcmp(*argv,\"-reconnect\") == 0)\n\t\t\t{\n\t\t\treconnect=5;\n\t\t\t}\n\t\telse if\t(strcmp(*argv,\"-CApath\") == 0)\n\t\t\t{\n\t\t\tif (--argc < 1) goto bad;\n\t\t\tCApath= *(++argv);\n\t\t\t}\n\t\telse if\t(strcmp(*argv,\"-CAfile\") == 0)\n\t\t\t{\n\t\t\tif (--argc < 1) goto bad;\n\t\t\tCAfile= *(++argv);\n\t\t\t}\n\t\telse if (strcmp(*argv,\"-no_tls1\") == 0)\n\t\t\toff|=SSL_OP_NO_TLSv1;\n\t\telse if (strcmp(*argv,\"-no_ssl3\") == 0)\n\t\t\toff|=SSL_OP_NO_SSLv3;\n\t\telse if (strcmp(*argv,\"-no_ssl2\") == 0)\n\t\t\toff|=SSL_OP_NO_SSLv2;\n#ifndef OPENSSL_NO_TLSEXT\n\t\telse if\t(strcmp(*argv,\"-no_ticket\") == 0)\n\t\t\t{ off|=SSL_OP_NO_TICKET; }\n#endif\n\t\telse if (strcmp(*argv,\"-serverpref\") == 0)\n\t\t\toff|=SSL_OP_CIPHER_SERVER_PREFERENCE;\n\t\telse if (strcmp(*argv,\"-legacy_renegotiation\") == 0)\n\t\t\toff|=SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;\n\t\telse if\t(strcmp(*argv,\"-legacy_server_connect\") == 0)\n\t\t\t{ off|=SSL_OP_LEGACY_SERVER_CONNECT; }\n\t\telse if\t(strcmp(*argv,\"-no_legacy_server_connect\") == 0)\n\t\t\t{ clr|=SSL_OP_LEGACY_SERVER_CONNECT; }\n\t\telse if\t(strcmp(*argv,\"-cipher\") == 0)\n\t\t\t{\n\t\t\tif (--argc < 1) goto bad;\n\t\t\tcipher= *(++argv);\n\t\t\t}\n#ifdef FIONBIO\n\t\telse if (strcmp(*argv,\"-nbio\") == 0)\n\t\t\t{ c_nbio=1; }\n#endif\n\t\telse if\t(strcmp(*argv,\"-starttls\") == 0)\n\t\t\t{\n\t\t\tif (--argc < 1) goto bad;\n\t\t\t++argv;\n\t\t\tif (strcmp(*argv,\"smtp\") == 0)\n\t\t\t\tstarttls_proto = PROTO_SMTP;\n\t\t\telse if (strcmp(*argv,\"pop3\") == 0)\n\t\t\t\tstarttls_proto = PROTO_POP3;\n\t\t\telse if (strcmp(*argv,\"imap\") == 0)\n\t\t\t\tstarttls_proto = PROTO_IMAP;\n\t\t\telse if (strcmp(*argv,\"ftp\") == 0)\n\t\t\t\tstarttls_proto = PROTO_FTP;\n\t\t\telse if (strcmp(*argv, \"xmpp\") == 0)\n\t\t\t\tstarttls_proto = PROTO_XMPP;\n\t\t\telse\n\t\t\t\tgoto bad;\n\t\t\t}\n#ifndef OPENSSL_NO_ENGINE\n\t\telse if\t(strcmp(*argv,\"-engine\") == 0)\n\t\t\t{\n\t\t\tif (--argc < 1) goto bad;\n\t\t\tengine_id = *(++argv);\n\t\t\t}\n\t\telse if\t(strcmp(*argv,\"-ssl_client_engine\") == 0)\n\t\t\t{\n\t\t\tif (--argc < 1) goto bad;\n\t\t\tssl_client_engine_id = *(++argv);\n\t\t\t}\n#endif\n\t\telse if (strcmp(*argv,\"-rand\") == 0)\n\t\t\t{\n\t\t\tif (--argc < 1) goto bad;\n\t\t\tinrand= *(++argv);\n\t\t\t}\n#ifndef OPENSSL_NO_TLSEXT\n\t\telse if (strcmp(*argv,\"-servername\") == 0)\n\t\t\t{\n\t\t\tif (--argc < 1) goto bad;\n\t\t\tservername= *(++argv);\n\t\t\t/* meth=TLSv1_client_method(); */\n\t\t\t}\n#endif\n#ifndef OPENSSL_NO_JPAKE\n\t\telse if (strcmp(*argv,\"-jpake\") == 0)\n\t\t\t{\n\t\t\tif (--argc < 1) goto bad;\n\t\t\tjpake_secret = *++argv;\n\t\t\t}\n#endif\n\t\telse\n\t\t\t{\n\t\t\tBIO_printf(bio_err,\"unknown option %s\\n\",*argv);\n\t\t\tbadop=1;\n\t\t\tbreak;\n\t\t\t}\n\t\targc--;\n\t\targv++;\n\t\t}\n\tif (badop)\n\t\t{\nbad:\n\t\tsc_usage();\n\t\tgoto end;\n\t\t}\n\n\tOpenSSL_add_ssl_algorithms();\n\tSSL_load_error_strings();\n\n#ifndef OPENSSL_NO_ENGINE\n e = setup_engine(bio_err, engine_id, 1);\n\tif (ssl_client_engine_id)\n\t\t{\n\t\tssl_client_engine = ENGINE_by_id(ssl_client_engine_id);\n\t\tif (!ssl_client_engine)\n\t\t\t{\n\t\t\tBIO_printf(bio_err,\n\t\t\t\t\t\"Error getting client auth engine\\n\");\n\t\t\tgoto end;\n\t\t\t}\n\t\t}\n#endif\n\tif (!app_passwd(bio_err, passarg, NULL, &pass, NULL))\n\t\t{\n\t\tBIO_printf(bio_err, \"Error getting password\\n\");\n\t\tgoto end;\n\t\t}\n\n\tif (key_file == NULL)\n\t\tkey_file = cert_file;\n\n\n\tif (key_file)\n\n\t\t{\n\n\t\tkey = load_key(bio_err, key_file, key_format, 0, pass, e,\n\t\t\t \"client certificate private key file\");\n\t\tif (!key)\n\t\t\t{\n\t\t\tERR_print_errors(bio_err);\n\t\t\tgoto end;\n\t\t\t}\n\n\t\t}\n\n\tif (cert_file)\n\n\t\t{\n\t\tcert = load_cert(bio_err,cert_file,cert_format,\n\t\t\t\tNULL, e, \"client certificate file\");\n\n\t\tif (!cert)\n\t\t\t{\n\t\t\tERR_print_errors(bio_err);\n\t\t\tgoto end;\n\t\t\t}\n\t\t}\n\n\tif (!app_RAND_load_file(NULL, bio_err, 1) && inrand == NULL\n\t\t&& !RAND_status())\n\t\t{\n\t\tBIO_printf(bio_err,\"warning, not much extra random data, consider using the -rand option\\n\");\n\t\t}\n\tif (inrand != NULL)\n\t\tBIO_printf(bio_err,\"%ld semi-random bytes loaded\\n\",\n\t\t\tapp_RAND_load_files(inrand));\n\n\tif (bio_c_out == NULL)\n\t\t{\n\t\tif (c_quiet && !c_debug && !c_msg)\n\t\t\t{\n\t\t\tbio_c_out=BIO_new(BIO_s_null());\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tif (bio_c_out == NULL)\n\t\t\t\tbio_c_out=BIO_new_fp(stdout,BIO_NOCLOSE);\n\t\t\t}\n\t\t}\n\n\tctx=SSL_CTX_new(meth);\n\tif (ctx == NULL)\n\t\t{\n\t\tERR_print_errors(bio_err);\n\t\tgoto end;\n\t\t}\n\n#ifndef OPENSSL_NO_ENGINE\n\tif (ssl_client_engine)\n\t\t{\n\t\tif (!SSL_CTX_set_client_cert_engine(ctx, ssl_client_engine))\n\t\t\t{\n\t\t\tBIO_puts(bio_err, \"Error setting client auth engine\\n\");\n\t\t\tERR_print_errors(bio_err);\n\t\t\tENGINE_free(ssl_client_engine);\n\t\t\tgoto end;\n\t\t\t}\n\t\tENGINE_free(ssl_client_engine);\n\t\t}\n#endif\n\n\tif (bugs)\n\t\tSSL_CTX_set_options(ctx,SSL_OP_ALL|off);\n\telse\n\t\tSSL_CTX_set_options(ctx,off);\n\n\tif (clr)\n\t\tSSL_CTX_clear_options(ctx, clr);\n\t/* DTLS: partial reads end up discarding unread UDP bytes :-( \n\t * Setting read ahead solves this problem.\n\t */\n\tif (sock_type == SOCK_DGRAM) SSL_CTX_set_read_ahead(ctx, 1);\n\n\tif (state) SSL_CTX_set_info_callback(ctx,apps_ssl_info_callback);\n\tif (cipher != NULL)\n\t\tif(!SSL_CTX_set_cipher_list(ctx,cipher)) {\n\t\tBIO_printf(bio_err,\"error setting cipher list\\n\");\n\t\tERR_print_errors(bio_err);\n\t\tgoto end;\n\t}\n#if 0\n\telse\n\t\tSSL_CTX_set_cipher_list(ctx,getenv(\"SSL_CIPHER\"));\n#endif\n\n\tSSL_CTX_set_verify(ctx,verify,verify_callback);\n\tif (!set_cert_key_stuff(ctx,cert,key))\n\t\tgoto end;\n\n\tif ((!SSL_CTX_load_verify_locations(ctx,CAfile,CApath)) ||\n\t\t(!SSL_CTX_set_default_verify_paths(ctx)))\n\t\t{\n\t\t/* BIO_printf(bio_err,\"error setting default verify locations\\n\"); */\n\t\tERR_print_errors(bio_err);\n\t\t/* goto end; */\n\t\t}\n\n\tstore = SSL_CTX_get_cert_store(ctx);\n\tX509_STORE_set_flags(store, vflags);\n#ifndef OPENSSL_NO_TLSEXT\n\tif (servername != NULL)\n\t\t{\n\t\ttlsextcbp.biodebug = bio_err;\n\t\tSSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);\n\t\tSSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);\n\t\t}\n#endif\n\n\tcon=SSL_new(ctx);\n\tif (sess_in)\n\t\t{\n\t\tSSL_SESSION *sess;\n\t\tBIO *stmp = BIO_new_file(sess_in, \"r\");\n\t\tif (!stmp)\n\t\t\t{\n\t\t\tBIO_printf(bio_err, \"Can't open session file %s\\n\",\n\t\t\t\t\t\tsess_in);\n\t\t\tERR_print_errors(bio_err);\n\t\t\tgoto end;\n\t\t\t}\n\t\tsess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);\n\t\tBIO_free(stmp);\n\t\tif (!sess)\n\t\t\t{\n\t\t\tBIO_printf(bio_err, \"Can't open session file %s\\n\",\n\t\t\t\t\t\tsess_in);\n\t\t\tERR_print_errors(bio_err);\n\t\t\tgoto end;\n\t\t\t}\n\t\tSSL_set_session(con, sess);\n\t\tSSL_SESSION_free(sess);\n\t\t}\n#ifndef OPENSSL_NO_TLSEXT\n\tif (servername != NULL)\n\t\t{\n\t\tif (!SSL_set_tlsext_host_name(con,servername))\n\t\t\t{\n\t\t\tBIO_printf(bio_err,\"Unable to set TLS servername extension.\\n\");\n\t\t\tERR_print_errors(bio_err);\n\t\t\tgoto end;\n\t\t\t}\n\t\t}\n#endif\n\n#ifndef OPENSSL_NO_KRB5\n\tif (con && (con->kssl_ctx = kssl_ctx_new()) != NULL)\n {\n kssl_ctx_setstring(con->kssl_ctx, KSSL_SERVER, host);\n\t\t}\n#endif\t/* OPENSSL_NO_KRB5 */\n/*\tSSL_set_cipher_list(con,\"RC4-MD5\"); */\n\nre_start:\n\n\tif (init_client(&s,host,port,sock_type) == 0)\n\t\t{\n\t\tBIO_printf(bio_err,\"connect:errno=%d\\n\",get_last_socket_error());\n\t\tSHUTDOWN(s);\n\t\tgoto end;\n\t\t}\n\tBIO_printf(bio_c_out,\"CONNECTED(%08X)\\n\",s);\n\n#ifdef FIONBIO\n\tif (c_nbio)\n\t\t{\n\t\tunsigned long l=1;\n\t\tBIO_printf(bio_c_out,\"turning on non blocking io\\n\");\n\t\tif (BIO_socket_ioctl(s,FIONBIO,&l) < 0)\n\t\t\t{\n\t\t\tERR_print_errors(bio_err);\n\t\t\tgoto end;\n\t\t\t}\n\t\t}\n#endif \n\tif (c_Pause & 0x01) con->debug=1;\n\n\tif ( SSL_version(con) == DTLS1_VERSION)\n\t\t{\n\n\t\tsbio=BIO_new_dgram(s,BIO_NOCLOSE);\n\t\tif (getsockname(s, &peer, (void *)&peerlen) < 0)\n\t\t\t{\n\t\t\tBIO_printf(bio_err, \"getsockname:errno=%d\\n\",\n\t\t\t\tget_last_socket_error());\n\t\t\tSHUTDOWN(s);\n\t\t\tgoto end;\n\t\t\t}\n\n\t\t(void)BIO_ctrl_set_connected(sbio, 1, &peer);\n\n\t\tif ( enable_timeouts)\n\t\t\t{\n\t\t\ttimeout.tv_sec = 0;\n\t\t\ttimeout.tv_usec = DGRAM_RCV_TIMEOUT;\n\t\t\tBIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);\n\t\t\t\n\t\t\ttimeout.tv_sec = 0;\n\t\t\ttimeout.tv_usec = DGRAM_SND_TIMEOUT;\n\t\t\tBIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);\n\t\t\t}\n\n\t\tif (socket_mtu > 28)\n\t\t\t{\n\t\t\tSSL_set_options(con, SSL_OP_NO_QUERY_MTU);\n\t\t\tSSL_set_mtu(con, socket_mtu - 28);\n\t\t\t}\n\t\telse\n\t\t\t/* want to do MTU discovery */\n\t\t\tBIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);\n\t\t}\n\telse\n\t\tsbio=BIO_new_socket(s,BIO_NOCLOSE);\n\n\tif (nbio_test)\n\t\t{\n\t\tBIO *test;\n\n\t\ttest=BIO_new(BIO_f_nbio_test());\n\t\tsbio=BIO_push(test,sbio);\n\t\t}\n\n\tif (c_debug)\n\t\t{\n\t\tcon->debug=1;\n\t\tBIO_set_callback(sbio,bio_dump_callback);\n\t\tBIO_set_callback_arg(sbio,(char *)bio_c_out);\n\t\t}\n\tif (c_msg)\n\t\t{\n\t\tSSL_set_msg_callback(con, msg_cb);\n\t\tSSL_set_msg_callback_arg(con, bio_c_out);\n\t\t}\n#ifndef OPENSSL_NO_TLSEXT\n\tif (c_tlsextdebug)\n\t\t{\n\t\tSSL_set_tlsext_debug_callback(con, tlsext_cb);\n\t\tSSL_set_tlsext_debug_arg(con, bio_c_out);\n\t\t}\n\tif (c_status_req)\n\t\t{\n\t\tSSL_set_tlsext_status_type(con, TLSEXT_STATUSTYPE_ocsp);\n\t\tSSL_CTX_set_tlsext_status_cb(ctx, ocsp_resp_cb);\n\t\tSSL_CTX_set_tlsext_status_arg(ctx, bio_c_out);\n#if 0\n{\nSTACK_OF(OCSP_RESPID) *ids = sk_OCSP_RESPID_new_null();\nOCSP_RESPID *id = OCSP_RESPID_new();\nid->value.byKey = ASN1_OCTET_STRING_new();\nid->type = V_OCSP_RESPID_KEY;\nASN1_STRING_set(id->value.byKey, \"Hello World\", -1);\nsk_OCSP_RESPID_push(ids, id);\nSSL_set_tlsext_status_ids(con, ids);\n}\n#endif\n\t\t}\n#endif\n#ifndef OPENSSL_NO_JPAKE\n\tif (jpake_secret)\n\t\tjpake_client_auth(bio_c_out, sbio, jpake_secret);\n#endif\n\n\tSSL_set_bio(con,sbio,sbio);\n\tSSL_set_connect_state(con);\n\n\t/* ok, lets connect */\n\twidth=SSL_get_fd(con)+1;\n\n\tread_tty=1;\n\twrite_tty=0;\n\ttty_on=0;\n\tread_ssl=1;\n\twrite_ssl=1;\n\t\n\tcbuf_len=0;\n\tcbuf_off=0;\n\tsbuf_len=0;\n\tsbuf_off=0;\n\n\t/* This is an ugly hack that does a lot of assumptions */\n\t/* We do have to handle multi-line responses which may come\n \t in a single packet or not. We therefore have to use\n\t BIO_gets() which does need a buffering BIO. So during\n\t the initial chitchat we do push a buffering BIO into the\n\t chain that is removed again later on to not disturb the\n\t rest of the s_client operation. */\n\tif (starttls_proto == PROTO_SMTP)\n\t\t{\n\t\tint foundit=0;\n\t\tBIO *fbio = BIO_new(BIO_f_buffer());\n\t\tBIO_push(fbio, sbio);\n\t\t/* wait for multi-line response to end from SMTP */\n\t\tdo\n\t\t\t{\n\t\t\tmbuf_len = BIO_gets(fbio,mbuf,BUFSIZZ);\n\t\t\t}\n\t\twhile (mbuf_len>3 && mbuf[3]=='-');\n\t\t/* STARTTLS command requires EHLO... */\n\t\tBIO_printf(fbio,\"EHLO openssl.client.net\\r\\n\");\n\t\t(void)BIO_flush(fbio);\n\t\t/* wait for multi-line response to end EHLO SMTP response */\n\t\tdo\n\t\t\t{\n\t\t\tmbuf_len = BIO_gets(fbio,mbuf,BUFSIZZ);\n\t\t\tif (strstr(mbuf,\"STARTTLS\"))\n\t\t\t\tfoundit=1;\n\t\t\t}\n\t\twhile (mbuf_len>3 && mbuf[3]=='-');\n\t\t(void)BIO_flush(fbio);\n\t\tBIO_pop(fbio);\n\t\tBIO_free(fbio);\n\t\tif (!foundit)\n\t\t\tBIO_printf(bio_err,\n\t\t\t\t \"didn't found starttls in server response,\"\n\t\t\t\t \" try anyway...\\n\");\n\t\tBIO_printf(sbio,\"STARTTLS\\r\\n\");\n\t\tBIO_read(sbio,sbuf,BUFSIZZ);\n\t\t}\n\telse if (starttls_proto == PROTO_POP3)\n\t\t{\n\t\tBIO_read(sbio,mbuf,BUFSIZZ);\n\t\tBIO_printf(sbio,\"STLS\\r\\n\");\n\t\tBIO_read(sbio,sbuf,BUFSIZZ);\n\t\t}\n\telse if (starttls_proto == PROTO_IMAP)\n\t\t{\n\t\tint foundit=0;\n\t\tBIO *fbio = BIO_new(BIO_f_buffer());\n\t\tBIO_push(fbio, sbio);\n\t\tBIO_gets(fbio,mbuf,BUFSIZZ);\n\t\t/* STARTTLS command requires CAPABILITY... */\n\t\tBIO_printf(fbio,\". CAPABILITY\\r\\n\");\n\t\t(void)BIO_flush(fbio);\n\t\t/* wait for multi-line CAPABILITY response */\n\t\tdo\n\t\t\t{\n\t\t\tmbuf_len = BIO_gets(fbio,mbuf,BUFSIZZ);\n\t\t\tif (strstr(mbuf,\"STARTTLS\"))\n\t\t\t\tfoundit=1;\n\t\t\t}\n\t\twhile (mbuf_len>3 && mbuf[0]!='.');\n\t\t(void)BIO_flush(fbio);\n\t\tBIO_pop(fbio);\n\t\tBIO_free(fbio);\n\t\tif (!foundit)\n\t\t\tBIO_printf(bio_err,\n\t\t\t\t \"didn't found STARTTLS in server response,\"\n\t\t\t\t \" try anyway...\\n\");\n\t\tBIO_printf(sbio,\". STARTTLS\\r\\n\");\n\t\tBIO_read(sbio,sbuf,BUFSIZZ);\n\t\t}\n\telse if (starttls_proto == PROTO_FTP)\n\t\t{\n\t\tBIO *fbio = BIO_new(BIO_f_buffer());\n\t\tBIO_push(fbio, sbio);\n\t\t/* wait for multi-line response to end from FTP */\n\t\tdo\n\t\t\t{\n\t\t\tmbuf_len = BIO_gets(fbio,mbuf,BUFSIZZ);\n\t\t\t}\n\t\twhile (mbuf_len>3 && mbuf[3]=='-');\n\t\t(void)BIO_flush(fbio);\n\t\tBIO_pop(fbio);\n\t\tBIO_free(fbio);\n\t\tBIO_printf(sbio,\"AUTH TLS\\r\\n\");\n\t\tBIO_read(sbio,sbuf,BUFSIZZ);\n\t\t}\n\tif (starttls_proto == PROTO_XMPP)\n\t\t{\n\t\tint seen = 0;\n\t\tBIO_printf(sbio,\"\", host);\n\t\tseen = BIO_read(sbio,mbuf,BUFSIZZ);\n\t\tmbuf[seen] = 0;\n\t\twhile (!strstr(mbuf, \"\"))\n\t\t\t\tgoto shut;\n\t\t\tseen = BIO_read(sbio,mbuf,BUFSIZZ);\n\t\t\tmbuf[seen] = 0;\n\t\t\t}\n\t\tBIO_printf(sbio, \"\");\n\t\tseen = BIO_read(sbio,sbuf,BUFSIZZ);\n\t\tsbuf[seen] = 0;\n\t\tif (!strstr(sbuf, \" 0) full_log--;\n\n\t\t\t\tif (starttls_proto)\n\t\t\t\t\t{\n\t\t\t\t\tBIO_printf(bio_err,\"%s\",mbuf);\n\t\t\t\t\t/* We don't need to know any more */\n\t\t\t\t\tstarttls_proto = PROTO_OFF;\n\t\t\t\t\t}\n\n\t\t\t\tif (reconnect)\n\t\t\t\t\t{\n\t\t\t\t\treconnect--;\n\t\t\t\t\tBIO_printf(bio_c_out,\"drop connection and then reconnect\\n\");\n\t\t\t\t\tSSL_shutdown(con);\n\t\t\t\t\tSSL_set_connect_state(con);\n\t\t\t\t\tSHUTDOWN(SSL_get_fd(con));\n\t\t\t\t\tgoto re_start;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\tssl_pending = read_ssl && SSL_pending(con);\n\n\t\tif (!ssl_pending)\n\t\t\t{\n#if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYS_NETWARE)\n\t\t\tif (tty_on)\n\t\t\t\t{\n\t\t\t\tif (read_tty) FD_SET(fileno(stdin),&readfds);\n\t\t\t\tif (write_tty) FD_SET(fileno(stdout),&writefds);\n\t\t\t\t}\n\t\t\tif (read_ssl)\n\t\t\t\tFD_SET(SSL_get_fd(con),&readfds);\n\t\t\tif (write_ssl)\n\t\t\t\tFD_SET(SSL_get_fd(con),&writefds);\n#else\n\t\t\tif(!tty_on || !write_tty) {\n\t\t\t\tif (read_ssl)\n\t\t\t\t\tFD_SET(SSL_get_fd(con),&readfds);\n\t\t\t\tif (write_ssl)\n\t\t\t\t\tFD_SET(SSL_get_fd(con),&writefds);\n\t\t\t}\n#endif\n/*\t\t\tprintf(\"mode tty(%d %d%d) ssl(%d%d)\\n\",\n\t\t\t\ttty_on,read_tty,write_tty,read_ssl,write_ssl);*/\n\n\t\t\t/* Note: under VMS with SOCKETSHR the second parameter\n\t\t\t * is currently of type (int *) whereas under other\n\t\t\t * systems it is (void *) if you don't have a cast it\n\t\t\t * will choke the compiler: if you do have a cast then\n\t\t\t * you can either go for (int *) or (void *).\n\t\t\t */\n#if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)\n /* Under Windows/DOS we make the assumption that we can\n\t\t\t * always write to the tty: therefore if we need to\n\t\t\t * write to the tty we just fall through. Otherwise\n\t\t\t * we timeout the select every second and see if there\n\t\t\t * are any keypresses. Note: this is a hack, in a proper\n\t\t\t * Windows application we wouldn't do this.\n\t\t\t */\n\t\t\ti=0;\n\t\t\tif(!write_tty) {\n\t\t\t\tif(read_tty) {\n\t\t\t\t\ttv.tv_sec = 1;\n\t\t\t\t\ttv.tv_usec = 0;\n\t\t\t\t\ti=select(width,(void *)&readfds,(void *)&writefds,\n\t\t\t\t\t\t NULL,&tv);\n#if defined(OPENSSL_SYS_WINCE) || defined(OPENSSL_SYS_MSDOS)\n\t\t\t\t\tif(!i && (!_kbhit() || !read_tty) ) continue;\n#else\n\t\t\t\t\tif(!i && (!((_kbhit()) || (WAIT_OBJECT_0 == WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE), 0))) || !read_tty) ) continue;\n#endif\n\t\t\t\t} else \ti=select(width,(void *)&readfds,(void *)&writefds,\n\t\t\t\t\t NULL,timeoutp);\n\t\t\t}\n#elif defined(OPENSSL_SYS_NETWARE)\n\t\t\tif(!write_tty) {\n\t\t\t\tif(read_tty) {\n\t\t\t\t\ttv.tv_sec = 1;\n\t\t\t\t\ttv.tv_usec = 0;\n\t\t\t\t\ti=select(width,(void *)&readfds,(void *)&writefds,\n\t\t\t\t\t\tNULL,&tv);\n\t\t\t\t} else \ti=select(width,(void *)&readfds,(void *)&writefds,\n\t\t\t\t\tNULL,timeoutp);\n\t\t\t}\n#else\n\t\t\ti=select(width,(void *)&readfds,(void *)&writefds,\n\t\t\t\t NULL,timeoutp);\n#endif\n\t\t\tif ( i < 0)\n\t\t\t\t{\n\t\t\t\tBIO_printf(bio_err,\"bad select %d\\n\",\n\t\t\t\tget_last_socket_error());\n\t\t\t\tgoto shut;\n\t\t\t\t/* goto end; */\n\t\t\t\t}\n\t\t\t}\n\n\t\tif ((SSL_version(con) == DTLS1_VERSION) && DTLSv1_handle_timeout(con) > 0)\n\t\t\t{\n\t\t\tBIO_printf(bio_err,\"TIMEOUT occured\\n\");\n\t\t\t}\n\n\t\tif (!ssl_pending && FD_ISSET(SSL_get_fd(con),&writefds))\n\t\t\t{\n\t\t\tk=SSL_write(con,&(cbuf[cbuf_off]),\n\t\t\t\t(unsigned int)cbuf_len);\n\t\t\tswitch (SSL_get_error(con,k))\n\t\t\t\t{\n\t\t\tcase SSL_ERROR_NONE:\n\t\t\t\tcbuf_off+=k;\n\t\t\t\tcbuf_len-=k;\n\t\t\t\tif (k <= 0) goto end;\n\t\t\t\t/* we have done a write(con,NULL,0); */\n\t\t\t\tif (cbuf_len <= 0)\n\t\t\t\t\t{\n\t\t\t\t\tread_tty=1;\n\t\t\t\t\twrite_ssl=0;\n\t\t\t\t\t}\n\t\t\t\telse /* if (cbuf_len > 0) */\n\t\t\t\t\t{\n\t\t\t\t\tread_tty=0;\n\t\t\t\t\twrite_ssl=1;\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase SSL_ERROR_WANT_WRITE:\n\t\t\t\tBIO_printf(bio_c_out,\"write W BLOCK\\n\");\n\t\t\t\twrite_ssl=1;\n\t\t\t\tread_tty=0;\n\t\t\t\tbreak;\n\t\t\tcase SSL_ERROR_WANT_READ:\n\t\t\t\tBIO_printf(bio_c_out,\"write R BLOCK\\n\");\n\t\t\t\twrite_tty=0;\n\t\t\t\tread_ssl=1;\n\t\t\t\twrite_ssl=0;\n\t\t\t\tbreak;\n\t\t\tcase SSL_ERROR_WANT_X509_LOOKUP:\n\t\t\t\tBIO_printf(bio_c_out,\"write X BLOCK\\n\");\n\t\t\t\tbreak;\n\t\t\tcase SSL_ERROR_ZERO_RETURN:\n\t\t\t\tif (cbuf_len != 0)\n\t\t\t\t\t{\n\t\t\t\t\tBIO_printf(bio_c_out,\"shutdown\\n\");\n\t\t\t\t\tgoto shut;\n\t\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\tread_tty=1;\n\t\t\t\t\twrite_ssl=0;\n\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\n\t\t\tcase SSL_ERROR_SYSCALL:\n\t\t\t\tif ((k != 0) || (cbuf_len != 0))\n\t\t\t\t\t{\n\t\t\t\t\tBIO_printf(bio_err,\"write:errno=%d\\n\",\n\t\t\t\t\t\tget_last_socket_error());\n\t\t\t\t\tgoto shut;\n\t\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\tread_tty=1;\n\t\t\t\t\twrite_ssl=0;\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase SSL_ERROR_SSL:\n\t\t\t\tERR_print_errors(bio_err);\n\t\t\t\tgoto shut;\n\t\t\t\t}\n\t\t\t}\n#if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_NETWARE)\n\t\t/* Assume Windows/DOS can always write */\n\t\telse if (!ssl_pending && write_tty)\n#else\n\t\telse if (!ssl_pending && FD_ISSET(fileno(stdout),&writefds))\n#endif\n\t\t\t{\n#ifdef CHARSET_EBCDIC\n\t\t\tascii2ebcdic(&(sbuf[sbuf_off]),&(sbuf[sbuf_off]),sbuf_len);\n#endif\n\t\t\ti=write(fileno(stdout),&(sbuf[sbuf_off]),sbuf_len);\n\n\t\t\tif (i <= 0)\n\t\t\t\t{\n\t\t\t\tBIO_printf(bio_c_out,\"DONE\\n\");\n\t\t\t\tgoto shut;\n\t\t\t\t/* goto end; */\n\t\t\t\t}\n\n\t\t\tsbuf_len-=i;;\n\t\t\tsbuf_off+=i;\n\t\t\tif (sbuf_len <= 0)\n\t\t\t\t{\n\t\t\t\tread_ssl=1;\n\t\t\t\twrite_tty=0;\n\t\t\t\t}\n\t\t\t}\n\t\telse if (ssl_pending || FD_ISSET(SSL_get_fd(con),&readfds))\n\t\t\t{\n#ifdef RENEG\n{ static int iiii; if (++iiii == 52) { SSL_renegotiate(con); iiii=0; } }\n#endif\n#if 1\n\t\t\tk=SSL_read(con,sbuf,1024 /* BUFSIZZ */ );\n#else\n/* Demo for pending and peek :-) */\n\t\t\tk=SSL_read(con,sbuf,16);\n{ char zbuf[10240]; \nprintf(\"read=%d pending=%d peek=%d\\n\",k,SSL_pending(con),SSL_peek(con,zbuf,10240));\n}\n#endif\n\n\t\t\tswitch (SSL_get_error(con,k))\n\t\t\t\t{\n\t\t\tcase SSL_ERROR_NONE:\n\t\t\t\tif (k <= 0)\n\t\t\t\t\tgoto end;\n\t\t\t\tsbuf_off=0;\n\t\t\t\tsbuf_len=k;\n\n\t\t\t\tread_ssl=0;\n\t\t\t\twrite_tty=1;\n\t\t\t\tbreak;\n\t\t\tcase SSL_ERROR_WANT_WRITE:\n\t\t\t\tBIO_printf(bio_c_out,\"read W BLOCK\\n\");\n\t\t\t\twrite_ssl=1;\n\t\t\t\tread_tty=0;\n\t\t\t\tbreak;\n\t\t\tcase SSL_ERROR_WANT_READ:\n\t\t\t\tBIO_printf(bio_c_out,\"read R BLOCK\\n\");\n\t\t\t\twrite_tty=0;\n\t\t\t\tread_ssl=1;\n\t\t\t\tif ((read_tty == 0) && (write_ssl == 0))\n\t\t\t\t\twrite_ssl=1;\n\t\t\t\tbreak;\n\t\t\tcase SSL_ERROR_WANT_X509_LOOKUP:\n\t\t\t\tBIO_printf(bio_c_out,\"read X BLOCK\\n\");\n\t\t\t\tbreak;\n\t\t\tcase SSL_ERROR_SYSCALL:\n\t\t\t\tBIO_printf(bio_err,\"read:errno=%d\\n\",get_last_socket_error());\n\t\t\t\tgoto shut;\n\t\t\tcase SSL_ERROR_ZERO_RETURN:\n\t\t\t\tBIO_printf(bio_c_out,\"closed\\n\");\n\t\t\t\tgoto shut;\n\t\t\tcase SSL_ERROR_SSL:\n\t\t\t\tERR_print_errors(bio_err);\n\t\t\t\tgoto shut;\n\t\t\t\t/* break; */\n\t\t\t\t}\n\t\t\t}\n\n#if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)\n#if defined(OPENSSL_SYS_WINCE) || defined(OPENSSL_SYS_MSDOS)\n\t\telse if (_kbhit())\n#else\n\t\telse if ((_kbhit()) || (WAIT_OBJECT_0 == WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE), 0)))\n#endif\n#elif defined (OPENSSL_SYS_NETWARE)\n else if (_kbhit())\n#else\n\t\telse if (FD_ISSET(fileno(stdin),&readfds))\n#endif\n\t\t\t{\n\t\t\tif (crlf)\n\t\t\t\t{\n\t\t\t\tint j, lf_num;\n\n\t\t\t\ti=read(fileno(stdin),cbuf,BUFSIZZ/2);\n\t\t\t\tlf_num = 0;\n\t\t\t\t/* both loops are skipped when i <= 0 */\n\t\t\t\tfor (j = 0; j < i; j++)\n\t\t\t\t\tif (cbuf[j] == '\\n')\n\t\t\t\t\t\tlf_num++;\n\t\t\t\tfor (j = i-1; j >= 0; j--)\n\t\t\t\t\t{\n\t\t\t\t\tcbuf[j+lf_num] = cbuf[j];\n\t\t\t\t\tif (cbuf[j] == '\\n')\n\t\t\t\t\t\t{\n\t\t\t\t\t\tlf_num--;\n\t\t\t\t\t\ti++;\n\t\t\t\t\t\tcbuf[j+lf_num] = '\\r';\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tassert(lf_num == 0);\n\t\t\t\t}\n\t\t\telse\n\t\t\t\ti=read(fileno(stdin),cbuf,BUFSIZZ);\n\n\t\t\tif ((!c_ign_eof) && ((i <= 0) || (cbuf[0] == 'Q')))\n\t\t\t\t{\n\t\t\t\tBIO_printf(bio_err,\"DONE\\n\");\n\t\t\t\tgoto shut;\n\t\t\t\t}\n\n\t\t\tif ((!c_ign_eof) && (cbuf[0] == 'R'))\n\t\t\t\t{\n\t\t\t\tBIO_printf(bio_err,\"RENEGOTIATING\\n\");\n\t\t\t\tSSL_renegotiate(con);\n\t\t\t\tcbuf_len=0;\n\t\t\t\t}\n\t\t\telse\n\t\t\t\t{\n\t\t\t\tcbuf_len=i;\n\t\t\t\tcbuf_off=0;\n#ifdef CHARSET_EBCDIC\n\t\t\t\tebcdic2ascii(cbuf, cbuf, i);\n#endif\n\t\t\t\t}\n\n\t\t\twrite_ssl=1;\n\t\t\tread_tty=0;\n\t\t\t}\n\t\t}\nshut:\n\tSSL_shutdown(con);\n\tSHUTDOWN(SSL_get_fd(con));\n\tret=0;\nend:\n\tif(prexit) print_stuff(bio_c_out,con,1);\n\tif (con != NULL) SSL_free(con);\n\tif (con2 != NULL) SSL_free(con2);\n\tif (ctx != NULL) SSL_CTX_free(ctx);\n\tif (cert)\n\t\tX509_free(cert);\n\tif (key)\n\t\tEVP_PKEY_free(key);\n\tif (pass)\n\t\tOPENSSL_free(pass);\n\tif (cbuf != NULL) { OPENSSL_cleanse(cbuf,BUFSIZZ); OPENSSL_free(cbuf); }\n\tif (sbuf != NULL) { OPENSSL_cleanse(sbuf,BUFSIZZ); OPENSSL_free(sbuf); }\n\tif (mbuf != NULL) { OPENSSL_cleanse(mbuf,BUFSIZZ); OPENSSL_free(mbuf); }\n\tif (bio_c_out != NULL)\n\t\t{\n\t\tBIO_free(bio_c_out);\n\t\tbio_c_out=NULL;\n\t\t}\n\tapps_shutdown();\n\tOPENSSL_EXIT(ret);\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Support TLS_FALLBACK_SCSV.\n\nReviewed-by: Stephen Henson '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ssl_parse_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al)\n\t{\n\tunsigned short length;\n\tunsigned short type;\n\tunsigned short size;\n\tunsigned char *data = *p;\n\tint tlsext_servername = 0;\n\tint renegotiate_seen = 0;\n\n#ifndef OPENSSL_NO_NEXTPROTONEG\n\ts->s3->next_proto_neg_seen = 0;\n#endif\n\n#ifndef OPENSSL_NO_HEARTBEATS\n\ts->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |\n\t SSL_TLSEXT_HB_DONT_SEND_REQUESTS);\n#endif\n\n\tif (data >= (d+n-2))\n\t\tgoto ri_check;\n\n\tn2s(data,length);\n\tif (data+length != d+n)\n\t\t{\n\t\t*al = SSL_AD_DECODE_ERROR;\n\t\treturn 0;\n\t\t}\n\n\twhile(data <= (d+n-4))\n\t\t{\n\t\tn2s(data,type);\n\t\tn2s(data,size);\n\n\t\tif (data+size > (d+n))\n\t \t\tgoto ri_check;\n\n\t\tif (s->tlsext_debug_cb)\n\t\t\ts->tlsext_debug_cb(s, 1, type, data, size,\n\t\t\t\t\t\ts->tlsext_debug_arg);\n\n\t\tif (type == TLSEXT_TYPE_server_name)\n\t\t\t{\n\t\t\tif (s->tlsext_hostname == NULL || size > 0)\n\t\t\t\t{\n\t\t\t\t*al = TLS1_AD_UNRECOGNIZED_NAME;\n\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\ttlsext_servername = 1; \n\t\t\t}\n\n#ifndef OPENSSL_NO_EC\n\t\telse if (type == TLSEXT_TYPE_ec_point_formats)\n\t\t\t{\n\t\t\tunsigned char *sdata = data;\n\t\t\tint ecpointformatlist_length = *(sdata++);\n\n\t\t\tif (ecpointformatlist_length != size - 1 || \n\t\t\t\tecpointformatlist_length < 1)\n\t\t\t\t{\n\t\t\t\t*al = TLS1_AD_DECODE_ERROR;\n\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\tif (!s->hit)\n\t\t\t\t{\n\t\t\t\ts->session->tlsext_ecpointformatlist_length = 0;\n\t\t\t\tif (s->session->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->session->tlsext_ecpointformatlist);\n\t\t\t\tif ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)\n\t\t\t\t\t{\n\t\t\t\t\t*al = TLS1_AD_INTERNAL_ERROR;\n\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\t\t\t\ts->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;\n\t\t\t\tmemcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);\n\t\t\t\t}\n#if 0\n\t\t\tfprintf(stderr,\"ssl_parse_serverhello_tlsext s->session->tlsext_ecpointformatlist \");\n\t\t\tsdata = s->session->tlsext_ecpointformatlist;\n\t\t\tfor (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)\n\t\t\t\tfprintf(stderr,\"%i \",*(sdata++));\n\t\t\tfprintf(stderr,\"\\n\");\n#endif\n\t\t\t}\n#endif /* OPENSSL_NO_EC */\n\n\t\telse if (type == TLSEXT_TYPE_session_ticket)\n\t\t\t{\n\t\t\tif (s->tls_session_ticket_ext_cb &&\n\t\t\t !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))\n\t\t\t\t{\n\t\t\t\t*al = TLS1_AD_INTERNAL_ERROR;\n\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\tif ((SSL_get_options(s) & SSL_OP_NO_TICKET)\n\t\t\t\t|| (size > 0))\n\t\t\t\t{\n\t\t\t\t*al = TLS1_AD_UNSUPPORTED_EXTENSION;\n\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\ts->tlsext_ticket_expected = 1;\n\t\t\t}\n#ifdef TLSEXT_TYPE_opaque_prf_input\n\t\telse if (type == TLSEXT_TYPE_opaque_prf_input &&\n\t s->version != DTLS1_VERSION)\n\t\t\t{\n\t\t\tunsigned char *sdata = data;\n\n\t\t\tif (size < 2)\n\t\t\t\t{\n\t\t\t\t*al = SSL_AD_DECODE_ERROR;\n\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\tn2s(sdata, s->s3->server_opaque_prf_input_len);\n\t\t\tif (s->s3->server_opaque_prf_input_len != size - 2)\n\t\t\t\t{\n\t\t\t\t*al = SSL_AD_DECODE_ERROR;\n\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\n\t\t\tif (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */\n\t\t\t\tOPENSSL_free(s->s3->server_opaque_prf_input);\n\t\t\tif (s->s3->server_opaque_prf_input_len == 0)\n\t\t\t\ts->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */\n\t\t\telse\n\t\t\t\ts->s3->server_opaque_prf_input = BUF_memdup(sdata, s->s3->server_opaque_prf_input_len);\n\n\t\t\tif (s->s3->server_opaque_prf_input == NULL)\n\t\t\t\t{\n\t\t\t\t*al = TLS1_AD_INTERNAL_ERROR;\n\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t}\n#endif\n\t\telse if (type == TLSEXT_TYPE_status_request &&\n\t\t s->version != DTLS1_VERSION)\n\t\t\t{\n\t\t\t/* MUST be empty and only sent if we've requested\n\t\t\t * a status request message.\n\t\t\t */ \n\t\t\tif ((s->tlsext_status_type == -1) || (size > 0))\n\t\t\t\t{\n\t\t\t\t*al = TLS1_AD_UNSUPPORTED_EXTENSION;\n\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t/* Set flag to expect CertificateStatus message */\n\t\t\ts->tlsext_status_expected = 1;\n\t\t\t}\n#ifndef OPENSSL_NO_NEXTPROTONEG\n\t\telse if (type == TLSEXT_TYPE_next_proto_neg &&\n\t\t\t s->s3->tmp.finish_md_len == 0)\n\t\t\t{\n\t\t\tunsigned char *selected;\n\t\t\tunsigned char selected_len;\n\n\t\t\t/* We must have requested it. */\n\t\t\tif (s->ctx->next_proto_select_cb == NULL)\n\t\t\t\t{\n\t\t\t\t*al = TLS1_AD_UNSUPPORTED_EXTENSION;\n\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t/* The data must be valid */\n\t\t\tif (!ssl_next_proto_validate(data, size))\n\t\t\t\t{\n\t\t\t\t*al = TLS1_AD_DECODE_ERROR;\n\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\tif (s->ctx->next_proto_select_cb(s, &selected, &selected_len, data, size, s->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK)\n\t\t\t\t{\n\t\t\t\t*al = TLS1_AD_INTERNAL_ERROR;\n\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\ts->next_proto_negotiated = OPENSSL_malloc(selected_len);\n\t\t\tif (!s->next_proto_negotiated)\n\t\t\t\t{\n\t\t\t\t*al = TLS1_AD_INTERNAL_ERROR;\n\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\tmemcpy(s->next_proto_negotiated, selected, selected_len);\n\t\t\ts->next_proto_negotiated_len = selected_len;\n\t\t\ts->s3->next_proto_neg_seen = 1;\n\t\t\t}\n#endif\n\t\telse if (type == TLSEXT_TYPE_renegotiate)\n\t\t\t{\n\t\t\tif(!ssl_parse_serverhello_renegotiate_ext(s, data, size, al))\n\t\t\t\treturn 0;\n\t\t\trenegotiate_seen = 1;\n\t\t\t}\n#ifndef OPENSSL_NO_HEARTBEATS\n\t\telse if (type == TLSEXT_TYPE_heartbeat)\n\t\t\t{\n\t\t\tswitch(data[0])\n\t\t\t\t{\n\t\t\t\tcase 0x01:\t/* Server allows us to send HB requests */\n\t\t\t\t\t\t\ts->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\tcase 0x02:\t/* Server doesn't accept HB requests */\n\t\t\t\t\t\t\ts->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;\n\t\t\t\t\t\t\ts->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\tdefault:\t*al = SSL_AD_ILLEGAL_PARAMETER;\n\t\t\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t}\n#endif\n#ifndef OPENSSL_NO_SRTP\n\t\telse if (type == TLSEXT_TYPE_use_srtp)\n\t\t\t{\n if(ssl_parse_serverhello_use_srtp_ext(s, data, size,\n\t\t\t\t\t\t\t al))\n return 0;\n\t\t\t}\n#endif\n\n\t\tdata+=size;\t\t\n\t\t}\n\n\tif (data != d+n)\n\t\t{\n\t\t*al = SSL_AD_DECODE_ERROR;\n\t\treturn 0;\n\t\t}\n\n\tif (!s->hit && tlsext_servername == 1)\n\t\t{\n \t\tif (s->tlsext_hostname)\n\t\t\t{\n\t\t\tif (s->session->tlsext_hostname == NULL)\n\t\t\t\t{\n\t\t\t\ts->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname);\t\n\t\t\t\tif (!s->session->tlsext_hostname)\n\t\t\t\t\t{\n\t\t\t\t\t*al = SSL_AD_UNRECOGNIZED_NAME;\n\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\telse \n\t\t\t\t{\n\t\t\t\t*al = SSL_AD_DECODE_ERROR;\n\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t*p = data;\n\n\tri_check:\n\n\t/* Determine if we need to see RI. Strictly speaking if we want to\n\t * avoid an attack we should *always* see RI even on initial server\n\t * hello because the client doesn't see any renegotiation during an\n\t * attack. However this would mean we could not connect to any server\n\t * which doesn't support RI so for the immediate future tolerate RI\n\t * absence on initial connect only.\n\t */\n\tif (!renegotiate_seen\n\t\t&& !(s->options & SSL_OP_LEGACY_SERVER_CONNECT)\n\t\t&& !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))\n\t\t{\n\t\t*al = SSL_AD_HANDSHAKE_FAILURE;\n\t\tSSLerr(SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT,\n\t\t\t\tSSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);\n\t\treturn 0;\n\t\t}\n\n\treturn 1;\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Fix for SRTP Memory Leak\n\nCVE-2014-3513\n\nThis issue was reported to OpenSSL on 26th September 2014, based on an origi\nissue and patch developed by the LibreSSL project. Further analysis of the i\nwas performed by the OpenSSL team.\n\nThe fix was developed by the OpenSSL team.\n\nReviewed-by: Tim Hudson '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ssl23_get_client_hello(SSL *s)\n\t{\n\tchar buf_space[11]; /* Request this many bytes in initial read.\n\t * We can detect SSL 3.0/TLS 1.0 Client Hellos\n\t * ('type == 3') correctly only when the following\n\t * is in a single record, which is not guaranteed by\n\t * the protocol specification:\n\t * Byte Content\n\t * 0 type \\\n\t * 1/2 version > record header\n\t * 3/4 length /\n\t * 5 msg_type \\\n\t * 6-8 length > Client Hello message\n\t * 9/10 client_version /\n\t */\n\tchar *buf= &(buf_space[0]);\n\tunsigned char *p,*d,*d_len,*dd;\n\tunsigned int i;\n\tunsigned int csl,sil,cl;\n\tint n=0,j;\n\tint type=0;\n\tint v[2];\n\n\tif (s->state ==\tSSL23_ST_SR_CLNT_HELLO_A)\n\t\t{\n\t\t/* read the initial header */\n\t\tv[0]=v[1]=0;\n\n\t\tif (!ssl3_setup_buffers(s)) goto err;\n\n\t\tn=ssl23_read_bytes(s, sizeof buf_space);\n\t\tif (n != sizeof buf_space) return(n); /* n == -1 || n == 0 */\n\n\t\tp=s->packet;\n\n\t\tmemcpy(buf,p,n);\n\n\t\tif ((p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO))\n\t\t\t{\n\t\t\t/*\n\t\t\t * SSLv2 header\n\t\t\t */\n\t\t\tif ((p[3] == 0x00) && (p[4] == 0x02))\n\t\t\t\t{\n\t\t\t\tv[0]=p[3]; v[1]=p[4];\n\t\t\t\t/* SSLv2 */\n\t\t\t\tif (!(s->options & SSL_OP_NO_SSLv2))\n\t\t\t\t\ttype=1;\n\t\t\t\t}\n\t\t\telse if (p[3] == SSL3_VERSION_MAJOR)\n\t\t\t\t{\n\t\t\t\tv[0]=p[3]; v[1]=p[4];\n\t\t\t\t/* SSLv3/TLSv1 */\n\t\t\t\tif (p[4] >= TLS1_VERSION_MINOR)\n\t\t\t\t\t{\n\t\t\t\t\tif (p[4] >= TLS1_2_VERSION_MINOR &&\n\t\t\t\t\t !(s->options & SSL_OP_NO_TLSv1_2))\n\t\t\t\t\t\t{\n\t\t\t\t\t\ts->version=TLS1_2_VERSION;\n\t\t\t\t\t\ts->state=SSL23_ST_SR_CLNT_HELLO_B;\n\t\t\t\t\t\t}\n\t\t\t\t\telse if (p[4] >= TLS1_1_VERSION_MINOR &&\n\t\t\t\t\t !(s->options & SSL_OP_NO_TLSv1_1))\n\t\t\t\t\t\t{\n\t\t\t\t\t\ts->version=TLS1_1_VERSION;\n\t\t\t\t\t\t/* type=2; */ /* done later to survive restarts */\n\t\t\t\t\t\ts->state=SSL23_ST_SR_CLNT_HELLO_B;\n\t\t\t\t\t\t}\n\t\t\t\t\telse if (!(s->options & SSL_OP_NO_TLSv1))\n\t\t\t\t\t\t{\n\t\t\t\t\t\ts->version=TLS1_VERSION;\n\t\t\t\t\t\t/* type=2; */ /* done later to survive restarts */\n\t\t\t\t\t\ts->state=SSL23_ST_SR_CLNT_HELLO_B;\n\t\t\t\t\t\t}\n\t\t\t\t\telse if (!(s->options & SSL_OP_NO_SSLv3))\n\t\t\t\t\t\t{\n\t\t\t\t\t\ts->version=SSL3_VERSION;\n\t\t\t\t\t\t/* type=2; */\n\t\t\t\t\t\ts->state=SSL23_ST_SR_CLNT_HELLO_B;\n\t\t\t\t\t\t}\n\t\t\t\t\telse if (!(s->options & SSL_OP_NO_SSLv2))\n\t\t\t\t\t\t{\n\t\t\t\t\t\ttype=1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\telse if (!(s->options & SSL_OP_NO_SSLv3))\n\t\t\t\t\t{\n\t\t\t\t\ts->version=SSL3_VERSION;\n\t\t\t\t\t/* type=2; */\n\t\t\t\t\ts->state=SSL23_ST_SR_CLNT_HELLO_B;\n\t\t\t\t\t}\n\t\t\t\telse if (!(s->options & SSL_OP_NO_SSLv2))\n\t\t\t\t\ttype=1;\n\n\t\t\t\t}\n\t\t\t}\n\t\telse if ((p[0] == SSL3_RT_HANDSHAKE) &&\n\t\t\t (p[1] == SSL3_VERSION_MAJOR) &&\n\t\t\t (p[5] == SSL3_MT_CLIENT_HELLO) &&\n\t\t\t ((p[3] == 0 && p[4] < 5 /* silly record length? */)\n\t\t\t\t|| (p[9] >= p[1])))\n\t\t\t{\n\t\t\t/*\n\t\t\t * SSLv3 or tls1 header\n\t\t\t */\n\t\t\t\n\t\t\tv[0]=p[1]; /* major version (= SSL3_VERSION_MAJOR) */\n\t\t\t/* We must look at client_version inside the Client Hello message\n\t\t\t * to get the correct minor version.\n\t\t\t * However if we have only a pathologically small fragment of the\n\t\t\t * Client Hello message, this would be difficult, and we'd have\n\t\t\t * to read more records to find out.\n\t\t\t * No known SSL 3.0 client fragments ClientHello like this,\n\t\t\t * so we simply reject such connections to avoid\n\t\t\t * protocol version downgrade attacks. */\n\t\t\tif (p[3] == 0 && p[4] < 6)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_SMALL);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\t\t\t/* if major version number > 3 set minor to a value\n\t\t\t * which will use the highest version 3 we support.\n\t\t\t * If TLS 2.0 ever appears we will need to revise\n\t\t\t * this....\n\t\t\t */\n\t\t\tif (p[9] > SSL3_VERSION_MAJOR)\n\t\t\t\tv[1]=0xff;\n\t\t\telse\n\t\t\t\tv[1]=p[10]; /* minor version according to client_version */\n\t\t\tif (v[1] >= TLS1_VERSION_MINOR)\n\t\t\t\t{\n\t\t\t\tif (v[1] >= TLS1_2_VERSION_MINOR &&\n\t\t\t\t\t!(s->options & SSL_OP_NO_TLSv1_2))\n\t\t\t\t\t{\n\t\t\t\t\ts->version=TLS1_2_VERSION;\n\t\t\t\t\ttype=3;\n\t\t\t\t\t}\n\t\t\t\telse if (v[1] >= TLS1_1_VERSION_MINOR &&\n\t\t\t\t\t!(s->options & SSL_OP_NO_TLSv1_1))\n\t\t\t\t\t{\n\t\t\t\t\ts->version=TLS1_1_VERSION;\n\t\t\t\t\ttype=3;\n\t\t\t\t\t}\n\t\t\t\telse if (!(s->options & SSL_OP_NO_TLSv1))\n\t\t\t\t\t{\n\t\t\t\t\ts->version=TLS1_VERSION;\n\t\t\t\t\ttype=3;\n\t\t\t\t\t}\n\t\t\t\telse if (!(s->options & SSL_OP_NO_SSLv3))\n\t\t\t\t\t{\n\t\t\t\t\ts->version=SSL3_VERSION;\n\t\t\t\t\ttype=3;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\telse\n\t\t\t\t{\n\t\t\t\t/* client requests SSL 3.0 */\n\t\t\t\tif (!(s->options & SSL_OP_NO_SSLv3))\n\t\t\t\t\t{\n\t\t\t\t\ts->version=SSL3_VERSION;\n\t\t\t\t\ttype=3;\n\t\t\t\t\t}\n\t\t\t\telse if (!(s->options & SSL_OP_NO_TLSv1))\n\t\t\t\t\t{\n\t\t\t\t\t/* we won't be able to use TLS of course,\n\t\t\t\t\t * but this will send an appropriate alert */\n\t\t\t\t\ts->version=TLS1_VERSION;\n\t\t\t\t\ttype=3;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\telse if ((strncmp(\"GET \", (char *)p,4) == 0) ||\n\t\t\t (strncmp(\"POST \",(char *)p,5) == 0) ||\n\t\t\t (strncmp(\"HEAD \",(char *)p,5) == 0) ||\n\t\t\t (strncmp(\"PUT \", (char *)p,4) == 0))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTP_REQUEST);\n\t\t\tgoto err;\n\t\t\t}\n\t\telse if (strncmp(\"CONNECT\",(char *)p,7) == 0)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTPS_PROXY_REQUEST);\n\t\t\tgoto err;\n\t\t\t}\n\t\t}\n\n\t/* ensure that TLS_MAX_VERSION is up-to-date */\n\tOPENSSL_assert(s->version <= TLS_MAX_VERSION);\n\n#ifdef OPENSSL_FIPS\n\tif (FIPS_mode() && (s->version < TLS1_VERSION))\n\t\t{\n\t\tSSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,\n\t\t\t\t\tSSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE);\n\t\tgoto err;\n\t\t}\n#endif\n\n\tif (s->state == SSL23_ST_SR_CLNT_HELLO_B)\n\t\t{\n\t\t/* we have SSLv3/TLSv1 in an SSLv2 header\n\t\t * (other cases skip this state) */\n\n\t\ttype=2;\n\t\tp=s->packet;\n\t\tv[0] = p[3]; /* == SSL3_VERSION_MAJOR */\n\t\tv[1] = p[4];\n\n\t\t/* An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2\n\t\t * header is sent directly on the wire, not wrapped as a TLS\n\t\t * record. It's format is:\n\t\t * Byte Content\n\t\t * 0-1 msg_length\n\t\t * 2 msg_type\n\t\t * 3-4 version\n\t\t * 5-6 cipher_spec_length\n\t\t * 7-8 session_id_length\n\t\t * 9-10 challenge_length\n\t\t * ... ...\n\t\t */\n\t\tn=((p[0]&0x7f)<<8)|p[1];\n\t\tif (n > (1024*4))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_LARGE);\n\t\t\tgoto err;\n\t\t\t}\n\t\tif (n < 9)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH);\n\t\t\tgoto err;\n\t\t\t}\n\n\t\tj=ssl23_read_bytes(s,n+2);\n\t\t/* We previously read 11 bytes, so if j > 0, we must have\n\t\t * j == n+2 == s->packet_length. We have at least 11 valid\n\t\t * packet bytes. */\n\t\tif (j <= 0) return(j);\n\n\t\tssl3_finish_mac(s, s->packet+2, s->packet_length-2);\n\t\tif (s->msg_callback)\n\t\t\ts->msg_callback(0, SSL2_VERSION, 0, s->packet+2, s->packet_length-2, s, s->msg_callback_arg); /* CLIENT-HELLO */\n\n\t\tp=s->packet;\n\t\tp+=5;\n\t\tn2s(p,csl);\n\t\tn2s(p,sil);\n\t\tn2s(p,cl);\n\t\td=(unsigned char *)s->init_buf->data;\n\t\tif ((csl+sil+cl+11) != s->packet_length) /* We can't have TLS extensions in SSL 2.0 format\n\t\t * Client Hello, can we? Error condition should be\n\t\t * '>' otherweise */\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH);\n\t\t\tgoto err;\n\t\t\t}\n\n\t\t/* record header: msg_type ... */\n\t\t*(d++) = SSL3_MT_CLIENT_HELLO;\n\t\t/* ... and length (actual value will be written later) */\n\t\td_len = d;\n\t\td += 3;\n\n\t\t/* client_version */\n\t\t*(d++) = SSL3_VERSION_MAJOR; /* == v[0] */\n\t\t*(d++) = v[1];\n\n\t\t/* lets populate the random area */\n\t\t/* get the challenge_length */\n\t\ti=(cl > SSL3_RANDOM_SIZE)?SSL3_RANDOM_SIZE:cl;\n\t\tmemset(d,0,SSL3_RANDOM_SIZE);\n\t\tmemcpy(&(d[SSL3_RANDOM_SIZE-i]),&(p[csl+sil]),i);\n\t\td+=SSL3_RANDOM_SIZE;\n\n\t\t/* no session-id reuse */\n\t\t*(d++)=0;\n\n\t\t/* ciphers */\n\t\tj=0;\n\t\tdd=d;\n\t\td+=2;\n\t\tfor (i=0; ipacket+s->packet_length)\n\t\t\t{\n\t\t\t*(d++)=*(p++);\n\t\t\t}\n#endif\n\n\t\ti = (d-(unsigned char *)s->init_buf->data) - 4;\n\t\tl2n3((long)i, d_len);\n\n\t\t/* get the data reused from the init_buf */\n\t\ts->s3->tmp.reuse_message=1;\n\t\ts->s3->tmp.message_type=SSL3_MT_CLIENT_HELLO;\n\t\ts->s3->tmp.message_size=i;\n\t\t}\n\n\t/* imaginary new state (for program structure): */\n\t/* s->state = SSL23_SR_CLNT_HELLO_C */\n\n\tif (type == 1)\n\t\t{\n#ifdef OPENSSL_NO_SSL2\n\t\tSSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL);\n\t\tgoto err;\n#else\n\t\t/* we are talking sslv2 */\n\t\t/* we need to clean up the SSLv3/TLSv1 setup and put in the\n\t\t * sslv2 stuff. */\n\n\t\tif (s->s2 == NULL)\n\t\t\t{\n\t\t\tif (!ssl2_new(s))\n\t\t\t\tgoto err;\n\t\t\t}\n\t\telse\n\t\t\tssl2_clear(s);\n\n\t\tif (s->s3 != NULL) ssl3_free(s);\n\n\t\tif (!BUF_MEM_grow_clean(s->init_buf,\n\t\t\tSSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER))\n\t\t\t{\n\t\t\tgoto err;\n\t\t\t}\n\n\t\ts->state=SSL2_ST_GET_CLIENT_HELLO_A;\n\t\tif (s->options & SSL_OP_NO_TLSv1 && s->options & SSL_OP_NO_SSLv3)\n\t\t\ts->s2->ssl2_rollback=0;\n\t\telse\n\t\t\t/* reject SSL 2.0 session if client supports SSL 3.0 or TLS 1.0\n\t\t\t * (SSL 3.0 draft/RFC 2246, App. E.2) */\n\t\t\ts->s2->ssl2_rollback=1;\n\n\t\t/* setup the n bytes we have read so we get them from\n\t\t * the sslv2 buffer */\n\t\ts->rstate=SSL_ST_READ_HEADER;\n\t\ts->packet_length=n;\n\t\ts->packet= &(s->s2->rbuf[0]);\n\t\tmemcpy(s->packet,buf,n);\n\t\ts->s2->rbuf_left=n;\n\t\ts->s2->rbuf_offs=0;\n\n\t\ts->method=SSLv2_server_method();\n\t\ts->handshake_func=s->method->ssl_accept;\n#endif\n\t\t}\n\n\tif ((type == 2) || (type == 3))\n\t\t{\n\t\t/* we have SSLv3/TLSv1 (type 2: SSL2 style, type 3: SSL3/TLS style) */\n\n\t\tif (!ssl_init_wbio_buffer(s,1)) goto err;\n\n\t\t/* we are in this state */\n\t\ts->state=SSL3_ST_SR_CLNT_HELLO_A;\n\n\t\tif (type == 3)\n\t\t\t{\n\t\t\t/* put the 'n' bytes we have read into the input buffer\n\t\t\t * for SSLv3 */\n\t\t\ts->rstate=SSL_ST_READ_HEADER;\n\t\t\ts->packet_length=n;\n\t\t\tif (s->s3->rbuf.buf == NULL)\n\t\t\t\tif (!ssl3_setup_read_buffer(s))\n\t\t\t\t\tgoto err;\n\n\t\t\ts->packet= &(s->s3->rbuf.buf[0]);\n\t\t\tmemcpy(s->packet,buf,n);\n\t\t\ts->s3->rbuf.left=n;\n\t\t\ts->s3->rbuf.offset=0;\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\ts->packet_length=0;\n\t\t\ts->s3->rbuf.left=0;\n\t\t\ts->s3->rbuf.offset=0;\n\t\t\t}\n\t\tif (s->version == TLS1_2_VERSION)\n\t\t\ts->method = TLSv1_2_server_method();\n\t\telse if (s->version == TLS1_1_VERSION)\n\t\t\ts->method = TLSv1_1_server_method();\n\t\telse if (s->version == TLS1_VERSION)\n\t\t\ts->method = TLSv1_server_method();\n\t\telse\n\t\t\ts->method = SSLv3_server_method();\n#if 0 /* ssl3_get_client_hello does this */\n\t\ts->client_version=(v[0]<<8)|v[1];\n#endif\n\t\ts->handshake_func=s->method->ssl_accept;\n\t\t}\n\t\n\tif ((type < 1) || (type > 3))\n\t\t{\n\t\t/* bad, very bad */\n\t\tSSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNKNOWN_PROTOCOL);\n\t\tgoto err;\n\t\t}\n\ts->init_num=0;\n\n\tif (buf != buf_space) OPENSSL_free(buf);\n\treturn(SSL_accept(s));\nerr:\n\tif (buf != buf_space) OPENSSL_free(buf);\n\treturn(-1);\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Fix no-ssl3 configuration option\n\nCVE-2014-3568\n\nReviewed-by: Emilia Kasper \nReviewed-by: Rich Salz '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ssl3_accept(SSL *s)\n\t{\n\tBUF_MEM *buf;\n\tunsigned long l,Time=(unsigned long)time(NULL);\n\tvoid (*cb)(const SSL *ssl,int type,int val)=NULL;\n\tint ret= -1;\n\tint new_state,state,skip=0;\n\n\tRAND_add(&Time,sizeof(Time),0);\n\tERR_clear_error();\n\tclear_sys_error();\n\n\tif (s->info_callback != NULL)\n\t\tcb=s->info_callback;\n\telse if (s->ctx->info_callback != NULL)\n\t\tcb=s->ctx->info_callback;\n\n\t/* init things to blank */\n\ts->in_handshake++;\n\tif (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);\n\n\tif (s->cert == NULL)\n\t\t{\n\t\tSSLerr(SSL_F_SSL3_ACCEPT,SSL_R_NO_CERTIFICATE_SET);\n\t\treturn(-1);\n\t\t}\n\n\tfor (;;)\n\t\t{\n\t\tstate=s->state;\n\n\t\tswitch (s->state)\n\t\t\t{\n\t\tcase SSL_ST_RENEGOTIATE:\n\t\t\ts->new_session=1;\n\t\t\t/* s->state=SSL_ST_ACCEPT; */\n\n\t\tcase SSL_ST_BEFORE:\n\t\tcase SSL_ST_ACCEPT:\n\t\tcase SSL_ST_BEFORE|SSL_ST_ACCEPT:\n\t\tcase SSL_ST_OK|SSL_ST_ACCEPT:\n\n\t\t\ts->server=1;\n\t\t\tif (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);\n\n\t\t\tif ((s->version>>8) != 3)\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);\n\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\ts->type=SSL_ST_ACCEPT;\n\n\t\t\tif (s->init_buf == NULL)\n\t\t\t\t{\n\t\t\t\tif ((buf=BUF_MEM_new()) == NULL)\n\t\t\t\t\t{\n\t\t\t\t\tret= -1;\n\t\t\t\t\tgoto end;\n\t\t\t\t\t}\n\t\t\t\tif (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))\n\t\t\t\t\t{\n\t\t\t\t\tret= -1;\n\t\t\t\t\tgoto end;\n\t\t\t\t\t}\n\t\t\t\ts->init_buf=buf;\n\t\t\t\t}\n\n\t\t\tif (!ssl3_setup_buffers(s))\n\t\t\t\t{\n\t\t\t\tret= -1;\n\t\t\t\tgoto end;\n\t\t\t\t}\n\n\t\t\ts->init_num=0;\n\t\t\ts->s3->flags &= ~SSL3_FLAGS_SGC_RESTART_DONE;\n\n\t\t\tif (s->state != SSL_ST_RENEGOTIATE)\n\t\t\t\t{\n\t\t\t\t/* Ok, we now need to push on a buffering BIO so that\n\t\t\t\t * the output is sent in a way that TCP likes :-)\n\t\t\t\t */\n\t\t\t\tif (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; }\n\t\t\t\t\n\t\t\t\tssl3_init_finished_mac(s);\n\t\t\t\ts->state=SSL3_ST_SR_CLNT_HELLO_A;\n\t\t\t\ts->ctx->stats.sess_accept++;\n\t\t\t\t}\n\t\t\telse if (!s->s3->send_connection_binding &&\n\t\t\t\t!(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))\n\t\t\t\t{\n\t\t\t\t/* Server attempting to renegotiate with\n\t\t\t\t * client that doesn't support secure\n\t\t\t\t * renegotiation.\n\t\t\t\t */\n\t\t\t\tSSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);\n\t\t\t\tssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);\n\t\t\t\tret = -1;\n\t\t\t\tgoto end;\n\t\t\t\t}\n\t\t\telse\n\t\t\t\t{\n\t\t\t\t/* s->state == SSL_ST_RENEGOTIATE,\n\t\t\t\t * we will just send a HelloRequest */\n\t\t\t\ts->ctx->stats.sess_accept_renegotiate++;\n\t\t\t\ts->state=SSL3_ST_SW_HELLO_REQ_A;\n\t\t\t\t}\n\t\t\tbreak;\n\n\t\tcase SSL3_ST_SW_HELLO_REQ_A:\n\t\tcase SSL3_ST_SW_HELLO_REQ_B:\n\n\t\t\ts->shutdown=0;\n\t\t\tret=ssl3_send_hello_request(s);\n\t\t\tif (ret <= 0) goto end;\n\t\t\ts->s3->tmp.next_state=SSL3_ST_SW_HELLO_REQ_C;\n\t\t\ts->state=SSL3_ST_SW_FLUSH;\n\t\t\ts->init_num=0;\n\n\t\t\tssl3_init_finished_mac(s);\n\t\t\tbreak;\n\n\t\tcase SSL3_ST_SW_HELLO_REQ_C:\n\t\t\ts->state=SSL_ST_OK;\n\t\t\tbreak;\n\n\t\tcase SSL3_ST_SR_CLNT_HELLO_A:\n\t\tcase SSL3_ST_SR_CLNT_HELLO_B:\n\t\tcase SSL3_ST_SR_CLNT_HELLO_C:\n\n\t\t\ts->shutdown=0;\n\t\t\tret=ssl3_get_client_hello(s);\n\t\t\tif (ret <= 0) goto end;\n\t\t\ts->new_session = 2;\n\t\t\ts->state=SSL3_ST_SW_SRVR_HELLO_A;\n\t\t\ts->init_num=0;\n\t\t\tbreak;\n\n\t\tcase SSL3_ST_SW_SRVR_HELLO_A:\n\t\tcase SSL3_ST_SW_SRVR_HELLO_B:\n\t\t\tret=ssl3_send_server_hello(s);\n\t\t\tif (ret <= 0) goto end;\n#ifndef OPENSSL_NO_TLSEXT\n\t\t\tif (s->hit)\n\t\t\t\t{\n\t\t\t\tif (s->tlsext_ticket_expected)\n\t\t\t\t\ts->state=SSL3_ST_SW_SESSION_TICKET_A;\n\t\t\t\telse\n\t\t\t\t\ts->state=SSL3_ST_SW_CHANGE_A;\n\t\t\t\t}\n#else\n\t\t\tif (s->hit)\n\t\t\t\t\ts->state=SSL3_ST_SW_CHANGE_A;\n#endif\n\t\t\telse\n\t\t\t\ts->state=SSL3_ST_SW_CERT_A;\n\t\t\ts->init_num=0;\n\t\t\tbreak;\n\n\t\tcase SSL3_ST_SW_CERT_A:\n\t\tcase SSL3_ST_SW_CERT_B:\n\t\t\t/* Check if it is anon DH or anon ECDH or KRB5 */\n\t\t\tif (!(s->s3->tmp.new_cipher->algorithms & SSL_aNULL)\n\t\t\t\t&& !(s->s3->tmp.new_cipher->algorithms & SSL_aKRB5))\n\t\t\t\t{\n\t\t\t\tret=ssl3_send_server_certificate(s);\n\t\t\t\tif (ret <= 0) goto end;\n#ifndef OPENSSL_NO_TLSEXT\n\t\t\t\tif (s->tlsext_status_expected)\n\t\t\t\t\ts->state=SSL3_ST_SW_CERT_STATUS_A;\n\t\t\t\telse\n\t\t\t\t\ts->state=SSL3_ST_SW_KEY_EXCH_A;\n\t\t\t\t}\n\t\t\telse\n\t\t\t\t{\n\t\t\t\tskip = 1;\n\t\t\t\ts->state=SSL3_ST_SW_KEY_EXCH_A;\n\t\t\t\t}\n#else\n\t\t\t\t}\n\t\t\telse\n\t\t\t\tskip=1;\n\n\t\t\ts->state=SSL3_ST_SW_KEY_EXCH_A;\n#endif\n\t\t\ts->init_num=0;\n\t\t\tbreak;\n\n\t\tcase SSL3_ST_SW_KEY_EXCH_A:\n\t\tcase SSL3_ST_SW_KEY_EXCH_B:\n\t\t\tl=s->s3->tmp.new_cipher->algorithms;\n\n\t\t\t/* clear this, it may get reset by\n\t\t\t * send_server_key_exchange */\n\t\t\tif ((s->options & SSL_OP_EPHEMERAL_RSA)\n#ifndef OPENSSL_NO_KRB5\n\t\t\t\t&& !(l & SSL_KRB5)\n#endif /* OPENSSL_NO_KRB5 */\n\t\t\t\t)\n\t\t\t\t/* option SSL_OP_EPHEMERAL_RSA sends temporary RSA key\n\t\t\t\t * even when forbidden by protocol specs\n\t\t\t\t * (handshake may fail as clients are not required to\n\t\t\t\t * be able to handle this) */\n\t\t\t\ts->s3->tmp.use_rsa_tmp=1;\n\t\t\telse\n\t\t\t\ts->s3->tmp.use_rsa_tmp=0;\n\n\n\t\t\t/* only send if a DH key exchange, fortezza or\n\t\t\t * RSA but we have a sign only certificate\n\t\t\t *\n\t\t\t * For ECC ciphersuites, we send a serverKeyExchange\n\t\t\t * message only if the cipher suite is either\n\t\t\t * ECDH-anon or ECDHE. In other cases, the\n\t\t\t * server certificate contains the server's \n\t\t\t * public key for key exchange.\n\t\t\t */\n\t\t\tif (s->s3->tmp.use_rsa_tmp\n\t\t\t || (l & SSL_kECDHE)\n\t\t\t || (l & (SSL_DH|SSL_kFZA))\n\t\t\t || ((l & SSL_kRSA)\n\t\t\t\t&& (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL\n\t\t\t\t || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)\n\t\t\t\t\t&& EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)\n\t\t\t\t\t)\n\t\t\t\t )\n\t\t\t\t)\n\t\t\t )\n\t\t\t\t{\n\t\t\t\tret=ssl3_send_server_key_exchange(s);\n\t\t\t\tif (ret <= 0) goto end;\n\t\t\t\t}\n\t\t\telse\n\t\t\t\tskip=1;\n\n\t\t\ts->state=SSL3_ST_SW_CERT_REQ_A;\n\t\t\ts->init_num=0;\n\t\t\tbreak;\n\n\t\tcase SSL3_ST_SW_CERT_REQ_A:\n\t\tcase SSL3_ST_SW_CERT_REQ_B:\n\t\t\tif (/* don't request cert unless asked for it: */\n\t\t\t\t!(s->verify_mode & SSL_VERIFY_PEER) ||\n\t\t\t\t/* if SSL_VERIFY_CLIENT_ONCE is set,\n\t\t\t\t * don't request cert during re-negotiation: */\n\t\t\t\t((s->session->peer != NULL) &&\n\t\t\t\t (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||\n\t\t\t\t/* never request cert in anonymous ciphersuites\n\t\t\t\t * (see section \"Certificate request\" in SSL 3 drafts\n\t\t\t\t * and in RFC 2246): */\n\t\t\t\t((s->s3->tmp.new_cipher->algorithms & SSL_aNULL) &&\n\t\t\t\t /* ... except when the application insists on verification\n\t\t\t\t * (against the specs, but s3_clnt.c accepts this for SSL 3) */\n\t\t\t\t !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||\n /* never request cert in Kerberos ciphersuites */\n (s->s3->tmp.new_cipher->algorithms & SSL_aKRB5))\n\t\t\t\t{\n\t\t\t\t/* no cert request */\n\t\t\t\tskip=1;\n\t\t\t\ts->s3->tmp.cert_request=0;\n\t\t\t\ts->state=SSL3_ST_SW_SRVR_DONE_A;\n\t\t\t\t}\n\t\t\telse\n\t\t\t\t{\n\t\t\t\ts->s3->tmp.cert_request=1;\n\t\t\t\tret=ssl3_send_certificate_request(s);\n\t\t\t\tif (ret <= 0) goto end;\n#ifndef NETSCAPE_HANG_BUG\n\t\t\t\ts->state=SSL3_ST_SW_SRVR_DONE_A;\n#else\n\t\t\t\ts->state=SSL3_ST_SW_FLUSH;\n\t\t\t\ts->s3->tmp.next_state=SSL3_ST_SR_CERT_A;\n#endif\n\t\t\t\ts->init_num=0;\n\t\t\t\t}\n\t\t\tbreak;\n\n\t\tcase SSL3_ST_SW_SRVR_DONE_A:\n\t\tcase SSL3_ST_SW_SRVR_DONE_B:\n\t\t\tret=ssl3_send_server_done(s);\n\t\t\tif (ret <= 0) goto end;\n\t\t\ts->s3->tmp.next_state=SSL3_ST_SR_CERT_A;\n\t\t\ts->state=SSL3_ST_SW_FLUSH;\n\t\t\ts->init_num=0;\n\t\t\tbreak;\n\t\t\n\t\tcase SSL3_ST_SW_FLUSH:\n\n\t\t\t/* This code originally checked to see if\n\t\t\t * any data was pending using BIO_CTRL_INFO\n\t\t\t * and then flushed. This caused problems\n\t\t\t * as documented in PR#1939. The proposed\n\t\t\t * fix doesn't completely resolve this issue\n\t\t\t * as buggy implementations of BIO_CTRL_PENDING\n\t\t\t * still exist. So instead we just flush\n\t\t\t * unconditionally.\n\t\t\t */\n\n\t\t\ts->rwstate=SSL_WRITING;\n\t\t\tif (BIO_flush(s->wbio) <= 0)\n\t\t\t\t{\n\t\t\t\tret= -1;\n\t\t\t\tgoto end;\n\t\t\t\t}\n\t\t\ts->rwstate=SSL_NOTHING;\n\n\t\t\ts->state=s->s3->tmp.next_state;\n\t\t\tbreak;\n\n\t\tcase SSL3_ST_SR_CERT_A:\n\t\tcase SSL3_ST_SR_CERT_B:\n\t\t\t/* Check for second client hello (MS SGC) */\n\t\t\tret = ssl3_check_client_hello(s);\n\t\t\tif (ret <= 0)\n\t\t\t\tgoto end;\n\t\t\tif (ret == 2)\n\t\t\t\ts->state = SSL3_ST_SR_CLNT_HELLO_C;\n\t\t\telse {\n\t\t\t\tif (s->s3->tmp.cert_request)\n\t\t\t\t\t{\n\t\t\t\t\tret=ssl3_get_client_certificate(s);\n\t\t\t\t\tif (ret <= 0) goto end;\n\t\t\t\t\t}\n\t\t\t\ts->init_num=0;\n\t\t\t\ts->state=SSL3_ST_SR_KEY_EXCH_A;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase SSL3_ST_SR_KEY_EXCH_A:\n\t\tcase SSL3_ST_SR_KEY_EXCH_B:\n\t\t\tret=ssl3_get_client_key_exchange(s);\n\t\t\tif (ret <= 0) \n\t\t\t\tgoto end;\n\t\t\tif (ret == 2)\n\t\t\t\t{\n\t\t\t\t/* For the ECDH ciphersuites when\n\t\t\t\t * the client sends its ECDH pub key in\n\t\t\t\t * a certificate, the CertificateVerify\n\t\t\t\t * message is not sent.\n\t\t\t\t */\n\t\t\t\ts->state=SSL3_ST_SR_FINISHED_A;\n\t\t\t\ts->init_num = 0;\n\t\t\t\t}\n\t\t\telse \n\t\t\t\t{\n\t\t\t\ts->state=SSL3_ST_SR_CERT_VRFY_A;\n\t\t\t\ts->init_num=0;\n\n\t\t\t\t/* We need to get hashes here so if there is\n\t\t\t\t * a client cert, it can be verified\n\t\t\t\t */ \n\t\t\t\ts->method->ssl3_enc->cert_verify_mac(s,\n\t\t\t\t &(s->s3->finish_dgst1),\n\t\t\t\t &(s->s3->tmp.cert_verify_md[0]));\n\t\t\t\ts->method->ssl3_enc->cert_verify_mac(s,\n\t\t\t\t &(s->s3->finish_dgst2),\n\t\t\t\t &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]));\n\t\t\t\t}\n\t\t\tbreak;\n\n\t\tcase SSL3_ST_SR_CERT_VRFY_A:\n\t\tcase SSL3_ST_SR_CERT_VRFY_B:\n\n\t\t\ts->s3->flags |= SSL3_FLAGS_CCS_OK;\n\t\t\t/* we should decide if we expected this one */\n\t\t\tret=ssl3_get_cert_verify(s);\n\t\t\tif (ret <= 0) goto end;\n\n\t\t\ts->state=SSL3_ST_SR_FINISHED_A;\n\t\t\ts->init_num=0;\n\t\t\tbreak;\n\n\t\tcase SSL3_ST_SR_FINISHED_A:\n\t\tcase SSL3_ST_SR_FINISHED_B:\n\t\t\ts->s3->flags |= SSL3_FLAGS_CCS_OK;\n\t\t\tret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A,\n\t\t\t\tSSL3_ST_SR_FINISHED_B);\n\t\t\tif (ret <= 0) goto end;\n\t\t\tif (s->hit)\n\t\t\t\ts->state=SSL_ST_OK;\n#ifndef OPENSSL_NO_TLSEXT\n\t\t\telse if (s->tlsext_ticket_expected)\n\t\t\t\ts->state=SSL3_ST_SW_SESSION_TICKET_A;\n#endif\n\t\t\telse\n\t\t\t\ts->state=SSL3_ST_SW_CHANGE_A;\n\t\t\ts->init_num=0;\n\t\t\tbreak;\n\n#ifndef OPENSSL_NO_TLSEXT\n\t\tcase SSL3_ST_SW_SESSION_TICKET_A:\n\t\tcase SSL3_ST_SW_SESSION_TICKET_B:\n\t\t\tret=ssl3_send_newsession_ticket(s);\n\t\t\tif (ret <= 0) goto end;\n\t\t\ts->state=SSL3_ST_SW_CHANGE_A;\n\t\t\ts->init_num=0;\n\t\t\tbreak;\n\n\t\tcase SSL3_ST_SW_CERT_STATUS_A:\n\t\tcase SSL3_ST_SW_CERT_STATUS_B:\n\t\t\tret=ssl3_send_cert_status(s);\n\t\t\tif (ret <= 0) goto end;\n\t\t\ts->state=SSL3_ST_SW_KEY_EXCH_A;\n\t\t\ts->init_num=0;\n\t\t\tbreak;\n\n#endif\n\n\t\tcase SSL3_ST_SW_CHANGE_A:\n\t\tcase SSL3_ST_SW_CHANGE_B:\n\n\t\t\ts->session->cipher=s->s3->tmp.new_cipher;\n\t\t\tif (!s->method->ssl3_enc->setup_key_block(s))\n\t\t\t\t{ ret= -1; goto end; }\n\n\t\t\tret=ssl3_send_change_cipher_spec(s,\n\t\t\t\tSSL3_ST_SW_CHANGE_A,SSL3_ST_SW_CHANGE_B);\n\n\t\t\tif (ret <= 0) goto end;\n\t\t\ts->state=SSL3_ST_SW_FINISHED_A;\n\t\t\ts->init_num=0;\n\n\t\t\tif (!s->method->ssl3_enc->change_cipher_state(s,\n\t\t\t\tSSL3_CHANGE_CIPHER_SERVER_WRITE))\n\t\t\t\t{\n\t\t\t\tret= -1;\n\t\t\t\tgoto end;\n\t\t\t\t}\n\n\t\t\tbreak;\n\n\t\tcase SSL3_ST_SW_FINISHED_A:\n\t\tcase SSL3_ST_SW_FINISHED_B:\n\t\t\tret=ssl3_send_finished(s,\n\t\t\t\tSSL3_ST_SW_FINISHED_A,SSL3_ST_SW_FINISHED_B,\n\t\t\t\ts->method->ssl3_enc->server_finished_label,\n\t\t\t\ts->method->ssl3_enc->server_finished_label_len);\n\t\t\tif (ret <= 0) goto end;\n\t\t\ts->state=SSL3_ST_SW_FLUSH;\n\t\t\tif (s->hit)\n\t\t\t\ts->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;\n\t\t\telse\n\t\t\t\ts->s3->tmp.next_state=SSL_ST_OK;\n\t\t\ts->init_num=0;\n\t\t\tbreak;\n\n\t\tcase SSL_ST_OK:\n\t\t\t/* clean a few things up */\n\t\t\tssl3_cleanup_key_block(s);\n\n\t\t\tBUF_MEM_free(s->init_buf);\n\t\t\ts->init_buf=NULL;\n\n\t\t\t/* remove buffering on output */\n\t\t\tssl_free_wbio_buffer(s);\n\n\t\t\ts->init_num=0;\n\n\t\t\tif (s->new_session == 2) /* skipped if we just sent a HelloRequest */\n\t\t\t\t{\n\t\t\t\t/* actually not necessarily a 'new' session unless\n\t\t\t\t * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION is set */\n\t\t\t\t\n\t\t\t\ts->new_session=0;\n\t\t\t\t\n\t\t\t\tssl_update_cache(s,SSL_SESS_CACHE_SERVER);\n\t\t\t\t\n\t\t\t\ts->ctx->stats.sess_accept_good++;\n\t\t\t\t/* s->server=1; */\n\t\t\t\ts->handshake_func=ssl3_accept;\n\n\t\t\t\tif (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);\n\t\t\t\t}\n\t\t\t\n\t\t\tret = 1;\n\t\t\tgoto end;\n\t\t\t/* break; */\n\n\t\tdefault:\n\t\t\tSSLerr(SSL_F_SSL3_ACCEPT,SSL_R_UNKNOWN_STATE);\n\t\t\tret= -1;\n\t\t\tgoto end;\n\t\t\t/* break; */\n\t\t\t}\n\t\t\n\t\tif (!s->s3->tmp.reuse_message && !skip)\n\t\t\t{\n\t\t\tif (s->debug)\n\t\t\t\t{\n\t\t\t\tif ((ret=BIO_flush(s->wbio)) <= 0)\n\t\t\t\t\tgoto end;\n\t\t\t\t}\n\n\n\t\t\tif ((cb != NULL) && (s->state != state))\n\t\t\t\t{\n\t\t\t\tnew_state=s->state;\n\t\t\t\ts->state=state;\n\t\t\t\tcb(s,SSL_CB_ACCEPT_LOOP,1);\n\t\t\t\ts->state=new_state;\n\t\t\t\t}\n\t\t\t}\n\t\tskip=0;\n\t\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Only allow ephemeral RSA keys in export ciphersuites.\n\nOpenSSL clients would tolerate temporary RSA keys in non-export\nciphersuites. It also had an option SSL_OP_EPHEMERAL_RSA which\nenabled this server side. Remove both options as they are a\nprotocol violation.\n\nThanks to Karthikeyan Bhargavan for reporting this issue.\n(CVE-2015-0204)\nReviewed-by: Matt Caswell \nReviewed-by: Tim Hudson \n\n(cherry picked from commit 4b4c1fcc88aec8c9e001b0a0077d3cd4de1ed0e6)\n\nConflicts:\n\tCHANGES\n\tdoc/ssl/SSL_CTX_set_options.pod\n\tssl/d1_srvr.c\n\tssl/s3_srvr.c'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ECDSA_verify(int type, const unsigned char *dgst, int dgst_len,\n\t\tconst unsigned char *sigbuf, int sig_len, EC_KEY *eckey)\n \t{\n\tECDSA_SIG *s;\n\tint ret=-1;\n\n\ts = ECDSA_SIG_new();\n\tif (s == NULL) return(ret);\n\tif (d2i_ECDSA_SIG(&s, &sigbuf, sig_len) == NULL) goto err;\n\tret=ECDSA_do_verify(dgst, dgst_len, s, eckey);\nerr:\n\tECDSA_SIG_free(s);\n\treturn(ret);\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Fix various certificate fingerprint issues.\n\nBy using non-DER or invalid encodings outside the signed portion of a\ncertificate the fingerprint can be changed without breaking the signature.\nAlthough no details of the signed portion of the certificate can be changed\nthis can cause problems with some applications: e.g. those using the\ncertificate fingerprint for blacklists.\n\n1. Reject signatures with non zero unused bits.\n\nIf the BIT STRING containing the signature has non zero unused bits reject\nthe signature. All current signature algorithms require zero unused bits.\n\n2. Check certificate algorithm consistency.\n\nCheck the AlgorithmIdentifier inside TBS matches the one in the\ncertificate signature. NB: this will result in signature failure\nerrors for some broken certificates.\n\n3. Check DSA/ECDSA signatures use DER.\n\nReencode DSA/ECDSA signatures and compare with the original received\nsignature. Return an error if there is a mismatch.\n\nThis will reject various cases including garbage after signature\n(thanks to Antti Karjalainen and Tuomo Untinen from the Codenomicon CROSS\nprogram for discovering this case) and use of BER or invalid ASN.1 INTEGERs\n(negative or with leading zeroes).\n\nCVE-2014-8275\nReviewed-by: Emilia K\u00e4sper '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int test_sqr(BIO *bp, BN_CTX *ctx)\n\t{\n\tBIGNUM a,c,d,e;\n\tint i;\n\n\tBN_init(&a);\n\tBN_init(&c);\n\tBN_init(&d);\n\tBN_init(&e);\n\n\tfor (i=0; i \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Fix for CVE-2014-3570 (with minor bn_asm.c revamp).\n\nReviewed-by: Emilia Kasper '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void bn_sqr_comba4(BN_ULONG *r, const BN_ULONG *a)\n\t{\n#ifdef BN_LLONG\n\tBN_ULLONG t,tt;\n#else\n\tBN_ULONG bl,bh;\n#endif\n\tBN_ULONG t1,t2;\n\tBN_ULONG c1,c2,c3;\n\n\tc1=0;\n\tc2=0;\n\tc3=0;\n\tsqr_add_c(a,0,c1,c2,c3);\n\tr[0]=c1;\n\tc1=0;\n\tsqr_add_c2(a,1,0,c2,c3,c1);\n\tr[1]=c2;\n\tc2=0;\n\tsqr_add_c(a,1,c3,c1,c2);\n\tsqr_add_c2(a,2,0,c3,c1,c2);\n\tr[2]=c3;\n\tc3=0;\n\tsqr_add_c2(a,3,0,c1,c2,c3);\n\tsqr_add_c2(a,2,1,c1,c2,c3);\n\tr[3]=c1;\n\tc1=0;\n\tsqr_add_c(a,2,c2,c3,c1);\n\tsqr_add_c2(a,3,1,c2,c3,c1);\n\tr[4]=c2;\n\tc2=0;\n\tsqr_add_c2(a,3,2,c3,c1,c2);\n\tr[5]=c3;\n\tc3=0;\n\tsqr_add_c(a,3,c1,c2,c3);\n\tr[6]=c1;\n\tr[7]=c2;\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Fix for CVE-2014-3570 (with minor bn_asm.c revamp).\n\nReviewed-by: Emilia Kasper '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ssl3_check_cert_and_algorithm(SSL *s)\n{\n int i, idx;\n long alg_k, alg_a;\n EVP_PKEY *pkey = NULL;\n SESS_CERT *sc;\n#ifndef OPENSSL_NO_RSA\n RSA *rsa;\n#endif\n#ifndef OPENSSL_NO_DH\n DH *dh;\n#endif\n\n alg_k = s->s3->tmp.new_cipher->algorithm_mkey;\n alg_a = s->s3->tmp.new_cipher->algorithm_auth;\n\n /* we don't have a certificate */\n if ((alg_a & (SSL_aDH | SSL_aNULL | SSL_aKRB5)) || (alg_k & SSL_kPSK))\n return (1);\n\n sc = s->session->sess_cert;\n if (sc == NULL) {\n SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR);\n goto err;\n }\n#ifndef OPENSSL_NO_RSA\n rsa = s->session->sess_cert->peer_rsa_tmp;\n#endif\n#ifndef OPENSSL_NO_DH\n dh = s->session->sess_cert->peer_dh_tmp;\n#endif\n\n /* This is the passed certificate */\n\n idx = sc->peer_cert_type;\n#ifndef OPENSSL_NO_ECDH\n if (idx == SSL_PKEY_ECC) {\n if (ssl_check_srvr_ecc_cert_and_alg(sc->peer_pkeys[idx].x509, s) == 0) {\n /* check failed */\n SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_BAD_ECC_CERT);\n goto f_err;\n } else {\n return 1;\n }\n }\n#endif\n pkey = X509_get_pubkey(sc->peer_pkeys[idx].x509);\n i = X509_certificate_type(sc->peer_pkeys[idx].x509, pkey);\n EVP_PKEY_free(pkey);\n\n /* Check that we have a certificate if we require one */\n if ((alg_a & SSL_aRSA) && !has_bits(i, EVP_PK_RSA | EVP_PKT_SIGN)) {\n SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,\n SSL_R_MISSING_RSA_SIGNING_CERT);\n goto f_err;\n }\n#ifndef OPENSSL_NO_DSA\n else if ((alg_a & SSL_aDSS) && !has_bits(i, EVP_PK_DSA | EVP_PKT_SIGN)) {\n SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,\n SSL_R_MISSING_DSA_SIGNING_CERT);\n goto f_err;\n }\n#endif\n#ifndef OPENSSL_NO_RSA\n if ((alg_k & SSL_kRSA) &&\n !(has_bits(i, EVP_PK_RSA | EVP_PKT_ENC) || (rsa != NULL))) {\n SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,\n SSL_R_MISSING_RSA_ENCRYPTING_CERT);\n goto f_err;\n }\n#endif\n#ifndef OPENSSL_NO_DH\n if ((alg_k & SSL_kEDH) &&\n !(has_bits(i, EVP_PK_DH | EVP_PKT_EXCH) || (dh != NULL))) {\n SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_MISSING_DH_KEY);\n goto f_err;\n } else if ((alg_k & SSL_kDHr) && !has_bits(i, EVP_PK_DH | EVP_PKS_RSA)) {\n SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,\n SSL_R_MISSING_DH_RSA_CERT);\n goto f_err;\n }\n# ifndef OPENSSL_NO_DSA\n else if ((alg_k & SSL_kDHd) && !has_bits(i, EVP_PK_DH | EVP_PKS_DSA)) {\n SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,\n SSL_R_MISSING_DH_DSA_CERT);\n goto f_err;\n }\n# endif\n#endif\n\n if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && !has_bits(i, EVP_PKT_EXP)) {\n#ifndef OPENSSL_NO_RSA\n if (alg_k & SSL_kRSA) {\n if (rsa == NULL\n || RSA_size(rsa) * 8 >\n SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {\n SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,\n SSL_R_MISSING_EXPORT_TMP_RSA_KEY);\n goto f_err;\n }\n } else\n#endif\n#ifndef OPENSSL_NO_DH\n if (alg_k & (SSL_kEDH | SSL_kDHr | SSL_kDHd)) {\n if (dh == NULL\n || DH_size(dh) * 8 >\n SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {\n SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,\n SSL_R_MISSING_EXPORT_TMP_DH_KEY);\n goto f_err;\n }\n } else\n#endif\n {\n SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,\n SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);\n goto f_err;\n }\n }\n return (1);\n f_err:\n ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);\n err:\n return (0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'client: reject handshakes with DH parameters < 768 bits.\n\nSince the client has no way of communicating her supported parameter\nrange to the server, connections to servers that choose weak DH will\nsimply fail.\n\nReviewed-by: Kurt Roeckx '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: SSL_SESSION *ssl_session_dup(SSL_SESSION *src, int ticket)\n{\n SSL_SESSION *dest;\n\n dest = OPENSSL_malloc(sizeof(*src));\n if (dest == NULL) {\n goto err;\n }\n memcpy(dest, src, sizeof(*dest));\n\n#ifndef OPENSSL_NO_PSK\n if (src->psk_identity_hint) {\n dest->psk_identity_hint = BUF_strdup(src->psk_identity_hint);\n if (dest->psk_identity_hint == NULL) {\n goto err;\n }\n } else {\n dest->psk_identity_hint = NULL;\n }\n if (src->psk_identity) {\n dest->psk_identity = BUF_strdup(src->psk_identity);\n if (dest->psk_identity == NULL) {\n goto err;\n }\n } else {\n dest->psk_identity = NULL;\n }\n#endif\n\n if (src->sess_cert != NULL)\n CRYPTO_add(&src->sess_cert->references, 1, CRYPTO_LOCK_SSL_SESS_CERT);\n\n if (src->peer != NULL)\n CRYPTO_add(&src->peer->references, 1, CRYPTO_LOCK_X509);\n\n dest->references = 1;\n\n if(src->ciphers != NULL) {\n dest->ciphers = sk_SSL_CIPHER_dup(src->ciphers);\n if (dest->ciphers == NULL)\n goto err;\n } else {\n dest->ciphers = NULL;\n }\n\n if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_SSL_SESSION,\n &dest->ex_data, &src->ex_data)) {\n goto err;\n }\n\n /* We deliberately don't copy the prev and next pointers */\n dest->prev = NULL;\n dest->next = NULL;\n\n#ifndef OPENSSL_NO_TLSEXT\n if (src->tlsext_hostname) {\n dest->tlsext_hostname = BUF_strdup(src->tlsext_hostname);\n if (dest->tlsext_hostname == NULL) {\n goto err;\n }\n } else {\n dest->tlsext_hostname = NULL;\n }\n# ifndef OPENSSL_NO_EC\n if (src->tlsext_ecpointformatlist) {\n dest->tlsext_ecpointformatlist =\n BUF_memdup(src->tlsext_ecpointformatlist,\n src->tlsext_ecpointformatlist_length);\n if (dest->tlsext_ecpointformatlist == NULL)\n goto err;\n dest->tlsext_ecpointformatlist_length =\n src->tlsext_ecpointformatlist_length;\n }\n if (src->tlsext_ellipticcurvelist) {\n dest->tlsext_ellipticcurvelist =\n BUF_memdup(src->tlsext_ellipticcurvelist,\n src->tlsext_ellipticcurvelist_length);\n if (dest->tlsext_ellipticcurvelist == NULL)\n goto err;\n dest->tlsext_ellipticcurvelist_length =\n src->tlsext_ellipticcurvelist_length;\n }\n# endif\n#endif\n\n if (ticket != 0) {\n dest->tlsext_tick_lifetime_hint = src->tlsext_tick_lifetime_hint;\n dest->tlsext_ticklen = src->tlsext_ticklen;\n if((dest->tlsext_tick = OPENSSL_malloc(src->tlsext_ticklen)) == NULL) {\n goto err;\n }\n }\n\n#ifndef OPENSSL_NO_SRP\n dest->srp_username = NULL;\n if (src->srp_username) {\n dest->srp_username = BUF_strdup(src->srp_username);\n if (dest->srp_username == NULL) {\n goto err;\n }\n } else {\n dest->srp_username = NULL;\n }\n#endif\n\n return dest;\nerr:\n SSLerr(SSL_F_SSL_SESSION_DUP, ERR_R_MALLOC_FAILURE);\n SSL_SESSION_free(dest);\n return NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'More ssl_session_dup fixes\n\nFix error handling in ssl_session_dup, as well as incorrect setting up of\nthe session ticket. Follow on from CVE-2015-1791.\n\nThanks to LibreSSL project for reporting these issues.\n\nReviewed-by: Tim Hudson '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,\n const ASN1_ITEM *it,\n int tag, int aclass, char opt, ASN1_TLC *ctx)\n{\n const ASN1_TEMPLATE *tt, *errtt = NULL;\n const ASN1_COMPAT_FUNCS *cf;\n const ASN1_EXTERN_FUNCS *ef;\n const ASN1_AUX *aux = it->funcs;\n ASN1_aux_cb *asn1_cb;\n const unsigned char *p = NULL, *q;\n unsigned char *wp = NULL; /* BIG FAT WARNING! BREAKS CONST WHERE USED */\n unsigned char imphack = 0, oclass;\n char seq_eoc, seq_nolen, cst, isopt;\n long tmplen;\n int i;\n int otag;\n int ret = 0;\n ASN1_VALUE **pchptr, *ptmpval;\n if (!pval)\n return 0;\n if (aux && aux->asn1_cb)\n asn1_cb = aux->asn1_cb;\n else\n asn1_cb = 0;\n\n switch (it->itype) {\n case ASN1_ITYPE_PRIMITIVE:\n if (it->templates) {\n /*\n * tagging or OPTIONAL is currently illegal on an item template\n * because the flags can't get passed down. In practice this\n * isn't a problem: we include the relevant flags from the item\n * template in the template itself.\n */\n if ((tag != -1) || opt) {\n ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,\n ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE);\n goto err;\n }\n return asn1_template_ex_d2i(pval, in, len,\n it->templates, opt, ctx);\n }\n return asn1_d2i_ex_primitive(pval, in, len, it,\n tag, aclass, opt, ctx);\n break;\n\n case ASN1_ITYPE_MSTRING:\n p = *in;\n /* Just read in tag and class */\n ret = asn1_check_tlen(NULL, &otag, &oclass, NULL, NULL,\n &p, len, -1, 0, 1, ctx);\n if (!ret) {\n ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);\n goto err;\n }\n\n /* Must be UNIVERSAL class */\n if (oclass != V_ASN1_UNIVERSAL) {\n /* If OPTIONAL, assume this is OK */\n if (opt)\n return -1;\n ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MSTRING_NOT_UNIVERSAL);\n goto err;\n }\n /* Check tag matches bit map */\n if (!(ASN1_tag2bit(otag) & it->utype)) {\n /* If OPTIONAL, assume this is OK */\n if (opt)\n return -1;\n ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MSTRING_WRONG_TAG);\n goto err;\n }\n return asn1_d2i_ex_primitive(pval, in, len, it, otag, 0, 0, ctx);\n\n case ASN1_ITYPE_EXTERN:\n /* Use new style d2i */\n ef = it->funcs;\n return ef->asn1_ex_d2i(pval, in, len, it, tag, aclass, opt, ctx);\n\n case ASN1_ITYPE_COMPAT:\n /* we must resort to old style evil hackery */\n cf = it->funcs;\n\n /* If OPTIONAL see if it is there */\n if (opt) {\n int exptag;\n p = *in;\n if (tag == -1)\n exptag = it->utype;\n else\n exptag = tag;\n /*\n * Don't care about anything other than presence of expected tag\n */\n\n ret = asn1_check_tlen(NULL, NULL, NULL, NULL, NULL,\n &p, len, exptag, aclass, 1, ctx);\n if (!ret) {\n ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);\n goto err;\n }\n if (ret == -1)\n return -1;\n }\n\n /*\n * This is the old style evil hack IMPLICIT handling: since the\n * underlying code is expecting a tag and class other than the one\n * present we change the buffer temporarily then change it back\n * afterwards. This doesn't and never did work for tags > 30. Yes\n * this is *horrible* but it is only needed for old style d2i which\n * will hopefully not be around for much longer. FIXME: should copy\n * the buffer then modify it so the input buffer can be const: we\n * should *always* copy because the old style d2i might modify the\n * buffer.\n */\n\n if (tag != -1) {\n wp = *(unsigned char **)in;\n imphack = *wp;\n if (p == NULL) {\n ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);\n goto err;\n }\n *wp = (unsigned char)((*p & V_ASN1_CONSTRUCTED)\n | it->utype);\n }\n\n ptmpval = cf->asn1_d2i(pval, in, len);\n\n if (tag != -1)\n *wp = imphack;\n\n if (ptmpval)\n return 1;\n\n ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);\n goto err;\n\n case ASN1_ITYPE_CHOICE:\n if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it))\n goto auxerr;\n if (*pval) {\n /* Free up and zero CHOICE value if initialised */\n i = asn1_get_choice_selector(pval, it);\n if ((i >= 0) && (i < it->tcount)) {\n tt = it->templates + i;\n pchptr = asn1_get_field_ptr(pval, tt);\n ASN1_template_free(pchptr, tt);\n asn1_set_choice_selector(pval, -1, it);\n }\n } else if (!ASN1_item_ex_new(pval, it)) {\n ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);\n goto err;\n }\n /* CHOICE type, try each possibility in turn */\n p = *in;\n for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {\n pchptr = asn1_get_field_ptr(pval, tt);\n /*\n * We mark field as OPTIONAL so its absence can be recognised.\n */\n ret = asn1_template_ex_d2i(pchptr, &p, len, tt, 1, ctx);\n /* If field not present, try the next one */\n if (ret == -1)\n continue;\n /* If positive return, read OK, break loop */\n if (ret > 0)\n break;\n /* Otherwise must be an ASN1 parsing error */\n errtt = tt;\n ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);\n goto err;\n }\n\n /* Did we fall off the end without reading anything? */\n if (i == it->tcount) {\n /* If OPTIONAL, this is OK */\n if (opt) {\n /* Free and zero it */\n ASN1_item_ex_free(pval, it);\n return -1;\n }\n ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_NO_MATCHING_CHOICE_TYPE);\n goto err;\n }\n\n asn1_set_choice_selector(pval, i, it);\n *in = p;\n if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it))\n goto auxerr;\n return 1;\n\n case ASN1_ITYPE_NDEF_SEQUENCE:\n case ASN1_ITYPE_SEQUENCE:\n p = *in;\n tmplen = len;\n\n /* If no IMPLICIT tagging set to SEQUENCE, UNIVERSAL */\n if (tag == -1) {\n tag = V_ASN1_SEQUENCE;\n aclass = V_ASN1_UNIVERSAL;\n }\n /* Get SEQUENCE length and update len, p */\n ret = asn1_check_tlen(&len, NULL, NULL, &seq_eoc, &cst,\n &p, len, tag, aclass, opt, ctx);\n if (!ret) {\n ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);\n goto err;\n } else if (ret == -1)\n return -1;\n if (aux && (aux->flags & ASN1_AFLG_BROKEN)) {\n len = tmplen - (p - *in);\n seq_nolen = 1;\n }\n /* If indefinite we don't do a length check */\n else\n seq_nolen = seq_eoc;\n if (!cst) {\n ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_SEQUENCE_NOT_CONSTRUCTED);\n goto err;\n }\n\n if (!*pval && !ASN1_item_ex_new(pval, it)) {\n ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);\n goto err;\n }\n\n if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it))\n goto auxerr;\n\n /* Free up and zero any ADB found */\n for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {\n if (tt->flags & ASN1_TFLG_ADB_MASK) {\n const ASN1_TEMPLATE *seqtt;\n ASN1_VALUE **pseqval;\n seqtt = asn1_do_adb(pval, tt, 1);\n pseqval = asn1_get_field_ptr(pval, seqtt);\n ASN1_template_free(pseqval, seqtt);\n }\n }\n\n /* Get each field entry */\n for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {\n const ASN1_TEMPLATE *seqtt;\n ASN1_VALUE **pseqval;\n seqtt = asn1_do_adb(pval, tt, 1);\n if (!seqtt)\n goto err;\n pseqval = asn1_get_field_ptr(pval, seqtt);\n /* Have we ran out of data? */\n if (!len)\n break;\n q = p;\n if (asn1_check_eoc(&p, len)) {\n if (!seq_eoc) {\n ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_UNEXPECTED_EOC);\n goto err;\n }\n len -= p - q;\n seq_eoc = 0;\n q = p;\n break;\n }\n /*\n * This determines the OPTIONAL flag value. The field cannot be\n * omitted if it is the last of a SEQUENCE and there is still\n * data to be read. This isn't strictly necessary but it\n * increases efficiency in some cases.\n */\n if (i == (it->tcount - 1))\n isopt = 0;\n else\n isopt = (char)(seqtt->flags & ASN1_TFLG_OPTIONAL);\n /*\n * attempt to read in field, allowing each to be OPTIONAL\n */\n\n ret = asn1_template_ex_d2i(pseqval, &p, len, seqtt, isopt, ctx);\n if (!ret) {\n errtt = seqtt;\n goto err;\n } else if (ret == -1) {\n /*\n * OPTIONAL component absent. Free and zero the field.\n */\n ASN1_template_free(pseqval, seqtt);\n continue;\n }\n /* Update length */\n len -= p - q;\n }\n\n /* Check for EOC if expecting one */\n if (seq_eoc && !asn1_check_eoc(&p, len)) {\n ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MISSING_EOC);\n goto err;\n }\n /* Check all data read */\n if (!seq_nolen && len) {\n ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_SEQUENCE_LENGTH_MISMATCH);\n goto err;\n }\n\n /*\n * If we get here we've got no more data in the SEQUENCE, however we\n * may not have read all fields so check all remaining are OPTIONAL\n * and clear any that are.\n */\n for (; i < it->tcount; tt++, i++) {\n const ASN1_TEMPLATE *seqtt;\n seqtt = asn1_do_adb(pval, tt, 1);\n if (!seqtt)\n goto err;\n if (seqtt->flags & ASN1_TFLG_OPTIONAL) {\n ASN1_VALUE **pseqval;\n pseqval = asn1_get_field_ptr(pval, seqtt);\n ASN1_template_free(pseqval, seqtt);\n } else {\n errtt = seqtt;\n ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_FIELD_MISSING);\n goto err;\n }\n }\n /* Save encoding */\n if (!asn1_enc_save(pval, *in, p - *in, it))\n goto auxerr;\n *in = p;\n if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it))\n goto auxerr;\n return 1;\n\n default:\n return 0;\n }\n auxerr:\n ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_AUX_ERROR);\n err:\n ASN1_item_ex_free(pval, it);\n if (errtt)\n ERR_add_error_data(4, \"Field=\", errtt->field_name,\n \", Type=\", it->sname);\n else\n ERR_add_error_data(2, \"Type=\", it->sname);\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'Fix leak with ASN.1 combine.\n\nWhen parsing a combined structure pass a flag to the decode routine\nso on error a pointer to the parent structure is not zeroed as\nthis will leak any additional components in the parent.\n\nThis can leak memory in any application parsing PKCS#7 or CMS structures.\n\nCVE-2015-3195.\n\nThanks to Adam Langley (Google/BoringSSL) for discovering this bug using\nlibFuzzer.\n\nPR#4131\n\nReviewed-by: Richard Levitte '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: size_t tls12_get_psigalgs(SSL *s, const unsigned char **psigs)\n\t{\n\t/* If Suite B mode use Suite B sigalgs only, ignore any other\n\t * preferences.\n\t */\n#ifndef OPENSSL_NO_EC\n\tswitch (tls1_suiteb(s))\n\t\t{\n\tcase SSL_CERT_FLAG_SUITEB_128_LOS:\n\t\t*psigs = suiteb_sigalgs;\n\t\treturn sizeof(suiteb_sigalgs);\n\n\tcase SSL_CERT_FLAG_SUITEB_128_LOS_ONLY:\n\t\t*psigs = suiteb_sigalgs;\n\t\treturn 2;\n\n\tcase SSL_CERT_FLAG_SUITEB_192_LOS:\n\t\t*psigs = suiteb_sigalgs + 2;\n\t\treturn 2;\n\t\t}\n#endif\n\t/* If server use client authentication sigalgs if not NULL */\n\tif (s->server && s->cert->client_sigalgs)\n\t\t{\n\t\t*psigs = s->cert->client_sigalgs;\n\t\treturn s->cert->client_sigalgslen;\n\t\t}\n\telse if (s->cert->conf_sigalgs)\n\t\t{\n\t\t*psigs = s->cert->conf_sigalgs;\n\t\treturn s->cert->conf_sigalgslen;\n\t\t}\n\telse\n\t\t{\n\t\t*psigs = tls12_sigalgs;\n#ifdef OPENSSL_FIPS\n\t\t/* If FIPS mode don't include MD5 which is last */\n\t\tif (FIPS_mode())\n\t\t\treturn sizeof(tls12_sigalgs) - 2;\n\t\telse\n#endif\n\t\t\treturn sizeof(tls12_sigalgs);\n\t\t}\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-19'], 'message': 'Prevent use of RSA+MD5 in TLS 1.2 by default.\n\nRemoving RSA+MD5 from the default signature algorithm list\nprevents its use by default.\n\nIf a broken implementation attempts to use RSA+MD5 anyway the sanity\nchecking of signature algorithms will cause a fatal alert.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: LogL16Decode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s)\n{\n\tstatic const char module[] = \"LogL16Decode\";\n\tLogLuvState* sp = DecoderState(tif);\n\tint shft;\n\ttmsize_t i;\n\ttmsize_t npixels;\n\tunsigned char* bp;\n\tint16* tp;\n\tint16 b;\n\ttmsize_t cc;\n\tint rc;\n\n\tassert(s == 0);\n\tassert(sp != NULL);\n\n\tnpixels = occ / sp->pixel_size;\n\n\tif (sp->user_datafmt == SGILOGDATAFMT_16BIT)\n\t\ttp = (int16*) op;\n\telse {\n\t\tassert(sp->tbuflen >= npixels);\n\t\ttp = (int16*) sp->tbuf;\n\t}\n\t_TIFFmemset((void*) tp, 0, npixels*sizeof (tp[0]));\n\n\tbp = (unsigned char*) tif->tif_rawcp;\n\tcc = tif->tif_rawcc;\n\t/* get each byte string */\n\tfor (shft = 2*8; (shft -= 8) >= 0; ) {\n\t\tfor (i = 0; i < npixels && cc > 0; )\n\t\t\tif (*bp >= 128) {\t\t/* run */\n\t\t\t\trc = *bp++ + (2-128); /* TODO: potential input buffer overrun when decoding corrupt or truncated data */\n\t\t\t\tb = (int16)(*bp++ << shft);\n\t\t\t\tcc -= 2;\n\t\t\t\twhile (rc-- && i < npixels)\n\t\t\t\t\ttp[i++] |= b;\n\t\t\t} else {\t\t\t/* non-run */\n\t\t\t\trc = *bp++;\t\t/* nul is noop */\n\t\t\t\twhile (--cc && rc-- && i < npixels)\n\t\t\t\t\ttp[i++] |= (int16)*bp++ << shft;\n\t\t\t}\n\t\tif (i != npixels) {\n#if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))\n\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\t\t \"Not enough data at row %lu (short %I64d pixels)\",\n\t\t\t\t (unsigned long) tif->tif_row,\n\t\t\t\t (unsigned __int64) (npixels - i));\n#else\n\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\t\t \"Not enough data at row %lu (short %llu pixels)\",\n\t\t\t\t (unsigned long) tif->tif_row,\n\t\t\t\t (unsigned long long) (npixels - i));\n#endif\n\t\t\ttif->tif_rawcp = (uint8*) bp;\n\t\t\ttif->tif_rawcc = cc;\n\t\t\treturn (0);\n\t\t}\n\t}\n\t(*sp->tfunc)(sp, op, npixels);\n\ttif->tif_rawcp = (uint8*) bp;\n\ttif->tif_rawcc = cc;\n\treturn (1);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': '* libtiff/tif_luv.c: fix potential out-of-bound writes in decode\nfunctions in non debug builds by replacing assert()s by regular if\nchecks (bugzilla #2522).\nFix potential out-of-bound reads in case of short input data.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p,\n const BIGNUM *m, BN_CTX *ctx,\n BN_MONT_CTX *in_mont)\n{\n int i, bits, ret = 0, window, wvalue;\n int top;\n BN_MONT_CTX *mont = NULL;\n\n int numPowers;\n unsigned char *powerbufFree = NULL;\n int powerbufLen = 0;\n unsigned char *powerbuf = NULL;\n BIGNUM tmp, am;\n#if defined(SPARC_T4_MONT)\n unsigned int t4 = 0;\n#endif\n\n bn_check_top(a);\n bn_check_top(p);\n bn_check_top(m);\n\n if (!BN_is_odd(m)) {\n BNerr(BN_F_BN_MOD_EXP_MONT_CONSTTIME, BN_R_CALLED_WITH_EVEN_MODULUS);\n return (0);\n }\n\n top = m->top;\n\n bits = BN_num_bits(p);\n if (bits == 0) {\n /* x**0 mod 1 is still zero. */\n if (BN_is_one(m)) {\n ret = 1;\n BN_zero(rr);\n } else {\n ret = BN_one(rr);\n }\n return ret;\n }\n\n BN_CTX_start(ctx);\n\n /*\n * Allocate a montgomery context if it was not supplied by the caller. If\n * this is not done, things will break in the montgomery part.\n */\n if (in_mont != NULL)\n mont = in_mont;\n else {\n if ((mont = BN_MONT_CTX_new()) == NULL)\n goto err;\n if (!BN_MONT_CTX_set(mont, m, ctx))\n goto err;\n }\n\n#ifdef RSAZ_ENABLED\n /*\n * If the size of the operands allow it, perform the optimized\n * RSAZ exponentiation. For further information see\n * crypto/bn/rsaz_exp.c and accompanying assembly modules.\n */\n if ((16 == a->top) && (16 == p->top) && (BN_num_bits(m) == 1024)\n && rsaz_avx2_eligible()) {\n if (NULL == bn_wexpand(rr, 16))\n goto err;\n RSAZ_1024_mod_exp_avx2(rr->d, a->d, p->d, m->d, mont->RR.d,\n mont->n0[0]);\n rr->top = 16;\n rr->neg = 0;\n bn_correct_top(rr);\n ret = 1;\n goto err;\n } else if ((8 == a->top) && (8 == p->top) && (BN_num_bits(m) == 512)) {\n if (NULL == bn_wexpand(rr, 8))\n goto err;\n RSAZ_512_mod_exp(rr->d, a->d, p->d, m->d, mont->n0[0], mont->RR.d);\n rr->top = 8;\n rr->neg = 0;\n bn_correct_top(rr);\n ret = 1;\n goto err;\n }\n#endif\n\n /* Get the window size to use with size of p. */\n window = BN_window_bits_for_ctime_exponent_size(bits);\n#if defined(SPARC_T4_MONT)\n if (window >= 5 && (top & 15) == 0 && top <= 64 &&\n (OPENSSL_sparcv9cap_P[1] & (CFR_MONTMUL | CFR_MONTSQR)) ==\n (CFR_MONTMUL | CFR_MONTSQR) && (t4 = OPENSSL_sparcv9cap_P[0]))\n window = 5;\n else\n#endif\n#if defined(OPENSSL_BN_ASM_MONT5)\n if (window >= 5) {\n window = 5; /* ~5% improvement for RSA2048 sign, and even\n * for RSA4096 */\n if ((top & 7) == 0)\n powerbufLen += 2 * top * sizeof(m->d[0]);\n }\n#endif\n (void)0;\n\n /*\n * Allocate a buffer large enough to hold all of the pre-computed powers\n * of am, am itself and tmp.\n */\n numPowers = 1 << window;\n powerbufLen += sizeof(m->d[0]) * (top * numPowers +\n ((2 * top) >\n numPowers ? (2 * top) : numPowers));\n#ifdef alloca\n if (powerbufLen < 3072)\n powerbufFree =\n alloca(powerbufLen + MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH);\n else\n#endif\n if ((powerbufFree =\n OPENSSL_malloc(powerbufLen + MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH))\n == NULL)\n goto err;\n\n powerbuf = MOD_EXP_CTIME_ALIGN(powerbufFree);\n memset(powerbuf, 0, powerbufLen);\n\n#ifdef alloca\n if (powerbufLen < 3072)\n powerbufFree = NULL;\n#endif\n\n /* lay down tmp and am right after powers table */\n tmp.d = (BN_ULONG *)(powerbuf + sizeof(m->d[0]) * top * numPowers);\n am.d = tmp.d + top;\n tmp.top = am.top = 0;\n tmp.dmax = am.dmax = top;\n tmp.neg = am.neg = 0;\n tmp.flags = am.flags = BN_FLG_STATIC_DATA;\n\n /* prepare a^0 in Montgomery domain */\n#if 1 /* by Shay Gueron's suggestion */\n if (m->d[top - 1] & (((BN_ULONG)1) << (BN_BITS2 - 1))) {\n /* 2^(top*BN_BITS2) - m */\n tmp.d[0] = (0 - m->d[0]) & BN_MASK2;\n for (i = 1; i < top; i++)\n tmp.d[i] = (~m->d[i]) & BN_MASK2;\n tmp.top = top;\n } else\n#endif\n if (!BN_to_montgomery(&tmp, BN_value_one(), mont, ctx))\n goto err;\n\n /* prepare a^1 in Montgomery domain */\n if (a->neg || BN_ucmp(a, m) >= 0) {\n if (!BN_mod(&am, a, m, ctx))\n goto err;\n if (!BN_to_montgomery(&am, &am, mont, ctx))\n goto err;\n } else if (!BN_to_montgomery(&am, a, mont, ctx))\n goto err;\n\n#if defined(SPARC_T4_MONT)\n if (t4) {\n typedef int (*bn_pwr5_mont_f) (BN_ULONG *tp, const BN_ULONG *np,\n const BN_ULONG *n0, const void *table,\n int power, int bits);\n int bn_pwr5_mont_t4_8(BN_ULONG *tp, const BN_ULONG *np,\n const BN_ULONG *n0, const void *table,\n int power, int bits);\n int bn_pwr5_mont_t4_16(BN_ULONG *tp, const BN_ULONG *np,\n const BN_ULONG *n0, const void *table,\n int power, int bits);\n int bn_pwr5_mont_t4_24(BN_ULONG *tp, const BN_ULONG *np,\n const BN_ULONG *n0, const void *table,\n int power, int bits);\n int bn_pwr5_mont_t4_32(BN_ULONG *tp, const BN_ULONG *np,\n const BN_ULONG *n0, const void *table,\n int power, int bits);\n static const bn_pwr5_mont_f pwr5_funcs[4] = {\n bn_pwr5_mont_t4_8, bn_pwr5_mont_t4_16,\n bn_pwr5_mont_t4_24, bn_pwr5_mont_t4_32\n };\n bn_pwr5_mont_f pwr5_worker = pwr5_funcs[top / 16 - 1];\n\n typedef int (*bn_mul_mont_f) (BN_ULONG *rp, const BN_ULONG *ap,\n const void *bp, const BN_ULONG *np,\n const BN_ULONG *n0);\n int bn_mul_mont_t4_8(BN_ULONG *rp, const BN_ULONG *ap, const void *bp,\n const BN_ULONG *np, const BN_ULONG *n0);\n int bn_mul_mont_t4_16(BN_ULONG *rp, const BN_ULONG *ap,\n const void *bp, const BN_ULONG *np,\n const BN_ULONG *n0);\n int bn_mul_mont_t4_24(BN_ULONG *rp, const BN_ULONG *ap,\n const void *bp, const BN_ULONG *np,\n const BN_ULONG *n0);\n int bn_mul_mont_t4_32(BN_ULONG *rp, const BN_ULONG *ap,\n const void *bp, const BN_ULONG *np,\n const BN_ULONG *n0);\n static const bn_mul_mont_f mul_funcs[4] = {\n bn_mul_mont_t4_8, bn_mul_mont_t4_16,\n bn_mul_mont_t4_24, bn_mul_mont_t4_32\n };\n bn_mul_mont_f mul_worker = mul_funcs[top / 16 - 1];\n\n void bn_mul_mont_vis3(BN_ULONG *rp, const BN_ULONG *ap,\n const void *bp, const BN_ULONG *np,\n const BN_ULONG *n0, int num);\n void bn_mul_mont_t4(BN_ULONG *rp, const BN_ULONG *ap,\n const void *bp, const BN_ULONG *np,\n const BN_ULONG *n0, int num);\n void bn_mul_mont_gather5_t4(BN_ULONG *rp, const BN_ULONG *ap,\n const void *table, const BN_ULONG *np,\n const BN_ULONG *n0, int num, int power);\n void bn_flip_n_scatter5_t4(const BN_ULONG *inp, size_t num,\n void *table, size_t power);\n void bn_gather5_t4(BN_ULONG *out, size_t num,\n void *table, size_t power);\n void bn_flip_t4(BN_ULONG *dst, BN_ULONG *src, size_t num);\n\n BN_ULONG *np = mont->N.d, *n0 = mont->n0;\n int stride = 5 * (6 - (top / 16 - 1)); /* multiple of 5, but less\n * than 32 */\n\n /*\n * BN_to_montgomery can contaminate words above .top [in\n * BN_DEBUG[_DEBUG] build]...\n */\n for (i = am.top; i < top; i++)\n am.d[i] = 0;\n for (i = tmp.top; i < top; i++)\n tmp.d[i] = 0;\n\n bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, 0);\n bn_flip_n_scatter5_t4(am.d, top, powerbuf, 1);\n if (!(*mul_worker) (tmp.d, am.d, am.d, np, n0) &&\n !(*mul_worker) (tmp.d, am.d, am.d, np, n0))\n bn_mul_mont_vis3(tmp.d, am.d, am.d, np, n0, top);\n bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, 2);\n\n for (i = 3; i < 32; i++) {\n /* Calculate a^i = a^(i-1) * a */\n if (!(*mul_worker) (tmp.d, tmp.d, am.d, np, n0) &&\n !(*mul_worker) (tmp.d, tmp.d, am.d, np, n0))\n bn_mul_mont_vis3(tmp.d, tmp.d, am.d, np, n0, top);\n bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, i);\n }\n\n /* switch to 64-bit domain */\n np = alloca(top * sizeof(BN_ULONG));\n top /= 2;\n bn_flip_t4(np, mont->N.d, top);\n\n bits--;\n for (wvalue = 0, i = bits % 5; i >= 0; i--, bits--)\n wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);\n bn_gather5_t4(tmp.d, top, powerbuf, wvalue);\n\n /*\n * Scan the exponent one window at a time starting from the most\n * significant bits.\n */\n while (bits >= 0) {\n if (bits < stride)\n stride = bits + 1;\n bits -= stride;\n wvalue = bn_get_bits(p, bits + 1);\n\n if ((*pwr5_worker) (tmp.d, np, n0, powerbuf, wvalue, stride))\n continue;\n /* retry once and fall back */\n if ((*pwr5_worker) (tmp.d, np, n0, powerbuf, wvalue, stride))\n continue;\n\n bits += stride - 5;\n wvalue >>= stride - 5;\n wvalue &= 31;\n bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);\n bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);\n bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);\n bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);\n bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);\n bn_mul_mont_gather5_t4(tmp.d, tmp.d, powerbuf, np, n0, top,\n wvalue);\n }\n\n bn_flip_t4(tmp.d, tmp.d, top);\n top *= 2;\n /* back to 32-bit domain */\n tmp.top = top;\n bn_correct_top(&tmp);\n OPENSSL_cleanse(np, top * sizeof(BN_ULONG));\n } else\n#endif\n#if defined(OPENSSL_BN_ASM_MONT5)\n if (window == 5 && top > 1) {\n /*\n * This optimization uses ideas from http://eprint.iacr.org/2011/239,\n * specifically optimization of cache-timing attack countermeasures\n * and pre-computation optimization.\n */\n\n /*\n * Dedicated window==4 case improves 512-bit RSA sign by ~15%, but as\n * 512-bit RSA is hardly relevant, we omit it to spare size...\n */\n void bn_mul_mont_gather5(BN_ULONG *rp, const BN_ULONG *ap,\n const void *table, const BN_ULONG *np,\n const BN_ULONG *n0, int num, int power);\n void bn_scatter5(const BN_ULONG *inp, size_t num,\n void *table, size_t power);\n void bn_gather5(BN_ULONG *out, size_t num, void *table, size_t power);\n void bn_power5(BN_ULONG *rp, const BN_ULONG *ap,\n const void *table, const BN_ULONG *np,\n const BN_ULONG *n0, int num, int power);\n int bn_get_bits5(const BN_ULONG *ap, int off);\n int bn_from_montgomery(BN_ULONG *rp, const BN_ULONG *ap,\n const BN_ULONG *not_used, const BN_ULONG *np,\n const BN_ULONG *n0, int num);\n\n BN_ULONG *np = mont->N.d, *n0 = mont->n0, *np2;\n\n /*\n * BN_to_montgomery can contaminate words above .top [in\n * BN_DEBUG[_DEBUG] build]...\n */\n for (i = am.top; i < top; i++)\n am.d[i] = 0;\n for (i = tmp.top; i < top; i++)\n tmp.d[i] = 0;\n\n if (top & 7)\n np2 = np;\n else\n for (np2 = am.d + top, i = 0; i < top; i++)\n np2[2 * i] = np[i];\n\n bn_scatter5(tmp.d, top, powerbuf, 0);\n bn_scatter5(am.d, am.top, powerbuf, 1);\n bn_mul_mont(tmp.d, am.d, am.d, np, n0, top);\n bn_scatter5(tmp.d, top, powerbuf, 2);\n\n# if 0\n for (i = 3; i < 32; i++) {\n /* Calculate a^i = a^(i-1) * a */\n bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np2, n0, top, i - 1);\n bn_scatter5(tmp.d, top, powerbuf, i);\n }\n# else\n /* same as above, but uses squaring for 1/2 of operations */\n for (i = 4; i < 32; i *= 2) {\n bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);\n bn_scatter5(tmp.d, top, powerbuf, i);\n }\n for (i = 3; i < 8; i += 2) {\n int j;\n bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np2, n0, top, i - 1);\n bn_scatter5(tmp.d, top, powerbuf, i);\n for (j = 2 * i; j < 32; j *= 2) {\n bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);\n bn_scatter5(tmp.d, top, powerbuf, j);\n }\n }\n for (; i < 16; i += 2) {\n bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np2, n0, top, i - 1);\n bn_scatter5(tmp.d, top, powerbuf, i);\n bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);\n bn_scatter5(tmp.d, top, powerbuf, 2 * i);\n }\n for (; i < 32; i += 2) {\n bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np2, n0, top, i - 1);\n bn_scatter5(tmp.d, top, powerbuf, i);\n }\n# endif\n bits--;\n for (wvalue = 0, i = bits % 5; i >= 0; i--, bits--)\n wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);\n bn_gather5(tmp.d, top, powerbuf, wvalue);\n\n /*\n * Scan the exponent one window at a time starting from the most\n * significant bits.\n */\n if (top & 7)\n while (bits >= 0) {\n for (wvalue = 0, i = 0; i < 5; i++, bits--)\n wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);\n\n bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);\n bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);\n bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);\n bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);\n bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);\n bn_mul_mont_gather5(tmp.d, tmp.d, powerbuf, np, n0, top,\n wvalue);\n } else {\n while (bits >= 0) {\n wvalue = bn_get_bits5(p->d, bits - 4);\n bits -= 5;\n bn_power5(tmp.d, tmp.d, powerbuf, np2, n0, top, wvalue);\n }\n }\n\n ret = bn_from_montgomery(tmp.d, tmp.d, NULL, np2, n0, top);\n tmp.top = top;\n bn_correct_top(&tmp);\n if (ret) {\n if (!BN_copy(rr, &tmp))\n ret = 0;\n goto err; /* non-zero ret means it's not error */\n }\n } else\n#endif\n {\n if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 0, numPowers))\n goto err;\n if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&am, top, powerbuf, 1, numPowers))\n goto err;\n\n /*\n * If the window size is greater than 1, then calculate\n * val[i=2..2^winsize-1]. Powers are computed as a*a^(i-1) (even\n * powers could instead be computed as (a^(i/2))^2 to use the slight\n * performance advantage of sqr over mul).\n */\n if (window > 1) {\n if (!BN_mod_mul_montgomery(&tmp, &am, &am, mont, ctx))\n goto err;\n if (!MOD_EXP_CTIME_COPY_TO_PREBUF\n (&tmp, top, powerbuf, 2, numPowers))\n goto err;\n for (i = 3; i < numPowers; i++) {\n /* Calculate a^i = a^(i-1) * a */\n if (!BN_mod_mul_montgomery(&tmp, &am, &tmp, mont, ctx))\n goto err;\n if (!MOD_EXP_CTIME_COPY_TO_PREBUF\n (&tmp, top, powerbuf, i, numPowers))\n goto err;\n }\n }\n\n bits--;\n for (wvalue = 0, i = bits % window; i >= 0; i--, bits--)\n wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);\n if (!MOD_EXP_CTIME_COPY_FROM_PREBUF\n (&tmp, top, powerbuf, wvalue, numPowers))\n goto err;\n\n /*\n * Scan the exponent one window at a time starting from the most\n * significant bits.\n */\n while (bits >= 0) {\n wvalue = 0; /* The 'value' of the window */\n\n /* Scan the window, squaring the result as we go */\n for (i = 0; i < window; i++, bits--) {\n if (!BN_mod_mul_montgomery(&tmp, &tmp, &tmp, mont, ctx))\n goto err;\n wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);\n }\n\n /*\n * Fetch the appropriate pre-computed value from the pre-buf\n */\n if (!MOD_EXP_CTIME_COPY_FROM_PREBUF\n (&am, top, powerbuf, wvalue, numPowers))\n goto err;\n\n /* Multiply the result into the intermediate result */\n if (!BN_mod_mul_montgomery(&tmp, &tmp, &am, mont, ctx))\n goto err;\n }\n }\n\n /* Convert the final result from montgomery to standard format */\n#if defined(SPARC_T4_MONT)\n if (OPENSSL_sparcv9cap_P[0] & (SPARCV9_VIS3 | SPARCV9_PREFER_FPU)) {\n am.d[0] = 1; /* borrow am */\n for (i = 1; i < top; i++)\n am.d[i] = 0;\n if (!BN_mod_mul_montgomery(rr, &tmp, &am, mont, ctx))\n goto err;\n } else\n#endif\n if (!BN_from_montgomery(rr, &tmp, mont, ctx))\n goto err;\n ret = 1;\n err:\n if (in_mont == NULL)\n BN_MONT_CTX_free(mont);\n if (powerbuf != NULL) {\n OPENSSL_cleanse(powerbuf, powerbufLen);\n OPENSSL_free(powerbufFree);\n }\n BN_CTX_end(ctx);\n return (ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'bn/bn_exp.c: constant-time MOD_EXP_CTIME_COPY_FROM_PREBUF.\n\nPerformance penalty varies from platform to platform, and even\nkey length. For rsa2048 sign it was observed to reach almost 10%.\n\nCVE-2016-0702\n\nReviewed-by: Richard Levitte \nReviewed-by: Rich Salz '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int BIO_vprintf(BIO *bio, const char *format, va_list args)\n{\n int ret;\n size_t retlen;\n char hugebuf[1024 * 2]; /* Was previously 10k, which is unreasonable\n * in small-stack environments, like threads\n * or DOS programs. */\n char *hugebufp = hugebuf;\n size_t hugebufsize = sizeof(hugebuf);\n char *dynbuf = NULL;\n int ignored;\n\n dynbuf = NULL;\n CRYPTO_push_info(\"doapr()\");\n _dopr(&hugebufp, &dynbuf, &hugebufsize, &retlen, &ignored, format, args);\n if (dynbuf) {\n ret = BIO_write(bio, dynbuf, (int)retlen);\n OPENSSL_free(dynbuf);\n } else {\n ret = BIO_write(bio, hugebuf, (int)retlen);\n }\n CRYPTO_pop_info();\n return (ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'Fix memory issues in BIO_*printf functions\n\nThe internal |fmtstr| function used in processing a \"%s\" format string\nin the BIO_*printf functions could overflow while calculating the length\nof a string and cause an OOB read when printing very long strings.\n\nAdditionally the internal |doapr_outch| function can attempt to write to\nan OOB memory location (at an offset from the NULL pointer) in the event of\na memory allocation failure. In 1.0.2 and below this could be caused where\nthe size of a buffer to be allocated is greater than INT_MAX. E.g. this\ncould be in processing a very long \"%s\" format string. Memory leaks can also\noccur.\n\nThese issues will only occur on certain platforms where sizeof(size_t) >\nsizeof(int). E.g. many 64 bit systems. The first issue may mask the second\nissue dependent on compiler behaviour.\n\nThese problems could enable attacks where large amounts of untrusted data\nis passed to the BIO_*printf functions. If applications use these functions\nin this way then they could be vulnerable. OpenSSL itself uses these\nfunctions when printing out human-readable dumps of ASN.1 data. Therefore\napplications that print this data could be vulnerable if the data is from\nuntrusted sources. OpenSSL command line applications could also be\nvulnerable where they print out ASN.1 data, or if untrusted data is passed\nas command line arguments.\n\nLibssl is not considered directly vulnerable. Additionally certificates etc\nreceived via remote connections via libssl are also unlikely to be able to\ntrigger these issues because of message size limits enforced within libssl.\n\nCVE-2016-0799\n\nIssue reported by Guido Vranken.\n\nReviewed-by: Andy Polyakov '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int aesni_cbc_hmac_sha256_cipher(EVP_CIPHER_CTX *ctx,\n unsigned char *out,\n const unsigned char *in, size_t len)\n{\n EVP_AES_HMAC_SHA256 *key = data(ctx);\n unsigned int l;\n size_t plen = key->payload_length, iv = 0, /* explicit IV in TLS 1.1 and\n * later */\n sha_off = 0;\n# if defined(STITCHED_CALL)\n size_t aes_off = 0, blocks;\n\n sha_off = SHA256_CBLOCK - key->md.num;\n# endif\n\n key->payload_length = NO_PAYLOAD_LENGTH;\n\n if (len % AES_BLOCK_SIZE)\n return 0;\n\n if (ctx->encrypt) {\n if (plen == NO_PAYLOAD_LENGTH)\n plen = len;\n else if (len !=\n ((plen + SHA256_DIGEST_LENGTH +\n AES_BLOCK_SIZE) & -AES_BLOCK_SIZE))\n return 0;\n else if (key->aux.tls_ver >= TLS1_1_VERSION)\n iv = AES_BLOCK_SIZE;\n\n# if defined(STITCHED_CALL)\n /*\n * Assembly stitch handles AVX-capable processors, but its\n * performance is not optimal on AMD Jaguar, ~40% worse, for\n * unknown reasons. Incidentally processor in question supports\n * AVX, but not AMD-specific XOP extension, which can be used\n * to identify it and avoid stitch invocation. So that after we\n * establish that current CPU supports AVX, we even see if it's\n * either even XOP-capable Bulldozer-based or GenuineIntel one.\n */\n if (OPENSSL_ia32cap_P[1] & (1 << (60 - 32)) && /* AVX? */\n ((OPENSSL_ia32cap_P[1] & (1 << (43 - 32))) /* XOP? */\n | (OPENSSL_ia32cap_P[0] & (1<<30))) && /* \"Intel CPU\"? */\n plen > (sha_off + iv) &&\n (blocks = (plen - (sha_off + iv)) / SHA256_CBLOCK)) {\n SHA256_Update(&key->md, in + iv, sha_off);\n\n (void)aesni_cbc_sha256_enc(in, out, blocks, &key->ks,\n ctx->iv, &key->md, in + iv + sha_off);\n blocks *= SHA256_CBLOCK;\n aes_off += blocks;\n sha_off += blocks;\n key->md.Nh += blocks >> 29;\n key->md.Nl += blocks <<= 3;\n if (key->md.Nl < (unsigned int)blocks)\n key->md.Nh++;\n } else {\n sha_off = 0;\n }\n# endif\n sha_off += iv;\n SHA256_Update(&key->md, in + sha_off, plen - sha_off);\n\n if (plen != len) { /* \"TLS\" mode of operation */\n if (in != out)\n memcpy(out + aes_off, in + aes_off, plen - aes_off);\n\n /* calculate HMAC and append it to payload */\n SHA256_Final(out + plen, &key->md);\n key->md = key->tail;\n SHA256_Update(&key->md, out + plen, SHA256_DIGEST_LENGTH);\n SHA256_Final(out + plen, &key->md);\n\n /* pad the payload|hmac */\n plen += SHA256_DIGEST_LENGTH;\n for (l = len - plen - 1; plen < len; plen++)\n out[plen] = l;\n /* encrypt HMAC|padding at once */\n aesni_cbc_encrypt(out + aes_off, out + aes_off, len - aes_off,\n &key->ks, ctx->iv, 1);\n } else {\n aesni_cbc_encrypt(in + aes_off, out + aes_off, len - aes_off,\n &key->ks, ctx->iv, 1);\n }\n } else {\n union {\n unsigned int u[SHA256_DIGEST_LENGTH / sizeof(unsigned int)];\n unsigned char c[64 + SHA256_DIGEST_LENGTH];\n } mac, *pmac;\n\n /* arrange cache line alignment */\n pmac = (void *)(((size_t)mac.c + 63) & ((size_t)0 - 64));\n\n /* decrypt HMAC|padding at once */\n aesni_cbc_encrypt(in, out, len, &key->ks, ctx->iv, 0);\n\n if (plen != NO_PAYLOAD_LENGTH) { /* \"TLS\" mode of operation */\n size_t inp_len, mask, j, i;\n unsigned int res, maxpad, pad, bitlen;\n int ret = 1;\n union {\n unsigned int u[SHA_LBLOCK];\n unsigned char c[SHA256_CBLOCK];\n } *data = (void *)key->md.data;\n\n if ((key->aux.tls_aad[plen - 4] << 8 | key->aux.tls_aad[plen - 3])\n >= TLS1_1_VERSION)\n iv = AES_BLOCK_SIZE;\n\n if (len < (iv + SHA256_DIGEST_LENGTH + 1))\n return 0;\n\n /* omit explicit iv */\n out += iv;\n len -= iv;\n\n /* figure out payload length */\n pad = out[len - 1];\n maxpad = len - (SHA256_DIGEST_LENGTH + 1);\n maxpad |= (255 - maxpad) >> (sizeof(maxpad) * 8 - 8);\n maxpad &= 255;\n\n inp_len = len - (SHA256_DIGEST_LENGTH + pad + 1);\n mask = (0 - ((inp_len - len) >> (sizeof(inp_len) * 8 - 1)));\n inp_len &= mask;\n ret &= (int)mask;\n\n key->aux.tls_aad[plen - 2] = inp_len >> 8;\n key->aux.tls_aad[plen - 1] = inp_len;\n\n /* calculate HMAC */\n key->md = key->head;\n SHA256_Update(&key->md, key->aux.tls_aad, plen);\n\n# if 1\n len -= SHA256_DIGEST_LENGTH; /* amend mac */\n if (len >= (256 + SHA256_CBLOCK)) {\n j = (len - (256 + SHA256_CBLOCK)) & (0 - SHA256_CBLOCK);\n j += SHA256_CBLOCK - key->md.num;\n SHA256_Update(&key->md, out, j);\n out += j;\n len -= j;\n inp_len -= j;\n }\n\n /* but pretend as if we hashed padded payload */\n bitlen = key->md.Nl + (inp_len << 3); /* at most 18 bits */\n# ifdef BSWAP4\n bitlen = BSWAP4(bitlen);\n# else\n mac.c[0] = 0;\n mac.c[1] = (unsigned char)(bitlen >> 16);\n mac.c[2] = (unsigned char)(bitlen >> 8);\n mac.c[3] = (unsigned char)bitlen;\n bitlen = mac.u[0];\n# endif\n\n pmac->u[0] = 0;\n pmac->u[1] = 0;\n pmac->u[2] = 0;\n pmac->u[3] = 0;\n pmac->u[4] = 0;\n pmac->u[5] = 0;\n pmac->u[6] = 0;\n pmac->u[7] = 0;\n\n for (res = key->md.num, j = 0; j < len; j++) {\n size_t c = out[j];\n mask = (j - inp_len) >> (sizeof(j) * 8 - 8);\n c &= mask;\n c |= 0x80 & ~mask & ~((inp_len - j) >> (sizeof(j) * 8 - 8));\n data->c[res++] = (unsigned char)c;\n\n if (res != SHA256_CBLOCK)\n continue;\n\n /* j is not incremented yet */\n mask = 0 - ((inp_len + 7 - j) >> (sizeof(j) * 8 - 1));\n data->u[SHA_LBLOCK - 1] |= bitlen & mask;\n sha256_block_data_order(&key->md, data, 1);\n mask &= 0 - ((j - inp_len - 72) >> (sizeof(j) * 8 - 1));\n pmac->u[0] |= key->md.h[0] & mask;\n pmac->u[1] |= key->md.h[1] & mask;\n pmac->u[2] |= key->md.h[2] & mask;\n pmac->u[3] |= key->md.h[3] & mask;\n pmac->u[4] |= key->md.h[4] & mask;\n pmac->u[5] |= key->md.h[5] & mask;\n pmac->u[6] |= key->md.h[6] & mask;\n pmac->u[7] |= key->md.h[7] & mask;\n res = 0;\n }\n\n for (i = res; i < SHA256_CBLOCK; i++, j++)\n data->c[i] = 0;\n\n if (res > SHA256_CBLOCK - 8) {\n mask = 0 - ((inp_len + 8 - j) >> (sizeof(j) * 8 - 1));\n data->u[SHA_LBLOCK - 1] |= bitlen & mask;\n sha256_block_data_order(&key->md, data, 1);\n mask &= 0 - ((j - inp_len - 73) >> (sizeof(j) * 8 - 1));\n pmac->u[0] |= key->md.h[0] & mask;\n pmac->u[1] |= key->md.h[1] & mask;\n pmac->u[2] |= key->md.h[2] & mask;\n pmac->u[3] |= key->md.h[3] & mask;\n pmac->u[4] |= key->md.h[4] & mask;\n pmac->u[5] |= key->md.h[5] & mask;\n pmac->u[6] |= key->md.h[6] & mask;\n pmac->u[7] |= key->md.h[7] & mask;\n\n memset(data, 0, SHA256_CBLOCK);\n j += 64;\n }\n data->u[SHA_LBLOCK - 1] = bitlen;\n sha256_block_data_order(&key->md, data, 1);\n mask = 0 - ((j - inp_len - 73) >> (sizeof(j) * 8 - 1));\n pmac->u[0] |= key->md.h[0] & mask;\n pmac->u[1] |= key->md.h[1] & mask;\n pmac->u[2] |= key->md.h[2] & mask;\n pmac->u[3] |= key->md.h[3] & mask;\n pmac->u[4] |= key->md.h[4] & mask;\n pmac->u[5] |= key->md.h[5] & mask;\n pmac->u[6] |= key->md.h[6] & mask;\n pmac->u[7] |= key->md.h[7] & mask;\n\n# ifdef BSWAP4\n pmac->u[0] = BSWAP4(pmac->u[0]);\n pmac->u[1] = BSWAP4(pmac->u[1]);\n pmac->u[2] = BSWAP4(pmac->u[2]);\n pmac->u[3] = BSWAP4(pmac->u[3]);\n pmac->u[4] = BSWAP4(pmac->u[4]);\n pmac->u[5] = BSWAP4(pmac->u[5]);\n pmac->u[6] = BSWAP4(pmac->u[6]);\n pmac->u[7] = BSWAP4(pmac->u[7]);\n# else\n for (i = 0; i < 8; i++) {\n res = pmac->u[i];\n pmac->c[4 * i + 0] = (unsigned char)(res >> 24);\n pmac->c[4 * i + 1] = (unsigned char)(res >> 16);\n pmac->c[4 * i + 2] = (unsigned char)(res >> 8);\n pmac->c[4 * i + 3] = (unsigned char)res;\n }\n# endif\n len += SHA256_DIGEST_LENGTH;\n# else\n SHA256_Update(&key->md, out, inp_len);\n res = key->md.num;\n SHA256_Final(pmac->c, &key->md);\n\n {\n unsigned int inp_blocks, pad_blocks;\n\n /* but pretend as if we hashed padded payload */\n inp_blocks =\n 1 + ((SHA256_CBLOCK - 9 - res) >> (sizeof(res) * 8 - 1));\n res += (unsigned int)(len - inp_len);\n pad_blocks = res / SHA256_CBLOCK;\n res %= SHA256_CBLOCK;\n pad_blocks +=\n 1 + ((SHA256_CBLOCK - 9 - res) >> (sizeof(res) * 8 - 1));\n for (; inp_blocks < pad_blocks; inp_blocks++)\n sha1_block_data_order(&key->md, data, 1);\n }\n# endif\n key->md = key->tail;\n SHA256_Update(&key->md, pmac->c, SHA256_DIGEST_LENGTH);\n SHA256_Final(pmac->c, &key->md);\n\n /* verify HMAC */\n out += inp_len;\n len -= inp_len;\n# if 1\n {\n unsigned char *p =\n out + len - 1 - maxpad - SHA256_DIGEST_LENGTH;\n size_t off = out - p;\n unsigned int c, cmask;\n\n maxpad += SHA256_DIGEST_LENGTH;\n for (res = 0, i = 0, j = 0; j < maxpad; j++) {\n c = p[j];\n cmask =\n ((int)(j - off - SHA256_DIGEST_LENGTH)) >>\n (sizeof(int) * 8 - 1);\n res |= (c ^ pad) & ~cmask; /* ... and padding */\n cmask &= ((int)(off - 1 - j)) >> (sizeof(int) * 8 - 1);\n res |= (c ^ pmac->c[i]) & cmask;\n i += 1 & cmask;\n }\n maxpad -= SHA256_DIGEST_LENGTH;\n\n res = 0 - ((0 - res) >> (sizeof(res) * 8 - 1));\n ret &= (int)~res;\n }\n# else\n for (res = 0, i = 0; i < SHA256_DIGEST_LENGTH; i++)\n res |= out[i] ^ pmac->c[i];\n res = 0 - ((0 - res) >> (sizeof(res) * 8 - 1));\n ret &= (int)~res;\n\n /* verify padding */\n pad = (pad & ~res) | (maxpad & res);\n out = out + len - 1 - pad;\n for (res = 0, i = 0; i < pad; i++)\n res |= out[i] ^ pad;\n\n res = (0 - res) >> (sizeof(res) * 8 - 1);\n ret &= (int)~res;\n# endif\n return ret;\n } else {\n SHA256_Update(&key->md, out, len);\n }\n }\n\n return 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Check that we have enough padding characters.\n\nReviewed-by: Emilia K\u00e4sper \n\nCVE-2016-2107\n\nMR: #2572'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: rsvg_state_clone (RsvgState * dst, const RsvgState * src)\n{\n gint i;\n RsvgState *parent = dst->parent;\n\n rsvg_state_finalize (dst);\n\n *dst = *src;\n dst->parent = parent;\n dst->font_family = g_strdup (src->font_family);\n dst->lang = g_strdup (src->lang);\n rsvg_paint_server_ref (dst->fill);\n rsvg_paint_server_ref (dst->stroke);\n\n dst->styles = g_hash_table_ref (src->styles);\n\n if (src->dash.n_dash > 0) {\n dst->dash.dash = g_new (gdouble, src->dash.n_dash);\n for (i = 0; i < src->dash.n_dash; i++)\n dst->dash.dash[i] = src->dash.dash[i];\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'state: Store mask as reference\n\nInstead of immediately looking up the mask, store the reference and look\nit up on use.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: RSA *RSA_generate_key(int bits, unsigned long e_value,\n\t void (*callback)(int,int,void *), void *cb_arg)\n\t{\n\tRSA *rsa=NULL;\n\tBIGNUM *r0=NULL,*r1=NULL,*r2=NULL,*r3=NULL,*tmp;\n\tint bitsp,bitsq,ok= -1,n=0,i;\n\tBN_CTX *ctx=NULL,*ctx2=NULL;\n\n\tctx=BN_CTX_new();\n\tif (ctx == NULL) goto err;\n\tctx2=BN_CTX_new();\n\tif (ctx2 == NULL) goto err;\n\tBN_CTX_start(ctx);\n\tr0 = BN_CTX_get(ctx);\n\tr1 = BN_CTX_get(ctx);\n\tr2 = BN_CTX_get(ctx);\n\tr3 = BN_CTX_get(ctx);\n\tif (r3 == NULL) goto err;\n\n\tbitsp=(bits+1)/2;\n\tbitsq=bits-bitsp;\n\trsa=RSA_new();\n\tif (rsa == NULL) goto err;\n\n\t/* set e */ \n\trsa->e=BN_new();\n\tif (rsa->e == NULL) goto err;\n\n#if 1\n\t/* The problem is when building with 8, 16, or 32 BN_ULONG,\n\t * unsigned long can be larger */\n\tfor (i=0; ie,i);\n\t\t}\n#else\n\tif (!BN_set_word(rsa->e,e_value)) goto err;\n#endif\n\n\t/* generate p and q */\n\tfor (;;)\n\t\t{\n\t\trsa->p=BN_generate_prime(NULL,bitsp,0,NULL,NULL,callback,cb_arg);\n\t\tif (rsa->p == NULL) goto err;\n\t\tif (!BN_sub(r2,rsa->p,BN_value_one())) goto err;\n\t\tif (!BN_gcd(r1,r2,rsa->e,ctx)) goto err;\n\t\tif (BN_is_one(r1)) break;\n\t\tif (callback != NULL) callback(2,n++,cb_arg);\n\t\tBN_free(rsa->p);\n\t\t}\n\tif (callback != NULL) callback(3,0,cb_arg);\n\tfor (;;)\n\t\t{\n\t\trsa->q=BN_generate_prime(NULL,bitsq,0,NULL,NULL,callback,cb_arg);\n\t\tif (rsa->q == NULL) goto err;\n\t\tif (!BN_sub(r2,rsa->q,BN_value_one())) goto err;\n\t\tif (!BN_gcd(r1,r2,rsa->e,ctx)) goto err;\n\t\tif (BN_is_one(r1) && (BN_cmp(rsa->p,rsa->q) != 0))\n\t\t\tbreak;\n\t\tif (callback != NULL) callback(2,n++,cb_arg);\n\t\tBN_free(rsa->q);\n\t\t}\n\tif (callback != NULL) callback(3,1,cb_arg);\n\tif (BN_cmp(rsa->p,rsa->q) < 0)\n\t\t{\n\t\ttmp=rsa->p;\n\t\trsa->p=rsa->q;\n\t\trsa->q=tmp;\n\t\t}\n\n\t/* calculate n */\n\trsa->n=BN_new();\n\tif (rsa->n == NULL) goto err;\n\tif (!BN_mul(rsa->n,rsa->p,rsa->q,ctx)) goto err;\n\n\t/* calculate d */\n\tif (!BN_sub(r1,rsa->p,BN_value_one())) goto err;\t/* p-1 */\n\tif (!BN_sub(r2,rsa->q,BN_value_one())) goto err;\t/* q-1 */\n\tif (!BN_mul(r0,r1,r2,ctx)) goto err;\t/* (p-1)(q-1) */\n\n/* should not be needed, since gcd(p-1,e) == 1 and gcd(q-1,e) == 1 */\n/*\tfor (;;)\n\t\t{\n\t\tif (!BN_gcd(r3,r0,rsa->e,ctx)) goto err;\n\t\tif (BN_is_one(r3)) break;\n\n\t\tif (1)\n\t\t\t{\n\t\t\tif (!BN_add_word(rsa->e,2L)) goto err;\n\t\t\tcontinue;\n\t\t\t}\n\t\tRSAerr(RSA_F_RSA_GENERATE_KEY,RSA_R_BAD_E_VALUE);\n\t\tgoto err;\n\t\t}\n*/\n\trsa->d=BN_mod_inverse(NULL,rsa->e,r0,ctx2);\t/* d */\n\tif (rsa->d == NULL) goto err;\n\n\t/* calculate d mod (p-1) */\n\trsa->dmp1=BN_new();\n\tif (rsa->dmp1 == NULL) goto err;\n\tif (!BN_mod(rsa->dmp1,rsa->d,r1,ctx)) goto err;\n\n\t/* calculate d mod (q-1) */\n\trsa->dmq1=BN_new();\n\tif (rsa->dmq1 == NULL) goto err;\n\tif (!BN_mod(rsa->dmq1,rsa->d,r2,ctx)) goto err;\n\n\t/* calculate inverse of q mod p */\n\trsa->iqmp=BN_mod_inverse(NULL,rsa->q,rsa->p,ctx2);\n\tif (rsa->iqmp == NULL) goto err;\n\n\tok=1;\nerr:\n\tif (ok == -1)\n\t\t{\n\t\tRSAerr(RSA_F_RSA_GENERATE_KEY,ERR_LIB_BN);\n\t\tok=0;\n\t\t}\n\tBN_CTX_end(ctx);\n\tBN_CTX_free(ctx);\n\tBN_CTX_free(ctx2);\n\t\n\tif (!ok)\n\t\t{\n\t\tif (rsa != NULL) RSA_free(rsa);\n\t\treturn(NULL);\n\t\t}\n\telse\n\t\treturn(rsa);\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-310'], 'message': 'Bug fix for 64 bit HP-UX.\n\nSubmitted by: Karsten Spang '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int tls1_process_ticket(SSL *s, unsigned char *session_id, int len,\n const unsigned char *limit, SSL_SESSION **ret)\n{\n /* Point after session ID in client hello */\n const unsigned char *p = session_id + len;\n unsigned short i;\n\n *ret = NULL;\n s->tlsext_ticket_expected = 0;\n\n /*\n * If tickets disabled behave as if no ticket present to permit stateful\n * resumption.\n */\n if (SSL_get_options(s) & SSL_OP_NO_TICKET)\n return 0;\n if ((s->version <= SSL3_VERSION) || !limit)\n return 0;\n if (p >= limit)\n return -1;\n /* Skip past DTLS cookie */\n if (s->version == DTLS1_VERSION || s->version == DTLS1_BAD_VER) {\n i = *(p++);\n p += i;\n if (p >= limit)\n return -1;\n }\n /* Skip past cipher list */\n n2s(p, i);\n p += i;\n if (p >= limit)\n return -1;\n /* Skip past compression algorithm list */\n i = *(p++);\n p += i;\n if (p > limit)\n return -1;\n /* Now at start of extensions */\n if ((p + 2) >= limit)\n return 0;\n n2s(p, i);\n while ((p + 4) <= limit) {\n unsigned short type, size;\n n2s(p, type);\n n2s(p, size);\n if (p + size > limit)\n return 0;\n if (type == TLSEXT_TYPE_session_ticket) {\n int r;\n if (size == 0) {\n /*\n * The client will accept a ticket but doesn't currently have\n * one.\n */\n s->tlsext_ticket_expected = 1;\n return 1;\n }\n if (s->tls_session_secret_cb) {\n /*\n * Indicate that the ticket couldn't be decrypted rather than\n * generating the session from ticket now, trigger\n * abbreviated handshake based on external mechanism to\n * calculate the master secret later.\n */\n return 2;\n }\n r = tls_decrypt_ticket(s, p, size, session_id, len, ret);\n switch (r) {\n case 2: /* ticket couldn't be decrypted */\n s->tlsext_ticket_expected = 1;\n return 2;\n case 3: /* ticket was decrypted */\n return r;\n case 4: /* ticket decrypted but need to renew */\n s->tlsext_ticket_expected = 1;\n return 3;\n default: /* fatal error */\n return -1;\n }\n }\n p += size;\n }\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Avoid some undefined pointer arithmetic\n\nA common idiom in the codebase is:\n\nif (p + len > limit)\n{\n return; /* Too long */\n}\n\nWhere \"p\" points to some malloc'd data of SIZE bytes and\nlimit == p + SIZE\n\n\"len\" here could be from some externally supplied data (e.g. from a TLS\nmessage).\n\nThe rules of C pointer arithmetic are such that \"p + len\" is only well\ndefined where len <= SIZE. Therefore the above idiom is actually\nundefined behaviour.\n\nFor example this could cause problems if some malloc implementation\nprovides an address for \"p\" such that \"p + len\" actually overflows for\nvalues of len that are too big and therefore p + len < limit!\n\nIssue reported by Guido Vranken.\n\nCVE-2016-2177\n\nReviewed-by: Rich Salz '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int TS_OBJ_print_bio(BIO *bio, const ASN1_OBJECT *obj)\n{\n char obj_txt[128];\n\n int len = OBJ_obj2txt(obj_txt, sizeof(obj_txt), obj, 0);\n BIO_write(bio, obj_txt, len);\n BIO_write(bio, \"\\n\", 1);\n\n return 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix OOB read in TS_OBJ_print_bio().\n\nTS_OBJ_print_bio() misuses OBJ_txt2obj: it should print the result\nas a null terminated buffer. The length value returned is the total\nlength the complete text reprsentation would need not the amount of\ndata written.\n\nCVE-2016-2180\n\nThanks to Shi Lei for reporting this bug.\n\nReviewed-by: Matt Caswell '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void dtls1_stop_timer(SSL *s)\n{\n /* Reset everything */\n memset(&(s->d1->timeout), 0, sizeof(struct dtls1_timeout_st));\n memset(&(s->d1->next_timeout), 0, sizeof(struct timeval));\n s->d1->timeout_duration = 1;\n BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0,\n &(s->d1->next_timeout));\n /* Clear retransmission buffer */\n dtls1_clear_record_buffer(s);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'Fix DTLS buffered message DoS attack\n\nDTLS can handle out of order record delivery. Additionally since\nhandshake messages can be bigger than will fit into a single packet, the\nmessages can be fragmented across multiple records (as with normal TLS).\nThat means that the messages can arrive mixed up, and we have to\nreassemble them. We keep a queue of buffered messages that are \"from the\nfuture\", i.e. messages we're not ready to deal with yet but have arrived\nearly. The messages held there may not be full yet - they could be one\nor more fragments that are still in the process of being reassembled.\n\nThe code assumes that we will eventually complete the reassembly and\nwhen that occurs the complete message is removed from the queue at the\npoint that we need to use it.\n\nHowever, DTLS is also tolerant of packet loss. To get around that DTLS\nmessages can be retransmitted. If we receive a full (non-fragmented)\nmessage from the peer after previously having received a fragment of\nthat message, then we ignore the message in the queue and just use the\nnon-fragmented version. At that point the queued message will never get\nremoved.\n\nAdditionally the peer could send \"future\" messages that we never get to\nin order to complete the handshake. Each message has a sequence number\n(starting from 0). We will accept a message fragment for the current\nmessage sequence number, or for any sequence up to 10 into the future.\nHowever if the Finished message has a sequence number of 2, anything\ngreater than that in the queue is just left there.\n\nSo, in those two ways we can end up with \"orphaned\" data in the queue\nthat will never get removed - except when the connection is closed. At\nthat point all the queues are flushed.\n\nAn attacker could seek to exploit this by filling up the queues with\nlots of large messages that are never going to be used in order to\nattempt a DoS by memory exhaustion.\n\nI will assume that we are only concerned with servers here. It does not\nseem reasonable to be concerned about a memory exhaustion attack on a\nclient. They are unlikely to process enough connections for this to be\nan issue.\n\nA \"long\" handshake with many messages might be 5 messages long (in the\nincoming direction), e.g. ClientHello, Certificate, ClientKeyExchange,\nCertificateVerify, Finished. So this would be message sequence numbers 0\nto 4. Additionally we can buffer up to 10 messages in the future.\nTherefore the maximum number of messages that an attacker could send\nthat could get orphaned would typically be 15.\n\nThe maximum size that a DTLS message is allowed to be is defined by\nmax_cert_list, which by default is 100k. Therefore the maximum amount of\n\"orphaned\" memory per connection is 1500k.\n\nMessage sequence numbers get reset after the Finished message, so\nrenegotiation will not extend the maximum number of messages that can be\norphaned per connection.\n\nAs noted above, the queues do get cleared when the connection is closed.\nTherefore in order to mount an effective attack, an attacker would have\nto open many simultaneous connections.\n\nIssue reported by Quan Luo.\n\nCVE-2016-2179\n\nReviewed-by: Richard Levitte '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int ssl3_get_client_certificate(SSL *s)\n{\n int i, ok, al, ret = -1;\n X509 *x = NULL;\n unsigned long l, nc, llen, n;\n const unsigned char *p, *q;\n unsigned char *d;\n STACK_OF(X509) *sk = NULL;\n\n n = s->method->ssl_get_message(s,\n SSL3_ST_SR_CERT_A,\n SSL3_ST_SR_CERT_B,\n -1, s->max_cert_list, &ok);\n\n if (!ok)\n return ((int)n);\n\n if (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) {\n if ((s->verify_mode & SSL_VERIFY_PEER) &&\n (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {\n SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,\n SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);\n al = SSL_AD_HANDSHAKE_FAILURE;\n goto f_err;\n }\n /*\n * If tls asked for a client cert, the client must return a 0 list\n */\n if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request) {\n SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,\n SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);\n al = SSL_AD_UNEXPECTED_MESSAGE;\n goto f_err;\n }\n s->s3->tmp.reuse_message = 1;\n return (1);\n }\n\n if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE) {\n al = SSL_AD_UNEXPECTED_MESSAGE;\n SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, SSL_R_WRONG_MESSAGE_TYPE);\n goto f_err;\n }\n p = d = (unsigned char *)s->init_msg;\n\n if ((sk = sk_X509_new_null()) == NULL) {\n SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);\n goto err;\n }\n\n n2l3(p, llen);\n if (llen + 3 != n) {\n al = SSL_AD_DECODE_ERROR;\n SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, SSL_R_LENGTH_MISMATCH);\n goto f_err;\n }\n for (nc = 0; nc < llen;) {\n n2l3(p, l);\n if ((l + nc + 3) > llen) {\n al = SSL_AD_DECODE_ERROR;\n SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,\n SSL_R_CERT_LENGTH_MISMATCH);\n goto f_err;\n }\n\n q = p;\n x = d2i_X509(NULL, &p, l);\n if (x == NULL) {\n SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_ASN1_LIB);\n goto err;\n }\n if (p != (q + l)) {\n al = SSL_AD_DECODE_ERROR;\n SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,\n SSL_R_CERT_LENGTH_MISMATCH);\n goto f_err;\n }\n if (!sk_X509_push(sk, x)) {\n SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);\n goto err;\n }\n x = NULL;\n nc += l + 3;\n }\n\n if (sk_X509_num(sk) <= 0) {\n /* TLS does not mind 0 certs returned */\n if (s->version == SSL3_VERSION) {\n al = SSL_AD_HANDSHAKE_FAILURE;\n SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,\n SSL_R_NO_CERTIFICATES_RETURNED);\n goto f_err;\n }\n /* Fail for TLS only if we required a certificate */\n else if ((s->verify_mode & SSL_VERIFY_PEER) &&\n (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {\n SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,\n SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);\n al = SSL_AD_HANDSHAKE_FAILURE;\n goto f_err;\n }\n /* No client certificate so digest cached records */\n if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s)) {\n al = SSL_AD_INTERNAL_ERROR;\n goto f_err;\n }\n } else {\n i = ssl_verify_cert_chain(s, sk);\n if (i <= 0) {\n al = ssl_verify_alarm_type(s->verify_result);\n SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,\n SSL_R_NO_CERTIFICATE_RETURNED);\n goto f_err;\n }\n }\n\n if (s->session->peer != NULL) /* This should not be needed */\n X509_free(s->session->peer);\n s->session->peer = sk_X509_shift(sk);\n s->session->verify_result = s->verify_result;\n\n /*\n * With the current implementation, sess_cert will always be NULL when we\n * arrive here.\n */\n if (s->session->sess_cert == NULL) {\n s->session->sess_cert = ssl_sess_cert_new();\n if (s->session->sess_cert == NULL) {\n SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);\n goto err;\n }\n }\n if (s->session->sess_cert->cert_chain != NULL)\n sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);\n s->session->sess_cert->cert_chain = sk;\n /*\n * Inconsistency alert: cert_chain does *not* include the peer's own\n * certificate, while we do include it in s3_clnt.c\n */\n\n sk = NULL;\n\n ret = 1;\n if (0) {\n f_err:\n ssl3_send_alert(s, SSL3_AL_FATAL, al);\n err:\n s->state = SSL_ST_ERR;\n }\n\n if (x != NULL)\n X509_free(x);\n if (sk != NULL)\n sk_X509_pop_free(sk, X509_free);\n return (ret);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix small OOB reads.\n\nIn ssl3_get_client_certificate, ssl3_get_server_certificate and\nssl3_get_certificate_request check we have enough room\nbefore reading a length.\n\nThanks to Shi Lei (Gear Team, Qihoo 360 Inc.) for reporting these bugs.\n\nCVE-2016-6306\n\nReviewed-by: Richard Levitte \nReviewed-by: Matt Caswell \n(cherry picked from commit ff553f837172ecb2b5c8eca257ec3c5619a4b299)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int my_redel(const char *org_name, const char *tmp_name,\n time_t backup_time_stamp, myf MyFlags)\n{\n int error=1;\n DBUG_ENTER(\"my_redel\");\n DBUG_PRINT(\"my\",(\"org_name: '%s' tmp_name: '%s' MyFlags: %d\",\n\t\t org_name,tmp_name,MyFlags));\n\n if (my_copystat(org_name,tmp_name,MyFlags) < 0)\n goto end;\n if (MyFlags & MY_REDEL_MAKE_BACKUP)\n {\n char name_buff[FN_REFLEN + MY_BACKUP_NAME_EXTRA_LENGTH]; \n my_create_backup_name(name_buff, org_name, backup_time_stamp);\n if (my_rename(org_name, name_buff, MyFlags))\n goto end;\n }\n else if (my_delete(org_name, MyFlags))\n goto end;\n if (my_rename(tmp_name,org_name,MyFlags))\n goto end;\n\n error=0;\nend:\n DBUG_RETURN(error);\n} /* my_redel */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-362'], 'message': 'don't use my_copystat in the server\n\nit was supposed to be used in command-line tools only.\nDifferent fix for 4e5473862e:\n\nBug#24388746: PRIVILEGE ESCALATION AND RACE CONDITION USING CREATE TABLE'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TIFFFlushData1(TIFF* tif)\n{\n\tif (tif->tif_rawcc > 0 && tif->tif_flags & TIFF_BUF4WRITE ) {\n\t\tif (!isFillOrder(tif, tif->tif_dir.td_fillorder) &&\n\t\t (tif->tif_flags & TIFF_NOBITREV) == 0)\n\t\t\tTIFFReverseBits((uint8*)tif->tif_rawdata,\n\t\t\t tif->tif_rawcc);\n\t\tif (!TIFFAppendToStrip(tif,\n\t\t isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip,\n\t\t tif->tif_rawdata, tif->tif_rawcc))\n\t\t\treturn (0);\n\t\ttif->tif_rawcc = 0;\n\t\ttif->tif_rawcp = tif->tif_rawdata;\n\t}\n\treturn (1);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': '* tools/tiffcrop.c: fix various out-of-bounds write vulnerabilities\nin heap or stack allocated buffers. Reported as MSVR 35093,\nMSVR 35096 and MSVR 35097. Discovered by Axel Souchet and Vishal\nChauhan from the MSRC Vulnerabilities & Mitigations team.\n* tools/tiff2pdf.c: fix out-of-bounds write vulnerabilities in\nheap allocate buffer in t2p_process_jpeg_strip(). Reported as MSVR\n35098. Discovered by Axel Souchet and Vishal Chauhan from the MSRC\nVulnerabilities & Mitigations team.\n* libtiff/tif_pixarlog.c: fix out-of-bounds write vulnerabilities\nin heap allocated buffers. Reported as MSVR 35094. Discovered by\nAxel Souchet and Vishal Chauhan from the MSRC Vulnerabilities &\nMitigations team.\n* libtiff/tif_write.c: fix issue in error code path of TIFFFlushData1()\nthat didn't reset the tif_rawcc and tif_rawcp members. I'm not\ncompletely sure if that could happen in practice outside of the odd\nbehaviour of t2p_seekproc() of tiff2pdf). The report points that a\nbetter fix could be to check the return value of TIFFFlushData1() in\nplaces where it isn't done currently, but it seems this patch is enough.\nReported as MSVR 35095. Discovered by Axel Souchet & Vishal Chauhan &\nSuha Can from the MSRC Vulnerabilities & Mitigations team.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: horDiff32(TIFF* tif, uint8* cp0, tmsize_t cc)\n{\n\tTIFFPredictorState* sp = PredictorState(tif);\n\ttmsize_t stride = sp->stride;\n\tuint32 *wp = (uint32*) cp0;\n\ttmsize_t wc = cc/4;\n\n\tassert((cc%(4*stride))==0);\n\n\tif (wc > stride) {\n\t\twc -= stride;\n\t\twp += wc - 1;\n\t\tdo {\n\t\t\tREPEAT4(stride, wp[stride] -= wp[0]; wp--)\n\t\t\twc -= stride;\n\t\t} while (wc > 0);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': '* libtiff/tif_predict.h, libtiff/tif_predict.c:\nReplace assertions by runtime checks to avoid assertions in debug mode,\nor buffer overflows in release mode. Can happen when dealing with\nunusual tile size like YCbCr with subsampling. Reported as MSVR 35105\nby Axel Souchet\t& Vishal Chauhan from the MSRC Vulnerabilities & Mitigations\nteam.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: fpAcc(TIFF* tif, uint8* cp0, tmsize_t cc)\n{\n\ttmsize_t stride = PredictorState(tif)->stride;\n\tuint32 bps = tif->tif_dir.td_bitspersample / 8;\n\ttmsize_t wc = cc / bps;\n\ttmsize_t count = cc;\n\tuint8 *cp = (uint8 *) cp0;\n\tuint8 *tmp = (uint8 *)_TIFFmalloc(cc);\n\n\tassert((cc%(bps*stride))==0);\n\n\tif (!tmp)\n\t\treturn;\n\n\twhile (count > stride) {\n\t\tREPEAT4(stride, cp[stride] =\n (unsigned char) ((cp[stride] + cp[0]) & 0xff); cp++)\n\t\tcount -= stride;\n\t}\n\n\t_TIFFmemcpy(tmp, cp0, cc);\n\tcp = (uint8 *) cp0;\n\tfor (count = 0; count < wc; count++) {\n\t\tuint32 byte;\n\t\tfor (byte = 0; byte < bps; byte++) {\n\t\t\t#if WORDS_BIGENDIAN\n\t\t\tcp[bps * count + byte] = tmp[byte * wc + count];\n\t\t\t#else\n\t\t\tcp[bps * count + byte] =\n\t\t\t\ttmp[(bps - byte - 1) * wc + count];\n\t\t\t#endif\n\t\t}\n\t}\n\t_TIFFfree(tmp);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': '* libtiff/tif_predict.h, libtiff/tif_predict.c:\nReplace assertions by runtime checks to avoid assertions in debug mode,\nor buffer overflows in release mode. Can happen when dealing with\nunusual tile size like YCbCr with subsampling. Reported as MSVR 35105\nby Axel Souchet\t& Vishal Chauhan from the MSRC Vulnerabilities & Mitigations\nteam.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: DECLAREreadFunc(readContigTilesIntoBuffer)\n{\n\tint status = 1;\n\ttsize_t tilesize = TIFFTileSize(in);\n\ttdata_t tilebuf;\n\tuint32 imagew = TIFFScanlineSize(in);\n\tuint32 tilew = TIFFTileRowSize(in);\n\tint iskew = imagew - tilew;\n\tuint8* bufp = (uint8*) buf;\n\tuint32 tw, tl;\n\tuint32 row;\n\n\t(void) spp;\n\ttilebuf = _TIFFmalloc(tilesize);\n\tif (tilebuf == 0)\n\t\treturn 0;\n\t_TIFFmemset(tilebuf, 0, tilesize);\n\t(void) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw);\n\t(void) TIFFGetField(in, TIFFTAG_TILELENGTH, &tl);\n \n\tfor (row = 0; row < imagelength; row += tl) {\n\t\tuint32 nrow = (row+tl > imagelength) ? imagelength-row : tl;\n\t\tuint32 colb = 0;\n\t\tuint32 col;\n\n\t\tfor (col = 0; col < imagewidth; col += tw) {\n\t\t\tif (TIFFReadTile(in, tilebuf, col, row, 0, 0) < 0\n\t\t\t && !ignore) {\n\t\t\t\tTIFFError(TIFFFileName(in),\n\t\t\t\t \"Error, can't read tile at %lu %lu\",\n\t\t\t\t (unsigned long) col,\n\t\t\t\t (unsigned long) row);\n\t\t\t\tstatus = 0;\n\t\t\t\tgoto done;\n\t\t\t}\n\t\t\tif (colb + tilew > imagew) {\n\t\t\t\tuint32 width = imagew - colb;\n\t\t\t\tuint32 oskew = tilew - width;\n\t\t\t\tcpStripToTile(bufp + colb,\n\t\t\t\t tilebuf, nrow, width,\n\t\t\t\t oskew + iskew, oskew );\n\t\t\t} else\n\t\t\t\tcpStripToTile(bufp + colb,\n\t\t\t\t tilebuf, nrow, tilew,\n\t\t\t\t iskew, 0);\n\t\t\tcolb += tilew;\n\t\t}\n\t\tbufp += imagew * nrow;\n\t}\ndone:\n\t_TIFFfree(tilebuf);\n\treturn status;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': '* tools/tiffcp.c: fix out-of-bounds write on tiled images with odd\ntile width vs image width. Reported as MSVR 35103\nby Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities &\nMitigations team.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void EC_GROUP_free(EC_GROUP *group)\n\t{\n\tif (!group) return;\n\n\tif (group->meth->group_finish != 0)\n\t\tgroup->meth->group_finish(group);\n\n\tEC_EX_DATA_free_all_data(&group->extra_data);\n\n\tif (group->generator != NULL)\n\t\tEC_POINT_free(group->generator);\n\tBN_free(&group->order);\n\tBN_free(&group->cofactor);\n\n\tif (group->seed)\n\t\tOPENSSL_free(group->seed);\n\n\tOPENSSL_free(group);\n\t} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-320'], 'message': 'Reserve option to use BN_mod_exp_mont_consttime in ECDSA.\n\nSubmitted by Shay Gueron, Intel Corp.\nRT: 3149\n\nReviewed-by: Rich Salz \n(cherry picked from commit f54be179aa4cbbd944728771d7d59ed588158a12)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int aes_gcm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr)\n{\n EVP_AES_GCM_CTX *gctx = EVP_C_DATA(EVP_AES_GCM_CTX,c);\n switch (type) {\n case EVP_CTRL_INIT:\n gctx->key_set = 0;\n gctx->iv_set = 0;\n gctx->ivlen = EVP_CIPHER_CTX_iv_length(c);\n gctx->iv = EVP_CIPHER_CTX_iv_noconst(c);\n gctx->taglen = -1;\n gctx->iv_gen = 0;\n gctx->tls_aad_len = -1;\n return 1;\n\n case EVP_CTRL_AEAD_SET_IVLEN:\n if (arg <= 0)\n return 0;\n /* Allocate memory for IV if needed */\n if ((arg > EVP_MAX_IV_LENGTH) && (arg > gctx->ivlen)) {\n if (gctx->iv != EVP_CIPHER_CTX_iv_noconst(c))\n OPENSSL_free(gctx->iv);\n gctx->iv = OPENSSL_malloc(arg);\n if (gctx->iv == NULL)\n return 0;\n }\n gctx->ivlen = arg;\n return 1;\n\n case EVP_CTRL_AEAD_SET_TAG:\n if (arg <= 0 || arg > 16 || EVP_CIPHER_CTX_encrypting(c))\n return 0;\n memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg);\n gctx->taglen = arg;\n return 1;\n\n case EVP_CTRL_AEAD_GET_TAG:\n if (arg <= 0 || arg > 16 || !EVP_CIPHER_CTX_encrypting(c)\n || gctx->taglen < 0)\n return 0;\n memcpy(ptr, EVP_CIPHER_CTX_buf_noconst(c), arg);\n return 1;\n\n case EVP_CTRL_GCM_SET_IV_FIXED:\n /* Special case: -1 length restores whole IV */\n if (arg == -1) {\n memcpy(gctx->iv, ptr, gctx->ivlen);\n gctx->iv_gen = 1;\n return 1;\n }\n /*\n * Fixed field must be at least 4 bytes and invocation field at least\n * 8.\n */\n if ((arg < 4) || (gctx->ivlen - arg) < 8)\n return 0;\n if (arg)\n memcpy(gctx->iv, ptr, arg);\n if (EVP_CIPHER_CTX_encrypting(c)\n && RAND_bytes(gctx->iv + arg, gctx->ivlen - arg) <= 0)\n return 0;\n gctx->iv_gen = 1;\n return 1;\n\n case EVP_CTRL_GCM_IV_GEN:\n if (gctx->iv_gen == 0 || gctx->key_set == 0)\n return 0;\n CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen);\n if (arg <= 0 || arg > gctx->ivlen)\n arg = gctx->ivlen;\n memcpy(ptr, gctx->iv + gctx->ivlen - arg, arg);\n /*\n * Invocation field will be at least 8 bytes in size and so no need\n * to check wrap around or increment more than last 8 bytes.\n */\n ctr64_inc(gctx->iv + gctx->ivlen - 8);\n gctx->iv_set = 1;\n return 1;\n\n case EVP_CTRL_GCM_SET_IV_INV:\n if (gctx->iv_gen == 0 || gctx->key_set == 0\n || EVP_CIPHER_CTX_encrypting(c))\n return 0;\n memcpy(gctx->iv + gctx->ivlen - arg, ptr, arg);\n CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen);\n gctx->iv_set = 1;\n return 1;\n\n case EVP_CTRL_AEAD_TLS1_AAD:\n /* Save the AAD for later use */\n if (arg != EVP_AEAD_TLS1_AAD_LEN)\n return 0;\n memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg);\n gctx->tls_aad_len = arg;\n {\n unsigned int len =\n EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] << 8\n | EVP_CIPHER_CTX_buf_noconst(c)[arg - 1];\n /* Correct length for explicit IV */\n len -= EVP_GCM_TLS_EXPLICIT_IV_LEN;\n /* If decrypting correct for tag too */\n if (!EVP_CIPHER_CTX_encrypting(c))\n len -= EVP_GCM_TLS_TAG_LEN;\n EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] = len >> 8;\n EVP_CIPHER_CTX_buf_noconst(c)[arg - 1] = len & 0xff;\n }\n /* Extra padding: tag appended to record */\n return EVP_GCM_TLS_TAG_LEN;\n\n case EVP_CTRL_COPY:\n {\n EVP_CIPHER_CTX *out = ptr;\n EVP_AES_GCM_CTX *gctx_out = EVP_C_DATA(EVP_AES_GCM_CTX,out);\n if (gctx->gcm.key) {\n if (gctx->gcm.key != &gctx->ks)\n return 0;\n gctx_out->gcm.key = &gctx_out->ks;\n }\n if (gctx->iv == EVP_CIPHER_CTX_iv_noconst(c))\n gctx_out->iv = EVP_CIPHER_CTX_iv_noconst(out);\n else {\n gctx_out->iv = OPENSSL_malloc(gctx->ivlen);\n if (gctx_out->iv == NULL)\n return 0;\n memcpy(gctx_out->iv, gctx->iv, gctx->ivlen);\n }\n return 1;\n }\n\n default:\n return -1;\n\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'crypto/evp: harden AEAD ciphers.\n\nOriginally a crash in 32-bit build was reported CHACHA20-POLY1305\ncipher. The crash is triggered by truncated packet and is result\nof excessive hashing to the edge of accessible memory. Since hash\noperation is read-only it is not considered to be exploitable\nbeyond a DoS condition. Other ciphers were hardened.\n\nThanks to Robert \u015awi\u0119cki for report.\n\nCVE-2017-3731\n\nReviewed-by: Rich Salz '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: _TIFFVSetField(TIFF* tif, uint32 tag, va_list ap)\n{\n\tstatic const char module[] = \"_TIFFVSetField\";\n\n\tTIFFDirectory* td = &tif->tif_dir;\n\tint status = 1;\n\tuint32 v32, i, v;\n double dblval;\n\tchar* s;\n\tconst TIFFField *fip = TIFFFindField(tif, tag, TIFF_ANY);\n\tuint32 standard_tag = tag;\n\tif( fip == NULL ) /* cannot happen since OkToChangeTag() already checks it */\n\t return 0;\n\t/*\n\t * We want to force the custom code to be used for custom\n\t * fields even if the tag happens to match a well known \n\t * one - important for reinterpreted handling of standard\n\t * tag values in custom directories (i.e. EXIF) \n\t */\n\tif (fip->field_bit == FIELD_CUSTOM) {\n\t\tstandard_tag = 0;\n\t}\n\n\tswitch (standard_tag) {\n\tcase TIFFTAG_SUBFILETYPE:\n\t\ttd->td_subfiletype = (uint32) va_arg(ap, uint32);\n\t\tbreak;\n\tcase TIFFTAG_IMAGEWIDTH:\n\t\ttd->td_imagewidth = (uint32) va_arg(ap, uint32);\n\t\tbreak;\n\tcase TIFFTAG_IMAGELENGTH:\n\t\ttd->td_imagelength = (uint32) va_arg(ap, uint32);\n\t\tbreak;\n\tcase TIFFTAG_BITSPERSAMPLE:\n\t\ttd->td_bitspersample = (uint16) va_arg(ap, uint16_vap);\n\t\t/*\n\t\t * If the data require post-decoding processing to byte-swap\n\t\t * samples, set it up here. Note that since tags are required\n\t\t * to be ordered, compression code can override this behaviour\n\t\t * in the setup method if it wants to roll the post decoding\n\t\t * work in with its normal work.\n\t\t */\n\t\tif (tif->tif_flags & TIFF_SWAB) {\n\t\t\tif (td->td_bitspersample == 8)\n\t\t\t\ttif->tif_postdecode = _TIFFNoPostDecode;\n\t\t\telse if (td->td_bitspersample == 16)\n\t\t\t\ttif->tif_postdecode = _TIFFSwab16BitData;\n\t\t\telse if (td->td_bitspersample == 24)\n\t\t\t\ttif->tif_postdecode = _TIFFSwab24BitData;\n\t\t\telse if (td->td_bitspersample == 32)\n\t\t\t\ttif->tif_postdecode = _TIFFSwab32BitData;\n\t\t\telse if (td->td_bitspersample == 64)\n\t\t\t\ttif->tif_postdecode = _TIFFSwab64BitData;\n\t\t\telse if (td->td_bitspersample == 128) /* two 64's */\n\t\t\t\ttif->tif_postdecode = _TIFFSwab64BitData;\n\t\t}\n\t\tbreak;\n\tcase TIFFTAG_COMPRESSION:\n\t\tv = (uint16) va_arg(ap, uint16_vap);\n\t\t/*\n\t\t * If we're changing the compression scheme, the notify the\n\t\t * previous module so that it can cleanup any state it's\n\t\t * setup.\n\t\t */\n\t\tif (TIFFFieldSet(tif, FIELD_COMPRESSION)) {\n\t\t\tif ((uint32)td->td_compression == v)\n\t\t\t\tbreak;\n\t\t\t(*tif->tif_cleanup)(tif);\n\t\t\ttif->tif_flags &= ~TIFF_CODERSETUP;\n\t\t}\n\t\t/*\n\t\t * Setup new compression routine state.\n\t\t */\n\t\tif( (status = TIFFSetCompressionScheme(tif, v)) != 0 )\n\t\t td->td_compression = (uint16) v;\n\t\telse\n\t\t status = 0;\n\t\tbreak;\n\tcase TIFFTAG_PHOTOMETRIC:\n\t\ttd->td_photometric = (uint16) va_arg(ap, uint16_vap);\n\t\tbreak;\n\tcase TIFFTAG_THRESHHOLDING:\n\t\ttd->td_threshholding = (uint16) va_arg(ap, uint16_vap);\n\t\tbreak;\n\tcase TIFFTAG_FILLORDER:\n\t\tv = (uint16) va_arg(ap, uint16_vap);\n\t\tif (v != FILLORDER_LSB2MSB && v != FILLORDER_MSB2LSB)\n\t\t\tgoto badvalue;\n\t\ttd->td_fillorder = (uint16) v;\n\t\tbreak;\n\tcase TIFFTAG_ORIENTATION:\n\t\tv = (uint16) va_arg(ap, uint16_vap);\n\t\tif (v < ORIENTATION_TOPLEFT || ORIENTATION_LEFTBOT < v)\n\t\t\tgoto badvalue;\n\t\telse\n\t\t\ttd->td_orientation = (uint16) v;\n\t\tbreak;\n\tcase TIFFTAG_SAMPLESPERPIXEL:\n\t\tv = (uint16) va_arg(ap, uint16_vap);\n\t\tif (v == 0)\n\t\t\tgoto badvalue;\n if( v != td->td_samplesperpixel )\n {\n /* See http://bugzilla.maptools.org/show_bug.cgi?id=2500 */\n if( td->td_sminsamplevalue != NULL )\n {\n TIFFWarningExt(tif->tif_clientdata,module,\n \"SamplesPerPixel tag value is changing, \"\n \"but SMinSampleValue tag was read with a different value. Cancelling it\");\n TIFFClrFieldBit(tif,FIELD_SMINSAMPLEVALUE);\n _TIFFfree(td->td_sminsamplevalue);\n td->td_sminsamplevalue = NULL;\n }\n if( td->td_smaxsamplevalue != NULL )\n {\n TIFFWarningExt(tif->tif_clientdata,module,\n \"SamplesPerPixel tag value is changing, \"\n \"but SMaxSampleValue tag was read with a different value. Cancelling it\");\n TIFFClrFieldBit(tif,FIELD_SMAXSAMPLEVALUE);\n _TIFFfree(td->td_smaxsamplevalue);\n td->td_smaxsamplevalue = NULL;\n }\n }\n\t\ttd->td_samplesperpixel = (uint16) v;\n\t\tbreak;\n\tcase TIFFTAG_ROWSPERSTRIP:\n\t\tv32 = (uint32) va_arg(ap, uint32);\n\t\tif (v32 == 0)\n\t\t\tgoto badvalue32;\n\t\ttd->td_rowsperstrip = v32;\n\t\tif (!TIFFFieldSet(tif, FIELD_TILEDIMENSIONS)) {\n\t\t\ttd->td_tilelength = v32;\n\t\t\ttd->td_tilewidth = td->td_imagewidth;\n\t\t}\n\t\tbreak;\n\tcase TIFFTAG_MINSAMPLEVALUE:\n\t\ttd->td_minsamplevalue = (uint16) va_arg(ap, uint16_vap);\n\t\tbreak;\n\tcase TIFFTAG_MAXSAMPLEVALUE:\n\t\ttd->td_maxsamplevalue = (uint16) va_arg(ap, uint16_vap);\n\t\tbreak;\n\tcase TIFFTAG_SMINSAMPLEVALUE:\n\t\tif (tif->tif_flags & TIFF_PERSAMPLE)\n\t\t\t_TIFFsetDoubleArray(&td->td_sminsamplevalue, va_arg(ap, double*), td->td_samplesperpixel);\n\t\telse\n\t\t\tsetDoubleArrayOneValue(&td->td_sminsamplevalue, va_arg(ap, double), td->td_samplesperpixel);\n\t\tbreak;\n\tcase TIFFTAG_SMAXSAMPLEVALUE:\n\t\tif (tif->tif_flags & TIFF_PERSAMPLE)\n\t\t\t_TIFFsetDoubleArray(&td->td_smaxsamplevalue, va_arg(ap, double*), td->td_samplesperpixel);\n\t\telse\n\t\t\tsetDoubleArrayOneValue(&td->td_smaxsamplevalue, va_arg(ap, double), td->td_samplesperpixel);\n\t\tbreak;\n\tcase TIFFTAG_XRESOLUTION:\n dblval = va_arg(ap, double);\n if( dblval < 0 )\n goto badvaluedouble;\n\t\ttd->td_xresolution = (float) dblval;\n\t\tbreak;\n\tcase TIFFTAG_YRESOLUTION:\n dblval = va_arg(ap, double);\n if( dblval < 0 )\n goto badvaluedouble;\n\t\ttd->td_yresolution = (float) dblval;\n\t\tbreak;\n\tcase TIFFTAG_PLANARCONFIG:\n\t\tv = (uint16) va_arg(ap, uint16_vap);\n\t\tif (v != PLANARCONFIG_CONTIG && v != PLANARCONFIG_SEPARATE)\n\t\t\tgoto badvalue;\n\t\ttd->td_planarconfig = (uint16) v;\n\t\tbreak;\n\tcase TIFFTAG_XPOSITION:\n\t\ttd->td_xposition = (float) va_arg(ap, double);\n\t\tbreak;\n\tcase TIFFTAG_YPOSITION:\n\t\ttd->td_yposition = (float) va_arg(ap, double);\n\t\tbreak;\n\tcase TIFFTAG_RESOLUTIONUNIT:\n\t\tv = (uint16) va_arg(ap, uint16_vap);\n\t\tif (v < RESUNIT_NONE || RESUNIT_CENTIMETER < v)\n\t\t\tgoto badvalue;\n\t\ttd->td_resolutionunit = (uint16) v;\n\t\tbreak;\n\tcase TIFFTAG_PAGENUMBER:\n\t\ttd->td_pagenumber[0] = (uint16) va_arg(ap, uint16_vap);\n\t\ttd->td_pagenumber[1] = (uint16) va_arg(ap, uint16_vap);\n\t\tbreak;\n\tcase TIFFTAG_HALFTONEHINTS:\n\t\ttd->td_halftonehints[0] = (uint16) va_arg(ap, uint16_vap);\n\t\ttd->td_halftonehints[1] = (uint16) va_arg(ap, uint16_vap);\n\t\tbreak;\n\tcase TIFFTAG_COLORMAP:\n\t\tv32 = (uint32)(1L<td_bitspersample);\n\t\t_TIFFsetShortArray(&td->td_colormap[0], va_arg(ap, uint16*), v32);\n\t\t_TIFFsetShortArray(&td->td_colormap[1], va_arg(ap, uint16*), v32);\n\t\t_TIFFsetShortArray(&td->td_colormap[2], va_arg(ap, uint16*), v32);\n\t\tbreak;\n\tcase TIFFTAG_EXTRASAMPLES:\n\t\tif (!setExtraSamples(td, ap, &v))\n\t\t\tgoto badvalue;\n\t\tbreak;\n\tcase TIFFTAG_MATTEING:\n\t\ttd->td_extrasamples = (((uint16) va_arg(ap, uint16_vap)) != 0);\n\t\tif (td->td_extrasamples) {\n\t\t\tuint16 sv = EXTRASAMPLE_ASSOCALPHA;\n\t\t\t_TIFFsetShortArray(&td->td_sampleinfo, &sv, 1);\n\t\t}\n\t\tbreak;\n\tcase TIFFTAG_TILEWIDTH:\n\t\tv32 = (uint32) va_arg(ap, uint32);\n\t\tif (v32 % 16) {\n\t\t\tif (tif->tif_mode != O_RDONLY)\n\t\t\t\tgoto badvalue32;\n\t\t\tTIFFWarningExt(tif->tif_clientdata, tif->tif_name,\n\t\t\t\t\"Nonstandard tile width %d, convert file\", v32);\n\t\t}\n\t\ttd->td_tilewidth = v32;\n\t\ttif->tif_flags |= TIFF_ISTILED;\n\t\tbreak;\n\tcase TIFFTAG_TILELENGTH:\n\t\tv32 = (uint32) va_arg(ap, uint32);\n\t\tif (v32 % 16) {\n\t\t\tif (tif->tif_mode != O_RDONLY)\n\t\t\t\tgoto badvalue32;\n\t\t\tTIFFWarningExt(tif->tif_clientdata, tif->tif_name,\n\t\t\t \"Nonstandard tile length %d, convert file\", v32);\n\t\t}\n\t\ttd->td_tilelength = v32;\n\t\ttif->tif_flags |= TIFF_ISTILED;\n\t\tbreak;\n\tcase TIFFTAG_TILEDEPTH:\n\t\tv32 = (uint32) va_arg(ap, uint32);\n\t\tif (v32 == 0)\n\t\t\tgoto badvalue32;\n\t\ttd->td_tiledepth = v32;\n\t\tbreak;\n\tcase TIFFTAG_DATATYPE:\n\t\tv = (uint16) va_arg(ap, uint16_vap);\n\t\tswitch (v) {\n\t\tcase DATATYPE_VOID:\tv = SAMPLEFORMAT_VOID;\tbreak;\n\t\tcase DATATYPE_INT:\tv = SAMPLEFORMAT_INT;\tbreak;\n\t\tcase DATATYPE_UINT:\tv = SAMPLEFORMAT_UINT;\tbreak;\n\t\tcase DATATYPE_IEEEFP:\tv = SAMPLEFORMAT_IEEEFP;break;\n\t\tdefault:\t\tgoto badvalue;\n\t\t}\n\t\ttd->td_sampleformat = (uint16) v;\n\t\tbreak;\n\tcase TIFFTAG_SAMPLEFORMAT:\n\t\tv = (uint16) va_arg(ap, uint16_vap);\n\t\tif (v < SAMPLEFORMAT_UINT || SAMPLEFORMAT_COMPLEXIEEEFP < v)\n\t\t\tgoto badvalue;\n\t\ttd->td_sampleformat = (uint16) v;\n\n\t\t/* Try to fix up the SWAB function for complex data. */\n\t\tif( td->td_sampleformat == SAMPLEFORMAT_COMPLEXINT\n\t\t && td->td_bitspersample == 32\n\t\t && tif->tif_postdecode == _TIFFSwab32BitData )\n\t\t tif->tif_postdecode = _TIFFSwab16BitData;\n\t\telse if( (td->td_sampleformat == SAMPLEFORMAT_COMPLEXINT\n\t\t\t || td->td_sampleformat == SAMPLEFORMAT_COMPLEXIEEEFP)\n\t\t\t && td->td_bitspersample == 64\n\t\t\t && tif->tif_postdecode == _TIFFSwab64BitData )\n\t\t tif->tif_postdecode = _TIFFSwab32BitData;\n\t\tbreak;\n\tcase TIFFTAG_IMAGEDEPTH:\n\t\ttd->td_imagedepth = (uint32) va_arg(ap, uint32);\n\t\tbreak;\n\tcase TIFFTAG_SUBIFD:\n\t\tif ((tif->tif_flags & TIFF_INSUBIFD) == 0) {\n\t\t\ttd->td_nsubifd = (uint16) va_arg(ap, uint16_vap);\n\t\t\t_TIFFsetLong8Array(&td->td_subifd, (uint64*) va_arg(ap, uint64*),\n\t\t\t (uint32) td->td_nsubifd);\n\t\t} else {\n\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\t\t\t \"%s: Sorry, cannot nest SubIFDs\",\n\t\t\t\t tif->tif_name);\n\t\t\tstatus = 0;\n\t\t}\n\t\tbreak;\n\tcase TIFFTAG_YCBCRPOSITIONING:\n\t\ttd->td_ycbcrpositioning = (uint16) va_arg(ap, uint16_vap);\n\t\tbreak;\n\tcase TIFFTAG_YCBCRSUBSAMPLING:\n\t\ttd->td_ycbcrsubsampling[0] = (uint16) va_arg(ap, uint16_vap);\n\t\ttd->td_ycbcrsubsampling[1] = (uint16) va_arg(ap, uint16_vap);\n\t\tbreak;\n\tcase TIFFTAG_TRANSFERFUNCTION:\n\t\tv = (td->td_samplesperpixel - td->td_extrasamples) > 1 ? 3 : 1;\n\t\tfor (i = 0; i < v; i++)\n\t\t\t_TIFFsetShortArray(&td->td_transferfunction[i],\n\t\t\t va_arg(ap, uint16*), 1U<td_bitspersample);\n\t\tbreak;\n\tcase TIFFTAG_REFERENCEBLACKWHITE:\n\t\t/* XXX should check for null range */\n\t\t_TIFFsetFloatArray(&td->td_refblackwhite, va_arg(ap, float*), 6);\n\t\tbreak;\n\tcase TIFFTAG_INKNAMES:\n\t\tv = (uint16) va_arg(ap, uint16_vap);\n\t\ts = va_arg(ap, char*);\n\t\tv = checkInkNamesString(tif, v, s);\n\t\tstatus = v > 0;\n\t\tif( v > 0 ) {\n\t\t\t_TIFFsetNString(&td->td_inknames, s, v);\n\t\t\ttd->td_inknameslen = v;\n\t\t}\n\t\tbreak;\n\tcase TIFFTAG_PERSAMPLE:\n\t\tv = (uint16) va_arg(ap, uint16_vap);\n\t\tif( v == PERSAMPLE_MULTI )\n\t\t\ttif->tif_flags |= TIFF_PERSAMPLE;\n\t\telse\n\t\t\ttif->tif_flags &= ~TIFF_PERSAMPLE;\n\t\tbreak;\n\tdefault: {\n\t\tTIFFTagValue *tv;\n\t\tint tv_size, iCustom;\n\n\t\t/*\n\t\t * This can happen if multiple images are open with different\n\t\t * codecs which have private tags. The global tag information\n\t\t * table may then have tags that are valid for one file but not\n\t\t * the other. If the client tries to set a tag that is not valid\n\t\t * for the image's codec then we'll arrive here. This\n\t\t * happens, for example, when tiffcp is used to convert between\n\t\t * compression schemes and codec-specific tags are blindly copied.\n\t\t */\n\t\tif(fip->field_bit != FIELD_CUSTOM) {\n\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\t\t \"%s: Invalid %stag \\\"%s\\\" (not supported by codec)\",\n\t\t\t tif->tif_name, isPseudoTag(tag) ? \"pseudo-\" : \"\",\n\t\t\t fip->field_name);\n\t\t\tstatus = 0;\n\t\t\tbreak;\n\t\t}\n\n\t\t/*\n\t\t * Find the existing entry for this custom value.\n\t\t */\n\t\ttv = NULL;\n\t\tfor (iCustom = 0; iCustom < td->td_customValueCount; iCustom++) {\n\t\t\tif (td->td_customValues[iCustom].info->field_tag == tag) {\n\t\t\t\ttv = td->td_customValues + iCustom;\n\t\t\t\tif (tv->value != NULL) {\n\t\t\t\t\t_TIFFfree(tv->value);\n\t\t\t\t\ttv->value = NULL;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * Grow the custom list if the entry was not found.\n\t\t */\n\t\tif(tv == NULL) {\n\t\t\tTIFFTagValue *new_customValues;\n\n\t\t\ttd->td_customValueCount++;\n\t\t\tnew_customValues = (TIFFTagValue *)\n\t\t\t _TIFFrealloc(td->td_customValues,\n\t\t\t sizeof(TIFFTagValue) * td->td_customValueCount);\n\t\t\tif (!new_customValues) {\n\t\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\t\t\t \"%s: Failed to allocate space for list of custom values\",\n\t\t\t\t tif->tif_name);\n\t\t\t\tstatus = 0;\n\t\t\t\tgoto end;\n\t\t\t}\n\n\t\t\ttd->td_customValues = new_customValues;\n\n\t\t\ttv = td->td_customValues + (td->td_customValueCount - 1);\n\t\t\ttv->info = fip;\n\t\t\ttv->value = NULL;\n\t\t\ttv->count = 0;\n\t\t}\n\n\t\t/*\n\t\t * Set custom value ... save a copy of the custom tag value.\n\t\t */\n\t\ttv_size = _TIFFDataSize(fip->field_type);\n\t\tif (tv_size == 0) {\n\t\t\tstatus = 0;\n\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\t\t \"%s: Bad field type %d for \\\"%s\\\"\",\n\t\t\t tif->tif_name, fip->field_type,\n\t\t\t fip->field_name);\n\t\t\tgoto end;\n\t\t}\n\n\t\tif (fip->field_type == TIFF_ASCII)\n\t\t{\n\t\t\tuint32 ma;\n\t\t\tchar* mb;\n\t\t\tif (fip->field_passcount)\n\t\t\t{\n\t\t\t\tassert(fip->field_writecount==TIFF_VARIABLE2);\n\t\t\t\tma=(uint32)va_arg(ap,uint32);\n\t\t\t\tmb=(char*)va_arg(ap,char*);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tmb=(char*)va_arg(ap,char*);\n\t\t\t\tma=(uint32)(strlen(mb)+1);\n\t\t\t}\n\t\t\ttv->count=ma;\n\t\t\tsetByteArray(&tv->value,mb,ma,1);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (fip->field_passcount) {\n\t\t\t\tif (fip->field_writecount == TIFF_VARIABLE2)\n\t\t\t\t\ttv->count = (uint32) va_arg(ap, uint32);\n\t\t\t\telse\n\t\t\t\t\ttv->count = (int) va_arg(ap, int);\n\t\t\t} else if (fip->field_writecount == TIFF_VARIABLE\n\t\t\t || fip->field_writecount == TIFF_VARIABLE2)\n\t\t\t\ttv->count = 1;\n\t\t\telse if (fip->field_writecount == TIFF_SPP)\n\t\t\t\ttv->count = td->td_samplesperpixel;\n\t\t\telse\n\t\t\t\ttv->count = fip->field_writecount;\n\n\t\t\tif (tv->count == 0) {\n\t\t\t\tstatus = 0;\n\t\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\t\t\t\t \"%s: Null count for \\\"%s\\\" (type \"\n\t\t\t\t\t \"%d, writecount %d, passcount %d)\",\n\t\t\t\t\t tif->tif_name,\n\t\t\t\t\t fip->field_name,\n\t\t\t\t\t fip->field_type,\n\t\t\t\t\t fip->field_writecount,\n\t\t\t\t\t fip->field_passcount);\n\t\t\t\tgoto end;\n\t\t\t}\n\n\t\t\ttv->value = _TIFFCheckMalloc(tif, tv->count, tv_size,\n\t\t\t \"custom tag binary object\");\n\t\t\tif (!tv->value) {\n\t\t\t\tstatus = 0;\n\t\t\t\tgoto end;\n\t\t\t}\n\n\t\t\tif (fip->field_tag == TIFFTAG_DOTRANGE \n\t\t\t && strcmp(fip->field_name,\"DotRange\") == 0) {\n\t\t\t\t/* TODO: This is an evil exception and should not have been\n\t\t\t\t handled this way ... likely best if we move it into\n\t\t\t\t the directory structure with an explicit field in \n\t\t\t\t libtiff 4.1 and assign it a FIELD_ value */\n\t\t\t\tuint16 v2[2];\n\t\t\t\tv2[0] = (uint16)va_arg(ap, int);\n\t\t\t\tv2[1] = (uint16)va_arg(ap, int);\n\t\t\t\t_TIFFmemcpy(tv->value, &v2, 4);\n\t\t\t}\n\n\t\t\telse if (fip->field_passcount\n\t\t\t\t || fip->field_writecount == TIFF_VARIABLE\n\t\t\t\t || fip->field_writecount == TIFF_VARIABLE2\n\t\t\t\t || fip->field_writecount == TIFF_SPP\n\t\t\t\t || tv->count > 1) {\n\t\t\t\t_TIFFmemcpy(tv->value, va_arg(ap, void *),\n\t\t\t\t tv->count * tv_size);\n\t\t\t} else {\n\t\t\t\tchar *val = (char *)tv->value;\n\t\t\t\tassert( tv->count == 1 );\n\n\t\t\t\tswitch (fip->field_type) {\n\t\t\t\tcase TIFF_BYTE:\n\t\t\t\tcase TIFF_UNDEFINED:\n\t\t\t\t\t{\n\t\t\t\t\t\tuint8 v2 = (uint8)va_arg(ap, int);\n\t\t\t\t\t\t_TIFFmemcpy(val, &v2, tv_size);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase TIFF_SBYTE:\n\t\t\t\t\t{\n\t\t\t\t\t\tint8 v2 = (int8)va_arg(ap, int);\n\t\t\t\t\t\t_TIFFmemcpy(val, &v2, tv_size);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase TIFF_SHORT:\n\t\t\t\t\t{\n\t\t\t\t\t\tuint16 v2 = (uint16)va_arg(ap, int);\n\t\t\t\t\t\t_TIFFmemcpy(val, &v2, tv_size);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase TIFF_SSHORT:\n\t\t\t\t\t{\n\t\t\t\t\t\tint16 v2 = (int16)va_arg(ap, int);\n\t\t\t\t\t\t_TIFFmemcpy(val, &v2, tv_size);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase TIFF_LONG:\n\t\t\t\tcase TIFF_IFD:\n\t\t\t\t\t{\n\t\t\t\t\t\tuint32 v2 = va_arg(ap, uint32);\n\t\t\t\t\t\t_TIFFmemcpy(val, &v2, tv_size);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase TIFF_SLONG:\n\t\t\t\t\t{\n\t\t\t\t\t\tint32 v2 = va_arg(ap, int32);\n\t\t\t\t\t\t_TIFFmemcpy(val, &v2, tv_size);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase TIFF_LONG8:\n\t\t\t\tcase TIFF_IFD8:\n\t\t\t\t\t{\n\t\t\t\t\t\tuint64 v2 = va_arg(ap, uint64);\n\t\t\t\t\t\t_TIFFmemcpy(val, &v2, tv_size);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase TIFF_SLONG8:\n\t\t\t\t\t{\n\t\t\t\t\t\tint64 v2 = va_arg(ap, int64);\n\t\t\t\t\t\t_TIFFmemcpy(val, &v2, tv_size);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase TIFF_RATIONAL:\n\t\t\t\tcase TIFF_SRATIONAL:\n\t\t\t\tcase TIFF_FLOAT:\n\t\t\t\t\t{\n\t\t\t\t\t\tfloat v2 = (float)va_arg(ap, double);\n\t\t\t\t\t\t_TIFFmemcpy(val, &v2, tv_size);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase TIFF_DOUBLE:\n\t\t\t\t\t{\n\t\t\t\t\t\tdouble v2 = va_arg(ap, double);\n\t\t\t\t\t\t_TIFFmemcpy(val, &v2, tv_size);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\t_TIFFmemset(val, 0, tv_size);\n\t\t\t\t\tstatus = 0;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t}\n\tif (status) {\n\t\tconst TIFFField* fip2=TIFFFieldWithTag(tif,tag);\n\t\tif (fip2) \n\t\t\tTIFFSetFieldBit(tif, fip2->field_bit);\n\t\ttif->tif_flags |= TIFF_DIRTYDIRECT;\n\t}\n\nend:\n\tva_end(ap);\n\treturn (status);\nbadvalue:\n {\n\t\tconst TIFFField* fip2=TIFFFieldWithTag(tif,tag);\n\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\t \"%s: Bad value %u for \\\"%s\\\" tag\",\n\t\t tif->tif_name, v,\n\t\t fip2 ? fip2->field_name : \"Unknown\");\n\t\tva_end(ap);\n }\n\treturn (0);\nbadvalue32:\n {\n\t\tconst TIFFField* fip2=TIFFFieldWithTag(tif,tag);\n\t\tTIFFErrorExt(tif->tif_clientdata, module,\n\t\t \"%s: Bad value %u for \\\"%s\\\" tag\",\n\t\t tif->tif_name, v32,\n\t\t fip2 ? fip2->field_name : \"Unknown\");\n\t\tva_end(ap);\n }\n\treturn (0);\nbadvaluedouble:\n {\n const TIFFField* fip2=TIFFFieldWithTag(tif,tag);\n TIFFErrorExt(tif->tif_clientdata, module,\n \"%s: Bad value %f for \\\"%s\\\" tag\",\n tif->tif_name, dblval,\n fip2 ? fip2->field_name : \"Unknown\");\n va_end(ap);\n }\n return (0);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': '* libtiff/tif_dir.c, tif_dirread.c, tif_dirwrite.c: implement various clampings\nof double to other data types to avoid undefined behaviour if the output range\nisn't big enough to hold the input value.\nFixes http://bugzilla.maptools.org/show_bug.cgi?id=2643\nhttp://bugzilla.maptools.org/show_bug.cgi?id=2642\nhttp://bugzilla.maptools.org/show_bug.cgi?id=2646\nhttp://bugzilla.maptools.org/show_bug.cgi?id=2647'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: _isBidi (const uint32_t *label, size_t llen)\n{\n while (llen-- > 0) {\n int bc = uc_bidi_category (*label++);\n\n if (bc == UC_BIDI_R || bc == UC_BIDI_AL || bc == UC_BIDI_AN)\n return 1;\n }\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'lib/bidi: Fix integer overflow (found by fuzzing)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: main (int argc, char * argv [])\n{\tconst char\t*progname, *infilename, *outfilename ;\n\tSNDFILE\t\t*infile = NULL, *outfile = NULL ;\n\tSF_INFO\t\tsfinfo ;\n\tint\t\t\tk, outfilemajor, outfileminor = 0, infileminor ;\n\tint\t\t\toverride_sample_rate = 0 ; /* assume no sample rate override. */\n\tint\t\t\tendian = SF_ENDIAN_FILE, normalize = SF_FALSE ;\n\n\tprogname = program_name (argv [0]) ;\n\n\tif (argc < 3 || argc > 5)\n\t\tusage_exit (progname) ;\n\n\tinfilename = argv [argc-2] ;\n\toutfilename = argv [argc-1] ;\n\n\tif (strcmp (infilename, outfilename) == 0)\n\t{\tprintf (\"Error : Input and output filenames are the same.\\n\\n\") ;\n\t\tusage_exit (progname) ;\n\t\t} ;\n\n\tif (strlen (infilename) > 1 && infilename [0] == '-')\n\t{\tprintf (\"Error : Input filename (%s) looks like an option.\\n\\n\", infilename) ;\n\t\tusage_exit (progname) ;\n\t\t} ;\n\n\tif (outfilename [0] == '-')\n\t{\tprintf (\"Error : Output filename (%s) looks like an option.\\n\\n\", outfilename) ;\n\t\tusage_exit (progname) ;\n\t\t} ;\n\n\tfor (k = 1 ; k < argc - 2 ; k++)\n\t{\tif (! strcmp (argv [k], \"-pcms8\"))\n\t\t{\toutfileminor = SF_FORMAT_PCM_S8 ;\n\t\t\tcontinue ;\n\t\t\t} ;\n\t\tif (! strcmp (argv [k], \"-pcmu8\"))\n\t\t{\toutfileminor = SF_FORMAT_PCM_U8 ;\n\t\t\tcontinue ;\n\t\t\t} ;\n\t\tif (! strcmp (argv [k], \"-pcm16\"))\n\t\t{\toutfileminor = SF_FORMAT_PCM_16 ;\n\t\t\tcontinue ;\n\t\t\t} ;\n\t\tif (! strcmp (argv [k], \"-pcm24\"))\n\t\t{\toutfileminor = SF_FORMAT_PCM_24 ;\n\t\t\tcontinue ;\n\t\t\t} ;\n\t\tif (! strcmp (argv [k], \"-pcm32\"))\n\t\t{\toutfileminor = SF_FORMAT_PCM_32 ;\n\t\t\tcontinue ;\n\t\t\t} ;\n\t\tif (! strcmp (argv [k], \"-float32\"))\n\t\t{\toutfileminor = SF_FORMAT_FLOAT ;\n\t\t\tcontinue ;\n\t\t\t} ;\n\t\tif (! strcmp (argv [k], \"-ulaw\"))\n\t\t{\toutfileminor = SF_FORMAT_ULAW ;\n\t\t\tcontinue ;\n\t\t\t} ;\n\t\tif (! strcmp (argv [k], \"-alaw\"))\n\t\t{\toutfileminor = SF_FORMAT_ALAW ;\n\t\t\tcontinue ;\n\t\t\t} ;\n\t\tif (! strcmp (argv [k], \"-alac16\"))\n\t\t{\toutfileminor = SF_FORMAT_ALAC_16 ;\n\t\t\tcontinue ;\n\t\t\t} ;\n\t\tif (! strcmp (argv [k], \"-alac20\"))\n\t\t{\toutfileminor = SF_FORMAT_ALAC_20 ;\n\t\t\tcontinue ;\n\t\t\t} ;\n\t\tif (! strcmp (argv [k], \"-alac24\"))\n\t\t{\toutfileminor = SF_FORMAT_ALAC_24 ;\n\t\t\tcontinue ;\n\t\t\t} ;\n\t\tif (! strcmp (argv [k], \"-alac32\"))\n\t\t{\toutfileminor = SF_FORMAT_ALAC_32 ;\n\t\t\tcontinue ;\n\t\t\t} ;\n\t\tif (! strcmp (argv [k], \"-ima-adpcm\"))\n\t\t{\toutfileminor = SF_FORMAT_IMA_ADPCM ;\n\t\t\tcontinue ;\n\t\t\t} ;\n\t\tif (! strcmp (argv [k], \"-ms-adpcm\"))\n\t\t{\toutfileminor = SF_FORMAT_MS_ADPCM ;\n\t\t\tcontinue ;\n\t\t\t} ;\n\t\tif (! strcmp (argv [k], \"-gsm610\"))\n\t\t{\toutfileminor = SF_FORMAT_GSM610 ;\n\t\t\tcontinue ;\n\t\t\t} ;\n\t\tif (! strcmp (argv [k], \"-dwvw12\"))\n\t\t{\toutfileminor = SF_FORMAT_DWVW_12 ;\n\t\t\tcontinue ;\n\t\t\t} ;\n\t\tif (! strcmp (argv [k], \"-dwvw16\"))\n\t\t{\toutfileminor = SF_FORMAT_DWVW_16 ;\n\t\t\tcontinue ;\n\t\t\t} ;\n\t\tif (! strcmp (argv [k], \"-dwvw24\"))\n\t\t{\toutfileminor = SF_FORMAT_DWVW_24 ;\n\t\t\tcontinue ;\n\t\t\t} ;\n\t\tif (! strcmp (argv [k], \"-vorbis\"))\n\t\t{\toutfileminor = SF_FORMAT_VORBIS ;\n\t\t\tcontinue ;\n\t\t\t} ;\n\n\t\tif (strstr (argv [k], \"-override-sample-rate=\") == argv [k])\n\t\t{\tconst char *ptr ;\n\n\t\t\tptr = argv [k] + strlen (\"-override-sample-rate=\") ;\n\t\t\toverride_sample_rate = atoi (ptr) ;\n\t\t\tcontinue ;\n\t\t\t} ;\n\n\t\tif (! strcmp (argv [k], \"-endian=little\"))\n\t\t{\tendian = SF_ENDIAN_LITTLE ;\n\t\t\tcontinue ;\n\t\t\t} ;\n\n\t\tif (! strcmp (argv [k], \"-endian=big\"))\n\t\t{\tendian = SF_ENDIAN_BIG ;\n\t\t\tcontinue ;\n\t\t\t} ;\n\n\t\tif (! strcmp (argv [k], \"-endian=cpu\"))\n\t\t{\tendian = SF_ENDIAN_CPU ;\n\t\t\tcontinue ;\n\t\t\t} ;\n\n\t\tif (! strcmp (argv [k], \"-endian=file\"))\n\t\t{\tendian = SF_ENDIAN_FILE ;\n\t\t\tcontinue ;\n\t\t\t} ;\n\n\t\tif (! strcmp (argv [k], \"-normalize\"))\n\t\t{\tnormalize = SF_TRUE ;\n\t\t\tcontinue ;\n\t\t\t} ;\n\n\t\tprintf (\"Error : Not able to decode argunment '%s'.\\n\", argv [k]) ;\n\t\texit (1) ;\n\t\t} ;\n\n\tmemset (&sfinfo, 0, sizeof (sfinfo)) ;\n\n\tif ((infile = sf_open (infilename, SFM_READ, &sfinfo)) == NULL)\n\t{\tprintf (\"Not able to open input file %s.\\n\", infilename) ;\n\t\tputs (sf_strerror (NULL)) ;\n\t\treturn 1 ;\n\t\t} ;\n\n\t/* Update sample rate if forced to something else. */\n\tif (override_sample_rate)\n\t\tsfinfo.samplerate = override_sample_rate ;\n\n\tinfileminor = sfinfo.format & SF_FORMAT_SUBMASK ;\n\n\tif ((sfinfo.format = sfe_file_type_of_ext (outfilename, sfinfo.format)) == 0)\n\t{\tprintf (\"Error : Not able to determine output file type for %s.\\n\", outfilename) ;\n\t\treturn 1 ;\n\t\t} ;\n\n\toutfilemajor = sfinfo.format & (SF_FORMAT_TYPEMASK | SF_FORMAT_ENDMASK) ;\n\n\tif (outfileminor == 0)\n\t\toutfileminor = sfinfo.format & SF_FORMAT_SUBMASK ;\n\n\tif (outfileminor != 0)\n\t\tsfinfo.format = outfilemajor | outfileminor ;\n\telse\n\t\tsfinfo.format = outfilemajor | (sfinfo.format & SF_FORMAT_SUBMASK) ;\n\n\tsfinfo.format |= endian ;\n\n\tif ((sfinfo.format & SF_FORMAT_TYPEMASK) == SF_FORMAT_XI)\n\t\tswitch (sfinfo.format & SF_FORMAT_SUBMASK)\n\t\t{\tcase SF_FORMAT_PCM_16 :\n\t\t\t\t\tsfinfo.format = outfilemajor | SF_FORMAT_DPCM_16 ;\n\t\t\t\t\tbreak ;\n\n\t\t\tcase SF_FORMAT_PCM_S8 :\n\t\t\tcase SF_FORMAT_PCM_U8 :\n\t\t\t\t\tsfinfo.format = outfilemajor | SF_FORMAT_DPCM_8 ;\n\t\t\t\t\tbreak ;\n\t\t\t} ;\n\n\tif (sf_format_check (&sfinfo) == 0)\n\t\treport_format_error_exit (argv [0], &sfinfo) ;\n\n\tif ((sfinfo.format & SF_FORMAT_SUBMASK) == SF_FORMAT_GSM610 && sfinfo.samplerate != 8000)\n\t{\tprintf (\n\t\t\t\"WARNING: GSM 6.10 data format only supports 8kHz sample rate. The converted\\n\"\n\t\t\t\"ouput file will contain the input data converted to the GSM 6.10 data format\\n\"\n\t\t\t\"but not re-sampled.\\n\"\n\t\t\t) ;\n\t\t} ;\n\n\t/* Open the output file. */\n\tif ((outfile = sf_open (outfilename, SFM_WRITE, &sfinfo)) == NULL)\n\t{\tprintf (\"Not able to open output file %s : %s\\n\", outfilename, sf_strerror (NULL)) ;\n\t\treturn 1 ;\n\t\t} ;\n\n\t/* Copy the metadata */\n\tcopy_metadata (outfile, infile, sfinfo.channels) ;\n\n\tif (normalize\n\t\t\t|| (outfileminor == SF_FORMAT_DOUBLE) || (outfileminor == SF_FORMAT_FLOAT)\n\t\t\t|| (infileminor == SF_FORMAT_DOUBLE) || (infileminor == SF_FORMAT_FLOAT)\n\t\t\t|| (infileminor == SF_FORMAT_VORBIS) || (outfileminor == SF_FORMAT_VORBIS))\n\t\tsfe_copy_data_fp (outfile, infile, sfinfo.channels, normalize) ;\n\telse\n\t\tsfe_copy_data_int (outfile, infile, sfinfo.channels) ;\n\n\tsf_close (infile) ;\n\tsf_close (outfile) ;\n\n\treturn 0 ;\n} /* main */ ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'sfe_copy_data_fp: check value of \"max\" variable for being normal\n\nand check elements of the data[] array for being finite.\n\nBoth checks use functions provided by the header as declared\nby the C99 standard.\n\nFixes #317\nCVE-2017-14245\nCVE-2017-14246'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int asn1_template_ex_d2i(ASN1_VALUE **val,\n const unsigned char **in, long inlen,\n const ASN1_TEMPLATE *tt, char opt,\n ASN1_TLC *ctx)\n{\n int flags, aclass;\n int ret;\n long len;\n const unsigned char *p, *q;\n char exp_eoc;\n if (!val)\n return 0;\n flags = tt->flags;\n aclass = flags & ASN1_TFLG_TAG_CLASS;\n\n p = *in;\n\n /* Check if EXPLICIT tag expected */\n if (flags & ASN1_TFLG_EXPTAG) {\n char cst;\n /*\n * Need to work out amount of data available to the inner content and\n * where it starts: so read in EXPLICIT header to get the info.\n */\n ret = asn1_check_tlen(&len, NULL, NULL, &exp_eoc, &cst,\n &p, inlen, tt->tag, aclass, opt, ctx);\n q = p;\n if (!ret) {\n ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I, ERR_R_NESTED_ASN1_ERROR);\n return 0;\n } else if (ret == -1)\n return -1;\n if (!cst) {\n ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I,\n ASN1_R_EXPLICIT_TAG_NOT_CONSTRUCTED);\n return 0;\n }\n /* We've found the field so it can't be OPTIONAL now */\n ret = asn1_template_noexp_d2i(val, &p, len, tt, 0, ctx);\n if (!ret) {\n ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I, ERR_R_NESTED_ASN1_ERROR);\n return 0;\n }\n /* We read the field in OK so update length */\n len -= p - q;\n if (exp_eoc) {\n /* If NDEF we must have an EOC here */\n if (!asn1_check_eoc(&p, len)) {\n ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I, ASN1_R_MISSING_EOC);\n goto err;\n }\n } else {\n /*\n * Otherwise we must hit the EXPLICIT tag end or its an error\n */\n if (len) {\n ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I,\n ASN1_R_EXPLICIT_LENGTH_MISMATCH);\n goto err;\n }\n }\n } else\n return asn1_template_noexp_d2i(val, in, inlen, tt, opt, ctx);\n\n *in = p;\n return 1;\n\n err:\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400', 'CWE-674', 'CWE-787'], 'message': 'Limit ASN.1 constructed types recursive definition depth\n\nConstructed types with a recursive definition (such as can be found in\nPKCS7) could eventually exceed the stack given malicious input with\nexcessive recursion. Therefore we limit the stack depth.\n\nCVE-2018-0739\n\nCredit to OSSFuzz for finding this issue.\n\nReviewed-by: Rich Salz '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: startElementHandler(void *userData, const char *name, const char **atts)\n{\n int pos;\n userdata_t *ud = (userdata_t *) userData;\n Agraph_t *g = NULL;\n\n if (strcmp(name, \"graphml\") == 0) {\n\t/* do nothing */\n } else if (strcmp(name, \"graph\") == 0) {\n\tconst char *edgeMode = \"\";\n\tconst char *id;\n\tAgdesc_t dir;\n\tchar buf[NAMEBUF];\t/* holds % + number */\n\n\tCurrent_class = TAG_GRAPH;\n\tif (ud->closedElementType == TAG_GRAPH) {\n\t fprintf(stderr,\n\t\t \"Warning: Node contains more than one graph.\\n\");\n\t}\n\tpos = get_xml_attr(\"id\", atts);\n\tif (pos > 0) {\n\t id = atts[pos];\n\t}\n\telse\n\t id = ud->gname;\n\tpos = get_xml_attr(\"edgedefault\", atts);\n\tif (pos > 0) {\n\t edgeMode = atts[pos];\n\t}\n\n\tif (GSP == 0) {\n\t if (strcmp(edgeMode, \"directed\") == 0) {\n\t\tdir = Agdirected;\n\t } else if (strcmp(edgeMode, \"undirected\") == 0) {\n\t\tdir = Agundirected;\n\t } else {\n\t\tif (Verbose) {\n\t\t fprintf(stderr,\n\t\t\t\"Warning: graph has no edgedefault attribute - assume directed\\n\");\n\t\t}\n\t\tdir = Agdirected;\n\t }\n\t g = agopen((char *) id, dir, &AgDefaultDisc);\n\t push_subg(g);\n\t} else {\n\t Agraph_t *subg;\n\t if (isAnonGraph((char *) id)) {\n\t\tstatic int anon_id = 1;\n\t\tsprintf(buf, \"%%%d\", anon_id++);\n\t\tid = buf;\n\t }\n\t subg = agsubg(G, (char *) id, 1);\n\t push_subg(subg);\n\t}\n\n\tpushString(&ud->elements, id);\n } else if (strcmp(name, \"node\") == 0) {\n\tCurrent_class = TAG_NODE;\n\tpos = get_xml_attr(\"id\", atts);\n\tif (pos > 0) {\n\t const char *attrname;\n\t attrname = atts[pos];\n\n\t bind_node(attrname);\n\n\t pushString(&ud->elements, attrname);\n\t}\n\n } else if (strcmp(name, \"edge\") == 0) {\n\tconst char *head = \"\", *tail = \"\";\n\tchar *tname;\n\tAgnode_t *t;\n\n\tCurrent_class = TAG_EDGE;\n\tpos = get_xml_attr(\"source\", atts);\n\tif (pos > 0)\n\t tail = atts[pos];\n\tpos = get_xml_attr(\"target\", atts);\n\tif (pos > 0)\n\t head = atts[pos];\n\n\ttname = mapLookup(ud->nameMap, (char *) tail);\n\tif (tname)\n\t tail = tname;\n\n\ttname = mapLookup(ud->nameMap, (char *) head);\n\tif (tname)\n\t head = tname;\n\n\tbind_edge(tail, head);\n\n\tt = AGTAIL(E);\n\ttname = agnameof(t);\n\n\tif (strcmp(tname, tail) == 0) {\n\t ud->edgeinverted = FALSE;\n\t} else if (strcmp(tname, head) == 0) {\n\t ud->edgeinverted = TRUE;\n\t}\n\n\tpos = get_xml_attr(\"id\", atts);\n\tif (pos > 0) {\n\t setEdgeAttr(E, GRAPHML_ID, (char *) atts[pos], ud);\n\t}\n } else {\n\t/* must be some extension */\n\tfprintf(stderr,\n\t\t\"Unknown node %s - ignoring.\\n\",\n\t\tname);\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'attempted fix for null pointer deference on malformed input'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int test_rand_drbg_reseed(void)\n{\n RAND_DRBG *master, *public, *private;\n unsigned char rand_add_buf[256];\n int rv=0;\n time_t before_reseed;\n\n /* Check whether RAND_OpenSSL() is the default method */\n if (!TEST_ptr_eq(RAND_get_rand_method(), RAND_OpenSSL()))\n return 0;\n\n /* All three DRBGs should be non-null */\n if (!TEST_ptr(master = RAND_DRBG_get0_master())\n || !TEST_ptr(public = RAND_DRBG_get0_public())\n || !TEST_ptr(private = RAND_DRBG_get0_private()))\n return 0;\n\n /* There should be three distinct DRBGs, two of them chained to master */\n if (!TEST_ptr_ne(public, private)\n || !TEST_ptr_ne(public, master)\n || !TEST_ptr_ne(private, master)\n || !TEST_ptr_eq(public->parent, master)\n || !TEST_ptr_eq(private->parent, master))\n return 0;\n\n /* uninstantiate the three global DRBGs */\n RAND_DRBG_uninstantiate(private);\n RAND_DRBG_uninstantiate(public);\n RAND_DRBG_uninstantiate(master);\n\n\n /* Install hooks for the following tests */\n hook_drbg(master, &master_ctx);\n hook_drbg(public, &public_ctx);\n hook_drbg(private, &private_ctx);\n\n\n /*\n * Test initial seeding of shared DRBGs\n */\n if (!TEST_true(test_drbg_reseed(1, master, public, private, 1, 1, 1, 0)))\n goto error;\n reset_drbg_hook_ctx();\n\n\n /*\n * Test initial state of shared DRBGs\n */\n if (!TEST_true(test_drbg_reseed(1, master, public, private, 0, 0, 0, 0)))\n goto error;\n reset_drbg_hook_ctx();\n\n /*\n * Test whether the public and private DRBG are both reseeded when their\n * reseed counters differ from the master's reseed counter.\n */\n master->reseed_prop_counter++;\n if (!TEST_true(test_drbg_reseed(1, master, public, private, 0, 1, 1, 0)))\n goto error;\n reset_drbg_hook_ctx();\n\n /*\n * Test whether the public DRBG is reseeded when its reseed counter differs\n * from the master's reseed counter.\n */\n master->reseed_prop_counter++;\n private->reseed_prop_counter++;\n if (!TEST_true(test_drbg_reseed(1, master, public, private, 0, 1, 0, 0)))\n goto error;\n reset_drbg_hook_ctx();\n\n /*\n * Test whether the private DRBG is reseeded when its reseed counter differs\n * from the master's reseed counter.\n */\n master->reseed_prop_counter++;\n public->reseed_prop_counter++;\n if (!TEST_true(test_drbg_reseed(1, master, public, private, 0, 0, 1, 0)))\n goto error;\n reset_drbg_hook_ctx();\n\n\n /* fill 'randomness' buffer with some arbitrary data */\n memset(rand_add_buf, 'r', sizeof(rand_add_buf));\n\n /*\n * Test whether all three DRBGs are reseeded by RAND_add().\n * The before_reseed time has to be measured here and passed into the\n * test_drbg_reseed() test, because the master DRBG gets already reseeded\n * in RAND_add(), whence the check for the condition\n * before_reseed <= master->reseed_time will fail if the time value happens\n * to increase between the RAND_add() and the test_drbg_reseed() call.\n */\n before_reseed = time(NULL);\n RAND_add(rand_add_buf, sizeof(rand_add_buf), sizeof(rand_add_buf));\n if (!TEST_true(test_drbg_reseed(1, master, public, private, 1, 1, 1,\n before_reseed)))\n goto error;\n reset_drbg_hook_ctx();\n\n\n /*\n * Test whether none of the DRBGs is reseed if the master fails to reseed\n */\n master_ctx.fail = 1;\n master->reseed_prop_counter++;\n RAND_add(rand_add_buf, sizeof(rand_add_buf), sizeof(rand_add_buf));\n if (!TEST_true(test_drbg_reseed(0, master, public, private, 0, 0, 0, 0)))\n goto error;\n reset_drbg_hook_ctx();\n\n rv = 1;\n\nerror:\n /* Remove hooks */\n unhook_drbg(master);\n unhook_drbg(public);\n unhook_drbg(private);\n\n return rv;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-330'], 'message': 'drbg: ensure fork-safety without using a pthread_atfork handler\n\nWhen the new OpenSSL CSPRNG was introduced in version 1.1.1,\nit was announced in the release notes that it would be fork-safe,\nwhich the old CSPRNG hadn't been.\n\nThe fork-safety was implemented using a fork count, which was\nincremented by a pthread_atfork handler. Initially, this handler\nwas enabled by default. Unfortunately, the default behaviour\nhad to be changed for other reasons in commit b5319bdbd095, so\nthe new OpenSSL CSPRNG failed to keep its promise.\n\nThis commit restores the fork-safety using a different approach.\nIt replaces the fork count by a fork id, which coincides with\nthe process id on UNIX-like operating systems and is zero on other\noperating systems. It is used to detect when an automatic reseed\nafter a fork is necessary.\n\nTo prevent a future regression, it also adds a test to verify that\nthe child reseeds after fork.\n\nCVE-2019-1549\n\nReviewed-by: Paul Dale \nReviewed-by: Matt Caswell \n(Merged from https://github.com/openssl/openssl/pull/9802)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: BIO *PKCS7_dataDecode(PKCS7 *p7, EVP_PKEY *pkey, BIO *in_bio, X509 *pcert)\n{\n int i, j;\n BIO *out = NULL, *btmp = NULL, *etmp = NULL, *bio = NULL;\n X509_ALGOR *xa;\n ASN1_OCTET_STRING *data_body = NULL;\n const EVP_MD *evp_md;\n const EVP_CIPHER *evp_cipher = NULL;\n EVP_CIPHER_CTX *evp_ctx = NULL;\n X509_ALGOR *enc_alg = NULL;\n STACK_OF(X509_ALGOR) *md_sk = NULL;\n STACK_OF(PKCS7_RECIP_INFO) *rsk = NULL;\n PKCS7_RECIP_INFO *ri = NULL;\n unsigned char *ek = NULL, *tkey = NULL;\n int eklen = 0, tkeylen = 0;\n\n if (p7 == NULL) {\n PKCS7err(PKCS7_F_PKCS7_DATADECODE, PKCS7_R_INVALID_NULL_POINTER);\n return NULL;\n }\n\n if (p7->d.ptr == NULL) {\n PKCS7err(PKCS7_F_PKCS7_DATADECODE, PKCS7_R_NO_CONTENT);\n return NULL;\n }\n\n i = OBJ_obj2nid(p7->type);\n p7->state = PKCS7_S_HEADER;\n\n switch (i) {\n case NID_pkcs7_signed:\n /*\n * p7->d.sign->contents is a PKCS7 structure consisting of a contentType\n * field and optional content.\n * data_body is NULL if that structure has no (=detached) content\n * or if the contentType is wrong (i.e., not \"data\").\n */\n data_body = PKCS7_get_octet_string(p7->d.sign->contents);\n if (!PKCS7_is_detached(p7) && data_body == NULL) {\n PKCS7err(PKCS7_F_PKCS7_DATADECODE,\n PKCS7_R_INVALID_SIGNED_DATA_TYPE);\n goto err;\n }\n md_sk = p7->d.sign->md_algs;\n break;\n case NID_pkcs7_signedAndEnveloped:\n rsk = p7->d.signed_and_enveloped->recipientinfo;\n md_sk = p7->d.signed_and_enveloped->md_algs;\n /* data_body is NULL if the optional EncryptedContent is missing. */\n data_body = p7->d.signed_and_enveloped->enc_data->enc_data;\n enc_alg = p7->d.signed_and_enveloped->enc_data->algorithm;\n evp_cipher = EVP_get_cipherbyobj(enc_alg->algorithm);\n if (evp_cipher == NULL) {\n PKCS7err(PKCS7_F_PKCS7_DATADECODE,\n PKCS7_R_UNSUPPORTED_CIPHER_TYPE);\n goto err;\n }\n break;\n case NID_pkcs7_enveloped:\n rsk = p7->d.enveloped->recipientinfo;\n enc_alg = p7->d.enveloped->enc_data->algorithm;\n /* data_body is NULL if the optional EncryptedContent is missing. */\n data_body = p7->d.enveloped->enc_data->enc_data;\n evp_cipher = EVP_get_cipherbyobj(enc_alg->algorithm);\n if (evp_cipher == NULL) {\n PKCS7err(PKCS7_F_PKCS7_DATADECODE,\n PKCS7_R_UNSUPPORTED_CIPHER_TYPE);\n goto err;\n }\n break;\n default:\n PKCS7err(PKCS7_F_PKCS7_DATADECODE, PKCS7_R_UNSUPPORTED_CONTENT_TYPE);\n goto err;\n }\n\n /* Detached content must be supplied via in_bio instead. */\n if (data_body == NULL && in_bio == NULL) {\n PKCS7err(PKCS7_F_PKCS7_DATADECODE, PKCS7_R_NO_CONTENT);\n goto err;\n }\n\n /* We will be checking the signature */\n if (md_sk != NULL) {\n for (i = 0; i < sk_X509_ALGOR_num(md_sk); i++) {\n xa = sk_X509_ALGOR_value(md_sk, i);\n if ((btmp = BIO_new(BIO_f_md())) == NULL) {\n PKCS7err(PKCS7_F_PKCS7_DATADECODE, ERR_R_BIO_LIB);\n goto err;\n }\n\n j = OBJ_obj2nid(xa->algorithm);\n evp_md = EVP_get_digestbynid(j);\n if (evp_md == NULL) {\n PKCS7err(PKCS7_F_PKCS7_DATADECODE,\n PKCS7_R_UNKNOWN_DIGEST_TYPE);\n goto err;\n }\n\n BIO_set_md(btmp, evp_md);\n if (out == NULL)\n out = btmp;\n else\n BIO_push(out, btmp);\n btmp = NULL;\n }\n }\n\n if (evp_cipher != NULL) {\n#if 0\n unsigned char key[EVP_MAX_KEY_LENGTH];\n unsigned char iv[EVP_MAX_IV_LENGTH];\n unsigned char *p;\n int keylen, ivlen;\n int max;\n X509_OBJECT ret;\n#endif\n\n if ((etmp = BIO_new(BIO_f_cipher())) == NULL) {\n PKCS7err(PKCS7_F_PKCS7_DATADECODE, ERR_R_BIO_LIB);\n goto err;\n }\n\n /*\n * It was encrypted, we need to decrypt the secret key with the\n * private key\n */\n\n /*\n * Find the recipientInfo which matches the passed certificate (if\n * any)\n */\n\n if (pcert) {\n for (i = 0; i < sk_PKCS7_RECIP_INFO_num(rsk); i++) {\n ri = sk_PKCS7_RECIP_INFO_value(rsk, i);\n if (!pkcs7_cmp_ri(ri, pcert))\n break;\n ri = NULL;\n }\n if (ri == NULL) {\n PKCS7err(PKCS7_F_PKCS7_DATADECODE,\n PKCS7_R_NO_RECIPIENT_MATCHES_CERTIFICATE);\n goto err;\n }\n }\n\n /* If we haven't got a certificate try each ri in turn */\n if (pcert == NULL) {\n /*\n * Always attempt to decrypt all rinfo even after sucess as a\n * defence against MMA timing attacks.\n */\n for (i = 0; i < sk_PKCS7_RECIP_INFO_num(rsk); i++) {\n ri = sk_PKCS7_RECIP_INFO_value(rsk, i);\n\n if (pkcs7_decrypt_rinfo(&ek, &eklen, ri, pkey) < 0)\n goto err;\n ERR_clear_error();\n }\n } else {\n /* Only exit on fatal errors, not decrypt failure */\n if (pkcs7_decrypt_rinfo(&ek, &eklen, ri, pkey) < 0)\n goto err;\n ERR_clear_error();\n }\n\n evp_ctx = NULL;\n BIO_get_cipher_ctx(etmp, &evp_ctx);\n if (EVP_CipherInit_ex(evp_ctx, evp_cipher, NULL, NULL, NULL, 0) <= 0)\n goto err;\n if (EVP_CIPHER_asn1_to_param(evp_ctx, enc_alg->parameter) < 0)\n goto err;\n /* Generate random key as MMA defence */\n tkeylen = EVP_CIPHER_CTX_key_length(evp_ctx);\n tkey = OPENSSL_malloc(tkeylen);\n if (!tkey)\n goto err;\n if (EVP_CIPHER_CTX_rand_key(evp_ctx, tkey) <= 0)\n goto err;\n if (ek == NULL) {\n ek = tkey;\n eklen = tkeylen;\n tkey = NULL;\n }\n\n if (eklen != EVP_CIPHER_CTX_key_length(evp_ctx)) {\n /*\n * Some S/MIME clients don't use the same key and effective key\n * length. The key length is determined by the size of the\n * decrypted RSA key.\n */\n if (!EVP_CIPHER_CTX_set_key_length(evp_ctx, eklen)) {\n /* Use random key as MMA defence */\n OPENSSL_cleanse(ek, eklen);\n OPENSSL_free(ek);\n ek = tkey;\n eklen = tkeylen;\n tkey = NULL;\n }\n }\n /* Clear errors so we don't leak information useful in MMA */\n ERR_clear_error();\n if (EVP_CipherInit_ex(evp_ctx, NULL, NULL, ek, NULL, 0) <= 0)\n goto err;\n\n if (ek) {\n OPENSSL_cleanse(ek, eklen);\n OPENSSL_free(ek);\n ek = NULL;\n }\n if (tkey) {\n OPENSSL_cleanse(tkey, tkeylen);\n OPENSSL_free(tkey);\n tkey = NULL;\n }\n\n if (out == NULL)\n out = etmp;\n else\n BIO_push(out, etmp);\n etmp = NULL;\n }\n#if 1\n if (in_bio != NULL) {\n bio = in_bio;\n } else {\n# if 0\n bio = BIO_new(BIO_s_mem());\n if (bio == NULL)\n goto err;\n /*\n * We need to set this so that when we have read all the data, the\n * encrypt BIO, if present, will read EOF and encode the last few\n * bytes\n */\n BIO_set_mem_eof_return(bio, 0);\n\n if (data_body->length > 0)\n BIO_write(bio, (char *)data_body->data, data_body->length);\n# else\n if (data_body->length > 0)\n bio = BIO_new_mem_buf(data_body->data, data_body->length);\n else {\n bio = BIO_new(BIO_s_mem());\n if (bio == NULL)\n goto err;\n BIO_set_mem_eof_return(bio, 0);\n }\n if (bio == NULL)\n goto err;\n# endif\n }\n BIO_push(out, bio);\n bio = NULL;\n#endif\n if (0) {\n err:\n if (ek) {\n OPENSSL_cleanse(ek, eklen);\n OPENSSL_free(ek);\n }\n if (tkey) {\n OPENSSL_cleanse(tkey, tkeylen);\n OPENSSL_free(tkey);\n }\n if (out != NULL)\n BIO_free_all(out);\n if (btmp != NULL)\n BIO_free_all(btmp);\n if (etmp != NULL)\n BIO_free_all(etmp);\n if (bio != NULL)\n BIO_free_all(bio);\n out = NULL;\n }\n return (out);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-327'], 'message': 'Fix a padding oracle in PKCS7_dataDecode and CMS_decrypt_set1_pkey\n\nAn attack is simple, if the first CMS_recipientInfo is valid but the\nsecond CMS_recipientInfo is chosen ciphertext. If the second\nrecipientInfo decodes to PKCS #1 v1.5 form plaintext, the correct\nencryption key will be replaced by garbage, and the message cannot be\ndecoded, but if the RSA decryption fails, the correct encryption key is\nused and the recipient will not notice the attack.\n\nAs a work around for this potential attack the length of the decrypted\nkey must be equal to the cipher default key length, in case the\ncertifiate is not given and all recipientInfo are tried out.\n\nThe old behaviour can be re-enabled in the CMS code by setting the\nCMS_DEBUG_DECRYPT flag.\n\nReviewed-by: Matt Caswell \n(Merged from https://github.com/openssl/openssl/pull/9777)\n\n(cherry picked from commit 5840ed0cd1e6487d247efbc1a04136a41d7b3a37)'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: main (int argc, char **argv)\n{\n g_test_init (&argc, &argv, NULL);\n\n g_test_add_func (\"/errors/non_svg_element\", test_non_svg_element);\n\n g_test_add_data_func_full (\"/errors/instancing_limit/323-nested-use.svg\",\n \"323-nested-use.svg\",\n test_instancing_limit,\n NULL);\n\n g_test_add_data_func_full (\"/errors/instancing_limit/515-pattern-billion-laughs.svg\",\n \"515-pattern-billion-laughs.svg\",\n test_instancing_limit,\n NULL);\n\n\n return g_test_run ();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-400'], 'message': '(#515) - Add a limit for the number of loaded elements\n\nThis fixes the last part of #515, an enormous SVG file with millions\nof elements, which causes out-of-memory.\n\nTo avoid unbounded memory consumption, we'll set a hard limit on the\nnumber of loaded elements. The largest legitimate file I have is a\nmap rendering with about 26K elements; here we set a limit of 200,000\nelements for good measure.\n\nFixes https://gitlab.gnome.org/GNOME/librsvg/issues/515'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: TEST_P(WasmTest, StatsHighLevel) {\n Stats::IsolatedStoreImpl stats_store;\n Api::ApiPtr api = Api::createApiForTest(stats_store);\n Upstream::MockClusterManager cluster_manager;\n Event::DispatcherPtr dispatcher(api->allocateDispatcher());\n auto scope = Stats::ScopeSharedPtr(stats_store.createScope(\"wasm.\"));\n NiceMock local_info;\n auto name = \"\";\n auto root_id = \"\";\n auto vm_id = \"\";\n auto vm_configuration = \"\";\n auto plugin = std::make_shared(\n name, root_id, vm_id, envoy::api::v2::core::TrafficDirection::UNSPECIFIED, local_info,\n nullptr);\n auto wasm = std::make_unique(\n absl::StrCat(\"envoy.wasm.runtime.\", GetParam()), vm_id, vm_configuration, plugin, scope,\n cluster_manager, *dispatcher);\n EXPECT_NE(wasm, nullptr);\n const auto code = TestEnvironment::readFileToStringForTest(TestEnvironment::substitute(\n \"{{ test_rundir }}/test/extensions/wasm/test_data/stats_cpp.wasm\"));\n EXPECT_FALSE(code.empty());\n auto context = std::make_unique(wasm.get());\n\n EXPECT_CALL(*context, scriptLog_(spdlog::level::trace, Eq(\"get counter = 1\")));\n EXPECT_CALL(*context, scriptLog_(spdlog::level::debug, Eq(\"get counter = 2\")));\n // recordMetric on a Counter is the same as increment.\n EXPECT_CALL(*context, scriptLog_(spdlog::level::info, Eq(\"get counter = 5\")));\n EXPECT_CALL(*context, scriptLog_(spdlog::level::warn, Eq(\"get gauge = 2\")));\n // Get is not supported on histograms.\n // EXPECT_CALL(*context, scriptLog(spdlog::level::err, Eq(std::string(\"resolved histogram name\n // = int_tag.7_string_tag.test_tag.bool_tag.true.test_histogram\"))));\n EXPECT_CALL(*context,\n scriptLog_(spdlog::level::err,\n Eq(\"h_id = int_tag.7.string_tag.test_tag.bool_tag.true.test_histogram\")));\n EXPECT_CALL(*context, scriptLog_(spdlog::level::err, Eq(\"stack_c = 1\")));\n EXPECT_CALL(*context, scriptLog_(spdlog::level::err, Eq(\"stack_g = 2\")));\n // Get is not supported on histograms.\n // EXPECT_CALL(*context, scriptLog_(spdlog::level::err, Eq(\"stack_h = 3\")));\n EXPECT_TRUE(wasm->initialize(code, false));\n wasm->setContext(context.get());\n context->onLog();\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': '1.4 - Do not call into the VM unless the VM Context has been created. (#24)\n\n* Ensure that the in VM Context is created before onDone is called.\n\nSigned-off-by: John Plevyak \n\n* Update as per offline discussion.\n\nSigned-off-by: John Plevyak \n\n* Set in_vm_context_created_ in onNetworkNewConnection.\n\nSigned-off-by: John Plevyak \n\n* Add guards to other network calls.\n\nSigned-off-by: John Plevyak \n\n* Fix common/wasm tests.\n\nSigned-off-by: John Plevyak \n\n* Patch tests.\n\nSigned-off-by: John Plevyak \n\n* Remove unecessary file from cherry-pick.\n\nSigned-off-by: John Plevyak '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void Context::onUpstreamConnectionClose(PeerType peer_type) {\n if (wasm_->onUpstreamConnectionClose_) {\n wasm_->onUpstreamConnectionClose_(this, id_, static_cast(peer_type));\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': '1.4 - Do not call into the VM unless the VM Context has been created. (#24)\n\n* Ensure that the in VM Context is created before onDone is called.\n\nSigned-off-by: John Plevyak \n\n* Update as per offline discussion.\n\nSigned-off-by: John Plevyak \n\n* Set in_vm_context_created_ in onNetworkNewConnection.\n\nSigned-off-by: John Plevyak \n\n* Add guards to other network calls.\n\nSigned-off-by: John Plevyak \n\n* Fix common/wasm tests.\n\nSigned-off-by: John Plevyak \n\n* Patch tests.\n\nSigned-off-by: John Plevyak \n\n* Remove unecessary file from cherry-pick.\n\nSigned-off-by: John Plevyak '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: napi_value Init(napi_env env, napi_value exports) {\n napi_property_descriptor properties[] = {\n DECLARE_NAPI_PROPERTY(\"TestLatin1\", TestLatin1),\n DECLARE_NAPI_PROPERTY(\"TestLatin1Insufficient\", TestLatin1Insufficient),\n DECLARE_NAPI_PROPERTY(\"TestUtf8\", TestUtf8),\n DECLARE_NAPI_PROPERTY(\"TestUtf8Insufficient\", TestUtf8Insufficient),\n DECLARE_NAPI_PROPERTY(\"TestUtf16\", TestUtf16),\n DECLARE_NAPI_PROPERTY(\"TestUtf16Insufficient\", TestUtf16Insufficient),\n DECLARE_NAPI_PROPERTY(\"Utf16Length\", Utf16Length),\n DECLARE_NAPI_PROPERTY(\"Utf8Length\", Utf8Length),\n DECLARE_NAPI_PROPERTY(\"TestLargeUtf8\", TestLargeUtf8),\n DECLARE_NAPI_PROPERTY(\"TestLargeLatin1\", TestLargeLatin1),\n DECLARE_NAPI_PROPERTY(\"TestLargeUtf16\", TestLargeUtf16),\n };\n\n NAPI_CALL(env, napi_define_properties(\n env, exports, sizeof(properties) / sizeof(*properties), properties));\n\n return exports;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-191'], 'message': 'napi: fix memory corruption vulnerability\n\nFixes: https://hackerone.com/reports/784186\nCVE-ID: CVE-2020-8174\nPR-URL: https://github.com/nodejs-private/node-private/pull/195\nReviewed-By: Anna Henningsen \nReviewed-By: Gabriel Schulhof \nReviewed-By: Michael Dawson \nReviewed-By: Colin Ihrig \nReviewed-By: Rich Trott '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int TLSWrap::DoWrite(WriteWrap* w,\n uv_buf_t* bufs,\n size_t count,\n uv_stream_t* send_handle) {\n CHECK_NULL(send_handle);\n Debug(this, \"DoWrite()\");\n\n if (ssl_ == nullptr) {\n ClearError();\n error_ = \"Write after DestroySSL\";\n return UV_EPROTO;\n }\n\n size_t length = 0;\n size_t i;\n for (i = 0; i < count; i++)\n length += bufs[i].len;\n\n // We want to trigger a Write() on the underlying stream to drive the stream\n // system, but don't want to encrypt empty buffers into a TLS frame, so see\n // if we can find something to Write().\n // First, call ClearOut(). It does an SSL_read(), which might cause handshake\n // or other internal messages to be encrypted. If it does, write them later\n // with EncOut().\n // If there is still no encrypted output, call Write(bufs) on the underlying\n // stream. Since the bufs are empty, it won't actually write non-TLS data\n // onto the socket, we just want the side-effects. After, make sure the\n // WriteWrap was accepted by the stream, or that we call Done() on it.\n if (length == 0) {\n Debug(this, \"Empty write\");\n ClearOut();\n if (BIO_pending(enc_out_) == 0) {\n Debug(this, \"No pending encrypted output, writing to underlying stream\");\n CHECK_NULL(current_empty_write_);\n current_empty_write_ = w;\n StreamWriteResult res =\n underlying_stream()->Write(bufs, count, send_handle);\n if (!res.async) {\n env()->SetImmediate([](Environment* env, void* data) {\n TLSWrap* self = static_cast(data);\n self->OnStreamAfterWrite(self->current_empty_write_, 0);\n }, this, object());\n }\n return 0;\n }\n }\n\n // Store the current write wrap\n CHECK_NULL(current_write_);\n current_write_ = w;\n\n // Write encrypted data to underlying stream and call Done().\n if (length == 0) {\n EncOut();\n return 0;\n }\n\n std::vector data;\n crypto::MarkPopErrorOnReturn mark_pop_error_on_return;\n\n int written = 0;\n if (count != 1) {\n data = std::vector(length);\n size_t offset = 0;\n for (i = 0; i < count; i++) {\n memcpy(data.data() + offset, bufs[i].base, bufs[i].len);\n offset += bufs[i].len;\n }\n written = SSL_write(ssl_.get(), data.data(), length);\n } else {\n // Only one buffer: try to write directly, only store if it fails\n written = SSL_write(ssl_.get(), bufs[0].base, bufs[0].len);\n if (written == -1) {\n data = std::vector(length);\n memcpy(data.data(), bufs[0].base, bufs[0].len);\n }\n }\n\n CHECK(written == -1 || written == static_cast(length));\n Debug(this, \"Writing %zu bytes, written = %d\", length, written);\n\n if (written == -1) {\n int err;\n Local arg = GetSSLError(written, &err, &error_);\n\n // If we stopped writing because of an error, it's fatal, discard the data.\n if (!arg.IsEmpty()) {\n Debug(this, \"Got SSL error (%d), returning UV_EPROTO\", err);\n current_write_ = nullptr;\n return UV_EPROTO;\n }\n\n Debug(this, \"Saving data for later write\");\n // Otherwise, save unwritten data so it can be written later by ClearIn().\n CHECK_EQ(pending_cleartext_input_.size(), 0);\n pending_cleartext_input_ = std::move(data);\n }\n\n // Write any encrypted/handshake output that may be ready.\n EncOut();\n\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'src: use unique_ptr for WriteWrap\n\nThis commit attempts to avoid a use-after-free error by using unqiue_ptr\nand passing a reference to it.\n\nCVE-ID: CVE-2020-8265\nFixes: https://github.com/nodejs-private/node-private/issues/227\nPR-URL: https://github.com/nodejs-private/node-private/pull/238\nReviewed-By: Michael Dawson \nReviewed-By: Tobias Nie\u00dfen \nReviewed-By: Richard Lau '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,\n const unsigned char *in, int inl)\n{\n int fix_len, cmpl = inl;\n unsigned int b;\n\n /* Prevent accidental use of encryption context when decrypting */\n if (ctx->encrypt) {\n EVPerr(EVP_F_EVP_DECRYPTUPDATE, EVP_R_INVALID_OPERATION);\n return 0;\n }\n\n b = ctx->cipher->block_size;\n\n if (EVP_CIPHER_CTX_test_flags(ctx, EVP_CIPH_FLAG_LENGTH_BITS))\n cmpl = (cmpl + 7) / 8;\n\n /*\n * CCM mode needs to know about the case where inl == 0 - it means the\n * plaintext/ciphertext length is 0\n */\n if (inl < 0\n || (inl == 0\n && EVP_CIPHER_mode(ctx->cipher) != EVP_CIPH_CCM_MODE)) {\n *outl = 0;\n return inl == 0;\n }\n\n if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {\n if (b == 1 && is_partially_overlapping(out, in, cmpl)) {\n EVPerr(EVP_F_EVP_DECRYPTUPDATE, EVP_R_PARTIALLY_OVERLAPPING);\n return 0;\n }\n\n fix_len = ctx->cipher->do_cipher(ctx, out, in, inl);\n if (fix_len < 0) {\n *outl = 0;\n return 0;\n } else\n *outl = fix_len;\n return 1;\n }\n\n if (ctx->flags & EVP_CIPH_NO_PADDING)\n return evp_EncryptDecryptUpdate(ctx, out, outl, in, inl);\n\n OPENSSL_assert(b <= sizeof(ctx->final));\n\n if (ctx->final_used) {\n /* see comment about PTRDIFF_T comparison above */\n if (((PTRDIFF_T)out == (PTRDIFF_T)in)\n || is_partially_overlapping(out, in, b)) {\n EVPerr(EVP_F_EVP_DECRYPTUPDATE, EVP_R_PARTIALLY_OVERLAPPING);\n return 0;\n }\n memcpy(out, ctx->final, b);\n out += b;\n fix_len = 1;\n } else\n fix_len = 0;\n\n if (!evp_EncryptDecryptUpdate(ctx, out, outl, in, inl))\n return 0;\n\n /*\n * if we have 'decrypted' a multiple of block size, make sure we have a\n * copy of this last block\n */\n if (b > 1 && !ctx->buf_len) {\n *outl -= b;\n ctx->final_used = 1;\n memcpy(ctx->final, &out[*outl], b);\n } else\n ctx->final_used = 0;\n\n if (fix_len)\n *outl += b;\n\n return 1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-190'], 'message': 'Don't overflow the output length in EVP_CipherUpdate calls\n\nCVE-2021-23840\n\nReviewed-by: Paul Dale '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void fdctrl_start_transfer(FDCtrl *fdctrl, int direction)\n{\n FDrive *cur_drv;\n uint8_t kh, kt, ks;\n\n SET_CUR_DRV(fdctrl, fdctrl->fifo[1] & FD_DOR_SELMASK);\n cur_drv = get_cur_drv(fdctrl);\n kt = fdctrl->fifo[2];\n kh = fdctrl->fifo[3];\n ks = fdctrl->fifo[4];\n FLOPPY_DPRINTF(\"Start transfer at %d %d %02x %02x (%d)\\n\",\n GET_CUR_DRV(fdctrl), kh, kt, ks,\n fd_sector_calc(kh, kt, ks, cur_drv->last_sect,\n NUM_SIDES(cur_drv)));\n switch (fd_seek(cur_drv, kh, kt, ks, fdctrl->config & FD_CONFIG_EIS)) {\n case 2:\n /* sect too big */\n fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, 0x00, 0x00);\n fdctrl->fifo[3] = kt;\n fdctrl->fifo[4] = kh;\n fdctrl->fifo[5] = ks;\n return;\n case 3:\n /* track too big */\n fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, FD_SR1_EC, 0x00);\n fdctrl->fifo[3] = kt;\n fdctrl->fifo[4] = kh;\n fdctrl->fifo[5] = ks;\n return;\n case 4:\n /* No seek enabled */\n fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, 0x00, 0x00);\n fdctrl->fifo[3] = kt;\n fdctrl->fifo[4] = kh;\n fdctrl->fifo[5] = ks;\n return;\n case 1:\n fdctrl->status0 |= FD_SR0_SEEK;\n break;\n default:\n break;\n }\n\n /* Check the data rate. If the programmed data rate does not match\n * the currently inserted medium, the operation has to fail. */\n if ((fdctrl->dsr & FD_DSR_DRATEMASK) != cur_drv->media_rate) {\n FLOPPY_DPRINTF(\"data rate mismatch (fdc=%d, media=%d)\\n\",\n fdctrl->dsr & FD_DSR_DRATEMASK, cur_drv->media_rate);\n fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, FD_SR1_MA, 0x00);\n fdctrl->fifo[3] = kt;\n fdctrl->fifo[4] = kh;\n fdctrl->fifo[5] = ks;\n return;\n }\n\n /* Set the FIFO state */\n fdctrl->data_dir = direction;\n fdctrl->data_pos = 0;\n assert(fdctrl->msr & FD_MSR_CMDBUSY);\n if (fdctrl->fifo[0] & 0x80)\n fdctrl->data_state |= FD_STATE_MULTI;\n else\n fdctrl->data_state &= ~FD_STATE_MULTI;\n if (fdctrl->fifo[5] == 0) {\n fdctrl->data_len = fdctrl->fifo[8];\n } else {\n int tmp;\n fdctrl->data_len = 128 << (fdctrl->fifo[5] > 7 ? 7 : fdctrl->fifo[5]);\n tmp = (fdctrl->fifo[6] - ks + 1);\n if (fdctrl->fifo[0] & 0x80)\n tmp += fdctrl->fifo[6];\n fdctrl->data_len *= tmp;\n }\n fdctrl->eot = fdctrl->fifo[6];\n if (fdctrl->dor & FD_DOR_DMAEN) {\n /* DMA transfer is enabled. */\n IsaDmaClass *k = ISADMA_GET_CLASS(fdctrl->dma);\n\n FLOPPY_DPRINTF(\"direction=%d (%d - %d)\\n\",\n direction, (128 << fdctrl->fifo[5]) *\n (cur_drv->last_sect - ks + 1), fdctrl->data_len);\n\n /* No access is allowed until DMA transfer has completed */\n fdctrl->msr &= ~FD_MSR_RQM;\n if (direction != FD_DIR_VERIFY) {\n /*\n * Now, we just have to wait for the DMA controller to\n * recall us...\n */\n k->hold_DREQ(fdctrl->dma, fdctrl->dma_chann);\n k->schedule(fdctrl->dma);\n } else {\n /* Start transfer */\n fdctrl_transfer_handler(fdctrl, fdctrl->dma_chann, 0,\n fdctrl->data_len);\n }\n return;\n }\n FLOPPY_DPRINTF(\"start non-DMA transfer\\n\");\n fdctrl->msr |= FD_MSR_NONDMA | FD_MSR_RQM;\n if (direction != FD_DIR_WRITE)\n fdctrl->msr |= FD_MSR_DIO;\n /* IO based transfer: calculate len */\n fdctrl_raise_irq(fdctrl);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'hw/block/fdc: Prevent end-of-track overrun (CVE-2021-3507)\n\nPer the 82078 datasheet, if the end-of-track (EOT byte in\nthe FIFO) is more than the number of sectors per side, the\ncommand is terminated unsuccessfully:\n\n* 5.2.5 DATA TRANSFER TERMINATION\n\n The 82078 supports terminal count explicitly through\n the TC pin and implicitly through the underrun/over-\n run and end-of-track (EOT) functions. For full sector\n transfers, the EOT parameter can define the last\n sector to be transferred in a single or multisector\n transfer. If the last sector to be transferred is a par-\n tial sector, the host can stop transferring the data in\n mid-sector, and the 82078 will continue to complete\n the sector as if a hardware TC was received. The\n only difference between these implicit functions and\n TC is that they return \"abnormal termination\" result\n status. Such status indications can be ignored if they\n were expected.\n\n* 6.1.3 READ TRACK\n\n This command terminates when the EOT specified\n number of sectors have been read. If the 82078\n does not find an I D Address Mark on the diskette\n after the second\u00b7 occurrence of a pulse on the\n INDX# pin, then it sets the IC code in Status Regis-\n ter 0 to \"01\" (Abnormal termination), sets the MA bit\n in Status Register 1 to \"1\", and terminates the com-\n mand.\n\n* 6.1.6 VERIFY\n\n Refer to Table 6-6 and Table 6-7 for information\n concerning the values of MT and EC versus SC and\n EOT value.\n\n* Table 6\u00b76. Result Phase Table\n\n* Table 6-7. Verify Command Result Phase Table\n\nFix by aborting the transfer when EOT > # Sectors Per Side.\n\nCc: qemu-stable@nongnu.org\nCc: Herv\u00e9 Poussineau \nFixes: baca51faff0 (\"floppy driver: disk geometry auto detect\")\nReported-by: Alexander Bulekov \nResolves: https://gitlab.com/qemu-project/qemu/-/issues/339\nSigned-off-by: Philippe Mathieu-Daud\u00e9 \nMessage-Id: <20211118115733.4038610-2-philmd@redhat.com>\nReviewed-by: Hanna Reitz \nSigned-off-by: Kevin Wolf '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void save_key_to(const char *algo, const char *name, const char *keydata)\n{\n\tconst char *error;\n\tstruct dict_transaction_context *ctx =\n\t\tdict_transaction_begin(keys_dict);\n\n\tdict_set(ctx, t_strconcat(DICT_PATH_SHARED, \"default/\", algo, \"/\",\n\t\t\t\t name, NULL),\n\t\t keydata);\n\tif (dict_transaction_commit(&ctx, &error) < 0)\n\t\ti_error(\"dict_set(%s) failed: %s\", name, error);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-22'], 'message': 'lib-oauth2: Add test for token escape'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int pkey_sm2_decrypt(EVP_PKEY_CTX *ctx,\n unsigned char *out, size_t *outlen,\n const unsigned char *in, size_t inlen)\n{\n EC_KEY *ec = ctx->pkey->pkey.ec;\n SM2_PKEY_CTX *dctx = ctx->data;\n const EVP_MD *md = (dctx->md == NULL) ? EVP_sm3() : dctx->md;\n\n if (out == NULL) {\n if (!sm2_plaintext_size(ec, md, inlen, outlen))\n return -1;\n else\n return 1;\n }\n\n return sm2_decrypt(ec, md, in, inlen, out, outlen);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'Correctly calculate the length of SM2 plaintext given the ciphertext\n\nPreviously the length of the SM2 plaintext could be incorrectly calculated.\nThe plaintext length was calculated by taking the ciphertext length and\ntaking off an \"overhead\" value.\n\nThe overhead value was assumed to have a \"fixed\" element of 10 bytes.\nThis is incorrect since in some circumstances it can be more than 10 bytes.\nAdditionally the overhead included the length of two integers C1x and C1y,\nwhich were assumed to be the same length as the field size (32 bytes for\nthe SM2 curve). However in some cases these integers can have an additional\npadding byte when the msb is set, to disambiguate them from negative\nintegers. Additionally the integers can also be less than 32 bytes in\nlength in some cases.\n\nIf the calculated overhead is incorrect and larger than the actual value\nthis can result in the calculated plaintext length being too small.\nApplications are likely to allocate buffer sizes based on this and therefore\na buffer overrun can occur.\n\nCVE-2021-3711\n\nIssue reported by John Ouyang.\n\nReviewed-by: Paul Dale \nReviewed-by: Nicola Tuveri '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int nc_dns(ASN1_IA5STRING *dns, ASN1_IA5STRING *base)\n{\n char *baseptr = (char *)base->data;\n char *dnsptr = (char *)dns->data;\n /* Empty matches everything */\n if (!*baseptr)\n return X509_V_OK;\n /*\n * Otherwise can add zero or more components on the left so compare RHS\n * and if dns is longer and expect '.' as preceding character.\n */\n if (dns->length > base->length) {\n dnsptr += dns->length - base->length;\n if (*baseptr != '.' && dnsptr[-1] != '.')\n return X509_V_ERR_PERMITTED_VIOLATION;\n }\n\n if (ia5casecmp(baseptr, dnsptr))\n return X509_V_ERR_PERMITTED_VIOLATION;\n\n return X509_V_OK;\n\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-125'], 'message': 'Fix the name constraints code to not assume NUL terminated strings\n\nASN.1 strings may not be NUL terminated. Don't assume they are.\n\nCVE-2021-3712\n\nReviewed-by: Viktor Dukhovni \nReviewed-by: Paul Dale '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: WORK_STATE tls_post_process_server_certificate(SSL *s, WORK_STATE wst)\n{\n X509 *x;\n EVP_PKEY *pkey = NULL;\n const SSL_CERT_LOOKUP *clu;\n size_t certidx;\n int i;\n\n i = ssl_verify_cert_chain(s, s->session->peer_chain);\n if (i == -1) {\n s->rwstate = SSL_RETRY_VERIFY;\n return WORK_MORE_A;\n }\n /*\n * The documented interface is that SSL_VERIFY_PEER should be set in order\n * for client side verification of the server certificate to take place.\n * However, historically the code has only checked that *any* flag is set\n * to cause server verification to take place. Use of the other flags makes\n * no sense in client mode. An attempt to clean up the semantics was\n * reverted because at least one application *only* set\n * SSL_VERIFY_FAIL_IF_NO_PEER_CERT. Prior to the clean up this still caused\n * server verification to take place, after the clean up it silently did\n * nothing. SSL_CTX_set_verify()/SSL_set_verify() cannot validate the flags\n * sent to them because they are void functions. Therefore, we now use the\n * (less clean) historic behaviour of performing validation if any flag is\n * set. The *documented* interface remains the same.\n */\n if (s->verify_mode != SSL_VERIFY_NONE && i <= 0) {\n SSLfatal(s, ssl_x509err2alert(s->verify_result),\n SSL_R_CERTIFICATE_VERIFY_FAILED);\n return WORK_ERROR;\n }\n ERR_clear_error(); /* but we keep s->verify_result */\n\n /*\n * Inconsistency alert: cert_chain does include the peer's certificate,\n * which we don't include in statem_srvr.c\n */\n x = sk_X509_value(s->session->peer_chain, 0);\n\n pkey = X509_get0_pubkey(x);\n\n if (pkey == NULL || EVP_PKEY_missing_parameters(pkey)) {\n SSLfatal(s, SSL_AD_INTERNAL_ERROR,\n SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);\n return WORK_ERROR;\n }\n\n if ((clu = ssl_cert_lookup_by_pkey(pkey, &certidx)) == NULL) {\n SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_CERTIFICATE_TYPE);\n return WORK_ERROR;\n }\n /*\n * Check certificate type is consistent with ciphersuite. For TLS 1.3\n * skip check since TLS 1.3 ciphersuites can be used with any certificate\n * type.\n */\n if (!SSL_IS_TLS13(s)) {\n if ((clu->amask & s->s3.tmp.new_cipher->algorithm_auth) == 0) {\n SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_CERTIFICATE_TYPE);\n return WORK_ERROR;\n }\n }\n\n X509_free(s->session->peer);\n X509_up_ref(x);\n s->session->peer = x;\n s->session->verify_result = s->verify_result;\n\n /* Save the current hash state for when we receive the CertificateVerify */\n if (SSL_IS_TLS13(s)\n && !ssl_handshake_hash(s, s->cert_verify_hash,\n sizeof(s->cert_verify_hash),\n &s->cert_verify_hash_len)) {\n /* SSLfatal() already called */;\n return WORK_ERROR;\n }\n return WORK_FINISHED_CONTINUE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-835'], 'message': 'Fix invalid handling of verify errors in libssl\n\nIn the event that X509_verify() returned an internal error result then\nlibssl would mishandle this and set rwstate to SSL_RETRY_VERIFY. This\nsubsequently causes SSL_get_error() to return SSL_ERROR_WANT_RETRY_VERIFY.\nThat return code is supposed to only ever be returned if an application\nis using an app verify callback to complete replace the use of\nX509_verify(). Applications may not be written to expect that return code\nand could therefore crash (or misbehave in some other way) as a result.\n\nCVE-2021-4044\n\nReviewed-by: Tomas Mraz '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool SafeX509ExtPrint(const BIOPointer& out, X509_EXTENSION* ext) {\n const X509V3_EXT_METHOD* method = X509V3_EXT_get(ext);\n\n if (method != X509V3_EXT_get_nid(NID_subject_alt_name))\n return false;\n\n GENERAL_NAMES* names = static_cast(X509V3_EXT_d2i(ext));\n if (names == nullptr)\n return false;\n\n for (int i = 0; i < sk_GENERAL_NAME_num(names); i++) {\n GENERAL_NAME* gen = sk_GENERAL_NAME_value(names, i);\n\n if (i != 0)\n BIO_write(out.get(), \", \", 2);\n\n if (gen->type == GEN_DNS) {\n ASN1_IA5STRING* name = gen->d.dNSName;\n\n BIO_write(out.get(), \"DNS:\", 4);\n BIO_write(out.get(), name->data, name->length);\n } else {\n STACK_OF(CONF_VALUE)* nval = i2v_GENERAL_NAME(\n const_cast(method), gen, nullptr);\n if (nval == nullptr)\n return false;\n X509V3_EXT_val_prn(out.get(), nval, 0, 0);\n sk_CONF_VALUE_pop_free(nval, X509V3_conf_free);\n }\n }\n sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);\n\n return true;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-295'], 'message': 'crypto,tls: implement safe x509 GeneralName format\n\nThis change introduces JSON-compatible escaping rules for strings that\ninclude X.509 GeneralName components (see RFC 5280). This non-standard\nformat avoids ambiguities and prevents injection attacks that could\npreviously lead to X.509 certificates being accepted even though they\nwere not valid for the target hostname.\n\nThese changes affect the format of subject alternative names and the\nformat of authority information access. The checkServerIdentity function\nhas been modified to safely handle the new format, eliminating the\npossibility of injecting subject alternative names into the verification\nlogic.\n\nBecause each subject alternative name is only encoded as a JSON string\nliteral if necessary for security purposes, this change will only be\nvisible in rare cases.\n\nThis addresses CVE-2021-44532.\n\nCVE-ID: CVE-2021-44532\nPR-URL: https://github.com/nodejs-private/node-private/pull/300\nReviewed-By: Michael Dawson \nReviewed-By: Rich Trott '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool st_select_lex::optimize_unflattened_subqueries(bool const_only)\n{\n SELECT_LEX_UNIT *next_unit= NULL;\n for (SELECT_LEX_UNIT *un= first_inner_unit();\n un;\n un= next_unit ? next_unit : un->next_unit())\n {\n Item_subselect *subquery_predicate= un->item;\n next_unit= NULL;\n\n if (subquery_predicate)\n {\n if (!subquery_predicate->fixed)\n {\n\t/*\n\t This subquery was excluded as part of some expression so it is\n\t invisible from all prepared expression.\n */\n\tnext_unit= un->next_unit();\n\tun->exclude_level();\n\tif (next_unit)\n\t continue;\n\tbreak;\n }\n if (subquery_predicate->substype() == Item_subselect::IN_SUBS)\n {\n Item_in_subselect *in_subs= (Item_in_subselect*) subquery_predicate;\n if (in_subs->is_jtbm_merged)\n continue;\n }\n\n if (const_only && !subquery_predicate->const_item())\n {\n /* Skip non-constant subqueries if the caller asked so. */\n continue;\n }\n\n bool empty_union_result= true;\n bool is_correlated_unit= false;\n bool first= true;\n bool union_plan_saved= false;\n /*\n If the subquery is a UNION, optimize all the subqueries in the UNION. If\n there is no UNION, then the loop will execute once for the subquery.\n */\n for (SELECT_LEX *sl= un->first_select(); sl; sl= sl->next_select())\n {\n JOIN *inner_join= sl->join;\n if (first)\n first= false;\n else\n {\n if (!union_plan_saved)\n {\n union_plan_saved= true;\n if (un->save_union_explain(un->thd->lex->explain))\n return true; /* Failure */\n }\n }\n if (!inner_join)\n continue;\n SELECT_LEX *save_select= un->thd->lex->current_select;\n ulonglong save_options;\n int res;\n /* We need only 1 row to determine existence */\n un->set_limit(un->global_parameters());\n un->thd->lex->current_select= sl;\n save_options= inner_join->select_options;\n if (options & SELECT_DESCRIBE)\n {\n /* Optimize the subquery in the context of EXPLAIN. */\n sl->set_explain_type(FALSE);\n sl->options|= SELECT_DESCRIBE;\n inner_join->select_options|= SELECT_DESCRIBE;\n }\n if ((res= inner_join->optimize()))\n return TRUE;\n if (!inner_join->cleaned)\n sl->update_used_tables();\n sl->update_correlated_cache();\n is_correlated_unit|= sl->is_correlated;\n inner_join->select_options= save_options;\n un->thd->lex->current_select= save_select;\n\n Explain_query *eq;\n if ((eq= inner_join->thd->lex->explain))\n {\n Explain_select *expl_sel;\n if ((expl_sel= eq->get_select(inner_join->select_lex->select_number)))\n {\n sl->set_explain_type(TRUE);\n expl_sel->select_type= sl->type;\n }\n }\n\n if (empty_union_result)\n {\n /*\n If at least one subquery in a union is non-empty, the UNION result\n is non-empty. If there is no UNION, the only subquery is non-empy.\n */\n empty_union_result= inner_join->empty_result();\n }\n if (res)\n return TRUE;\n }\n if (empty_union_result)\n subquery_predicate->no_rows_in_result();\n if (!is_correlated_unit)\n un->uncacheable&= ~UNCACHEABLE_DEPENDENT;\n subquery_predicate->is_correlated= is_correlated_unit;\n }\n }\n return FALSE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-476'], 'message': 'MDEV-25636: Bug report: abortion in sql/sql_parse.cc:6294\n\nThe asserion failure was caused by this query\n\n select /*id=1*/ from t1\n where\n col= ( select /*id=2*/ from ... where corr_cond1\n union\n select /*id=4*/ from ... where corr_cond2)\n\nHere,\n- select with id=2 was correlated due to corr_cond1.\n- select with id=4 was initially correlated due to corr_cond2, but then\n the optimizer optimized away the correlation, making the select with id=4\n uncorrelated.\n\nHowever, since select with id=2 remained correlated, the execution had to\nre-compute the whole UNION. When it tried to execute select with id=4, it\nhit an assertion (join buffer already free'd).\n\nThis is because select with id=4 has freed its execution structures after\nit has been executed once. The select is uncorrelated, so it did not expect\nit would need to be executed for the second time.\n\nFixed this by adding this logic in\nst_select_lex::optimize_unflattened_subqueries():\n\n If a member of a UNION is correlated, mark all its members as\n correlated, so that they are prepared to be executed multiple times.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool lock_tables(THD *thd, TABLE_LIST *tables, uint count,\n uint flags)\n{\n TABLE_LIST *table;\n DBUG_ENTER(\"lock_tables\");\n /*\n We can't meet statement requiring prelocking if we already\n in prelocked mode.\n */\n DBUG_ASSERT(thd->locked_tables_mode <= LTM_LOCK_TABLES ||\n !thd->lex->requires_prelocking());\n\n if (!tables && !thd->lex->requires_prelocking())\n DBUG_RETURN(thd->decide_logging_format(tables));\n\n /*\n Check for thd->locked_tables_mode to avoid a redundant\n and harmful attempt to lock the already locked tables again.\n Checking for thd->lock is not enough in some situations. For example,\n if a stored function contains\n \"drop table t3; create temporary t3 ..; insert into t3 ...;\"\n thd->lock may be 0 after drop tables, whereas locked_tables_mode\n is still on. In this situation an attempt to lock temporary\n table t3 will lead to a memory leak.\n */\n if (! thd->locked_tables_mode)\n {\n DBUG_ASSERT(thd->lock == 0);\t// You must lock everything at once\n TABLE **start,**ptr;\n\n if (!(ptr=start=(TABLE**) thd->alloc(sizeof(TABLE*)*count)))\n DBUG_RETURN(TRUE);\n for (table= tables; table; table= table->next_global)\n {\n if (!table->placeholder())\n\t*(ptr++)= table->table;\n }\n\n DEBUG_SYNC(thd, \"before_lock_tables_takes_lock\");\n\n if (! (thd->lock= mysql_lock_tables(thd, start, (uint) (ptr - start),\n flags)))\n DBUG_RETURN(TRUE);\n\n DEBUG_SYNC(thd, \"after_lock_tables_takes_lock\");\n\n if (thd->lex->requires_prelocking() &&\n thd->lex->sql_command != SQLCOM_LOCK_TABLES)\n {\n TABLE_LIST *first_not_own= thd->lex->first_not_own_table();\n /*\n We just have done implicit LOCK TABLES, and now we have\n to emulate first open_and_lock_tables() after it.\n\n When open_and_lock_tables() is called for a single table out of\n a table list, the 'next_global' chain is temporarily broken. We\n may not find 'first_not_own' before the end of the \"list\".\n Look for example at those places where open_n_lock_single_table()\n is called. That function implements the temporary breaking of\n a table list for opening a single table.\n */\n for (table= tables;\n table && table != first_not_own;\n table= table->next_global)\n {\n if (!table->placeholder())\n {\n table->table->query_id= thd->query_id;\n if (check_lock_and_start_stmt(thd, thd->lex, table))\n {\n mysql_unlock_tables(thd, thd->lock);\n thd->lock= 0;\n DBUG_RETURN(TRUE);\n }\n }\n }\n /*\n Let us mark all tables which don't belong to the statement itself,\n and was marked as occupied during open_tables() as free for reuse.\n */\n mark_real_tables_as_free_for_reuse(first_not_own);\n DBUG_PRINT(\"info\",(\"locked_tables_mode= LTM_PRELOCKED\"));\n thd->enter_locked_tables_mode(LTM_PRELOCKED);\n }\n }\n else\n {\n TABLE_LIST *first_not_own= thd->lex->first_not_own_table();\n /*\n When open_and_lock_tables() is called for a single table out of\n a table list, the 'next_global' chain is temporarily broken. We\n may not find 'first_not_own' before the end of the \"list\".\n Look for example at those places where open_n_lock_single_table()\n is called. That function implements the temporary breaking of\n a table list for opening a single table.\n */\n for (table= tables;\n table && table != first_not_own;\n table= table->next_global)\n {\n if (table->placeholder())\n continue;\n\n /*\n In a stored function or trigger we should ensure that we won't change\n a table that is already used by the calling statement.\n */\n if (thd->locked_tables_mode >= LTM_PRELOCKED &&\n table->lock_type >= TL_WRITE_ALLOW_WRITE)\n {\n for (TABLE* opentab= thd->open_tables; opentab; opentab= opentab->next)\n {\n if (table->table->s == opentab->s && opentab->query_id &&\n table->table->query_id != opentab->query_id)\n {\n my_error(ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG, MYF(0),\n table->table->s->table_name.str);\n DBUG_RETURN(TRUE);\n }\n }\n }\n\n if (check_lock_and_start_stmt(thd, thd->lex, table))\n {\n\tDBUG_RETURN(TRUE);\n }\n }\n /*\n If we are under explicit LOCK TABLES and our statement requires\n prelocking, we should mark all \"additional\" tables as free for use\n and enter prelocked mode.\n */\n if (thd->lex->requires_prelocking())\n {\n mark_real_tables_as_free_for_reuse(first_not_own);\n DBUG_PRINT(\"info\",\n (\"thd->locked_tables_mode= LTM_PRELOCKED_UNDER_LOCK_TABLES\"));\n thd->locked_tables_mode= LTM_PRELOCKED_UNDER_LOCK_TABLES;\n }\n }\n\n bool res= fix_all_session_vcol_exprs(thd, tables);\n if (!res)\n res= thd->decide_logging_format(tables);\n\n DBUG_RETURN(res);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416'], 'message': 'MDEV-24176 Preparations\n\n1. moved fix_vcol_exprs() call to open_table()\n\nmysql_alter_table() doesn't do lock_tables() so it cannot win from\nfix_vcol_exprs() from there. Tests affected: main.default_session\n\n2. Vanilla cleanups and comments.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void close_thread_table(THD *thd, TABLE **table_ptr)\n{\n TABLE *table= *table_ptr;\n DBUG_ENTER(\"close_thread_table\");\n DBUG_PRINT(\"tcache\", (\"table: '%s'.'%s' %p\", table->s->db.str,\n table->s->table_name.str, table));\n DBUG_ASSERT(!table->file->keyread_enabled());\n DBUG_ASSERT(!table->file || table->file->inited == handler::NONE);\n\n /*\n The metadata lock must be released after giving back\n the table to the table cache.\n */\n DBUG_ASSERT(thd->mdl_context.is_lock_owner(MDL_key::TABLE,\n table->s->db.str,\n table->s->table_name.str,\n MDL_SHARED));\n table->mdl_ticket= NULL;\n\n if (table->file)\n {\n table->file->update_global_table_stats();\n table->file->update_global_index_stats();\n }\n\n /*\n This look is needed to allow THD::notify_shared_lock() to\n traverse the thd->open_tables list without having to worry that\n some of the tables are removed from under it\n */\n\n mysql_mutex_lock(&thd->LOCK_thd_data);\n *table_ptr=table->next;\n mysql_mutex_unlock(&thd->LOCK_thd_data);\n\n if (! table->needs_reopen())\n {\n /* Avoid having MERGE tables with attached children in table cache. */\n table->file->extra(HA_EXTRA_DETACH_CHILDREN);\n /* Free memory and reset for next loop. */\n free_field_buffers_larger_than(table, MAX_TDC_BLOB_SIZE);\n table->file->ha_reset();\n }\n\n /*\n Do this *before* entering the TABLE_SHARE::tdc.LOCK_table_share\n critical section.\n */\n MYSQL_UNBIND_TABLE(table->file);\n\n tc_release_table(table);\n DBUG_VOID_RETURN;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-703'], 'message': 'MDEV-24176 Server crashes after insert in the table with virtual\ncolumn generated using date_format() and if()\n\nvcol_info->expr is allocated on expr_arena at parsing stage. Since\nexpr item is allocated on expr_arena all its containee items must be\nallocated on expr_arena too. Otherwise fix_session_expr() will\nencounter prematurely freed item.\n\nWhen table is reopened from cache vcol_info contains stale\nexpression. We refresh expression via TABLE::vcol_fix_exprs() but\nfirst we must prepare a proper context (Vcol_expr_context) which meets\nsome requirements:\n\n1. As noted above expr update must be done on expr_arena as there may\nbe new items created. It was a bug in fix_session_expr_for_read() and\nwas just not reproduced because of no second refix. Now refix is done\nfor more cases so it does reproduce. Tests affected: vcol.binlog\n\n2. Also name resolution context must be narrowed to the single table.\nTested by: vcol.update main.default vcol.vcol_syntax gcol.gcol_bugfixes\n\n3. sql_mode must be clean and not fail expr update.\n\nsql_mode such as MODE_NO_BACKSLASH_ESCAPES, MODE_NO_ZERO_IN_DATE, etc\nmust not affect vcol expression update. If the table was created\nsuccessfully any further evaluation must not fail. Tests affected:\nmain.func_like\n\nReviewed by: Sergei Golubchik '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool Virtual_column_info::fix_session_expr_for_read(THD *thd, Field *field)\n{\n DBUG_ENTER(\"fix_session_vcol_expr_for_read\");\n TABLE_LIST *tl= field->table->pos_in_table_list;\n if (!tl || tl->lock_type >= TL_WRITE_ALLOW_WRITE)\n DBUG_RETURN(0);\n Security_context *save_security_ctx= thd->security_ctx;\n if (tl->security_ctx)\n thd->security_ctx= tl->security_ctx;\n bool res= fix_session_expr(thd);\n thd->security_ctx= save_security_ctx;\n DBUG_RETURN(res);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-416', 'CWE-703'], 'message': 'MDEV-24176 Server crashes after insert in the table with virtual\ncolumn generated using date_format() and if()\n\nvcol_info->expr is allocated on expr_arena at parsing stage. Since\nexpr item is allocated on expr_arena all its containee items must be\nallocated on expr_arena too. Otherwise fix_session_expr() will\nencounter prematurely freed item.\n\nWhen table is reopened from cache vcol_info contains stale\nexpression. We refresh expression via TABLE::vcol_fix_exprs() but\nfirst we must prepare a proper context (Vcol_expr_context) which meets\nsome requirements:\n\n1. As noted above expr update must be done on expr_arena as there may\nbe new items created. It was a bug in fix_session_expr_for_read() and\nwas just not reproduced because of no second refix. Now refix is done\nfor more cases so it does reproduce. Tests affected: vcol.binlog\n\n2. Also name resolution context must be narrowed to the single table.\nTested by: vcol.update main.default vcol.vcol_syntax gcol.gcol_bugfixes\n\n3. sql_mode must be clean and not fail expr update.\n\nsql_mode such as MODE_NO_BACKSLASH_ESCAPES, MODE_NO_ZERO_IN_DATE, etc\nmust not affect vcol expression update. If the table was created\nsuccessfully any further evaluation must not fail. Tests affected:\nmain.func_like\n\nReviewed by: Sergei Golubchik '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: Field *get_tmp_table_field() { return 0; } ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-89'], 'message': 'MDEV-26423 MariaDB server crash in Create_tmp_table::finalize\n\nRemoved prohibition of creating temporary field of Item_default_value\n(added by mistake by 1d9b043a1f5db7ff229d5200652cff7a78ea6266 fix of\nMDEV-10780 and MDEV-11265).'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: bool Item_func_round::fix_length_and_dec()\n{\n int decimals_to_set;\n longlong val1;\n bool val1_unsigned;\n \n unsigned_flag= args[0]->unsigned_flag;\n if (!args[1]->const_item())\n {\n decimals= args[0]->decimals;\n max_length= float_length(decimals);\n if (args[0]->result_type() == DECIMAL_RESULT)\n {\n max_length++;\n set_handler_by_result_type(DECIMAL_RESULT);\n }\n else\n set_handler_by_result_type(REAL_RESULT);\n return FALSE;\n }\n\n val1= args[1]->val_int();\n if ((null_value= args[1]->null_value))\n return FALSE;\n\n val1_unsigned= args[1]->unsigned_flag;\n if (val1 < 0)\n decimals_to_set= val1_unsigned ? INT_MAX : 0;\n else\n decimals_to_set= (val1 > INT_MAX) ? INT_MAX : (int) val1;\n\n if (args[0]->decimals == NOT_FIXED_DEC)\n {\n decimals= MY_MIN(decimals_to_set, NOT_FIXED_DEC);\n max_length= float_length(decimals);\n set_handler_by_result_type(REAL_RESULT);\n return FALSE;\n }\n \n switch (args[0]->result_type()) {\n case REAL_RESULT:\n case STRING_RESULT:\n set_handler_by_result_type(REAL_RESULT);\n decimals= MY_MIN(decimals_to_set, NOT_FIXED_DEC);\n max_length= float_length(decimals);\n break;\n case INT_RESULT:\n if ((!decimals_to_set && truncate) || (args[0]->decimal_precision() < DECIMAL_LONGLONG_DIGITS))\n {\n int length_can_increase= MY_TEST(!truncate && (val1 < 0) &&\n !val1_unsigned);\n max_length= args[0]->max_length + length_can_increase;\n /* Here we can keep INT_RESULT */\n set_handler_by_result_type(INT_RESULT);\n decimals= 0;\n break;\n }\n /* fall through */\n case DECIMAL_RESULT:\n {\n set_handler_by_result_type(DECIMAL_RESULT);\n decimals_to_set= MY_MIN(DECIMAL_MAX_SCALE, decimals_to_set);\n int decimals_delta= args[0]->decimals - decimals_to_set;\n int precision= args[0]->decimal_precision();\n int length_increase= ((decimals_delta <= 0) || truncate) ? 0:1;\n\n precision-= decimals_delta - length_increase;\n decimals= MY_MIN(decimals_to_set, DECIMAL_MAX_SCALE);\n if (!precision)\n precision= 1; // DECIMAL(0,0) -> DECIMAL(1,0)\n max_length= my_decimal_precision_to_length_no_truncation(precision,\n decimals,\n unsigned_flag);\n break;\n }\n case ROW_RESULT:\n case TIME_RESULT:\n DBUG_ASSERT(0); /* This result type isn't handled */\n }\n return FALSE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-120'], 'message': 'MDEV-25317 Assertion `scale <= precision' failed in decimal_bin_size And Assertion `scale >= 0 && precision > 0 && scale <= precision' failed in decimal_bin_size_inline/decimal_bin_size.\n\nPrecision should be kept below DECIMAL_MAX_SCALE for computations.\nIt can be bigger in Item_decimal. I'd fix this too but it changes the\nexisting behaviour so problemmatic to ix.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: create_worker_threads(uint n)\n{\n\tcomp_thread_ctxt_t\t*threads;\n\tuint \t\t\ti;\n\n\tthreads = (comp_thread_ctxt_t *)\n\t\tmy_malloc(sizeof(comp_thread_ctxt_t) * n, MYF(MY_FAE));\n\n\tfor (i = 0; i < n; i++) {\n\t\tcomp_thread_ctxt_t *thd = threads + i;\n\n\t\tthd->num = i + 1;\n\t\tthd->started = FALSE;\n\t\tthd->cancelled = FALSE;\n\t\tthd->data_avail = FALSE;\n\n\t\tthd->to = (char *) my_malloc(COMPRESS_CHUNK_SIZE +\n\t\t\t\t\t\t MY_QLZ_COMPRESS_OVERHEAD,\n\t\t\t\t\t\t MYF(MY_FAE));\n\n\t\t/* Initialize the control mutex and condition var */\n\t\tif (pthread_mutex_init(&thd->ctrl_mutex, NULL) ||\n\t\t pthread_cond_init(&thd->ctrl_cond, NULL)) {\n\t\t\tgoto err;\n\t\t}\n\n\t\t/* Initialize and data mutex and condition var */\n\t\tif (pthread_mutex_init(&thd->data_mutex, NULL) ||\n\t\t pthread_cond_init(&thd->data_cond, NULL)) {\n\t\t\tgoto err;\n\t\t}\n\n\t\tpthread_mutex_lock(&thd->ctrl_mutex);\n\n\t\tif (pthread_create(&thd->id, NULL, compress_worker_thread_func,\n\t\t\t\t thd)) {\n\t\t\tmsg(\"compress: pthread_create() failed: \"\n\t\t\t \"errno = %d\", errno);\n\t\t\tgoto err;\n\t\t}\n\t}\n\n\t/* Wait for the threads to start */\n\tfor (i = 0; i < n; i++) {\n\t\tcomp_thread_ctxt_t *thd = threads + i;\n\n\t\twhile (thd->started == FALSE)\n\t\t\tpthread_cond_wait(&thd->ctrl_cond, &thd->ctrl_mutex);\n\t\tpthread_mutex_unlock(&thd->ctrl_mutex);\n\t}\n\n\treturn threads;\n\nerr:\n\tmy_free(threads);\n\treturn NULL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-404', 'CWE-703'], 'message': 'MDEV-26561 Fix a bug due to unreleased lock\n\nFix a bug of unreleased lock ctrl_mutex in the method create_worker_threads'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr,\n hwaddr *xlat, hwaddr *plen,\n MemTxAttrs attrs, int *prot)\n{\n MemoryRegionSection *section;\n IOMMUMemoryRegion *iommu_mr;\n IOMMUMemoryRegionClass *imrc;\n IOMMUTLBEntry iotlb;\n int iommu_idx;\n AddressSpaceDispatch *d =\n qatomic_rcu_read(&cpu->cpu_ases[asidx].memory_dispatch);\n\n for (;;) {\n section = address_space_translate_internal(d, addr, &addr, plen, false);\n\n iommu_mr = memory_region_get_iommu(section->mr);\n if (!iommu_mr) {\n break;\n }\n\n imrc = memory_region_get_iommu_class_nocheck(iommu_mr);\n\n iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);\n tcg_register_iommu_notifier(cpu, iommu_mr, iommu_idx);\n /* We need all the permissions, so pass IOMMU_NONE so the IOMMU\n * doesn't short-cut its translation table walk.\n */\n iotlb = imrc->translate(iommu_mr, addr, IOMMU_NONE, iommu_idx);\n addr = ((iotlb.translated_addr & ~iotlb.addr_mask)\n | (addr & iotlb.addr_mask));\n /* Update the caller's prot bits to remove permissions the IOMMU\n * is giving us a failure response for. If we get down to no\n * permissions left at all we can give up now.\n */\n if (!(iotlb.perm & IOMMU_RO)) {\n *prot &= ~(PAGE_READ | PAGE_EXEC);\n }\n if (!(iotlb.perm & IOMMU_WO)) {\n *prot &= ~PAGE_WRITE;\n }\n\n if (!*prot) {\n goto translate_fail;\n }\n\n d = flatview_to_dispatch(address_space_to_flatview(iotlb.target_as));\n }\n\n assert(!memory_region_is_iommu(section->mr));\n *xlat = addr;\n return section;\n\ntranslate_fail:\n return &d->map.sections[PHYS_SECTION_UNASSIGNED];\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-908'], 'message': 'softmmu: Always initialize xlat in address_space_translate_for_iotlb\n\nThe bug is an uninitialized memory read, along the translate_fail\npath, which results in garbage being read from iotlb_to_section,\nwhich can lead to a crash in io_readx/io_writex.\n\nThe bug may be fixed by writing any value with zero\nin ~TARGET_PAGE_MASK, so that the call to iotlb_to_section using\nthe xlat'ed address returns io_mem_unassigned, as desired by the\ntranslate_fail path.\n\nIt is most useful to record the original physical page address,\nwhich will eventually be logged by memory_region_access_valid\nwhen the access is rejected by unassigned_mem_accepts.\n\nResolves: https://gitlab.com/qemu-project/qemu/-/issues/1065\nSigned-off-by: Richard Henderson \nReviewed-by: Peter Maydell \nMessage-Id: <20220621153829.366423-1-richard.henderson@linaro.org>'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: zfs_groupmember(zfsvfs_t *zfsvfs, uint64_t id, cred_t *cr)\n{\n#ifdef HAVE_KSID\n\tksid_t\t\t*ksid = crgetsid(cr, KSID_GROUP);\n\tksidlist_t\t*ksidlist = crgetsidlist(cr);\n\tuid_t\t\tgid;\n\n\tif (ksid && ksidlist) {\n\t\tint\t\ti;\n\t\tksid_t\t\t*ksid_groups;\n\t\tuint32_t\tidx = FUID_INDEX(id);\n\t\tuint32_t\trid = FUID_RID(id);\n\n\t\tksid_groups = ksidlist->ksl_sids;\n\n\t\tfor (i = 0; i != ksidlist->ksl_nsid; i++) {\n\t\t\tif (idx == 0) {\n\t\t\t\tif (id != IDMAP_WK_CREATOR_GROUP_GID &&\n\t\t\t\t id == ksid_groups[i].ks_id) {\n\t\t\t\t\treturn (B_TRUE);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst char *domain;\n\n\t\t\t\tdomain = zfs_fuid_find_by_idx(zfsvfs, idx);\n\t\t\t\tASSERT(domain != NULL);\n\n\t\t\t\tif (strcmp(domain,\n\t\t\t\t IDMAP_WK_CREATOR_SID_AUTHORITY) == 0)\n\t\t\t\t\treturn (B_FALSE);\n\n\t\t\t\tif ((strcmp(domain,\n\t\t\t\t ksid_groups[i].ks_domain->kd_name) == 0) &&\n\t\t\t\t rid == ksid_groups[i].ks_rid)\n\t\t\t\t\treturn (B_TRUE);\n\t\t\t}\n\t\t}\n\t}\n\n\t/*\n\t * Not found in ksidlist, check posix groups\n\t */\n\tgid = zfs_fuid_map_id(zfsvfs, id, cr, ZFS_GROUP);\n\treturn (groupmember(gid, cr));\n#else\n\treturn (B_TRUE);\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200', 'CWE-732'], 'message': 'FreeBSD: Fix UNIX permissions checking\n\nReviewed-by: Ryan Moeller \r\nReviewed-by: Brian Behlendorf \r\nSigned-off-by: Matt Macy \r\nCloses #10727'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void LEX::relink_hack(st_select_lex *select_lex)\n{\n if (!select_stack_top) // Statements of the second type\n {\n if (!select_lex->get_master()->get_master())\n ((st_select_lex *) select_lex->get_master())->\n set_master(&builtin_select);\n if (!builtin_select.get_slave())\n builtin_select.set_slave(select_lex->get_master());\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-703'], 'message': 'MDEV-22001: Server crashes in st_select_lex_unit::exclude_level upon execution of SP\n\nRunning some statements that use IN subqueries outside context of a regular\nquery could result in server abnormal termination.\n\nThe reason for failure is that internal structures SELECT_LEX/SELECT_LEX_UNIT\ncreated on behalf of parsed query were initialized incorrectly. Incorrect\ninitialization of the structures SELECT_LEX/SELECT_LEX_UNIT was introduced\nby the commit de745ecf29721795710910a19bd0ea3389da804c\n(MDEV-11953: support of brackets in UNION/EXCEPT/INTERSECT operations)\npushed into 10.4, that is the reason this bug report is not reproduced in 10.3.\n\nTo fix the issue the method SLECTE_LEX::register_unit is used for proper\ninitialization of the data structures SELECT_LEX/SELECT_LEX_UNIT. Additionally,\nthe method SELECT_LEX::get_slave() was removed from the source code base\nsince for those use cases where it is used it can be replaced by the method\nfirst_inner_unit().'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: int do_ssl3_write(SSL *s, int type, const unsigned char *buf,\n unsigned int *pipelens, unsigned int numpipes,\n int create_empty_fragment)\n{\n unsigned char *outbuf[SSL_MAX_PIPELINES], *plen[SSL_MAX_PIPELINES];\n SSL3_RECORD wr[SSL_MAX_PIPELINES];\n int i, mac_size, clear = 0;\n int prefix_len = 0;\n int eivlen;\n size_t align = 0;\n SSL3_BUFFER *wb;\n SSL_SESSION *sess;\n unsigned int totlen = 0;\n unsigned int j;\n\n for (j = 0; j < numpipes; j++)\n totlen += pipelens[j];\n /*\n * first check if there is a SSL3_BUFFER still being written out. This\n * will happen with non blocking IO\n */\n if (RECORD_LAYER_write_pending(&s->rlayer))\n return (ssl3_write_pending(s, type, buf, totlen));\n\n /* If we have an alert to send, lets send it */\n if (s->s3->alert_dispatch) {\n i = s->method->ssl_dispatch_alert(s);\n if (i <= 0)\n return (i);\n /* if it went, fall through and send more stuff */\n }\n\n if (s->rlayer.numwpipes < numpipes)\n if (!ssl3_setup_write_buffer(s, numpipes, 0))\n return -1;\n\n if (totlen == 0 && !create_empty_fragment)\n return 0;\n\n sess = s->session;\n\n if ((sess == NULL) ||\n (s->enc_write_ctx == NULL) || (EVP_MD_CTX_md(s->write_hash) == NULL)) {\n clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */\n mac_size = 0;\n } else {\n mac_size = EVP_MD_CTX_size(s->write_hash);\n if (mac_size < 0)\n goto err;\n }\n\n /*\n * 'create_empty_fragment' is true only when this function calls itself\n */\n if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done) {\n /*\n * countermeasure against known-IV weakness in CBC ciphersuites (see\n * http://www.openssl.org/~bodo/tls-cbc.txt)\n */\n\n if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {\n /*\n * recursive function call with 'create_empty_fragment' set; this\n * prepares and buffers the data for an empty fragment (these\n * 'prefix_len' bytes are sent out later together with the actual\n * payload)\n */\n unsigned int tmppipelen = 0;\n\n prefix_len = do_ssl3_write(s, type, buf, &tmppipelen, 1, 1);\n if (prefix_len <= 0)\n goto err;\n\n if (prefix_len >\n (SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD)) {\n /* insufficient space */\n SSLerr(SSL_F_DO_SSL3_WRITE, ERR_R_INTERNAL_ERROR);\n goto err;\n }\n }\n\n s->s3->empty_fragment_done = 1;\n }\n\n if (create_empty_fragment) {\n wb = &s->rlayer.wbuf[0];\n#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0\n /*\n * extra fragment would be couple of cipher blocks, which would be\n * multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real\n * payload, then we can just pretend we simply have two headers.\n */\n align = (size_t)SSL3_BUFFER_get_buf(wb) + 2 * SSL3_RT_HEADER_LENGTH;\n align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);\n#endif\n outbuf[0] = SSL3_BUFFER_get_buf(wb) + align;\n SSL3_BUFFER_set_offset(wb, align);\n } else if (prefix_len) {\n wb = &s->rlayer.wbuf[0];\n outbuf[0] = SSL3_BUFFER_get_buf(wb) + SSL3_BUFFER_get_offset(wb)\n + prefix_len;\n } else {\n for (j = 0; j < numpipes; j++) {\n wb = &s->rlayer.wbuf[j];\n#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0\n align = (size_t)SSL3_BUFFER_get_buf(wb) + SSL3_RT_HEADER_LENGTH;\n align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);\n#endif\n outbuf[j] = SSL3_BUFFER_get_buf(wb) + align;\n SSL3_BUFFER_set_offset(wb, align);\n }\n }\n\n /* Explicit IV length, block ciphers appropriate version flag */\n if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s)) {\n int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx);\n if (mode == EVP_CIPH_CBC_MODE) {\n eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx);\n if (eivlen <= 1)\n eivlen = 0;\n }\n /* Need explicit part of IV for GCM mode */\n else if (mode == EVP_CIPH_GCM_MODE)\n eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;\n else if (mode == EVP_CIPH_CCM_MODE)\n eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;\n else\n eivlen = 0;\n } else\n eivlen = 0;\n\n totlen = 0;\n /* Clear our SSL3_RECORD structures */\n memset(wr, 0, sizeof wr);\n for (j = 0; j < numpipes; j++) {\n /* write the header */\n *(outbuf[j]++) = type & 0xff;\n SSL3_RECORD_set_type(&wr[j], type);\n\n *(outbuf[j]++) = (s->version >> 8);\n /*\n * Some servers hang if initial client hello is larger than 256 bytes\n * and record version number > TLS 1.0\n */\n if (SSL_get_state(s) == TLS_ST_CW_CLNT_HELLO\n && !s->renegotiate && TLS1_get_version(s) > TLS1_VERSION)\n *(outbuf[j]++) = 0x1;\n else\n *(outbuf[j]++) = s->version & 0xff;\n\n /* field where we are to write out packet length */\n plen[j] = outbuf[j];\n outbuf[j] += 2;\n\n /* lets setup the record stuff. */\n SSL3_RECORD_set_data(&wr[j], outbuf[j] + eivlen);\n SSL3_RECORD_set_length(&wr[j], (int)pipelens[j]);\n SSL3_RECORD_set_input(&wr[j], (unsigned char *)&buf[totlen]);\n totlen += pipelens[j];\n\n /*\n * we now 'read' from wr->input, wr->length bytes into wr->data\n */\n\n /* first we compress */\n if (s->compress != NULL) {\n if (!ssl3_do_compress(s, &wr[j])) {\n SSLerr(SSL_F_DO_SSL3_WRITE, SSL_R_COMPRESSION_FAILURE);\n goto err;\n }\n } else {\n memcpy(wr[j].data, wr[j].input, wr[j].length);\n SSL3_RECORD_reset_input(&wr[j]);\n }\n\n /*\n * we should still have the output to wr->data and the input from\n * wr->input. Length should be wr->length. wr->data still points in the\n * wb->buf\n */\n\n if (!SSL_USE_ETM(s) && mac_size != 0) {\n if (s->method->ssl3_enc->mac(s, &wr[j],\n &(outbuf[j][wr[j].length + eivlen]),\n 1) < 0)\n goto err;\n SSL3_RECORD_add_length(&wr[j], mac_size);\n }\n\n SSL3_RECORD_set_data(&wr[j], outbuf[j]);\n SSL3_RECORD_reset_input(&wr[j]);\n\n if (eivlen) {\n /*\n * if (RAND_pseudo_bytes(p, eivlen) <= 0) goto err;\n */\n SSL3_RECORD_add_length(&wr[j], eivlen);\n }\n }\n\n if (s->method->ssl3_enc->enc(s, wr, numpipes, 1) < 1)\n goto err;\n\n for (j = 0; j < numpipes; j++) {\n if (SSL_USE_ETM(s) && mac_size != 0) {\n if (s->method->ssl3_enc->mac(s, &wr[j],\n outbuf[j] + wr[j].length, 1) < 0)\n goto err;\n SSL3_RECORD_add_length(&wr[j], mac_size);\n }\n\n /* record length after mac and block padding */\n s2n(SSL3_RECORD_get_length(&wr[j]), plen[j]);\n\n if (s->msg_callback)\n s->msg_callback(1, 0, SSL3_RT_HEADER, plen[j] - 5, 5, s,\n s->msg_callback_arg);\n\n /*\n * we should now have wr->data pointing to the encrypted data, which is\n * wr->length long\n */\n SSL3_RECORD_set_type(&wr[j], type); /* not needed but helps for\n * debugging */\n SSL3_RECORD_add_length(&wr[j], SSL3_RT_HEADER_LENGTH);\n\n if (create_empty_fragment) {\n /*\n * we are in a recursive call; just return the length, don't write\n * out anything here\n */\n if (j > 0) {\n /* We should never be pipelining an empty fragment!! */\n SSLerr(SSL_F_DO_SSL3_WRITE, ERR_R_INTERNAL_ERROR);\n goto err;\n }\n return SSL3_RECORD_get_length(wr);\n }\n\n /* now let's set up wb */\n SSL3_BUFFER_set_left(&s->rlayer.wbuf[j],\n prefix_len + SSL3_RECORD_get_length(&wr[j]));\n }\n\n /*\n * memorize arguments so that ssl3_write_pending can detect bad write\n * retries later\n */\n s->rlayer.wpend_tot = totlen;\n s->rlayer.wpend_buf = buf;\n s->rlayer.wpend_type = type;\n s->rlayer.wpend_ret = totlen;\n\n /* we now just need to write the buffer */\n return ssl3_write_pending(s, type, buf, totlen);\n err:\n return -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Don't change the state of the ETM flags until CCS processing\n\nChanging the ciphersuite during a renegotiation can result in a crash\nleading to a DoS attack. ETM has not been implemented in 1.1.0 for DTLS\nso this is TLS only.\n\nThe problem is caused by changing the flag indicating whether to use ETM\nor not immediately on negotiation of ETM, rather than at CCS. Therefore,\nduring a renegotiation, if the ETM state is changing (usually due to a\nchange of ciphersuite), then an error/crash will occur.\n\nDue to the fact that there are separate CCS messages for read and write\nwe actually now need two flags to determine whether to use ETM or not.\n\nCVE-2017-3733\n\nReviewed-by: Richard Levitte '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: auth_passdb_preinit(struct auth *auth, const struct auth_passdb_settings *set,\n\t\t struct auth_passdb **passdbs)\n{\n\tstruct auth_passdb *auth_passdb, **dest;\n\n\tauth_passdb = p_new(auth->pool, struct auth_passdb, 1);\n\tauth_passdb->set = set;\n\tauth_passdb->skip = auth_passdb_skip_parse(set->skip);\n\tauth_passdb->result_success =\n\t\tauth_db_rule_parse(set->result_success);\n\tauth_passdb->result_failure =\n\t\tauth_db_rule_parse(set->result_failure);\n\tauth_passdb->result_internalfail =\n\t\tauth_db_rule_parse(set->result_internalfail);\n\n\tauth_passdb->default_fields_tmpl =\n\t\tpassdb_template_build(auth->pool, set->default_fields);\n\tauth_passdb->override_fields_tmpl =\n\t\tpassdb_template_build(auth->pool, set->override_fields);\n\n\t/* for backwards compatibility: */\n\tif (set->pass)\n\t\tauth_passdb->result_success = AUTH_DB_RULE_CONTINUE;\n\n\tfor (dest = passdbs; *dest != NULL; dest = &(*dest)->next) ;\n\t*dest = auth_passdb;\n\n\tauth_passdb->passdb = passdb_preinit(auth->pool, set);\n\t/* make sure any %variables in default_fields exist in cache_key */\n\tif (auth_passdb->passdb->default_cache_key != NULL) {\n\t\tauth_passdb->cache_key =\n\t\t\tp_strconcat(auth->pool, auth_passdb->passdb->default_cache_key,\n\t\t\t\tset->default_fields, NULL);\n\t}\n\telse {\n\t\tauth_passdb->cache_key = NULL;\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-284'], 'message': 'auth: Fix handling passdbs with identical driver/args but different mechanisms/username_filter\n\nThe passdb was wrongly deduplicated in this situation, causing wrong\nmechanisms or username_filter setting to be used. This would be a rather\nunlikely configuration though.\n\nFixed by moving mechanisms and username_filter from struct passdb_module\nto struct auth_passdb, which is where they should have been in the first\nplace.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static char *make_filename_safe(const char *filename TSRMLS_DC)\n{\n\tif (*filename && memcmp(filename, \":memory:\", sizeof(\":memory:\"))) {\n\t\tchar *fullpath = expand_filepath(filename, NULL TSRMLS_CC);\n\n\t\tif (!fullpath) {\n\t\t\treturn NULL;\n\t\t}\n\n\t\tif (PG(safe_mode) && (!php_checkuid(fullpath, NULL, CHECKUID_CHECK_FILE_AND_DIR))) {\n\t\t\tefree(fullpath);\n\t\t\treturn NULL;\n\t\t}\n\n\t\tif (php_check_open_basedir(fullpath TSRMLS_CC)) {\n\t\t\tefree(fullpath);\n\t\t\treturn NULL;\n\t\t}\n\t\treturn fullpath;\n\t}\n\treturn estrdup(filename);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'Improve check for :memory: pseudo-filename in SQlite'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void pdo_sqlite_request_shutdown(pdo_dbh_t *dbh TSRMLS_DC)\n{\n\tpdo_sqlite_db_handle *H = (pdo_sqlite_db_handle *)dbh->driver_data;\n\t/* unregister functions, so that they don't linger for the next\n\t * request */\n\tif (H) {\n\t\tpdo_sqlite_cleanup_callbacks(H TSRMLS_CC);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'Improve check for :memory: pseudo-filename in SQlite'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static PHP_METHOD(SQLite, sqliteCreateCollation)\n{\n\tstruct pdo_sqlite_collation *collation;\n\tzval *callback;\n\tchar *collation_name;\n\tint collation_name_len;\n\tchar *cbname = NULL;\n\tpdo_dbh_t *dbh;\n\tpdo_sqlite_db_handle *H;\n\tint ret;\n\n\tif (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"sz\",\n\t\t&collation_name, &collation_name_len, &callback)) {\n\t\tRETURN_FALSE;\n\t}\n\n\tdbh = zend_object_store_get_object(getThis() TSRMLS_CC);\n\tPDO_CONSTRUCT_CHECK;\n\n\tif (!zend_is_callable(callback, 0, &cbname TSRMLS_CC)) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"function '%s' is not callable\", cbname);\n\t\tefree(cbname);\n\t\tRETURN_FALSE;\n\t}\n\tefree(cbname);\n\n\tH = (pdo_sqlite_db_handle *)dbh->driver_data;\n\n\tcollation = (struct pdo_sqlite_collation*)ecalloc(1, sizeof(*collation));\n\n\tret = sqlite3_create_collation(H->db, collation_name, SQLITE_UTF8, collation, php_sqlite3_collation_callback);\n\tif (ret == SQLITE_OK) {\n\t\tcollation->name = estrdup(collation_name);\n\n\t\tMAKE_STD_ZVAL(collation->callback);\n\t\tMAKE_COPY_ZVAL(&callback, collation->callback);\n\n\t\tcollation->next = H->collations;\n\t\tH->collations = collation;\n\n\t\tRETURN_TRUE;\n\t}\n\n\tefree(collation);\n\tRETURN_FALSE;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-264'], 'message': 'Improve check for :memory: pseudo-filename in SQlite'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static uint32_t cirrus_get_bpp16_depth(CirrusVGAState * s)\n{\n uint32_t ret = 16;\n\n switch (s->cirrus_hidden_dac_data & 0xf) {\n case 0:\n\tret = 15;\n\tbreak;\t\t\t/* Sierra HiColor */\n case 1:\n\tret = 16;\n\tbreak;\t\t\t/* XGA HiColor */\n default:\n#ifdef DEBUG_CIRRUS\n\tprintf(\"cirrus: invalid DAC value %x in 16bpp\\n\",\n\t (s->cirrus_hidden_dac_data & 0xf));\n#endif\n\tret = 15;\t\t/* XXX */\n\tbreak;\n }\n return ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2007-1320 - Cirrus LGD-54XX \"bitblt\" heap overflow\n\nI have just noticed that patch for CVE-2007-1320 has never been applied\nto the QEMU CVS. Please find it below.\n\n| Multiple heap-based buffer overflows in the cirrus_invalidate_region\n| function in the Cirrus VGA extension in QEMU 0.8.2, as used in Xen and\n| possibly other products, might allow local users to execute arbitrary\n| code via unspecified vectors related to \"attempting to mark\n| non-existent regions as dirty,\" aka the \"bitblt\" heap overflow.\n\n\ngit-svn-id: svn://svn.savannah.nongnu.org/qemu/trunk@4340 c046a42c-6fe2-441c-8c8c-71466251a162'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void cirrus_linear_writel(void *opaque, target_phys_addr_t addr,\n\t\t\t\t uint32_t val)\n{\n#ifdef TARGET_WORDS_BIGENDIAN\n cirrus_linear_writeb(opaque, addr, (val >> 24) & 0xff);\n cirrus_linear_writeb(opaque, addr + 1, (val >> 16) & 0xff);\n cirrus_linear_writeb(opaque, addr + 2, (val >> 8) & 0xff);\n cirrus_linear_writeb(opaque, addr + 3, val & 0xff);\n#else\n cirrus_linear_writeb(opaque, addr, val & 0xff);\n cirrus_linear_writeb(opaque, addr + 1, (val >> 8) & 0xff);\n cirrus_linear_writeb(opaque, addr + 2, (val >> 16) & 0xff);\n cirrus_linear_writeb(opaque, addr + 3, (val >> 24) & 0xff);\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2007-1320 - Cirrus LGD-54XX \"bitblt\" heap overflow\n\nI have just noticed that patch for CVE-2007-1320 has never been applied\nto the QEMU CVS. Please find it below.\n\n| Multiple heap-based buffer overflows in the cirrus_invalidate_region\n| function in the Cirrus VGA extension in QEMU 0.8.2, as used in Xen and\n| possibly other products, might allow local users to execute arbitrary\n| code via unspecified vectors related to \"attempting to mark\n| non-existent regions as dirty,\" aka the \"bitblt\" heap overflow.\n\n\ngit-svn-id: svn://svn.savannah.nongnu.org/qemu/trunk@4340 c046a42c-6fe2-441c-8c8c-71466251a162'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int cirrus_bitblt_videotocpu(CirrusVGAState * s)\n{\n /* XXX */\n#ifdef DEBUG_BITBLT\n printf(\"cirrus: bitblt (video to cpu) is not implemented yet\\n\");\n#endif\n return 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2007-1320 - Cirrus LGD-54XX \"bitblt\" heap overflow\n\nI have just noticed that patch for CVE-2007-1320 has never been applied\nto the QEMU CVS. Please find it below.\n\n| Multiple heap-based buffer overflows in the cirrus_invalidate_region\n| function in the Cirrus VGA extension in QEMU 0.8.2, as used in Xen and\n| possibly other products, might allow local users to execute arbitrary\n| code via unspecified vectors related to \"attempting to mark\n| non-existent regions as dirty,\" aka the \"bitblt\" heap overflow.\n\n\ngit-svn-id: svn://svn.savannah.nongnu.org/qemu/trunk@4340 c046a42c-6fe2-441c-8c8c-71466251a162'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void cirrus_update_bank_ptr(CirrusVGAState * s, unsigned bank_index)\n{\n unsigned offset;\n unsigned limit;\n\n if ((s->gr[0x0b] & 0x01) != 0)\t/* dual bank */\n\toffset = s->gr[0x09 + bank_index];\n else\t\t\t/* single bank */\n\toffset = s->gr[0x09];\n\n if ((s->gr[0x0b] & 0x20) != 0)\n\toffset <<= 14;\n else\n\toffset <<= 12;\n\n if (s->real_vram_size <= offset)\n\tlimit = 0;\n else\n\tlimit = s->real_vram_size - offset;\n\n if (((s->gr[0x0b] & 0x01) == 0) && (bank_index != 0)) {\n\tif (limit > 0x8000) {\n\t offset += 0x8000;\n\t limit -= 0x8000;\n\t} else {\n\t limit = 0;\n\t}\n }\n\n if (limit > 0) {\n\ts->cirrus_bank_base[bank_index] = offset;\n\ts->cirrus_bank_limit[bank_index] = limit;\n } else {\n\ts->cirrus_bank_base[bank_index] = 0;\n\ts->cirrus_bank_limit[bank_index] = 0;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2007-1320 - Cirrus LGD-54XX \"bitblt\" heap overflow\n\nI have just noticed that patch for CVE-2007-1320 has never been applied\nto the QEMU CVS. Please find it below.\n\n| Multiple heap-based buffer overflows in the cirrus_invalidate_region\n| function in the Cirrus VGA extension in QEMU 0.8.2, as used in Xen and\n| possibly other products, might allow local users to execute arbitrary\n| code via unspecified vectors related to \"attempting to mark\n| non-existent regions as dirty,\" aka the \"bitblt\" heap overflow.\n\n\ngit-svn-id: svn://svn.savannah.nongnu.org/qemu/trunk@4340 c046a42c-6fe2-441c-8c8c-71466251a162'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void cirrus_get_offsets(VGAState *s1,\n uint32_t *pline_offset,\n uint32_t *pstart_addr,\n uint32_t *pline_compare)\n{\n CirrusVGAState * s = (CirrusVGAState *)s1;\n uint32_t start_addr, line_offset, line_compare;\n\n line_offset = s->cr[0x13]\n\t| ((s->cr[0x1b] & 0x10) << 4);\n line_offset <<= 3;\n *pline_offset = line_offset;\n\n start_addr = (s->cr[0x0c] << 8)\n\t| s->cr[0x0d]\n\t| ((s->cr[0x1b] & 0x01) << 16)\n\t| ((s->cr[0x1b] & 0x0c) << 15)\n\t| ((s->cr[0x1d] & 0x80) << 12);\n *pstart_addr = start_addr;\n\n line_compare = s->cr[0x18] |\n ((s->cr[0x07] & 0x10) << 4) |\n ((s->cr[0x09] & 0x40) << 3);\n *pline_compare = line_compare;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2007-1320 - Cirrus LGD-54XX \"bitblt\" heap overflow\n\nI have just noticed that patch for CVE-2007-1320 has never been applied\nto the QEMU CVS. Please find it below.\n\n| Multiple heap-based buffer overflows in the cirrus_invalidate_region\n| function in the Cirrus VGA extension in QEMU 0.8.2, as used in Xen and\n| possibly other products, might allow local users to execute arbitrary\n| code via unspecified vectors related to \"attempting to mark\n| non-existent regions as dirty,\" aka the \"bitblt\" heap overflow.\n\n\ngit-svn-id: svn://svn.savannah.nongnu.org/qemu/trunk@4340 c046a42c-6fe2-441c-8c8c-71466251a162'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static uint32_t cirrus_linear_readw(void *opaque, target_phys_addr_t addr)\n{\n uint32_t v;\n#ifdef TARGET_WORDS_BIGENDIAN\n v = cirrus_linear_readb(opaque, addr) << 8;\n v |= cirrus_linear_readb(opaque, addr + 1);\n#else\n v = cirrus_linear_readb(opaque, addr);\n v |= cirrus_linear_readb(opaque, addr + 1) << 8;\n#endif\n return v;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2007-1320 - Cirrus LGD-54XX \"bitblt\" heap overflow\n\nI have just noticed that patch for CVE-2007-1320 has never been applied\nto the QEMU CVS. Please find it below.\n\n| Multiple heap-based buffer overflows in the cirrus_invalidate_region\n| function in the Cirrus VGA extension in QEMU 0.8.2, as used in Xen and\n| possibly other products, might allow local users to execute arbitrary\n| code via unspecified vectors related to \"attempting to mark\n| non-existent regions as dirty,\" aka the \"bitblt\" heap overflow.\n\n\ngit-svn-id: svn://svn.savannah.nongnu.org/qemu/trunk@4340 c046a42c-6fe2-441c-8c8c-71466251a162'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: glue(cirrus_bitblt_rop_fwd_, ROP_NAME)(CirrusVGAState *s,\n uint8_t *dst,const uint8_t *src,\n int dstpitch,int srcpitch,\n int bltwidth,int bltheight)\n{\n int x,y;\n dstpitch -= bltwidth;\n srcpitch -= bltwidth;\n\n if (dstpitch < 0 || srcpitch < 0) {\n /* is 0 valid? srcpitch == 0 could be useful */\n return;\n }\n\n for (y = 0; y < bltheight; y++) {\n for (x = 0; x < bltwidth; x++) {\n ROP_OP(*dst, *src);\n dst++;\n src++;\n }\n dst += dstpitch;\n src += srcpitch;\n }\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2007-1320 - Cirrus LGD-54XX \"bitblt\" heap overflow\n\nI have just noticed that patch for CVE-2007-1320 has never been applied\nto the QEMU CVS. Please find it below.\n\n| Multiple heap-based buffer overflows in the cirrus_invalidate_region\n| function in the Cirrus VGA extension in QEMU 0.8.2, as used in Xen and\n| possibly other products, might allow local users to execute arbitrary\n| code via unspecified vectors related to \"attempting to mark\n| non-existent regions as dirty,\" aka the \"bitblt\" heap overflow.\n\n\ngit-svn-id: svn://svn.savannah.nongnu.org/qemu/trunk@4340 c046a42c-6fe2-441c-8c8c-71466251a162'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static uint32_t cirrus_vga_mem_readw(void *opaque, target_phys_addr_t addr)\n{\n uint32_t v;\n#ifdef TARGET_WORDS_BIGENDIAN\n v = cirrus_vga_mem_readb(opaque, addr) << 8;\n v |= cirrus_vga_mem_readb(opaque, addr + 1);\n#else\n v = cirrus_vga_mem_readb(opaque, addr);\n v |= cirrus_vga_mem_readb(opaque, addr + 1) << 8;\n#endif\n return v;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2007-1320 - Cirrus LGD-54XX \"bitblt\" heap overflow\n\nI have just noticed that patch for CVE-2007-1320 has never been applied\nto the QEMU CVS. Please find it below.\n\n| Multiple heap-based buffer overflows in the cirrus_invalidate_region\n| function in the Cirrus VGA extension in QEMU 0.8.2, as used in Xen and\n| possibly other products, might allow local users to execute arbitrary\n| code via unspecified vectors related to \"attempting to mark\n| non-existent regions as dirty,\" aka the \"bitblt\" heap overflow.\n\n\ngit-svn-id: svn://svn.savannah.nongnu.org/qemu/trunk@4340 c046a42c-6fe2-441c-8c8c-71466251a162'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: asmlinkage void syscall_trace_leave(struct pt_regs *regs)\n{\n\tif (unlikely(current->audit_context))\n\t\taudit_syscall_exit(AUDITSC_RESULT(regs->rax), regs->rax);\n\n\tif ((test_thread_flag(TIF_SYSCALL_TRACE)\n\t || test_thread_flag(TIF_SINGLESTEP))\n\t && (current->ptrace & PT_PTRACED))\n\t\tsyscall_trace(regs);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Handle bogus %cs selector in single-step instruction decoding\n\nThe code for LDT segment selectors was not robust in the face of a bogus\nselector set in %cs via ptrace before the single-step was done.\n\nSigned-off-by: Roland McGrath \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void ptrace_disable(struct task_struct *child)\n{ \n\tclear_singlestep(child);\n\tclear_tsk_thread_flag(child, TIF_SYSCALL_TRACE);\n\tclear_tsk_thread_flag(child, TIF_SYSCALL_EMU);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Handle bogus %cs selector in single-step instruction decoding\n\nThe code for LDT segment selectors was not robust in the face of a bogus\nselector set in %cs via ptrace before the single-step was done.\n\nSigned-off-by: Roland McGrath \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void send_sigtrap(struct task_struct *tsk, struct pt_regs *regs, int error_code)\n{\n\tstruct siginfo info;\n\n\ttsk->thread.trap_no = 1;\n\ttsk->thread.error_code = error_code;\n\n\tmemset(&info, 0, sizeof(info));\n\tinfo.si_signo = SIGTRAP;\n\tinfo.si_code = TRAP_BRKPT;\n\n\t/* User-mode eip? */\n\tinfo.si_addr = user_mode_vm(regs) ? (void __user *) regs->eip : NULL;\n\n\t/* Send us the fakey SIGTRAP */\n\tforce_sig_info(SIGTRAP, &info, tsk);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'Handle bogus %cs selector in single-step instruction decoding\n\nThe code for LDT segment selectors was not robust in the face of a bogus\nselector set in %cs via ptrace before the single-step was done.\n\nSigned-off-by: Roland McGrath \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int pwc_video_open(struct inode *inode, struct file *file)\n{\n\tint i, ret;\n\tstruct video_device *vdev = video_devdata(file);\n\tstruct pwc_device *pdev;\n\n\tPWC_DEBUG_OPEN(\">> video_open called(vdev = 0x%p).\\n\", vdev);\n\n\tpdev = (struct pwc_device *)vdev->priv;\n\tBUG_ON(!pdev);\n\tif (pdev->vopen) {\n\t\tPWC_DEBUG_OPEN(\"I'm busy, someone is using the device.\\n\");\n\t\treturn -EBUSY;\n\t}\n\n\tmutex_lock(&pdev->modlock);\n\tif (!pdev->usb_init) {\n\t\tPWC_DEBUG_OPEN(\"Doing first time initialization.\\n\");\n\t\tpdev->usb_init = 1;\n\n\t\t/* Query sensor type */\n\t\tret = pwc_get_cmos_sensor(pdev, &i);\n\t\tif (ret >= 0)\n\t\t{\n\t\t\tPWC_DEBUG_OPEN(\"This %s camera is equipped with a %s (%d).\\n\",\n\t\t\t\t\tpdev->vdev->name,\n\t\t\t\t\tpwc_sensor_type_to_string(i), i);\n\t\t}\n\t}\n\n\t/* Turn on camera */\n\tif (power_save) {\n\t\ti = pwc_camera_power(pdev, 1);\n\t\tif (i < 0)\n\t\t\tPWC_DEBUG_OPEN(\"Failed to restore power to the camera! (%d)\\n\", i);\n\t}\n\t/* Set LED on/off time */\n\tif (pwc_set_leds(pdev, led_on, led_off) < 0)\n\t\tPWC_DEBUG_OPEN(\"Failed to set LED on/off time.\\n\");\n\n\tpwc_construct(pdev); /* set min/max sizes correct */\n\n\t/* So far, so good. Allocate memory. */\n\ti = pwc_allocate_buffers(pdev);\n\tif (i < 0) {\n\t\tPWC_DEBUG_OPEN(\"Failed to allocate buffers memory.\\n\");\n\t\tpwc_free_buffers(pdev);\n\t\tmutex_unlock(&pdev->modlock);\n\t\treturn i;\n\t}\n\n\t/* Reset buffers & parameters */\n\tpwc_reset_buffers(pdev);\n\tfor (i = 0; i < pwc_mbufs; i++)\n\t\tpdev->image_used[i] = 0;\n\tpdev->vframe_count = 0;\n\tpdev->vframes_dumped = 0;\n\tpdev->vframes_error = 0;\n\tpdev->visoc_errors = 0;\n\tpdev->error_status = 0;\n\tpwc_construct(pdev); /* set min/max sizes correct */\n\n\t/* Set some defaults */\n\tpdev->vsnapshot = 0;\n\n\t/* Start iso pipe for video; first try the last used video size\n\t (or the default one); if that fails try QCIF/10 or QSIF/10;\n\t it that fails too, give up.\n\t */\n\ti = pwc_set_video_mode(pdev, pwc_image_sizes[pdev->vsize].x, pwc_image_sizes[pdev->vsize].y, pdev->vframes, pdev->vcompression, 0);\n\tif (i)\t{\n\t\tunsigned int default_resolution;\n\t\tPWC_DEBUG_OPEN(\"First attempt at set_video_mode failed.\\n\");\n\t\tif (pdev->type>= 730)\n\t\t\tdefault_resolution = PSZ_QSIF;\n\t\telse\n\t\t\tdefault_resolution = PSZ_QCIF;\n\n\t\ti = pwc_set_video_mode(pdev,\n\t\t\t\t pwc_image_sizes[default_resolution].x,\n\t\t\t\t pwc_image_sizes[default_resolution].y,\n\t\t\t\t 10,\n\t\t\t\t pdev->vcompression,\n\t\t\t\t 0);\n\t}\n\tif (i) {\n\t\tPWC_DEBUG_OPEN(\"Second attempt at set_video_mode failed.\\n\");\n\t\tpwc_free_buffers(pdev);\n\t\tmutex_unlock(&pdev->modlock);\n\t\treturn i;\n\t}\n\n\ti = pwc_isoc_init(pdev);\n\tif (i) {\n\t\tPWC_DEBUG_OPEN(\"Failed to init ISOC stuff = %d.\\n\", i);\n\t\tpwc_isoc_cleanup(pdev);\n\t\tpwc_free_buffers(pdev);\n\t\tmutex_unlock(&pdev->modlock);\n\t\treturn i;\n\t}\n\n\t/* Initialize the webcam to sane value */\n\tpwc_set_brightness(pdev, 0x7fff);\n\tpwc_set_agc(pdev, 1, 0);\n\n\tpdev->vopen++;\n\tfile->private_data = vdev;\n\tmutex_unlock(&pdev->modlock);\n\tPWC_DEBUG_OPEN(\"<< video_open() returns 0.\\n\");\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'USB: fix DoS in pwc USB video driver\n\nthe pwc driver has a disconnect method that waits for user space to\nclose the device. This opens up an opportunity for a DoS attack,\nblocking the USB subsystem and making khubd's task busy wait in\nkernel space. This patch shifts freeing resources to close if an opened\ndevice is disconnected.\n\nSigned-off-by: Oliver Neukum \nCC: stable \nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int pwc_video_mmap(struct file *file, struct vm_area_struct *vma)\n{\n\tstruct video_device *vdev = file->private_data;\n\tstruct pwc_device *pdev;\n\tunsigned long start;\n\tunsigned long size;\n\tunsigned long page, pos = 0;\n\tint index;\n\n\tPWC_DEBUG_MEMORY(\">> %s\\n\", __FUNCTION__);\n\tpdev = vdev->priv;\n\tsize = vma->vm_end - vma->vm_start;\n\tstart = vma->vm_start;\n\n\t/* Find the idx buffer for this mapping */\n\tfor (index = 0; index < pwc_mbufs; index++) {\n\t\tpos = pdev->images[index].offset;\n\t\tif ((pos>>PAGE_SHIFT) == vma->vm_pgoff)\n\t\t\tbreak;\n\t}\n\tif (index == MAX_IMAGES)\n\t\treturn -EINVAL;\n\tif (index == 0) {\n\t\t/*\n\t\t * Special case for v4l1. In v4l1, we map only one big buffer,\n\t\t * but in v4l2 each buffer is mapped\n\t\t */\n\t\tunsigned long total_size;\n\t\ttotal_size = pwc_mbufs * pdev->len_per_image;\n\t\tif (size != pdev->len_per_image && size != total_size) {\n\t\t\tPWC_ERROR(\"Wrong size (%lu) needed to be len_per_image=%d or total_size=%lu\\n\",\n\t\t\t\t size, pdev->len_per_image, total_size);\n\t\t\treturn -EINVAL;\n\t\t}\n\t} else if (size > pdev->len_per_image)\n\t\treturn -EINVAL;\n\n\tvma->vm_flags |= VM_IO;\t/* from 2.6.9-acX */\n\n\tpos += (unsigned long)pdev->image_data;\n\twhile (size > 0) {\n\t\tpage = vmalloc_to_pfn((void *)pos);\n\t\tif (remap_pfn_range(vma, start, page, PAGE_SIZE, PAGE_SHARED))\n\t\t\treturn -EAGAIN;\n\t\tstart += PAGE_SIZE;\n\t\tpos += PAGE_SIZE;\n\t\tif (size > PAGE_SIZE)\n\t\t\tsize -= PAGE_SIZE;\n\t\telse\n\t\t\tsize = 0;\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'USB: fix DoS in pwc USB video driver\n\nthe pwc driver has a disconnect method that waits for user space to\nclose the device. This opens up an opportunity for a DoS attack,\nblocking the USB subsystem and making khubd's task busy wait in\nkernel space. This patch shifts freeing resources to close if an opened\ndevice is disconnected.\n\nSigned-off-by: Oliver Neukum \nCC: stable \nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void pwc_remove_sysfs_files(struct video_device *vdev)\n{\n\tstruct pwc_device *pdev = video_get_drvdata(vdev);\n\tif (pdev->features & FEATURE_MOTOR_PANTILT)\n\t\tvideo_device_remove_file(vdev, &class_device_attr_pan_tilt);\n\tvideo_device_remove_file(vdev, &class_device_attr_button);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'USB: fix DoS in pwc USB video driver\n\nthe pwc driver has a disconnect method that waits for user space to\nclose the device. This opens up an opportunity for a DoS attack,\nblocking the USB subsystem and making khubd's task busy wait in\nkernel space. This patch shifts freeing resources to close if an opened\ndevice is disconnected.\n\nSigned-off-by: Oliver Neukum \nCC: stable \nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static const char *pwc_sensor_type_to_string(unsigned int sensor_type)\n{\n\tswitch(sensor_type) {\n\t\tcase 0x00:\n\t\t\treturn \"Hyundai CMOS sensor\";\n\t\tcase 0x20:\n\t\t\treturn \"Sony CCD sensor + TDA8787\";\n\t\tcase 0x2E:\n\t\t\treturn \"Sony CCD sensor + Exas 98L59\";\n\t\tcase 0x2F:\n\t\t\treturn \"Sony CCD sensor + ADI 9804\";\n\t\tcase 0x30:\n\t\t\treturn \"Sharp CCD sensor + TDA8787\";\n\t\tcase 0x3E:\n\t\t\treturn \"Sharp CCD sensor + Exas 98L59\";\n\t\tcase 0x3F:\n\t\t\treturn \"Sharp CCD sensor + ADI 9804\";\n\t\tcase 0x40:\n\t\t\treturn \"UPA 1021 sensor\";\n\t\tcase 0x100:\n\t\t\treturn \"VGA sensor\";\n\t\tcase 0x101:\n\t\t\treturn \"PAL MR sensor\";\n\t\tdefault:\n\t\t\treturn \"unknown type of sensor\";\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-399'], 'message': 'USB: fix DoS in pwc USB video driver\n\nthe pwc driver has a disconnect method that waits for user space to\nclose the device. This opens up an opportunity for a DoS attack,\nblocking the USB subsystem and making khubd's task busy wait in\nkernel space. This patch shifts freeing resources to close if an opened\ndevice is disconnected.\n\nSigned-off-by: Oliver Neukum \nCC: stable \nSigned-off-by: Greg Kroah-Hartman '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: void flush_hash_range(unsigned long number, int local)\n{\n\tif (ppc_md.flush_hash_range)\n\t\tppc_md.flush_hash_range(number, local);\n\telse {\n\t\tint i;\n\t\tstruct ppc64_tlb_batch *batch =\n\t\t\t&__get_cpu_var(ppc64_tlb_batch);\n\n\t\tfor (i = 0; i < number; i++)\n\t\t\tflush_hash_page(batch->vaddr[i], batch->pte[i],\n\t\t\t\t\tbatch->psize, local);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': '[POWERPC] Allow drivers to map individual 4k pages to userspace\n\nSome drivers have resources that they want to be able to map into\nuserspace that are 4k in size. On a kernel configured with 64k pages\nwe currently end up mapping the 4k we want plus another 60k of\nphysical address space, which could contain anything. This can\nintroduce security problems, for example in the case of an infiniband\nadaptor where the other 60k could contain registers that some other\nprogram is using for its communications.\n\nThis patch adds a new function, remap_4k_pfn, which drivers can use to\nmap a single 4k page to userspace regardless of whether the kernel is\nusing a 4k or a 64k page size. Like remap_pfn_range, it would\ntypically be called in a driver's mmap function. It only maps a\nsingle 4k page, which on a 64k page kernel appears replicated 16 times\nthroughout a 64k page. On a 4k page kernel it reduces to a call to\nremap_pfn_range.\n\nThe way this works on a 64k kernel is that a new bit, _PAGE_4K_PFN,\ngets set on the linux PTE. This alters the way that __hash_page_4K\ncomputes the real address to put in the HPTE. The RPN field of the\nlinux PTE becomes the 4k RPN directly rather than being interpreted as\na 64k RPN. Since the RPN field is 32 bits, this means that physical\naddresses being mapped with remap_4k_pfn have to be below 2^44,\ni.e. 0x100000000000.\n\nThe patch also factors out the code in arch/powerpc/mm/hash_utils_64.c\nthat deals with demoting a process to use 4k pages into one function\nthat gets called in the various different places where we need to do\nthat. There were some discrepancies between exactly what was done in\nthe various places, such as a call to spu_flush_all_slbs in one case\nbut not in others.\n\nSigned-off-by: Paul Mackerras '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int __init htab_dt_scan_pftsize(unsigned long node,\n\t\t\t\t const char *uname, int depth,\n\t\t\t\t void *data)\n{\n\tchar *type = of_get_flat_dt_prop(node, \"device_type\", NULL);\n\tu32 *prop;\n\n\t/* We are scanning \"cpu\" nodes only */\n\tif (type == NULL || strcmp(type, \"cpu\") != 0)\n\t\treturn 0;\n\n\tprop = (u32 *)of_get_flat_dt_prop(node, \"ibm,pft-size\", NULL);\n\tif (prop != NULL) {\n\t\t/* pft_size[0] is the NUMA CEC cookie */\n\t\tppc64_pft_size = prop[1];\n\t\treturn 1;\n\t}\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': '[POWERPC] Allow drivers to map individual 4k pages to userspace\n\nSome drivers have resources that they want to be able to map into\nuserspace that are 4k in size. On a kernel configured with 64k pages\nwe currently end up mapping the 4k we want plus another 60k of\nphysical address space, which could contain anything. This can\nintroduce security problems, for example in the case of an infiniband\nadaptor where the other 60k could contain registers that some other\nprogram is using for its communications.\n\nThis patch adds a new function, remap_4k_pfn, which drivers can use to\nmap a single 4k page to userspace regardless of whether the kernel is\nusing a 4k or a 64k page size. Like remap_pfn_range, it would\ntypically be called in a driver's mmap function. It only maps a\nsingle 4k page, which on a 64k page kernel appears replicated 16 times\nthroughout a 64k page. On a 4k page kernel it reduces to a call to\nremap_pfn_range.\n\nThe way this works on a 64k kernel is that a new bit, _PAGE_4K_PFN,\ngets set on the linux PTE. This alters the way that __hash_page_4K\ncomputes the real address to put in the HPTE. The RPN field of the\nlinux PTE becomes the 4k RPN directly rather than being interpreted as\na 64k RPN. Since the RPN field is 32 bits, this means that physical\naddresses being mapped with remap_4k_pfn have to be below 2^44,\ni.e. 0x100000000000.\n\nThe patch also factors out the code in arch/powerpc/mm/hash_utils_64.c\nthat deals with demoting a process to use 4k pages into one function\nthat gets called in the various different places where we need to do\nthat. There were some discrepancies between exactly what was done in\nthe various places, such as a call to spu_flush_all_slbs in one case\nbut not in others.\n\nSigned-off-by: Paul Mackerras '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ieee80211_rx_frame_mgmt(struct ieee80211_device *ieee, struct sk_buff *skb,\n\t\t\tstruct ieee80211_rx_stats *rx_stats, u16 type,\n\t\t\tu16 stype)\n{\n\tif (ieee->iw_mode == IW_MODE_MASTER) {\n\t\tprintk(KERN_DEBUG \"%s: Master mode not yet suppported.\\n\",\n\t\t ieee->dev->name);\n\t\treturn 0;\n/*\n hostap_update_sta_ps(ieee, (struct hostap_ieee80211_hdr_4addr *)\n skb->data);*/\n\t}\n\n\tif (ieee->hostapd && type == WLAN_FC_TYPE_MGMT) {\n\t\tif (stype == WLAN_FC_STYPE_BEACON &&\n\t\t ieee->iw_mode == IW_MODE_MASTER) {\n\t\t\tstruct sk_buff *skb2;\n\t\t\t/* Process beacon frames also in kernel driver to\n\t\t\t * update STA(AP) table statistics */\n\t\t\tskb2 = skb_clone(skb, GFP_ATOMIC);\n\t\t\tif (skb2)\n\t\t\t\thostap_rx(skb2->dev, skb2, rx_stats);\n\t\t}\n\n\t\t/* send management frames to the user space daemon for\n\t\t * processing */\n\t\tieee->apdevstats.rx_packets++;\n\t\tieee->apdevstats.rx_bytes += skb->len;\n\t\tprism2_rx_80211(ieee->apdev, skb, rx_stats, PRISM2_RX_MGMT);\n\t\treturn 0;\n\t}\n\n\tif (ieee->iw_mode == IW_MODE_MASTER) {\n\t\tif (type != WLAN_FC_TYPE_MGMT && type != WLAN_FC_TYPE_CTRL) {\n\t\t\tprintk(KERN_DEBUG \"%s: unknown management frame \"\n\t\t\t \"(type=0x%02x, stype=0x%02x) dropped\\n\",\n\t\t\t skb->dev->name, type, stype);\n\t\t\treturn -1;\n\t\t}\n\n\t\thostap_rx(skb->dev, skb, rx_stats);\n\t\treturn 0;\n\t}\n\n\tprintk(KERN_DEBUG \"%s: hostap_rx_frame_mgmt: management frame \"\n\t \"received in non-Host AP mode\\n\", skb->dev->name);\n\treturn -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': '[IEEE80211]: avoid integer underflow for runt rx frames\n\nReported by Chris Evans :\n\n> The summary is that an evil 80211 frame can crash out a victim's\n> machine. It only applies to drivers using the 80211 wireless code, and\n> only then to certain drivers (and even then depends on a card's\n> firmware not dropping a dubious packet). I must confess I'm not\n> keeping track of Linux wireless support, and the different protocol\n> stacks etc.\n>\n> Details are as follows:\n>\n> ieee80211_rx() does not explicitly check that \"skb->len >= hdrlen\".\n> There are other skb->len checks, but not enough to prevent a subtle\n> off-by-two error if the frame has the IEEE80211_STYPE_QOS_DATA flag\n> set.\n>\n> This leads to integer underflow and crash here:\n>\n> if (frag != 0)\n> flen -= hdrlen;\n>\n> (flen is subsequently used as a memcpy length parameter).\n\nHow about this?\n\nSigned-off-by: John W. Linville \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int ieee80211_read_qos_info_element(struct\n\t\t\t\t\t ieee80211_qos_information_element\n\t\t\t\t\t *element_info, struct ieee80211_info_element\n\t\t\t\t\t *info_element)\n{\n\tint ret = 0;\n\tu16 size = sizeof(struct ieee80211_qos_information_element) - 2;\n\n\tif (element_info == NULL)\n\t\treturn -1;\n\tif (info_element == NULL)\n\t\treturn -1;\n\n\tif ((info_element->id == QOS_ELEMENT_ID) && (info_element->len == size)) {\n\t\tmemcpy(element_info->qui, info_element->data,\n\t\t info_element->len);\n\t\telement_info->elementID = info_element->id;\n\t\telement_info->length = info_element->len;\n\t} else\n\t\tret = -1;\n\n\tif (ret == 0)\n\t\tret = ieee80211_verify_qos_info(element_info,\n\t\t\t\t\t\tQOS_OUI_INFO_SUB_TYPE);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': '[IEEE80211]: avoid integer underflow for runt rx frames\n\nReported by Chris Evans :\n\n> The summary is that an evil 80211 frame can crash out a victim's\n> machine. It only applies to drivers using the 80211 wireless code, and\n> only then to certain drivers (and even then depends on a card's\n> firmware not dropping a dubious packet). I must confess I'm not\n> keeping track of Linux wireless support, and the different protocol\n> stacks etc.\n>\n> Details are as follows:\n>\n> ieee80211_rx() does not explicitly check that \"skb->len >= hdrlen\".\n> There are other skb->len checks, but not enough to prevent a subtle\n> off-by-two error if the frame has the IEEE80211_STYPE_QOS_DATA flag\n> set.\n>\n> This leads to integer underflow and crash here:\n>\n> if (frag != 0)\n> flen -= hdrlen;\n>\n> (flen is subsequently used as a memcpy length parameter).\n\nHow about this?\n\nSigned-off-by: John W. Linville \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: isdn_net_new(char *name, struct net_device *master)\n{\n\tisdn_net_dev *netdev;\n\n\t/* Avoid creating an existing interface */\n\tif (isdn_net_findif(name)) {\n\t\tprintk(KERN_WARNING \"isdn_net: interface %s already exists\\n\", name);\n\t\treturn NULL;\n\t}\n\tif (name == NULL)\n\t\treturn NULL;\n\tif (!(netdev = kzalloc(sizeof(isdn_net_dev), GFP_KERNEL))) {\n\t\tprintk(KERN_WARNING \"isdn_net: Could not allocate net-device\\n\");\n\t\treturn NULL;\n\t}\n\tnetdev->dev = alloc_netdev(sizeof(isdn_net_local), name, _isdn_setup);\n\tif (!netdev->dev) {\n\t\tprintk(KERN_WARNING \"isdn_net: Could not allocate network device\\n\");\n\t\tkfree(netdev);\n\t\treturn NULL;\n\t}\n\tnetdev->local = netdev->dev->priv;\n\tnetdev->dev->init = isdn_net_init;\n\tif (master) {\n\t\t/* Device shall be a slave */\n\t\tstruct net_device *p = (((isdn_net_local *) master->priv)->slave);\n\t\tstruct net_device *q = master;\n\n\t\tnetdev->local->master = master;\n\t\t/* Put device at end of slave-chain */\n\t\twhile (p) {\n\t\t\tq = p;\n\t\t\tp = (((isdn_net_local *) p->priv)->slave);\n\t\t}\n\t\t((isdn_net_local *) q->priv)->slave = netdev->dev;\n\t} else {\n\t\t/* Device shall be a master */\n\t\t/*\n\t\t * Watchdog timer (currently) for master only.\n\t\t */\n\t\tnetdev->dev->tx_timeout = isdn_net_tx_timeout;\n\t\tnetdev->dev->watchdog_timeo = ISDN_NET_TX_TIMEOUT;\n\t\tif (register_netdev(netdev->dev) != 0) {\n\t\t\tprintk(KERN_WARNING \"isdn_net: Could not register net-device\\n\");\n\t\t\tfree_netdev(netdev->dev);\n\t\t\tkfree(netdev);\n\t\t\treturn NULL;\n\t\t}\n\t}\n\tnetdev->queue = netdev->local;\n\tspin_lock_init(&netdev->queue_lock);\n\n\tnetdev->local->netdev = netdev;\n\n\tINIT_WORK(&netdev->local->tqueue, isdn_net_softint);\n\tspin_lock_init(&netdev->local->xmit_lock);\n\n\t/* Put into to netdev-chain */\n\tnetdev->next = (void *) dev->netdev;\n\tdev->netdev = netdev;\n\treturn netdev->dev->name;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'isdn: avoid copying overly-long strings\n\nAddresses http://bugzilla.kernel.org/show_bug.cgi?id=9416\n\nSigned-off-by: Karsten Keil \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static __inline__ void isdn_net_inc_frame_cnt(isdn_net_local *lp)\n{\n\tatomic_inc(&lp->frame_cnt);\n\tif (isdn_net_device_busy(lp))\n\t\tisdn_net_device_stop_queue(lp);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'isdn: avoid copying overly-long strings\n\nAddresses http://bugzilla.kernel.org/show_bug.cgi?id=9416\n\nSigned-off-by: Karsten Keil \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: isdn_net_reset(struct net_device *dev)\n{\n#ifdef CONFIG_ISDN_X25\n\tstruct concap_device_ops * dops =\n\t\t( (isdn_net_local *) dev->priv ) -> dops;\n\tstruct concap_proto * cprot =\n\t\t( (isdn_net_local *) dev->priv ) -> netdev -> cprot;\n#endif\n#ifdef CONFIG_ISDN_X25\n\tif( cprot && cprot -> pops && dops )\n\t\tcprot -> pops -> restart ( cprot, dev, dops );\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'isdn: avoid copying overly-long strings\n\nAddresses http://bugzilla.kernel.org/show_bug.cgi?id=9416\n\nSigned-off-by: Karsten Keil \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int isdn_header_cache(const struct neighbour *neigh, struct hh_cache *hh)\n{\n\tconst struct net_device *dev = neigh->dev;\n\tisdn_net_local *lp = dev->priv;\n\n\tif (lp->p_encap == ISDN_NET_ENCAP_ETHER)\n\t\treturn eth_header_cache(neigh, hh);\n\treturn -1;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'isdn: avoid copying overly-long strings\n\nAddresses http://bugzilla.kernel.org/show_bug.cgi?id=9416\n\nSigned-off-by: Karsten Keil \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: isdn_net_ciscohdlck_receive(isdn_net_local *lp, struct sk_buff *skb)\n{\n\tunsigned char *p;\n \tu8 addr;\n \tu8 ctrl;\n \tu16 type;\n\t\n\tif (skb->len < 4)\n\t\tgoto out_free;\n\n\tp = skb->data;\n\tp += get_u8 (p, &addr);\n\tp += get_u8 (p, &ctrl);\n\tp += get_u16(p, &type);\n\tskb_pull(skb, 4);\n\t\n\tif (addr != CISCO_ADDR_UNICAST && addr != CISCO_ADDR_BROADCAST) {\n\t\tprintk(KERN_WARNING \"%s: Unknown Cisco addr 0x%02x\\n\",\n\t\t lp->netdev->dev->name, addr);\n\t\tgoto out_free;\n\t}\n\tif (ctrl != CISCO_CTRL) {\n\t\tprintk(KERN_WARNING \"%s: Unknown Cisco ctrl 0x%02x\\n\",\n\t\t lp->netdev->dev->name, ctrl);\n\t\tgoto out_free;\n\t}\n\n\tswitch (type) {\n\tcase CISCO_TYPE_SLARP:\n\t\tisdn_net_ciscohdlck_slarp_in(lp, skb);\n\t\tgoto out_free;\n\tcase CISCO_TYPE_CDP:\n\t\tif (lp->cisco_debserint)\n\t\t\tprintk(KERN_DEBUG \"%s: Received CDP packet. use \"\n\t\t\t\t\"\\\"no cdp enable\\\" on cisco.\\n\",\n\t\t\t\tlp->netdev->dev->name);\n\t\tgoto out_free;\n\tdefault:\n\t\t/* no special cisco protocol */\n\t\tskb->protocol = htons(type);\n\t\tnetif_rx(skb);\n\t\treturn;\n\t}\n\n out_free:\n\tkfree_skb(skb);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'isdn: avoid copying overly-long strings\n\nAddresses http://bugzilla.kernel.org/show_bug.cgi?id=9416\n\nSigned-off-by: Karsten Keil \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: isdn_net_force_dial_lp(isdn_net_local * lp)\n{\n\tif ((!(lp->flags & ISDN_NET_CONNECTED)) && !lp->dialstate) {\n\t\tint chi;\n\t\tif (lp->phone[1]) {\n\t\t\tulong flags;\n\n\t\t\t/* Grab a free ISDN-Channel */\n\t\t\tspin_lock_irqsave(&dev->lock, flags);\n\t\t\tif ((chi = isdn_get_free_channel(\n\t\t\t\t\tISDN_USAGE_NET,\n\t\t\t\t\tlp->l2_proto,\n\t\t\t\t\tlp->l3_proto,\n\t\t\t\t\tlp->pre_device,\n\t\t\t\t\tlp->pre_channel,\n\t\t\t\t\tlp->msn)) < 0) {\n\t\t\t\tprintk(KERN_WARNING \"isdn_net_force_dial: No channel for %s\\n\",\n\t\t\t\t\tlp->netdev->dev->name);\n\t\t\t\tspin_unlock_irqrestore(&dev->lock, flags);\n\t\t\t\treturn -EAGAIN;\n\t\t\t}\n\t\t\tlp->dialstate = 1;\n\t\t\t/* Connect interface with channel */\n\t\t\tisdn_net_bind_channel(lp, chi);\n#ifdef CONFIG_ISDN_PPP\n\t\t\tif (lp->p_encap == ISDN_NET_ENCAP_SYNCPPP)\n\t\t\t\tif (isdn_ppp_bind(lp) < 0) {\n\t\t\t\t\tisdn_net_unbind_channel(lp);\n\t\t\t\t\tspin_unlock_irqrestore(&dev->lock, flags);\n\t\t\t\t\treturn -EAGAIN;\n\t\t\t\t}\n#endif\n\t\t\t/* Initiate dialing */\n\t\t\tspin_unlock_irqrestore(&dev->lock, flags);\n\t\t\tisdn_net_dial();\n\t\t\treturn 0;\n\t\t} else\n\t\t\treturn -EINVAL;\n\t} else\n\t\treturn -EBUSY;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'isdn: avoid copying overly-long strings\n\nAddresses http://bugzilla.kernel.org/show_bug.cgi?id=9416\n\nSigned-off-by: Karsten Keil \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int esp6_output(struct xfrm_state *x, struct sk_buff *skb)\n{\n\tint err;\n\tstruct ip_esp_hdr *esph;\n\tstruct crypto_aead *aead;\n\tstruct aead_givcrypt_request *req;\n\tstruct scatterlist *sg;\n\tstruct scatterlist *asg;\n\tstruct sk_buff *trailer;\n\tvoid *tmp;\n\tint blksize;\n\tint clen;\n\tint alen;\n\tint nfrags;\n\tu8 *iv;\n\tu8 *tail;\n\tstruct esp_data *esp = x->data;\n\n\t/* skb is pure payload to encrypt */\n\terr = -ENOMEM;\n\n\t/* Round to block size */\n\tclen = skb->len;\n\n\taead = esp->aead;\n\talen = crypto_aead_authsize(aead);\n\n\tblksize = ALIGN(crypto_aead_blocksize(aead), 4);\n\tclen = ALIGN(clen + 2, blksize);\n\tif (esp->padlen)\n\t\tclen = ALIGN(clen, esp->padlen);\n\n\tif ((err = skb_cow_data(skb, clen - skb->len + alen, &trailer)) < 0)\n\t\tgoto error;\n\tnfrags = err;\n\n\ttmp = esp_alloc_tmp(aead, nfrags + 1);\n\tif (!tmp)\n\t\tgoto error;\n\n\tiv = esp_tmp_iv(aead, tmp);\n\treq = esp_tmp_givreq(aead, iv);\n\tasg = esp_givreq_sg(aead, req);\n\tsg = asg + 1;\n\n\t/* Fill padding... */\n\ttail = skb_tail_pointer(trailer);\n\tdo {\n\t\tint i;\n\t\tfor (i=0; ilen - 2; i++)\n\t\t\ttail[i] = i + 1;\n\t} while (0);\n\ttail[clen-skb->len - 2] = (clen - skb->len) - 2;\n\ttail[clen - skb->len - 1] = *skb_mac_header(skb);\n\tpskb_put(skb, trailer, clen - skb->len + alen);\n\n\tskb_push(skb, -skb_network_offset(skb));\n\tesph = ip_esp_hdr(skb);\n\t*skb_mac_header(skb) = IPPROTO_ESP;\n\n\tesph->spi = x->id.spi;\n\tesph->seq_no = htonl(XFRM_SKB_CB(skb)->seq.output);\n\n\tsg_init_table(sg, nfrags);\n\tskb_to_sgvec(skb, sg,\n\t\t esph->enc_data + crypto_aead_ivsize(aead) - skb->data,\n\t\t clen + alen);\n\tsg_init_one(asg, esph, sizeof(*esph));\n\n\taead_givcrypt_set_callback(req, 0, esp_output_done, skb);\n\taead_givcrypt_set_crypt(req, sg, sg, clen, iv);\n\taead_givcrypt_set_assoc(req, asg, sizeof(*esph));\n\taead_givcrypt_set_giv(req, esph->enc_data,\n\t\t\t XFRM_SKB_CB(skb)->seq.output);\n\n\tESP_SKB_CB(skb)->tmp = tmp;\n\terr = crypto_aead_givencrypt(req);\n\tif (err == -EINPROGRESS)\n\t\tgoto error;\n\n\tif (err == -EBUSY)\n\t\terr = NET_XMIT_DROP;\n\n\tkfree(tmp);\n\nerror:\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-16'], 'message': '[ESP]: Ensure IV is in linear part of the skb to avoid BUG() due to OOB access\n\nESP does not account for the IV size when calling pskb_may_pull() to\nensure everything it accesses directly is within the linear part of a\npotential fragment. This results in a BUG() being triggered when the\nboth the IPv4 and IPv6 ESP stack is fed with an skb where the first\nfragment ends between the end of the esp header and the end of the IV.\n\nThis bug was found by Dirk Nehring .\n\nSigned-off-by: Thomas Graf \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline struct scatterlist *esp_req_sg(struct crypto_aead *aead,\n\t\t\t\t\t struct aead_request *req)\n{\n\treturn (void *)ALIGN((unsigned long)(req + 1) +\n\t\t\t crypto_aead_reqsize(aead),\n\t\t\t __alignof__(struct scatterlist));\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-16'], 'message': '[ESP]: Ensure IV is in linear part of the skb to avoid BUG() due to OOB access\n\nESP does not account for the IV size when calling pskb_may_pull() to\nensure everything it accesses directly is within the linear part of a\npotential fragment. This results in a BUG() being triggered when the\nboth the IPv4 and IPv6 ESP stack is fed with an skb where the first\nfragment ends between the end of the esp header and the end of the IV.\n\nThis bug was found by Dirk Nehring .\n\nSigned-off-by: Thomas Graf \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int esp_input_done2(struct sk_buff *skb, int err)\n{\n\tstruct iphdr *iph;\n\tstruct xfrm_state *x = xfrm_input_state(skb);\n\tstruct esp_data *esp = x->data;\n\tstruct crypto_aead *aead = esp->aead;\n\tint alen = crypto_aead_authsize(aead);\n\tint hlen = sizeof(struct ip_esp_hdr) + crypto_aead_ivsize(aead);\n\tint elen = skb->len - hlen;\n\tint ihl;\n\tu8 nexthdr[2];\n\tint padlen;\n\n\tkfree(ESP_SKB_CB(skb)->tmp);\n\n\tif (unlikely(err))\n\t\tgoto out;\n\n\tif (skb_copy_bits(skb, skb->len-alen-2, nexthdr, 2))\n\t\tBUG();\n\n\terr = -EINVAL;\n\tpadlen = nexthdr[0];\n\tif (padlen + 2 + alen >= elen)\n\t\tgoto out;\n\n\t/* ... check padding bits here. Silly. :-) */\n\n\tiph = ip_hdr(skb);\n\tihl = iph->ihl * 4;\n\n\tif (x->encap) {\n\t\tstruct xfrm_encap_tmpl *encap = x->encap;\n\t\tstruct udphdr *uh = (void *)(skb_network_header(skb) + ihl);\n\n\t\t/*\n\t\t * 1) if the NAT-T peer's IP or port changed then\n\t\t * advertize the change to the keying daemon.\n\t\t * This is an inbound SA, so just compare\n\t\t * SRC ports.\n\t\t */\n\t\tif (iph->saddr != x->props.saddr.a4 ||\n\t\t uh->source != encap->encap_sport) {\n\t\t\txfrm_address_t ipaddr;\n\n\t\t\tipaddr.a4 = iph->saddr;\n\t\t\tkm_new_mapping(x, &ipaddr, uh->source);\n\n\t\t\t/* XXX: perhaps add an extra\n\t\t\t * policy check here, to see\n\t\t\t * if we should allow or\n\t\t\t * reject a packet from a\n\t\t\t * different source\n\t\t\t * address/port.\n\t\t\t */\n\t\t}\n\n\t\t/*\n\t\t * 2) ignore UDP/TCP checksums in case\n\t\t * of NAT-T in Transport Mode, or\n\t\t * perform other post-processing fixes\n\t\t * as per draft-ietf-ipsec-udp-encaps-06,\n\t\t * section 3.1.2\n\t\t */\n\t\tif (x->props.mode == XFRM_MODE_TRANSPORT)\n\t\t\tskb->ip_summed = CHECKSUM_UNNECESSARY;\n\t}\n\n\tpskb_trim(skb, skb->len - alen - padlen - 2);\n\t__skb_pull(skb, hlen);\n\tskb_set_transport_header(skb, -ihl);\n\n\terr = nexthdr[1];\n\n\t/* RFC4303: Drop dummy packets without any error */\n\tif (err == IPPROTO_NONE)\n\t\terr = -EINVAL;\n\nout:\n\treturn err;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-16'], 'message': '[ESP]: Ensure IV is in linear part of the skb to avoid BUG() due to OOB access\n\nESP does not account for the IV size when calling pskb_may_pull() to\nensure everything it accesses directly is within the linear part of a\npotential fragment. This results in a BUG() being triggered when the\nboth the IPv4 and IPv6 ESP stack is fed with an skb where the first\nfragment ends between the end of the esp header and the end of the IV.\n\nThis bug was found by Dirk Nehring .\n\nSigned-off-by: Thomas Graf \nSigned-off-by: David S. Miller '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: isdn_lock_drivers(void)\n{\n\tint i;\n\n\tfor (i = 0; i < ISDN_MAX_DRIVERS; i++) {\n\t\tif (!dev->drv[i])\n\t\t\tcontinue;\n\t\tisdn_lock_driver(dev->drv[i]);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'I4L: fix isdn_ioctl memory overrun vulnerability\n\nFix possible memory overrun issue in the isdn ioctl code.\n\nFound by ADLAB \n\nSigned-off-by: Karsten Keil \nCc: ADLAB \nCc: \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: isdn_writebuf_skb_stub(int drvidx, int chan, int ack, struct sk_buff *skb)\n{\n\tint ret;\n\tstruct sk_buff *nskb = NULL;\n\tint v110_ret = skb->len;\n\tint idx = isdn_dc2minor(drvidx, chan);\n\n\tif (dev->v110[idx]) {\n\t\tatomic_inc(&dev->v110use[idx]);\n\t\tnskb = isdn_v110_encode(dev->v110[idx], skb);\n\t\tatomic_dec(&dev->v110use[idx]);\n\t\tif (!nskb)\n\t\t\treturn 0;\n\t\tv110_ret = *((int *)nskb->data);\n\t\tskb_pull(nskb, sizeof(int));\n\t\tif (!nskb->len) {\n\t\t\tdev_kfree_skb(nskb);\n\t\t\treturn v110_ret;\n\t\t}\n\t\t/* V.110 must always be acknowledged */\n\t\tack = 1;\n\t\tret = dev->drv[drvidx]->interface->writebuf_skb(drvidx, chan, ack, nskb);\n\t} else {\n\t\tint hl = dev->drv[drvidx]->interface->hl_hdrlen;\n\n\t\tif( skb_headroom(skb) < hl ){\n\t\t\t/* \n\t\t\t * This should only occur when new HL driver with\n\t\t\t * increased hl_hdrlen was loaded after netdevice\n\t\t\t * was created and connected to the new driver.\n\t\t\t *\n\t\t\t * The V.110 branch (re-allocates on its own) does\n\t\t\t * not need this\n\t\t\t */\n\t\t\tstruct sk_buff * skb_tmp;\n\n\t\t\tskb_tmp = skb_realloc_headroom(skb, hl);\n\t\t\tprintk(KERN_DEBUG \"isdn_writebuf_skb_stub: reallocating headroom%s\\n\", skb_tmp ? \"\" : \" failed\");\n\t\t\tif (!skb_tmp) return -ENOMEM; /* 0 better? */\n\t\t\tret = dev->drv[drvidx]->interface->writebuf_skb(drvidx, chan, ack, skb_tmp);\n\t\t\tif( ret > 0 ){\n\t\t\t\tdev_kfree_skb(skb);\n\t\t\t} else {\n\t\t\t\tdev_kfree_skb(skb_tmp);\n\t\t\t}\n\t\t} else {\n\t\t\tret = dev->drv[drvidx]->interface->writebuf_skb(drvidx, chan, ack, skb);\n\t\t}\n\t}\n\tif (ret > 0) {\n\t\tdev->obytes[idx] += ret;\n\t\tif (dev->v110[idx]) {\n\t\t\tatomic_inc(&dev->v110use[idx]);\n\t\t\tdev->v110[idx]->skbuser++;\n\t\t\tatomic_dec(&dev->v110use[idx]);\n\t\t\t/* For V.110 return unencoded data length */\n\t\t\tret = v110_ret;\n\t\t\t/* if the complete frame was send we free the skb;\n\t\t\t if not upper function will requeue the skb */ \n\t\t\tif (ret == skb->len)\n\t\t\t\tdev_kfree_skb(skb);\n\t\t}\n\t} else\n\t\tif (dev->v110[idx])\n\t\t\tdev_kfree_skb(nskb);\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'I4L: fix isdn_ioctl memory overrun vulnerability\n\nFix possible memory overrun issue in the isdn ioctl code.\n\nFound by ADLAB \n\nSigned-off-by: Karsten Keil \nCc: ADLAB \nCc: \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: isdn_all_eaz(int di, int ch)\n{\n\tisdn_ctrl cmd;\n\n\tif (di < 0)\n\t\treturn;\n\tcmd.driver = di;\n\tcmd.arg = ch;\n\tcmd.command = ISDN_CMD_SETEAZ;\n\tcmd.parm.num[0] = '\\0';\n\tisdn_command(&cmd);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'I4L: fix isdn_ioctl memory overrun vulnerability\n\nFix possible memory overrun issue in the isdn ioctl code.\n\nFound by ADLAB \n\nSigned-off-by: Karsten Keil \nCc: ADLAB \nCc: \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: isdn_wildmat(char *s, char *p)\n{\n\tregister int last;\n\tregister int matched;\n\tregister int reverse;\n\tregister int nostar = 1;\n\n\tif (!(*s) && !(*p))\n\t\treturn(1);\n\tfor (; *p; s++, p++)\n\t\tswitch (*p) {\n\t\t\tcase '\\\\':\n\t\t\t\t/*\n\t\t\t\t * Literal match with following character,\n\t\t\t\t * fall through.\n\t\t\t\t */\n\t\t\t\tp++;\n\t\t\tdefault:\n\t\t\t\tif (*s != *p)\n\t\t\t\t\treturn (*s == '\\0')?2:1;\n\t\t\t\tcontinue;\n\t\t\tcase '?':\n\t\t\t\t/* Match anything. */\n\t\t\t\tif (*s == '\\0')\n\t\t\t\t\treturn (2);\n\t\t\t\tcontinue;\n\t\t\tcase '*':\n\t\t\t\tnostar = 0;\t\n\t\t\t\t/* Trailing star matches everything. */\n\t\t\t\treturn (*++p ? isdn_star(s, p) : 0);\n\t\t\tcase '[':\n\t\t\t\t/* [^....] means inverse character class. */\n\t\t\t\tif ((reverse = (p[1] == '^')))\n\t\t\t\t\tp++;\n\t\t\t\tfor (last = 0, matched = 0; *++p && (*p != ']'); last = *p)\n\t\t\t\t\t/* This next line requires a good C compiler. */\n\t\t\t\t\tif (*p == '-' ? *s <= *++p && *s >= last : *s == *p)\n\t\t\t\t\t\tmatched = 1;\n\t\t\t\tif (matched == reverse)\n\t\t\t\t\treturn (1);\n\t\t\t\tcontinue;\n\t\t}\n\treturn (*s == '\\0')?0:nostar;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-119'], 'message': 'I4L: fix isdn_ioctl memory overrun vulnerability\n\nFix possible memory overrun issue in the isdn ioctl code.\n\nFound by ADLAB \n\nSigned-off-by: Karsten Keil \nCc: ADLAB \nCc: \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void *shmem_follow_link(struct dentry *dentry, struct nameidata *nd)\n{\n\tstruct page *page = NULL;\n\tint res = shmem_getpage(dentry->d_inode, 0, &page, SGP_READ, NULL);\n\tnd_set_link(nd, res ? ERR_PTR(res) : kmap(page));\n\treturn page;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'tmpfs: restore missing clear_highpage\n\ntmpfs was misconverted to __GFP_ZERO in 2.6.11. There's an unusual case in\nwhich shmem_getpage receives the page from its caller instead of allocating.\nWe must cover this case by clear_highpage before SetPageUptodate, as before.\n\nSigned-off-by: Hugh Dickins \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline int shmem_acct_size(unsigned long flags, loff_t size)\n{\n\treturn (flags & VM_ACCOUNT)?\n\t\tsecurity_vm_enough_memory(VM_ACCT(size)): 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'tmpfs: restore missing clear_highpage\n\ntmpfs was misconverted to __GFP_ZERO in 2.6.11. There's an unusual case in\nwhich shmem_getpage receives the page from its caller instead of allocating.\nWe must cover this case by clear_highpage before SetPageUptodate, as before.\n\nSigned-off-by: Hugh Dickins \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void shmem_recalc_inode(struct inode *inode)\n{\n\tstruct shmem_inode_info *info = SHMEM_I(inode);\n\tlong freed;\n\n\tfreed = info->alloced - info->swapped - inode->i_mapping->nrpages;\n\tif (freed > 0) {\n\t\tinfo->alloced -= freed;\n\t\tshmem_unacct_blocks(info->flags, freed);\n\t\tshmem_free_blocks(inode, freed);\n\t}\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'tmpfs: restore missing clear_highpage\n\ntmpfs was misconverted to __GFP_ZERO in 2.6.11. There's an unusual case in\nwhich shmem_getpage receives the page from its caller instead of allocating.\nWe must cover this case by clear_highpage before SetPageUptodate, as before.\n\nSigned-off-by: Hugh Dickins \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static ssize_t shmem_file_read(struct file *filp, char __user *buf, size_t count, loff_t *ppos)\n{\n\tread_descriptor_t desc;\n\n\tif ((ssize_t) count < 0)\n\t\treturn -EINVAL;\n\tif (!access_ok(VERIFY_WRITE, buf, count))\n\t\treturn -EFAULT;\n\tif (!count)\n\t\treturn 0;\n\n\tdesc.written = 0;\n\tdesc.count = count;\n\tdesc.arg.buf = buf;\n\tdesc.error = 0;\n\n\tdo_shmem_file_read(filp, ppos, &desc, file_read_actor);\n\tif (desc.written)\n\t\treturn desc.written;\n\treturn desc.error;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'tmpfs: restore missing clear_highpage\n\ntmpfs was misconverted to __GFP_ZERO in 2.6.11. There's an unusual case in\nwhich shmem_getpage receives the page from its caller instead of allocating.\nWe must cover this case by clear_highpage before SetPageUptodate, as before.\n\nSigned-off-by: Hugh Dickins \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void shmem_truncate(struct inode *inode)\n{\n\tshmem_truncate_range(inode, inode->i_size, (loff_t)-1);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'tmpfs: restore missing clear_highpage\n\ntmpfs was misconverted to __GFP_ZERO in 2.6.11. There's an unusual case in\nwhich shmem_getpage receives the page from its caller instead of allocating.\nWe must cover this case by clear_highpage before SetPageUptodate, as before.\n\nSigned-off-by: Hugh Dickins \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int shmem_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry)\n{\n\tstruct inode *inode = old_dentry->d_inode;\n\tstruct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);\n\n\t/*\n\t * No ordinary (disk based) filesystem counts links as inodes;\n\t * but each new link needs a new dentry, pinning lowmem, and\n\t * tmpfs dentries cannot be pruned until they are unlinked.\n\t */\n\tif (sbinfo->max_inodes) {\n\t\tspin_lock(&sbinfo->stat_lock);\n\t\tif (!sbinfo->free_inodes) {\n\t\t\tspin_unlock(&sbinfo->stat_lock);\n\t\t\treturn -ENOSPC;\n\t\t}\n\t\tsbinfo->free_inodes--;\n\t\tspin_unlock(&sbinfo->stat_lock);\n\t}\n\n\tdir->i_size += BOGO_DIRENT_SIZE;\n\tinode->i_ctime = dir->i_ctime = dir->i_mtime = CURRENT_TIME;\n\tinc_nlink(inode);\n\tatomic_inc(&inode->i_count);\t/* New dentry reference */\n\tdget(dentry);\t\t/* Extra pinning count for the created dentry */\n\td_instantiate(dentry, inode);\n\treturn 0;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'tmpfs: restore missing clear_highpage\n\ntmpfs was misconverted to __GFP_ZERO in 2.6.11. There's an unusual case in\nwhich shmem_getpage receives the page from its caller instead of allocating.\nWe must cover this case by clear_highpage before SetPageUptodate, as before.\n\nSigned-off-by: Hugh Dickins \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static struct page *shmem_swapin_async(struct shared_policy *p,\n\t\t\t\t swp_entry_t entry, unsigned long idx)\n{\n\tstruct page *page;\n\tstruct vm_area_struct pvma;\n\n\t/* Create a pseudo vma that just contains the policy */\n\tmemset(&pvma, 0, sizeof(struct vm_area_struct));\n\tpvma.vm_end = PAGE_SIZE;\n\tpvma.vm_pgoff = idx;\n\tpvma.vm_policy = mpol_shared_policy_lookup(p, idx);\n\tpage = read_swap_cache_async(entry, &pvma, 0);\n\tmpol_free(pvma.vm_policy);\n\treturn page;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'tmpfs: restore missing clear_highpage\n\ntmpfs was misconverted to __GFP_ZERO in 2.6.11. There's an unusual case in\nwhich shmem_getpage receives the page from its caller instead of allocating.\nWe must cover this case by clear_highpage before SetPageUptodate, as before.\n\nSigned-off-by: Hugh Dickins \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static inline struct page *shmem_dir_alloc(gfp_t gfp_mask)\n{\n\t/*\n\t * The above definition of ENTRIES_PER_PAGE, and the use of\n\t * BLOCKS_PER_PAGE on indirect pages, assume PAGE_CACHE_SIZE:\n\t * might be reconsidered if it ever diverges from PAGE_SIZE.\n\t *\n\t * Mobility flags are masked out as swap vectors cannot move\n\t */\n\treturn alloc_pages((gfp_mask & ~GFP_MOVABLE_MASK) | __GFP_ZERO,\n\t\t\t\tPAGE_CACHE_SHIFT-PAGE_SHIFT);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-200'], 'message': 'tmpfs: restore missing clear_highpage\n\ntmpfs was misconverted to __GFP_ZERO in 2.6.11. There's an unusual case in\nwhich shmem_getpage receives the page from its caller instead of allocating.\nWe must cover this case by clear_highpage before SetPageUptodate, as before.\n\nSigned-off-by: Hugh Dickins \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: SProcShmGetImage(client)\n ClientPtr client;\n{\n register int n;\n REQUEST(xShmGetImageReq);\n swaps(&stuff->length, n);\n REQUEST_SIZE_MATCH(xShmGetImageReq);\n swapl(&stuff->drawable, n);\n swaps(&stuff->x, n);\n swaps(&stuff->y, n);\n swaps(&stuff->width, n);\n swaps(&stuff->height, n);\n swapl(&stuff->planeMask, n);\n swapl(&stuff->shmseg, n);\n swapl(&stuff->offset, n);\n return ProcShmGetImage(client);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'CVE-2007-6429: Always test for size+offset wrapping.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ProcShmCreatePixmap(client)\n register ClientPtr client;\n{\n PixmapPtr pMap;\n DrawablePtr pDraw;\n DepthPtr pDepth;\n register int i, rc;\n ShmDescPtr shmdesc;\n REQUEST(xShmCreatePixmapReq);\n unsigned int width, height, depth;\n unsigned long size;\n\n REQUEST_SIZE_MATCH(xShmCreatePixmapReq);\n client->errorValue = stuff->pid;\n if (!sharedPixmaps)\n\treturn BadImplementation;\n LEGAL_NEW_RESOURCE(stuff->pid, client);\n rc = dixLookupDrawable(&pDraw, stuff->drawable, client, M_ANY,\n\t\t\t DixGetAttrAccess);\n if (rc != Success)\n\treturn rc;\n\n VERIFY_SHMPTR(stuff->shmseg, stuff->offset, TRUE, shmdesc, client);\n \n width = stuff->width;\n height = stuff->height;\n depth = stuff->depth;\n if (!width || !height || !depth)\n {\n\tclient->errorValue = 0;\n return BadValue;\n }\n if (width > 32767 || height > 32767)\n\treturn BadAlloc;\n\n if (stuff->depth != 1)\n {\n pDepth = pDraw->pScreen->allowedDepths;\n for (i=0; ipScreen->numDepths; i++, pDepth++)\n\t if (pDepth->depth == stuff->depth)\n goto CreatePmap;\n\tclient->errorValue = stuff->depth;\n return BadValue;\n }\n\nCreatePmap:\n size = PixmapBytePad(width, depth) * height;\n if (sizeof(size) == 4 && BitsPerPixel(depth) > 8) {\n\tif (size < width * height)\n\t return BadAlloc;\n }\n /* thankfully, offset is unsigned */\n if (stuff->offset + size < size)\n\treturn BadAlloc;\n\n VERIFY_SHMSIZE(shmdesc, stuff->offset, size, client);\n pMap = (*shmFuncs[pDraw->pScreen->myNum]->CreatePixmap)(\n\t\t\t pDraw->pScreen, stuff->width,\n\t\t\t stuff->height, stuff->depth,\n\t\t\t shmdesc->addr + stuff->offset);\n if (pMap)\n {\n\trc = XaceHook(XACE_RESOURCE_ACCESS, client, stuff->pid, RT_PIXMAP,\n\t\t pMap, RT_NONE, NULL, DixCreateAccess);\n\tif (rc != Success) {\n\t pDraw->pScreen->DestroyPixmap(pMap);\n\t return rc;\n\t}\n\tdixSetPrivate(&pMap->devPrivates, shmPixmapPrivate, shmdesc);\n\tshmdesc->refcnt++;\n\tpMap->drawable.serialNumber = NEXT_SERIAL_NUMBER;\n\tpMap->drawable.id = stuff->pid;\n\tif (AddResource(stuff->pid, RT_PIXMAP, (pointer)pMap))\n\t{\n\t return(client->noClientException);\n\t}\n\tpDraw->pScreen->DestroyPixmap(pMap);\n }\n return (BadAlloc);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'CVE-2007-6429: Always test for size+offset wrapping.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: SProcShmPutImage(client)\n ClientPtr client;\n{\n register int n;\n REQUEST(xShmPutImageReq);\n swaps(&stuff->length, n);\n REQUEST_SIZE_MATCH(xShmPutImageReq);\n swapl(&stuff->drawable, n);\n swapl(&stuff->gc, n);\n swaps(&stuff->totalWidth, n);\n swaps(&stuff->totalHeight, n);\n swaps(&stuff->srcX, n);\n swaps(&stuff->srcY, n);\n swaps(&stuff->srcWidth, n);\n swaps(&stuff->srcHeight, n);\n swaps(&stuff->dstX, n);\n swaps(&stuff->dstY, n);\n swapl(&stuff->shmseg, n);\n swapl(&stuff->offset, n);\n return ProcShmPutImage(client);\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-189'], 'message': 'CVE-2007-6429: Always test for size+offset wrapping.'" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ssize_t splice_direct_to_actor(struct file *in, struct splice_desc *sd,\n\t\t\t splice_direct_actor *actor)\n{\n\tstruct pipe_inode_info *pipe;\n\tlong ret, bytes;\n\tumode_t i_mode;\n\tsize_t len;\n\tint i, flags;\n\n\t/*\n\t * We require the input being a regular file, as we don't want to\n\t * randomly drop data for eg socket -> socket splicing. Use the\n\t * piped splicing for that!\n\t */\n\ti_mode = in->f_path.dentry->d_inode->i_mode;\n\tif (unlikely(!S_ISREG(i_mode) && !S_ISBLK(i_mode)))\n\t\treturn -EINVAL;\n\n\t/*\n\t * neither in nor out is a pipe, setup an internal pipe attached to\n\t * 'out' and transfer the wanted data from 'in' to 'out' through that\n\t */\n\tpipe = current->splice_pipe;\n\tif (unlikely(!pipe)) {\n\t\tpipe = alloc_pipe_info(NULL);\n\t\tif (!pipe)\n\t\t\treturn -ENOMEM;\n\n\t\t/*\n\t\t * We don't have an immediate reader, but we'll read the stuff\n\t\t * out of the pipe right after the splice_to_pipe(). So set\n\t\t * PIPE_READERS appropriately.\n\t\t */\n\t\tpipe->readers = 1;\n\n\t\tcurrent->splice_pipe = pipe;\n\t}\n\n\t/*\n\t * Do the splice.\n\t */\n\tret = 0;\n\tbytes = 0;\n\tlen = sd->total_len;\n\tflags = sd->flags;\n\n\t/*\n\t * Don't block on output, we have to drain the direct pipe.\n\t */\n\tsd->flags &= ~SPLICE_F_NONBLOCK;\n\n\twhile (len) {\n\t\tsize_t read_len;\n\t\tloff_t pos = sd->pos;\n\n\t\tret = do_splice_to(in, &pos, pipe, len, flags);\n\t\tif (unlikely(ret <= 0))\n\t\t\tgoto out_release;\n\n\t\tread_len = ret;\n\t\tsd->total_len = read_len;\n\n\t\t/*\n\t\t * NOTE: nonblocking mode only applies to the input. We\n\t\t * must not do the output in nonblocking mode as then we\n\t\t * could get stuck data in the internal pipe:\n\t\t */\n\t\tret = actor(pipe, sd);\n\t\tif (unlikely(ret <= 0))\n\t\t\tgoto out_release;\n\n\t\tbytes += ret;\n\t\tlen -= ret;\n\t\tsd->pos = pos;\n\n\t\tif (ret < read_len)\n\t\t\tgoto out_release;\n\t}\n\ndone:\n\tpipe->nrbufs = pipe->curbuf = 0;\n\tfile_accessed(in);\n\treturn bytes;\n\nout_release:\n\t/*\n\t * If we did an incomplete transfer we must release\n\t * the pipe buffers in question:\n\t */\n\tfor (i = 0; i < PIPE_BUFFERS; i++) {\n\t\tstruct pipe_buffer *buf = pipe->bufs + i;\n\n\t\tif (buf->ops) {\n\t\t\tbuf->ops->release(pipe, buf);\n\t\t\tbuf->ops = NULL;\n\t\t}\n\t}\n\n\tif (!bytes)\n\t\tbytes = ret;\n\n\tgoto done;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-94'], 'message': 'splice: missing user pointer access verification\n\nvmsplice_to_user() must always check the user pointer and length\nwith access_ok() before copying. Likewise, for the slow path of\ncopy_from_user_mmap_sem() we need to check that we may read from\nthe user region.\n\nSigned-off-by: Jens Axboe \nCc: Wojciech Purczynski \nSigned-off-by: Greg Kroah-Hartman \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: ssize_t splice_from_pipe(struct pipe_inode_info *pipe, struct file *out,\n\t\t\t loff_t *ppos, size_t len, unsigned int flags,\n\t\t\t splice_actor *actor)\n{\n\tssize_t ret;\n\tstruct inode *inode = out->f_mapping->host;\n\tstruct splice_desc sd = {\n\t\t.total_len = len,\n\t\t.flags = flags,\n\t\t.pos = *ppos,\n\t\t.u.file = out,\n\t};\n\n\t/*\n\t * The actor worker might be calling ->prepare_write and\n\t * ->commit_write. Most of the time, these expect i_mutex to\n\t * be held. Since this may result in an ABBA deadlock with\n\t * pipe->inode, we have to order lock acquiry here.\n\t */\n\tinode_double_lock(inode, pipe->inode);\n\tret = __splice_from_pipe(pipe, &sd, actor);\n\tinode_double_unlock(inode, pipe->inode);\n\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-94'], 'message': 'splice: missing user pointer access verification\n\nvmsplice_to_user() must always check the user pointer and length\nwith access_ok() before copying. Likewise, for the slow path of\ncopy_from_user_mmap_sem() we need to check that we may read from\nthe user region.\n\nSigned-off-by: Jens Axboe \nCc: Wojciech Purczynski \nSigned-off-by: Greg Kroah-Hartman \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static long do_splice(struct file *in, loff_t __user *off_in,\n\t\t struct file *out, loff_t __user *off_out,\n\t\t size_t len, unsigned int flags)\n{\n\tstruct pipe_inode_info *pipe;\n\tloff_t offset, *off;\n\tlong ret;\n\n\tpipe = pipe_info(in->f_path.dentry->d_inode);\n\tif (pipe) {\n\t\tif (off_in)\n\t\t\treturn -ESPIPE;\n\t\tif (off_out) {\n\t\t\tif (out->f_op->llseek == no_llseek)\n\t\t\t\treturn -EINVAL;\n\t\t\tif (copy_from_user(&offset, off_out, sizeof(loff_t)))\n\t\t\t\treturn -EFAULT;\n\t\t\toff = &offset;\n\t\t} else\n\t\t\toff = &out->f_pos;\n\n\t\tret = do_splice_from(pipe, out, off, len, flags);\n\n\t\tif (off_out && copy_to_user(off_out, off, sizeof(loff_t)))\n\t\t\tret = -EFAULT;\n\n\t\treturn ret;\n\t}\n\n\tpipe = pipe_info(out->f_path.dentry->d_inode);\n\tif (pipe) {\n\t\tif (off_out)\n\t\t\treturn -ESPIPE;\n\t\tif (off_in) {\n\t\t\tif (in->f_op->llseek == no_llseek)\n\t\t\t\treturn -EINVAL;\n\t\t\tif (copy_from_user(&offset, off_in, sizeof(loff_t)))\n\t\t\t\treturn -EFAULT;\n\t\t\toff = &offset;\n\t\t} else\n\t\t\toff = &in->f_pos;\n\n\t\tret = do_splice_to(in, off, pipe, len, flags);\n\n\t\tif (off_in && copy_to_user(off_in, off, sizeof(loff_t)))\n\t\t\tret = -EFAULT;\n\n\t\treturn ret;\n\t}\n\n\treturn -EINVAL;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-94'], 'message': 'splice: missing user pointer access verification\n\nvmsplice_to_user() must always check the user pointer and length\nwith access_ok() before copying. Likewise, for the slow path of\ncopy_from_user_mmap_sem() we need to check that we may read from\nthe user region.\n\nSigned-off-by: Jens Axboe \nCc: Wojciech Purczynski \nSigned-off-by: Greg Kroah-Hartman \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static int pipe_to_file(struct pipe_inode_info *pipe, struct pipe_buffer *buf,\n\t\t\tstruct splice_desc *sd)\n{\n\tstruct file *file = sd->u.file;\n\tstruct address_space *mapping = file->f_mapping;\n\tunsigned int offset, this_len;\n\tstruct page *page;\n\tvoid *fsdata;\n\tint ret;\n\n\t/*\n\t * make sure the data in this buffer is uptodate\n\t */\n\tret = buf->ops->confirm(pipe, buf);\n\tif (unlikely(ret))\n\t\treturn ret;\n\n\toffset = sd->pos & ~PAGE_CACHE_MASK;\n\n\tthis_len = sd->len;\n\tif (this_len + offset > PAGE_CACHE_SIZE)\n\t\tthis_len = PAGE_CACHE_SIZE - offset;\n\n\tret = pagecache_write_begin(file, mapping, sd->pos, this_len,\n\t\t\t\tAOP_FLAG_UNINTERRUPTIBLE, &page, &fsdata);\n\tif (unlikely(ret))\n\t\tgoto out;\n\n\tif (buf->page != page) {\n\t\t/*\n\t\t * Careful, ->map() uses KM_USER0!\n\t\t */\n\t\tchar *src = buf->ops->map(pipe, buf, 1);\n\t\tchar *dst = kmap_atomic(page, KM_USER1);\n\n\t\tmemcpy(dst + offset, src + buf->offset, this_len);\n\t\tflush_dcache_page(page);\n\t\tkunmap_atomic(dst, KM_USER1);\n\t\tbuf->ops->unmap(pipe, buf, src);\n\t}\n\tret = pagecache_write_end(file, mapping, sd->pos, this_len, this_len,\n\t\t\t\tpage, fsdata);\nout:\n\treturn ret;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-94'], 'message': 'splice: missing user pointer access verification\n\nvmsplice_to_user() must always check the user pointer and length\nwith access_ok() before copying. Likewise, for the slow path of\ncopy_from_user_mmap_sem() we need to check that we may read from\nthe user region.\n\nSigned-off-by: Jens Axboe \nCc: Wojciech Purczynski \nSigned-off-by: Greg Kroah-Hartman \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: static void kernel_kexec(void)\n{\n#ifdef CONFIG_KEXEC\n\tstruct kimage *image;\n\timage = xchg(&kexec_image, NULL);\n\tif (!image)\n\t\treturn;\n\tkernel_restart_prepare(NULL);\n\tprintk(KERN_EMERG \"Starting new kernel\\n\");\n\tmachine_shutdown();\n\tmachine_kexec(image);\n#endif\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'CPU time limit patch / setrlimit(RLIMIT_CPU, 0) cheat fix\n\nAs discovered here today, the change in Kernel 2.6.17 intended to inhibit\nusers from setting RLIMIT_CPU to 0 (as that is equivalent to unlimited) by\n\"cheating\" and setting it to 1 in such a case, does not make a difference,\nas the check is done in the wrong place (too late), and only applies to the\nprofiling code.\n\nOn all systems I checked running kernels above 2.6.17, no matter what the\nhard and soft CPU time limits were before, a user could escape them by\nissuing in the shell (sh/bash/zsh) \"ulimit -t 0\", and then the user's\nprocess was not ever killed.\n\nAttached is a trivial patch to fix that. Simply moving the check to a\nslightly earlier location (specifically, before the line that actually\nassigns the limit - *old_rlim = new_rlim), does the trick.\n\nDo note that at least the zsh (but not ash, dash, or bash) shell has the\nproblem of \"caching\" the limits set by the ulimit command, so when running\nzsh the fix will not immediately be evident - after entering \"ulimit -t 0\",\n\"ulimit -a\" will show \"-t: cpu time (seconds) 0\", even though the actual\nlimit as returned by getrlimit(...) will be 1. It can be verified by\nopening a subshell (which will not have the values of the parent shell in\ncache) and checking in it, or just by running a CPU intensive command like\n\"echo '65536^1048576' | bc\" and verifying that it dumps core after one\nsecond.\n\nRegardless of whether that is a misfeature in the shell, perhaps it would\nbe better to return -EINVAL from setrlimit in such a case instead of\ncheating and setting to 1, as that does not really reflect the actual state\nof the process anymore. I do not however know what the ground for that\ndecision was in the original 2.6.17 change, and whether there would be any\n\"backward\" compatibility issues, so I preferred not to touch that right\nnow.\n\nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" }, { "text": "[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.\n Code: asmlinkage long sys_sethostname(char __user *name, int len)\n{\n\tint errno;\n\tchar tmp[__NEW_UTS_LEN];\n\n\tif (!capable(CAP_SYS_ADMIN))\n\t\treturn -EPERM;\n\tif (len < 0 || len > __NEW_UTS_LEN)\n\t\treturn -EINVAL;\n\tdown_write(&uts_sem);\n\terrno = -EFAULT;\n\tif (!copy_from_user(tmp, name, len)) {\n\t\tmemcpy(utsname()->nodename, tmp, len);\n\t\tutsname()->nodename[len] = 0;\n\t\terrno = 0;\n\t}\n\tup_write(&uts_sem);\n\treturn errno;\n} ; Sample JSON Format Confermily Expected output: \"examples\" => \"cwe\": \"xxx\"; \"message\": \"xxx\"\n [/INST] 'cwe': ['CWE-20'], 'message': 'CPU time limit patch / setrlimit(RLIMIT_CPU, 0) cheat fix\n\nAs discovered here today, the change in Kernel 2.6.17 intended to inhibit\nusers from setting RLIMIT_CPU to 0 (as that is equivalent to unlimited) by\n\"cheating\" and setting it to 1 in such a case, does not make a difference,\nas the check is done in the wrong place (too late), and only applies to the\nprofiling code.\n\nOn all systems I checked running kernels above 2.6.17, no matter what the\nhard and soft CPU time limits were before, a user could escape them by\nissuing in the shell (sh/bash/zsh) \"ulimit -t 0\", and then the user's\nprocess was not ever killed.\n\nAttached is a trivial patch to fix that. Simply moving the check to a\nslightly earlier location (specifically, before the line that actually\nassigns the limit - *old_rlim = new_rlim), does the trick.\n\nDo note that at least the zsh (but not ash, dash, or bash) shell has the\nproblem of \"caching\" the limits set by the ulimit command, so when running\nzsh the fix will not immediately be evident - after entering \"ulimit -t 0\",\n\"ulimit -a\" will show \"-t: cpu time (seconds) 0\", even though the actual\nlimit as returned by getrlimit(...) will be 1. It can be verified by\nopening a subshell (which will not have the values of the parent shell in\ncache) and checking in it, or just by running a CPU intensive command like\n\"echo '65536^1048576' | bc\" and verifying that it dumps core after one\nsecond.\n\nRegardless of whether that is a misfeature in the shell, perhaps it would\nbe better to return -EINVAL from setrlimit in such a case instead of\ncheating and setting to 1, as that does not really reflect the actual state\nof the process anymore. I do not however know what the ground for that\ndecision was in the original 2.6.17 change, and whether there would be any\n\"backward\" compatibility issues, so I preferred not to touch that right\nnow.\n\nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds '" } ]